rev |
line source |
jbe@121
|
1 #include <lua.h>
|
jbe@121
|
2 #include <lauxlib.h>
|
jbe@122
|
3 #include <stdlib.h>
|
jbe@121
|
4 #include <string.h>
|
jbe@154
|
5 #include <math.h>
|
jbe@121
|
6
|
jbe@144
|
7 // maximum number of nested JSON values (objects and arrays):
|
jbe@150
|
8 // NOTE: The Lua reference states that the stack may typically contain at least
|
jbe@150
|
9 // "a few thousand elements". Since every nested level consumes
|
jbe@150
|
10 // 3 elements on the Lua stack (the object/array, its shadow table,
|
jbe@150
|
11 // a string key or a placeholder), we limit the number of nested levels
|
jbe@150
|
12 // to 500. If a stack overflow would still happen in the import function,
|
jbe@150
|
13 // this is detected nevertheless and an error is thrown (instead of
|
jbe@150
|
14 // returning nil and an error string).
|
jbe@150
|
15 #define JSON_MAXDEPTH 500
|
jbe@142
|
16
|
jbe@155
|
17 // generate dummy memory addresses that represents null values:
|
jbe@155
|
18 char json_nullmark;
|
jbe@155
|
19 #define json_isnullmark(L, i) (lua_touserdata((L), (i)) == &json_nullmark)
|
jbe@155
|
20 #define json_pushnullmark(L) lua_pushlightuserdata((L), &json_nullmark)
|
jbe@155
|
21
|
jbe@144
|
22 // macros for usage of Lua registry:
|
jbe@144
|
23 #define JSON_REGENT char
|
jbe@145
|
24 #define JSON_REGPOINTER void *
|
jbe@145
|
25 #define json_regpointer(x) (&json_registry.x)
|
jbe@151
|
26 #define json_regfetchpointer(L, x) lua_rawgetp((L), LUA_REGISTRYINDEX, (x))
|
jbe@151
|
27 #define json_regfetch(L, x) json_regfetchpointer(L, json_regpointer(x))
|
jbe@151
|
28 #define json_regstore(L, x) lua_rawsetp(L, LUA_REGISTRYINDEX, json_regpointer(x))
|
jbe@145
|
29
|
jbe@144
|
30 // generate dummy memory addresses that represent Lua objects
|
jbe@145
|
31 // via lightuserdata keys and LUA_REGISTRYINDEX:
|
jbe@144
|
32 static struct {
|
jbe@145
|
33 JSON_REGENT shadowtbl; // ephemeron table that maps tables to their corresponding shadow table
|
jbe@145
|
34 JSON_REGENT objectmt; // metatable for JSON objects
|
jbe@145
|
35 JSON_REGENT arraymt; // metatable for JSON arrays
|
jbe@144
|
36 } json_registry;
|
jbe@138
|
37
|
jbe@157
|
38 // returns the string "<JSON null marker>":
|
jbe@157
|
39 static int json_nullmark_tostring(lua_State *L) {
|
jbe@157
|
40 lua_pushliteral(L, "<JSON null marker>");
|
jbe@157
|
41 return 1;
|
jbe@157
|
42 }
|
jbe@157
|
43
|
jbe@145
|
44 // marks a Lua table as JSON object or JSON array:
|
jbe@136
|
45 // (returns its modified argument or a new table if argument is nil)
|
jbe@145
|
46 static int json_mark(lua_State *L, JSON_REGPOINTER mt) {
|
jbe@145
|
47 // check if argument is nil
|
jbe@136
|
48 if (lua_isnoneornil(L, 1)) {
|
jbe@145
|
49 // create new table at stack position 1:
|
jbe@136
|
50 lua_settop(L, 0);
|
jbe@136
|
51 lua_newtable(L);
|
jbe@145
|
52 // create shadow table (leaving previously created table on stack position 1):
|
jbe@144
|
53 json_regfetch(L, shadowtbl);
|
jbe@136
|
54 lua_pushvalue(L, 1);
|
jbe@136
|
55 lua_newtable(L);
|
jbe@143
|
56 lua_rawset(L, -3);
|
jbe@143
|
57 } else {
|
jbe@166
|
58 // require argument to be a table:
|
jbe@166
|
59 luaL_checktype(L, 1, LUA_TTABLE);
|
jbe@145
|
60 // push shadow table on top of stack:
|
jbe@144
|
61 json_regfetch(L, shadowtbl);
|
jbe@143
|
62 lua_pushvalue(L, 1);
|
jbe@143
|
63 lua_rawget(L, -2);
|
jbe@145
|
64 // if shadow table does not exist:
|
jbe@143
|
65 if (lua_isnil(L, -1)) {
|
jbe@145
|
66 // create shadow table and leave it on top of stack:
|
jbe@143
|
67 lua_newtable(L);
|
jbe@143
|
68 lua_pushvalue(L, 1);
|
jbe@143
|
69 lua_pushvalue(L, -2);
|
jbe@143
|
70 lua_rawset(L, -5);
|
jbe@143
|
71 }
|
jbe@145
|
72 // move elements from original table to shadow table (that's expected on top of stack):
|
jbe@143
|
73 for(lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
|
jbe@143
|
74 lua_pushvalue(L, -2);
|
jbe@143
|
75 lua_pushnil(L);
|
jbe@143
|
76 lua_rawset(L, 1);
|
jbe@143
|
77 lua_pushvalue(L, -2);
|
jbe@143
|
78 lua_pushvalue(L, -2);
|
jbe@143
|
79 lua_rawset(L, -5);
|
jbe@143
|
80 }
|
jbe@136
|
81 }
|
jbe@138
|
82 // discard everything but table to return:
|
jbe@138
|
83 lua_settop(L, 1);
|
jbe@136
|
84 // set metatable:
|
jbe@145
|
85 json_regfetchpointer(L, mt);
|
jbe@136
|
86 lua_setmetatable(L, 1);
|
jbe@138
|
87 // return table:
|
jbe@136
|
88 return 1;
|
jbe@136
|
89 }
|
jbe@136
|
90
|
jbe@136
|
91 // marks a table as JSON object:
|
jbe@136
|
92 // (returns its modified argument or a new table if argument is nil)
|
jbe@136
|
93 static int json_object(lua_State *L) {
|
jbe@145
|
94 return json_mark(L, json_regpointer(objectmt));
|
jbe@136
|
95 }
|
jbe@136
|
96
|
jbe@136
|
97 // marks a table as JSON array:
|
jbe@136
|
98 // (returns its modified argument or a new table if argument is nil)
|
jbe@136
|
99 static int json_array(lua_State *L) {
|
jbe@145
|
100 return json_mark(L, json_regpointer(arraymt));
|
jbe@136
|
101 }
|
jbe@136
|
102
|
jbe@167
|
103 #define json_utf16_surrogate(x) ((x) >= 0xD800 && (x) <= 0xDFFF)
|
jbe@167
|
104 #define json_utf16_lead(x) ((x) >= 0xD800 && (x) <= 0xDBFF)
|
jbe@167
|
105 #define json_utf16_tail(x) ((x) >= 0xDC00 && (x) <= 0xDFFF)
|
jbe@167
|
106
|
jbe@145
|
107 // internal states of JSON parser:
|
jbe@124
|
108 #define JSON_STATE_VALUE 0
|
jbe@124
|
109 #define JSON_STATE_OBJECT_KEY 1
|
jbe@124
|
110 #define JSON_STATE_OBJECT_KEY_TERMINATOR 2
|
jbe@124
|
111 #define JSON_STATE_OBJECT_VALUE 3
|
jbe@124
|
112 #define JSON_STATE_OBJECT_SEPARATOR 4
|
jbe@124
|
113 #define JSON_STATE_ARRAY_VALUE 5
|
jbe@124
|
114 #define JSON_STATE_ARRAY_SEPARATOR 6
|
jbe@124
|
115 #define JSON_STATE_END 7
|
jbe@121
|
116
|
jbe@145
|
117 // special Lua stack indicies for json_import function:
|
jbe@138
|
118 #define json_import_objectmt_idx 2
|
jbe@138
|
119 #define json_import_arraymt_idx 3
|
jbe@138
|
120 #define json_import_shadowtbl_idx 4
|
jbe@138
|
121
|
jbe@167
|
122 // macro for hex decoding:
|
jbe@167
|
123 #define json_import_readhex(x) \
|
jbe@167
|
124 do { \
|
jbe@167
|
125 x = 0; \
|
jbe@167
|
126 for (i=0; i<4; i++) { \
|
jbe@167
|
127 x <<= 4; \
|
jbe@167
|
128 c = str[pos++]; \
|
jbe@167
|
129 if (c >= '0' && c <= '9') x += c - '0'; \
|
jbe@167
|
130 else if (c >= 'A' && c <= 'F') x += c - 'A' + 10; \
|
jbe@167
|
131 else if (c >= 'a' && c <= 'f') x += c - 'a' + 10; \
|
jbe@167
|
132 else if (c == 0) goto json_import_unexpected_eof; \
|
jbe@167
|
133 else goto json_import_unexpected_escape; \
|
jbe@167
|
134 } \
|
jbe@167
|
135 } while (0)
|
jbe@167
|
136
|
jbe@136
|
137 // decodes a JSON document:
|
jbe@121
|
138 static int json_import(lua_State *L) {
|
jbe@167
|
139 int i; // loop variable
|
jbe@136
|
140 const char *str; // string to parse
|
jbe@136
|
141 size_t total; // total length of string to parse
|
jbe@136
|
142 size_t pos = 0; // current position in string to parse
|
jbe@136
|
143 size_t level = 0; // nested levels of objects/arrays currently being processed
|
jbe@145
|
144 int mode = JSON_STATE_VALUE; // state of parser (i.e. "what's expected next?")
|
jbe@136
|
145 char c; // variable to store a single character to be processed
|
jbe@145
|
146 luaL_Buffer luabuf; // Lua buffer to decode JSON string values
|
jbe@145
|
147 char *cbuf; // C buffer to decode JSON string values
|
jbe@162
|
148 size_t outlen; // maximum length or write position of C buffer
|
jbe@167
|
149 long codepoint; // decoded UTF-16 character or higher codepoint
|
jbe@167
|
150 long utf16tail; // second decoded UTF-16 character (surrogate tail)
|
jbe@152
|
151 size_t arraylen; // variable to temporarily store the array length
|
jbe@166
|
152 // require string as argument and convert to C string with length information:
|
jbe@166
|
153 str = luaL_checklstring(L, 1, &total);
|
jbe@166
|
154 // if string contains a NULL byte, this is a syntax error
|
jbe@166
|
155 if (strlen(str) != total) goto json_import_syntax_error;
|
jbe@147
|
156 // stack shall contain one function argument:
|
jbe@138
|
157 lua_settop(L, 1);
|
jbe@147
|
158 // push objectmt onto stack position 2:
|
jbe@144
|
159 json_regfetch(L, objectmt);
|
jbe@147
|
160 // push arraymt onto stack position 3:
|
jbe@144
|
161 json_regfetch(L, arraymt);
|
jbe@147
|
162 // push shadowtbl onto stack position 4:
|
jbe@144
|
163 json_regfetch(L, shadowtbl);
|
jbe@136
|
164 // main loop of parser:
|
jbe@136
|
165 json_import_loop:
|
jbe@136
|
166 // skip whitespace and store next character in variable 'c':
|
jbe@146
|
167 while (c = str[pos],
|
jbe@146
|
168 c == ' ' ||
|
jbe@146
|
169 c == '\f' ||
|
jbe@146
|
170 c == '\n' ||
|
jbe@146
|
171 c == '\r' ||
|
jbe@146
|
172 c == '\t' ||
|
jbe@146
|
173 c == '\v'
|
jbe@146
|
174 ) pos++;
|
jbe@136
|
175 // switch statement to handle certain (single) characters:
|
jbe@121
|
176 switch (c) {
|
jbe@136
|
177 // handle end of JSON document:
|
jbe@121
|
178 case 0:
|
jbe@136
|
179 // if end of JSON document was expected, then return top element of stack as result:
|
jbe@124
|
180 if (mode == JSON_STATE_END) return 1;
|
jbe@136
|
181 // otherwise, the JSON document was malformed:
|
jbe@167
|
182 if (level == 0) {
|
jbe@167
|
183 lua_pushnil(L);
|
jbe@167
|
184 lua_pushliteral(L, "Empty string");
|
jbe@167
|
185 } else {
|
jbe@167
|
186 json_import_unexpected_eof:
|
jbe@167
|
187 lua_pushnil(L);
|
jbe@167
|
188 lua_pushliteral(L, "Unexpected end of JSON document");
|
jbe@167
|
189 }
|
jbe@121
|
190 return 2;
|
jbe@136
|
191 // new JSON object:
|
jbe@121
|
192 case '{':
|
jbe@136
|
193 // if a JSON object is not expected here, then return an error:
|
jbe@146
|
194 if (
|
jbe@146
|
195 mode != JSON_STATE_VALUE &&
|
jbe@146
|
196 mode != JSON_STATE_OBJECT_VALUE &&
|
jbe@146
|
197 mode != JSON_STATE_ARRAY_VALUE
|
jbe@146
|
198 ) goto json_import_syntax_error;
|
jbe@136
|
199 // create JSON object on stack:
|
jbe@136
|
200 lua_newtable(L);
|
jbe@136
|
201 // set metatable of JSON object:
|
jbe@138
|
202 lua_pushvalue(L, json_import_objectmt_idx);
|
jbe@125
|
203 lua_setmetatable(L, -2);
|
jbe@136
|
204 // create internal shadow table on stack:
|
jbe@136
|
205 lua_newtable(L);
|
jbe@146
|
206 // register internal shadow table:
|
jbe@123
|
207 lua_pushvalue(L, -2);
|
jbe@123
|
208 lua_pushvalue(L, -2);
|
jbe@138
|
209 lua_rawset(L, json_import_shadowtbl_idx);
|
jbe@146
|
210 // expect object key (or end of object) to follow:
|
jbe@136
|
211 mode = JSON_STATE_OBJECT_KEY;
|
jbe@146
|
212 // jump to common code for opening JSON object and JSON array:
|
jbe@142
|
213 goto json_import_open;
|
jbe@136
|
214 // new JSON array:
|
jbe@121
|
215 case '[':
|
jbe@136
|
216 // if a JSON array is not expected here, then return an error:
|
jbe@146
|
217 if (
|
jbe@146
|
218 mode != JSON_STATE_VALUE &&
|
jbe@146
|
219 mode != JSON_STATE_OBJECT_VALUE &&
|
jbe@146
|
220 mode != JSON_STATE_ARRAY_VALUE
|
jbe@146
|
221 ) goto json_import_syntax_error;
|
jbe@136
|
222 // create JSON array on stack:
|
jbe@136
|
223 lua_newtable(L);
|
jbe@136
|
224 // set metatable of JSON array:
|
jbe@138
|
225 lua_pushvalue(L, json_import_arraymt_idx);
|
jbe@125
|
226 lua_setmetatable(L, -2);
|
jbe@136
|
227 // create internal shadow table on stack:
|
jbe@136
|
228 lua_newtable(L);
|
jbe@146
|
229 // register internal shadow table:
|
jbe@123
|
230 lua_pushvalue(L, -2);
|
jbe@123
|
231 lua_pushvalue(L, -2);
|
jbe@138
|
232 lua_rawset(L, json_import_shadowtbl_idx);
|
jbe@140
|
233 // add nil as key (needed to keep stack balance) and as magic to detect arrays:
|
jbe@140
|
234 lua_pushnil(L);
|
jbe@146
|
235 // expect array value (or end of array) to follow:
|
jbe@142
|
236 mode = JSON_STATE_ARRAY_VALUE;
|
jbe@142
|
237 // continue with common code for opening JSON object and JSON array:
|
jbe@146
|
238 // common code for opening JSON object or JSON array:
|
jbe@142
|
239 json_import_open:
|
jbe@142
|
240 // limit nested levels:
|
jbe@142
|
241 if (level >= JSON_MAXDEPTH) {
|
jbe@142
|
242 lua_pushnil(L);
|
jbe@164
|
243 lua_pushfstring(L, "More than %d nested JSON levels", JSON_MAXDEPTH);
|
jbe@142
|
244 return 2;
|
jbe@142
|
245 }
|
jbe@142
|
246 // additional buffer overflow protection:
|
jbe@142
|
247 if (!lua_checkstack(L, LUA_MINSTACK))
|
jbe@142
|
248 return luaL_error(L, "Caught stack overflow in JSON import function (too many nested levels and stack size too small)");
|
jbe@136
|
249 // increment level:
|
jbe@121
|
250 level++;
|
jbe@142
|
251 // consume input character:
|
jbe@142
|
252 pos++;
|
jbe@121
|
253 goto json_import_loop;
|
jbe@136
|
254 // end of JSON object:
|
jbe@121
|
255 case '}':
|
jbe@136
|
256 // if end of JSON object is not expected here, then return an error:
|
jbe@146
|
257 if (
|
jbe@146
|
258 mode != JSON_STATE_OBJECT_KEY &&
|
jbe@146
|
259 mode != JSON_STATE_OBJECT_SEPARATOR
|
jbe@146
|
260 ) goto json_import_syntax_error;
|
jbe@136
|
261 // jump to common code for end of JSON object and JSON array:
|
jbe@121
|
262 goto json_import_close;
|
jbe@136
|
263 // end of JSON array:
|
jbe@121
|
264 case ']':
|
jbe@136
|
265 // if end of JSON array is not expected here, then return an error:
|
jbe@146
|
266 if (
|
jbe@146
|
267 mode != JSON_STATE_ARRAY_VALUE &&
|
jbe@146
|
268 mode != JSON_STATE_ARRAY_SEPARATOR
|
jbe@146
|
269 ) goto json_import_syntax_error;
|
jbe@146
|
270 // pop nil key/magic (that was needed to keep stack balance):
|
jbe@140
|
271 lua_pop(L, 1);
|
jbe@136
|
272 // continue with common code for end of JSON object and JSON array:
|
jbe@136
|
273 // common code for end of JSON object or JSON array:
|
jbe@121
|
274 json_import_close:
|
jbe@136
|
275 // consume input character:
|
jbe@121
|
276 pos++;
|
jbe@136
|
277 // pop shadow table:
|
jbe@136
|
278 lua_pop(L, 1);
|
jbe@136
|
279 // check if nested:
|
jbe@121
|
280 if (--level) {
|
jbe@146
|
281 // if nested,
|
jbe@146
|
282 // check if outer(!) structure is an array or object:
|
jbe@140
|
283 if (lua_isnil(L, -2)) {
|
jbe@136
|
284 // select array value processing:
|
jbe@124
|
285 mode = JSON_STATE_ARRAY_VALUE;
|
jbe@121
|
286 } else {
|
jbe@136
|
287 // select object value processing:
|
jbe@124
|
288 mode = JSON_STATE_OBJECT_VALUE;
|
jbe@121
|
289 }
|
jbe@136
|
290 // store value in outer structure:
|
jbe@121
|
291 goto json_import_process_value;
|
jbe@121
|
292 }
|
jbe@136
|
293 // if not nested, then expect end of JSON document and continue with loop:
|
jbe@136
|
294 mode = JSON_STATE_END;
|
jbe@121
|
295 goto json_import_loop;
|
jbe@136
|
296 // key terminator:
|
jbe@121
|
297 case ':':
|
jbe@136
|
298 // if key terminator is not expected here, then return an error:
|
jbe@124
|
299 if (mode != JSON_STATE_OBJECT_KEY_TERMINATOR)
|
jbe@121
|
300 goto json_import_syntax_error;
|
jbe@136
|
301 // consume input character:
|
jbe@121
|
302 pos++;
|
jbe@146
|
303 // expect object value to follow:
|
jbe@124
|
304 mode = JSON_STATE_OBJECT_VALUE;
|
jbe@146
|
305 // continue with loop:
|
jbe@121
|
306 goto json_import_loop;
|
jbe@136
|
307 // value terminator (NOTE: trailing comma at end of value or key-value list is tolerated by this parser)
|
jbe@121
|
308 case ',':
|
jbe@146
|
309 // branch according to parser state:
|
jbe@124
|
310 if (mode == JSON_STATE_OBJECT_SEPARATOR) {
|
jbe@146
|
311 // expect an object key to follow:
|
jbe@124
|
312 mode = JSON_STATE_OBJECT_KEY;
|
jbe@124
|
313 } else if (mode == JSON_STATE_ARRAY_SEPARATOR) {
|
jbe@146
|
314 // expect an array value to follow:
|
jbe@124
|
315 mode = JSON_STATE_ARRAY_VALUE;
|
jbe@121
|
316 } else {
|
jbe@136
|
317 // if value terminator is not expected here, then return an error:
|
jbe@136
|
318 goto json_import_syntax_error;
|
jbe@121
|
319 }
|
jbe@136
|
320 // consume input character:
|
jbe@121
|
321 pos++;
|
jbe@136
|
322 // continue with loop:
|
jbe@121
|
323 goto json_import_loop;
|
jbe@136
|
324 // string literal:
|
jbe@121
|
325 case '"':
|
jbe@146
|
326 // consume quote character:
|
jbe@146
|
327 pos++;
|
jbe@162
|
328 // find last character in input string:
|
jbe@162
|
329 outlen = pos;
|
jbe@162
|
330 while ((c = str[outlen]) != '"') {
|
jbe@161
|
331 // consume one character:
|
jbe@162
|
332 outlen++;
|
jbe@161
|
333 // handle unexpected end of JSON document:
|
jbe@161
|
334 if (c == 0) goto json_import_unexpected_eof;
|
jbe@161
|
335 // consume one extra character when encountering an escaped quote:
|
jbe@162
|
336 else if (c == '\\' && str[outlen] == '"') outlen++;
|
jbe@161
|
337 }
|
jbe@162
|
338 // determine buffer length:
|
jbe@162
|
339 outlen -= pos;
|
jbe@161
|
340 // check if string is non empty:
|
jbe@162
|
341 if (outlen) {
|
jbe@161
|
342 // prepare buffer to decode string (with maximum possible length) and set write position to zero:
|
jbe@162
|
343 cbuf = luaL_buffinitsize(L, &luabuf, outlen);
|
jbe@162
|
344 outlen = 0;
|
jbe@161
|
345 // loop through the characters until encountering end quote:
|
jbe@161
|
346 while ((c = str[pos++]) != '"') {
|
jbe@162
|
347 // NOTE: unexpected end cannot happen anymore
|
jbe@162
|
348 if (c < 32 || c == 127) {
|
jbe@161
|
349 // do not allow ASCII control characters:
|
jbe@161
|
350 // NOTE: illegal UTF-8 sequences and extended control characters are not sanitized
|
jbe@161
|
351 // by this parser to allow different encodings than Unicode
|
jbe@161
|
352 lua_pushnil(L);
|
jbe@161
|
353 lua_pushliteral(L, "Unexpected control character in JSON string");
|
jbe@161
|
354 return 2;
|
jbe@161
|
355 } else if (c == '\\') {
|
jbe@161
|
356 // read next char after backslash escape:
|
jbe@161
|
357 c = str[pos++];
|
jbe@161
|
358 switch (c) {
|
jbe@161
|
359 // unexpected end-of-string:
|
jbe@161
|
360 case 0:
|
jbe@161
|
361 goto json_import_unexpected_eof;
|
jbe@161
|
362 // unescaping of quotation mark, slash, and backslash:
|
jbe@161
|
363 case '"':
|
jbe@161
|
364 case '/':
|
jbe@161
|
365 case '\\':
|
jbe@162
|
366 cbuf[outlen++] = c;
|
jbe@161
|
367 break;
|
jbe@161
|
368 // unescaping of backspace:
|
jbe@162
|
369 case 'b': cbuf[outlen++] = '\b'; break;
|
jbe@161
|
370 // unescaping of form-feed:
|
jbe@162
|
371 case 'f': cbuf[outlen++] = '\f'; break;
|
jbe@161
|
372 // unescaping of new-line:
|
jbe@162
|
373 case 'n': cbuf[outlen++] = '\n'; break;
|
jbe@161
|
374 // unescaping of carriage-return:
|
jbe@162
|
375 case 'r': cbuf[outlen++] = '\r'; break;
|
jbe@161
|
376 // unescaping of tabulator:
|
jbe@162
|
377 case 't': cbuf[outlen++] = '\t'; break;
|
jbe@161
|
378 // unescaping of UTF-16 characters
|
jbe@161
|
379 case 'u':
|
jbe@167
|
380 // decode 4 hex nibbles:
|
jbe@167
|
381 json_import_readhex(codepoint);
|
jbe@167
|
382 // handle surrogate character:
|
jbe@167
|
383 if (json_utf16_surrogate(codepoint)) {
|
jbe@167
|
384 // check if first surrogate is in valid range:
|
jbe@167
|
385 if (json_utf16_lead(codepoint)) {
|
jbe@167
|
386 // require second surrogate:
|
jbe@167
|
387 if ((c = str[pos++]) != '\\' || (c = str[pos++]) != 'u') {
|
jbe@167
|
388 if (c == 0) goto json_import_unexpected_eof;
|
jbe@167
|
389 else goto json_import_wrong_surrogate;
|
jbe@167
|
390 }
|
jbe@167
|
391 // read 4 hex nibbles of second surrogate character:
|
jbe@167
|
392 json_import_readhex(utf16tail);
|
jbe@167
|
393 // check if second surrogate is in valid range:
|
jbe@167
|
394 if (!json_utf16_tail(utf16tail)) goto json_import_wrong_surrogate;
|
jbe@167
|
395 // calculate codepoint:
|
jbe@167
|
396 codepoint = 0x10000 + (utf16tail - 0xDC00) + (codepoint - 0xD800) * 0x400;
|
jbe@167
|
397 } else {
|
jbe@167
|
398 // throw error for wrong surrogates:
|
jbe@167
|
399 json_import_wrong_surrogate:
|
jbe@167
|
400 lua_pushnil(L);
|
jbe@167
|
401 lua_pushliteral(L, "Illegal UTF-16 surrogate in JSON string escape sequence");
|
jbe@167
|
402 return 2;
|
jbe@167
|
403 }
|
jbe@167
|
404 }
|
jbe@167
|
405 // encode as UTF-8:
|
jbe@167
|
406 if (codepoint < 0x80) {
|
jbe@167
|
407 cbuf[outlen++] = (char)codepoint;
|
jbe@167
|
408 } else if (codepoint < 0x800) {
|
jbe@167
|
409 cbuf[outlen++] = (char)(0xc0 | (codepoint >> 6));
|
jbe@167
|
410 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
|
jbe@167
|
411 } else if (codepoint < 0x10000) {
|
jbe@167
|
412 cbuf[outlen++] = (char)(0xe0 | (codepoint >> 12));
|
jbe@167
|
413 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
|
jbe@167
|
414 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
|
jbe@167
|
415 } else {
|
jbe@167
|
416 cbuf[outlen++] = (char)(0xf0 | (codepoint >> 18));
|
jbe@167
|
417 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 12) & 0x3f));
|
jbe@167
|
418 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
|
jbe@167
|
419 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
|
jbe@167
|
420 }
|
jbe@167
|
421 break;
|
jbe@161
|
422 // unexpected escape sequence:
|
jbe@161
|
423 default:
|
jbe@167
|
424 json_import_unexpected_escape:
|
jbe@161
|
425 lua_pushnil(L);
|
jbe@161
|
426 lua_pushliteral(L, "Unexpected string escape sequence in JSON document");
|
jbe@161
|
427 return 2;
|
jbe@161
|
428 }
|
jbe@161
|
429 } else {
|
jbe@161
|
430 // normal character:
|
jbe@162
|
431 cbuf[outlen++] = c;
|
jbe@121
|
432 }
|
jbe@121
|
433 }
|
jbe@161
|
434 // process buffer to Lua string:
|
jbe@162
|
435 luaL_pushresultsize(&luabuf, outlen);
|
jbe@161
|
436 } else {
|
jbe@161
|
437 // if JSON string is empty,
|
jbe@161
|
438 // push empty Lua string:
|
jbe@161
|
439 lua_pushliteral(L, "");
|
jbe@167
|
440 // consume closing quote:
|
jbe@167
|
441 pos++;
|
jbe@121
|
442 }
|
jbe@136
|
443 // continue with processing of decoded string:
|
jbe@121
|
444 goto json_import_process_value;
|
jbe@121
|
445 }
|
jbe@136
|
446 // process values whose type is is not deducible from a single character:
|
jbe@136
|
447 if ((c >= '0' && c <= '9') || c == '-' || c == '+') {
|
jbe@146
|
448 // for numbers,
|
jbe@146
|
449 // use strtod() call to parse a (double precision) floating point number:
|
jbe@167
|
450 double numval;
|
jbe@122
|
451 char *endptr;
|
jbe@122
|
452 numval = strtod(str+pos, &endptr);
|
jbe@146
|
453 // catch parsing errors:
|
jbe@122
|
454 if (endptr == str+pos) goto json_import_syntax_error;
|
jbe@146
|
455 // consume characters that were parsed:
|
jbe@122
|
456 pos += endptr - (str+pos);
|
jbe@146
|
457 // push parsed (double precision) floating point number on Lua stack:
|
jbe@122
|
458 lua_pushnumber(L, numval);
|
jbe@122
|
459 } else if (!strncmp(str+pos, "true", 4)) {
|
jbe@136
|
460 // consume 4 input characters for "true":
|
jbe@121
|
461 pos += 4;
|
jbe@147
|
462 // put Lua true value onto stack:
|
jbe@136
|
463 lua_pushboolean(L, 1);
|
jbe@121
|
464 } else if (!strncmp(str+pos, "false", 5)) {
|
jbe@136
|
465 // consume 5 input characters for "false":
|
jbe@121
|
466 pos += 5;
|
jbe@147
|
467 // put Lua false value onto stack:
|
jbe@136
|
468 lua_pushboolean(L, 0);
|
jbe@121
|
469 } else if (!strncmp(str+pos, "null", 4)) {
|
jbe@136
|
470 // consume 4 input characters for "null":
|
jbe@136
|
471 pos += 4;
|
jbe@153
|
472 // different behavor for top-level and sub-levels:
|
jbe@153
|
473 if (level) {
|
jbe@153
|
474 // if sub-level,
|
jbe@153
|
475 // push special null-marker onto stack:
|
jbe@155
|
476 json_pushnullmark(L);
|
jbe@153
|
477 } else {
|
jbe@153
|
478 // if top-level,
|
jbe@153
|
479 // push nil onto stack:
|
jbe@153
|
480 lua_pushnil(L);
|
jbe@153
|
481 }
|
jbe@121
|
482 } else {
|
jbe@136
|
483 // all other cases are a syntax error:
|
jbe@121
|
484 goto json_import_syntax_error;
|
jbe@121
|
485 }
|
jbe@136
|
486 // process a decoded value or key value pair (expected on top of Lua stack):
|
jbe@136
|
487 json_import_process_value:
|
jbe@121
|
488 switch (mode) {
|
jbe@136
|
489 // an object key has been read:
|
jbe@124
|
490 case JSON_STATE_OBJECT_KEY:
|
jbe@136
|
491 // if an object key is not a string, then this is a syntax error:
|
jbe@121
|
492 if (lua_type(L, -1) != LUA_TSTRING) goto json_import_syntax_error;
|
jbe@146
|
493 // expect key terminator to follow:
|
jbe@124
|
494 mode = JSON_STATE_OBJECT_KEY_TERMINATOR;
|
jbe@146
|
495 // continue with loop:
|
jbe@121
|
496 goto json_import_loop;
|
jbe@136
|
497 // a key value pair has been read:
|
jbe@124
|
498 case JSON_STATE_OBJECT_VALUE:
|
jbe@136
|
499 // store key value pair in outer shadow table:
|
jbe@130
|
500 lua_rawset(L, -3);
|
jbe@146
|
501 // expect value terminator (or end of object) to follow:
|
jbe@124
|
502 mode = JSON_STATE_OBJECT_SEPARATOR;
|
jbe@146
|
503 // continue with loop:
|
jbe@121
|
504 goto json_import_loop;
|
jbe@136
|
505 // an array value has been read:
|
jbe@124
|
506 case JSON_STATE_ARRAY_VALUE:
|
jbe@152
|
507 // get current array length:
|
jbe@152
|
508 arraylen = lua_rawlen(L, -3);
|
jbe@152
|
509 // throw error if array would exceed INT_MAX elements:
|
jbe@152
|
510 // TODO: Lua 5.3 may support more elements
|
jbe@152
|
511 if (arraylen >= INT_MAX) {
|
jbe@152
|
512 lua_pushnil(L);
|
jbe@152
|
513 lua_pushfstring(L, "Array exceeded length of %d elements", INT_MAX);
|
jbe@152
|
514 }
|
jbe@136
|
515 // store value in outer shadow table:
|
jbe@152
|
516 lua_rawseti(L, -3, arraylen + 1);
|
jbe@146
|
517 // expect value terminator (or end of object) to follow:
|
jbe@124
|
518 mode = JSON_STATE_ARRAY_SEPARATOR;
|
jbe@146
|
519 // continue with loop
|
jbe@121
|
520 goto json_import_loop;
|
jbe@136
|
521 // a single value has been read:
|
jbe@124
|
522 case JSON_STATE_VALUE:
|
jbe@136
|
523 // leave value on top of stack, expect end of JSON document, and continue with loop:
|
jbe@124
|
524 mode = JSON_STATE_END;
|
jbe@121
|
525 goto json_import_loop;
|
jbe@121
|
526 }
|
jbe@146
|
527 // syntax error handling (reachable by goto statement):
|
jbe@136
|
528 json_import_syntax_error:
|
jbe@121
|
529 lua_pushnil(L);
|
jbe@121
|
530 lua_pushliteral(L, "Syntax error in JSON document");
|
jbe@121
|
531 return 2;
|
jbe@121
|
532 }
|
jbe@121
|
533
|
jbe@146
|
534 // special Lua stack indicies for json_path function:
|
jbe@138
|
535 #define json_path_shadowtbl_idx 1
|
jbe@146
|
536
|
jbe@146
|
537 // stack offset of arguments to json_path function:
|
jbe@155
|
538 #define json_path_idxshift 1
|
jbe@138
|
539
|
jbe@146
|
540 // gets a value or its type from a JSON document (passed as first argument)
|
jbe@147
|
541 // using a path (passed as variable number of keys after first argument):
|
jbe@137
|
542 static int json_path(lua_State *L, int type_mode) {
|
jbe@146
|
543 int stacktop; // stack index of top of stack (after shifting)
|
jbe@146
|
544 int idx = 2 + json_path_idxshift; // stack index of current argument to process
|
jbe@148
|
545 // insert shadowtbl into stack at position 1 (shifting the arguments):
|
jbe@144
|
546 json_regfetch(L, shadowtbl);
|
jbe@138
|
547 lua_insert(L, 1);
|
jbe@146
|
548 // store stack index of top of stack:
|
jbe@138
|
549 stacktop = lua_gettop(L);
|
jbe@146
|
550 // use first argument as "current value" (stored on top of stack):
|
jbe@138
|
551 lua_pushvalue(L, 1 + json_path_idxshift);
|
jbe@146
|
552 // process each "path key" (2nd argument and following arguments):
|
jbe@138
|
553 while (idx <= stacktop) {
|
jbe@146
|
554 // if "current value" (on top of stack) is nil, then the path cannot be walked and nil is returned:
|
jbe@137
|
555 if (lua_isnil(L, -1)) return 1;
|
jbe@137
|
556 // try to get shadow table of "current value":
|
jbe@130
|
557 lua_pushvalue(L, -1);
|
jbe@138
|
558 lua_rawget(L, json_path_shadowtbl_idx);
|
jbe@126
|
559 if (lua_isnil(L, -1)) {
|
jbe@137
|
560 // if no shadow table is found,
|
jbe@130
|
561 if (lua_type(L, -1) == LUA_TTABLE) {
|
jbe@146
|
562 // and if "current value" is a table,
|
jbe@146
|
563 // drop nil from stack:
|
jbe@146
|
564 lua_pop(L, 1);
|
jbe@137
|
565 // get "next value" using the "path key":
|
jbe@130
|
566 lua_pushvalue(L, idx++);
|
jbe@130
|
567 lua_gettable(L, -2);
|
jbe@130
|
568 } else {
|
jbe@137
|
569 // if "current value" is not a table,
|
jbe@146
|
570 // then the path cannot be walked and nil (already on top of stack) is returned:
|
jbe@137
|
571 return 1;
|
jbe@130
|
572 }
|
jbe@130
|
573 } else {
|
jbe@137
|
574 // if a shadow table is found,
|
jbe@137
|
575 // set "current value" to its shadow table:
|
jbe@130
|
576 lua_replace(L, -2);
|
jbe@137
|
577 // get "next value" using the "path key":
|
jbe@130
|
578 lua_pushvalue(L, idx++);
|
jbe@130
|
579 lua_rawget(L, -2);
|
jbe@126
|
580 }
|
jbe@137
|
581 // the "next value" replaces the "current value":
|
jbe@130
|
582 lua_replace(L, -2);
|
jbe@126
|
583 }
|
jbe@137
|
584 if (!type_mode) {
|
jbe@137
|
585 // if a value (and not its type) was requested,
|
jbe@137
|
586 // check if value is the null-marker, and store nil on top of Lua stack in that case:
|
jbe@155
|
587 if (json_isnullmark(L, -1)) lua_pushnil(L);
|
jbe@137
|
588 } else {
|
jbe@137
|
589 // if the type was requested,
|
jbe@137
|
590 // check if value is the null-marker:
|
jbe@155
|
591 if (json_isnullmark(L, -1)) {
|
jbe@137
|
592 // if yes, store string "null" on top of Lua stack:
|
jbe@130
|
593 lua_pushliteral(L, "null");
|
jbe@137
|
594 } else {
|
jbe@137
|
595 // otherwise,
|
jbe@138
|
596 // check if metatable indicates "object" or "array":
|
jbe@138
|
597 if (lua_getmetatable(L, -1)) {
|
jbe@144
|
598 json_regfetch(L, objectmt);
|
jbe@138
|
599 if (lua_rawequal(L, -2, -1)) {
|
jbe@146
|
600 // if value has metatable for JSON objects,
|
jbe@138
|
601 // return string "object":
|
jbe@138
|
602 lua_pushliteral(L, "object");
|
jbe@138
|
603 return 1;
|
jbe@138
|
604 }
|
jbe@144
|
605 json_regfetch(L, arraymt);
|
jbe@138
|
606 if (lua_rawequal(L, -3, -1)) {
|
jbe@146
|
607 // if value has metatable for JSON arrays,
|
jbe@146
|
608 // return string "object":
|
jbe@138
|
609 lua_pushliteral(L, "array");
|
jbe@138
|
610 return 1;
|
jbe@138
|
611 }
|
jbe@146
|
612 // remove 3 metatables (one of the value, two for comparison) from stack:
|
jbe@138
|
613 lua_pop(L, 3);
|
jbe@138
|
614 }
|
jbe@138
|
615 // otherwise, get the Lua type:
|
jbe@138
|
616 lua_pushstring(L, lua_typename(L, lua_type(L, -1)));
|
jbe@126
|
617 }
|
jbe@126
|
618 }
|
jbe@137
|
619 // return the top most value on the Lua stack:
|
jbe@137
|
620 return 1;
|
jbe@130
|
621 }
|
jbe@130
|
622
|
jbe@147
|
623 // gets a value from a JSON document (passed as first argument)
|
jbe@147
|
624 // using a path (passed as variable number of keys after first argument):
|
jbe@130
|
625 static int json_get(lua_State *L) {
|
jbe@137
|
626 return json_path(L, 0);
|
jbe@130
|
627 }
|
jbe@130
|
628
|
jbe@147
|
629 // gets a value's type from a JSON document (passed as first argument)
|
jbe@147
|
630 // using a path (variable number of keys after first argument):
|
jbe@130
|
631 static int json_type(lua_State *L) {
|
jbe@137
|
632 return json_path(L, 1);
|
jbe@130
|
633 }
|
jbe@130
|
634
|
jbe@147
|
635 // returns the length of a JSON array (or zero for a table without numeric keys):
|
jbe@130
|
636 static int json_len(lua_State *L) {
|
jbe@147
|
637 // stack shall contain one function argument:
|
jbe@130
|
638 lua_settop(L, 1);
|
jbe@148
|
639 // try to get corresponding shadow table for first argument:
|
jbe@144
|
640 json_regfetch(L, shadowtbl);
|
jbe@130
|
641 lua_pushvalue(L, 1);
|
jbe@138
|
642 lua_rawget(L, -2);
|
jbe@147
|
643 // if shadow table does not exist, return length of argument, else length of shadow table:
|
jbe@147
|
644 lua_pushnumber(L, lua_rawlen(L, lua_isnil(L, -1) ? 1 : -1));
|
jbe@123
|
645 return 1;
|
jbe@123
|
646 }
|
jbe@123
|
647
|
jbe@130
|
648 static int json_index(lua_State *L) {
|
jbe@148
|
649 // stack shall contain two function arguments:
|
jbe@130
|
650 lua_settop(L, 2);
|
jbe@155
|
651 // get corresponding shadow table for first argument:
|
jbe@144
|
652 json_regfetch(L, shadowtbl);
|
jbe@130
|
653 lua_pushvalue(L, 1);
|
jbe@155
|
654 lua_rawget(L, -2);
|
jbe@148
|
655 // throw error if no shadow table was found:
|
jbe@139
|
656 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
|
jbe@148
|
657 // use key passed as second argument to lookup value in shadow table:
|
jbe@130
|
658 lua_pushvalue(L, 2);
|
jbe@130
|
659 lua_rawget(L, -2);
|
jbe@148
|
660 // if value is null-marker, then push nil onto stack:
|
jbe@155
|
661 if (json_isnullmark(L, -1)) lua_pushnil(L);
|
jbe@148
|
662 // return either looked up value, or nil
|
jbe@127
|
663 return 1;
|
jbe@127
|
664 }
|
jbe@127
|
665
|
jbe@130
|
666 static int json_newindex(lua_State *L) {
|
jbe@148
|
667 // stack shall contain three function arguments:
|
jbe@130
|
668 lua_settop(L, 3);
|
jbe@148
|
669 // get corresponding shadow table for first argument:
|
jbe@144
|
670 json_regfetch(L, shadowtbl);
|
jbe@123
|
671 lua_pushvalue(L, 1);
|
jbe@143
|
672 lua_rawget(L, -2);
|
jbe@148
|
673 // throw error if no shadow table was found:
|
jbe@130
|
674 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
|
jbe@148
|
675 // replace first argument with shadow table:
|
jbe@130
|
676 lua_replace(L, 1);
|
jbe@148
|
677 // reset stack and use second and third argument to write to shadow table:
|
jbe@139
|
678 lua_settop(L, 3);
|
jbe@130
|
679 lua_rawset(L, 1);
|
jbe@148
|
680 // return nothing:
|
jbe@148
|
681 return 0;
|
jbe@121
|
682 }
|
jbe@121
|
683
|
jbe@135
|
684 static int json_pairs_iterfunc(lua_State *L) {
|
jbe@149
|
685 // stack shall contain two function arguments:
|
jbe@135
|
686 lua_settop(L, 2);
|
jbe@155
|
687 // get corresponding shadow table for first argument:
|
jbe@144
|
688 json_regfetch(L, shadowtbl);
|
jbe@135
|
689 lua_pushvalue(L, 1);
|
jbe@155
|
690 lua_rawget(L, -2);
|
jbe@149
|
691 // throw error if no shadow table was found:
|
jbe@135
|
692 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
|
jbe@149
|
693 // get next key value pair from shadow table (using previous key from argument 2)
|
jbe@149
|
694 // and return nothing if there is no next pair:
|
jbe@135
|
695 lua_pushvalue(L, 2);
|
jbe@135
|
696 if (!lua_next(L, -2)) return 0;
|
jbe@149
|
697 // replace null-marker with nil:
|
jbe@155
|
698 if (json_isnullmark(L, -1)) {
|
jbe@135
|
699 lua_pop(L, 1);
|
jbe@135
|
700 lua_pushnil(L);
|
jbe@135
|
701 }
|
jbe@149
|
702 // return key and value (or key and nil, if null-marker was found):
|
jbe@135
|
703 return 2;
|
jbe@135
|
704 }
|
jbe@135
|
705
|
jbe@149
|
706 // returns a triple such that 'for key, value in pairs(obj) do ... end'
|
jbe@149
|
707 // iterates through all key value pairs (including JSON null keys represented as Lua nil):
|
jbe@135
|
708 static int json_pairs(lua_State *L) {
|
jbe@149
|
709 // return triple of function json_pairs_iterfunc, first argument, and nil:
|
jbe@139
|
710 lua_pushcfunction(L, json_pairs_iterfunc);
|
jbe@135
|
711 lua_pushvalue(L, 1);
|
jbe@135
|
712 lua_pushnil(L);
|
jbe@135
|
713 return 3;
|
jbe@135
|
714 }
|
jbe@135
|
715
|
jbe@134
|
716 static int json_ipairs_iterfunc(lua_State *L) {
|
jbe@152
|
717 lua_Integer idx;
|
jbe@149
|
718 // stack shall contain two function arguments:
|
jbe@134
|
719 lua_settop(L, 2);
|
jbe@149
|
720 // calculate new index by incrementing second argument:
|
jbe@134
|
721 idx = lua_tointeger(L, 2) + 1;
|
jbe@149
|
722 // get corresponding shadow table for first argument:
|
jbe@155
|
723 json_regfetch(L, shadowtbl);
|
jbe@134
|
724 lua_pushvalue(L, 1);
|
jbe@155
|
725 lua_rawget(L, -2);
|
jbe@149
|
726 // throw error if no shadow table was found:
|
jbe@134
|
727 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
|
jbe@149
|
728 // do integer lookup in shadow table:
|
jbe@134
|
729 lua_rawgeti(L, -1, idx);
|
jbe@149
|
730 // return nothing if there was no value:
|
jbe@134
|
731 if (lua_isnil(L, -1)) return 0;
|
jbe@149
|
732 // return new index and
|
jbe@149
|
733 // either the looked up value if it is not equal to the null-marker
|
jbe@149
|
734 // or nil instead of null-marker:
|
jbe@134
|
735 lua_pushinteger(L, idx);
|
jbe@155
|
736 if (json_isnullmark(L, -2)) lua_pushnil(L);
|
jbe@134
|
737 else lua_pushvalue(L, -2);
|
jbe@134
|
738 return 2;
|
jbe@134
|
739 }
|
jbe@134
|
740
|
jbe@149
|
741 // returns a triple such that 'for idx, value in ipairs(ary) do ... end'
|
jbe@149
|
742 // iterates through all values (including JSON null represented as Lua nil):
|
jbe@134
|
743 static int json_ipairs(lua_State *L) {
|
jbe@149
|
744 // return triple of function json_ipairs_iterfunc, first argument, and zero:
|
jbe@139
|
745 lua_pushcfunction(L, json_ipairs_iterfunc);
|
jbe@134
|
746 lua_pushvalue(L, 1);
|
jbe@134
|
747 lua_pushinteger(L, 0);
|
jbe@134
|
748 return 3;
|
jbe@134
|
749 }
|
jbe@134
|
750
|
jbe@163
|
751 typedef struct {
|
jbe@163
|
752 size_t length;
|
jbe@163
|
753 const char *data;
|
jbe@163
|
754 } json_key_t;
|
jbe@163
|
755
|
jbe@163
|
756 static int json_key_cmp(json_key_t *key1, json_key_t *key2) {
|
jbe@163
|
757 size_t pos = 0;
|
jbe@163
|
758 unsigned char c1, c2;
|
jbe@163
|
759 while (1) {
|
jbe@163
|
760 if (key1->length > pos) {
|
jbe@163
|
761 if (key2->length > pos) {
|
jbe@163
|
762 c1 = key1->data[pos];
|
jbe@163
|
763 c2 = key2->data[pos];
|
jbe@163
|
764 if (c1 < c2) return -1;
|
jbe@163
|
765 else if (c1 > c2) return 1;
|
jbe@163
|
766 } else {
|
jbe@163
|
767 return 1;
|
jbe@163
|
768 }
|
jbe@163
|
769 } else {
|
jbe@163
|
770 if (key2->length > pos) {
|
jbe@163
|
771 return -1;
|
jbe@163
|
772 } else {
|
jbe@163
|
773 return 0;
|
jbe@163
|
774 }
|
jbe@163
|
775 }
|
jbe@163
|
776 pos++;
|
jbe@163
|
777 }
|
jbe@163
|
778 }
|
jbe@163
|
779
|
jbe@154
|
780 #define JSON_TABLETYPE_UNKNOWN 0
|
jbe@154
|
781 #define JSON_TABLETYPE_OBJECT 1
|
jbe@154
|
782 #define JSON_TABLETYPE_ARRAY 2
|
jbe@154
|
783
|
jbe@164
|
784 #define json_export_internal_indentstring_idx 1
|
jbe@164
|
785 #define json_export_internal_level_idx 2
|
jbe@164
|
786 #define json_export_internal_value_idx 3
|
jbe@164
|
787 #define json_export_internal_tmp_idx 4
|
jbe@164
|
788
|
jbe@164
|
789 static int json_export_internal(lua_State *L) {
|
jbe@164
|
790 int level;
|
jbe@164
|
791 int pretty;
|
jbe@164
|
792 int i;
|
jbe@154
|
793 lua_Number num;
|
jbe@154
|
794 const char *str;
|
jbe@154
|
795 unsigned char c;
|
jbe@154
|
796 size_t strlen;
|
jbe@154
|
797 size_t pos = 0;
|
jbe@154
|
798 luaL_Buffer buf;
|
jbe@154
|
799 char hexcode[7]; // backslash, character 'u', 4 hex digits, and terminating NULL byte
|
jbe@154
|
800 int tabletype = JSON_TABLETYPE_UNKNOWN;
|
jbe@164
|
801 int anyelement = 0;
|
jbe@163
|
802 size_t keycount = 0;
|
jbe@163
|
803 size_t keypos = 0;
|
jbe@165
|
804 json_key_t *keybuf = NULL;
|
jbe@154
|
805 lua_Integer idx;
|
jbe@164
|
806 lua_settop(L, json_export_internal_value_idx);
|
jbe@164
|
807 if (json_isnullmark(L, json_export_internal_value_idx)) {
|
jbe@164
|
808 lua_pop(L, 1);
|
jbe@157
|
809 lua_pushnil(L);
|
jbe@157
|
810 }
|
jbe@164
|
811 switch (lua_type(L, json_export_internal_value_idx)) {
|
jbe@154
|
812 case LUA_TNIL:
|
jbe@154
|
813 lua_pushliteral(L, "null");
|
jbe@154
|
814 return 1;
|
jbe@154
|
815 case LUA_TNUMBER:
|
jbe@164
|
816 num = lua_tonumber(L, json_export_internal_value_idx);
|
jbe@154
|
817 if (isnan(num)) return luaL_error(L, "JSON export not possible for NaN value");
|
jbe@154
|
818 if (isinf(num)) return luaL_error(L, "JSON export not possible for infinite numbers");
|
jbe@164
|
819 lua_tostring(L, json_export_internal_value_idx);
|
jbe@154
|
820 return 1;
|
jbe@154
|
821 case LUA_TBOOLEAN:
|
jbe@164
|
822 if (lua_toboolean(L, json_export_internal_value_idx)) {
|
jbe@164
|
823 lua_pushliteral(L, "true");
|
jbe@164
|
824 } else {
|
jbe@164
|
825 lua_pushliteral(L, "false");
|
jbe@164
|
826 }
|
jbe@154
|
827 return 1;
|
jbe@154
|
828 case LUA_TSTRING:
|
jbe@164
|
829 str = lua_tolstring(L, 3, &strlen);
|
jbe@154
|
830 luaL_buffinit(L, &buf);
|
jbe@154
|
831 luaL_addchar(&buf, '"');
|
jbe@154
|
832 while (pos < strlen) {
|
jbe@154
|
833 c = str[pos++];
|
jbe@154
|
834 if (c == '"') luaL_addstring(&buf, "\\\"");
|
jbe@154
|
835 else if (c == '\\') luaL_addstring(&buf, "\\\\");
|
jbe@154
|
836 else if (c == 127) luaL_addstring(&buf, "\\u007F");
|
jbe@154
|
837 else if (c >= 32) luaL_addchar(&buf, c);
|
jbe@154
|
838 else if (c == '\b') luaL_addstring(&buf, "\\b");
|
jbe@154
|
839 else if (c == '\f') luaL_addstring(&buf, "\\f");
|
jbe@154
|
840 else if (c == '\n') luaL_addstring(&buf, "\\n");
|
jbe@154
|
841 else if (c == '\r') luaL_addstring(&buf, "\\r");
|
jbe@154
|
842 else if (c == '\t') luaL_addstring(&buf, "\\t");
|
jbe@154
|
843 else if (c == '\v') luaL_addstring(&buf, "\\v");
|
jbe@154
|
844 else {
|
jbe@154
|
845 sprintf(hexcode, "\\u%04X", c);
|
jbe@154
|
846 luaL_addstring(&buf, hexcode);
|
jbe@154
|
847 }
|
jbe@154
|
848 }
|
jbe@154
|
849 luaL_addchar(&buf, '"');
|
jbe@154
|
850 luaL_pushresult(&buf);
|
jbe@154
|
851 return 1;
|
jbe@154
|
852 case LUA_TTABLE:
|
jbe@164
|
853 if (lua_getmetatable(L, json_export_internal_value_idx)) {
|
jbe@154
|
854 json_regfetch(L, objectmt);
|
jbe@154
|
855 if (lua_rawequal(L, -2, -1)) {
|
jbe@154
|
856 tabletype = JSON_TABLETYPE_OBJECT;
|
jbe@154
|
857 } else {
|
jbe@154
|
858 json_regfetch(L, arraymt);
|
jbe@164
|
859 if (lua_rawequal(L, -3, -1)) {
|
jbe@164
|
860 tabletype = JSON_TABLETYPE_ARRAY;
|
jbe@164
|
861 } else {
|
jbe@164
|
862 return luaL_error(L, "JSON export not possible for tables with nonsupported metatable");
|
jbe@164
|
863 }
|
jbe@154
|
864 }
|
jbe@154
|
865 }
|
jbe@154
|
866 json_regfetch(L, shadowtbl);
|
jbe@164
|
867 lua_pushvalue(L, json_export_internal_value_idx);
|
jbe@154
|
868 lua_rawget(L, -2);
|
jbe@164
|
869 if (!lua_isnil(L, -1)) lua_replace(L, json_export_internal_value_idx);
|
jbe@164
|
870 lua_settop(L, json_export_internal_value_idx);
|
jbe@154
|
871 if (tabletype == JSON_TABLETYPE_UNKNOWN) {
|
jbe@164
|
872 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
|
jbe@164
|
873 switch (lua_type(L, -2)) {
|
jbe@164
|
874 case LUA_TSTRING:
|
jbe@164
|
875 keycount++;
|
jbe@164
|
876 if (tabletype == JSON_TABLETYPE_UNKNOWN) tabletype = JSON_TABLETYPE_OBJECT;
|
jbe@164
|
877 else if (tabletype == JSON_TABLETYPE_ARRAY) goto json_export_tabletype_error;
|
jbe@164
|
878 break;
|
jbe@164
|
879 case LUA_TNUMBER:
|
jbe@164
|
880 if (tabletype == JSON_TABLETYPE_UNKNOWN) tabletype = JSON_TABLETYPE_ARRAY;
|
jbe@164
|
881 else if (tabletype == JSON_TABLETYPE_OBJECT) goto json_export_tabletype_error;
|
jbe@164
|
882 break;
|
jbe@154
|
883 }
|
jbe@154
|
884 }
|
jbe@154
|
885 }
|
jbe@164
|
886 pretty = lua_toboolean(L, json_export_internal_indentstring_idx);
|
jbe@164
|
887 level = lua_tointeger(L, json_export_internal_level_idx) + 1;
|
jbe@164
|
888 if (level > JSON_MAXDEPTH) {
|
jbe@164
|
889 return luaL_error(L, "More than %d nested JSON levels", JSON_MAXDEPTH);
|
jbe@164
|
890 }
|
jbe@154
|
891 switch (tabletype) {
|
jbe@154
|
892 case JSON_TABLETYPE_OBJECT:
|
jbe@164
|
893 if (!keycount) {
|
jbe@164
|
894 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
|
jbe@164
|
895 if (lua_type(L, -2) == LUA_TSTRING) keycount++;
|
jbe@164
|
896 }
|
jbe@163
|
897 }
|
jbe@163
|
898 if (keycount) {
|
jbe@163
|
899 keybuf = calloc(keycount, sizeof(json_key_t));
|
jbe@163
|
900 if (!keybuf) return luaL_error(L, "Memory allocation failed in JSON library");
|
jbe@164
|
901 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
|
jbe@163
|
902 if (lua_type(L, -2) == LUA_TSTRING) {
|
jbe@163
|
903 json_key_t *key = keybuf + (keypos++);
|
jbe@163
|
904 key->data = lua_tolstring(L, -2, &key->length);
|
jbe@163
|
905 }
|
jbe@163
|
906 }
|
jbe@163
|
907 qsort(keybuf, keycount, sizeof(json_key_t), (void *)json_key_cmp);
|
jbe@163
|
908 }
|
jbe@154
|
909 luaL_buffinit(L, &buf);
|
jbe@154
|
910 luaL_addchar(&buf, '{');
|
jbe@163
|
911 for (keypos=0; keypos<keycount; keypos++) {
|
jbe@163
|
912 json_key_t *key = keybuf + keypos;
|
jbe@163
|
913 if (keypos) luaL_addchar(&buf, ',');
|
jbe@164
|
914 if (pretty) {
|
jbe@164
|
915 luaL_addchar(&buf, '\n');
|
jbe@164
|
916 for (i=0; i<level; i++) {
|
jbe@164
|
917 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
918 luaL_addvalue(&buf);
|
jbe@164
|
919 }
|
jbe@164
|
920 }
|
jbe@164
|
921 lua_pushcfunction(L, json_export_internal);
|
jbe@164
|
922 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
923 lua_pushinteger(L, level);
|
jbe@163
|
924 lua_pushlstring(L, key->data, key->length);
|
jbe@164
|
925 if (lua_pcall(L, 3, 1, 0)) {
|
jbe@163
|
926 if (keybuf) free(keybuf);
|
jbe@163
|
927 return lua_error(L);
|
jbe@154
|
928 }
|
jbe@163
|
929 luaL_addvalue(&buf);
|
jbe@163
|
930 luaL_addchar(&buf, ':');
|
jbe@164
|
931 if (pretty) luaL_addchar(&buf, ' ');
|
jbe@164
|
932 lua_pushcfunction(L, json_export_internal);
|
jbe@164
|
933 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
934 lua_pushinteger(L, level);
|
jbe@163
|
935 lua_pushlstring(L, key->data, key->length);
|
jbe@164
|
936 lua_rawget(L, json_export_internal_value_idx);
|
jbe@164
|
937 if (lua_pcall(L, 3, 1, 0)) {
|
jbe@163
|
938 if (keybuf) free(keybuf);
|
jbe@163
|
939 return lua_error(L);
|
jbe@163
|
940 }
|
jbe@163
|
941 luaL_addvalue(&buf);
|
jbe@154
|
942 }
|
jbe@163
|
943 if (keybuf) free(keybuf);
|
jbe@164
|
944 if (pretty && keycount != 0) {
|
jbe@164
|
945 luaL_addchar(&buf, '\n');
|
jbe@164
|
946 for (i=0; i<level-1; i++) {
|
jbe@164
|
947 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
948 luaL_addvalue(&buf);
|
jbe@164
|
949 }
|
jbe@164
|
950 }
|
jbe@154
|
951 luaL_addchar(&buf, '}');
|
jbe@164
|
952 if (pretty && level == 1) luaL_addchar(&buf, '\n');
|
jbe@154
|
953 luaL_pushresult(&buf);
|
jbe@154
|
954 return 1;
|
jbe@154
|
955 case JSON_TABLETYPE_ARRAY:
|
jbe@164
|
956 lua_settop(L, json_export_internal_tmp_idx);
|
jbe@154
|
957 luaL_buffinit(L, &buf);
|
jbe@154
|
958 luaL_addchar(&buf, '[');
|
jbe@154
|
959 for (idx = 1; ; idx++) {
|
jbe@164
|
960 lua_rawgeti(L, json_export_internal_value_idx, idx);
|
jbe@154
|
961 if (lua_isnil(L, -1)) {
|
jbe@154
|
962 lua_pop(L, 1);
|
jbe@154
|
963 break;
|
jbe@154
|
964 }
|
jbe@164
|
965 lua_replace(L, json_export_internal_tmp_idx);
|
jbe@164
|
966 if (anyelement) luaL_addchar(&buf, ',');
|
jbe@164
|
967 anyelement = 1;
|
jbe@164
|
968 if (pretty) {
|
jbe@164
|
969 luaL_addchar(&buf, '\n');
|
jbe@164
|
970 for (i=0; i<level; i++) {
|
jbe@164
|
971 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
972 luaL_addvalue(&buf);
|
jbe@164
|
973 }
|
jbe@164
|
974 }
|
jbe@164
|
975 lua_pushcfunction(L, json_export_internal);
|
jbe@164
|
976 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
977 lua_pushinteger(L, level);
|
jbe@164
|
978 lua_pushvalue(L, json_export_internal_tmp_idx);
|
jbe@164
|
979 lua_call(L, 3, 1);
|
jbe@154
|
980 luaL_addvalue(&buf);
|
jbe@154
|
981 }
|
jbe@164
|
982 if (pretty && anyelement) {
|
jbe@164
|
983 luaL_addchar(&buf, '\n');
|
jbe@164
|
984 for (i=0; i<level-1; i++) {
|
jbe@164
|
985 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
986 luaL_addvalue(&buf);
|
jbe@164
|
987 }
|
jbe@164
|
988 }
|
jbe@154
|
989 luaL_addchar(&buf, ']');
|
jbe@164
|
990 if (pretty && level == 1) luaL_addchar(&buf, '\n');
|
jbe@154
|
991 luaL_pushresult(&buf);
|
jbe@154
|
992 return 1;
|
jbe@154
|
993 }
|
jbe@154
|
994 json_export_tabletype_error:
|
jbe@154
|
995 return luaL_error(L, "JSON export not possible for ambiguous table (cannot decide whether it is an object or array)");
|
jbe@154
|
996 }
|
jbe@166
|
997 return luaL_error(L, "JSON export not possible for values of type \"%s\"", lua_typename(L, lua_type(L, json_export_internal_value_idx)));
|
jbe@154
|
998 }
|
jbe@154
|
999
|
jbe@164
|
1000 static int json_export(lua_State *L) {
|
jbe@164
|
1001 lua_settop(L, 1);
|
jbe@164
|
1002 lua_pushcfunction(L, json_export_internal);
|
jbe@164
|
1003 lua_pushnil(L);
|
jbe@164
|
1004 lua_pushinteger(L, 0);
|
jbe@164
|
1005 lua_pushvalue(L, 1);
|
jbe@164
|
1006 lua_call(L, 3, 1);
|
jbe@164
|
1007 return 1;
|
jbe@164
|
1008 }
|
jbe@164
|
1009
|
jbe@164
|
1010 static int json_pretty(lua_State *L) {
|
jbe@164
|
1011 lua_settop(L, 2);
|
jbe@164
|
1012 lua_pushcfunction(L, json_export_internal);
|
jbe@164
|
1013 if (lua_isnil(L, 2)) lua_pushliteral(L, " ");
|
jbe@164
|
1014 else lua_pushvalue(L, 2);
|
jbe@164
|
1015 lua_pushinteger(L, 0);
|
jbe@164
|
1016 lua_pushvalue(L, 1);
|
jbe@164
|
1017 lua_call(L, 3, 1);
|
jbe@164
|
1018 return 1;
|
jbe@164
|
1019 }
|
jbe@164
|
1020
|
jbe@149
|
1021 // functions in library module:
|
jbe@121
|
1022 static const struct luaL_Reg json_module_functions[] = {
|
jbe@133
|
1023 {"object", json_object},
|
jbe@133
|
1024 {"array", json_array},
|
jbe@121
|
1025 {"import", json_import},
|
jbe@154
|
1026 {"export", json_export},
|
jbe@164
|
1027 {"pretty", json_pretty},
|
jbe@130
|
1028 {"get", json_get},
|
jbe@127
|
1029 {"type", json_type},
|
jbe@121
|
1030 {NULL, NULL}
|
jbe@121
|
1031 };
|
jbe@121
|
1032
|
jbe@149
|
1033 // metamethods for JSON objects, JSON arrays, and unknown JSON collections (object or array):
|
jbe@126
|
1034 static const struct luaL_Reg json_metatable_functions[] = {
|
jbe@130
|
1035 {"__len", json_len},
|
jbe@130
|
1036 {"__index", json_index},
|
jbe@130
|
1037 {"__newindex", json_newindex},
|
jbe@135
|
1038 {"__pairs", json_pairs},
|
jbe@134
|
1039 {"__ipairs", json_ipairs},
|
jbe@160
|
1040 {"__tostring", json_export},
|
jbe@126
|
1041 {NULL, NULL}
|
jbe@126
|
1042 };
|
jbe@126
|
1043
|
jbe@157
|
1044 // metamethods for JSON null marker:
|
jbe@157
|
1045 static const struct luaL_Reg json_nullmark_metamethods[] = {
|
jbe@157
|
1046 {"__tostring", json_nullmark_tostring},
|
jbe@157
|
1047 {NULL, NULL}
|
jbe@157
|
1048 };
|
jbe@157
|
1049
|
jbe@149
|
1050 // initializes json library:
|
jbe@121
|
1051 int luaopen_json(lua_State *L) {
|
jbe@149
|
1052 // empty stack:
|
jbe@126
|
1053 lua_settop(L, 0);
|
jbe@149
|
1054 // push library module onto stack position 1:
|
jbe@149
|
1055 lua_newtable(L);
|
jbe@149
|
1056 // register library functions:
|
jbe@149
|
1057 luaL_setfuncs(L, json_module_functions, 0);
|
jbe@149
|
1058 // create and store objectmt:
|
jbe@138
|
1059 lua_newtable(L);
|
jbe@138
|
1060 luaL_setfuncs(L, json_metatable_functions, 0);
|
jbe@144
|
1061 json_regstore(L, objectmt);
|
jbe@149
|
1062 // create and store arraymt:
|
jbe@138
|
1063 lua_newtable(L);
|
jbe@138
|
1064 luaL_setfuncs(L, json_metatable_functions, 0);
|
jbe@144
|
1065 json_regstore(L, arraymt);
|
jbe@149
|
1066 // create and store ephemeron table to store shadow tables for each JSON object/array
|
jbe@149
|
1067 // to allow NULL values returned as nil
|
jbe@149
|
1068 lua_newtable(L);
|
jbe@138
|
1069 lua_newtable(L); // metatable for ephemeron table
|
jbe@121
|
1070 lua_pushliteral(L, "__mode");
|
jbe@121
|
1071 lua_pushliteral(L, "k");
|
jbe@138
|
1072 lua_rawset(L, -3);
|
jbe@138
|
1073 lua_setmetatable(L, -2);
|
jbe@144
|
1074 json_regstore(L, shadowtbl);
|
jbe@157
|
1075 // set metatable of null marker and make it available through library module:
|
jbe@157
|
1076 json_pushnullmark(L);
|
jbe@157
|
1077 lua_newtable(L);
|
jbe@157
|
1078 luaL_setfuncs(L, json_nullmark_metamethods, 0);
|
jbe@157
|
1079 lua_setmetatable(L, -2);
|
jbe@157
|
1080 lua_setfield(L, 1, "null");
|
jbe@157
|
1081 // return library module (that's expected on top of stack):
|
jbe@121
|
1082 return 1;
|
jbe@121
|
1083 }
|