allow reading maps from number -> value
[folly.git] / folly / json.cpp
1 /*
2  * Copyright 2013 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(const unsigned char*& p, const unsigned char* const e) {
34   /* The following encodings are valid, except for the 5 and 6 byte
35    * combinations:
36    * 0xxxxxxx
37    * 110xxxxx 10xxxxxx
38    * 1110xxxx 10xxxxxx 10xxxxxx
39    * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
40    * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
41    * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
42    */
43
44   if (p >= e) {
45     throw std::runtime_error("folly::decodeUtf8 empty/invalid string");
46   }
47
48   unsigned char fst = *p;
49   if (!(fst & 0x80)) {
50     // trivial case
51     return *p++;
52   }
53
54   static const uint32_t bitMask[] = {
55     (1 << 7) - 1,
56     (1 << 11) - 1,
57     (1 << 16) - 1,
58     (1 << 21) - 1
59   };
60
61   // upper control bits are masked out later
62   uint32_t d = fst;
63
64   if ((fst & 0xC0) != 0xC0) {
65     throw std::runtime_error(
66       to<std::string>("folly::decodeUtf8 i=0 d=", d));
67   }
68
69   fst <<= 1;
70
71   for (unsigned int i = 1; i != 3 && p + i < e; ++i) {
72     unsigned char tmp = p[i];
73
74     if ((tmp & 0xC0) != 0x80) {
75       throw std::runtime_error(
76         to<std::string>("folly::decodeUtf8 i=", i, " tmp=", (uint32_t)tmp));
77     }
78
79     d = (d << 6) | (tmp & 0x3F);
80     fst <<= 1;
81
82     if (!(fst & 0x80)) {
83       d &= bitMask[i];
84
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));
89       }
90
91       // check for surrogates only needed for 3 bytes
92       if (i == 2) {
93         if ((d >= 0xD800 && d <= 0xDFFF) || d > 0x10FFFF) {
94           throw std::runtime_error(
95             to<std::string>("folly::decodeUtf8 i=", i, " d=", d));
96         }
97       }
98
99       p += i + 1;
100       return d;
101     }
102   }
103
104   throw std::runtime_error("folly::decodeUtf8 encoding length maxed out");
105 }
106
107 struct Printer {
108   explicit Printer(fbstring& out,
109                    unsigned* indentLevel,
110                    serialization_opts const* opts)
111     : out_(out)
112     , indentLevel_(indentLevel)
113     , opts_(*opts)
114   {}
115
116   void operator()(dynamic const& v) const {
117     switch (v.type()) {
118     case dynamic::DOUBLE:
119       toAppend(v.asDouble(), &out_);
120       break;
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));
127       }
128       toAppend(intval, &out_);
129       break;
130     }
131     case dynamic::BOOL:
132       out_ += v.asBool() ? "true" : "false";
133       break;
134     case dynamic::NULLT:
135       out_ += "null";
136       break;
137     case dynamic::STRING:
138       escapeString(v.asString(), out_, opts_);
139       break;
140     case dynamic::OBJECT:
141       printObject(v);
142       break;
143     case dynamic::ARRAY:
144       printArray(v);
145       break;
146     default:
147       CHECK(0) << "Bad type " << v.type();
148     }
149   }
150
151 private:
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 "
155         "string");
156     }
157     (*this)(p.first);
158     mapColon();
159     (*this)(p.second);
160   }
161
162   void printObject(dynamic const& o) const {
163     if (o.empty()) {
164       out_ += "{}";
165       return;
166     }
167
168     out_ += '{';
169     indent();
170     newline();
171     auto it = o.items().begin();
172     printKV(*it);
173     for (++it; it != o.items().end(); ++it) {
174       out_ += ',';
175       newline();
176       printKV(*it);
177     }
178     outdent();
179     newline();
180     out_ += '}';
181   }
182
183   void printArray(dynamic const& a) const {
184     if (a.empty()) {
185       out_ += "[]";
186       return;
187     }
188
189     out_ += '[';
190     indent();
191     newline();
192     (*this)(a[0]);
193     for (auto& val : makeRange(boost::next(a.begin()), a.end())) {
194       out_ += ',';
195       newline();
196       (*this)(val);
197     }
198     outdent();
199     newline();
200     out_ += ']';
201   }
202
203 private:
204   void outdent() const {
205     if (indentLevel_) {
206       --*indentLevel_;
207     }
208   }
209
210   void indent() const {
211     if (indentLevel_) {
212       ++*indentLevel_;
213     }
214   }
215
216   void newline() const {
217     if (indentLevel_) {
218       out_ += to<fbstring>('\n', fbstring(*indentLevel_ * 2, ' '));
219     }
220   }
221
222   void mapColon() const {
223     out_ += indentLevel_ ? " : " : ":";
224   }
225
226 private:
227   fbstring& out_;
228   unsigned* const indentLevel_;
229   serialization_opts const& opts_;
230 };
231
232 //////////////////////////////////////////////////////////////////////
233
234 struct ParseError : std::runtime_error {
235   explicit ParseError(int line)
236     : std::runtime_error(to<std::string>("json parse error on line ", line))
237   {}
238
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, '\'')
243                         : "",
244         ": ", expected))
245   {}
246
247   explicit ParseError(std::string const& what)
248     : std::runtime_error("json parse error: " + what)
249   {}
250 };
251
252 // Wraps our input buffer with some helper functions.
253 struct Input {
254   explicit Input(StringPiece range, json::serialization_opts const* opts)
255       : range_(range)
256       , opts_(*opts)
257       , lineNum_(0)
258   {
259     storeCurrent();
260   }
261
262   Input(Input const&) = delete;
263   Input& operator=(Input const&) = delete;
264
265   char const* begin() const { return range_.begin(); }
266
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])) {
274         break;
275       }
276       if (range_[skipped] == '\n') {
277         ++lineNum_;
278       }
279     }
280     auto ret = range_.subpiece(0, skipped);
281     range_.advance(skipped);
282     storeCurrent();
283     return ret;
284   }
285
286   StringPiece skipDigits() {
287     return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
288   }
289
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';
296     };
297
298   loop:
299     for (; !range_.empty() && range_.front() == ' '; range_.pop_front()) {
300     }
301     if (!range_.empty() && oddspace(range_.front())) {
302       range_.pop_front();
303       goto loop;
304     }
305     storeCurrent();
306   }
307
308   void expect(char c) {
309     if (**this != c) {
310       throw ParseError(lineNum_, context(),
311         to<std::string>("expected '", c, '\''));
312     }
313     ++*this;
314   }
315
316   std::size_t size() const {
317     return range_.size();
318   }
319
320   int operator*() const {
321     return current_;
322   }
323
324   void operator++() {
325     range_.pop_front();
326     storeCurrent();
327   }
328
329   template<class T>
330   T extract() {
331     try {
332       return to<T>(&range_);
333     } catch (std::exception const& e) {
334       error(e.what());
335     }
336   }
337
338   bool consume(StringPiece str) {
339     if (boost::starts_with(range_, str)) {
340       range_.advance(str.size());
341       storeCurrent();
342       return true;
343     }
344     return false;
345   }
346
347   std::string context() const {
348     return range_.subpiece(0, 16 /* arbitrary */).toString();
349   }
350
351   dynamic error(char const* what) const {
352     throw ParseError(lineNum_, context(), what);
353   }
354
355   json::serialization_opts const& getOpts() {
356     return opts_;
357   }
358
359 private:
360   void storeCurrent() {
361     current_ = range_.empty() ? EOF : range_.front();
362   }
363
364 private:
365   StringPiece range_;
366   json::serialization_opts const& opts_;
367   unsigned lineNum_;
368   int current_;
369 };
370
371 dynamic parseValue(Input& in);
372 fbstring parseString(Input& in);
373 dynamic parseNumber(Input& in);
374
375 dynamic parseObject(Input& in) {
376   assert(*in == '{');
377   ++in;
378
379   dynamic ret = dynamic::object;
380
381   in.skipWhitespace();
382   if (*in == '}') {
383     ++in;
384     return ret;
385   }
386
387   for (;;) {
388     if (*in == '\"') { // string
389       auto key = parseString(in);
390       in.skipWhitespace();
391       in.expect(':');
392       in.skipWhitespace();
393       ret.insert(std::move(key), parseValue(in));
394     } else if (!in.getOpts().allow_non_string_keys) {
395       in.error("expected string for object key name");
396     } else {
397       auto key = parseValue(in);
398       in.skipWhitespace();
399       in.expect(':');
400       in.skipWhitespace();
401       ret.insert(std::move(key), parseValue(in));
402     }
403
404     in.skipWhitespace();
405     if (*in != ',') {
406       break;
407     }
408     ++in;
409     in.skipWhitespace();
410   }
411   in.expect('}');
412
413   return ret;
414 }
415
416 dynamic parseArray(Input& in) {
417   assert(*in == '[');
418   ++in;
419
420   dynamic ret = {};
421
422   in.skipWhitespace();
423   if (*in == ']') {
424     ++in;
425     return ret;
426   }
427
428   for (;;) {
429     ret.push_back(parseValue(in));
430     in.skipWhitespace();
431     if (*in != ',') {
432       break;
433     }
434     ++in;
435     in.skipWhitespace();
436   }
437   in.expect(']');
438
439   return ret;
440 }
441
442 dynamic parseNumber(Input& in) {
443   bool const negative = (*in == '-');
444   if (negative) {
445     ++in;
446     if (in.consume("Infinity")) {
447       return -std::numeric_limits<double>::infinity();
448     }
449   }
450
451   auto integral = in.skipDigits();
452   if (integral.empty()) {
453     in.error("expected digits after `-'");
454   }
455   auto const wasE = *in == 'e' || *in == 'E';
456   if (*in != '.' && !wasE) {
457     auto val = to<int64_t>(integral);
458     if (negative) {
459       val = -val;
460     }
461     in.skipWhitespace();
462     return val;
463   }
464
465   auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
466   if (*in == 'e' || *in == 'E') {
467     ++in;
468     if (*in == '+' || *in == '-') {
469       ++in;
470     }
471     auto expPart = in.skipDigits();
472     end = expPart.end();
473   }
474   auto fullNum = makeRange(integral.begin(), end);
475
476   auto val = to<double>(fullNum);
477   if (negative) {
478     val *= -1;
479   }
480   return val;
481 }
482
483 fbstring decodeUnicodeEscape(Input& in) {
484   auto hexVal = [&] (char c) -> unsigned {
485     return c >= '0' && c <= '9' ? c - '0' :
486            c >= 'a' && c <= 'f' ? c - 'a' + 10 :
487            c >= 'A' && c <= 'F' ? c - 'A' + 10 :
488            (in.error("invalid hex digit"), 0);
489   };
490
491   auto readHex = [&]() -> uint16_t {
492     if (in.size() < 4) {
493       in.error("expected 4 hex digits");
494     }
495
496     uint16_t ret = hexVal(*in) * 4096;
497     ++in;
498     ret += hexVal(*in) * 256;
499     ++in;
500     ret += hexVal(*in) * 16;
501     ++in;
502     ret += hexVal(*in);
503     ++in;
504     return ret;
505   };
506
507   /*
508    * If the value encoded is in the surrogate pair range, we need to
509    * make sure there is another escape that we can use also.
510    */
511   uint32_t codePoint = readHex();
512   if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
513     if (!in.consume("\\u")) {
514       in.error("expected another unicode escape for second half of "
515         "surrogate pair");
516     }
517     uint16_t second = readHex();
518     if (second >= 0xdc00 && second <= 0xdfff) {
519       codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
520                   (second & 0x3ff);
521     } else {
522       in.error("second character in surrogate pair is invalid");
523     }
524   } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
525     in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
526   }
527
528   return codePointToUtf8(codePoint);
529 }
530
531 fbstring parseString(Input& in) {
532   assert(*in == '\"');
533   ++in;
534
535   fbstring ret;
536   for (;;) {
537     auto range = in.skipWhile(
538       [] (char c) { return c != '\"' && c != '\\'; }
539     );
540     ret.append(range.begin(), range.end());
541
542     if (*in == '\"') {
543       ++in;
544       break;
545     }
546     if (*in == '\\') {
547       ++in;
548       switch (*in) {
549       case '\"':    ret.push_back('\"'); ++in; break;
550       case '\\':    ret.push_back('\\'); ++in; break;
551       case '/':     ret.push_back('/');  ++in; break;
552       case 'b':     ret.push_back('\b'); ++in; break;
553       case 'f':     ret.push_back('\f'); ++in; break;
554       case 'n':     ret.push_back('\n'); ++in; break;
555       case 'r':     ret.push_back('\r'); ++in; break;
556       case 't':     ret.push_back('\t'); ++in; break;
557       case 'u':     ++in; ret += decodeUnicodeEscape(in); break;
558       default:      in.error(to<fbstring>("unknown escape ", *in,
559                                           " in string").c_str());
560       }
561       continue;
562     }
563     if (*in == EOF) {
564       in.error("unterminated string");
565     }
566     if (!*in) {
567       /*
568        * Apparently we're actually supposed to ban all control
569        * characters from strings.  This seems unnecessarily
570        * restrictive, so we're only banning zero bytes.  (Since the
571        * string is presumed to be UTF-8 encoded it's fine to just
572        * check this way.)
573        */
574       in.error("null byte in string");
575     }
576
577     ret.push_back(*in);
578     ++in;
579   }
580
581   return ret;
582 }
583
584 dynamic parseValue(Input& in) {
585   in.skipWhitespace();
586   return *in == '[' ? parseArray(in) :
587          *in == '{' ? parseObject(in) :
588          *in == '\"' ? parseString(in) :
589          (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
590          in.consume("true") ? true :
591          in.consume("false") ? false :
592          in.consume("null") ? nullptr :
593          in.consume("Infinity") ? std::numeric_limits<double>::infinity() :
594          in.consume("NaN") ? std::numeric_limits<double>::quiet_NaN() :
595          in.error("expected json value");
596 }
597
598 }
599
600 //////////////////////////////////////////////////////////////////////
601
602 fbstring serialize(dynamic const& dyn, serialization_opts const& opts) {
603   fbstring ret;
604   unsigned indentLevel = 0;
605   Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
606   p(dyn);
607   return ret;
608 }
609
610 // Escape a string so that it is legal to print it in JSON text.
611 void escapeString(StringPiece input,
612                   fbstring& out,
613                   const serialization_opts& opts) {
614   auto hexDigit = [] (int c) -> char {
615     return c < 10 ? c + '0' : c - 10 + 'a';
616   };
617
618   out.reserve(out.size() + input.size() + 2);
619   out.push_back('\"');
620
621   auto* p = reinterpret_cast<const unsigned char*>(input.begin());
622   auto* q = reinterpret_cast<const unsigned char*>(input.begin());
623   auto* e = reinterpret_cast<const unsigned char*>(input.end());
624
625   while (p < e) {
626     // Since non-ascii encoding inherently does utf8 validation
627     // we explicitly validate utf8 only if non-ascii encoding is disabled.
628     if (opts.validate_utf8 && !opts.encode_non_ascii) {
629       // to achieve better spatial and temporal coherence
630       // we do utf8 validation progressively along with the
631       // string-escaping instead of two separate passes
632
633       // as the encoding progresses, q will stay at or ahead of p
634       CHECK(q >= p);
635
636       // as p catches up with q, move q forward
637       if (q == p) {
638         // calling utf8_decode has the side effect of
639         // checking that utf8 encodings are valid
640         decodeUtf8(q, e);
641       }
642     }
643     if (opts.encode_non_ascii && (*p & 0x80)) {
644       // note that this if condition captures utf8 chars
645       // with value > 127, so size > 1 byte
646       char32_t v = decodeUtf8(p, e);
647       out.append("\\u");
648       out.push_back(hexDigit(v >> 12));
649       out.push_back(hexDigit((v >> 8) & 0x0f));
650       out.push_back(hexDigit((v >> 4) & 0x0f));
651       out.push_back(hexDigit(v & 0x0f));
652     } else if (*p == '\\' || *p == '\"') {
653       out.push_back('\\');
654       out.push_back(*p++);
655     } else if (*p <= 0x1f) {
656       switch (*p) {
657         case '\b': out.append("\\b"); p++; break;
658         case '\f': out.append("\\f"); p++; break;
659         case '\n': out.append("\\n"); p++; break;
660         case '\r': out.append("\\r"); p++; break;
661         case '\t': out.append("\\t"); p++; break;
662         default:
663           // note that this if condition captures non readable chars
664           // with value < 32, so size = 1 byte (e.g control chars).
665           out.append("\\u00");
666           out.push_back(hexDigit((*p & 0xf0) >> 4));
667           out.push_back(hexDigit(*p & 0xf));
668           p++;
669       }
670     } else {
671       out.push_back(*p++);
672     }
673   }
674
675   out.push_back('\"');
676 }
677
678 }
679
680 //////////////////////////////////////////////////////////////////////
681
682 dynamic parseJson(StringPiece range) {
683   return parseJson(range, json::serialization_opts());
684 }
685
686 dynamic parseJson(
687     StringPiece range,
688     json::serialization_opts const& opts) {
689
690   json::Input in(range, &opts);
691
692   auto ret = parseValue(in);
693   in.skipWhitespace();
694   if (in.size() && *in != '\0') {
695     in.error("parsing didn't consume all input");
696   }
697   return ret;
698 }
699
700 fbstring toJson(dynamic const& dyn) {
701   return json::serialize(dyn, json::serialization_opts());
702 }
703
704 fbstring toPrettyJson(dynamic const& dyn) {
705   json::serialization_opts opts;
706   opts.pretty_formatting = true;
707   return json::serialize(dyn, opts);
708 }
709
710 //////////////////////////////////////////////////////////////////////
711 // dynamic::print_as_pseudo_json() is implemented here for header
712 // ordering reasons (most of the dynamic implementation is in
713 // dynamic-inl.h, which we don't want to include json.h).
714
715 void dynamic::print_as_pseudo_json(std::ostream& out) const {
716   json::serialization_opts opts;
717   opts.allow_non_string_keys = true;
718   out << json::serialize(*this, opts);
719 }
720
721 //////////////////////////////////////////////////////////////////////
722
723 }