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