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