summaryrefslogtreecommitdiff
path: root/src/script/rapidjson/rapidjson.cpp
blob: 9e878123dd8cadb12786d123abc2ff3726a8ad84 (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
409
410
411
412
413
414

#include <limits>
#include <cstdio>
#include <vector>
#include <algorithm>

#include "userdata.hpp"
#include "values.hpp"
#include "luax.hpp"
#include "file.hpp"

#include "lua.hpp"
#include "rapidjson.h"

using namespace rapidjson;

#ifndef LUA_RAPIDJSON_VERSION
#define LUA_RAPIDJSON_VERSION "1.0.0"
#endif

static void createSharedMeta(lua_State* L, const char* meta, const char* type)
{
    luaL_newmetatable(L, meta);
    lua_pushstring(L, type);
    lua_setfield(L, -2, "__jsontype");
    lua_pop(L, 1);
}

static int makeTableType(lua_State* L, int idx, const char* meta, const char* type)
{
    auto isnoarg = lua_isnoneornil(L, idx);
    auto istable = lua_istable(L, idx);
    if (!isnoarg && !istable)
        return luaL_argerror(L, idx, "optional table excepted");

    if (isnoarg)
        lua_createtable(L, 0, 0);
    else // is table.
    {
        lua_pushvalue(L, idx);
        if (lua_getmetatable(L, -1))
        {
            // already have a metatable, just set the __jsontype field.

            lua_pushstring(L, type);
            lua_setfield(L, -2, "__jsontype");
            lua_pop(L, 1);
            return 1;
        }
        // else fall through
    }

    // Now we have a table without meta table
    luaL_getmetatable(L, meta);
    lua_setmetatable(L, -2);
    return 1;
}

static int json_object(lua_State* L)
{
    return makeTableType(L, 1, "json.object", "object");
}

static int json_array(lua_State* L)
{
    return makeTableType(L, 1, "json.array", "array");
}

template<typename Stream>
int decode(lua_State* L, Stream* s)
{
    auto top = lua_gettop(L);
    values::ToLuaHandler handler(L);
    Reader reader;

    ParseResult r = reader.Parse(*s, handler);
    if (!r)
    {
        lua_settop(L, top);
        lua_pushnil(L);
        lua_pushfstring(L, "%s (%d)", GetParseError_En(r.Code()), r.Offset());
        return 2;
    }

    return 1;
}

static int json_decode(lua_State* L)
{
    size_t len = 0;
    auto contents = luaL_checklstring(L, 1, &len);
    StringStream s(contents);
    return decode(L, &s);
}

static int json_load(lua_State* L)
{
    auto filename = luaL_checklstring(L, 1, nullptr);
    auto fp = file::open(filename, "rb");
    if (!fp)
        luaL_error(L, "error while open file: %s", filename);

    char buffer[512];
    FileReadStream fs(fp, buffer, sizeof(buffer));
    AutoUTFInputStream<unsigned, FileReadStream> eis(fs);

    auto n = decode(L, &eis);

    fclose(fp);
    return n;
}

struct Key
{
    Key(const char* k, SizeType l) : key(k), size(l)
    {}
    bool operator<(const Key& rhs) const
    {
        return strcmp(key, rhs.key) < 0;
    }
    const char* key;
    SizeType size;
};

class Encoder
{
    bool pretty;
    bool sort_keys;
    int max_depth;
    static const int MAX_DEPTH_DEFAULT = 128;
    public:
    Encoder(lua_State*L, int opt) : pretty(false), sort_keys(false), max_depth(MAX_DEPTH_DEFAULT)
    {
        if (lua_isnoneornil(L, opt))
            return;
        luaL_checktype(L, opt, LUA_TTABLE);

        pretty = luax::optboolfield(L, opt, "pretty", false);
        sort_keys = luax::optboolfield(L, opt, "sort_keys", false);
        max_depth = luax::optintfield(L, opt, "max_depth", MAX_DEPTH_DEFAULT);
    }

    private:
    template<typename Writer>
        void encodeValue(lua_State* L, Writer* writer, int idx, int depth = 0)
        {
            size_t len;
            const char* s;
            int64_t integer;
            auto t = lua_type(L, idx);
            switch (t)
            {
                case LUA_TBOOLEAN:
                    writer->Bool(lua_toboolean(L, idx) != 0);
                    return;
                case LUA_TNUMBER:
                    if (luax::isinteger(L, idx, &integer))
                        writer->Int64(integer);
                    else
                    {
                        if (!writer->Double(lua_tonumber(L, idx)))
                            luaL_error(L, "error while encode double value.");
                    }
                    return;
                case LUA_TSTRING:
                    s = lua_tolstring(L, idx, &len);
                    writer->String(s, static_cast<SizeType>(len));
                    return;
                case LUA_TTABLE:
                    return encodeTable(L, writer, idx, depth + 1);
                case LUA_TNIL:
                    writer->Null();
                    return;
                case LUA_TFUNCTION:
                    if (values::isnull(L, idx))
                    {
                        writer->Null();
                        return;
                    }
                    // otherwise fall thought
                case LUA_TLIGHTUSERDATA: // fall thought
                case LUA_TUSERDATA: // fall thought
                case LUA_TTHREAD: // fall thought
                case LUA_TNONE: // fall thought
                default:
                    luaL_error(L, "value type : %s", lua_typename(L, t));
            }
        }

    template<typename Writer>
        void encodeTable(lua_State* L, Writer* writer, int idx, int depth)
        {
            if (depth > max_depth)
                luaL_error(L, "nested too depth");

            if (!lua_checkstack(L, 4)) // requires at least 4 slots in stack: table, key, value, key
                luaL_error(L, "stack overflow");

            lua_pushvalue(L, idx);
            if (values::isarray(L, -1))
            {
                encodeArray(L, writer, depth);
                lua_pop(L, 1);
                return;
            }

            // is object.
            if (!sort_keys)
            {
                encodeObject(L, writer, depth);
                lua_pop(L, 1);
                return;
            }

            lua_pushnil(L);
            std::vector<Key> keys;

            while (lua_next(L, -2))
            {


                if (lua_type(L, -2) == LUA_TSTRING)
                {
                    size_t len = 0;
                    auto key = lua_tolstring(L, -2, &len);
                    keys.push_back(Key(key, static_cast<SizeType>(len)));
                }

                // pop value, leaving original key
                lua_pop(L, 1);

            }

            encodeObject(L, writer, depth, keys);
            lua_pop(L, 1);
        }

    template<typename Writer>
        void encodeObject(lua_State* L, Writer* writer, int depth)
        {
            writer->StartObject();


            lua_pushnil(L);
            while (lua_next(L, -2))
            {

                if (lua_type(L, -2) == LUA_TSTRING)
                {
                    size_t len = 0;
                    auto key = lua_tolstring(L, -2, &len);
                    writer->Key(key, static_cast<SizeType>(len));
                    encodeValue(L, writer, -1, depth);
                }

                // pop value, leaving original key
                lua_pop(L, 1);

            }

            writer->EndObject();
        }

    template<typename Writer>
        void encodeObject(lua_State* L, Writer* writer, int depth, std::vector<Key> &keys)
        {

            writer->StartObject();
            std::sort(keys.begin(), keys.end());

            std::vector<Key>::const_iterator i = keys.begin();
            std::vector<Key>::const_iterator e = keys.end();
            for ( auto const& i : keys )
            {
                writer->Key(i.key, static_cast<SizeType>(i.size));
                lua_pushlstring(L, i.key, i.size);
                lua_gettable(L, -2);
                encodeValue(L, writer, -1, depth);
                lua_pop(L, 1);
            }

            writer->EndObject();
        }

    template<typename Writer>
        void encodeArray(lua_State* L, Writer* writer, int depth)
        {

            writer->StartArray();
            auto MAX = static_cast<int>(luax::rawlen(L, -1)); // lua_rawlen always returns value >= 0
            for (auto n = 1; n <= MAX; ++n)
            {
                lua_rawgeti(L, -1, n);
                encodeValue(L, writer, -1, depth);
                lua_pop(L, 1);
            }
            writer->EndArray();

        }

    public:
    template<typename Stream>
        void encode(lua_State* L, Stream* s, int idx)
        {
            if (pretty)
            {
                PrettyWriter<Stream> writer(*s);
                encodeValue(L, &writer, idx);
            }
            else
            {
                Writer<Stream> writer(*s);
                encodeValue(L, &writer, idx);
            }
        }
};

static int json_encode(lua_State* L)
{
    try
    {
        Encoder encode(L, 2);
        StringBuffer s;
        encode.encode(L, &s, 1);
        lua_pushlstring(L, s.GetString(), s.GetSize());
        return 1;
    }
    catch (...)
    {
        luaL_error(L, "error while encoding");
    }
    return 0;
}

static int json_dump(lua_State* L)
{
    Encoder encoder(L, 3);

    auto filename = luaL_checkstring(L, 2);
    auto fp = file::open(filename, "wb");
    if (fp == nullptr)
        luaL_error(L, "error while open file: %s", filename);

    char buffer[512];
    FileWriteStream fs(fp, buffer, sizeof(buffer));
    encoder.encode(L, &fs, 1);
    fclose(fp);
    return 0;
}

namespace values
{
    static auto nullref = LUA_NOREF;
    /**
     * Returns rapidjson.null.
     */
    int json_null(lua_State* L)
    {
        lua_rawgeti(L, LUA_REGISTRYINDEX, nullref);
        return 1;
    }
}

static const luaL_Reg methods[] =
{
    // string <--> lua table
    { "decode", json_decode },
    { "encode", json_encode },

    // file <--> lua table
    { "load", json_load },
    { "dump", json_dump },

    // special tags and functions
    { "null", values::json_null },
    { "object", json_object },
    { "array", json_array },

    // JSON types
    { "Document", Userdata<Document>::create },
    { "SchemaDocument", Userdata<SchemaDocument>::create },
    { "SchemaValidator", Userdata<SchemaValidator>::create },

    {nullptr, nullptr }
};

extern "C"
{
    LUALIB_API int luaopen_rapidjson(lua_State* L)
    {
        lua_newtable(L);

        luax::setfuncs(L, methods);

        lua_pushliteral(L, "rapidjson");
        lua_setfield(L, -2, "_NAME");

        lua_pushliteral(L, LUA_RAPIDJSON_VERSION);
        lua_setfield(L, -2, "_VERSION");

        lua_getfield(L, -1, "null");
        values::nullref = luaL_ref(L, LUA_REGISTRYINDEX);


        createSharedMeta(L, "json.object", "object");
        createSharedMeta(L, "json.array", "array");

        Userdata<Document>::luaopen(L);
        Userdata<SchemaDocument>::luaopen(L);
        Userdata<SchemaValidator>::luaopen(L);

        return 1;
    }
}