Debian Codegraph @

src/dmlc-core/include/dmlc/json.h

raw symbols SCIP
1 /*!
2 * Copyright (c) 2015 by Contributors
3 * \file json.h
4 * \brief Lightweight JSON Reader/Writer that read save into C++ data structs.
5 * This includes STL composites and structures.
6 */
7 #ifndef DMLC_JSON_H_
8 #define DMLC_JSON_H_
9
10 // This code requires C++11 to compile
11 #include <vector>
12 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
13 #include <iostream>
14 #include <sstream>
15 #endif
16 #include <algorithm>
17 #include <cctype>
18 #include <list>
19 #include <map>
20 #include <string>
21 #include <utility>
22
23 #include "./base.h"
24 #include "./logging.h"
25 #include "./type_traits.h"
26
27 #if DMLC_USE_CXX11
28 #include <typeindex>
29 #include <typeinfo>
30 #include <unordered_map>
31 #if DMLC_STRICT_CXX11
32 #if DMLC_ENABLE_RTTI
33 #include "./any.h"
34 #endif // DMLC_ENABLE_RTTI
35 #endif // DMLC_STRICT_CXX11
36 #endif // DMLC_USE_CXX11
37
38 namespace dmlc {
39 /*!
40 * \brief Lightweight JSON Reader to read any STL compositions and structs.
41 * The user need to know the schema of the
42 *
43 */
44 class JSONReader {
45 public:
46 /*!
47 * \brief Constructor.
48 * \param is the input source.
49 */
50 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
51 explicit JSONReader(std::istream *is)
52 #else
53 explicit JSONReader(std::string *is)
54 #endif
55 : is_(is), line_count_r_(0), line_count_n_(0) {
56 }
57 /*!
58 * \brief Parse next JSON string.
59 * \param out_str the output string.
60 * \throw dmlc::Error when next token is not string
61 */
62 inline void ReadString(std::string *out_str);
63 /*!
64 * \brief Read Number.
65 * \param out_value output value;
66 * \throw dmlc::Error when next token is not number of ValueType.
67 * \tparam ValueType type of the number
68 */
69 template <typename ValueType>
70 inline void ReadNumber(ValueType *out_value);
71 /*!
72 * \brief Begin parsing an object.
73 * \code
74 * std::string key;
75 * // value can be any type that is json serializable.
76 * std::string value;
77 * reader->BeginObject();
78 * while (reader->NextObjectItem(&key)) {
79 * // do somthing to key value
80 * reader->Read(&value);
81 * }
82 * \endcode
83 */
84 inline void BeginObject();
85 /*!
86 * \brief Begin parsing an array.
87 * \code
88 * // value can be any type that is json serializable.
89 * std::string value;
90 * reader->BeginArray();
91 * while (reader->NextArrayItem()) {
92 * reader->Read(&value);
93 * // do somthing to value
94 * }
95 * \endcode
96 */
97 inline void BeginArray();
98 /*!
99 * \brief Try to move to next object item.
100 * If this call is successful, user can proceed to call
101 * reader->Read to read in the value.
102 * \param out_key the key to the next object.
103 * \return true if the read is successful, false if we are at end of the object.
104 */
105 inline bool NextObjectItem(std::string *out_key);
106 /*!
107 * \brief Try to read the next element in the array.
108 * If this call is successful, user can proceed to call
109 * reader->Read to read in the value.
110 * \return true if the read is successful, false if we are at end of the array.
111 */
112 inline bool NextArrayItem();
113 /*!
114 * \brief Read next ValueType.
115 * \param out_value any STL or json readable type to be read
116 * \throw dmlc::Error when the read of ValueType is not successful.
117 * \tparam ValueType the data type to be read.
118 */
119 template <typename ValueType>
120 inline void Read(ValueType *out_value);
121
122 /*! \return current line count */
123 inline std::string line_info() const {
124 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
125 char temp[64];
126 std::ostringstream os;
127 os << " Line " << std::max(line_count_r_, line_count_n_);
128 is_->getline(temp, 64);
129 os << ", around ^`" << temp << "`";
130 return os.str();
131 #else
132 std::string info = " Line ";
133 info += std::to_string(std::max(line_count_r_, line_count_n_));
134
135 // string getline
136 size_t end_pos = is_->find('\n');
137 end_pos
138 = std::min(static_cast<size_t>(64), end_pos == std::string::npos ? is_->size() : end_pos);
139 std::string line = is_->substr(0, end_pos);
140 is_->erase(0, line.size() + 1); // +1 for \n
141
142 info += ", around ^`" + line + "`";
143 return info;
144 #endif
145 }
146
147 private:
148 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
149 /*! \brief internal reader stream */
150 std::istream *is_;
151 #else
152 /*! \brief internal reader string */
153 std::string *is_;
154 #endif
155 /*! \brief "\\r" counter */
156 size_t line_count_r_;
157 /*! \brief "\\n" counter */
158 size_t line_count_n_;
159 /*!
160 * \brief record how many element processed in
161 * current array/object scope.
162 */
163 std::vector<size_t> scope_counter_;
164 /*!
165 * \brief Read next nonspace character.
166 * \return the next nonspace character.
167 */
168 inline int NextNonSpace();
169 /*!
170 * \brief Read just before next nonspace but not read that.
171 * \return the next nonspace character.
172 */
173 inline int PeekNextNonSpace();
174 /*!
175 * \brief Takes the next char from the input source.
176 * \return the next character.
177 */
178 inline int NextChar();
179 /*!
180 * \brief Returns the next char from the input source.
181 * \return the next character.
182 */
183 inline int PeekNextChar();
184 };
185
186 /*!
187 * \brief Lightweight json to write any STL compositions.
188 */
189 class JSONWriter {
190 public:
191 /*!
192 * \brief Constructor.
193 * \param os the output reciever.
194 */
195 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
196 explicit JSONWriter(std::ostream *os)
197 #else
198 explicit JSONWriter(std::string *os)
199 #endif
200 : os_(os) {
201 }
202 /*!
203 * \brief Write a string that do not contain escape characters.
204 * \param s the string to be written.
205 */
206 inline void WriteNoEscape(const std::string &s);
207 /*!
208 * \brief Write a string that can contain escape characters.
209 * \param s the string to be written.
210 */
211 inline void WriteString(const std::string &s);
212 /*!
213 * \brief Write a string that can contain escape characters.
214 * \param v the value to be written.
215 * \tparam ValueType The value type to be written.
216 */
217 template <typename ValueType>
218 inline void WriteNumber(const ValueType &v);
219 /*!
220 * \brief Start beginning of array.
221 * \param multi_line whether to start an multi_line array.
222 * \code
223 * writer->BeginArray();
224 * for (auto& v : vdata) {
225 * writer->WriteArrayItem(v);
226 * }
227 * writer->EndArray();
228 * \endcode
229 */
230 inline void BeginArray(bool multi_line = true);
231 /*! \brief Finish writing an array. */
232 inline void EndArray();
233 /*!
234 * \brief Start beginning of array.
235 * \param multi_line whether to start an multi_line array.
236 * \code
237 * writer->BeginObject();
238 * for (auto& kv : vmap) {
239 * writer->WriteObjectKeyValue(kv.first, kv.second);
240 * }
241 * writer->EndObject();
242 * \endcode
243 */
244 inline void BeginObject(bool multi_line = true);
245 /*! \brief Finish writing object. */
246 inline void EndObject();
247 /*!
248 * \brief Write key value pair in the object.
249 * \param key the key of the object.
250 * \param value the value of to be written.
251 * \tparam ValueType The value type to be written.
252 */
253 template <typename ValueType>
254 inline void WriteObjectKeyValue(const std::string &key, const ValueType &value);
255 /*!
256 * \brief Write seperator of array, before writing next element.
257 * User can proceed to call writer->Write to write next item
258 */
259 inline void WriteArraySeperator();
260 /*!
261 * \brief Write value into array.
262 * \param value The value of to be written.
263 * \tparam ValueType The value type to be written.
264 */
265 template <typename ValueType>
266 inline void WriteArrayItem(const ValueType &value);
267 /*!
268 * \brief Write value to json.
269 * \param value any STL or json readable that can be written.
270 * \tparam ValueType the data type to be write.
271 */
272 template <typename ValueType>
273 inline void Write(const ValueType &value);
274
275 private:
276 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
277 /*! \brief Output stream */
278 std::ostream *os_;
279 #else
280 std::string *os_;
281 #endif
282 /*!
283 * \brief record how many element processed in
284 * current array/object scope.
285 */
286 std::vector<size_t> scope_counter_;
287 /*! \brief Record whether current is a multiline scope */
288 std::vector<bool> scope_multi_line_;
289 /*!
290 * \brief Write seperating space and newlines
291 */
292 inline void WriteSeperator();
293 };
294
295 /*!
296 * \brief Helper class to read JSON into a class or struct object.
297 * \code
298 * struct Param {
299 * std::string name;
300 * int value;
301 * // define load function from JSON
302 * inline void Load(dmlc::JSONReader *reader) {
303 * dmlc::JSONStructReadHelper helper;
304 * helper.DeclareField("name", &name);
305 * helper.DeclareField("value", &value);
306 * helper.ReadAllFields(reader);
307 * }
308 * };
309 * \endcode
310 */
311 class JSONObjectReadHelper {
312 public:
313 /*!
314 * \brief Declare field of type T
315 * \param key the key of the of field.
316 * \param addr address of the data type.
317 * \tparam T the data type to be read, must be STL composition of JSON serializable.
318 */
319 template <typename T>
320 inline void DeclareField(const std::string &key, T *addr) {
321 DeclareFieldInternal(key, addr, false);
322 }
323 /*!
324 * \brief Declare optional field of type T
325 * \param key the key of the of field.
326 * \param addr address of the data type.
327 * \tparam T the data type to be read, must be STL composition of JSON serializable.
328 */
329 template <typename T>
330 inline void DeclareOptionalField(const std::string &key, T *addr) {
331 DeclareFieldInternal(key, addr, true);
332 }
333 /*!
334 * \brief Read in all the declared fields.
335 * \param reader the JSONReader to read the json.
336 */
337 inline void ReadAllFields(JSONReader *reader);
338
339 private:
340 /*!
341 * \brief Internal function to declare field.
342 * \param key the key of the of field.
343 * \param addr address of the data type.
344 * \param optional if set to true, no error will be reported if the key is not presented.
345 * \tparam T the data type to be read, must be STL composition of JSON serializable.
346 */
347 template <typename T>
348 inline void DeclareFieldInternal(const std::string &key, T *addr, bool optional);
349 /*!
350 * \brief The internal reader function.
351 * \param reader The reader to read.
352 * \param addr The memory address to read.
353 */
354 template <typename T>
355 inline static void ReaderFunction(JSONReader *reader, void *addr);
356 /*! \brief callback type to reader function */
357 typedef void (*ReadFunction)(JSONReader *reader, void *addr);
358 /*! \brief internal data entry */
359 struct Entry {
360 /*! \brief the reader function */
361 ReadFunction func;
362 /*! \brief the address to read */
363 void *addr;
364 /*! \brief whether it is optional */
365 bool optional;
366 };
367 /*! \brief the internal map of reader callbacks */
368 std::map<std::string, Entry> map_;
369 };
370
371 #define DMLC_JSON_ENABLE_ANY_VAR_DEF(KeyName) \
372 static DMLC_ATTRIBUTE_UNUSED ::dmlc::json::AnyJSONManager &__make_AnyJSONType##_##KeyName##__
373
374 /*!
375 * \def DMLC_JSON_ENABLE_ANY
376 * \brief Macro to enable save/load JSON of dmlc:: whose actual type is Type.
377 * Any type will be saved as json array [KeyName, content]
378 *
379 * \param Type The type to be registered.
380 * \param KeyName The Type key assigned to the type, must be same during load.
381 */
382 #define DMLC_JSON_ENABLE_ANY(Type, KeyName) \
383 DMLC_STR_CONCAT(DMLC_JSON_ENABLE_ANY_VAR_DEF(KeyName), __COUNTER__) \
384 = ::dmlc::json::AnyJSONManager::Global()->EnableType<Type>(#KeyName)
385
386 //! \cond Doxygen_Suppress
387 namespace json {
388
389 /*!
390 * \brief generic serialization handler
391 * \tparam T the type to be serialized
392 */
393 template <typename T>
394 struct Handler;
395
396 template <typename ValueType>
397 struct NumericHandler {
398 inline static void Write(JSONWriter *writer, const ValueType &value) {
399 writer->WriteNumber<ValueType>(value);
400 }
401 inline static void Read(JSONReader *reader, ValueType *value) {
402 reader->ReadNumber<ValueType>(value);
403 }
404 };
405
406 template <typename ContainerType>
407 struct ArrayHandler {
408 inline static void Write(JSONWriter *writer, const ContainerType &array) {
409 typedef typename ContainerType::value_type ElemType;
410 writer->BeginArray(array.size() > 10 || !dmlc::is_pod<ElemType>::value);
411 for (typename ContainerType::const_iterator it = array.begin(); it != array.end(); ++it) {
412 writer->WriteArrayItem(*it);
413 }
414 writer->EndArray();
415 }
416 inline static void Read(JSONReader *reader, ContainerType *array) {
417 typedef typename ContainerType::value_type ElemType;
418 array->clear();
419 reader->BeginArray();
420 while (reader->NextArrayItem()) {
421 ElemType value;
422 Handler<ElemType>::Read(reader, &value);
423 array->insert(array->end(), value);
424 }
425 }
426 };
427
428 template <typename ContainerType>
429 struct MapHandler {
430 inline static void Write(JSONWriter *writer, const ContainerType &map) {
431 writer->BeginObject(map.size() > 1);
432 for (typename ContainerType::const_iterator it = map.begin(); it != map.end(); ++it) {
433 writer->WriteObjectKeyValue(it->first, it->second);
434 }
435 writer->EndObject();
436 }
437 inline static void Read(JSONReader *reader, ContainerType *map) {
438 typedef typename ContainerType::mapped_type ElemType;
439 map->clear();
440 reader->BeginObject();
441 std::string key;
442 while (reader->NextObjectItem(&key)) {
443 ElemType value;
444 reader->Read(&value);
445 (*map)[key] = value;
446 }
447 }
448 };
449
450 template <typename T>
451 struct CommonJSONSerializer {
452 inline static void Write(JSONWriter *writer, const T &value) {
453 value.Save(writer);
454 }
455 inline static void Read(JSONReader *reader, T *value) {
456 value->Load(reader);
457 }
458 };
459
460 template <>
461 struct Handler<std::string> {
462 inline static void Write(JSONWriter *writer, const std::string &value) {
463 writer->WriteString(value);
464 }
465 inline static void Read(JSONReader *reader, std::string *str) {
466 reader->ReadString(str);
467 }
468 };
469
470 template <typename T>
471 struct Handler<std::vector<T>> : public ArrayHandler<std::vector<T>> {};
472
473 template <typename K, typename V>
474 struct Handler<std::pair<K, V>> {
475 inline static void Write(JSONWriter *writer, const std::pair<K, V> &kv) {
476 writer->BeginArray();
477 writer->WriteArrayItem(kv.first);
478 writer->WriteArrayItem(kv.second);
479 writer->EndArray();
480 }
481 inline static void Read(JSONReader *reader, std::pair<K, V> *kv) {
482 reader->BeginArray();
483 CHECK(reader->NextArrayItem()) << "Expect array of length 2";
484 Handler<K>::Read(reader, &(kv->first));
485 CHECK(reader->NextArrayItem()) << "Expect array of length 2";
486 Handler<V>::Read(reader, &(kv->second));
487 CHECK(!reader->NextArrayItem()) << "Expect array of length 2";
488 }
489 };
490
491 template <typename T>
492 struct Handler<std::list<T>> : public ArrayHandler<std::list<T>> {};
493
494 template <typename V>
495 struct Handler<std::map<std::string, V>> : public MapHandler<std::map<std::string, V>> {};
496
497 #if DMLC_USE_CXX11
498 template <typename V>
499 struct Handler<std::unordered_map<std::string, V>> :
500 public MapHandler<std::unordered_map<std::string, V>> {};
501 #endif // DMLC_USE_CXX11
502
503 template <typename T>
504 struct Handler {
505 inline static void Write(JSONWriter *writer, const T &data) {
506 typedef typename dmlc::IfThenElseType<dmlc::is_arithmetic<T>::value, NumericHandler<T>,
507 CommonJSONSerializer<T>>::Type THandler;
508 THandler::Write(writer, data);
509 }
510 inline static void Read(JSONReader *reader, T *data) {
511 typedef typename dmlc::IfThenElseType<dmlc::is_arithmetic<T>::value, NumericHandler<T>,
512 CommonJSONSerializer<T>>::Type THandler;
513 THandler::Read(reader, data);
514 }
515 };
516
517 #if DMLC_STRICT_CXX11
518 #if DMLC_ENABLE_RTTI
519 // Manager to store json serialization strategy.
520 class AnyJSONManager {
521 public:
522 template <typename T>
523 inline AnyJSONManager &EnableType(const std::string &type_name) { // NOLINT(*)
524 std::type_index tp = std::type_index(typeid(T));
525 if (type_name_.count(tp) != 0) {
526 CHECK(type_name_.at(tp) == type_name)
527 << "Type has already been registered as another typename " << type_name_.at(tp);
528 return *this;
529 }
530 CHECK(type_map_.count(type_name) == 0)
531 << "Type name " << type_name << " already registered in registry";
532 Entry e;
533 e.read = ReadAny<T>;
534 e.write = WriteAny<T>;
535 type_name_[tp] = type_name;
536 type_map_[type_name] = e;
537 return *this;
538 }
539 // return global singleton
540 inline static AnyJSONManager *Global() {
541 static AnyJSONManager inst;
542 return &inst;
543 }
544
545 private:
546 AnyJSONManager() {}
547
548 template <typename T>
549 inline static void WriteAny(JSONWriter *writer, const any &data) {
550 writer->Write(dmlc::unsafe_get<T>(data));
551 }
552 template <typename T>
553 inline static void ReadAny(JSONReader *reader, any *data) {
554 T temp;
555 reader->Read(&temp);
556 *data = std::move(temp);
557 }
558 // data entry to store vtable for any type
559 struct Entry {
560 void (*read)(JSONReader *reader, any *data);
561 void (*write)(JSONWriter *reader, const any &data);
562 };
563
564 template <typename T>
565 friend struct Handler;
566
567 std::unordered_map<std::type_index, std::string> type_name_;
568 std::unordered_map<std::string, Entry> type_map_;
569 };
570
571 template <>
572 struct Handler<any> {
573 inline static void Write(JSONWriter *writer, const any &data) {
574 std::unordered_map<std::type_index, std::string> &nmap = AnyJSONManager::Global()->type_name_;
575 std::type_index id = std::type_index(data.type());
576 auto it = nmap.find(id);
577 CHECK(it != nmap.end() && it->first == id)
578 << "Type " << id.name() << " has not been registered via DMLC_JSON_ENABLE_ANY";
579 std::string type_name = it->second;
580 AnyJSONManager::Entry e = AnyJSONManager::Global()->type_map_.at(type_name);
581 writer->BeginArray(false);
582 writer->WriteArrayItem(type_name);
583 writer->WriteArraySeperator();
584 e.write(writer, data);
585 writer->EndArray();
586 }
587 inline static void Read(JSONReader *reader, any *data) {
588 std::string type_name;
589 reader->BeginArray();
590 CHECK(reader->NextArrayItem()) << "invalid any json format";
591 Handler<std::string>::Read(reader, &type_name);
592 std::unordered_map<std::string, AnyJSONManager::Entry> &tmap
593 = AnyJSONManager::Global()->type_map_;
594 auto it = tmap.find(type_name);
595 CHECK(it != tmap.end() && it->first == type_name)
596 << "Typename " << type_name << " has not been registered via DMLC_JSON_ENABLE_ANY";
597 AnyJSONManager::Entry e = it->second;
598 CHECK(reader->NextArrayItem()) << "invalid any json format";
599 e.read(reader, data);
600 CHECK(!reader->NextArrayItem()) << "invalid any json format";
601 }
602 };
603 #endif // DMLC_ENABLE_RTTI
604 #endif // DMLC_STRICT_CXX11
605
606 } // namespace json
607
608 // implementations of JSONReader/Writer
609 inline int JSONReader::NextChar() {
610 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
611 return is_->get();
612 #else
613 int ch = is_->at(0);
614 is_->erase(0, 1);
615 return ch;
616 #endif
617 }
618
619 inline int JSONReader::PeekNextChar() {
620 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
621 return is_->peek();
622 #else
623 return is_->at(0);
624 #endif
625 }
626
627 inline int JSONReader::NextNonSpace() {
628 int ch;
629 do {
630 ch = NextChar();
631 if (ch == '\n') {
632 ++line_count_n_;
633 }
634 if (ch == '\r') {
635 ++line_count_r_;
636 }
637 } while (isspace(ch));
638 return ch;
639 }
640
641 inline int JSONReader::PeekNextNonSpace() {
642 int ch;
643 while (true) {
644 ch = PeekNextChar();
645 if (ch == '\n') {
646 ++line_count_n_;
647 }
648 if (ch == '\r') {
649 ++line_count_r_;
650 }
651 if (!isspace(ch)) {
652 break;
653 }
654 NextChar();
655 }
656 return ch;
657 }
658
659 namespace {
660 template <typename T>
661 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
662 void Extend(std::ostream *os, T item) {
663 *os << item;
664 }
665 #else
666 void Extend(std::string *ostr, T item) {
667 *ostr += item;
668 }
669 #endif
670 } // namespace
671
672 inline void JSONReader::ReadString(std::string *out_str) {
673 int ch = NextNonSpace();
674 CHECK_EQ(ch, '\"') << "Error at" << line_info() << ", Expect \'\"\' but get \'"
675 << static_cast<char>(ch) << '\'';
676 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
677 std::ostringstream output;
678 #else
679 std::string output = "";
680 #endif
681 while (true) {
682 ch = NextChar();
683 if (ch == '\\') {
684 char sch = static_cast<char>(NextChar());
685 switch (sch) {
686 case 'r':
687 Extend(&output, "\r");
688 break;
689 case 'n':
690 Extend(&output, "\n");
691 break;
692 case '\\':
693 Extend(&output, "\\");
694 break;
695 case 't':
696 Extend(&output, "\t");
697 break;
698 case '\"':
699 Extend(&output, "\"");
700 break;
701 default:
702 LOG(FATAL) << "unknown string escape \\" << sch;
703 }
704 } else {
705 if (ch == '\"') {
706 break;
707 }
708 Extend(&output, static_cast<char>(ch));
709 }
710 if (ch == EOF || ch == '\r' || ch == '\n') {
711 LOG(FATAL) << "Error at" << line_info() << ", Expect \'\"\' but reach end of line ";
712 }
713 }
714 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
715 *out_str = output.str();
716 #else
717 *out_str = output;
718 #endif
719 }
720
721 template <typename ValueType>
722 inline void JSONReader::ReadNumber(ValueType *out_value) {
723 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
724 *is_ >> *out_value;
725 CHECK(!is_->fail()) << "Error at" << line_info() << ", Expect number";
726 #else
727 char *endptr;
728 const char *icstr = is_->c_str();
729 unsigned number = strtol(icstr, &endptr, 10);
730 is_->erase(0, endptr - icstr);
731 *out_value = static_cast<ValueType>(number);
732 #endif
733 }
734
735 inline void JSONReader::BeginObject() {
736 int ch = NextNonSpace();
737 CHECK_EQ(ch, '{') << "Error at" << line_info() << ", Expect \'{\' but get \'"
738 << static_cast<char>(ch) << '\'';
739 scope_counter_.push_back(0);
740 }
741
742 inline void JSONReader::BeginArray() {
743 int ch = NextNonSpace();
744 CHECK_EQ(ch, '[') << "Error at" << line_info() << ", Expect \'[\' but get \'"
745 << static_cast<char>(ch) << '\'';
746 scope_counter_.push_back(0);
747 }
748
749 inline bool JSONReader::NextObjectItem(std::string *out_key) {
750 bool next = true;
751 if (scope_counter_.back() != 0) {
752 int ch = NextNonSpace();
753 if (ch == EOF) {
754 next = false;
755 } else if (ch == '}') {
756 next = false;
757 } else {
758 CHECK_EQ(ch, ',') << "Error at" << line_info() << ", JSON object expect \'}\' or \',\' \'"
759 << static_cast<char>(ch) << '\'';
760 }
761 } else {
762 int ch = PeekNextNonSpace();
763 if (ch == '}') {
764 NextChar();
765 next = false;
766 }
767 }
768 if (!next) {
769 scope_counter_.pop_back();
770 return false;
771 } else {
772 scope_counter_.back() += 1;
773 ReadString(out_key);
774 int ch = NextNonSpace();
775 CHECK_EQ(ch, ':') << "Error at" << line_info() << ", Expect \':\' but get \'"
776 << static_cast<char>(ch) << '\'';
777 return true;
778 }
779 }
780
781 inline bool JSONReader::NextArrayItem() {
782 bool next = true;
783 if (scope_counter_.back() != 0) {
784 int ch = NextNonSpace();
785 if (ch == EOF) {
786 next = false;
787 } else if (ch == ']') {
788 next = false;
789 } else {
790 CHECK_EQ(ch, ',') << "Error at" << line_info() << ", JSON array expect \']\' or \',\'. Get \'"
791 << static_cast<char>(ch) << "\' instead";
792 }
793 } else {
794 int ch = PeekNextNonSpace();
795 if (ch == ']') {
796 NextChar();
797 next = false;
798 }
799 }
800 if (!next) {
801 scope_counter_.pop_back();
802 return false;
803 } else {
804 scope_counter_.back() += 1;
805 return true;
806 }
807 }
808
809 template <typename ValueType>
810 inline void JSONReader::Read(ValueType *out_value) {
811 json::Handler<ValueType>::Read(this, out_value);
812 }
813
814 inline void JSONWriter::WriteNoEscape(const std::string &s) {
815 Extend(os_, '\"');
816 Extend(os_, s);
817 Extend(os_, '\"');
818 }
819
820 inline void JSONWriter::WriteString(const std::string &s) {
821 Extend(os_, '\"');
822 for (size_t i = 0; i < s.length(); ++i) {
823 char ch = s[i];
824 switch (ch) {
825 case '\r':
826 Extend(os_, "\\r");
827 break;
828 case '\n':
829 Extend(os_, "\\n");
830 break;
831 case '\\':
832 Extend(os_, "\\\\");
833 break;
834 case '\t':
835 Extend(os_, "\\t");
836 break;
837 case '\"':
838 Extend(os_, "\\\"");
839 break;
840 default:
841 Extend(os_, ch);
842 }
843 }
844 Extend(os_, '\"');
845 }
846
847 template <typename ValueType>
848 inline void JSONWriter::WriteNumber(const ValueType &v) {
849 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
850 Extend(os_, v);
851 #else
852 Extend(os_, std::to_string(v));
853 #endif
854 }
855
856 inline void JSONWriter::BeginArray(bool multi_line) {
857 Extend(os_, '[');
858 scope_multi_line_.push_back(multi_line);
859 scope_counter_.push_back(0);
860 }
861
862 inline void JSONWriter::EndArray() {
863 CHECK_NE(scope_multi_line_.size(), 0U);
864 CHECK_NE(scope_counter_.size(), 0U);
865 bool newline = scope_multi_line_.back();
866 size_t nelem = scope_counter_.back();
867 scope_multi_line_.pop_back();
868 scope_counter_.pop_back();
869 if (newline && nelem != 0) {
870 WriteSeperator();
871 }
872 Extend(os_, ']');
873 }
874
875 inline void JSONWriter::BeginObject(bool multi_line) {
876 Extend(os_, '{');
877 scope_multi_line_.push_back(multi_line);
878 scope_counter_.push_back(0);
879 }
880
881 inline void JSONWriter::EndObject() {
882 CHECK_NE(scope_multi_line_.size(), 0U);
883 CHECK_NE(scope_counter_.size(), 0U);
884 bool newline = scope_multi_line_.back();
885 size_t nelem = scope_counter_.back();
886 scope_multi_line_.pop_back();
887 scope_counter_.pop_back();
888 if (newline && nelem != 0) {
889 WriteSeperator();
890 }
891 Extend(os_, '}');
892 }
893
894 template <typename ValueType>
895 inline void JSONWriter::WriteObjectKeyValue(const std::string &key, const ValueType &value) {
896 if (scope_counter_.back() > 0) {
897 Extend(os_, ", ");
898 }
899 WriteSeperator();
900 Extend(os_, '\"');
901 Extend(os_, key);
902 Extend(os_, "\": ");
903 scope_counter_.back() += 1;
904 json::Handler<ValueType>::Write(this, value);
905 }
906
907 inline void JSONWriter::WriteArraySeperator() {
908 if (scope_counter_.back() != 0) {
909 Extend(os_, ", ");
910 }
911 scope_counter_.back() += 1;
912 WriteSeperator();
913 }
914
915 template <typename ValueType>
916 inline void JSONWriter::WriteArrayItem(const ValueType &value) {
917 this->WriteArraySeperator();
918 json::Handler<ValueType>::Write(this, value);
919 }
920
921 template <typename ValueType>
922 inline void JSONWriter::Write(const ValueType &value) {
923 size_t nscope = scope_multi_line_.size();
924 json::Handler<ValueType>::Write(this, value);
925 CHECK_EQ(nscope, scope_multi_line_.size())
926 << "Uneven scope, did you call EndArray/EndObject after each BeginObject/Array?";
927 }
928
929 inline void JSONWriter::WriteSeperator() {
930 if (scope_multi_line_.size() == 0 || scope_multi_line_.back()) {
931 Extend(os_, '\n');
932 Extend(os_, std::string(scope_multi_line_.size() * 2, ' '));
933 }
934 }
935
936 inline void JSONObjectReadHelper::ReadAllFields(JSONReader *reader) {
937 reader->BeginObject();
938 std::map<std::string, int> visited;
939 std::string key;
940 while (reader->NextObjectItem(&key)) {
941 if (map_.count(key) != 0) {
942 Entry e = map_[key];
943 (*e.func)(reader, e.addr);
944 visited[key] = 0;
945 } else {
946 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
947 std::ostringstream err;
948 #else
949 std::string err("");
950 #endif
951 Extend(&err, "JSONReader: Unknown field ");
952 Extend(&err, key);
953 Extend(&err, ", candidates are: \n");
954 for (std::map<std::string, Entry>::iterator it = map_.begin(); it != map_.end(); ++it) {
955 Extend(&err, '\"');
956 Extend(&err, it->first);
957 Extend(&err, "\"\n");
958 }
959 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
960 LOG(FATAL) << err.str();
961 #else
962 LOG(FATAL) << err;
963 #endif
964 }
965 }
966 if (visited.size() != map_.size()) {
967 for (std::map<std::string, Entry>::iterator it = map_.begin(); it != map_.end(); ++it) {
968 if (it->second.optional) {
969 continue;
970 }
971 CHECK_NE(visited.count(it->first), 0U)
972 << "JSONReader: Missing field \"" << it->first << "\"\n At " << reader->line_info();
973 }
974 }
975 }
976
977 template <typename T>
978 inline void JSONObjectReadHelper::ReaderFunction(JSONReader *reader, void *addr) {
979 json::Handler<T>::Read(reader, static_cast<T *>(addr));
980 }
981
982 template <typename T>
983 inline void JSONObjectReadHelper::DeclareFieldInternal(
984 const std::string &key, T *addr, bool optional) {
985 CHECK_EQ(map_.count(key), 0U) << "Adding duplicate field " << key;
986 Entry e;
987 e.func = ReaderFunction<T>;
988 e.addr = static_cast<void *>(addr);
989 e.optional = optional;
990 map_[key] = e;
991 }
992
993 //! \endcond
994 } // namespace dmlc
995 #endif // DMLC_JSON_H_