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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
|
#include "_pch.hpp"
#include "shared.h"
// #################################################################################################
// #################################################################################################
// internal fixture module
// #################################################################################################
// #################################################################################################
LANES_API int luaopen_deep_userdata_example(lua_State* L_);
namespace
{
extern int luaopen_fixture(lua_State*);
namespace local {
void PreloadModule(lua_State* const L_, std::string_view const& name_, lua_CFunction const openf_)
{
STACK_CHECK_START_REL(L_, 0);
lua_getglobal(L_, "package"); // L_: package
std::ignore = luaG_getfield(L_, kIdxTop, "preload"); // L_: package package.preload
lua_pushcfunction(L_, openf_); // L_: package package.preload openf_
luaG_setfield(L_, StackIndex{ -2 }, name_); // L_: package package.preload
lua_pop(L_, 2);
STACK_CHECK(L_, 0);
}
static std::map<lua_State*, std::atomic_flag> sFinalizerHits;
static std::mutex sCallCountsLock;
// a finalizer that we can detect even after closing the state
lua_CFunction sThrowingFinalizer = +[](lua_State* L_) {
std::lock_guard _guard{ sCallCountsLock };
sFinalizerHits[L_].test_and_set();
luaG_pushstring(L_, "throw");
return 1;
};
// a finalizer that we can detect even after closing the state
lua_CFunction sYieldingFinalizer = +[](lua_State* L_) {
std::lock_guard _guard{ sCallCountsLock };
sFinalizerHits[L_].test_and_set();
return 0;
};
// a function that runs forever
lua_CFunction sForever = +[](lua_State* L_) {
while (true) {
std::this_thread::yield();
}
return 0;
};
// a function that returns immediately (so that LuaJIT issues a function call for it)
lua_CFunction sGiveMeBack = +[](lua_State* L_) {
return lua_gettop(L_);
};
lua_CFunction sNewLightUserData = +[](lua_State* const L_) {
lua_pushlightuserdata(L_, std::bit_cast<void*>(static_cast<uintptr_t>(42)));
return 1;
};
lua_CFunction sNewUserData = +[](lua_State* const L_) {
std::ignore = luaG_newuserdatauv<int>(L_, UserValueCount{ 0 });
return 1;
};
// a function that enables any lane to require "fixture"
lua_CFunction sOnStateCreate = +[](lua_State* const L_) {
PreloadModule(L_, "fixture", luaopen_fixture);
PreloadModule(L_, "deep_userdata_example", luaopen_deep_userdata_example);
return 0;
};
static luaL_Reg const sFixture[] = {
{ "forever", sForever },
{ "give_me_back()", sGiveMeBack },
{ "newlightuserdata", sNewLightUserData },
{ "newuserdata", sNewUserData },
{ "on_state_create", sOnStateCreate },
{ "throwing_finalizer", sThrowingFinalizer },
{ "yielding_finalizer", sYieldingFinalizer },
{ nullptr, nullptr }
};
} // namespace local
// ############################################################################################
int luaopen_fixture(lua_State* L_)
{
STACK_CHECK_START_REL(L_, 0);
luaG_newlib<std::size(local::sFixture)>(L_, local::sFixture); // M
STACK_CHECK(L_, 1);
return 1;
}
} // namespace
// #################################################################################################
// #################################################################################################
// Internals
// #################################################################################################
// #################################################################################################
#if HAVE_LUA_ASSERT()
TEST_CASE("lanes.stack checker")
{
LuaState _L{ LuaState::WithBaseLibs{ true }, LuaState::WithFixture{ false } };
StackChecker::CallsCassert = false;
auto _doStackCheckerTest = [&_L](lua_CFunction const _f, LuaError const _expected) {
lua_pushcfunction(_L, _f);
REQUIRE(ToLuaError(lua_pcall(_L, 0, 0, 0)) == _expected);
};
// function where the StackChecker detects something wrong with the stack
lua_CFunction _unbalancedStack1 = +[](lua_State* const _L) {
// record current position
STACK_CHECK_START_REL(_L, 0);
// push something
lua_newtable(_L);
// check if we are at the same position as before (no)
STACK_CHECK(_L, 0);
return 1;
};
// function where the StackChecker detects no issue
lua_CFunction _balancedStack1 = +[](lua_State* const _L) {
// record current position
STACK_CHECK_START_REL(_L, 0);
// check if we are at the same position as before (yes)
STACK_CHECK(_L, 0);
return 0;
};
lua_CFunction _goodStart = +[](lua_State* const _L) {
// check that the stack ends at the specified position, and record that as our reference point
STACK_CHECK_START_ABS(_L, 0);
// check if we are at the same position as before (yes)
STACK_CHECK(_L, 0);
return 0;
};
lua_CFunction _badStart = +[](lua_State* const _L) {
// check that the stack ends at the specified position (no), and record that as our reference point
STACK_CHECK_START_ABS(_L, 1);
// check if we are at the same position as before (yes)
STACK_CHECK(_L, 0);
return 0;
};
SECTION("unbalanced stack")
{
_doStackCheckerTest(_unbalancedStack1, LuaError::ERRRUN);
}
SECTION("balanced stack")
{
_doStackCheckerTest(_balancedStack1, LuaError::OK);
}
SECTION("good start")
{
_doStackCheckerTest(_goodStart, LuaError::OK);
}
SECTION("bad start")
{
_doStackCheckerTest(_badStart, LuaError::ERRRUN);
}
}
#endif // HAVE_LUA_ASSERT()
// #################################################################################################
// #################################################################################################
// LuaState
// #################################################################################################
// #################################################################################################
LuaState::LuaState(WithBaseLibs const withBaseLibs_, WithFixture const withFixture_)
{
STACK_CHECK_START_REL(L, 0);
if (withBaseLibs_) {
luaL_openlibs(L);
} else {
#if LUAJIT_FLAVOR()
// lanes_core relies on the presence of jit to detect LuaJIT/PUC-Lua mismatches
luaL_requiref(L, LUA_JITLIBNAME, luaopen_jit, 1);
lua_pop(L, 1);
#endif // LUAJIT_FLAVOR
}
if (withFixture_) {
// make require "fixture" call luaopen_fixture
local::PreloadModule(L, "fixture", luaopen_fixture);
local::PreloadModule(L, "deep_userdata_example", luaopen_deep_userdata_example);
}
STACK_CHECK(L, 0);
}
// #################################################################################################
void LuaState::close()
{
if (L) {
lua_close(L);
{
std::lock_guard _guard{ local::sCallCountsLock };
finalizerWasCalled = local::sFinalizerHits[L].test();
local::sFinalizerHits.erase(L);
}
L = nullptr;
}
}
// #################################################################################################
LuaError LuaState::doString(std::string_view const& str_) const
{
lua_settop(L, 0);
if (str_.empty()) {
lua_pushnil(L);
return LuaError::OK;
}
STACK_CHECK_START_REL(L, 0);
LuaError const _loadErr{ luaL_loadstring(L, str_.data()) }; // L: chunk()
if (_loadErr != LuaError::OK) {
STACK_CHECK(L, 1); // the error message is on the stack
return _loadErr;
}
LuaError const _callErr{ lua_pcall(L, 0, 1, 0) }; // L: "<msg>"?
[[maybe_unused]] std::string_view const _out{ luaG_tostring(L, kIdxTop) };
STACK_CHECK(L, 1);
return _callErr;
}
// #################################################################################################
std::string_view LuaState::doStringAndRet(std::string_view const& str_) const
{
lua_settop(L, 0);
if (str_.empty()) {
luaG_pushstring(L, "");
return luaG_tostring(L, kIdxTop);
}
STACK_CHECK_START_REL(L, 0);
LuaError const _loadErr{ luaL_loadstring(L, str_.data()) }; // L: chunk()
if (_loadErr != LuaError::OK) {
STACK_CHECK(L, 1); // the error message is on the stack
return "";
}
[[maybe_unused]] LuaError const _callErr{ lua_pcall(L, 0, 1, 0) }; // L: "<msg>"?|retstring
STACK_CHECK(L, 1);
return luaG_tostring(L, kIdxTop);
}
// #################################################################################################
LuaError LuaState::doFile(std::filesystem::path const& root_, std::string_view const& str_) const
{
lua_settop(L, 0);
if (str_.empty()) {
lua_pushnil(L);
return LuaError::OK;
}
STACK_CHECK_START_REL(L, 0);
std::filesystem::path _combined{ root_ };
_combined.append(str_);
_combined.replace_extension(".lua");
LuaError const _loadErr{ luaL_loadfile(L, _combined.generic_string().c_str()) }; // L: chunk()
if (_loadErr != LuaError::OK) {
STACK_CHECK(L, 1);
return _loadErr;
}
LuaError const _callErr{ lua_pcall(L, 0, 1, 0) }; // L: "<msg>"?
STACK_CHECK(L, 1); // either nil, a return value, or an error string
return _callErr;
}
// #################################################################################################
LuaError LuaState::loadString(std::string_view const& str_) const
{
lua_settop(L, 0);
if (str_.empty()) {
// this particular test is disabled: just create a dummy function that will run without error
lua_pushcfunction(L, +[](lua_State*){return 0;});
return LuaError::OK;
}
STACK_CHECK_START_REL(L, 0);
LuaError const _loadErr{ luaL_loadstring(L, str_.data()) }; // L: chunk()
STACK_CHECK(L, 1); // function on success, error string on failure
return _loadErr;
}
// #################################################################################################
LuaError LuaState::loadFile(std::filesystem::path const& root_, std::string_view const& str_) const
{
lua_settop(L, 0);
STACK_CHECK_START_REL(L, 0);
if (str_.empty()) {
// this particular test is disabled: just create a dummy function that will run without error
lua_pushcfunction(L, +[](lua_State*){return 0;});
return LuaError::OK;
}
std::filesystem::path _combined{ root_ };
_combined.append(str_);
_combined.replace_extension(".lua");
LuaError const _loadErr{ luaL_loadfile(L, _combined.generic_string().c_str()) }; // L: chunk()
STACK_CHECK(L, 1); // function on success, error string on failure
return _loadErr;
}
// #################################################################################################
void LuaState::requireFailure(std::string_view const& script_)
{
auto const _result{ doString(script_) };
if (_result == LuaError::OK) {
WARN(luaG_tostring(L, kIdxTop));
}
REQUIRE(_result != LuaError::OK);
lua_settop(L, 0);
}
// #################################################################################################
void LuaState::requireNotReturnedString(std::string_view const& script_, std::string_view const& unexpected_)
{
auto const _result{ doStringAndRet(script_) };
if (_result == unexpected_) {
WARN(_result);
}
REQUIRE(_result != unexpected_);
lua_settop(L, 0);
}
// #################################################################################################
void LuaState::requireReturnedString(std::string_view const& script_, std::string_view const& expected_)
{
auto const _result{ doStringAndRet(script_) };
if (_result != expected_) {
WARN(_result);
}
REQUIRE(_result == expected_);
lua_settop(L, 0);
}
// #################################################################################################
void LuaState::requireSuccess(std::string_view const& script_)
{
auto const _result{ doString(script_) };
if (_result != LuaError::OK) {
WARN(luaG_tostring(L, kIdxTop));
}
REQUIRE(_result == LuaError::OK);
lua_settop(L, 0);
}
// #################################################################################################
void LuaState::requireSuccess(std::filesystem::path const& root_, std::string_view const& path_)
{
auto const _result{ doFile(root_, path_) };
if (_result != LuaError::OK) {
WARN(luaG_tostring(L, kIdxTop));
}
REQUIRE(_result == LuaError::OK);
lua_settop(L, 0);
}
// #################################################################################################
LuaError LuaState::runChunk() const
{
STACK_CHECK_START_ABS(L, 1); // we must start with the chunk on the stack (or an error string if it failed to load)
LuaError const _callErr{ lua_pcall(L, 0, 1, 0) }; // L: "<msg>"?
STACK_CHECK(L, 1);
return _callErr;
}
// #################################################################################################
// #################################################################################################
TEST_CASE("LuaState.doString")
{
LuaState _L{ LuaState::WithBaseLibs{ true }, LuaState::WithFixture{ false } };
// if the script fails to load, we should find the error message at the top of the stack
REQUIRE([&L = _L]() { std::ignore = L.doString("function end"); return lua_gettop(L) == 1 && luaG_type(L, StackIndex{1}) == LuaType::STRING; }());
// if the script runs, the stack should contain its return value
REQUIRE([&L = _L]() { std::ignore = L.doString("return true"); return lua_gettop(L) == 1 && luaG_type(L, StackIndex{1}) == LuaType::BOOLEAN; }());
REQUIRE([&L = _L]() { std::ignore = L.doString("return 'hello'"); return lua_gettop(L) == 1 && luaG_tostring(L, StackIndex{1}) == "hello"; }());
// or nil if it didn't return anything
REQUIRE([&L = _L]() { std::ignore = L.doString("return"); return lua_gettop(L) == 1 && luaG_type(L, StackIndex{1}) == LuaType::NIL; }());
// on failure, doStringAndRet returns "", and the error message is on the stack
REQUIRE([&L = _L]() { return L.doStringAndRet("function end") == "" && lua_gettop(L) == 1 && luaG_type(L, StackIndex{ 1 }) == LuaType::STRING && luaG_tostring(L, StackIndex{ 1 }) != ""; }());
// on success doStringAndRet returns the string returned by the script, that is also at the top of the stack
REQUIRE([&L = _L]() { return L.doStringAndRet("return 'hello'") == "hello" && lua_gettop(L) == 1 && luaG_type(L, StackIndex{ 1 }) == LuaType::STRING && luaG_tostring(L, StackIndex{ 1 }) == "hello"; }());
// if the returned value is not (convertible to) a string, we should get an empty string out of doStringAndRet
REQUIRE([&L = _L]() { return L.doStringAndRet("return function() end") == "" && lua_gettop(L) == 1 && luaG_type(L, StackIndex{ 1 }) == LuaType::FUNCTION && luaG_tostring(L, StackIndex{ 1 }) == ""; }());
}
// #################################################################################################
// #################################################################################################
// FileRunner
// #################################################################################################
// #################################################################################################
FileRunner::FileRunner(std::string_view const& where_)
: LuaState{ LuaState::WithBaseLibs{ true }, LuaState::WithFixture{ true } }
{
// _G.print = _nullprint
// because the VS Test Explorer doesn't appreciate the text output of some scripts, so absorb them
if constexpr (1) {
auto const _nullprint = +[](lua_State* const L_) { return 0; };
luaG_pushglobaltable(L);
lua_pushcfunction(L, _nullprint);
luaG_setfield(L, StackIndex{ -2 }, std::string_view{ "print" });
lua_pop(L, 1);
stackCheck(0);
}
// TODO: do the same with io.stderr:write?
[[maybe_unused]] std::filesystem::path const _current{ std::filesystem::current_path() };
std::filesystem::path _path{ where_ };
root = std::filesystem::canonical(_path).generic_string();
// I need to append that path to the list of locations where modules can be required
// so that the legacy scripts can require"assert" and find assert.lua
std::string _script{ "package.path = package.path.." };
_script += "';";
_script += root;
_script += "/?.lua'";
std::ignore = doString(_script.c_str());
}
// #################################################################################################
void FileRunner::performTest(FileRunnerParam const& testParam_)
{
INFO(testParam_.script);
switch (testParam_.test) {
case TestType::AssertNoLuaError:
requireSuccess(root, testParam_.script);
break;
case TestType::AssertNoThrow:
REQUIRE_NOTHROW((std::ignore = doFile(root, testParam_.script), close()));
break;
case TestType::AssertThrows:
REQUIRE_THROWS_AS((std::ignore = doFile(root, testParam_.script), close()), std::logic_error);
break;
}
}
|