summaryrefslogtreecommitdiffstats
path: root/src/python/json.cpp
blob: 873523b4a2e00f300bcb5da233b6164b767b1162 (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
/* -*- 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/.
 */

#include "orcus/env.hpp"
#include "orcus/json_parser.hpp"
#include "orcus/json_document_tree.hpp"
#include "orcus/config.hpp"

#include <algorithm>
#include <sstream>
#include <boost/current_function.hpp>

#include <Python.h>

#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))

using namespace std;

namespace orcus { namespace python {

namespace {

class python_json_error : public general_error
{
public:
    python_json_error(const std::string& msg) : general_error("python_json_error", msg) {}
};

struct module_state
{
    PyObject* error;
};

int orcus_traverse(PyObject* m, visitproc visit, void* arg)
{
    Py_VISIT(GETSTATE(m)->error);
    return 0;
}

int orcus_clear(PyObject* m)
{
    Py_CLEAR(GETSTATE(m)->error);
    return 0;
}

struct parser_stack
{
    PyObject* key;
    PyObject* node;
    json::node_t type;

    parser_stack(PyObject* _node, json::node_t _type) : key(nullptr), node(_node), type(_type) {}
};

class json_parser_handler
{
    PyObject* m_root;
    std::vector<parser_stack> m_stack;

    PyObject* push_value(PyObject* value)
    {
        if (!value)
        {
            std::ostringstream os;
            os << BOOST_CURRENT_FUNCTION << ": Empty value is passed.";
            throw python_json_error(os.str());
        }

        if (m_stack.empty())
        {
            std::ostringstream os;
            os << BOOST_CURRENT_FUNCTION << ": Stack is unexpectedly empty.";
            throw python_json_error(os.str());
        }

        parser_stack& cur = m_stack.back();

        switch (cur.type)
        {
            case json::node_t::array:
            {
                PyList_Append(cur.node, value);
                return value;
            }
            break;
            case json::node_t::object:
            {
                assert(cur.key);
                PyDict_SetItem(cur.node, cur.key, value);
                cur.key = nullptr;
                return value;
            }
            break;
            default:
                Py_DECREF(value);
        }

        std::ostringstream os;
        os << BOOST_CURRENT_FUNCTION << ": unstackable JSON value type.";
        throw python_json_error(os.str());
    }

public:
    json_parser_handler() : m_root(nullptr) {}

    ~json_parser_handler()
    {
        if (m_root)
            Py_XDECREF(m_root);

        std::for_each(m_stack.begin(), m_stack.end(),
            [](parser_stack& ps)
            {
                if (ps.key)
                {
                    Py_XDECREF(ps.key);
                    ps.key = nullptr;
                }
            }
        );
    }

    void begin_parse()
    {
        if (m_root)
        {
            std::ostringstream os;
            os << BOOST_CURRENT_FUNCTION << ": Root JSON value already exists.";
            throw python_json_error(os.str());
        }
    }

    void end_parse() {}

    void begin_array()
    {
        if (m_root)
        {
            PyObject* array = push_value(PyList_New(0));
            m_stack.push_back(parser_stack(array, json::node_t::array));
        }
        else
        {
            m_root = PyList_New(0);
            m_stack.push_back(parser_stack(m_root, json::node_t::array));
        }
    }

    void end_array()
    {
        if (m_stack.empty())
        {
            std::ostringstream os;
            os << BOOST_CURRENT_FUNCTION << ": Stack is unexpectedly empty.";
            throw python_json_error(os.str());
        }

        m_stack.pop_back();
    }

    void begin_object()
    {
        if (m_root)
        {
            PyObject* dict = push_value(PyDict_New());
            m_stack.push_back(parser_stack(dict, json::node_t::object));
        }
        else
        {
            m_root = PyDict_New();
            m_stack.push_back(parser_stack(m_root, json::node_t::object));
        }
    }

    void object_key(std::string_view key, bool /*transient*/)
    {
        parser_stack& cur = m_stack.back();
        cur.key = PyUnicode_FromStringAndSize(key.data(), key.size());
    }

    void end_object()
    {
        if (m_stack.empty())
        {
            std::ostringstream os;
            os << BOOST_CURRENT_FUNCTION << ": Stack is unexpectedly empty.";
            throw python_json_error(os.str());
        }

        m_stack.pop_back();
    }

    void boolean_true()
    {
        Py_INCREF(Py_True);
        push_value(Py_True);
    }

    void boolean_false()
    {
        Py_INCREF(Py_False);
        push_value(Py_False);
    }

    void null()
    {
        Py_INCREF(Py_None);
        push_value(Py_None);
    }

    void string(std::string_view val, bool /*transient*/)
    {
        push_value(PyUnicode_FromStringAndSize(val.data(), val.size()));
    }

    void number(double val)
    {
        push_value(PyFloat_FromDouble(val));
    }

    PyObject* get_root()
    {
        PyObject* o = m_root;
        m_root = nullptr;
        return o;
    }
};

PyObject* json_loads(PyObject* /*module*/, PyObject* args, PyObject* kwargs)
{
    char* stream = nullptr;
    static const char* kwlist[] = { "s", nullptr };
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", const_cast<char**>(kwlist), &stream))
    {
        PyErr_SetString(PyExc_TypeError, "The method must be given a string.");
        return nullptr;
    }

    json_parser_handler hdl;
    orcus::json_parser<json_parser_handler> parser(stream, hdl);
    try
    {
        parser.parse();
        return hdl.get_root();
    }
    catch (const orcus::parse_error& e)
    {
        PyErr_SetString(PyExc_TypeError, e.what());
    }
    return nullptr;
}

PyMethodDef orcus_methods[] =
{
    { "loads", (PyCFunction)json_loads, METH_VARARGS | METH_KEYWORDS, "Load JSON string into a Python object." },
    { nullptr, nullptr, 0, nullptr }
};

struct PyModuleDef moduledef =
{
    PyModuleDef_HEAD_INIT,
    "_orcus_json",
    nullptr,
    sizeof(struct module_state),
    orcus_methods,
    nullptr,
    orcus_traverse,
    orcus_clear,
    nullptr
};

}

}}

extern "C" {

ORCUS_DLLPUBLIC PyObject* PyInit__orcus_json()
{
    PyObject* m = PyModule_Create(&orcus::python::moduledef);
    return m;
}

}

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