2 * Copyright 2013 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 //////////////////////////////////////////////////////////////////////
33 char32_t decodeUtf8(const unsigned char*& p, const unsigned char* const e) {
34 /* The following encodings are valid, except for the 5 and 6 byte
38 * 1110xxxx 10xxxxxx 10xxxxxx
39 * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
40 * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
41 * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
45 throw std::runtime_error("folly::decodeUtf8 empty/invalid string");
48 unsigned char fst = *p;
54 static const uint32_t bitMask[] = {
61 // upper control bits are masked out later
64 if ((fst & 0xC0) != 0xC0) {
65 throw std::runtime_error(
66 to<std::string>("folly::decodeUtf8 i=0 d=", d));
71 for (unsigned int i = 1; i != 3 && p + i < e; ++i) {
72 unsigned char tmp = p[i];
74 if ((tmp & 0xC0) != 0x80) {
75 throw std::runtime_error(
76 to<std::string>("folly::decodeUtf8 i=", i, " tmp=", (uint32_t)tmp));
79 d = (d << 6) | (tmp & 0x3F);
85 // overlong, could have been encoded with i bytes
86 if ((d & ~bitMask[i - 1]) == 0) {
87 throw std::runtime_error(
88 to<std::string>("folly::decodeUtf8 i=", i, " d=", d));
91 // check for surrogates only needed for 3 bytes
93 if ((d >= 0xD800 && d <= 0xDFFF) || d > 0x10FFFF) {
94 throw std::runtime_error(
95 to<std::string>("folly::decodeUtf8 i=", i, " d=", d));
104 throw std::runtime_error("folly::decodeUtf8 encoding length maxed out");
108 explicit Printer(fbstring& out,
109 unsigned* indentLevel,
110 serialization_opts const* opts)
112 , indentLevel_(indentLevel)
116 void operator()(dynamic const& v) const {
118 case dynamic::DOUBLE:
119 toAppend(v.asDouble(), &out_);
121 case dynamic::INT64: {
122 auto intval = v.asInt();
123 if (opts_.javascript_safe) {
124 // Use folly::to to check that this integer can be represented
125 // as a double without loss of precision.
126 intval = int64_t(to<double>(intval));
128 toAppend(intval, &out_);
132 out_ += v.asBool() ? "true" : "false";
137 case dynamic::STRING:
138 escapeString(v.asString(), out_, opts_);
140 case dynamic::OBJECT:
147 CHECK(0) << "Bad type " << v.type();
152 void printKV(const std::pair<const dynamic, dynamic>& p) const {
153 if (!opts_.allow_non_string_keys && !p.first.isString()) {
154 throw std::runtime_error("folly::toJson: JSON object key was not a "
162 template <typename Iterator>
163 void printKVPairs(Iterator begin, Iterator end) const {
165 for (++begin; begin != end; ++begin) {
172 void printObject(dynamic const& o) const {
181 if (opts_.sort_keys) {
182 std::vector<std::pair<dynamic, dynamic>> items(
183 o.items().begin(), o.items().end());
184 std::sort(items.begin(), items.end());
185 printKVPairs(items.begin(), items.end());
187 printKVPairs(o.items().begin(), o.items().end());
194 void printArray(dynamic const& a) const {
204 for (auto& val : makeRange(boost::next(a.begin()), a.end())) {
215 void outdent() const {
221 void indent() const {
227 void newline() const {
229 out_ += to<fbstring>('\n', fbstring(*indentLevel_ * 2, ' '));
233 void mapColon() const {
234 out_ += indentLevel_ ? " : " : ":";
239 unsigned* const indentLevel_;
240 serialization_opts const& opts_;
243 //////////////////////////////////////////////////////////////////////
245 struct ParseError : std::runtime_error {
246 explicit ParseError(int line)
247 : std::runtime_error(to<std::string>("json parse error on line ", line))
250 explicit ParseError(int line, std::string const& context,
251 std::string const& expected)
252 : std::runtime_error(to<std::string>("json parse error on line ", line,
253 !context.empty() ? to<std::string>(" near `", context, '\'')
258 explicit ParseError(std::string const& what)
259 : std::runtime_error("json parse error: " + what)
263 // Wraps our input buffer with some helper functions.
265 explicit Input(StringPiece range, json::serialization_opts const* opts)
273 Input(Input const&) = delete;
274 Input& operator=(Input const&) = delete;
276 char const* begin() const { return range_.begin(); }
278 // Parse ahead for as long as the supplied predicate is satisfied,
279 // returning a range of what was skipped.
280 template<class Predicate>
281 StringPiece skipWhile(const Predicate& p) {
282 std::size_t skipped = 0;
283 for (; skipped < range_.size(); ++skipped) {
284 if (!p(range_[skipped])) {
287 if (range_[skipped] == '\n') {
291 auto ret = range_.subpiece(0, skipped);
292 range_.advance(skipped);
297 StringPiece skipDigits() {
298 return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
301 void skipWhitespace() {
302 // Spaces other than ' ' characters are less common but should be
303 // checked. This configuration where we loop on the ' '
304 // separately from oddspaces was empirically fastest.
305 auto oddspace = [] (char c) {
306 return c == '\n' || c == '\t' || c == '\r';
310 for (; !range_.empty() && range_.front() == ' '; range_.pop_front()) {
312 if (!range_.empty() && oddspace(range_.front())) {
319 void expect(char c) {
321 throw ParseError(lineNum_, context(),
322 to<std::string>("expected '", c, '\''));
327 std::size_t size() const {
328 return range_.size();
331 int operator*() const {
343 return to<T>(&range_);
344 } catch (std::exception const& e) {
349 bool consume(StringPiece str) {
350 if (boost::starts_with(range_, str)) {
351 range_.advance(str.size());
358 std::string context() const {
359 return range_.subpiece(0, 16 /* arbitrary */).toString();
362 dynamic error(char const* what) const {
363 throw ParseError(lineNum_, context(), what);
366 json::serialization_opts const& getOpts() {
371 void storeCurrent() {
372 current_ = range_.empty() ? EOF : range_.front();
377 json::serialization_opts const& opts_;
382 dynamic parseValue(Input& in);
383 fbstring parseString(Input& in);
384 dynamic parseNumber(Input& in);
386 dynamic parseObject(Input& in) {
390 dynamic ret = dynamic::object;
399 if (in.getOpts().allow_trailing_comma && *in == '}') {
402 if (*in == '\"') { // string
403 auto key = parseString(in);
407 ret.insert(std::move(key), parseValue(in));
408 } else if (!in.getOpts().allow_non_string_keys) {
409 in.error("expected string for object key name");
411 auto key = parseValue(in);
415 ret.insert(std::move(key), parseValue(in));
430 dynamic parseArray(Input& in) {
443 if (in.getOpts().allow_trailing_comma && *in == ']') {
446 ret.push_back(parseValue(in));
459 dynamic parseNumber(Input& in) {
460 bool const negative = (*in == '-');
463 if (in.consume("Infinity")) {
464 return -std::numeric_limits<double>::infinity();
468 auto integral = in.skipDigits();
469 if (integral.empty()) {
470 in.error("expected digits after `-'");
472 auto const wasE = *in == 'e' || *in == 'E';
473 if (*in != '.' && !wasE) {
474 auto val = to<int64_t>(integral);
482 auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
483 if (*in == 'e' || *in == 'E') {
485 if (*in == '+' || *in == '-') {
488 auto expPart = in.skipDigits();
491 auto fullNum = makeRange(integral.begin(), end);
493 auto val = to<double>(fullNum);
500 fbstring decodeUnicodeEscape(Input& in) {
501 auto hexVal = [&] (char c) -> unsigned {
502 return c >= '0' && c <= '9' ? c - '0' :
503 c >= 'a' && c <= 'f' ? c - 'a' + 10 :
504 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
505 (in.error("invalid hex digit"), 0);
508 auto readHex = [&]() -> uint16_t {
510 in.error("expected 4 hex digits");
513 uint16_t ret = hexVal(*in) * 4096;
515 ret += hexVal(*in) * 256;
517 ret += hexVal(*in) * 16;
525 * If the value encoded is in the surrogate pair range, we need to
526 * make sure there is another escape that we can use also.
528 uint32_t codePoint = readHex();
529 if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
530 if (!in.consume("\\u")) {
531 in.error("expected another unicode escape for second half of "
534 uint16_t second = readHex();
535 if (second >= 0xdc00 && second <= 0xdfff) {
536 codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
539 in.error("second character in surrogate pair is invalid");
541 } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
542 in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
545 return codePointToUtf8(codePoint);
548 fbstring parseString(Input& in) {
554 auto range = in.skipWhile(
555 [] (char c) { return c != '\"' && c != '\\'; }
557 ret.append(range.begin(), range.end());
566 case '\"': ret.push_back('\"'); ++in; break;
567 case '\\': ret.push_back('\\'); ++in; break;
568 case '/': ret.push_back('/'); ++in; break;
569 case 'b': ret.push_back('\b'); ++in; break;
570 case 'f': ret.push_back('\f'); ++in; break;
571 case 'n': ret.push_back('\n'); ++in; break;
572 case 'r': ret.push_back('\r'); ++in; break;
573 case 't': ret.push_back('\t'); ++in; break;
574 case 'u': ++in; ret += decodeUnicodeEscape(in); break;
575 default: in.error(to<fbstring>("unknown escape ", *in,
576 " in string").c_str());
581 in.error("unterminated string");
585 * Apparently we're actually supposed to ban all control
586 * characters from strings. This seems unnecessarily
587 * restrictive, so we're only banning zero bytes. (Since the
588 * string is presumed to be UTF-8 encoded it's fine to just
591 in.error("null byte in string");
601 dynamic parseValue(Input& in) {
603 return *in == '[' ? parseArray(in) :
604 *in == '{' ? parseObject(in) :
605 *in == '\"' ? parseString(in) :
606 (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
607 in.consume("true") ? true :
608 in.consume("false") ? false :
609 in.consume("null") ? nullptr :
610 in.consume("Infinity") ? std::numeric_limits<double>::infinity() :
611 in.consume("NaN") ? std::numeric_limits<double>::quiet_NaN() :
612 in.error("expected json value");
617 //////////////////////////////////////////////////////////////////////
619 fbstring serialize(dynamic const& dyn, serialization_opts const& opts) {
621 unsigned indentLevel = 0;
622 Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
627 // Escape a string so that it is legal to print it in JSON text.
628 void escapeString(StringPiece input,
630 const serialization_opts& opts) {
631 auto hexDigit = [] (int c) -> char {
632 return c < 10 ? c + '0' : c - 10 + 'a';
635 out.reserve(out.size() + input.size() + 2);
638 auto* p = reinterpret_cast<const unsigned char*>(input.begin());
639 auto* q = reinterpret_cast<const unsigned char*>(input.begin());
640 auto* e = reinterpret_cast<const unsigned char*>(input.end());
643 // Since non-ascii encoding inherently does utf8 validation
644 // we explicitly validate utf8 only if non-ascii encoding is disabled.
645 if (opts.validate_utf8 && !opts.encode_non_ascii) {
646 // to achieve better spatial and temporal coherence
647 // we do utf8 validation progressively along with the
648 // string-escaping instead of two separate passes
650 // as the encoding progresses, q will stay at or ahead of p
653 // as p catches up with q, move q forward
655 // calling utf8_decode has the side effect of
656 // checking that utf8 encodings are valid
660 if (opts.encode_non_ascii && (*p & 0x80)) {
661 // note that this if condition captures utf8 chars
662 // with value > 127, so size > 1 byte
663 char32_t v = decodeUtf8(p, e);
665 out.push_back(hexDigit(v >> 12));
666 out.push_back(hexDigit((v >> 8) & 0x0f));
667 out.push_back(hexDigit((v >> 4) & 0x0f));
668 out.push_back(hexDigit(v & 0x0f));
669 } else if (*p == '\\' || *p == '\"') {
672 } else if (*p <= 0x1f) {
674 case '\b': out.append("\\b"); p++; break;
675 case '\f': out.append("\\f"); p++; break;
676 case '\n': out.append("\\n"); p++; break;
677 case '\r': out.append("\\r"); p++; break;
678 case '\t': out.append("\\t"); p++; break;
680 // note that this if condition captures non readable chars
681 // with value < 32, so size = 1 byte (e.g control chars).
683 out.push_back(hexDigit((*p & 0xf0) >> 4));
684 out.push_back(hexDigit(*p & 0xf));
697 //////////////////////////////////////////////////////////////////////
699 dynamic parseJson(StringPiece range) {
700 return parseJson(range, json::serialization_opts());
705 json::serialization_opts const& opts) {
707 json::Input in(range, &opts);
709 auto ret = parseValue(in);
711 if (in.size() && *in != '\0') {
712 in.error("parsing didn't consume all input");
717 fbstring toJson(dynamic const& dyn) {
718 return json::serialize(dyn, json::serialization_opts());
721 fbstring toPrettyJson(dynamic const& dyn) {
722 json::serialization_opts opts;
723 opts.pretty_formatting = true;
724 return json::serialize(dyn, opts);
727 //////////////////////////////////////////////////////////////////////
728 // dynamic::print_as_pseudo_json() is implemented here for header
729 // ordering reasons (most of the dynamic implementation is in
730 // dynamic-inl.h, which we don't want to include json.h).
732 void dynamic::print_as_pseudo_json(std::ostream& out) const {
733 json::serialization_opts opts;
734 opts.allow_non_string_keys = true;
735 out << json::serialize(*this, opts);
738 //////////////////////////////////////////////////////////////////////