aboutsummaryrefslogtreecommitdiff
path: root/libbutl/json/parser.hxx
blob: 241ca4655ad2b7d67bd372eb2cf562516a27ead3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#pragma once

#ifdef BUILD2_BOOTSTRAP
#  error JSON parser not available during bootstrap
#endif

#include <iosfwd>
#include <string>
#include <cstddef>   // size_t
#include <cstdint>   // uint64_t
#include <utility>   // pair
#include <exception> // exception_ptr
#include <stdexcept> // invalid_argument

#include <libbutl/optional.hxx> // butl::optional is std::optional or similar.

#include <libbutl/json/event.hxx>

#include <libbutl/json/pdjson.h> // Implementation details.

#include <libbutl/export.hxx>

namespace butl
{
  // Using the RFC8259 terminology: JSON (input) text, JSON value, object
  // member.
  //
  namespace json
  {
    class invalid_json_input: public std::invalid_argument
    {
    public:
      std::string   name;
      std::uint64_t line;
      std::uint64_t column;
      std::uint64_t position;

      invalid_json_input (std::string name,
                          std::uint64_t line,
                          std::uint64_t column,
                          std::uint64_t position,
                          const std::string& description);

      invalid_json_input (std::string name,
                          std::uint64_t line,
                          std::uint64_t column,
                          std::uint64_t position,
                          const char* description);
    };

    class LIBBUTL_SYMEXPORT parser
    {
    public:
      const char* input_name;

      // Construction.
      //

      // Parse JSON input text from std::istream.
      //
      // The name argument is used to identify the input being parsed. Note
      // that the stream, name, and separators are kept as references so they
      // must outlive the parser instance.
      //
      // If stream exceptions are enabled then the std::ios_base::failure
      // exception is used to report input/output errors (badbit and failbit).
      // Otherwise, those are reported as the invalid_json_input exception.
      //
      // If multi_value is true, enable the multi-value mode in which case the
      // input stream may contain multiple JSON values (more precisely, zero
      // or more). If false (the default), parsing will fail unless there is
      // exactly one JSON value in the input stream.
      //
      // If multi_value is true, the separators argument specifies the
      // required separator characters between JSON values. At least one of
      // them must be present between every pair of JSON values (in addition
      // to any number of JSON whitespaces). No separators are required after
      // the last JSON value (but any found will be skipped).
      //
      // Specifically, if it is NULL, then no separation is required (that is,
      // both `{...}{...}` and `{...}  {...}` would be valid). If it is empty,
      // then at least one JSON whitespace is required. And if it is non-
      // empty, then at least one of its characters must be present (for
      // example, "\n\t" would require at least one newline or TAB character
      // between JSON values).
      //
      // Note that a separator need not be valid JSON whitespace: any
      // character is acceptable (though it probably shouldn't be an object,
      // array, or string delimiter and should not occur within a non-self-
      // delimited top-level value, such as `true`, `false`, `null`, or a
      // number). All instances of required separators before and after a
      // value are skipped. Therefore JSON Text Sequences (RFC 7464; AKA
      // Record Separator-delimited JSON), which requires the RS (0x1E)
      // character before each value, can be handled as well.
      //
      parser (std::istream&,
              const std::string& name,
              bool multi_value = false,
              const char* separators = nullptr) noexcept;

      parser (std::istream&,
              const char* name,
              bool multi_value = false,
              const char* separators = nullptr) noexcept;

      parser (std::istream&,
              std::string&&,
              bool = false,
              const char* = nullptr) = delete;

      // Parse a memory buffer that contains the entire JSON input text.
      //
      // The name argument is used to identify the input being parsed. Note
      // that the buffer, name, and separators are kept as references so they
      // must outlive the parser instance.
      //
      parser (const void* text,
              std::size_t size,
              const std::string& name,
              bool multi_value = false,
              const char* separators = nullptr) noexcept;

      parser (const void* text,
              std::size_t size,
              const char* name,
              bool multi_value = false,
              const char* separators = nullptr) noexcept;

      parser (const void*,
              std::size_t,
              std::string&&,
              bool = false,
              const char* = nullptr) = delete;

      // Similar to the above but parse a string.
      //
      parser (const std::string& text,
              const std::string& name,
              bool multi_value = false,
              const char* separators = nullptr) noexcept;

      parser (const std::string& text,
              const char* name,
              bool multi_value = false,
              const char* separators = nullptr) noexcept;

      parser (const std::string&,
              std::string&&,
              bool = false,
              const char* = nullptr) = delete;

      // Similar to the above but parse a C-string.
      //
      parser (const char* text,
              const std::string& name,
              bool multi_value = false,
              const char* separators = nullptr) noexcept;

      parser (const char* text,
              const char* name,
              bool multi_value = false,
              const char* separators = nullptr) noexcept;

      parser (const char*,
              std::string&&,
              bool = false,
              const char* = nullptr) = delete;

      parser (parser&&) = delete;
      parser (const parser&) = delete;

      parser& operator= (parser&&) = delete;
      parser& operator= (const parser&) = delete;

