Codemod: use #include angle brackets in folly and thrift
[folly.git] / folly / json.cpp
1 /*
2  * Copyright 2014 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 #include <cassert>
19 #include <boost/next_prior.hpp>
20 #include <boost/algorithm/string.hpp>
21
22 #include <folly/Range.h>
23 #include <folly/Unicode.h>
24 #include <folly/Conv.h>
25
26 namespace folly {
27
28 //////////////////////////////////////////////////////////////////////
29
30 namespace json {
31 namespace {
32
33 char32_t decodeUtf8(
34     const unsigned char*& p,
35     const unsigned char* const e,
36     bool skipOnError) {
37   /* The following encodings are valid, except for the 5 and 6 byte
38    * combinations:
39    * 0xxxxxxx
40    * 110xxxxx 10xxxxxx
41    * 1110xxxx 10xxxxxx 10xxxxxx
42    * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
43    * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
44    * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
45    */
46
47   auto skip = [&] { ++p; return U'\ufffd'; };
48
49   if (p >= e) {
50     if (skipOnError) return skip();
51     throw std::runtime_error("folly::decodeUtf8 empty/invalid string");
52   }
53
54   unsigned char fst = *p;
55   if (!(fst & 0x80)) {
56     // trivial case
57     return *p++;
58   }
59
60   static const uint32_t bitMask[] = {
61     (1 << 7) - 1,
62     (1 << 11) - 1,
63     (1 << 16) - 1,
64     (1 << 21) - 1
65   };
66
67   // upper control bits are masked out later
68   uint32_t d = fst;
69
70   if ((fst & 0xC0) != 0xC0) {
71     if (skipOnError) return skip();
72     throw std::runtime_error(to<std::string>("folly::decodeUtf8 i=0 d=", d));
73   }
74
75   fst <<= 1;
76
77   for (unsigned int i = 1; i != 3 && p + i < e; ++i) {
78     unsigned char tmp = p[i];
79
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));
84     }
85
86     d = (d << 6) | (tmp & 0x3F);
87     fst <<= 1;
88
89     if (!(fst & 0x80)) {
90       d &= bitMask[i];
91
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));
97       }
98
99       // check for surrogates only needed for 3 bytes
100       if (i == 2) {
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));
105         }
106       }
107
108       p += i + 1;
109       return d;
110     }
111   }
112
113   if (skipOnError) return skip();
114   throw std::runtime_error("folly::decodeUtf8 encoding length maxed out");
115 }
116
117 struct Printer {
118   explicit Printer(fbstring& out,
119                    unsigned* indentLevel,
120                    serialization_opts const* opts)
121     : out_(out)
122     , indentLevel_(indentLevel)
123     , opts_(*opts)
124   {}
125
126   void operator()(dynamic const& v) const {
127     switch (v.type()) {
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 "
132           "NaN or INF");
133       }
134       toAppend(v.asDouble(), &out_, opts_.double_mode, opts_.double_num_digits);
135       break;
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));
142       }
143       toAppend(intval, &out_);
144       break;
145     }
146     case dynamic::BOOL:
147       out_ += v.asBool() ? "true" : "false";
148       break;
149     case dynamic::NULLT:
150       out_ += "null";
151       break;
152     case dynamic::STRING:
153       escapeString(v.asString(), out_, opts_);
154       break;
155     case dynamic::OBJECT:
156       printObject(v);
157       break;
158     case dynamic::ARRAY:
159       printArray(v);
160       break;
161     default:
162       CHECK(0) << "Bad type " << v.type();
163     }
164   }
165
166 private:
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 "
170         "string");
171     }
172     (*this)(p.first);
173     mapColon();
174     (*this)(p.second);
175   }
176
177   template <typename Iterator>
178   void printKVPairs(Iterator begin, Iterator end) const {
179     printKV(*begin);
180     for (++begin; begin != end; ++begin) {
181       out_ += ',';
182       newline();
183       printKV(*begin);
184     }
185   }
186
187   void printObject(dynamic const& o) const {
188     if (o.empty()) {
189       out_ += "{}";
190       return;
191     }
192
193     out_ += '{';
194     indent();
195     newline();
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());
201     } else {
202       printKVPairs(o.items().begin(), o.items().end());
203     }
204     outdent();
205     newline();
206     out_ += '}';
207   }
208
209   void printArray(dynamic const& a) const {
210     if (a.empty()) {
211       out_ += "[]";
212       return;
213     }
214
215     out_ += '[';
216     indent();
217     newline();
218     (*this)(a[0]);
219     for (auto& val : range(boost::next(a.begin()), a.end())) {
220       out_ += ',';
221       newline();
222       (*this)(val);
223     }
224     outdent();
225     newline();
226     out_ += ']';
227   }
228
229 private:
230   void outdent() const {
231     if (indentLevel_) {
232       --*indentLevel_;
233     }
234   }
235
236   void indent() const {
237     if (indentLevel_) {
238       ++*indentLevel_;
239     }
240   }
241
242   void newline() const {
243     if (indentLevel_) {
244       out_ += to<fbstring>('\n', fbstring(*indentLevel_ * 2, ' '));
245     }
246   }
247
248   void mapColon() const {
249     out_ += indentLevel_ ? " : " : ":";
250   }
251
252 private:
253   fbstring& out_;
254   unsigned* const indentLevel_;
255   serialization_opts const& opts_;
256 };
257
258 //////////////////////////////////////////////////////////////////////
259
260 struct ParseError : std::runtime_error {
261   explicit ParseError(int line)
262     : std::runtime_error(to<std::string>("json parse error on line ", line))
263   {}
264
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, '\'')
269                         : "",
270         ": ", expected))
271   {}
272
273   explicit ParseError(std::string const& what)
274     : std::runtime_error("json parse error: " + what)
275   {}
276 };
277
278 // Wraps our input buffer with some helper functions.
279 struct Input {
280   explicit Input(StringPiece range, json::serialization_opts const* opts)
281       : range_(range)
282       , opts_(*opts)
283       , lineNum_(0)
284   {
285     storeCurrent();
286   }
287
288   Input(Input const&) = delete;
289   Input& operator=(Input const&) = delete;
290
291   char const* begin() const { return range_.begin(); }
292
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])) {
300         break;
301       }
302       if (range_[skipped] == '\n') {
303         ++lineNum_;
304       }
305     }
306     auto ret = range_.subpiece(0, skipped);
307     range_.advance(skipped);
308     storeCurrent();
309     return ret;
310   }
311
312   StringPiece skipDigits() {
313     return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
314   }
315
316   StringPiece skipMinusAndDigits() {
317     bool firstChar = true;
318     return skipWhile([&firstChar] (char c) {
319         bool result = (c >= '0' && c <= '9') || (firstChar && c == '-');
320         firstChar = false;
321         return result;
322       });
323   }
324
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';
331     };
332
333   loop:
334     for (; !range_.empty() && range_.front() == ' '; range_.pop_front()) {
335     }
336     if (!range_.empty() && oddspace(range_.front())) {
337       range_.pop_front();
338       goto loop;
339     }
340     storeCurrent();
341   }
342
343   void expect(char c) {
344     if (**this != c) {
345       throw ParseError(lineNum_, context(),
346         to<std::string>("expected '", c, '\''));
347     }
348     ++*this;
349   }
350
351   std::size_t size() const {
352     return range_.size();
353   }
354
355   int operator*() const {
356     return current_;
357   }
358
359   void operator++() {
360     range_.pop_front();
361     storeCurrent();
362   }
363
364   template<class T>
365   T extract() {
366     try {
367       return to<T>(&range_);
368     } catch (std::exception const& e) {
369       error(e.what());
370     }
371   }
372
373   bool consume(StringPiece str) {
374     if (boost::starts_with(range_, str)) {
375       range_.advance(str.size());
376       storeCurrent();
377       return true;
378     }
379     return false;
380   }
381
382   std::string context() const {
383     return range_.subpiece(0, 16 /* arbitrary */).toString();
384   }
385
386   dynamic error(char const* what) const {
387     throw ParseError(lineNum_, context(), what);
388   }
389
390   json::serialization_opts const& getOpts() {
391     return opts_;
392   }
393
394 private:
395   void storeCurrent() {
396     current_ = range_.empty() ? EOF : range_.front();
397   }
398
399 private:
400   StringPiece range_;
401   json::serialization_opts const& opts_;
402   unsigned lineNum_;
403   int current_;
404 };
405
406 dynamic parseValue(Input& in);
407 fbstring parseString(Input& in);
408 dynamic parseNumber(Input& in);
409
410 dynamic parseObject(Input& in) {
411   assert(*in == '{');
412   ++in;
413
414   dynamic ret = dynamic::object;
415
416   in.skipWhitespace();
417   if (*in == '}') {
418     ++in;
419     return ret;
420   }
421
422   for (;;) {
423     if (in.getOpts().allow_trailing_comma && *in == '}') {
424       break;
425     }
426     if (*in == '\"') { // string
427       auto key = parseString(in);
428       in.skipWhitespace();
429       in.expect(':');
430       in.skipWhitespace();
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");
434     } else {
435       auto key = parseValue(in);
436       in.skipWhitespace();
437       in.expect(':');
438       in.skipWhitespace();
439       ret.insert(std::move(key), parseValue(in));
440     }
441
442     in.skipWhitespace();
443     if (*in != ',') {
444       break;
445     }
446     ++in;
447     in.skipWhitespace();
448   }
449   in.expect('}');
450
451   return ret;
452 }
453
454 dynamic parseArray(Input& in) {
455   assert(*in == '[');
456   ++in;
457
458   dynamic ret = {};
459
460   in.skipWhitespace();
461   if (*in == ']') {
462     ++in;
463     return ret;
464   }
465
466   for (;;) {
467     if (in.getOpts().allow_trailing_comma && *in == ']') {
468       break;
469     }
470     ret.push_back(parseValue(in));
471     in.skipWhitespace();
472     if (*in != ',') {
473       break;
474     }
475     ++in;
476     in.skipWhitespace();
477   }
478   in.expect(']');
479
480   return ret;
481 }
482
483 dynamic parseNumber(Input& in) {
484   bool const negative = (*in == '-');
485   if (negative) {
486     if (in.consume("-Infinity")) {
487       return -std::numeric_limits<double>::infinity();
488     }
489   }
490
491   auto integral = in.skipMinusAndDigits();
492   if (negative && integral.size() < 2) {
493     in.error("expected digits after `-'");
494   }
495
496   auto const wasE = *in == 'e' || *in == 'E';
497   if (*in != '.' && !wasE) {
498     auto val = to<int64_t>(integral);
499     in.skipWhitespace();
500     return val;
501   }
502
503   auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
504   if (*in == 'e' || *in == 'E') {
505     ++in;
506     if (*in == '+' || *in == '-') {
507       ++in;
508     }
509     auto expPart = in.skipDigits();
510     end = expPart.end();
511   }
512   auto fullNum = range(integral.begin(), end);
513
514   auto val = to<double>(fullNum);
515   return val;
516 }
517
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);
524   };
525
526   auto readHex = [&]() -> uint16_t {
527     if (in.size() < 4) {
528       in.error("expected 4 hex digits");
529     }
530
531     uint16_t ret = hexVal(*in) * 4096;
532     ++in;
533     ret += hexVal(*in) * 256;
534     ++in;
535     ret += hexVal(*in) * 16;
536     ++in;
537     ret += hexVal(*in);
538     ++in;
539     return ret;
540   };
541
542   /*
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.
545    */
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 "
550         "surrogate pair");
551     }
552     uint16_t second = readHex();
553     if (second >= 0xdc00 && second <= 0xdfff) {
554       codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
555                   (second & 0x3ff);
556     } else {
557       in.error("second character in surrogate pair is invalid");
558     }
559   } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
560     in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
561   }
562
563   return codePointToUtf8(codePoint);
564 }
565
566 fbstring parseString(Input& in) {
567   assert(*in == '\"');
568   ++in;
569
570   fbstring ret;
571   for (;;) {
572     auto range = in.skipWhile(
573       [] (char c) { return c != '\"' && c != '\\'; }
574     );
575     ret.append(range.begin(), range.end());
576
577     if (*in == '\"') {
578       ++in;
579       break;
580     }
581     if (*in == '\\') {
582       ++in;
583       switch (*in) {
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());
595       }
596       continue;
597     }
598     if (*in == EOF) {
599       in.error("unterminated string");
600     }
601     if (!*in) {
602       /*
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
607        * check this way.)
608        */
609       in.error("null byte in string");
610     }
611
612     ret.push_back(*in);
613     ++in;
614   }
615
616   return ret;
617 }
618
619 dynamic parseValue(Input& in) {
620   in.skipWhitespace();
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");
631 }
632
633 }
634
635 //////////////////////////////////////////////////////////////////////
636
637 fbstring serialize(dynamic const& dyn, serialization_opts const& opts) {
638   fbstring ret;
639   unsigned indentLevel = 0;
640   Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
641   p(dyn);
642   return ret;
643 }
644
645 // Escape a string so that it is legal to print it in JSON text.
646 void escapeString(StringPiece input,
647                   fbstring& out,
648                   const serialization_opts& opts) {
649   auto hexDigit = [] (int c) -> char {
650     return c < 10 ? c + '0' : c - 10 + 'a';
651   };
652
653   out.reserve(out.size() + input.size() + 2);
654   out.push_back('\"');
655
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());
659
660   while (p < e) {
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
668
669       // as the encoding progresses, q will stay at or ahead of p
670       CHECK(q >= p);
671
672       // as p catches up with q, move q forward
673       if (q == p) {
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");
679           p = q;
680           continue;
681         }
682       }
683     }
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);
688       out.append("\\u");
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 == '\"') {
694       out.push_back('\\');
695       out.push_back(*p++);
696     } else if (*p <= 0x1f) {
697       switch (*p) {
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;
703         default:
704           // note that this if condition captures non readable chars
705           // with value < 32, so size = 1 byte (e.g control chars).
706           out.append("\\u00");
707           out.push_back(hexDigit((*p & 0xf0) >> 4));
708           out.push_back(hexDigit(*p & 0xf));
709           p++;
710       }
711     } else {
712       out.push_back(*p++);
713     }
714   }
715
716   out.push_back('\"');
717 }
718
719 }
720
721 //////////////////////////////////////////////////////////////////////
722
723 dynamic parseJson(StringPiece range) {
724   return parseJson(range, json::serialization_opts());
725 }
726
727 dynamic parseJson(
728     StringPiece range,
729     json::serialization_opts const& opts) {
730
731   json::Input in(range, &opts);
732
733   auto ret = parseValue(in);
734   in.skipWhitespace();
735   if (in.size() && *in != '\0') {
736     in.error("parsing didn't consume all input");
737   }
738   return ret;
739 }
740
741 fbstring toJson(dynamic const& dyn) {
742   return json::serialize(dyn, json::serialization_opts());
743 }
744
745 fbstring toPrettyJson(dynamic const& dyn) {
746   json::serialization_opts opts;
747   opts.pretty_formatting = true;
748   return json::serialize(dyn, opts);
749 }
750
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).
755
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);
761 }
762
763 //////////////////////////////////////////////////////////////////////
764
765 }