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