48ef486ebc87d3f17195f6d15c77d95726371121
[folly.git] / folly / json.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <folly/json.h>
18
19 #include <algorithm>
20 #include <cassert>
21 #include <functional>
22
23 #include <boost/next_prior.hpp>
24 #include <boost/algorithm/string.hpp>
25
26 #include <folly/Conv.h>
27 #include <folly/Range.h>
28 #include <folly/String.h>
29 #include <folly/Unicode.h>
30 #include <folly/portability/Constexpr.h>
31
32 namespace folly {
33
34 //////////////////////////////////////////////////////////////////////
35
36 namespace json {
37 namespace {
38
39 struct Printer {
40   explicit Printer(
41       std::string& out,
42       unsigned* indentLevel,
43       serialization_opts const* opts)
44       : out_(out), indentLevel_(indentLevel), opts_(*opts) {}
45
46   void operator()(dynamic const& v) const {
47     switch (v.type()) {
48     case dynamic::DOUBLE:
49       if (!opts_.allow_nan_inf &&
50           (std::isnan(v.asDouble()) || std::isinf(v.asDouble()))) {
51         throw std::runtime_error("folly::toJson: JSON object value was a "
52           "NaN or INF");
53       }
54       toAppend(v.asDouble(), &out_, opts_.double_mode, opts_.double_num_digits);
55       break;
56     case dynamic::INT64: {
57       auto intval = v.asInt();
58       if (opts_.javascript_safe) {
59         // Use folly::to to check that this integer can be represented
60         // as a double without loss of precision.
61         intval = int64_t(to<double>(intval));
62       }
63       toAppend(intval, &out_);
64       break;
65     }
66     case dynamic::BOOL:
67       out_ += v.asBool() ? "true" : "false";
68       break;
69     case dynamic::NULLT:
70       out_ += "null";
71       break;
72     case dynamic::STRING:
73       escapeString(v.asString(), out_, opts_);
74       break;
75     case dynamic::OBJECT:
76       printObject(v);
77       break;
78     case dynamic::ARRAY:
79       printArray(v);
80       break;
81     default:
82       CHECK(0) << "Bad type " << v.type();
83     }
84   }
85
86 private:
87   void printKV(const std::pair<const dynamic, dynamic>& p) const {
88     if (!opts_.allow_non_string_keys && !p.first.isString()) {
89       throw std::runtime_error("folly::toJson: JSON object key was not a "
90         "string");
91     }
92     (*this)(p.first);
93     mapColon();
94     (*this)(p.second);
95   }
96
97   template <typename Iterator>
98   void printKVPairs(Iterator begin, Iterator end) const {
99     printKV(*begin);
100     for (++begin; begin != end; ++begin) {
101       out_ += ',';
102       newline();
103       printKV(*begin);
104     }
105   }
106
107   void printObject(dynamic const& o) const {
108     if (o.empty()) {
109       out_ += "{}";
110       return;
111     }
112
113     out_ += '{';
114     indent();
115     newline();
116     if (opts_.sort_keys) {
117       using ref = std::reference_wrapper<decltype(o.items())::value_type const>;
118       std::vector<ref> refs(o.items().begin(), o.items().end());
119       std::sort(refs.begin(), refs.end(), [](ref a, ref b) {
120         // Only compare keys.  No ordering among identical keys.
121         return a.get().first < b.get().first;
122       });
123       printKVPairs(refs.cbegin(), refs.cend());
124     } else {
125       printKVPairs(o.items().begin(), o.items().end());
126     }
127     outdent();
128     newline();
129     out_ += '}';
130   }
131
132   void printArray(dynamic const& a) const {
133     if (a.empty()) {
134       out_ += "[]";
135       return;
136     }
137
138     out_ += '[';
139     indent();
140     newline();
141     (*this)(a[0]);
142     for (auto& val : range(boost::next(a.begin()), a.end())) {
143       out_ += ',';
144       newline();
145       (*this)(val);
146     }
147     outdent();
148     newline();
149     out_ += ']';
150   }
151
152 private:
153   void outdent() const {
154     if (indentLevel_) {
155       --*indentLevel_;
156     }
157   }
158
159   void indent() const {
160     if (indentLevel_) {
161       ++*indentLevel_;
162     }
163   }
164
165   void newline() const {
166     if (indentLevel_) {
167       out_ += to<std::string>('\n', std::string(*indentLevel_ * 2, ' '));
168     }
169   }
170
171   void mapColon() const {
172     out_ += indentLevel_ ? " : " : ":";
173   }
174
175 private:
176  std::string& out_;
177  unsigned* const indentLevel_;
178  serialization_opts const& opts_;
179 };
180
181 //////////////////////////////////////////////////////////////////////
182
183 struct ParseError : std::runtime_error {
184   explicit ParseError(
185       unsigned int line,
186       std::string const& context,
187       std::string const& expected)
188       : std::runtime_error(to<std::string>(
189             "json parse error on line ",
190             line,
191             !context.empty() ? to<std::string>(" near `", context, '\'') : "",
192             ": ",
193             expected)) {}
194 };
195
196 // Wraps our input buffer with some helper functions.
197 struct Input {
198   explicit Input(StringPiece range, json::serialization_opts const* opts)
199       : range_(range)
200       , opts_(*opts)
201       , lineNum_(0)
202   {
203     storeCurrent();
204   }
205
206   Input(Input const&) = delete;
207   Input& operator=(Input const&) = delete;
208
209   char const* begin() const { return range_.begin(); }
210
211   // Parse ahead for as long as the supplied predicate is satisfied,
212   // returning a range of what was skipped.
213   template<class Predicate>
214   StringPiece skipWhile(const Predicate& p) {
215     std::size_t skipped = 0;
216     for (; skipped < range_.size(); ++skipped) {
217       if (!p(range_[skipped])) {
218         break;
219       }
220       if (range_[skipped] == '\n') {
221         ++lineNum_;
222       }
223     }
224     auto ret = range_.subpiece(0, skipped);
225     range_.advance(skipped);
226     storeCurrent();
227     return ret;
228   }
229
230   StringPiece skipDigits() {
231     return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
232   }
233
234   StringPiece skipMinusAndDigits() {
235     bool firstChar = true;
236     return skipWhile([&firstChar] (char c) {
237         bool result = (c >= '0' && c <= '9') || (firstChar && c == '-');
238         firstChar = false;
239         return result;
240       });
241   }
242
243   void skipWhitespace() {
244     range_ = folly::skipWhitespace(range_);
245     storeCurrent();
246   }
247
248   void expect(char c) {
249     if (**this != c) {
250       throw ParseError(lineNum_, context(),
251         to<std::string>("expected '", c, '\''));
252     }
253     ++*this;
254   }
255
256   std::size_t size() const {
257     return range_.size();
258   }
259
260   int operator*() const {
261     return current_;
262   }
263
264   void operator++() {
265     range_.pop_front();
266     storeCurrent();
267   }
268
269   template<class T>
270   T extract() {
271     try {
272       return to<T>(&range_);
273     } catch (std::exception const& e) {
274       error(e.what());
275     }
276   }
277
278   bool consume(StringPiece str) {
279     if (boost::starts_with(range_, str)) {
280       range_.advance(str.size());
281       storeCurrent();
282       return true;
283     }
284     return false;
285   }
286
287   std::string context() const {
288     return range_.subpiece(0, 16 /* arbitrary */).toString();
289   }
290
291   dynamic error(char const* what) const {
292     throw ParseError(lineNum_, context(), what);
293   }
294
295   json::serialization_opts const& getOpts() {
296     return opts_;
297   }
298
299   void incrementRecursionLevel() {
300     if (currentRecursionLevel_ > opts_.recursion_limit) {
301       error("recursion limit exceeded");
302     }
303     currentRecursionLevel_++;
304   }
305
306   void decrementRecursionLevel() {
307     currentRecursionLevel_--;
308   }
309
310  private:
311   void storeCurrent() {
312     current_ = range_.empty() ? EOF : range_.front();
313   }
314
315 private:
316   StringPiece range_;
317   json::serialization_opts const& opts_;
318   unsigned lineNum_;
319   int current_;
320   unsigned int currentRecursionLevel_{0};
321 };
322
323 class RecursionGuard {
324  public:
325   explicit RecursionGuard(Input& in) : in_(in) {
326     in_.incrementRecursionLevel();
327   }
328
329   ~RecursionGuard() {
330     in_.decrementRecursionLevel();
331   }
332
333  private:
334   Input& in_;
335 };
336
337 dynamic parseValue(Input& in);
338 std::string parseString(Input& in);
339 dynamic parseNumber(Input& in);
340
341 dynamic parseObject(Input& in) {
342   assert(*in == '{');
343   ++in;
344
345   dynamic ret = dynamic::object;
346
347   in.skipWhitespace();
348   if (*in == '}') {
349     ++in;
350     return ret;
351   }
352
353   for (;;) {
354     if (in.getOpts().allow_trailing_comma && *in == '}') {
355       break;
356     }
357     if (*in == '\"') { // string
358       auto key = parseString(in);
359       in.skipWhitespace();
360       in.expect(':');
361       in.skipWhitespace();
362       ret.insert(std::move(key), parseValue(in));
363     } else if (!in.getOpts().allow_non_string_keys) {
364       in.error("expected string for object key name");
365     } else {
366       auto key = parseValue(in);
367       in.skipWhitespace();
368       in.expect(':');
369       in.skipWhitespace();
370       ret.insert(std::move(key), parseValue(in));
371     }
372
373     in.skipWhitespace();
374     if (*in != ',') {
375       break;
376     }
377     ++in;
378     in.skipWhitespace();
379   }
380   in.expect('}');
381
382   return ret;
383 }
384
385 dynamic parseArray(Input& in) {
386   assert(*in == '[');
387   ++in;
388
389   dynamic ret = dynamic::array;
390
391   in.skipWhitespace();
392   if (*in == ']') {
393     ++in;
394     return ret;
395   }
396
397   for (;;) {
398     if (in.getOpts().allow_trailing_comma && *in == ']') {
399       break;
400     }
401     ret.push_back(parseValue(in));
402     in.skipWhitespace();
403     if (*in != ',') {
404       break;
405     }
406     ++in;
407     in.skipWhitespace();
408   }
409   in.expect(']');
410
411   return ret;
412 }
413
414 dynamic parseNumber(Input& in) {
415   bool const negative = (*in == '-');
416   if (negative && in.consume("-Infinity")) {
417     if (in.getOpts().parse_numbers_as_strings) {
418       return "-Infinity";
419     } else {
420       return -std::numeric_limits<double>::infinity();
421     }
422   }
423
424   auto integral = in.skipMinusAndDigits();
425   if (negative && integral.size() < 2) {
426     in.error("expected digits after `-'");
427   }
428
429   auto const wasE = *in == 'e' || *in == 'E';
430
431   constexpr const char* maxInt = "9223372036854775807";
432   constexpr const char* minInt = "-9223372036854775808";
433   constexpr auto maxIntLen = constexpr_strlen(maxInt);
434   constexpr auto minIntLen = constexpr_strlen(minInt);
435
436   if (*in != '.' && !wasE && in.getOpts().parse_numbers_as_strings) {
437     return integral;
438   }
439
440   if (*in != '.' && !wasE) {
441     if (LIKELY(!in.getOpts().double_fallback || integral.size() < maxIntLen) ||
442         (!negative && integral.size() == maxIntLen && integral <= maxInt) ||
443         (negative && integral.size() == minIntLen && integral <= minInt)) {
444       auto val = to<int64_t>(integral);
445       in.skipWhitespace();
446       return val;
447     } else {
448       auto val = to<double>(integral);
449       in.skipWhitespace();
450       return val;
451     }
452   }
453
454   auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
455   if (*in == 'e' || *in == 'E') {
456     ++in;
457     if (*in == '+' || *in == '-') {
458       ++in;
459     }
460     auto expPart = in.skipDigits();
461     end = expPart.end();
462   }
463   auto fullNum = range(integral.begin(), end);
464   if (in.getOpts().parse_numbers_as_strings) {
465     return fullNum;
466   }
467   auto val = to<double>(fullNum);
468   return val;
469 }
470
471 std::string decodeUnicodeEscape(Input& in) {
472   auto hexVal = [&] (int c) -> uint16_t {
473     return uint16_t(
474            c >= '0' && c <= '9' ? c - '0' :
475            c >= 'a' && c <= 'f' ? c - 'a' + 10 :
476            c >= 'A' && c <= 'F' ? c - 'A' + 10 :
477            (in.error("invalid hex digit"), 0));
478   };
479
480   auto readHex = [&]() -> uint16_t {
481     if (in.size() < 4) {
482       in.error("expected 4 hex digits");
483     }
484
485     uint16_t ret = uint16_t(hexVal(*in) * 4096);
486     ++in;
487     ret += hexVal(*in) * 256;
488     ++in;
489     ret += hexVal(*in) * 16;
490     ++in;
491     ret += hexVal(*in);
492     ++in;
493     return ret;
494   };
495
496   /*
497    * If the value encoded is in the surrogate pair range, we need to
498    * make sure there is another escape that we can use also.
499    */
500   uint32_t codePoint = readHex();
501   if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
502     if (!in.consume("\\u")) {
503       in.error("expected another unicode escape for second half of "
504         "surrogate pair");
505     }
506     uint16_t second = readHex();
507     if (second >= 0xdc00 && second <= 0xdfff) {
508       codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
509                   (second & 0x3ff);
510     } else {
511       in.error("second character in surrogate pair is invalid");
512     }
513   } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
514     in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
515   }
516
517   return codePointToUtf8(codePoint);
518 }
519
520 std::string parseString(Input& in) {
521   assert(*in == '\"');
522   ++in;
523
524   std::string ret;
525   for (;;) {
526     auto range = in.skipWhile(
527       [] (char c) { return c != '\"' && c != '\\'; }
528     );
529     ret.append(range.begin(), range.end());
530
531     if (*in == '\"') {
532       ++in;
533       break;
534     }
535     if (*in == '\\') {
536       ++in;
537       switch (*in) {
538       case '\"':    ret.push_back('\"'); ++in; break;
539       case '\\':    ret.push_back('\\'); ++in; break;
540       case '/':     ret.push_back('/');  ++in; break;
541       case 'b':     ret.push_back('\b'); ++in; break;
542       case 'f':     ret.push_back('\f'); ++in; break;
543       case 'n':     ret.push_back('\n'); ++in; break;
544       case 'r':     ret.push_back('\r'); ++in; break;
545       case 't':     ret.push_back('\t'); ++in; break;
546       case 'u':     ++in; ret += decodeUnicodeEscape(in); break;
547       default:
548         in.error(to<std::string>("unknown escape ", *in, " in string").c_str());
549       }
550       continue;
551     }
552     if (*in == EOF) {
553       in.error("unterminated string");
554     }
555     if (!*in) {
556       /*
557        * Apparently we're actually supposed to ban all control
558        * characters from strings.  This seems unnecessarily
559        * restrictive, so we're only banning zero bytes.  (Since the
560        * string is presumed to be UTF-8 encoded it's fine to just
561        * check this way.)
562        */
563       in.error("null byte in string");
564     }
565
566     ret.push_back(char(*in));
567     ++in;
568   }
569
570   return ret;
571 }
572
573 dynamic parseValue(Input& in) {
574   RecursionGuard guard(in);
575
576   in.skipWhitespace();
577   return *in == '[' ? parseArray(in) :
578          *in == '{' ? parseObject(in) :
579          *in == '\"' ? parseString(in) :
580          (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
581          in.consume("true") ? true :
582          in.consume("false") ? false :
583          in.consume("null") ? nullptr :
584          in.consume("Infinity") ?
585           (in.getOpts().parse_numbers_as_strings ? (dynamic)"Infinity" :
586             (dynamic)std::numeric_limits<double>::infinity()) :
587          in.consume("NaN") ?
588            (in.getOpts().parse_numbers_as_strings ? (dynamic)"NaN" :
589              (dynamic)std::numeric_limits<double>::quiet_NaN()) :
590          in.error("expected json value");
591 }
592
593 }
594
595 //////////////////////////////////////////////////////////////////////
596
597 std::string serialize(dynamic const& dyn, serialization_opts const& opts) {
598   std::string ret;
599   unsigned indentLevel = 0;
600   Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
601   p(dyn);
602   return ret;
603 }
604
605 // Escape a string so that it is legal to print it in JSON text.
606 void escapeString(
607     StringPiece input,
608     std::string& out,
609     const serialization_opts& opts) {
610   auto hexDigit = [] (uint8_t c) -> char {
611     return c < 10 ? c + '0' : c - 10 + 'a';
612   };
613
614   out.push_back('\"');
615
616   auto* p = reinterpret_cast<const unsigned char*>(input.begin());
617   auto* q = reinterpret_cast<const unsigned char*>(input.begin());
618   auto* e = reinterpret_cast<const unsigned char*>(input.end());
619
620   while (p < e) {
621     // Since non-ascii encoding inherently does utf8 validation
622     // we explicitly validate utf8 only if non-ascii encoding is disabled.
623     if ((opts.validate_utf8 || opts.skip_invalid_utf8)
624         && !opts.encode_non_ascii) {
625       // to achieve better spatial and temporal coherence
626       // we do utf8 validation progressively along with the
627       // string-escaping instead of two separate passes
628
629       // as the encoding progresses, q will stay at or ahead of p
630       CHECK(q >= p);
631
632       // as p catches up with q, move q forward
633       if (q == p) {
634         // calling utf8_decode has the side effect of
635         // checking that utf8 encodings are valid
636         char32_t v = utf8ToCodePoint(q, e, opts.skip_invalid_utf8);
637         if (opts.skip_invalid_utf8 && v == U'\ufffd') {
638           out.append(u8"\ufffd");
639           p = q;
640           continue;
641         }
642       }
643     }
644     if (opts.encode_non_ascii && (*p & 0x80)) {
645       // note that this if condition captures utf8 chars
646       // with value > 127, so size > 1 byte
647       char32_t v = utf8ToCodePoint(p, e, opts.skip_invalid_utf8);
648       out.append("\\u");
649       out.push_back(hexDigit(uint8_t(v >> 12)));
650       out.push_back(hexDigit((v >> 8) & 0x0f));
651       out.push_back(hexDigit((v >> 4) & 0x0f));
652       out.push_back(hexDigit(v & 0x0f));
653     } else if (*p == '\\' || *p == '\"') {
654       out.push_back('\\');
655       out.push_back(char(*p++));
656     } else if (*p <= 0x1f) {
657       switch (*p) {
658         case '\b': out.append("\\b"); p++; break;
659         case '\f': out.append("\\f"); p++; break;
660         case '\n': out.append("\\n"); p++; break;
661         case '\r': out.append("\\r"); p++; break;
662         case '\t': out.append("\\t"); p++; break;
663         default:
664           // note that this if condition captures non readable chars
665           // with value < 32, so size = 1 byte (e.g control chars).
666           out.append("\\u00");
667           out.push_back(hexDigit(uint8_t((*p & 0xf0) >> 4)));
668           out.push_back(hexDigit(uint8_t(*p & 0xf)));
669           p++;
670       }
671     } else {
672       out.push_back(char(*p++));
673     }
674   }
675
676   out.push_back('\"');
677 }
678
679 std::string stripComments(StringPiece jsonC) {
680   std::string result;
681   enum class State {
682     None,
683     InString,
684     InlineComment,
685     LineComment
686   } state = State::None;
687
688   for (size_t i = 0; i < jsonC.size(); ++i) {
689     auto s = jsonC.subpiece(i);
690     switch (state) {
691       case State::None:
692         if (s.startsWith("/*")) {
693           state = State::InlineComment;
694           ++i;
695           continue;
696         } else if (s.startsWith("//")) {
697           state = State::LineComment;
698           ++i;
699           continue;
700         } else if (s[0] == '\"') {
701           state = State::InString;
702         }
703         result.push_back(s[0]);
704         break;
705       case State::InString:
706         if (s[0] == '\\') {
707           if (UNLIKELY(s.size() == 1)) {
708             throw std::logic_error("Invalid JSONC: string is not terminated");
709           }
710           result.push_back(s[0]);
711           result.push_back(s[1]);
712           ++i;
713           continue;
714         } else if (s[0] == '\"') {
715           state = State::None;
716         }
717         result.push_back(s[0]);
718         break;
719       case State::InlineComment:
720         if (s.startsWith("*/")) {
721           state = State::None;
722           ++i;
723         }
724         break;
725       case State::LineComment:
726         if (s[0] == '\n') {
727           // skip the line break. It doesn't matter.
728           state = State::None;
729         }
730         break;
731       default:
732         throw std::logic_error("Unknown comment state");
733     }
734   }
735   return result;
736 }
737
738 }
739
740 //////////////////////////////////////////////////////////////////////
741
742 dynamic parseJson(StringPiece range) {
743   return parseJson(range, json::serialization_opts());
744 }
745
746 dynamic parseJson(
747     StringPiece range,
748     json::serialization_opts const& opts) {
749
750   json::Input in(range, &opts);
751
752   auto ret = parseValue(in);
753   in.skipWhitespace();
754   if (in.size() && *in != '\0') {
755     in.error("parsing didn't consume all input");
756   }
757   return ret;
758 }
759
760 std::string toJson(dynamic const& dyn) {
761   return json::serialize(dyn, json::serialization_opts());
762 }
763
764 std::string toPrettyJson(dynamic const& dyn) {
765   json::serialization_opts opts;
766   opts.pretty_formatting = true;
767   return json::serialize(dyn, opts);
768 }
769
770 //////////////////////////////////////////////////////////////////////
771 // dynamic::print_as_pseudo_json() is implemented here for header
772 // ordering reasons (most of the dynamic implementation is in
773 // dynamic-inl.h, which we don't want to include json.h).
774
775 void dynamic::print_as_pseudo_json(std::ostream& out) const {
776   json::serialization_opts opts;
777   opts.allow_non_string_keys = true;
778   opts.allow_nan_inf = true;
779   out << json::serialize(*this, opts);
780 }
781
782 void PrintTo(const dynamic& dyn, std::ostream* os) {
783   json::serialization_opts opts;
784   opts.allow_nan_inf = true;
785   opts.allow_non_string_keys = true;
786   opts.pretty_formatting = true;
787   opts.sort_keys = true;
788   *os << json::serialize(dyn, opts);
789 }
790
791 //////////////////////////////////////////////////////////////////////
792
793 }