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 toAppend(v.asDouble(), &out_);
131 case dynamic::INT64: {
132 auto intval = v.asInt();
133 if (opts_.javascript_safe) {
134 // Use folly::to to check that this integer can be represented
135 // as a double without loss of precision.
136 intval = int64_t(to<double>(intval));
138 toAppend(intval, &out_);
142 out_ += v.asBool() ? "true" : "false";
147 case dynamic::STRING:
148 escapeString(v.asString(), out_, opts_);
150 case dynamic::OBJECT:
157 CHECK(0) << "Bad type " << v.type();
162 void printKV(const std::pair<const dynamic, dynamic>& p) const {
163 if (!opts_.allow_non_string_keys && !p.first.isString()) {
164 throw std::runtime_error("folly::toJson: JSON object key was not a "
172 template <typename Iterator>
173 void printKVPairs(Iterator begin, Iterator end) const {
175 for (++begin; begin != end; ++begin) {
182 void printObject(dynamic const& o) const {
191 if (opts_.sort_keys) {
192 std::vector<std::pair<dynamic, dynamic>> items(
193 o.items().begin(), o.items().end());
194 std::sort(items.begin(), items.end());
195 printKVPairs(items.begin(), items.end());
197 printKVPairs(o.items().begin(), o.items().end());
204 void printArray(dynamic const& a) const {
214 for (auto& val : makeRange(boost::next(a.begin()), a.end())) {
225 void outdent() const {
231 void indent() const {
237 void newline() const {
239 out_ += to<fbstring>('\n', fbstring(*indentLevel_ * 2, ' '));
243 void mapColon() const {
244 out_ += indentLevel_ ? " : " : ":";
249 unsigned* const indentLevel_;
250 serialization_opts const& opts_;
253 //////////////////////////////////////////////////////////////////////
255 struct ParseError : std::runtime_error {
256 explicit ParseError(int line)
257 : std::runtime_error(to<std::string>("json parse error on line ", line))
260 explicit ParseError(int line, std::string const& context,
261 std::string const& expected)
262 : std::runtime_error(to<std::string>("json parse error on line ", line,
263 !context.empty() ? to<std::string>(" near `", context, '\'')
268 explicit ParseError(std::string const& what)
269 : std::runtime_error("json parse error: " + what)
273 // Wraps our input buffer with some helper functions.
275 explicit Input(StringPiece range, json::serialization_opts const* opts)
283 Input(Input const&) = delete;
284 Input& operator=(Input const&) = delete;
286 char const* begin() const { return range_.begin(); }
288 // Parse ahead for as long as the supplied predicate is satisfied,
289 // returning a range of what was skipped.
290 template<class Predicate>
291 StringPiece skipWhile(const Predicate& p) {
292 std::size_t skipped = 0;
293 for (; skipped < range_.size(); ++skipped) {
294 if (!p(range_[skipped])) {
297 if (range_[skipped] == '\n') {
301 auto ret = range_.subpiece(0, skipped);
302 range_.advance(skipped);
307 StringPiece skipDigits() {
308 return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
311 StringPiece skipMinusAndDigits() {
312 bool firstChar = true;
313 return skipWhile([&firstChar] (char c) {
314 bool result = (c >= '0' && c <= '9') || (firstChar && c == '-');
320 void skipWhitespace() {
321 // Spaces other than ' ' characters are less common but should be
322 // checked. This configuration where we loop on the ' '
323 // separately from oddspaces was empirically fastest.
324 auto oddspace = [] (char c) {
325 return c == '\n' || c == '\t' || c == '\r';
329 for (; !range_.empty() && range_.front() == ' '; range_.pop_front()) {
331 if (!range_.empty() && oddspace(range_.front())) {
338 void expect(char c) {
340 throw ParseError(lineNum_, context(),
341 to<std::string>("expected '", c, '\''));
346 std::size_t size() const {
347 return range_.size();
350 int operator*() const {
362 return to<T>(&range_);
363 } catch (std::exception const& e) {
368 bool consume(StringPiece str) {
369 if (boost::starts_with(range_, str)) {
370 range_.advance(str.size());
377 std::string context() const {
378 return range_.subpiece(0, 16 /* arbitrary */).toString();
381 dynamic error(char const* what) const {
382 throw ParseError(lineNum_, context(), what);
385 json::serialization_opts const& getOpts() {
390 void storeCurrent() {
391 current_ = range_.empty() ? EOF : range_.front();
396 json::serialization_opts const& opts_;
401 dynamic parseValue(Input& in);
402 fbstring parseString(Input& in);
403 dynamic parseNumber(Input& in);
405 dynamic parseObject(Input& in) {
409 dynamic ret = dynamic::object;
418 if (in.getOpts().allow_trailing_comma && *in == '}') {
421 if (*in == '\"') { // string
422 auto key = parseString(in);
426 ret.insert(std::move(key), parseValue(in));
427 } else if (!in.getOpts().allow_non_string_keys) {
428 in.error("expected string for object key name");
430 auto key = parseValue(in);
434 ret.insert(std::move(key), parseValue(in));
449 dynamic parseArray(Input& in) {
462 if (in.getOpts().allow_trailing_comma && *in == ']') {
465 ret.push_back(parseValue(in));
478 dynamic parseNumber(Input& in) {
479 bool const negative = (*in == '-');
481 if (in.consume("-Infinity")) {
482 return -std::numeric_limits<double>::infinity();
486 auto integral = in.skipMinusAndDigits();
487 if (negative && integral.size() < 2) {
488 in.error("expected digits after `-'");
491 auto const wasE = *in == 'e' || *in == 'E';
492 if (*in != '.' && !wasE) {
493 auto val = to<int64_t>(integral);
498 auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
499 if (*in == 'e' || *in == 'E') {
501 if (*in == '+' || *in == '-') {
504 auto expPart = in.skipDigits();
507 auto fullNum = makeRange(integral.begin(), end);
509 auto val = to<double>(fullNum);
513 fbstring decodeUnicodeEscape(Input& in) {
514 auto hexVal = [&] (char c) -> unsigned {
515 return c >= '0' && c <= '9' ? c - '0' :
516 c >= 'a' && c <= 'f' ? c - 'a' + 10 :
517 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
518 (in.error("invalid hex digit"), 0);
521 auto readHex = [&]() -> uint16_t {
523 in.error("expected 4 hex digits");
526 uint16_t ret = hexVal(*in) * 4096;
528 ret += hexVal(*in) * 256;
530 ret += hexVal(*in) * 16;
538 * If the value encoded is in the surrogate pair range, we need to
539 * make sure there is another escape that we can use also.
541 uint32_t codePoint = readHex();
542 if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
543 if (!in.consume("\\u")) {
544 in.error("expected another unicode escape for second half of "
547 uint16_t second = readHex();
548 if (second >= 0xdc00 && second <= 0xdfff) {
549 codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
552 in.error("second character in surrogate pair is invalid");
554 } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
555 in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
558 return codePointToUtf8(codePoint);
561 fbstring parseString(Input& in) {
567 auto range = in.skipWhile(
568 [] (char c) { return c != '\"' && c != '\\'; }
570 ret.append(range.begin(), range.end());
579 case '\"': ret.push_back('\"'); ++in; break;
580 case '\\': ret.push_back('\\'); ++in; break;
581 case '/': ret.push_back('/'); ++in; break;
582 case 'b': ret.push_back('\b'); ++in; break;
583 case 'f': ret.push_back('\f'); ++in; break;
584 case 'n': ret.push_back('\n'); ++in; break;
585 case 'r': ret.push_back('\r'); ++in; break;
586 case 't': ret.push_back('\t'); ++in; break;
587 case 'u': ++in; ret += decodeUnicodeEscape(in); break;
588 default: in.error(to<fbstring>("unknown escape ", *in,
589 " in string").c_str());
594 in.error("unterminated string");
598 * Apparently we're actually supposed to ban all control
599 * characters from strings. This seems unnecessarily
600 * restrictive, so we're only banning zero bytes. (Since the
601 * string is presumed to be UTF-8 encoded it's fine to just
604 in.error("null byte in string");
614 dynamic parseValue(Input& in) {
616 return *in == '[' ? parseArray(in) :
617 *in == '{' ? parseObject(in) :
618 *in == '\"' ? parseString(in) :
619 (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
620 in.consume("true") ? true :
621 in.consume("false") ? false :
622 in.consume("null") ? nullptr :
623 in.consume("Infinity") ? std::numeric_limits<double>::infinity() :
624 in.consume("NaN") ? std::numeric_limits<double>::quiet_NaN() :
625 in.error("expected json value");
630 //////////////////////////////////////////////////////////////////////
632 fbstring serialize(dynamic const& dyn, serialization_opts const& opts) {
634 unsigned indentLevel = 0;
635 Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
640 // Escape a string so that it is legal to print it in JSON text.
641 void escapeString(StringPiece input,
643 const serialization_opts& opts) {
644 auto hexDigit = [] (int c) -> char {
645 return c < 10 ? c + '0' : c - 10 + 'a';
648 out.reserve(out.size() + input.size() + 2);
651 auto* p = reinterpret_cast<const unsigned char*>(input.begin());
652 auto* q = reinterpret_cast<const unsigned char*>(input.begin());
653 auto* e = reinterpret_cast<const unsigned char*>(input.end());
656 // Since non-ascii encoding inherently does utf8 validation
657 // we explicitly validate utf8 only if non-ascii encoding is disabled.
658 if ((opts.validate_utf8 || opts.skip_invalid_utf8)
659 && !opts.encode_non_ascii) {
660 // to achieve better spatial and temporal coherence
661 // we do utf8 validation progressively along with the
662 // string-escaping instead of two separate passes
664 // as the encoding progresses, q will stay at or ahead of p
667 // as p catches up with q, move q forward
669 // calling utf8_decode has the side effect of
670 // checking that utf8 encodings are valid
671 char32_t v = decodeUtf8(q, e, opts.skip_invalid_utf8);
672 if (opts.skip_invalid_utf8 && v == U'\ufffd') {
673 out.append("\ufffd");
679 if (opts.encode_non_ascii && (*p & 0x80)) {
680 // note that this if condition captures utf8 chars
681 // with value > 127, so size > 1 byte
682 char32_t v = decodeUtf8(p, e, opts.skip_invalid_utf8);
684 out.push_back(hexDigit(v >> 12));
685 out.push_back(hexDigit((v >> 8) & 0x0f));
686 out.push_back(hexDigit((v >> 4) & 0x0f));
687 out.push_back(hexDigit(v & 0x0f));
688 } else if (*p == '\\' || *p == '\"') {
691 } else if (*p <= 0x1f) {
693 case '\b': out.append("\\b"); p++; break;
694 case '\f': out.append("\\f"); p++; break;
695 case '\n': out.append("\\n"); p++; break;
696 case '\r': out.append("\\r"); p++; break;
697 case '\t': out.append("\\t"); p++; break;
699 // note that this if condition captures non readable chars
700 // with value < 32, so size = 1 byte (e.g control chars).
702 out.push_back(hexDigit((*p & 0xf0) >> 4));
703 out.push_back(hexDigit(*p & 0xf));
716 //////////////////////////////////////////////////////////////////////
718 dynamic parseJson(StringPiece range) {
719 return parseJson(range, json::serialization_opts());
724 json::serialization_opts const& opts) {
726 json::Input in(range, &opts);
728 auto ret = parseValue(in);
730 if (in.size() && *in != '\0') {
731 in.error("parsing didn't consume all input");
736 fbstring toJson(dynamic const& dyn) {
737 return json::serialize(dyn, json::serialization_opts());
740 fbstring toPrettyJson(dynamic const& dyn) {
741 json::serialization_opts opts;
742 opts.pretty_formatting = true;
743 return json::serialize(dyn, opts);
746 //////////////////////////////////////////////////////////////////////
747 // dynamic::print_as_pseudo_json() is implemented here for header
748 // ordering reasons (most of the dynamic implementation is in
749 // dynamic-inl.h, which we don't want to include json.h).
751 void dynamic::print_as_pseudo_json(std::ostream& out) const {
752 json::serialization_opts opts;
753 opts.allow_non_string_keys = true;
754 out << json::serialize(*this, opts);
757 //////////////////////////////////////////////////////////////////////