summaryrefslogtreecommitdiffstats
path: root/src/Bindings/LuaJson.cpp
blob: 1cd88cf96064190a6e435ac6deca5a49a327c768 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405

// LuaJson.cpp

// Implements the Json exposure bindings to Lua

#include "Globals.h"
#include <sstream>
#include "LuaJson.h"
#include "LuaState.h"
#include "tolua++/include/tolua++.h"
#include "json/json.h"
#include "../JsonUtils.h"





// fwd:

static void PushJsonValue(const Json::Value & a_Value, cLuaState & a_LuaState);
static Json::Value JsonSerializeValue(cLuaState & a_LuaState);




/** Exception thrown when the input cannot be serialized.
Keeps track of the error message and the problematic value's path in the table.
*/
class CannotSerializeException:
	public std::runtime_error
{
	using Super = std::runtime_error;

public:
	/** Constructs a new instance of the exception based on the provided values directly. */
	explicit CannotSerializeException(const AString & a_ValueName, const char * a_ErrorMsg):
		Super(a_ErrorMsg),
		m_ValueName(a_ValueName)
	{
	}

	/** Constructs a new instance of the exception based on the provided values directly. */
	explicit CannotSerializeException(int a_ValueIndex, const char * a_ErrorMsg):
		Super(a_ErrorMsg),
		m_ValueName(Printf("%d", a_ValueIndex))
	{
	}

	/** Constructs a new instance of the exception that takes the error message and value name from the parent, and prefix the value name with the specified prefix.
	Used for prefixing the value name's path along the call stack that lead to the main exception. */
	explicit CannotSerializeException(const CannotSerializeException & a_Parent, const AString & a_ValueNamePrefix):
		Super(a_Parent.what()),
		m_ValueName(a_ValueNamePrefix + "." + a_Parent.m_ValueName)
	{
	}

	/** Constructs a new instance of the exception that takes the error message and value name from the parent, and prefix the value name with the specified prefix.
	Used for prefixing the value name's path along the call stack that lead to the main exception. */
	explicit CannotSerializeException(const CannotSerializeException & a_Parent, int a_ValueNamePrefixIndex):
		Super(a_Parent.what()),
		m_ValueName(Printf("%d", a_ValueNamePrefixIndex) + "." + a_Parent.m_ValueName)
	{
	}

	const AString & GetValueName() const { return m_ValueName; }

protected:
	AString m_ValueName;
};





/** Pushes the specified Json array as a table on top of the specified Lua state.
Assumes that a_Value is an array. */
static void PushJsonArray(const Json::Value & a_Value, cLuaState & a_LuaState)
{
	// Create the appropriately-sized Lua table:
	lua_createtable(a_LuaState, static_cast<int>(a_Value.size()), 0);

	// Insert each value to the appropriate index (1-based):
	int idx = 1;
	for (const auto & v: a_Value)
	{
		// Include Json null values in the array - it will have holes, but indices will stay the same
		PushJsonValue(v, a_LuaState);
		lua_rawseti(a_LuaState, -2, idx);
		idx += 1;
	}  // for v: a_Value[]
}





/** Pushes the specified Json object as a table on top of the specified Lua state.
Assumes that a_Value is an object. */
static void PushJsonObject(const Json::Value & a_Value, cLuaState & a_LuaState)
{
	// Create the appropriately-sized Lua table:
	lua_createtable(a_LuaState, 0, static_cast<int>(a_Value.size()));

	// Json::Value has no means of iterating over children with their names included.
	// We need to iterate over names and "find" them in the object again:
	auto names = a_Value.getMemberNames();
	for (const auto & n: names)
	{
		auto v = a_Value[n];
		if (v.isNull())
		{
			// Skip null values
			continue;
		}

		// Set the value in Lua's table:
		a_LuaState.Push(n);
		PushJsonValue(v, a_LuaState);
		lua_rawset(a_LuaState, -3);
	}  // for itr - a_Value[]
}





/** Pushes the specified Json value as an appropriate type on top of the specified Lua state. */
void PushJsonValue(const Json::Value & a_Value, cLuaState & a_LuaState)
{
	switch (a_Value.type())
	{
		case Json::nullValue:
		{
			a_LuaState.Push(cLuaState::Nil);
			break;
		}

		case Json::intValue:
		case Json::uintValue:
		case Json::realValue:
		{
			a_LuaState.Push(static_cast<lua_Number>(a_Value.asDouble()));
			break;
		}

		case Json::booleanValue:
		{
			a_LuaState.Push(a_Value.asBool());
			break;
		}

		case Json::stringValue:
		{
			a_LuaState.Push(a_Value.asString());
			break;
		}

		case Json::arrayValue:
		{
			PushJsonArray(a_Value, a_LuaState);
			break;
		}

		case Json::objectValue:
		{
			PushJsonObject(a_Value, a_LuaState);
			break;
		}
	}  // switch (v.type())
}





