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