2 * Copyright 2014 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/Range.h"
23 #include "folly/Unicode.h"
24 #include "folly/Conv.h"
28 //////////////////////////////////////////////////////////////////////
34 const unsigned char*& p,
35 const unsigned char* const e,
37 /* The following encodings are valid, except for the 5 and 6 byte
41 * 1110xxxx 10xxxxxx 10xxxxxx
42 * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
43 * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
44 * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
47 auto skip = [&] { ++p; return U'\ufffd'; };
50 if (skipOnError) return skip();
51 throw std::runtime_error("folly::decodeUtf8 empty/invalid string");
54 unsigned char fst = *p;
60 static const uint32_t bitMask[] = {
67 // upper control bits are masked out later
70 if ((fst & 0xC0) != 0xC0) {
71 if (skipOnError) return skip();
72 throw std::runtime_error(to<std::string>("folly::decodeUtf8 i=0 d=", d));
77 for (unsigned int i = 1; i != 3 && p + i < e; ++i) {
78 unsigned char tmp = p[i];
80 if ((tmp & 0xC0) != 0x80) {
81 if (skipOnError) return skip();
82 throw std::runtime_error(
83 to<std::string>("folly::decodeUtf8 i=", i, " tmp=", (uint32_t)tmp));
86 d = (d << 6) | (tmp & 0x3F);
92 // overlong, could have been encoded with i bytes
93 if ((d & ~bitMask[i - 1]) == 0) {
94 if (skipOnError) return skip();
95 throw std::runtime_error(
96 to<std::string>("folly::decodeUtf8 i=", i, " d=", d));
99 // check for surrogates only needed for 3 bytes
101 if ((d >= 0xD800 && d <= 0xDFFF) || d > 0x10FFFF) {
102 if (skipOnError) return skip();
103 throw std::runtime_error(
104 to<std::string>("folly::decodeUtf8 i=", i, " d=", d));
113 if (skipOnError) return skip();
114 throw std::runtime_error("folly::decodeUtf8 encoding length maxed out");
118 explicit Printer(fbstring& out,
119 unsigned* indentLevel,
120 serialization_opts const* opts)
122 , indentLevel_(indentLevel)
126 void operator()(dynamic const& v) const {
128 case dynamic::DOUBLE:
129 if (!opts_.allow_nan_inf &&
130 (std::isnan(v.asDouble()) || std::isinf(v.asDouble()))) {
131 throw std::runtime_error("folly::toJson: JSON object value was a "
134 toAppend(v.asDouble(), &out_, opts_.double_mode, opts_.double_num_digits);
136 case dynamic::INT64: {
137 auto intval = v.asInt();
138 if (opts_.javascript_safe) {
139 // Use folly::to to check that this integer can be represented
140 // as a double without loss of precision.
141 intval = int64_t(to<double>(intval));
143 toAppend(intval, &out_);
147 out_ += v.asBool() ? "true" : "false";
152 case dynamic::STRING:
153 escapeString(v.asString(), out_, opts_);
155 case dynamic::OBJECT:
162 CHECK(0) << "Bad type " << v.type();
167 void printKV(const std::pair<const dynamic, dynamic>& p) const {
168 if (!opts_.allow_non_string_keys && !p.first.isString()) {
169 throw std::runtime_error("folly::toJson: JSON object key was not a "
177 template <typename Iterator>
178 void printKVPairs(Iterator begin, Iterator end) const {
180 for (++begin; begin != end; ++begin) {
187 void printObject(dynamic const& o) const {
196 if (opts_.sort_keys) {
197 std::vector<std::pair<dynamic, dynamic>> items(
198 o.items().begin(), o.items().end());
199 std::sort(items.begin(), items.end());
200 printKVPairs(items.begin(), items.end());
202 printKVPairs(o.items().begin(), o.items().end());
209 void printArray(dynamic const& a) const {
219 for (auto& val : range(boost::next(a.begin()), a.end())) {
230 void outdent() const {
236 void indent() const {
242 void newline() const {
244 out_ += to<fbstring>('\n', fbstring(*indentLevel_ * 2, ' '));
248 void mapColon() const {
249 out_ += indentLevel_ ? " : " : ":";
254 unsigned* const indentLevel_;
255 serialization_opts const& opts_;
258 //////////////////////////////////////////////////////////////////////
260 struct ParseError : std::runtime_error {
261 explicit ParseError(int line)
262 : std::runtime_error(to<std::string>("json parse error on line ", line))
265 explicit ParseError(int line, std::string const& context,
266 std::string const& expected)
267 : std::runtime_error(to<std::string>("json parse error on line ", line,
268 !context.empty() ? to<std::string>(" near `", context, '\'')
273 explicit ParseError(std::string const& what)
274 : std::runtime_error("json parse error: " + what)
278 // Wraps our input buffer with some helper functions.
280 explicit Input(StringPiece range, json::serialization_opts const* opts)
288 Input(Input const&) = delete;
289 Input& operator=(Input const&) = delete;
291 char const* begin() const { return range_.begin(); }
293 // Parse ahead for as long as the supplied predicate is satisfied,
294 // returning a range of what was skipped.
295 template<class Predicate>
296 StringPiece skipWhile(const Predicate& p) {
297 std::size_t skipped = 0;
298 for (; skipped < range_.size(); ++skipped) {
299 if (!p(range_[skipped])) {
302 if (range_[skipped] == '\n') {
306 auto ret = range_.subpiece(0, skipped);
307 range_.advance(skipped);
312 StringPiece skipDigits() {
313 return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
316 StringPiece skipMinusAndDigits() {
317 bool firstChar = true;
318 return skipWhile([&firstChar] (char c) {
319 bool result = (c >= '0' && c <= '9') || (firstChar && c == '-');
325 void skipWhitespace() {
326 // Spaces other than ' ' characters are less common but should be
327 // checked. This configuration where we loop on the ' '
328 // separately from oddspaces was empirically fastest.
329 auto oddspace = [] (char c) {
330 return c == '\n' || c == '\t' || c == '\r';
334 for (; !range_.empty() && range_.front() == ' '; range_.pop_front()) {
336 if (!range_.empty() && oddspace(range_.front())) {
343 void expect(char c) {
345 throw ParseError(lineNum_, context(),
346 to<std::string>("expected '", c, '\''));
351 std::size_t size() const {
352 return range_.size();
355 int operator*() const {
367 return to<T>(&range_);
368 } catch (std::exception const& e) {
373 bool consume(StringPiece str) {
374 if (boost::starts_with(range_, str)) {
375 range_.advance(str.size());
382 std::string context() const {
383 return range_.subpiece(0, 16 /* arbitrary */).toString();
386 dynamic error(char const* what) const {
387 throw ParseError(lineNum_, context(), what);
390 json::serialization_opts const& getOpts() {
395 void storeCurrent() {
396 current_ = range_.empty() ? EOF : range_.front();
401 json::serialization_opts const& opts_;
406 dynamic parseValue(Input& in);
407 fbstring parseString(Input& in);
408 dynamic parseNumber(Input& in);
410 dynamic parseObject(Input& in) {
414 dynamic ret = dynamic::object;
423 if (in.getOpts().allow_trailing_comma && *in == '}') {
426 if (*in == '\"') { // string
427 auto key = parseString(in);
431 ret.insert(std::move(key), parseValue(in));
432 } else if (!in.getOpts().allow_non_string_keys) {
433 in.error("expected string for object key name");
435 auto key = parseValue(in);
439 ret.insert(std::move(key), parseValue(in));
454 dynamic parseArray(Input& in) {
467 if (in.getOpts().allow_trailing_comma && *in == ']') {
470 ret.push_back(parseValue(in));
483 dynamic parseNumber(Input& in) {
484 bool const negative = (*in == '-');
486 if (in.consume("-Infinity")) {
487 return -std::numeric_limits<double>::infinity();
491 auto integral = in.skipMinusAndDigits();
492 if (negative && integral.size() < 2) {
493 in.error("expected digits after `-'");
496 auto const wasE = *in == 'e' || *in == 'E';
497 if (*in != '.' && !wasE) {
498 auto val = to<int64_t>(integral);
503 auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
504 if (*in == 'e' || *in == 'E') {
506 if (*in == '+' || *in == '-') {
509 auto expPart = in.skipDigits();
512 auto fullNum = range(integral.begin(), end);
514 auto val = to<double>(fullNum);
518 fbstring decodeUnicodeEscape(Input& in) {
519 auto hexVal = [&] (char c) -> unsigned {
520 return c >= '0' && c <= '9' ? c - '0' :
521 c >= 'a' && c <= 'f' ? c - 'a' + 10 :
522 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
523 (in.error("invalid hex digit"), 0);
526 auto readHex = [&]() -> uint16_t {
528 in.error("expected 4 hex digits");
531 uint16_t ret = hexVal(*in) * 4096;
533 ret += hexVal(*in) * 256;
535 ret += hexVal(*in) * 16;
543 * If the value encoded is in the surrogate pair range, we need to
544 * make sure there is another escape that we can use also.
546 uint32_t codePoint = readHex();
547 if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
548 if (!in.consume("\\u")) {
549 in.error("expected another unicode escape for second half of "
552 uint16_t second = readHex();
553 if (second >= 0xdc00 && second <= 0xdfff) {
554 codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
557 in.error("second character in surrogate pair is invalid");
559 } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
560 in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
563 return codePointToUtf8(codePoint);
566 fbstring parseString(Input& in) {
572 auto range = in.skipWhile(
573 [] (char c) { return c != '\"' && c != '\\'; }
575 ret.append(range.begin(), range.end());
584 case '\"': ret.push_back('\"'); ++in; break;
585 case '\\': ret.push_back('\\'); ++in; break;
586 case '/': ret.push_back('/'); ++in; break;
587 case 'b': ret.push_back('\b'); ++in; break;
588 case 'f': ret.push_back('\f'); ++in; break;
589 case 'n': ret.push_back('\n'); ++in; break;
590 case 'r': ret.push_back('\r'); ++in; break;
591 case 't': ret.push_back('\t'); ++in; break;
592 case 'u': ++in; ret += decodeUnicodeEscape(in); break;
593 default: in.error(to<fbstring>("unknown escape ", *in,
594 " in string").c_str());
599 in.error("unterminated string");
603 * Apparently we're actually supposed to ban all control
604 * characters from strings. This seems unnecessarily
605 * restrictive, so we're only banning zero bytes. (Since the
606 * string is presumed to be UTF-8 encoded it's fine to just
609 in.error("null byte in string");
619 dynamic parseValue(Input& in) {
621 return *in == '[' ? parseArray(in) :
622 *in == '{' ? parseObject(in) :
623 *in == '\"' ? parseString(in) :
624 (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
625 in.consume("true") ? true :
626 in.consume("false") ? false :
627 in.consume("null") ? nullptr :
628 in.consume("Infinity") ? std::numeric_limits<double>::infinity() :
629 in.consume("NaN") ? std::numeric_limits<double>::quiet_NaN() :
630 in.error("expected json value");
635 //////////////////////////////////////////////////////////////////////
637 fbstring serialize(dynamic const& dyn, serialization_opts const& opts) {
639 unsigned indentLevel = 0;
640 Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
645 // Escape a string so that it is legal to print it in JSON text.
646 void escapeString(StringPiece input,
648 const serialization_opts& opts) {
649 auto hexDigit = [] (int c) -> char {
650 return c < 10 ? c + '0' : c - 10 + 'a';
653 out.reserve(out.size() + input.size() + 2);
656 auto* p = reinterpret_cast<const unsigned char*>(input.begin());
657 auto* q = reinterpret_cast<const unsigned char*>(input.begin());
658 auto* e = reinterpret_cast<const unsigned char*>(input.end());
661 // Since non-ascii encoding inherently does utf8 validation
662 // we explicitly validate utf8 only if non-ascii encoding is disabled.
663 if ((opts.validate_utf8 || opts.skip_invalid_utf8)
664 && !opts.encode_non_ascii) {
665 // to achieve better spatial and temporal coherence
666 // we do utf8 validation progressively along with the
667 // string-escaping instead of two separate passes
669 // as the encoding progresses, q will stay at or ahead of p
672 // as p catches up with q, move q forward
674 // calling utf8_decode has the side effect of
675 // checking that utf8 encodings are valid
676 char32_t v = decodeUtf8(q, e, opts.skip_invalid_utf8);
677 if (opts.skip_invalid_utf8 && v == U'\ufffd') {
678 out.append("\ufffd");
684 if (opts.encode_non_ascii && (*p & 0x80)) {
685 // note that this if condition captures utf8 chars
686 // with value > 127, so size > 1 byte
687 char32_t v = decodeUtf8(p, e, opts.skip_invalid_utf8);
689 out.push_back(hexDigit(v >> 12));
690 out.push_back(hexDigit((v >> 8) & 0x0f));
691 out.push_back(hexDigit((v >> 4) & 0x0f));
692 out.push_back(hexDigit(v & 0x0f));
693 } else if (*p == '\\' || *p == '\"') {
696 } else if (*p <= 0x1f) {
698 case '\b': out.append("\\b"); p++; break;
699 case '\f': out.append("\\f"); p++; break;
700 case '\n': out.append("\\n"); p++; break;
701 case '\r': out.append("\\r"); p++; break;
702 case '\t': out.append("\\t"); p++; break;
704 // note that this if condition captures non readable chars
705 // with value < 32, so size = 1 byte (e.g control chars).
707 out.push_back(hexDigit((*p & 0xf0) >> 4));
708 out.push_back(hexDigit(*p & 0xf));
721 //////////////////////////////////////////////////////////////////////
723 dynamic parseJson(StringPiece range) {
724 return parseJson(range, json::serialization_opts());
729 json::serialization_opts const& opts) {
731 json::Input in(range, &opts);
733 auto ret = parseValue(in);
735 if (in.size() && *in != '\0') {
736 in.error("parsing didn't consume all input");
741 fbstring toJson(dynamic const& dyn) {
742 return json::serialize(dyn, json::serialization_opts());
745 fbstring toPrettyJson(dynamic const& dyn) {
746 json::serialization_opts opts;
747 opts.pretty_formatting = true;
748 return json::serialize(dyn, opts);
751 //////////////////////////////////////////////////////////////////////
752 // dynamic::print_as_pseudo_json() is implemented here for header
753 // ordering reasons (most of the dynamic implementation is in
754 // dynamic-inl.h, which we don't want to include json.h).
756 void dynamic::print_as_pseudo_json(std::ostream& out) const {
757 json::serialization_opts opts;
758 opts.allow_non_string_keys = true;
759 opts.allow_nan_inf = true;
760 out << json::serialize(*this, opts);
763 //////////////////////////////////////////////////////////////////////