/** Serializes the Lua table at the top of the specified Lua state's stack into a Json value.
Lets jsoncpp decides whether to serialize into an object or an array. */
static Json::Value JsonSerializeTable(cLuaState & a_LuaState)
{
	Json::Value res;
	lua_pushnil(a_LuaState);
	while (lua_next(a_LuaState, -2) != 0)
	{
		if (lua_type(a_LuaState, -2) == LUA_TNUMBER)
		{
			int idx;
			a_LuaState.GetStackValue(-2, idx);
			try
			{
				res[idx - 1] = JsonSerializeValue(a_LuaState);
			}
			catch (const CannotSerializeException & exc)
			{
				throw CannotSerializeException(exc, idx);
			}
			catch (const std::exception & exc)  // Cannot catch Json::Exception, because it's not properly defined
			{
				throw CannotSerializeException(idx, exc.what());
			}
		}
		else
		{
			AString name;
			if (a_LuaState.GetStackValue(-2, name))
			{
				try
				{
					res[name] = JsonSerializeValue(a_LuaState);
				}
				catch (const CannotSerializeException & exc)
				{
					throw CannotSerializeException(exc, name);
				}
				catch (const std::exception & exc)  // Cannot catch Json::Exception, because it's not properly defined
				{
					throw CannotSerializeException(name, exc.what());
				}
			}
		}
		lua_pop(a_LuaState, 1);
	}
	return res;
}





/** Serializes the Lua value at the top of the specified Lua state into a Json value. */
static Json::Value JsonSerializeValue(cLuaState & a_LuaState)
{
	switch (lua_type(a_LuaState, -1))
	{
		case LUA_TBOOLEAN:
		{
			bool v;
			a_LuaState.GetStackValue(-1, v);
			return Json::Value(v);
		}
		case LUA_TNIL:
		{
			return Json::Value(Json::nullValue);
		}
		case LUA_TNUMBER:
		{
			lua_Number v;
			a_LuaState.GetStackValue(-1, v);
			return Json::Value(v);
		}
		case LUA_TSTRING:
		{
			AString v;
			a_LuaState.GetStackValue(-1, v);
			return Json::Value(v);
		}
		case LUA_TTABLE:
		{
			return JsonSerializeTable(a_LuaState);
		}
		default:
		{
			LOGD("Attempting to serialize an unhandled Lua value type: %d", lua_type(a_LuaState, -1));
			return Json::Value(Json::nullValue);
		}
	}
}





static int tolua_cJson_Parse(lua_State * a_LuaState)
{
	// Function signature:
	// cJson:Parse("string") -> table

	// Check the param types:
	cLuaState L(a_LuaState);
	if (
		!L.CheckParamUserTable(1, "cJson") ||
		!L.CheckParamString(2) ||
		!L.CheckParamEnd(3)
	)
	{
		return 0;
	}

	// Get the input string:
	AString input;
	if (!L.GetStackValue(2, input))
	{
		LOGWARNING("cJson:Parse(): Cannot read input string");
		L.LogStackTrace();
		return 0;
	}

	// Parse the string:
	Json::Value root;
	AString ParseError;
	if (!JsonUtils::ParseString(input, root, &ParseError))
	{
		L.Push(cLuaState::Nil, Printf("Parsing Json failed: %s", ParseError));
		return 2;
	}

	// Push the Json value onto Lua stack:
	PushJsonValue(root, L);
	return 1;
}





static int tolua_cJson_Serialize(lua_State * a_LuaState)
{
	// Function signature:
	// cJson:Serialize({table}, [{option1 = value1, option2 = value2}]) -> string

	// Check the param types:
	cLuaState L(a_LuaState);
	if (
		!L.CheckParamUserTable(1, "cJson") ||
		!L.CheckParamTable(2) ||
		!L.CheckParamEnd(4)
	)
	{
		return 0;
	}

	// Push the table to the top of the Lua stack, and call the serializing function:
	lua_pushvalue(L, 2);
	Json::Value root;
	try
	{
		root = JsonSerializeValue(L);
	}
	catch (const CannotSerializeException & exc)
	{
		lua_pushnil(L);
		L.Push(Printf("Cannot serialize into Json, value \"%s\" caused an error \"%s\"", exc.GetValueName().c_str(), exc.what()));
		return 2;
	}
	lua_pop(L, 1);

	// Create the writer, with all properties (optional param 3) applied to it:
	Json::StreamWriterBuilder builder;
	if (lua_istable(L, 3))
	{
		lua_pushnil(L);
		while (lua_next(L, -2) != 0)
		{
			if (lua_type(L, -2) == LUA_TSTRING)
			{
				AString propName, propValue;
				if (L.GetStackValues(-2, propName, propValue))
				{
					builder[propName] = propValue;
				}
			}
			lua_pop(L, 1);
		}
		// Check for invalid settings:
		Json::Value invalid;
		if (!builder.validate(&invalid))
		{
			LOGINFO("cJson:Serialize(): detected invalid settings:");
			for (const auto & n: invalid.getMemberNames())
			{
				LOGINFO("  \"%s\" (\"%s\")", n.c_str(), invalid[n].asCString());
			}
		}
	}
	auto writer(builder.newStreamWriter());

	// Serialize the string and push it as the return value:
	std::stringstream ss;
	writer->write(root, &ss);
	L.Push(ss.str());
	return 1;
}





void cLuaJson::Bind(cLuaState & a_LuaState)
{
	tolua_beginmodule(a_LuaState, nullptr);

		// Create the cJson API class:
		tolua_usertype(a_LuaState, "cJson");
		tolua_cclass(a_LuaState, "cJson", "cJson", "", nullptr);

		// Fill in the functions (alpha-sorted):
		tolua_beginmodule(a_LuaState, "cJson");
			tolua_function(a_LuaState, "Parse",     tolua_cJson_Parse);
			tolua_function(a_LuaState, "Serialize", tolua_cJson_Serialize);
		tolua_endmodule(a_LuaState);
	tolua_endmodule(a_LuaState);
}