summaryrefslogtreecommitdiffstats
path: root/include/orcus/json_parser.hpp
blob: b021ff8bb841d270408cb303f84df5549e073bab (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDED_ORCUS_JSON_PARSER_HPP
#define INCLUDED_ORCUS_JSON_PARSER_HPP

#include "json_parser_base.hpp"

#include <cassert>
#include <cmath>

namespace orcus {

class json_handler
{
public:
    /**
     * Called when the parsing begins.
     */
    void begin_parse() {}

    /**
     * Called when the parsing ends.
     */
    void end_parse() {}

    /**
     * Called when the opening brace of an array is encountered.
     */
    void begin_array() {}

    /**
     * Called when the closing brace of an array is encountered.
     */
    void end_array() {}

    /**
     * Called when the opening curly brace of an object is encountered.
     */
    void begin_object() {}

    /**
     * Called when a key value string of an object is encountered.
     *
     * @param key key value string.
     * @param transient true if the string value is stored in a temporary
     *                  buffer which is not guaranteed to hold the string
     *                  value after the end of this callback. When false, the
     *                  pointer points to somewhere in the JSON stream being
     *                  parsed.
     */
    void object_key(std::string_view key, bool transient)
    {
        (void)key; (void)transient;
    }

    /**
     * Called when the closing curly brace of an object is encountered.
     */
    void end_object() {}

    /**
     * Called when a boolean 'true' keyword is encountered.
     */
    void boolean_true() {}

    /**
     * Called when a boolean 'false' keyword is encountered.
     */
    void boolean_false() {}

    /**
     * Called when a 'null' keyword is encountered.
     */
    void null() {}

    /**
     * Called when a string value is encountered.
     *
     * @param val string value.
     * @param transient true if the string value is stored in a temporary
     *                  buffer which is not guaranteed to hold the string
     *                  value after the end of this callback. When false, the
     *                  pointer points to somewhere in the JSON stream being
     *                  parsed.
     */
    void string(std::string_view val, bool transient)
    {
        (void)val; (void)transient;
    }

    /**
     * Called when a numeric value is encountered.
     *
     * @param val numeric value.
     */
    void number(double val)
    {
        (void)val;
    }
};

/**
 * Parser for JSON documents.
 *
 * @tparam HandlerT Hanlder type with member functions for event callbacks.
 *         Refer to json_handler.
 */
template<typename HandlerT>
class json_parser : public json::parser_base
{
public:
    typedef HandlerT handler_type;

    /**
     * Constructor.
     *
     * @param content string stream containing JSON string.
     * @param hdl handler class instance.
     */
    json_parser(std::string_view content, handler_type& hdl);

    /**
     * Call this method to start parsing.
     */
    void parse();

private:
    void root_value();
    void value();
    void array();
    void end_array();
    void object();
    void number();
    void string();

private:
    handler_type& m_handler;
};

template<typename _Handler>
json_parser<_Handler>::json_parser(
    std::string_view content, handler_type& hdl) :
    json::parser_base(content), m_handler(hdl) {}

template<typename _Handler>
void json_parser<_Handler>::parse()
{
    m_handler.begin_parse();

    skip_ws();
    if (has_char())
        root_value();
    else
        throw parse_error("parse: no json content could be found in file", offset());

    if (has_char())
        throw parse_error("parse: unexpected trailing string segment.", offset());

    m_handler.end_parse();
}

template<typename _Handler>
void json_parser<_Handler>::root_value()
{
    char c = cur_char();

    switch (c)
    {
        case '[':
            array();
        break;
        case '{':
            object();
        break;
        default:
            parse_error::throw_with(
                "root_value: either '[' or '{' was expected, but '", cur_char(), "' was found.", offset());
    }
}

template<typename _Handler>
void json_parser<_Handler>::value()
{
    char c = cur_char();
    if (is_numeric(c))
    {
        number();
        return;
    }

    switch (c)
    {
        case '-':
            number();
        break;
        case '[':
            array();
        break;
        case '{':
            object();
        break;
        case 't':
            parse_true();
            m_handler.boolean_true();
        break;
        case 'f':
            parse_false();
            m_handler.boolean_false();
        break;
        case 'n':
            parse_null();
            m_handler.null();
        break;
        case '"':
            string();
        break;
        default:
            parse_error::throw_with("value: failed to parse '", cur_char(), "'.", offset());
    }
}

template<typename _Handler>
void json_parser<_Handler>::array()
{
    assert(cur_char() == '[');

    m_handler.begin_array();
    for (next(); has_char(); next())
    {
        skip_ws();

        if (cur_char() == ']')
        {
            end_array();
            return;
        }

        value();
        skip_ws();

        if (has_char())
        {
            switch (cur_char())
            {
                case ']':
                    end_array();
                    return;
                case ',':
                    if (peek_char() == ']')
                    {
                        parse_error::throw_with(
                            "array: ']' expected but '", cur_char(), "' found.", offset() );
                    }
                    continue;
                default:
                    parse_error::throw_with(
                        "array: either ']' or ',' expected, but '", cur_char(), "' found.", offset());
            }
        }
        else
        {
            // needs to be handled here,
            // we would call next() before checking again with has_char() which
            // is already past the end
            break;
        }
    }

    throw parse_error("array: failed to parse array.", offset());
}

template<typename _Handler>
void json_parser<_Handler>::end_array()
{
    m_handler.end_array();
    next();
    skip_ws();
}

template<typename _Handler>
void json_parser<_Handler>::object()
{
    assert(cur_char() == '{');

    bool require_new_key = false;
    m_handler.begin_object();
    for (next(); has_char(); next())
    {
        skip_ws();
        if (!has_char())
            throw parse_error("object: stream ended prematurely before reaching a key.", offset());

        switch (cur_char())
        {
            case '}':
                if (require_new_key)
                {
                    parse_error::throw_with(
                        "object: new key expected, but '", cur_char(), "' found.", offset());
                }
                m_handler.end_object();
                next();
                skip_ws();
                return;
            case '"':
                break;
            default:
                parse_error::throw_with(
                    "object: '\"' was expected, but '", cur_char(), "' found.", offset());
        }
        require_new_key = false;

        parse_quoted_string_state res = parse_string();
        if (!res.str)
        {
            // Parsing was unsuccessful.
            if (res.length == parse_quoted_string_state::error_no_closing_quote)
                throw parse_error("object: stream ended prematurely before reaching the closing quote of a key.", offset());
            else if (res.length == parse_quoted_string_state::error_illegal_escape_char)
                parse_error::throw_with(
                    "object: illegal escape character '", cur_char(), "' in key value.", offset());
            else
                throw parse_error("object: unknown error while parsing a key value.", offset());
        }

        m_handler.object_key({res.str, res.length}, res.transient);

        skip_ws();
        if (cur_char() != ':')
            parse_error::throw_with(
                "object: ':' was expected, but '", cur_char(), "' found.", offset());

        next();
        skip_ws();

        if (!has_char())
            throw parse_error("object: stream ended prematurely before reaching a value.", offset());

        value();

        skip_ws();
        if (!has_char())
            throw parse_error("object: stream ended prematurely before reaching either '}' or ','.", offset());

        switch (cur_char())
        {
            case '}':
                m_handler.end_object();
                next();
                skip_ws();
                return;
            case ',':
                require_new_key = true;
                continue;
            default:
                parse_error::throw_with(
                    "object: either '}' or ',' expected, but '", cur_char(), "' found.", offset());
        }
    }

    throw parse_error("object: closing '}' was never reached.", offset());
}

template<typename _Handler>
void json_parser<_Handler>::number()
{
    assert(is_numeric(cur_char()) || cur_char() == '-');

    double val = parse_double_or_throw();
    m_handler.number(val);
    skip_ws();
}

template<typename _Handler>
void json_parser<_Handler>::string()
{
    parse_quoted_string_state res = parse_string();
    if (res.str)
    {
        m_handler.string({res.str, res.length}, res.transient);
        return;
    }

    // Parsing was unsuccessful.
    if (res.length == parse_quoted_string_state::error_no_closing_quote)
        throw parse_error("string: stream ended prematurely before reaching the closing quote.", offset());
    else if (res.length == parse_quoted_string_state::error_illegal_escape_char)
        parse_error::throw_with("string: illegal escape character '", cur_char(), "'.", offset());
    else
        throw parse_error("string: unknown error.", offset());
}

}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */