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
143 throwRuntimeError(
"Exceeded stackLimit in readValue().");
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();
587 else if (!std::isinf(value))
589 "'" +
String(token.start_, token.end_) +
"' is not a number.", token);
595bool Reader::decodeString(Token& token) {
597 if (!decodeString(token, decoded_string))
599 Value decoded(decoded_string);
600 currentValue().swapPayload(decoded);
601 currentValue().setOffsetStart(token.start_ - begin_);
602 currentValue().setOffsetLimit(token.end_ - begin_);
606bool Reader::decodeString(Token& token,
String& decoded) {
607 decoded.reserve(
static_cast<size_t>(token.end_ - token.start_ - 2));
608 Location current = token.start_ + 1;
610 while (current != end) {
616 return addError(
"Empty escape sequence in string", token, current);
617 Char escape = *current++;
644 unsigned int unicode;
645 if (!decodeUnicodeCodePoint(token, current, end, unicode))
650 return addError(
"Bad escape sequence in string", token, current);
653 if (
static_cast<unsigned char>(c) < 0x20)
654 return addError(
"Control character in string", token, current - 1);
661bool Reader::decodeUnicodeCodePoint(Token& token, Location& current,
662 Location end,
unsigned int& unicode) {
664 if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
666 if (unicode >= 0xD800 && unicode <= 0xDBFF) {
668 if (end - current < 6)
670 "additional six characters expected to parse unicode surrogate pair.",
672 if (*(current++) ==
'\\' && *(current++) ==
'u') {
673 unsigned int surrogatePair;
674 if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
675 unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
679 return addError(
"expecting another \\u token to begin the second half of "
680 "a unicode surrogate pair",
686bool Reader::decodeUnicodeEscapeSequence(Token& token, Location& current,
688 unsigned int& ret_unicode) {
689 if (end - current < 4)
691 "Bad unicode escape sequence in string: four digits expected.", token,
694 for (
int index = 0; index < 4; ++index) {
697 if (c >=
'0' && c <=
'9')
699 else if (c >=
'a' && c <=
'f')
700 unicode += c -
'a' + 10;
701 else if (c >=
'A' && c <=
'F')
702 unicode += c -
'A' + 10;
705 "Bad unicode escape sequence in string: hexadecimal digit expected.",
708 ret_unicode =
static_cast<unsigned int>(unicode);
712bool Reader::addError(
const String& message, Token& token, Location extra) {
715 info.message_ = message;
717 errors_.push_back(info);
721bool Reader::recoverFromError(TokenType skipUntilToken) {
722 size_t const errorCount = errors_.size();
725 if (!readToken(skip))
726 errors_.resize(errorCount);
727 if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
730 errors_.resize(errorCount);
734bool Reader::addErrorAndRecover(
const String& message, Token& token,
735 TokenType skipUntilToken) {
736 addError(message, token);
737 return recoverFromError(skipUntilToken);
740Value& Reader::currentValue() {
return *(nodes_.top()); }
743 if (current_ == end_)
748void Reader::getLocationLineAndColumn(Location location,
int& line,
753 while (current < location && current != end_) {
756 if (current != end_ && *current ==
'\n')
758 lastLineStart = current;
760 }
else if (c ==
'\n') {
761 lastLineStart = current;
766 column = int(location - lastLineStart) + 1;
770String Reader::getLocationLineAndColumn(Location location)
const {
772 getLocationLineAndColumn(location, line, column);
773 char buffer[18 + 16 + 16 + 1];
774 jsoncpp_snprintf(buffer,
sizeof(buffer),
"Line %d, Column %d", line, column);
779String Reader::getFormatedErrorMessages()
const {
785 for (
const auto& error : errors_) {
787 "* " + getLocationLineAndColumn(error.token_.start_) +
"\n";
788 formattedMessage +=
" " + error.message_ +
"\n";
791 "See " + getLocationLineAndColumn(error.extra_) +
" for detail.\n";
793 return formattedMessage;
797 std::vector<Reader::StructuredError> allErrors;
798 for (
const auto& error : errors_) {
802 structured.
message = error.message_;
803 allErrors.push_back(structured);
809 ptrdiff_t
const length = end_ - begin_;
813 token.type_ = tokenError;
818 info.message_ = message;
819 info.extra_ =
nullptr;
820 errors_.push_back(info);
825 const Value& extra) {
826 ptrdiff_t
const length = end_ - begin_;
831 token.type_ = tokenError;
836 info.message_ = message;
838 errors_.push_back(info);
848 static OurFeatures all();
850 bool allowTrailingCommas_;
852 bool allowDroppedNullPlaceholders_;
853 bool allowNumericKeys_;
854 bool allowSingleQuotes_;
857 bool allowSpecialFloats_;
862OurFeatures OurFeatures::all() {
return {}; }
872 using Location =
const Char*;
874 explicit OurReader(OurFeatures
const& features);
875 bool parse(
const char* beginDoc,
const char* endDoc, Value& root,
876 bool collectComments =
true);
877 String getFormattedErrorMessages()
const;
878 std::vector<CharReader::StructuredError> getStructuredErrors()
const;
881 OurReader(OurReader
const&);
882 void operator=(OurReader
const&);
885 tokenEndOfStream = 0,
899 tokenMemberSeparator,
918 using Errors = std::deque<ErrorInfo>;
920 bool readToken(Token& token);
921 bool readTokenSkippingComments(Token& token);
923 void skipBom(
bool skipBom);
924 bool match(
const Char* pattern,
int patternLength);
926 bool readCStyleComment(
bool* containsNewLineResult);
927 bool readCppStyleComment();
929 bool readStringSingleQuote();
930 bool readNumber(
bool checkInf);
932 bool readObject(Token& token);
933 bool readArray(Token& token);
934 bool decodeNumber(Token& token);
935 bool decodeNumber(Token& token, Value& decoded);
936 bool decodeString(Token& token);
937 bool decodeString(Token& token,
String& decoded);
938 bool decodeDouble(Token& token);
939 bool decodeDouble(Token& token, Value& decoded);
940 bool decodeUnicodeCodePoint(Token& token, Location& current, Location end,
941 unsigned int& unicode);
942 bool decodeUnicodeEscapeSequence(Token& token, Location& current,
943 Location end,
unsigned int& unicode);
944 bool addError(
const String& message, Token& token, Location extra =
nullptr);
945 bool recoverFromError(TokenType skipUntilToken);
946 bool addErrorAndRecover(
const String& message, Token& token,
947 TokenType skipUntilToken);
948 void skipUntilSpace();
949 Value& currentValue();
951 void getLocationLineAndColumn(Location location,
int& line,
953 String getLocationLineAndColumn(Location location)
const;
956 static String normalizeEOL(Location begin, Location end);
957 static bool containsNewLine(Location begin, Location end);
959 using Nodes = std::stack<Value*>;
964 Location begin_ =
nullptr;
965 Location end_ =
nullptr;
966 Location current_ =
nullptr;
967 Location lastValueEnd_ =
nullptr;
968 Value* lastValue_ =
nullptr;
969 bool lastValueHasAComment_ =
false;
972 OurFeatures
const features_;
973 bool collectComments_ =
false;
978bool OurReader::containsNewLine(OurReader::Location begin,
979 OurReader::Location end) {
980 return std::any_of(begin, end, [](
char b) {
return b ==
'\n' || b ==
'\r'; });
983OurReader::OurReader(OurFeatures
const& features) : features_(features) {}
985bool OurReader::parse(
const char* beginDoc,
const char* endDoc,
Value& root,
986 bool collectComments) {
987 if (!features_.allowComments_) {
988 collectComments =
false;
993 collectComments_ = collectComments;
995 lastValueEnd_ =
nullptr;
996 lastValue_ =
nullptr;
997 commentsBefore_.clear();
999 while (!nodes_.empty())
1004 skipBom(features_.skipBom_);
1005 bool successful = readValue();
1008 readTokenSkippingComments(token);
1009 if (features_.failIfExtra_ && (token.type_ != tokenEndOfStream)) {
1010 addError(
"Extra non-whitespace after JSON value.", token);
1013 if (collectComments_ && !commentsBefore_.empty())
1015 if (features_.strictRoot_) {
1016 if (!root.isArray() && !root.isObject()) {
1019 token.type_ = tokenError;
1020 token.start_ = beginDoc;
1021 token.end_ = endDoc;
1023 "A valid JSON document must be either an array or an object value.",
1031bool OurReader::readValue() {
1033 if (nodes_.size() > features_.stackLimit_)
1034 throwRuntimeError(
"Exceeded stackLimit in readValue().");
1036 readTokenSkippingComments(token);
1037 bool successful =
true;
1039 if (collectComments_ && !commentsBefore_.empty()) {
1041 commentsBefore_.clear();
1044 switch (token.type_) {
1045 case tokenObjectBegin:
1046 successful = readObject(token);
1047 currentValue().setOffsetLimit(current_ - begin_);
1049 case tokenArrayBegin:
1050 successful = readArray(token);
1051 currentValue().setOffsetLimit(current_ - begin_);
1054 successful = decodeNumber(token);
1057 successful = decodeString(token);
1061 currentValue().swapPayload(v);
1062 currentValue().setOffsetStart(token.start_ - begin_);
1063 currentValue().setOffsetLimit(token.end_ - begin_);
1067 currentValue().swapPayload(v);
1068 currentValue().setOffsetStart(token.start_ - begin_);
1069 currentValue().setOffsetLimit(token.end_ - begin_);
1073 currentValue().swapPayload(v);
1074 currentValue().setOffsetStart(token.start_ - begin_);
1075 currentValue().setOffsetLimit(token.end_ - begin_);
1078 Value v(std::numeric_limits<double>::quiet_NaN());
1079 currentValue().swapPayload(v);
1080 currentValue().setOffsetStart(token.start_ - begin_);
1081 currentValue().setOffsetLimit(token.end_ - begin_);
1084 Value v(std::numeric_limits<double>::infinity());
1085 currentValue().swapPayload(v);
1086 currentValue().setOffsetStart(token.start_ - begin_);
1087 currentValue().setOffsetLimit(token.end_ - begin_);
1090 Value v(-std::numeric_limits<double>::infinity());
1091 currentValue().swapPayload(v);
1092 currentValue().setOffsetStart(token.start_ - begin_);
1093 currentValue().setOffsetLimit(token.end_ - begin_);
1095 case tokenArraySeparator:
1096 case tokenObjectEnd:
1098 if (features_.allowDroppedNullPlaceholders_) {
1103 currentValue().swapPayload(v);
1104 currentValue().setOffsetStart(current_ - begin_ - 1);
1105 currentValue().setOffsetLimit(current_ - begin_);
1109 currentValue().setOffsetStart(token.start_ - begin_);
1110 currentValue().setOffsetLimit(token.end_ - begin_);
1111 return addError(
"Syntax error: value, object or array expected.", token);
1114 if (collectComments_) {
1115 lastValueEnd_ = current_;
1116 lastValueHasAComment_ =
false;
1117 lastValue_ = ¤tValue();
1123bool OurReader::readTokenSkippingComments(Token& token) {
1124 bool success = readToken(token);
1125 if (features_.allowComments_) {
1126 while (success && token.type_ == tokenComment) {
1127 success = readToken(token);
1133bool OurReader::readToken(Token& token) {
1135 token.start_ = current_;
1136 Char c = getNextChar();
1140 token.type_ = tokenObjectBegin;
1143 token.type_ = tokenObjectEnd;
1146 token.type_ = tokenArrayBegin;
1149 token.type_ = tokenArrayEnd;
1152 token.type_ = tokenString;
1156 if (features_.allowSingleQuotes_) {
1157 token.type_ = tokenString;
1158 ok = readStringSingleQuote();
1165 token.type_ = tokenComment;
1178 token.type_ = tokenNumber;
1182 if (readNumber(
true)) {
1183 token.type_ = tokenNumber;
1185 token.type_ = tokenNegInf;
1186 ok = features_.allowSpecialFloats_ && match(
"nfinity", 7);
1190 if (readNumber(
true)) {
1191 token.type_ = tokenNumber;
1193 token.type_ = tokenPosInf;
1194 ok = features_.allowSpecialFloats_ && match(
"nfinity", 7);
1198 token.type_ = tokenTrue;
1199 ok = match(
"rue", 3);
1202 token.type_ = tokenFalse;
1203 ok = match(
"alse", 4);
1206 token.type_ = tokenNull;
1207 ok = match(
"ull", 3);
1210 if (features_.allowSpecialFloats_) {
1211 token.type_ = tokenNaN;
1212 ok = match(
"aN", 2);
1218 if (features_.allowSpecialFloats_) {
1219 token.type_ = tokenPosInf;
1220 ok = match(
"nfinity", 7);
1226 token.type_ = tokenArraySeparator;
1229 token.type_ = tokenMemberSeparator;
1232 token.type_ = tokenEndOfStream;
1239 token.type_ = tokenError;
1240 token.end_ = current_;
1244void OurReader::skipSpaces() {
1245 while (current_ != end_) {
1247 if (c ==
' ' || c ==
'\t' || c ==
'\r' || c ==
'\n')
1254void OurReader::skipBom(
bool skipBom) {
1257 if ((end_ - begin_) >= 3 && strncmp(begin_,
"\xEF\xBB\xBF", 3) == 0) {
1264bool OurReader::match(
const Char* pattern,
int patternLength) {
1265 if (end_ - current_ < patternLength)
1267 int index = patternLength;
1269 if (current_[index] != pattern[index])
1271 current_ += patternLength;
1275bool OurReader::readComment() {
1276 const Location commentBegin = current_ - 1;
1277 const Char c = getNextChar();
1278 bool successful =
false;
1279 bool cStyleWithEmbeddedNewline =
false;
1281 const bool isCStyleComment = (c ==
'*');
1282 const bool isCppStyleComment = (c ==
'/');
1283 if (isCStyleComment) {
1284 successful = readCStyleComment(&cStyleWithEmbeddedNewline);
1285 }
else if (isCppStyleComment) {
1286 successful = readCppStyleComment();
1292 if (collectComments_) {
1295 if (!lastValueHasAComment_) {
1296 if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
1297 if (isCppStyleComment || !cStyleWithEmbeddedNewline) {
1299 lastValueHasAComment_ =
true;
1304 addComment(commentBegin, current_, placement);
1309String OurReader::normalizeEOL(OurReader::Location begin,
1310 OurReader::Location end) {
1312 normalized.reserve(
static_cast<size_t>(end - begin));
1313 OurReader::Location current = begin;
1314 while (current != end) {
1315 char c = *current++;
1317 if (current != end && *current ==
'\n')
1329void OurReader::addComment(Location begin, Location end,
1331 assert(collectComments_);
1332 const String& normalized = normalizeEOL(begin, end);
1334 assert(lastValue_ !=
nullptr);
1335 lastValue_->setComment(normalized, placement);
1337 commentsBefore_ += normalized;
1341bool OurReader::readCStyleComment(
bool* containsNewLineResult) {
1342 *containsNewLineResult =
false;
1344 while ((current_ + 1) < end_) {
1345 Char c = getNextChar();
1346 if (c ==
'*' && *current_ ==
'/')
1349 *containsNewLineResult =
true;
1352 return getNextChar() ==
'/';
1355bool OurReader::readCppStyleComment() {
1356 while (current_ != end_) {
1357 Char c = getNextChar();
1362 if (current_ != end_ && *current_ ==
'\n')
1371bool OurReader::readNumber(
bool checkInf) {
1372 Location p = current_;
1373 if (checkInf && p != end_ && *p ==
'I') {
1379 while (c >=
'0' && c <=
'9')
1380 c = (current_ = p) < end_ ? *p++ :
'\0';
1383 c = (current_ = p) < end_ ? *p++ :
'\0';
1384 while (c >=
'0' && c <=
'9')
1385 c = (current_ = p) < end_ ? *p++ :
'\0';
1388 if (c ==
'e' || c ==
'E') {
1389 c = (current_ = p) < end_ ? *p++ :
'\0';
1390 if (c ==
'+' || c ==
'-')
1391 c = (current_ = p) < end_ ? *p++ :
'\0';
1392 while (c >=
'0' && c <=
'9')
1393 c = (current_ = p) < end_ ? *p++ :
'\0';
1397bool OurReader::readString() {
1399 while (current_ != end_) {
1409bool OurReader::readStringSingleQuote() {
1411 while (current_ != end_) {
1421bool OurReader::readObject(Token& token) {
1425 currentValue().swapPayload(init);
1426 currentValue().setOffsetStart(token.start_ - begin_);
1427 while (readTokenSkippingComments(tokenName)) {
1428 if (tokenName.type_ == tokenObjectEnd &&
1430 features_.allowTrailingCommas_))
1433 if (tokenName.type_ == tokenString) {
1434 if (!decodeString(tokenName, name))
1435 return recoverFromError(tokenObjectEnd);
1436 }
else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
1438 if (!decodeNumber(tokenName, numberName))
1439 return recoverFromError(tokenObjectEnd);
1440 name = numberName.asString();
1444 if (name.length() >= (1U << 30))
1445 throwRuntimeError(
"keylength >= 2^30");
1446 if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
1447 String msg =
"Duplicate key: '" + name +
"'";
1448 return addErrorAndRecover(msg, tokenName, tokenObjectEnd);
1452 if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
1453 return addErrorAndRecover(
"Missing ':' after object member name", colon,
1456 Value& value = currentValue()[name];
1457 nodes_.push(&value);
1458 bool ok = readValue();
1461 return recoverFromError(tokenObjectEnd);
1464 if (!readTokenSkippingComments(comma) ||
1465 (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator)) {
1466 return addErrorAndRecover(
"Missing ',' or '}' in object declaration",
1467 comma, tokenObjectEnd);
1469 if (comma.type_ == tokenObjectEnd)
1472 return addErrorAndRecover(
"Missing '}' or object member name", tokenName,
1476bool OurReader::readArray(Token& token) {
1478 currentValue().swapPayload(init);
1479 currentValue().setOffsetStart(token.start_ - begin_);
1483 if (current_ != end_ && *current_ ==
']' &&
1485 (features_.allowTrailingCommas_ &&
1486 !features_.allowDroppedNullPlaceholders_)))
1490 readToken(endArray);
1493 Value& value = currentValue()[index++];
1494 nodes_.push(&value);
1495 bool ok = readValue();
1498 return recoverFromError(tokenArrayEnd);
1502 ok = readTokenSkippingComments(currentToken);
1503 bool badTokenType = (currentToken.type_ != tokenArraySeparator &&
1504 currentToken.type_ != tokenArrayEnd);
1505 if (!ok || badTokenType) {
1506 return addErrorAndRecover(
"Missing ',' or ']' in array declaration",
1507 currentToken, tokenArrayEnd);
1509 if (currentToken.type_ == tokenArrayEnd)
1515bool OurReader::decodeNumber(Token& token) {
1517 if (!decodeNumber(token, decoded))
1519 currentValue().swapPayload(decoded);
1520 currentValue().setOffsetStart(token.start_ - begin_);
1521 currentValue().setOffsetLimit(token.end_ - begin_);
1525bool OurReader::decodeNumber(Token& token,
Value& decoded) {
1529 Location current = token.start_;
1530 const bool isNegative = *current ==
'-';
1539 "Int must be smaller than UInt");
1546 "The absolute value of minLargestInt must be greater than or "
1547 "equal to maxLargestInt");
1549 "The absolute value of minLargestInt must be only 1 magnitude "
1550 "larger than maxLargest Int");
1561 static constexpr auto negative_threshold =
1563 static constexpr auto negative_last_digit =
1567 isNegative ? negative_threshold : positive_threshold;
1569 isNegative ? negative_last_digit : positive_last_digit;
1572 while (current < token.end_) {
1573 Char c = *current++;
1574 if (c <
'0' || c >
'9')
1575 return decodeDouble(token, decoded);
1577 const auto digit(
static_cast<Value::UInt>(c -
'0'));
1578 if (value >= threshold) {
1584 if (value > threshold || current != token.end_ ||
1585 digit > max_last_digit) {
1586 return decodeDouble(token, decoded);
1589 value = value * 10 + digit;
1594 const auto last_digit =
static_cast<Value::UInt>(value % 10);
1605bool OurReader::decodeDouble(Token& token) {
1607 if (!decodeDouble(token, decoded))
1609 currentValue().swapPayload(decoded);
1610 currentValue().setOffsetStart(token.start_ - begin_);
1611 currentValue().setOffsetLimit(token.end_ - begin_);
1615bool OurReader::decodeDouble(Token& token,
Value& decoded) {
1618 is.imbue(std::locale::classic());
1619 if (!(is >> value)) {
1620 if (value == std::numeric_limits<double>::max())
1621 value = std::numeric_limits<double>::infinity();
1622 else if (value == std::numeric_limits<double>::lowest())
1623 value = -std::numeric_limits<double>::infinity();
1624 else if (!std::isinf(value))
1626 "'" +
String(token.start_, token.end_) +
"' is not a number.", token);
1632bool OurReader::decodeString(Token& token) {
1634 if (!decodeString(token, decoded_string))
1636 Value decoded(decoded_string);
1637 currentValue().swapPayload(decoded);
1638 currentValue().setOffsetStart(token.start_ - begin_);
1639 currentValue().setOffsetLimit(token.end_ - begin_);
1643bool OurReader::decodeString(Token& token,
String& decoded) {
1644 decoded.reserve(
static_cast<size_t>(token.end_ - token.start_ - 2));
1645 Location current = token.start_ + 1;
1646 Location end = token.end_ - 1;
1647 while (current != end) {
1648 Char c = *current++;
1653 return addError(
"Empty escape sequence in string", token, current);
1654 Char escape = *current++;
1681 unsigned int unicode;
1682 if (!decodeUnicodeCodePoint(token, current, end, unicode))
1687 return addError(
"Bad escape sequence in string", token, current);
1690 if (
static_cast<unsigned char>(c) < 0x20)
1691 return addError(
"Control character in string", token, current - 1);
1698bool OurReader::decodeUnicodeCodePoint(Token& token, Location& current,
1699 Location end,
unsigned int& unicode) {
1701 if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
1703 if (unicode >= 0xD800 && unicode <= 0xDBFF) {
1705 if (end - current < 6)
1707 "additional six characters expected to parse unicode surrogate pair.",
1709 if (*(current++) ==
'\\' && *(current++) ==
'u') {
1710 unsigned int surrogatePair;
1711 if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
1712 unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
1716 return addError(
"expecting another \\u token to begin the second half of "
1717 "a unicode surrogate pair",
1723bool OurReader::decodeUnicodeEscapeSequence(Token& token, Location& current,
1725 unsigned int& ret_unicode) {
1726 if (end - current < 4)
1728 "Bad unicode escape sequence in string: four digits expected.", token,
1731 for (
int index = 0; index < 4; ++index) {
1732 Char c = *current++;
1734 if (c >=
'0' && c <=
'9')
1736 else if (c >=
'a' && c <=
'f')
1737 unicode += c -
'a' + 10;
1738 else if (c >=
'A' && c <=
'F')
1739 unicode += c -
'A' + 10;
1742 "Bad unicode escape sequence in string: hexadecimal digit expected.",
1745 ret_unicode =
static_cast<unsigned int>(unicode);
1749bool OurReader::addError(
const String& message, Token& token, Location extra) {
1751 info.token_ = token;
1752 info.message_ = message;
1753 info.extra_ = extra;
1754 errors_.push_back(info);
1758bool OurReader::recoverFromError(TokenType skipUntilToken) {
1759 size_t errorCount = errors_.size();
1762 if (!readToken(skip))
1763 errors_.resize(errorCount);
1764 if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
1767 errors_.resize(errorCount);
1771bool OurReader::addErrorAndRecover(
const String& message, Token& token,
1772 TokenType skipUntilToken) {
1773 addError(message, token);
1774 return recoverFromError(skipUntilToken);
1777Value& OurReader::currentValue() {
return *(nodes_.top()); }
1779OurReader::Char OurReader::getNextChar() {
1780 if (current_ == end_)
1785void OurReader::getLocationLineAndColumn(Location location,
int& line,
1786 int& column)
const {
1787 Location current = begin_;
1788 Location lastLineStart = current;
1790 while (current < location && current != end_) {
1791 Char c = *current++;
1793 if (current != end_ && *current ==
'\n')
1795 lastLineStart = current;
1797 }
else if (c ==
'\n') {
1798 lastLineStart = current;
1803 column = int(location - lastLineStart) + 1;
1807String OurReader::getLocationLineAndColumn(Location location)
const {
1809 getLocationLineAndColumn(location, line, column);
1810 char buffer[18 + 16 + 16 + 1];
1811 jsoncpp_snprintf(buffer,
sizeof(buffer),
"Line %d, Column %d", line, column);
1815String OurReader::getFormattedErrorMessages()
const {
1817 for (
const auto& error : errors_) {
1819 "* " + getLocationLineAndColumn(error.token_.start_) +
"\n";
1820 formattedMessage +=
" " + error.message_ +
"\n";
1823 "See " + getLocationLineAndColumn(error.extra_) +
" for detail.\n";
1825 return formattedMessage;
1828std::vector<CharReader::StructuredError>
1829OurReader::getStructuredErrors()
const {
1830 std::vector<CharReader::StructuredError> allErrors;
1831 for (
const auto& error : errors_) {
1832 CharReader::StructuredError structured;
1833 structured.offset_start = error.token_.start_ - begin_;
1834 structured.offset_limit = error.token_.end_ - begin_;
1835 structured.message = error.message_;
1836 allErrors.push_back(structured);
1844 OurCharReader(
bool collectComments, OurFeatures
const& features)
1846 std::unique_ptr<OurImpl>(new OurImpl(collectComments, features))) {}
1849 class OurImpl :
public Impl {
1851 OurImpl(
bool collectComments, OurFeatures
const& features)
1852 : collectComments_(collectComments), reader_(features) {}
1854 bool parse(
char const* beginDoc,
char const* endDoc, Value* root,
1856 bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
1858 *errs = reader_.getFormattedErrorMessages();
1863 std::vector<CharReader::StructuredError>
1865 return reader_.getStructuredErrors();
1869 bool const collectComments_;
1874CharReaderBuilder::CharReaderBuilder() {
setDefaults(&settings_); }
1875CharReaderBuilder::~CharReaderBuilder() =
default;
1877 bool collectComments = settings_[
"collectComments"].asBool();
1878 OurFeatures features = OurFeatures::all();
1879 features.allowComments_ = settings_[
"allowComments"].asBool();
1880 features.allowTrailingCommas_ = settings_[
"allowTrailingCommas"].asBool();
1881 features.strictRoot_ = settings_[
"strictRoot"].asBool();
1882 features.allowDroppedNullPlaceholders_ =
1883 settings_[
"allowDroppedNullPlaceholders"].asBool();
1884 features.allowNumericKeys_ = settings_[
"allowNumericKeys"].asBool();
1885 features.allowSingleQuotes_ = settings_[
"allowSingleQuotes"].asBool();
1889 features.stackLimit_ =
static_cast<size_t>(settings_[
"stackLimit"].asUInt());
1890 features.failIfExtra_ = settings_[
"failIfExtra"].asBool();
1891 features.rejectDupKeys_ = settings_[
"rejectDupKeys"].asBool();
1892 features.allowSpecialFloats_ = settings_[
"allowSpecialFloats"].asBool();
1893 features.skipBom_ = settings_[
"skipBom"].asBool();
1894 return new OurCharReader(collectComments, features);
1898 static const auto& valid_keys = *
new std::set<String>{
1901 "allowTrailingCommas",
1903 "allowDroppedNullPlaceholders",
1905 "allowSingleQuotes",
1909 "allowSpecialFloats",
1912 for (
auto si = settings_.begin(); si != settings_.end(); ++si) {
1913 auto key = si.name();
1914 if (valid_keys.count(key))
1917 (*invalid)[key] = *si;
1921 return invalid ? invalid->
empty() :
true;
1925 return settings_[key];
1930 (*settings)[
"allowComments"] =
false;
1931 (*settings)[
"allowTrailingCommas"] =
false;
1932 (*settings)[
"strictRoot"] =
true;
1933 (*settings)[
"allowDroppedNullPlaceholders"] =
false;
1934 (*settings)[
"allowNumericKeys"] =
false;
1935 (*settings)[
"allowSingleQuotes"] =
false;
1936 (*settings)[
"stackLimit"] = 256;
1937 (*settings)[
"failIfExtra"] =
true;
1938 (*settings)[
"rejectDupKeys"] =
true;
1939 (*settings)[
"allowSpecialFloats"] =
false;
1940 (*settings)[
"skipBom"] =
true;
1946 (*settings)[
"collectComments"] =
true;
1947 (*settings)[
"allowComments"] =
true;
1948 (*settings)[
"allowTrailingCommas"] =
true;
1949 (*settings)[
"strictRoot"] =
false;
1950 (*settings)[
"allowDroppedNullPlaceholders"] =
false;
1951 (*settings)[
"allowNumericKeys"] =
false;
1952 (*settings)[
"allowSingleQuotes"] =
false;
1953 (*settings)[
"stackLimit"] = 256;
1954 (*settings)[
"failIfExtra"] =
false;
1955 (*settings)[
"rejectDupKeys"] =
false;
1956 (*settings)[
"allowSpecialFloats"] =
false;
1957 (*settings)[
"skipBom"] =
true;
1963 (*settings)[
"allowComments"] =
false;
1964 (*settings)[
"allowTrailingCommas"] =
false;
1965 (*settings)[
"strictRoot"] =
false;
1966 (*settings)[
"allowDroppedNullPlaceholders"] =
false;
1967 (*settings)[
"allowNumericKeys"] =
false;
1968 (*settings)[
"allowSingleQuotes"] =
false;
1969 (*settings)[
"stackLimit"] = 256;
1970 (*settings)[
"failIfExtra"] =
true;
1971 (*settings)[
"rejectDupKeys"] =
false;
1972 (*settings)[
"allowSpecialFloats"] =
false;
1973 (*settings)[
"skipBom"] =
false;
1977std::vector<CharReader::StructuredError>
1979 return _impl->getStructuredErrors();
1984 return _impl->parse(beginDoc, endDoc, root, errs);
1993 ssin << sin.rdbuf();
1994 String doc = std::move(ssin).str();
1995 char const* begin = doc.data();
1996 char const* end = begin + doc.size();
1999 return reader->
parse(begin, end, root, errs);
2007 throwRuntimeError(errs);
virtual CharReader * newCharReader() const =0
Allocate a CharReader via operator new().
virtual std::vector< StructuredError > getStructuredErrors() const =0
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.
static void strictMode(Json::Value *settings)
Same as old Features::strictMode().
bool validate(Json::Value *invalid) const
Configuration of this builder.
Interface for reading JSON from a char array.
CharReader(std::unique_ptr< Impl > impl)
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.
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, size_t len, CommentPlacement placement)
Comments must be //... or /* ... */.
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_DEPRECATED_STACK_LIMIT
static size_t const stackLimit_g
JSON (JavaScript Object Notation).
std::basic_ostringstream< String::value_type, String::traits_type, String::allocator_type > OStringStream
@ 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).
static String codePointToUTF8(unsigned int cp)
Converts a unicode code-point to UTF-8.
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.
An error tagged with where in the JSON text it was encountered.