      // Return the next event or nullopt if end of input is reached.
      //
      // In the single-value parsing mode (default) the parsing code could
      // look like this:
      //
      //     while (optional<event> e = p.next ())
      //     {
      //       switch (*e)
      //       {
      //         // ...
      //       }
      //     }
      //
      // In the multi-value mode the parser additionally returns nullopt after
      // every JSON value parsed (so there will be two nullopt's after the
      // last JSON value, the second indicating the end of input).
      //
      // One way to perform multi-value parsing is with the help of the peek()
      // function (see below):
      //
      //     while (p.peek ())
      //     {
      //       while (optional<event> e = p.next ())
      //       {
      //         switch (*e)
      //         {
      //           //...
      //         }
      //       }
      //     }
      //
      // Note that while the single-value mode will always parse exactly one
      // value, the multi-value mode will accept zero values in which case a
      // single nullopt is returned.
      //
      optional<event>
      next ();

      // The range-based for loop support.
      //
      // In the single-value parsing mode (default) the parsing code could
      // look like this:
      //
      //     for (event e: p)
      //     {
      //       switch (e)
      //       {
      //         //...
      //       }
      //     }
      //
      // And in the multi-value mode (see next() for more information) like
      // this:
      //
      //     while (p.peek ())
      //     {
      //       for (event e: p)
      //       {
      //         switch (e)
      //         {
      //           //...
      //         }
      //       }
      //     }
      //
      // Note that generally, the iterator interface doesn't make much sense
      // for the parser so for now we have an implementation that is just
      // enough for the range-based for.
      //
      struct iterator;

      iterator begin () {return iterator (this, next ());}
      iterator end ()   {return iterator (nullptr, nullopt);}

      // Return the next event without considering it parsed. In other words,
      // after this call, any subsequent calls to peek() and the next call to
      // next() (if any) will all return the same event.
      //
      // Note that the name, value, and line corresponding to the peeked event
      // are not accessible with name(), value() and line(); these functions
      // will still return values corresponding to the most recent call to
      // next(). The peeked values, however, can be accessed in the raw form
      // using data().
      //
      optional<event>
      peek ();

      // Event data.
      //

      // Return the object member name.
      //
      const std::string&
      name ();

      // Any value (string, number, boolean, and null) can be retrieved as a
      // string. Calling this function after any non-value events is illegal.
      //
      // Note that the value is returned as a non-const string reference and
      // you are allowed to move the value out of it. However, this should not
      // be done unnecessarily or in cases where the small string optimization
      // is likely since the string's buffer is reused to store subsequent
      // values.
      //
      std::string&
      value ();

      // Convert the value to an integer, floating point, or bool. Throw
      // invalid_json_input if the conversion is impossible without a loss.
      //
      template <typename T>
      T
      value () const;

      // Return the value or object member name in the raw form.
      //
      // Calling this function on non-value/name events is legal in which case
      // NULL is returned. Note also that the returned data corresponds to the
      // most recent event, whether peeked or parsed.
      //
      std::pair<const char*, std::size_t>
      data () const {return std::make_pair (raw_s_, raw_n_);}

      // Return the line number (1-based) corresponding to the most recently
      // parsed event or 0 if nothing has been parsed yet.
      //
      std::uint64_t
      line () const noexcept;

      // Return the column number (1-based) corresponding to the beginning of
      // the most recently parsed event or 0 if nothing has been parsed yet.
      //
      std::uint64_t
      column () const noexcept;

      // Return the position (byte offset) pointing immediately after the most
      // recently parsed event or 0 if nothing has been parsed yet.
      //
      std::uint64_t
      position () const noexcept;

      // Implementation details.
      //
    public:
      struct iterator
      {
        using value_type = event;

        explicit
        iterator (parser* p = nullptr, optional<event> e = nullopt)
            : p_ (p), e_ (e) {}

        event operator* () const {return *e_;}
        iterator& operator++ () {e_ = p_->next (); return *this;}

        // Comparison only makes sense when comparing to end (eof).
        //
        bool operator== (iterator y) const {return !e_ && !y.e_;}
        bool operator!= (iterator y) const {return !(*this == y);}

      private:
        parser* p_;
        optional<event> e_;
      };

      struct stream
      {
        std::istream*                is;
        optional<std::exception_ptr> exception;
      };

      [[noreturn]] void
      throw_invalid_value (const char* type, const char*, std::size_t) const;

      ~parser ();

    private:
      // Functionality shared by next() and peek().
      //
      json_type
      next_impl ();

      // Translate the event produced by the most recent call to next_impl().
      //
      // Note that the underlying parser state determines whether name or
      // value is returned when translating JSON_STRING.
      //
      optional<event>
      translate (json_type) const noexcept;

      // Cache state (name/value) produced by the most recent call to
      // next_impl().
      //
      void
      cache_parsed_data ();

      // Cache the location numbers as determined by the most recent call to
      // next_impl().
      //
      void
      cache_parsed_location () noexcept;

      // Return true if this is a value event (string, number, boolean, or
      // null).
      //
      static bool
      value_event (optional<event>) noexcept;

      stream stream_;

      bool multi_value_;
      const char* separators_;

      // The *_p_ members indicate whether the value is present (cached).
      // Note: not using optional not to reallocate the string's buffer.
      //
      std::string name_;                       bool name_p_     = false;
      std::string value_;                      bool value_p_    = false;
      std::uint64_t line_, column_, position_; bool location_p_ = false;

      optional<json_type> parsed_; // Current parsed event if any.
      optional<json_type> peeked_; // Current peeked event if any.

      ::json_stream impl_[1];

      // Cached raw value.
      //
      const char* raw_s_;
      std::size_t raw_n_;
    };
  }
}

#include <libbutl/json/parser.ixx>