2 * Copyright 2017 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>
21 #include <type_traits>
23 #include <boost/algorithm/string.hpp>
24 #include <boost/next_prior.hpp>
25 #include <folly/Bits.h>
26 #include <folly/Portability.h>
28 #include <folly/Conv.h>
29 #include <folly/Range.h>
30 #include <folly/String.h>
31 #include <folly/Unicode.h>
32 #include <folly/portability/Constexpr.h>
36 //////////////////////////////////////////////////////////////////////
44 unsigned* indentLevel,
45 serialization_opts const* opts)
46 : out_(out), indentLevel_(indentLevel), opts_(*opts) {}
48 void operator()(dynamic const& v) const {
51 if (!opts_.allow_nan_inf &&
52 (std::isnan(v.asDouble()) || std::isinf(v.asDouble()))) {
53 throw std::runtime_error("folly::toJson: JSON object value was a "
56 toAppend(v.asDouble(), &out_, opts_.double_mode, opts_.double_num_digits);
58 case dynamic::INT64: {
59 auto intval = v.asInt();
60 if (opts_.javascript_safe) {
61 // Use folly::to to check that this integer can be represented
62 // as a double without loss of precision.
63 intval = int64_t(to<double>(intval));
65 toAppend(intval, &out_);
69 out_ += v.asBool() ? "true" : "false";
75 escapeString(v.asString(), out_, opts_);
84 CHECK(0) << "Bad type " << v.type();
89 void printKV(const std::pair<const dynamic, dynamic>& p) const {
90 if (!opts_.allow_non_string_keys && !p.first.isString()) {
91 throw std::runtime_error("folly::toJson: JSON object key was not a "
99 template <typename Iterator>
100 void printKVPairs(Iterator begin, Iterator end) const {
102 for (++begin; begin != end; ++begin) {
109 void printObject(dynamic const& o) const {
118 if (opts_.sort_keys || opts_.sort_keys_by) {
119 using ref = std::reference_wrapper<decltype(o.items())::value_type const>;
120 std::vector<ref> refs(o.items().begin(), o.items().end());
122 using SortByRef = FunctionRef<bool(dynamic const&, dynamic const&)>;
123 auto const& sort_keys_by = opts_.sort_keys_by
124 ? SortByRef(opts_.sort_keys_by)
125 : SortByRef(std::less<dynamic>());
126 std::sort(refs.begin(), refs.end(), [&](ref a, ref b) {
127 // Only compare keys. No ordering among identical keys.
128 return sort_keys_by(a.get().first, b.get().first);
130 printKVPairs(refs.cbegin(), refs.cend());
132 printKVPairs(o.items().begin(), o.items().end());
139 void printArray(dynamic const& a) const {
149 for (auto& val : range(boost::next(a.begin()), a.end())) {
160 void outdent() const {
166 void indent() const {
172 void newline() const {
174 out_ += to<std::string>('\n', std::string(*indentLevel_ * 2, ' '));
178 void mapColon() const {
179 out_ += indentLevel_ ? " : " : ":";
184 unsigned* const indentLevel_;
185 serialization_opts const& opts_;
188 //////////////////////////////////////////////////////////////////////
190 struct ParseError : std::runtime_error {
193 std::string const& context,
194 std::string const& expected)
195 : std::runtime_error(to<std::string>(
196 "json parse error on line ",
198 !context.empty() ? to<std::string>(" near `", context, '\'') : "",
203 // Wraps our input buffer with some helper functions.
205 explicit Input(StringPiece range, json::serialization_opts const* opts)
213 Input(Input const&) = delete;
214 Input& operator=(Input const&) = delete;
216 char const* begin() const { return range_.begin(); }
218 // Parse ahead for as long as the supplied predicate is satisfied,
219 // returning a range of what was skipped.
220 template<class Predicate>
221 StringPiece skipWhile(const Predicate& p) {
222 std::size_t skipped = 0;
223 for (; skipped < range_.size(); ++skipped) {
224 if (!p(range_[skipped])) {
227 if (range_[skipped] == '\n') {
231 auto ret = range_.subpiece(0, skipped);
232 range_.advance(skipped);
237 StringPiece skipDigits() {
238 return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
241 StringPiece skipMinusAndDigits() {
242 bool firstChar = true;
243 return skipWhile([&firstChar] (char c) {
244 bool result = (c >= '0' && c <= '9') || (firstChar && c == '-');
250 void skipWhitespace() {
251 range_ = folly::skipWhitespace(range_);
255 void expect(char c) {
257 throw ParseError(lineNum_, context(),
258 to<std::string>("expected '", c, '\''));
263 std::size_t size() const {
264 return range_.size();
267 int operator*() const {
279 return to<T>(&range_);
280 } catch (std::exception const& e) {
285 bool consume(StringPiece str) {
286 if (boost::starts_with(range_, str)) {
287 range_.advance(str.size());
294 std::string context() const {
295 return range_.subpiece(0, 16 /* arbitrary */).toString();
298 dynamic error(char const* what) const {
299 throw ParseError(lineNum_, context(), what);
302 json::serialization_opts const& getOpts() {
306 void incrementRecursionLevel() {
307 if (currentRecursionLevel_ > opts_.recursion_limit) {
308 error("recursion limit exceeded");
310 currentRecursionLevel_++;
313 void decrementRecursionLevel() {
314 currentRecursionLevel_--;
318 void storeCurrent() {
319 current_ = range_.empty() ? EOF : range_.front();
324 json::serialization_opts const& opts_;
327 unsigned int currentRecursionLevel_{0};
330 class RecursionGuard {
332 explicit RecursionGuard(Input& in) : in_(in) {
333 in_.incrementRecursionLevel();
337 in_.decrementRecursionLevel();
344 dynamic parseValue(Input& in);
345 std::string parseString(Input& in);
346 dynamic parseNumber(Input& in);
348 dynamic parseObject(Input& in) {
352 dynamic ret = dynamic::object;
361 if (in.getOpts().allow_trailing_comma && *in == '}') {
364 if (*in == '\"') { // string
365 auto key = parseString(in);
369 ret.insert(std::move(key), parseValue(in));
370 } else if (!in.getOpts().allow_non_string_keys) {
371 in.error("expected string for object key name");
373 auto key = parseValue(in);
377 ret.insert(std::move(key), parseValue(in));
392 dynamic parseArray(Input& in) {
396 dynamic ret = dynamic::array;
405 if (in.getOpts().allow_trailing_comma && *in == ']') {
408 ret.push_back(parseValue(in));
421 dynamic parseNumber(Input& in) {
422 bool const negative = (*in == '-');
423 if (negative && in.consume("-Infinity")) {
424 if (in.getOpts().parse_numbers_as_strings) {
427 return -std::numeric_limits<double>::infinity();
431 auto integral = in.skipMinusAndDigits();
432 if (negative && integral.size() < 2) {
433 in.error("expected digits after `-'");
436 auto const wasE = *in == 'e' || *in == 'E';
438 constexpr const char* maxInt = "9223372036854775807";
439 constexpr const char* minInt = "-9223372036854775808";
440 constexpr auto maxIntLen = constexpr_strlen(maxInt);
441 constexpr auto minIntLen = constexpr_strlen(minInt);
443 if (*in != '.' && !wasE && in.getOpts().parse_numbers_as_strings) {
447 if (*in != '.' && !wasE) {
448 if (LIKELY(!in.getOpts().double_fallback || integral.size() < maxIntLen) ||
449 (!negative && integral.size() == maxIntLen && integral <= maxInt) ||
450 (negative && integral.size() == minIntLen && integral <= minInt)) {
451 auto val = to<int64_t>(integral);
455 auto val = to<double>(integral);
461 auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
462 if (*in == 'e' || *in == 'E') {
464 if (*in == '+' || *in == '-') {
467 auto expPart = in.skipDigits();
470 auto fullNum = range(integral.begin(), end);
471 if (in.getOpts().parse_numbers_as_strings) {
474 auto val = to<double>(fullNum);
478 std::string decodeUnicodeEscape(Input& in) {
479 auto hexVal = [&] (int c) -> uint16_t {
481 c >= '0' && c <= '9' ? c - '0' :
482 c >= 'a' && c <= 'f' ? c - 'a' + 10 :
483 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
484 (in.error("invalid hex digit"), 0));
487 auto readHex = [&]() -> uint16_t {
489 in.error("expected 4 hex digits");
492 uint16_t ret = uint16_t(hexVal(*in) * 4096);
494 ret += hexVal(*in) * 256;
496 ret += hexVal(*in) * 16;
504 * If the value encoded is in the surrogate pair range, we need to
505 * make sure there is another escape that we can use also.
507 uint32_t codePoint = readHex();
508 if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
509 if (!in.consume("\\u")) {
510 in.error("expected another unicode escape for second half of "
513 uint16_t second = readHex();
514 if (second >= 0xdc00 && second <= 0xdfff) {
515 codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
518 in.error("second character in surrogate pair is invalid");
520 } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
521 in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
524 return codePointToUtf8(codePoint);
527 std::string parseString(Input& in) {
528 DCHECK_EQ(*in, '\"');
533 auto range = in.skipWhile(
534 [] (char c) { return c != '\"' && c != '\\'; }
536 ret.append(range.begin(), range.end());
545 case '\"': ret.push_back('\"'); ++in; break;
546 case '\\': ret.push_back('\\'); ++in; break;
547 case '/': ret.push_back('/'); ++in; break;
548 case 'b': ret.push_back('\b'); ++in; break;
549 case 'f': ret.push_back('\f'); ++in; break;
550 case 'n': ret.push_back('\n'); ++in; break;
551 case 'r': ret.push_back('\r'); ++in; break;
552 case 't': ret.push_back('\t'); ++in; break;
553 case 'u': ++in; ret += decodeUnicodeEscape(in); break;
555 in.error(to<std::string>("unknown escape ", *in, " in string").c_str());
560 in.error("unterminated string");
564 * Apparently we're actually supposed to ban all control
565 * characters from strings. This seems unnecessarily
566 * restrictive, so we're only banning zero bytes. (Since the
567 * string is presumed to be UTF-8 encoded it's fine to just
570 in.error("null byte in string");
573 ret.push_back(char(*in));
580 dynamic parseValue(Input& in) {
581 RecursionGuard guard(in);
584 return *in == '[' ? parseArray(in) :
585 *in == '{' ? parseObject(in) :
586 *in == '\"' ? parseString(in) :
587 (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
588 in.consume("true") ? true :
589 in.consume("false") ? false :
590 in.consume("null") ? nullptr :
591 in.consume("Infinity") ?
592 (in.getOpts().parse_numbers_as_strings ? (dynamic)"Infinity" :
593 (dynamic)std::numeric_limits<double>::infinity()) :
595 (in.getOpts().parse_numbers_as_strings ? (dynamic)"NaN" :
596 (dynamic)std::numeric_limits<double>::quiet_NaN()) :
597 in.error("expected json value");
602 //////////////////////////////////////////////////////////////////////
604 std::string serialize(dynamic const& dyn, serialization_opts const& opts) {
606 unsigned indentLevel = 0;
607 Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
612 // Fast path to determine the longest prefix that can be left
613 // unescaped in a string of sizeof(T) bytes packed in an integer of
616 size_t firstEscapableInWord(T s) {
617 static_assert(std::is_unsigned<T>::value, "Unsigned integer required");
618 static constexpr T kOnes = ~T() / 255; // 0x...0101
619 static constexpr T kMsbs = kOnes * 0x80; // 0x...8080
621 // Sets the MSB of bytes < b. Precondition: b < 128.
622 auto isLess = [](T w, uint8_t b) {
623 // A byte is < b iff subtracting b underflows, so we check that
624 // the MSB wasn't set before and it's set after the subtraction.
625 return (w - kOnes * b) & ~w & kMsbs;
628 auto isChar = [&](uint8_t c) {
629 // A byte is == c iff it is 0 if xored with c.
630 return isLess(s ^ (kOnes * c), 1);
633 // The following masks have the MSB set for each byte of the word
634 // that satisfies the corresponding condition.
635 auto isHigh = s & kMsbs; // >= 128
636 auto isLow = isLess(s, 0x20); // <= 0x1f
637 auto needsEscape = isHigh | isLow | isChar('\\') | isChar('"');
643 if (folly::kIsLittleEndian) {
644 return folly::findFirstSet(needsEscape) / 8 - 1;
646 return sizeof(T) - folly::findLastSet(needsEscape) / 8;
650 // Escape a string so that it is legal to print it in JSON text.
654 const serialization_opts& opts) {
655 auto hexDigit = [] (uint8_t c) -> char {
656 return c < 10 ? c + '0' : c - 10 + 'a';
661 auto* p = reinterpret_cast<const unsigned char*>(input.begin());
662 auto* q = reinterpret_cast<const unsigned char*>(input.begin());
663 auto* e = reinterpret_cast<const unsigned char*>(input.end());
666 // Find the longest prefix that does not need escaping, and copy
667 // it literally into the output string.
669 while (firstEsc < e) {
670 auto avail = e - firstEsc;
673 word = folly::loadUnaligned<uint64_t>(firstEsc);
675 memcpy(static_cast<void*>(&word), firstEsc, avail);
677 auto prefix = firstEscapableInWord(word);
678 DCHECK_LE(prefix, avail);
685 out.append(reinterpret_cast<const char*>(p), firstEsc - p);
687 // We can't be in the middle of a multibyte sequence, so we can reset q.
694 // Handle the next byte that may need escaping.
696 // Since non-ascii encoding inherently does utf8 validation
697 // we explicitly validate utf8 only if non-ascii encoding is disabled.
698 if ((opts.validate_utf8 || opts.skip_invalid_utf8)
699 && !opts.encode_non_ascii) {
700 // To achieve better spatial and temporal coherence
701 // we do utf8 validation progressively along with the
702 // string-escaping instead of two separate passes.
704 // As the encoding progresses, q will stay at or ahead of p.
707 // As p catches up with q, move q forward.
709 // calling utf8_decode has the side effect of
710 // checking that utf8 encodings are valid
711 char32_t v = utf8ToCodePoint(q, e, opts.skip_invalid_utf8);
712 if (opts.skip_invalid_utf8 && v == U'\ufffd') {
713 out.append(u8"\ufffd");
719 if (opts.encode_non_ascii && (*p & 0x80)) {
720 // note that this if condition captures utf8 chars
721 // with value > 127, so size > 1 byte
722 char32_t v = utf8ToCodePoint(p, e, opts.skip_invalid_utf8);
723 char buf[] = "\\u\0\0\0\0";
724 buf[2] = hexDigit(uint8_t(v >> 12));
725 buf[3] = hexDigit((v >> 8) & 0x0f);
726 buf[4] = hexDigit((v >> 4) & 0x0f);
727 buf[5] = hexDigit(v & 0x0f);
729 } else if (*p == '\\' || *p == '\"') {
733 } else if (*p <= 0x1f) {
735 case '\b': out.append("\\b"); p++; break;
736 case '\f': out.append("\\f"); p++; break;
737 case '\n': out.append("\\n"); p++; break;
738 case '\r': out.append("\\r"); p++; break;
739 case '\t': out.append("\\t"); p++; break;
741 // Note that this if condition captures non readable chars
742 // with value < 32, so size = 1 byte (e.g control chars).
743 char buf[] = "\\u00\0\0";
744 buf[4] = hexDigit(uint8_t((*p & 0xf0) >> 4));
745 buf[5] = hexDigit(uint8_t(*p & 0xf));
750 out.push_back(char(*p++));
757 std::string stripComments(StringPiece jsonC) {
764 } state = State::None;
766 for (size_t i = 0; i < jsonC.size(); ++i) {
767 auto s = jsonC.subpiece(i);
770 if (s.startsWith("/*")) {
771 state = State::InlineComment;
774 } else if (s.startsWith("//")) {
775 state = State::LineComment;
778 } else if (s[0] == '\"') {
779 state = State::InString;
781 result.push_back(s[0]);
783 case State::InString:
785 if (UNLIKELY(s.size() == 1)) {
786 throw std::logic_error("Invalid JSONC: string is not terminated");
788 result.push_back(s[0]);
789 result.push_back(s[1]);
792 } else if (s[0] == '\"') {
795 result.push_back(s[0]);
797 case State::InlineComment:
798 if (s.startsWith("*/")) {
803 case State::LineComment:
805 // skip the line break. It doesn't matter.
810 throw std::logic_error("Unknown comment state");
818 //////////////////////////////////////////////////////////////////////
820 dynamic parseJson(StringPiece range) {
821 return parseJson(range, json::serialization_opts());
826 json::serialization_opts const& opts) {
828 json::Input in(range, &opts);
830 auto ret = parseValue(in);
832 if (in.size() && *in != '\0') {
833 in.error("parsing didn't consume all input");
838 std::string toJson(dynamic const& dyn) {
839 return json::serialize(dyn, json::serialization_opts());
842 std::string toPrettyJson(dynamic const& dyn) {
843 json::serialization_opts opts;
844 opts.pretty_formatting = true;
845 return json::serialize(dyn, opts);
848 //////////////////////////////////////////////////////////////////////
849 // dynamic::print_as_pseudo_json() is implemented here for header
850 // ordering reasons (most of the dynamic implementation is in
851 // dynamic-inl.h, which we don't want to include json.h).
853 void dynamic::print_as_pseudo_json(std::ostream& out) const {
854 json::serialization_opts opts;
855 opts.allow_non_string_keys = true;
856 opts.allow_nan_inf = true;
857 out << json::serialize(*this, opts);
860 void PrintTo(const dynamic& dyn, std::ostream* os) {
861 json::serialization_opts opts;
862 opts.allow_nan_inf = true;
863 opts.allow_non_string_keys = true;
864 opts.pretty_formatting = true;
865 opts.sort_keys = true;
866 *os << json::serialize(dyn, opts);
869 //////////////////////////////////////////////////////////////////////