2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/json.h>
19 #include <boost/next_prior.hpp>
20 #include <boost/algorithm/string.hpp>
22 #include <folly/Conv.h>
23 #include <folly/Portability.h>
24 #include <folly/Range.h>
25 #include <folly/String.h>
26 #include <folly/Unicode.h>
27 #include <folly/portability/Constexpr.h>
31 //////////////////////////////////////////////////////////////////////
37 const unsigned char*& p,
38 const unsigned char* const e,
40 /* The following encodings are valid, except for the 5 and 6 byte
44 * 1110xxxx 10xxxxxx 10xxxxxx
45 * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
46 * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
47 * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
50 auto skip = [&] { ++p; return U'\ufffd'; };
53 if (skipOnError) return skip();
54 throw std::runtime_error("folly::decodeUtf8 empty/invalid string");
57 unsigned char fst = *p;
63 static const uint32_t bitMask[] = {
70 // upper control bits are masked out later
73 if ((fst & 0xC0) != 0xC0) {
74 if (skipOnError) return skip();
75 throw std::runtime_error(to<std::string>("folly::decodeUtf8 i=0 d=", d));
80 for (unsigned int i = 1; i != 3 && p + i < e; ++i) {
81 unsigned char tmp = p[i];
83 if ((tmp & 0xC0) != 0x80) {
84 if (skipOnError) return skip();
85 throw std::runtime_error(
86 to<std::string>("folly::decodeUtf8 i=", i, " tmp=", (uint32_t)tmp));
89 d = (d << 6) | (tmp & 0x3F);
95 // overlong, could have been encoded with i bytes
96 if ((d & ~bitMask[i - 1]) == 0) {
97 if (skipOnError) return skip();
98 throw std::runtime_error(
99 to<std::string>("folly::decodeUtf8 i=", i, " d=", d));
102 // check for surrogates only needed for 3 bytes
104 if ((d >= 0xD800 && d <= 0xDFFF) || d > 0x10FFFF) {
105 if (skipOnError) return skip();
106 throw std::runtime_error(
107 to<std::string>("folly::decodeUtf8 i=", i, " d=", d));
116 if (skipOnError) return skip();
117 throw std::runtime_error("folly::decodeUtf8 encoding length maxed out");
123 unsigned* indentLevel,
124 serialization_opts const* opts)
125 : out_(out), indentLevel_(indentLevel), opts_(*opts) {}
127 void operator()(dynamic const& v) const {
129 case dynamic::DOUBLE:
130 if (!opts_.allow_nan_inf &&
131 (std::isnan(v.asDouble()) || std::isinf(v.asDouble()))) {
132 throw std::runtime_error("folly::toJson: JSON object value was a "
135 toAppend(v.asDouble(), &out_, opts_.double_mode, opts_.double_num_digits);
137 case dynamic::INT64: {
138 auto intval = v.asInt();
139 if (opts_.javascript_safe) {
140 // Use folly::to to check that this integer can be represented
141 // as a double without loss of precision.
142 intval = int64_t(to<double>(intval));
144 toAppend(intval, &out_);
148 out_ += v.asBool() ? "true" : "false";
153 case dynamic::STRING:
154 escapeString(v.asString(), out_, opts_);
156 case dynamic::OBJECT:
163 CHECK(0) << "Bad type " << v.type();
168 void printKV(const std::pair<const dynamic, dynamic>& p) const {
169 if (!opts_.allow_non_string_keys && !p.first.isString()) {
170 throw std::runtime_error("folly::toJson: JSON object key was not a "
178 template <typename Iterator>
179 void printKVPairs(Iterator begin, Iterator end) const {
181 for (++begin; begin != end; ++begin) {
188 void printObject(dynamic const& o) const {
197 if (opts_.sort_keys) {
198 std::vector<std::pair<dynamic, dynamic>> items(
199 o.items().begin(), o.items().end());
200 std::sort(items.begin(), items.end());
201 printKVPairs(items.begin(), items.end());
203 printKVPairs(o.items().begin(), o.items().end());
210 void printArray(dynamic const& a) const {
220 for (auto& val : range(boost::next(a.begin()), a.end())) {
231 void outdent() const {
237 void indent() const {
243 void newline() const {
245 out_ += to<std::string>('\n', std::string(*indentLevel_ * 2, ' '));
249 void mapColon() const {
250 out_ += indentLevel_ ? " : " : ":";
255 unsigned* const indentLevel_;
256 serialization_opts const& opts_;
259 //////////////////////////////////////////////////////////////////////
261 struct ParseError : std::runtime_error {
262 explicit ParseError(int line)
263 : std::runtime_error(to<std::string>("json parse error on line ", line))
266 explicit ParseError(int line, std::string const& context,
267 std::string const& expected)
268 : std::runtime_error(to<std::string>("json parse error on line ", line,
269 !context.empty() ? to<std::string>(" near `", context, '\'')
274 explicit ParseError(std::string const& msg)
275 : std::runtime_error("json parse error: " + msg)
279 // Wraps our input buffer with some helper functions.
281 explicit Input(StringPiece range, json::serialization_opts const* opts)
289 Input(Input const&) = delete;
290 Input& operator=(Input const&) = delete;
292 char const* begin() const { return range_.begin(); }
294 // Parse ahead for as long as the supplied predicate is satisfied,
295 // returning a range of what was skipped.
296 template<class Predicate>
297 StringPiece skipWhile(const Predicate& p) {
298 std::size_t skipped = 0;
299 for (; skipped < range_.size(); ++skipped) {
300 if (!p(range_[skipped])) {
303 if (range_[skipped] == '\n') {
307 auto ret = range_.subpiece(0, skipped);
308 range_.advance(skipped);
313 StringPiece skipDigits() {
314 return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
317 StringPiece skipMinusAndDigits() {
318 bool firstChar = true;
319 return skipWhile([&firstChar] (char c) {
320 bool result = (c >= '0' && c <= '9') || (firstChar && c == '-');
326 void skipWhitespace() {
327 range_ = folly::skipWhitespace(range_);
331 void expect(char c) {
333 throw ParseError(lineNum_, context(),
334 to<std::string>("expected '", c, '\''));
339 std::size_t size() const {
340 return range_.size();
343 int operator*() const {
355 return to<T>(&range_);
356 } catch (std::exception const& e) {
361 bool consume(StringPiece str) {
362 if (boost::starts_with(range_, str)) {
363 range_.advance(str.size());
370 std::string context() const {
371 return range_.subpiece(0, 16 /* arbitrary */).toString();
374 dynamic error(char const* what) const {
375 throw ParseError(lineNum_, context(), what);
378 json::serialization_opts const& getOpts() {
383 void storeCurrent() {
384 current_ = range_.empty() ? EOF : range_.front();
389 json::serialization_opts const& opts_;
394 dynamic parseValue(Input& in);
395 std::string parseString(Input& in);
396 dynamic parseNumber(Input& in);
398 dynamic parseObject(Input& in) {
402 dynamic ret = dynamic::object;
411 if (in.getOpts().allow_trailing_comma && *in == '}') {
414 if (*in == '\"') { // string
415 auto key = parseString(in);
419 ret.insert(std::move(key), parseValue(in));
420 } else if (!in.getOpts().allow_non_string_keys) {
421 in.error("expected string for object key name");
423 auto key = parseValue(in);
427 ret.insert(std::move(key), parseValue(in));
442 dynamic parseArray(Input& in) {
446 dynamic ret = dynamic::array;
455 if (in.getOpts().allow_trailing_comma && *in == ']') {
458 ret.push_back(parseValue(in));
471 dynamic parseNumber(Input& in) {
472 bool const negative = (*in == '-');
473 if (negative && in.consume("-Infinity")) {
474 if (in.getOpts().parse_numbers_as_strings) {
477 return -std::numeric_limits<double>::infinity();
481 auto integral = in.skipMinusAndDigits();
482 if (negative && integral.size() < 2) {
483 in.error("expected digits after `-'");
486 auto const wasE = *in == 'e' || *in == 'E';
488 constexpr const char* maxInt = "9223372036854775807";
489 constexpr const char* minInt = "9223372036854775808";
490 constexpr auto maxIntLen = constexpr_strlen(maxInt);
493 if (*in != '.' && !wasE && in.getOpts().parse_numbers_as_strings) {
497 if (*in != '.' && !wasE) {
498 if (LIKELY(!in.getOpts().double_fallback || integral.size() < maxIntLen) ||
499 (integral.size() == maxIntLen &&
500 (integral <= maxInt || (integral == minInt && negative)))) {
501 auto val = to<int64_t>(integral);
505 auto val = to<double>(integral);
511 auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
512 if (*in == 'e' || *in == 'E') {
514 if (*in == '+' || *in == '-') {
517 auto expPart = in.skipDigits();
520 auto fullNum = range(integral.begin(), end);
521 if (in.getOpts().parse_numbers_as_strings) {
524 auto val = to<double>(fullNum);
528 std::string decodeUnicodeEscape(Input& in) {
529 auto hexVal = [&] (char c) -> unsigned {
530 return c >= '0' && c <= '9' ? c - '0' :
531 c >= 'a' && c <= 'f' ? c - 'a' + 10 :
532 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
533 (in.error("invalid hex digit"), 0);
536 auto readHex = [&]() -> uint16_t {
538 in.error("expected 4 hex digits");
541 uint16_t ret = hexVal(*in) * 4096;
543 ret += hexVal(*in) * 256;
545 ret += hexVal(*in) * 16;
553 * If the value encoded is in the surrogate pair range, we need to
554 * make sure there is another escape that we can use also.
556 uint32_t codePoint = readHex();
557 if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
558 if (!in.consume("\\u")) {
559 in.error("expected another unicode escape for second half of "
562 uint16_t second = readHex();
563 if (second >= 0xdc00 && second <= 0xdfff) {
564 codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
567 in.error("second character in surrogate pair is invalid");
569 } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
570 in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
573 return codePointToUtf8(codePoint);
576 std::string parseString(Input& in) {
582 auto range = in.skipWhile(
583 [] (char c) { return c != '\"' && c != '\\'; }
585 ret.append(range.begin(), range.end());
594 case '\"': ret.push_back('\"'); ++in; break;
595 case '\\': ret.push_back('\\'); ++in; break;
596 case '/': ret.push_back('/'); ++in; break;
597 case 'b': ret.push_back('\b'); ++in; break;
598 case 'f': ret.push_back('\f'); ++in; break;
599 case 'n': ret.push_back('\n'); ++in; break;
600 case 'r': ret.push_back('\r'); ++in; break;
601 case 't': ret.push_back('\t'); ++in; break;
602 case 'u': ++in; ret += decodeUnicodeEscape(in); break;
604 in.error(to<std::string>("unknown escape ", *in, " in string").c_str());
609 in.error("unterminated string");
613 * Apparently we're actually supposed to ban all control
614 * characters from strings. This seems unnecessarily
615 * restrictive, so we're only banning zero bytes. (Since the
616 * string is presumed to be UTF-8 encoded it's fine to just
619 in.error("null byte in string");
629 dynamic parseValue(Input& in) {
631 return *in == '[' ? parseArray(in) :
632 *in == '{' ? parseObject(in) :
633 *in == '\"' ? parseString(in) :
634 (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
635 in.consume("true") ? true :
636 in.consume("false") ? false :
637 in.consume("null") ? nullptr :
638 in.consume("Infinity") ?
639 (in.getOpts().parse_numbers_as_strings ? (dynamic)"Infinity" :
640 (dynamic)std::numeric_limits<double>::infinity()) :
642 (in.getOpts().parse_numbers_as_strings ? (dynamic)"NaN" :
643 (dynamic)std::numeric_limits<double>::quiet_NaN()) :
644 in.error("expected json value");
649 //////////////////////////////////////////////////////////////////////
651 std::string serialize(dynamic const& dyn, serialization_opts const& opts) {
653 unsigned indentLevel = 0;
654 Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
659 // Escape a string so that it is legal to print it in JSON text.
663 const serialization_opts& opts) {
664 auto hexDigit = [] (int c) -> char {
665 return c < 10 ? c + '0' : c - 10 + 'a';
668 out.reserve(out.size() + input.size() + 2);
671 auto* p = reinterpret_cast<const unsigned char*>(input.begin());
672 auto* q = reinterpret_cast<const unsigned char*>(input.begin());
673 auto* e = reinterpret_cast<const unsigned char*>(input.end());
676 // Since non-ascii encoding inherently does utf8 validation
677 // we explicitly validate utf8 only if non-ascii encoding is disabled.
678 if ((opts.validate_utf8 || opts.skip_invalid_utf8)
679 && !opts.encode_non_ascii) {
680 // to achieve better spatial and temporal coherence
681 // we do utf8 validation progressively along with the
682 // string-escaping instead of two separate passes
684 // as the encoding progresses, q will stay at or ahead of p
687 // as p catches up with q, move q forward
689 // calling utf8_decode has the side effect of
690 // checking that utf8 encodings are valid
691 char32_t v = decodeUtf8(q, e, opts.skip_invalid_utf8);
692 if (opts.skip_invalid_utf8 && v == U'\ufffd') {
693 out.append(u8"\ufffd");
699 if (opts.encode_non_ascii && (*p & 0x80)) {
700 // note that this if condition captures utf8 chars
701 // with value > 127, so size > 1 byte
702 char32_t v = decodeUtf8(p, e, opts.skip_invalid_utf8);
704 out.push_back(hexDigit(v >> 12));
705 out.push_back(hexDigit((v >> 8) & 0x0f));
706 out.push_back(hexDigit((v >> 4) & 0x0f));
707 out.push_back(hexDigit(v & 0x0f));
708 } else if (*p == '\\' || *p == '\"') {
711 } else if (*p <= 0x1f) {
713 case '\b': out.append("\\b"); p++; break;
714 case '\f': out.append("\\f"); p++; break;
715 case '\n': out.append("\\n"); p++; break;
716 case '\r': out.append("\\r"); p++; break;
717 case '\t': out.append("\\t"); p++; break;
719 // note that this if condition captures non readable chars
720 // with value < 32, so size = 1 byte (e.g control chars).
722 out.push_back(hexDigit((*p & 0xf0) >> 4));
723 out.push_back(hexDigit(*p & 0xf));
734 std::string stripComments(StringPiece jsonC) {
741 } state = State::None;
743 for (size_t i = 0; i < jsonC.size(); ++i) {
744 auto s = jsonC.subpiece(i);
747 if (s.startsWith("/*")) {
748 state = State::InlineComment;
751 } else if (s.startsWith("//")) {
752 state = State::LineComment;
755 } else if (s[0] == '\"') {
756 state = State::InString;
758 result.push_back(s[0]);
760 case State::InString:
762 if (UNLIKELY(s.size() == 1)) {
763 throw std::logic_error("Invalid JSONC: string is not terminated");
765 result.push_back(s[0]);
766 result.push_back(s[1]);
769 } else if (s[0] == '\"') {
772 result.push_back(s[0]);
774 case State::InlineComment:
775 if (s.startsWith("*/")) {
780 case State::LineComment:
782 // skip the line break. It doesn't matter.
787 throw std::logic_error("Unknown comment state");
795 //////////////////////////////////////////////////////////////////////
797 dynamic parseJson(StringPiece range) {
798 return parseJson(range, json::serialization_opts());
803 json::serialization_opts const& opts) {
805 json::Input in(range, &opts);
807 auto ret = parseValue(in);
809 if (in.size() && *in != '\0') {
810 in.error("parsing didn't consume all input");
815 std::string toJson(dynamic const& dyn) {
816 return json::serialize(dyn, json::serialization_opts());
819 std::string toPrettyJson(dynamic const& dyn) {
820 json::serialization_opts opts;
821 opts.pretty_formatting = true;
822 return json::serialize(dyn, opts);
825 //////////////////////////////////////////////////////////////////////
826 // dynamic::print_as_pseudo_json() is implemented here for header
827 // ordering reasons (most of the dynamic implementation is in
828 // dynamic-inl.h, which we don't want to include json.h).
830 void dynamic::print_as_pseudo_json(std::ostream& out) const {
831 json::serialization_opts opts;
832 opts.allow_non_string_keys = true;
833 opts.allow_nan_inf = true;
834 out << json::serialize(*this, opts);
837 void PrintTo(const dynamic& dyn, std::ostream* os) {
838 json::serialization_opts opts;
839 opts.allow_nan_inf = true;
840 opts.allow_non_string_keys = true;
841 opts.pretty_formatting = true;
842 opts.sort_keys = true;
843 *os << json::serialize(dyn, opts);
846 //////////////////////////////////////////////////////////////////////