aa6fc614f1ba2f40f39d1ddad01b227b42236dda
[novacoin.git] / src / json / json_spirit_reader_template.h
1 #ifndef JSON_SPIRIT_READER_TEMPLATE
2 #define JSON_SPIRIT_READER_TEMPLATE
3
4 //          Copyright John W. Wilkinson 2007 - 2009.
5 // Distributed under the MIT License, see accompanying file LICENSE.txt
6
7 // json spirit version 4.03
8
9 #include "json_spirit_value.h"
10 #include "json_spirit_error_position.h"
11
12 //#define BOOST_SPIRIT_THREADSAFE  // uncomment for multithreaded use, requires linking to boost.thread
13
14 #include <boost/version.hpp>
15
16 #include <functional>
17
18
19 #if BOOST_VERSION >= 103800
20     #include <boost/spirit/include/classic_core.hpp>
21     #include <boost/spirit/include/classic_confix.hpp>
22     #include <boost/spirit/include/classic_escape_char.hpp>
23     #include <boost/spirit/include/classic_multi_pass.hpp>
24     #include <boost/spirit/include/classic_position_iterator.hpp>
25     #define spirit_namespace boost::spirit::classic
26 #else
27     #include <boost/spirit/core.hpp>
28     #include <boost/spirit/utility/confix.hpp>
29     #include <boost/spirit/utility/escape_char.hpp>
30     #include <boost/spirit/iterator/multi_pass.hpp>
31     #include <boost/spirit/iterator/position_iterator.hpp>
32     #define spirit_namespace boost::spirit
33 #endif
34
35
36 namespace json_spirit
37 {
38     const spirit_namespace::int_parser < int64_t >  int64_p  = spirit_namespace::int_parser < int64_t  >();
39     const spirit_namespace::uint_parser< uint64_t > uint64_p = spirit_namespace::uint_parser< uint64_t >();
40
41     template< class Iter_type >
42     bool is_eq( Iter_type first, Iter_type last, const char* c_str )
43     {
44         for( Iter_type i = first; i != last; ++i, ++c_str )
45         {
46             if( *c_str == 0 ) return false;
47
48             if( *i != *c_str ) return false;
49         }
50
51         return true;
52     }
53
54     template< class Char_type >
55     Char_type hex_to_num( const Char_type c )
56     {
57         if( ( c >= '0' ) && ( c <= '9' ) ) return c - '0';
58         if( ( c >= 'a' ) && ( c <= 'f' ) ) return c - 'a' + 10;
59         if( ( c >= 'A' ) && ( c <= 'F' ) ) return c - 'A' + 10;
60         return 0;
61     }
62
63     template< class Char_type, class Iter_type >
64     Char_type hex_str_to_char( Iter_type& begin )
65     {
66         const Char_type c1( *( ++begin ) );
67         const Char_type c2( *( ++begin ) );
68
69         return ( hex_to_num( c1 ) << 4 ) + hex_to_num( c2 );
70     }       
71
72     template< class Char_type, class Iter_type >
73     Char_type unicode_str_to_char( Iter_type& begin )
74     {
75         const Char_type c1( *( ++begin ) );
76         const Char_type c2( *( ++begin ) );
77         const Char_type c3( *( ++begin ) );
78         const Char_type c4( *( ++begin ) );
79
80         return ( hex_to_num( c1 ) << 12 ) + 
81                ( hex_to_num( c2 ) <<  8 ) + 
82                ( hex_to_num( c3 ) <<  4 ) + 
83                hex_to_num( c4 );
84     }
85
86     template< class String_type >
87     void append_esc_char_and_incr_iter( String_type& s, 
88                                         typename String_type::const_iterator& begin, 
89                                         typename String_type::const_iterator end )
90     {
91         typedef typename String_type::value_type Char_type;
92              
93         const Char_type c2( *begin );
94
95         switch( c2 )
96         {
97             case 't':  s += '\t'; break;
98             case 'b':  s += '\b'; break;
99             case 'f':  s += '\f'; break;
100             case 'n':  s += '\n'; break;
101             case 'r':  s += '\r'; break;
102             case '\\': s += '\\'; break;
103             case '/':  s += '/';  break;
104             case '"':  s += '"';  break;
105             case 'x':  
106             {
107                 if( end - begin >= 3 )  //  expecting "xHH..."
108                 {
109                     s += hex_str_to_char< Char_type >( begin );  
110                 }
111                 break;
112             }
113             case 'u':  
114             {
115                 if( end - begin >= 5 )  //  expecting "uHHHH..."
116                 {
117                     s += unicode_str_to_char< Char_type >( begin );  
118                 }
119                 break;
120             }
121         }
122     }
123
124     template< class String_type >
125     String_type substitute_esc_chars( typename String_type::const_iterator begin, 
126                                    typename String_type::const_iterator end )
127     {
128         typedef typename String_type::const_iterator Iter_type;
129
130         if( end - begin < 2 ) return String_type( begin, end );
131
132         String_type result;
133         
134         result.reserve( end - begin );
135
136         const Iter_type end_minus_1( end - 1 );
137
138         Iter_type substr_start = begin;
139         Iter_type i = begin;
140
141         for( ; i < end_minus_1; ++i )
142         {
143             if( *i == '\\' )
144             {
145                 result.append( substr_start, i );
146
147                 ++i;  // skip the '\'
148              
149                 append_esc_char_and_incr_iter( result, i, end );
150
151                 substr_start = i + 1;
152             }
153         }
154
155         result.append( substr_start, end );
156
157         return result;
158     }
159
160     template< class String_type >
161     String_type get_str_( typename String_type::const_iterator begin, 
162                        typename String_type::const_iterator end )
163     {
164         assert( end - begin >= 2 );
165
166         typedef typename String_type::const_iterator Iter_type;
167
168         Iter_type str_without_quotes( ++begin );
169         Iter_type end_without_quotes( --end );
170
171         return substitute_esc_chars< String_type >( str_without_quotes, end_without_quotes );
172     }
173
174     inline std::string get_str( std::string::const_iterator begin, std::string::const_iterator end )
175     {
176         return get_str_< std::string >( begin, end );
177     }
178
179     inline std::wstring get_str( std::wstring::const_iterator begin, std::wstring::const_iterator end )
180     {
181         return get_str_< std::wstring >( begin, end );
182     }
183     
184     template< class String_type, class Iter_type >
185     String_type get_str( Iter_type begin, Iter_type end )
186     {
187         const String_type tmp( begin, end );  // convert multipass iterators to string iterators
188
189         return get_str( tmp.begin(), tmp.end() );
190     }
191
192     // this class's methods get called by the spirit parse resulting
193     // in the creation of a JSON object or array
194     //
195     // NB Iter_type could be a std::string iterator, wstring iterator, a position iterator or a multipass iterator
196     //
197     template< class Value_type, class Iter_type >
198     class Semantic_actions 
199     {
200     public:
201
202         typedef typename Value_type::Config_type Config_type;
203         typedef typename Config_type::String_type String_type;
204         typedef typename Config_type::Object_type Object_type;
205         typedef typename Config_type::Array_type Array_type;
206         typedef typename String_type::value_type Char_type;
207
208         Semantic_actions( Value_type& value )
209         :   value_( value )
210         ,   current_p_( 0 )
211         {
212         }
213
214         void begin_obj( Char_type c )
215         {
216             assert( c == '{' );
217
218             begin_compound< Object_type >();
219         }
220
221         void end_obj( Char_type c )
222         {
223             assert( c == '}' );
224
225             end_compound();
226         }
227
228         void begin_array( Char_type c )
229         {
230             assert( c == '[' );
231      
232             begin_compound< Array_type >();
233         }
234
235         void end_array( Char_type c )
236         {
237             assert( c == ']' );
238
239             end_compound();
240         }
241
242         void new_name( Iter_type begin, Iter_type end )
243         {
244             assert( current_p_->type() == obj_type );
245
246             name_ = get_str< String_type >( begin, end );
247         }
248
249         void new_str( Iter_type begin, Iter_type end )
250         {
251             add_to_current( get_str< String_type >( begin, end ) );
252         }
253
254         void new_true( Iter_type begin, Iter_type end )
255         {
256             assert( is_eq( begin, end, "true" ) );
257
258             add_to_current( true );
259         }
260
261         void new_false( Iter_type begin, Iter_type end )
262         {
263             assert( is_eq( begin, end, "false" ) );
264
265             add_to_current( false );
266         }
267
268         void new_null( Iter_type begin, Iter_type end )
269         {
270             assert( is_eq( begin, end, "null" ) );
271
272             add_to_current( Value_type() );
273         }
274
275         void new_int( int64_t i )
276         {
277             add_to_current( i );
278         }
279
280         void new_uint64( uint64_t ui )
281         {
282             add_to_current( ui );
283         }
284
285         void new_real( double d )
286         {
287             add_to_current( d );
288         }
289
290     private:
291
292         Semantic_actions& operator=( const Semantic_actions& ); 
293                                     // to prevent "assignment operator could not be generated" warning
294
295         Value_type* add_first( const Value_type& value )
296         {
297             assert( current_p_ == 0 );
298
299             value_ = value;
300             current_p_ = &value_;
301             return current_p_;
302         }
303
304         template< class Array_or_obj >
305         void begin_compound()
306         {
307             if( current_p_ == 0 )
308             {
309                 add_first( Array_or_obj() );
310             }
311             else
312             {
313                 stack_.push_back( current_p_ );
314
315                 Array_or_obj new_array_or_obj;   // avoid copy by building new array or object in place
316
317                 current_p_ = add_to_current( new_array_or_obj );
318             }
319         }
320
321         void end_compound()
322         {
323             if( current_p_ != &value_ )
324             {
325                 current_p_ = stack_.back();
326                 
327                 stack_.pop_back();
328             }    
329         }
330
331         Value_type* add_to_current( const Value_type& value )
332         {
333             if( current_p_ == 0 )
334             {
335                 return add_first( value );
336             }
337             else if( current_p_->type() == array_type )
338             {
339                 current_p_->get_array().push_back( value );
340
341                 return &current_p_->get_array().back(); 
342             }
343             
344             assert( current_p_->type() == obj_type );
345
346             return &Config_type::add( current_p_->get_obj(), name_, value );
347         }
348
349         Value_type& value_;             // this is the object or array that is being created
350         Value_type* current_p_;         // the child object or array that is currently being constructed
351
352         std::vector< Value_type* > stack_;   // previous child objects and arrays
353
354         String_type name_;              // of current name/value pair
355     };
356
357     template< typename Iter_type >
358     void throw_error( spirit_namespace::position_iterator< Iter_type > i, const std::string& reason )
359     {
360         throw Error_position( i.get_position().line, i.get_position().column, reason );
361     }
362
363     template< typename Iter_type >
364     void throw_error( Iter_type i, const std::string& reason )
365     {
366        throw reason;
367     }
368
369     // the spirit grammer 
370     //
371     template< class Value_type, class Iter_type >
372     class Json_grammer : public spirit_namespace::grammar< Json_grammer< Value_type, Iter_type > >
373     {
374     public:
375
376         typedef Semantic_actions< Value_type, Iter_type > Semantic_actions_t;
377
378         Json_grammer( Semantic_actions_t& semantic_actions )
379         :   actions_( semantic_actions )
380         {
381         }
382
383         static void throw_not_value( Iter_type begin, Iter_type end )
384         {
385             throw_error( begin, "not a value" );
386         }
387
388         static void throw_not_array( Iter_type begin, Iter_type end )
389         {
390             throw_error( begin, "not an array" );
391         }
392
393         static void throw_not_object( Iter_type begin, Iter_type end )
394         {
395             throw_error( begin, "not an object" );
396         }
397
398         static void throw_not_pair( Iter_type begin, Iter_type end )
399         {
400             throw_error( begin, "not a pair" );
401         }
402
403         static void throw_not_colon( Iter_type begin, Iter_type end )
404         {
405             throw_error( begin, "no colon in pair" );
406         }
407
408         static void throw_not_string( Iter_type begin, Iter_type end )
409         {
410             throw_error( begin, "not a string" );
411         }
412
413         template< typename ScannerT >
414         class definition
415         {
416         public:
417
418             definition( const Json_grammer& self )
419             {
420                 using namespace spirit_namespace;
421
422                 typedef typename Value_type::String_type::value_type Char_type;
423
424                 // first we convert the semantic action class methods to functors with the 
425                 // parameter signature expected by spirit
426
427                 typedef std::function< void( Char_type )            > Char_action;
428                 typedef std::function< void( Iter_type, Iter_type ) > Str_action;
429                 typedef std::function< void( double )               > Real_action;
430                 typedef std::function< void( int64_t )       > Int_action;
431                 typedef std::function< void( uint64_t )      > Uint64_action;
432
433                 namespace stdp = std::placeholders;
434                 Char_action   begin_obj  ( std::bind( &Semantic_actions_t::begin_obj,   &self.actions_, stdp::_1 ) );
435                 Char_action   end_obj    ( std::bind( &Semantic_actions_t::end_obj,     &self.actions_, stdp::_1 ) );
436                 Char_action   begin_array( std::bind( &Semantic_actions_t::begin_array, &self.actions_, stdp::_1 ) );
437                 Char_action   end_array  ( std::bind( &Semantic_actions_t::end_array,   &self.actions_, stdp::_1 ) );
438                 Str_action    new_name   ( std::bind( &Semantic_actions_t::new_name,    &self.actions_, stdp::_1, stdp::_2 ) );
439                 Str_action    new_str    ( std::bind( &Semantic_actions_t::new_str,     &self.actions_, stdp::_1, stdp::_2 ) );
440                 Str_action    new_true   ( std::bind( &Semantic_actions_t::new_true,    &self.actions_, stdp::_1, stdp::_2 ) );
441                 Str_action    new_false  ( std::bind( &Semantic_actions_t::new_false,   &self.actions_, stdp::_1, stdp::_2 ) );
442                 Str_action    new_null   ( std::bind( &Semantic_actions_t::new_null,    &self.actions_, stdp::_1, stdp::_2 ) );
443                 Real_action   new_real   ( std::bind( &Semantic_actions_t::new_real,    &self.actions_, stdp::_1 ) );
444                 Int_action    new_int    ( std::bind( &Semantic_actions_t::new_int,     &self.actions_, stdp::_1 ) );
445                 Uint64_action new_uint64 ( std::bind( &Semantic_actions_t::new_uint64,  &self.actions_, stdp::_1 ) );
446
447
448                 // actual grammer
449
450                 json_
451                     = value_ | eps_p[ &throw_not_value ]
452                     ;
453
454                 value_
455                     = string_[ new_str ] 
456                     | number_ 
457                     | object_ 
458                     | array_ 
459                     | str_p( "true" ) [ new_true  ] 
460                     | str_p( "false" )[ new_false ] 
461                     | str_p( "null" ) [ new_null  ]
462                     ;
463
464                 object_ 
465                     = ch_p('{')[ begin_obj ]
466                     >> !members_
467                     >> ( ch_p('}')[ end_obj ] | eps_p[ &throw_not_object ] )
468                     ;
469
470                 members_
471                     = pair_ >> *( ',' >> pair_ )
472                     ;
473
474                 pair_
475                     = string_[ new_name ]
476                     >> ( ':' | eps_p[ &throw_not_colon ] )
477                     >> ( value_ | eps_p[ &throw_not_value ] )
478                     ;
479
480                 array_
481                     = ch_p('[')[ begin_array ]
482                     >> !elements_
483                     >> ( ch_p(']')[ end_array ] | eps_p[ &throw_not_array ] )
484                     ;
485
486                 elements_
487                     = value_ >> *( ',' >> value_ )
488                     ;
489
490                 string_ 
491                     = lexeme_d // this causes white space inside a string to be retained
492                       [
493                           confix_p
494                           ( 
495                               '"', 
496                               *lex_escape_ch_p,
497                               '"'
498                           ) 
499                       ]
500                     ;
501
502                 number_
503                     = strict_real_p[ new_real   ] 
504                     | int64_p      [ new_int    ]
505                     | uint64_p     [ new_uint64 ]
506                     ;
507             }
508
509             spirit_namespace::rule< ScannerT > json_, object_, members_, pair_, array_, elements_, value_, string_, number_;
510
511             const spirit_namespace::rule< ScannerT >& start() const { return json_; }
512         };
513
514     private:
515
516         Json_grammer& operator=( const Json_grammer& ); // to prevent "assignment operator could not be generated" warning
517
518         Semantic_actions_t& actions_;
519     };
520
521     template< class Iter_type, class Value_type >
522     Iter_type read_range_or_throw( Iter_type begin, Iter_type end, Value_type& value )
523     {
524         Semantic_actions< Value_type, Iter_type > semantic_actions( value );
525      
526         const spirit_namespace::parse_info< Iter_type > info = 
527                             spirit_namespace::parse( begin, end, 
528                                                     Json_grammer< Value_type, Iter_type >( semantic_actions ), 
529                                                     spirit_namespace::space_p );
530
531         if( !info.hit )
532         {
533             assert( false ); // in theory exception should already have been thrown
534             throw_error( info.stop, "error" );
535         }
536
537         return info.stop;
538     }
539
540     template< class Iter_type, class Value_type >
541     void add_posn_iter_and_read_range_or_throw( Iter_type begin, Iter_type end, Value_type& value )
542     {
543         typedef spirit_namespace::position_iterator< Iter_type > Posn_iter_t;
544
545         const Posn_iter_t posn_begin( begin, end );
546         const Posn_iter_t posn_end( end, end );
547      
548         read_range_or_throw( posn_begin, posn_end, value );
549     }
550
551     template< class Iter_type, class Value_type >
552     bool read_range( Iter_type& begin, Iter_type end, Value_type& value )
553     {
554         try
555         {
556             begin = read_range_or_throw( begin, end, value );
557
558             return true;
559         }
560         catch( ... )
561         {
562             return false;
563         }
564     }
565
566     template< class String_type, class Value_type >
567     void read_string_or_throw( const String_type& s, Value_type& value )
568     {
569         add_posn_iter_and_read_range_or_throw( s.begin(), s.end(), value );
570     }
571
572     template< class String_type, class Value_type >
573     bool read_string( const String_type& s, Value_type& value )
574     {
575         typename String_type::const_iterator begin = s.begin();
576
577         return read_range( begin, s.end(), value );
578     }
579
580     template< class Istream_type >
581     struct Multi_pass_iters
582     {
583         typedef typename Istream_type::char_type Char_type;
584         typedef std::istream_iterator< Char_type, Char_type > istream_iter;
585         typedef spirit_namespace::multi_pass< istream_iter > Mp_iter;
586
587         Multi_pass_iters( Istream_type& is )
588         {
589             is.unsetf( std::ios::skipws );
590
591             begin_ = spirit_namespace::make_multi_pass( istream_iter( is ) );
592             end_   = spirit_namespace::make_multi_pass( istream_iter() );
593         }
594
595         Mp_iter begin_;
596         Mp_iter end_;
597     };
598
599     template< class Istream_type, class Value_type >
600     bool read_stream( Istream_type& is, Value_type& value )
601     {
602         Multi_pass_iters< Istream_type > mp_iters( is );
603
604         return read_range( mp_iters.begin_, mp_iters.end_, value );
605     }
606
607     template< class Istream_type, class Value_type >
608     void read_stream_or_throw( Istream_type& is, Value_type& value )
609     {
610         const Multi_pass_iters< Istream_type > mp_iters( is );
611
612         add_posn_iter_and_read_range_or_throw( mp_iters.begin_, mp_iters.end_, value );
613     }
614 }
615
616 #endif