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<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 void printObject(dynamic const& o) const {
171 auto it = o.items().begin();
173 for (++it; it != o.items().end(); ++it) {
183 void printArray(dynamic const& a) const {
193 for (auto& val : makeRange(boost::next(a.begin()), a.end())) {
204 void outdent() const {
210 void indent() const {
216 void newline() const {
218 out_ += to<fbstring>('\n', fbstring(*indentLevel_ * 2, ' '));
222 void mapColon() const {
223 out_ += indentLevel_ ? " : " : ":";
228 unsigned* const indentLevel_;
229 serialization_opts const& opts_;
232 //////////////////////////////////////////////////////////////////////
234 struct ParseError : std::runtime_error {
235 explicit ParseError(int line)
236 : std::runtime_error(to<std::string>("json parse error on line ", line))
239 explicit ParseError(int line, std::string const& context,
240 std::string const& expected)
241 : std::runtime_error(to<std::string>("json parse error on line ", line,
242 !context.empty() ? to<std::string>(" near `", context, '\'')
247 explicit ParseError(std::string const& what)
248 : std::runtime_error("json parse error: " + what)
252 // Wraps our input buffer with some helper functions.
254 explicit Input(StringPiece range, json::serialization_opts const* opts)
262 Input(Input const&) = delete;
263 Input& operator=(Input const&) = delete;
265 char const* begin() const { return range_.begin(); }
267 // Parse ahead for as long as the supplied predicate is satisfied,
268 // returning a range of what was skipped.
269 template<class Predicate>
270 StringPiece skipWhile(const Predicate& p) {
271 std::size_t skipped = 0;
272 for (; skipped < range_.size(); ++skipped) {
273 if (!p(range_[skipped])) {
276 if (range_[skipped] == '\n') {
280 auto ret = range_.subpiece(0, skipped);
281 range_.advance(skipped);
286 StringPiece skipDigits() {
287 return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
290 void skipWhitespace() {
291 // Spaces other than ' ' characters are less common but should be
292 // checked. This configuration where we loop on the ' '
293 // separately from oddspaces was empirically fastest.
294 auto oddspace = [] (char c) {
295 return c == '\n' || c == '\t' || c == '\r';
299 for (; !range_.empty() && range_.front() == ' '; range_.pop_front()) {
301 if (!range_.empty() && oddspace(range_.front())) {
308 void expect(char c) {
310 throw ParseError(lineNum_, context(),
311 to<std::string>("expected '", c, '\''));
316 std::size_t size() const {
317 return range_.size();
320 int operator*() const {
332 return to<T>(&range_);
333 } catch (std::exception const& e) {
338 bool consume(StringPiece str) {
339 if (boost::starts_with(range_, str)) {
340 range_.advance(str.size());
347 std::string context() const {
348 return range_.subpiece(0, 16 /* arbitrary */).toString();
351 dynamic error(char const* what) const {
352 throw ParseError(lineNum_, context(), what);
355 json::serialization_opts const& getOpts() {
360 void storeCurrent() {
361 current_ = range_.empty() ? EOF : range_.front();
366 json::serialization_opts const& opts_;
371 dynamic parseValue(Input& in);
372 fbstring parseString(Input& in);
373 dynamic parseNumber(Input& in);
375 dynamic parseObject(Input& in) {
379 dynamic ret = dynamic::object;
388 if (in.getOpts().allow_trailing_comma && *in == '}') {
391 if (*in == '\"') { // string
392 auto key = parseString(in);
396 ret.insert(std::move(key), parseValue(in));
397 } else if (!in.getOpts().allow_non_string_keys) {
398 in.error("expected string for object key name");
400 auto key = parseValue(in);
404 ret.insert(std::move(key), parseValue(in));
419 dynamic parseArray(Input& in) {
432 if (in.getOpts().allow_trailing_comma && *in == ']') {
435 ret.push_back(parseValue(in));
448 dynamic parseNumber(Input& in) {
449 bool const negative = (*in == '-');
452 if (in.consume("Infinity")) {
453 return -std::numeric_limits<double>::infinity();
457 auto integral = in.skipDigits();
458 if (integral.empty()) {
459 in.error("expected digits after `-'");
461 auto const wasE = *in == 'e' || *in == 'E';
462 if (*in != '.' && !wasE) {
463 auto val = to<int64_t>(integral);
471 auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
472 if (*in == 'e' || *in == 'E') {
474 if (*in == '+' || *in == '-') {
477 auto expPart = in.skipDigits();
480 auto fullNum = makeRange(integral.begin(), end);
482 auto val = to<double>(fullNum);
489 fbstring decodeUnicodeEscape(Input& in) {
490 auto hexVal = [&] (char c) -> unsigned {
491 return c >= '0' && c <= '9' ? c - '0' :
492 c >= 'a' && c <= 'f' ? c - 'a' + 10 :
493 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
494 (in.error("invalid hex digit"), 0);
497 auto readHex = [&]() -> uint16_t {
499 in.error("expected 4 hex digits");
502 uint16_t ret = hexVal(*in) * 4096;
504 ret += hexVal(*in) * 256;
506 ret += hexVal(*in) * 16;
514 * If the value encoded is in the surrogate pair range, we need to
515 * make sure there is another escape that we can use also.
517 uint32_t codePoint = readHex();
518 if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
519 if (!in.consume("\\u")) {
520 in.error("expected another unicode escape for second half of "
523 uint16_t second = readHex();
524 if (second >= 0xdc00 && second <= 0xdfff) {
525 codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
528 in.error("second character in surrogate pair is invalid");
530 } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
531 in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
534 return codePointToUtf8(codePoint);
537 fbstring parseString(Input& in) {
543 auto range = in.skipWhile(
544 [] (char c) { return c != '\"' && c != '\\'; }
546 ret.append(range.begin(), range.end());
555 case '\"': ret.push_back('\"'); ++in; break;
556 case '\\': ret.push_back('\\'); ++in; break;
557 case '/': ret.push_back('/'); ++in; break;
558 case 'b': ret.push_back('\b'); ++in; break;
559 case 'f': ret.push_back('\f'); ++in; break;
560 case 'n': ret.push_back('\n'); ++in; break;
561 case 'r': ret.push_back('\r'); ++in; break;
562 case 't': ret.push_back('\t'); ++in; break;
563 case 'u': ++in; ret += decodeUnicodeEscape(in); break;
564 default: in.error(to<fbstring>("unknown escape ", *in,
565 " in string").c_str());
570 in.error("unterminated string");
574 * Apparently we're actually supposed to ban all control
575 * characters from strings. This seems unnecessarily
576 * restrictive, so we're only banning zero bytes. (Since the
577 * string is presumed to be UTF-8 encoded it's fine to just
580 in.error("null byte in string");
590 dynamic parseValue(Input& in) {
592 return *in == '[' ? parseArray(in) :
593 *in == '{' ? parseObject(in) :
594 *in == '\"' ? parseString(in) :
595 (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
596 in.consume("true") ? true :
597 in.consume("false") ? false :
598 in.consume("null") ? nullptr :
599 in.consume("Infinity") ? std::numeric_limits<double>::infinity() :
600 in.consume("NaN") ? std::numeric_limits<double>::quiet_NaN() :
601 in.error("expected json value");
606 //////////////////////////////////////////////////////////////////////
608 fbstring serialize(dynamic const& dyn, serialization_opts const& opts) {
610 unsigned indentLevel = 0;
611 Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
616 // Escape a string so that it is legal to print it in JSON text.
617 void escapeString(StringPiece input,
619 const serialization_opts& opts) {
620 auto hexDigit = [] (int c) -> char {
621 return c < 10 ? c + '0' : c - 10 + 'a';
624 out.reserve(out.size() + input.size() + 2);
627 auto* p = reinterpret_cast<const unsigned char*>(input.begin());
628 auto* q = reinterpret_cast<const unsigned char*>(input.begin());
629 auto* e = reinterpret_cast<const unsigned char*>(input.end());
632 // Since non-ascii encoding inherently does utf8 validation
633 // we explicitly validate utf8 only if non-ascii encoding is disabled.
634 if (opts.validate_utf8 && !opts.encode_non_ascii) {
635 // to achieve better spatial and temporal coherence
636 // we do utf8 validation progressively along with the
637 // string-escaping instead of two separate passes
639 // as the encoding progresses, q will stay at or ahead of p
642 // as p catches up with q, move q forward
644 // calling utf8_decode has the side effect of
645 // checking that utf8 encodings are valid
649 if (opts.encode_non_ascii && (*p & 0x80)) {
650 // note that this if condition captures utf8 chars
651 // with value > 127, so size > 1 byte
652 char32_t v = decodeUtf8(p, e);
654 out.push_back(hexDigit(v >> 12));
655 out.push_back(hexDigit((v >> 8) & 0x0f));
656 out.push_back(hexDigit((v >> 4) & 0x0f));
657 out.push_back(hexDigit(v & 0x0f));
658 } else if (*p == '\\' || *p == '\"') {
661 } else if (*p <= 0x1f) {
663 case '\b': out.append("\\b"); p++; break;
664 case '\f': out.append("\\f"); p++; break;
665 case '\n': out.append("\\n"); p++; break;
666 case '\r': out.append("\\r"); p++; break;
667 case '\t': out.append("\\t"); p++; break;
669 // note that this if condition captures non readable chars
670 // with value < 32, so size = 1 byte (e.g control chars).
672 out.push_back(hexDigit((*p & 0xf0) >> 4));
673 out.push_back(hexDigit(*p & 0xf));
686 //////////////////////////////////////////////////////////////////////
688 dynamic parseJson(StringPiece range) {
689 return parseJson(range, json::serialization_opts());
694 json::serialization_opts const& opts) {
696 json::Input in(range, &opts);
698 auto ret = parseValue(in);
700 if (in.size() && *in != '\0') {
701 in.error("parsing didn't consume all input");
706 fbstring toJson(dynamic const& dyn) {
707 return json::serialize(dyn, json::serialization_opts());
710 fbstring toPrettyJson(dynamic const& dyn) {
711 json::serialization_opts opts;
712 opts.pretty_formatting = true;
713 return json::serialize(dyn, opts);
716 //////////////////////////////////////////////////////////////////////
717 // dynamic::print_as_pseudo_json() is implemented here for header
718 // ordering reasons (most of the dynamic implementation is in
719 // dynamic-inl.h, which we don't want to include json.h).
721 void dynamic::print_as_pseudo_json(std::ostream& out) const {
722 json::serialization_opts opts;
723 opts.allow_non_string_keys = true;
724 out << json::serialize(*this, opts);
727 //////////////////////////////////////////////////////////////////////