From 2e27d4153943145f9102d5d56782ad6e20b76182 Mon Sep 17 00:00:00 2001 From: Benoit Germain Date: Mon, 13 May 2024 18:00:21 +0200 Subject: Progressively applying the coding rules --- src/keeper.cpp | 10 +- src/keeper.h | 2 +- src/lanes.cpp | 662 ++++++++++++++++++++++++------------------------- src/lanesconf.h | 2 +- src/linda.cpp | 464 +++++++++++++++++----------------- src/lindafactory.cpp | 40 +-- src/macros_and_utils.h | 2 +- src/state.cpp | 133 +++++----- src/tools.cpp | 124 ++++----- src/universe.cpp | 66 ++--- 10 files changed, 751 insertions(+), 754 deletions(-) (limited to 'src') diff --git a/src/keeper.cpp b/src/keeper.cpp index 39d2e85..dcfa2ec 100644 --- a/src/keeper.cpp +++ b/src/keeper.cpp @@ -738,9 +738,9 @@ void keeper_toggle_nil_sentinels(lua_State* L_, int start_, LookupMode const mod * * Returns: number of return values (pushed to 'L'), unset in case of error */ -KeeperCallResult keeper_call(Universe* U_, KeeperState K_, keeper_api_t func_, lua_State* L_, void* linda_, int starting_index_) +KeeperCallResult keeper_call(KeeperState K_, keeper_api_t func_, lua_State* L_, Linda* linda_, int starting_index_) { - KeeperCallResult _result{}; + KeeperCallResult _result; int const _args{ starting_index_ ? (lua_gettop(L_) - starting_index_ + 1) : 0 }; // L: ... args... K_: int const _top_K{ lua_gettop(K_) }; // if we didn't do anything wrong, the keeper stack should be clean @@ -751,7 +751,7 @@ KeeperCallResult keeper_call(Universe* U_, KeeperState K_, keeper_api_t func_, l lua_pushlightuserdata(K_, linda_); // L: ... args... K_: func_ linda if ( (_args == 0) || - (InterCopyContext{ U_, DestState{ K_ }, SourceState{ L_ }, {}, {}, {}, LookupMode::ToKeeper, {} }.inter_copy(_args) == InterCopyResult::Success) + (InterCopyContext{ linda_->U, DestState{ K_ }, SourceState{ L_ }, {}, {}, {}, LookupMode::ToKeeper, {} }.inter_copy(_args) == InterCopyResult::Success) ) { // L: ... args... K_: func_ linda args... lua_call(K_, 1 + _args, LUA_MULTRET); // L: ... args... K_: result... int const retvals{ lua_gettop(K_) - _top_K }; @@ -761,7 +761,7 @@ KeeperCallResult keeper_call(Universe* U_, KeeperState K_, keeper_api_t func_, l // when attempting to grab the mutex again (WINVER <= 0x400 does this, but locks just fine, I don't know about pthread) if ( (retvals == 0) || - (InterCopyContext{ U_, DestState{ L_ }, SourceState{ K_ }, {}, {}, {}, LookupMode::FromKeeper, {} }.inter_move(retvals) == InterCopyResult::Success) + (InterCopyContext{ linda_->U, DestState{ L_ }, SourceState{ K_ }, {}, {}, {}, LookupMode::FromKeeper, {} }.inter_move(retvals) == InterCopyResult::Success) ) { // L: ... args... result... K_: result... _result.emplace(retvals); } @@ -772,7 +772,7 @@ KeeperCallResult keeper_call(Universe* U_, KeeperState K_, keeper_api_t func_, l // don't do this for this particular function, as it is only called during Linda destruction, and we don't want to raise an error, ever if (func_ != KEEPER_API(clear)) [[unlikely]] { // since keeper state GC is stopped, let's run a step once in a while if required - int const _gc_threshold{ U_->keepers->gc_threshold }; + int const _gc_threshold{ linda_->U->keepers->gc_threshold }; if (_gc_threshold == 0) [[unlikely]] { lua_gc(K_, LUA_GCSTEP, 0); } else if (_gc_threshold > 0) [[likely]] { diff --git a/src/keeper.h b/src/keeper.h index 8f30720..ebe2946 100644 --- a/src/keeper.h +++ b/src/keeper.h @@ -58,4 +58,4 @@ using keeper_api_t = lua_CFunction; [[nodiscard]] int keepercall_count(lua_State* L_); using KeeperCallResult = Unique>; -[[nodiscard]] KeeperCallResult keeper_call(Universe* U_, KeeperState K_, keeper_api_t func_, lua_State* L_, void* linda_, int starting_index_); +[[nodiscard]] KeeperCallResult keeper_call(KeeperState K_, keeper_api_t func_, lua_State* L_, Linda* linda_, int starting_index_); diff --git a/src/lanes.cpp b/src/lanes.cpp index ee40ffa..f0ec84c 100644 --- a/src/lanes.cpp +++ b/src/lanes.cpp @@ -116,7 +116,7 @@ THE SOFTWARE. */ static void tracking_add(Lane* lane_) { - std::lock_guard guard{ lane_->U->trackingMutex }; + std::lock_guard _guard{ lane_->U->trackingMutex }; assert(lane_->tracking_next == nullptr); lane_->tracking_next = lane_->U->trackingFirst; @@ -130,27 +130,27 @@ static void tracking_add(Lane* lane_) */ [[nodiscard]] static bool tracking_remove(Lane* lane_) { - bool found{ false }; - std::lock_guard guard{ lane_->U->trackingMutex }; + bool _found{ false }; + std::lock_guard _guard{ lane_->U->trackingMutex }; // Make sure (within the MUTEX) that we actually are in the chain // still (at process exit they will remove us from chain and then // cancel/kill). // if (lane_->tracking_next != nullptr) { - Lane** ref = (Lane**) &lane_->U->trackingFirst; + Lane** _ref = (Lane**) &lane_->U->trackingFirst; - while (*ref != TRACKING_END) { - if (*ref == lane_) { - *ref = lane_->tracking_next; + while (*_ref != TRACKING_END) { + if (*_ref == lane_) { + *_ref = lane_->tracking_next; lane_->tracking_next = nullptr; - found = true; + _found = true; break; } - ref = (Lane**) &((*ref)->tracking_next); + _ref = (Lane**) &((*_ref)->tracking_next); } - assert(found); + assert(_found); } - return found; + return _found; } #endif // HAVE_LANE_TRACKING() @@ -172,15 +172,15 @@ Lane::Lane(Universe* U_, lua_State* L_) bool Lane::waitForCompletion(std::chrono::time_point until_) { - std::unique_lock lock{ doneMutex }; + std::unique_lock _guard{ doneMutex }; // std::stop_token token{ thread.get_stop_token() }; // return doneCondVar.wait_until(lock, token, secs_, [this](){ return status >= Lane::Done; }); - return doneCondVar.wait_until(lock, until_, [this]() { return status >= Lane::Done; }); + return doneCondVar.wait_until(_guard, until_, [this]() { return status >= Lane::Done; }); } // ################################################################################################# -static void lane_main(Lane* lane); +static void lane_main(Lane* lane_); void Lane::startThread(int priority_) { thread = std::jthread([this]() { lane_main(this); }); @@ -267,9 +267,9 @@ LUAG_FUNC(set_finalizer) // Get the current finalizer table (if any), create one if it doesn't exist std::ignore = kFinalizerRegKey.getSubTable(L_, 1, 0); // L_: finalizer {finalisers} // must cast to int, not lua_Integer, because LuaJIT signature of lua_rawseti is not the same as PUC-Lua. - int const idx{ static_cast(lua_rawlen(L_, -1) + 1) }; + int const _idx{ static_cast(lua_rawlen(L_, -1) + 1) }; lua_pushvalue(L_, 1); // L_: finalizer {finalisers} finalizer - lua_rawseti(L_, -2, idx); // L_: finalizer {finalisers} + lua_rawseti(L_, -2, _idx); // L_: finalizer {finalisers} // no need to adjust the stack, Lua does this for us return 0; } @@ -337,28 +337,28 @@ static void push_stack_trace(lua_State* L_, int rc_, int stk_base_) STACK_GROW(L_, 5); - int const finalizers_index{ lua_gettop(L_) }; - int const err_handler_index{ ERROR_FULL_STACK ? (lua_pushcfunction(L_, lane_error), lua_gettop(L_)) : 0 }; + int const _finalizers_index{ lua_gettop(L_) }; + int const _err_handler_index{ ERROR_FULL_STACK ? (lua_pushcfunction(L_, lane_error), lua_gettop(L_)) : 0 }; int rc{ LUA_OK }; - for (int n = static_cast(lua_rawlen(L_, finalizers_index)); n > 0; --n) { + for (int n = static_cast(lua_rawlen(L_, _finalizers_index)); n > 0; --n) { int args = 0; lua_pushinteger(L_, n); // L_: ... finalizers lane_error n - lua_rawget(L_, finalizers_index); // L_: ... finalizers lane_error finalizer + lua_rawget(L_, _finalizers_index); // L_: ... finalizers lane_error finalizer LUA_ASSERT(L_, lua_isfunction(L_, -1)); if (lua_rc_ != LUA_OK) { // we have an error message and an optional stack trace at the bottom of the stack - LUA_ASSERT(L_, finalizers_index == 2 || finalizers_index == 3); + LUA_ASSERT(L_, _finalizers_index == 2 || _finalizers_index == 3); // char const* err_msg = lua_tostring(L_, 1); lua_pushvalue(L_, 1); // L_: ... finalizers lane_error finalizer err_msg // note we don't always have a stack trace for example when kCancelError, or when we got an error that doesn't call our handler, such as LUA_ERRMEM - if (finalizers_index == 3) { + if (_finalizers_index == 3) { lua_pushvalue(L_, 2); // L_: ... finalizers lane_error finalizer err_msg stack_trace } - args = finalizers_index - 1; + args = _finalizers_index - 1; } // if no error from the main body, finalizer doesn't receive any argument, else it gets the error message and optional stack trace - rc = lua_pcall(L_, args, 0, err_handler_index); // L_: ... finalizers lane_error err_msg2? + rc = lua_pcall(L_, args, 0, _err_handler_index); // L_: ... finalizers lane_error err_msg2? if (rc != LUA_OK) { push_stack_trace(L_, rc, lua_gettop(L_)); // L_: ... finalizers lane_error err_msg2? trace // If one finalizer fails, don't run the others. Return this @@ -371,7 +371,7 @@ static void push_stack_trace(lua_State* L_, int rc_, int stk_base_) if (rc != LUA_OK) { // ERROR_FULL_STACK accounts for the presence of lane_error on the stack - int const nb_err_slots{ lua_gettop(L_) - finalizers_index - ERROR_FULL_STACK }; + int const nb_err_slots{ lua_gettop(L_) - _finalizers_index - ERROR_FULL_STACK }; // a finalizer generated an error, this is what we leave of the stack for (int n = nb_err_slots; n > 0; --n) { lua_replace(L_, n); @@ -379,7 +379,7 @@ static void push_stack_trace(lua_State* L_, int rc_, int stk_base_) // leave on the stack only the error and optional stack trace produced by the error in the finalizer lua_settop(L_, nb_err_slots); // L_: ... lane_error trace } else { // no error from the finalizers, make sure only the original return values from the lane body remain on the stack - lua_settop(L_, finalizers_index - 1); + lua_settop(L_, _finalizers_index - 1); } return rc; @@ -395,7 +395,7 @@ static void push_stack_trace(lua_State* L_, int rc_, int stk_base_) */ static void selfdestruct_add(Lane* lane_) { - std::lock_guard guard{ lane_->U->selfdestructMutex }; + std::lock_guard _guard{ lane_->U->selfdestructMutex }; assert(lane_->selfdestruct_next == nullptr); lane_->selfdestruct_next = lane_->U->selfdestructFirst; @@ -407,29 +407,29 @@ static void selfdestruct_add(Lane* lane_) // A free-running lane has ended; remove it from selfdestruct chain [[nodiscard]] static bool selfdestruct_remove(Lane* lane_) { - bool found{ false }; - std::lock_guard guard{ lane_->U->selfdestructMutex }; + bool _found{ false }; + std::lock_guard _guard{ lane_->U->selfdestructMutex }; // Make sure (within the MUTEX) that we actually are in the chain // still (at process exit they will remove us from chain and then // cancel/kill). // if (lane_->selfdestruct_next != nullptr) { - Lane* volatile* ref = static_cast(&lane_->U->selfdestructFirst); + Lane* volatile* _ref = static_cast(&lane_->U->selfdestructFirst); - while (*ref != SELFDESTRUCT_END) { - if (*ref == lane_) { - *ref = lane_->selfdestruct_next; + while (*_ref != SELFDESTRUCT_END) { + if (*_ref == lane_) { + *_ref = lane_->selfdestruct_next; lane_->selfdestruct_next = nullptr; // the terminal shutdown should wait until the lane is done with its lua_close() lane_->U->selfdestructingCount.fetch_add(1, std::memory_order_release); - found = true; + _found = true; break; } - ref = static_cast(&((*ref)->selfdestruct_next)); + _ref = static_cast(&((*_ref)->selfdestruct_next)); } - assert(found); + assert(_found); } - return found; + return _found; } // ################################################################################################# @@ -442,11 +442,11 @@ static void selfdestruct_add(Lane* lane_) // LUAG_FUNC(set_singlethreaded) { - [[maybe_unused]] lua_Integer const cores{ luaL_optinteger(L_, 1, 1) }; + [[maybe_unused]] lua_Integer const _cores{ luaL_optinteger(L_, 1, 1) }; #ifdef PLATFORM_OSX #ifdef _UTILBINDTHREADTOCPU - if (cores > 1) { + if (_cores > 1) { raise_luaL_error(L_, "Limiting to N>1 cores not possible"); } // requires 'chudInitialize()' @@ -486,15 +486,15 @@ static constexpr RegistryUniqueKey kExtendedStackTraceRegKey{ 0x38147AD48FB426E2 LUAG_FUNC(set_error_reporting) { luaL_checktype(L_, 1, LUA_TSTRING); - char const* mode{ lua_tostring(L_, 1) }; + char const* _mode{ lua_tostring(L_, 1) }; lua_pushliteral(L_, "extended"); - bool const extended{ strcmp(mode, "extended") == 0 }; - bool const basic{ strcmp(mode, "basic") == 0 }; - if (!extended && !basic) { - raise_luaL_error(L_, "unsupported error reporting model %s", mode); + bool const _extended{ strcmp(_mode, "extended") == 0 }; + bool const _basic{ strcmp(_mode, "basic") == 0 }; + if (!_extended && !_basic) { + raise_luaL_error(L_, "unsupported error reporting model %s", _mode); } - kExtendedStackTraceRegKey.setValue(L_, [extended](lua_State* L_) { lua_pushboolean(L_, extended ? 1 : 0); }); + kExtendedStackTraceRegKey.setValue(L_, [extended = _extended](lua_State* L_) { lua_pushboolean(L_, extended ? 1 : 0); }); return 0; } @@ -512,7 +512,7 @@ LUAG_FUNC(set_error_reporting) } STACK_GROW(L_, 3); - bool const extended{ kExtendedStackTraceRegKey.readBoolValue(L_) }; + bool const _extended{ kExtendedStackTraceRegKey.readBoolValue(L_) }; STACK_CHECK(L_, 1); // Place stack trace at 'registry[kStackTraceRegKey]' for the 'lua_pcall()' @@ -531,32 +531,32 @@ LUAG_FUNC(set_error_reporting) // and we don't get '.currentline' for that. It's okay - just keep level // and table index growing separate. --AKa 22-Jan-2009 // - lua_Debug ar; - for (int n = 1; lua_getstack(L_, n, &ar); ++n) { - lua_getinfo(L_, extended ? "Sln" : "Sl", &ar); - if (extended) { + lua_Debug _ar; + for (int _n = 1; lua_getstack(L_, _n, &_ar); ++_n) { + lua_getinfo(L_, _extended ? "Sln" : "Sl", &_ar); + if (_extended) { lua_newtable(L_); // L_: some_error {} {} - lua_pushstring(L_, ar.source); // L_: some_error {} {} source + lua_pushstring(L_, _ar.source); // L_: some_error {} {} source lua_setfield(L_, -2, "source"); // L_: some_error {} {} - lua_pushinteger(L_, ar.currentline); // L_: some_error {} {} currentline + lua_pushinteger(L_, _ar.currentline); // L_: some_error {} {} currentline lua_setfield(L_, -2, "currentline"); // L_: some_error {} {} - lua_pushstring(L_, ar.name); // L_: some_error {} {} name + lua_pushstring(L_, _ar.name); // L_: some_error {} {} name lua_setfield(L_, -2, "name"); // L_: some_error {} {} - lua_pushstring(L_, ar.namewhat); // L_: some_error {} {} namewhat + lua_pushstring(L_, _ar.namewhat); // L_: some_error {} {} namewhat lua_setfield(L_, -2, "namewhat"); // L_: some_error {} {} - lua_pushstring(L_, ar.what); // L_: some_error {} {} what + lua_pushstring(L_, _ar.what); // L_: some_error {} {} what lua_setfield(L_, -2, "what"); // L_: some_error {} {} - } else if (ar.currentline > 0) { - lua_pushfstring(L_, "%s:%d", ar.short_src, ar.currentline); // L_: some_error {} "blah:blah" + } else if (_ar.currentline > 0) { + lua_pushfstring(L_, "%s:%d", _ar.short_src, _ar.currentline); // L_: some_error {} "blah:blah" } else { - lua_pushfstring(L_, "%s:?", ar.short_src); // L_: some_error {} "blah" + lua_pushfstring(L_, "%s:?", _ar.short_src); // L_: some_error {} "blah" } - lua_rawseti(L_, -2, (lua_Integer) n); // L_: some_error {} + lua_rawseti(L_, -2, static_cast(_n)); // L_: some_error {} } // store the stack trace table in the registry @@ -572,12 +572,12 @@ LUAG_FUNC(set_error_reporting) void Lane::changeDebugName(int nameIdx_) { // xxh64 of string "debugName" generated at https://www.pelock.com/products/hash-calculator - static constexpr RegistryUniqueKey hidden_regkey{ 0xA194E2645C57F6DDull }; + static constexpr RegistryUniqueKey kRegKey{ 0xA194E2645C57F6DDull }; nameIdx_ = lua_absindex(L, nameIdx_); luaL_checktype(L, nameIdx_, LUA_TSTRING); // L: ... "name" ... STACK_CHECK_START_REL(L, 0); // store a hidden reference in the registry to make sure the string is kept around even if a lane decides to manually change the "decoda_name" global... - hidden_regkey.setValue(L, [nameIdx = nameIdx_](lua_State* L_) { lua_pushvalue(L_, nameIdx); });// L: ... "name" ... + kRegKey.setValue(L, [nameIdx = nameIdx_](lua_State* L_) { lua_pushvalue(L_, nameIdx); }); // L: ... "name" ... // keep a direct pointer on the string debugName = lua_tostring(L, nameIdx_); // to see VM name in Decoda debugger Virtual Machine window @@ -594,11 +594,11 @@ void Lane::changeDebugName(int nameIdx_) LUAG_FUNC(set_debug_threadname) { // C s_lane structure is a light userdata upvalue - Lane* const lane{ lua_tolightuserdata(L_, lua_upvalueindex(1)) }; - LUA_ASSERT(L_, L_ == lane->L); // this function is exported in a lane's state, therefore it is callable only from inside the Lane's state + Lane* const _lane{ lua_tolightuserdata(L_, lua_upvalueindex(1)) }; + LUA_ASSERT(L_, L_ == _lane->L); // this function is exported in a lane's state, therefore it is callable only from inside the Lane's state lua_settop(L_, 1); STACK_CHECK_START_REL(L_, 0); - lane->changeDebugName(-1); + _lane->changeDebugName(-1); STACK_CHECK(L_, 0); return 0; } @@ -607,9 +607,9 @@ LUAG_FUNC(set_debug_threadname) LUAG_FUNC(get_debug_threadname) { - Lane* const lane{ ToLane(L_, 1) }; + Lane* const _lane{ ToLane(L_, 1) }; luaL_argcheck(L_, lua_gettop(L_) == 1, 2, "too many arguments"); - lua_pushstring(L_, lane->debugName); + lua_pushstring(L_, _lane->debugName); return 1; } @@ -617,14 +617,14 @@ LUAG_FUNC(get_debug_threadname) LUAG_FUNC(set_thread_priority) { - lua_Integer const prio{ luaL_checkinteger(L_, 1) }; + lua_Integer const _prio{ luaL_checkinteger(L_, 1) }; // public Lanes API accepts a generic range -3/+3 // that will be remapped into the platform-specific scheduler priority scheme // On some platforms, -3 is equivalent to -2 and +3 to +2 - if (prio < kThreadPrioMin || prio > kThreadPrioMax) { - raise_luaL_error(L_, "priority out of range: %d..+%d (%d)", kThreadPrioMin, kThreadPrioMax, prio); + if (_prio < kThreadPrioMin || _prio > kThreadPrioMax) { + raise_luaL_error(L_, "priority out of range: %d..+%d (%d)", kThreadPrioMin, kThreadPrioMax, _prio); } - THREAD_SET_PRIORITY(static_cast(prio), universe_get(L_)->sudo); + THREAD_SET_PRIORITY(static_cast(_prio), universe_get(L_)->sudo); return 0; } @@ -632,11 +632,11 @@ LUAG_FUNC(set_thread_priority) LUAG_FUNC(set_thread_affinity) { - lua_Integer const affinity{ luaL_checkinteger(L_, 1) }; - if (affinity <= 0) { - raise_luaL_error(L_, "invalid affinity (%d)", affinity); + lua_Integer const _affinity{ luaL_checkinteger(L_, 1) }; + if (_affinity <= 0) { + raise_luaL_error(L_, "invalid affinity (%d)", _affinity); } - THREAD_SET_AFFINITY(static_cast(affinity)); + THREAD_SET_AFFINITY(static_cast(_affinity)); return 0; } @@ -662,9 +662,9 @@ static struct errcode_name s_errcodes[] = { }; static char const* get_errcode_name(int _code) { - for (int i{ 0 }; i < 7; ++i) { - if (s_errcodes[i].code == _code) { - return s_errcodes[i].name; + for (errcode_name const& _entry : s_errcodes) { + if (_entry.code == _code) { + return _entry.name; } } return ""; @@ -675,61 +675,61 @@ static char const* get_errcode_name(int _code) static void lane_main(Lane* lane_) { - lua_State* const L{ lane_->L }; + lua_State* const _L{ lane_->L }; // wait until the launching thread has finished preparing L lane_->ready.wait(); - int rc{ LUA_ERRRUN }; + int _rc{ LUA_ERRRUN }; if (lane_->status == Lane::Pending) { // nothing wrong happened during preparation, we can work // At this point, the lane function and arguments are on the stack - int const nargs{ lua_gettop(L) - 1 }; - DEBUGSPEW_CODE(Universe* U = universe_get(L)); + int const nargs{ lua_gettop(_L) - 1 }; + DEBUGSPEW_CODE(Universe* U = universe_get(_L)); lane_->status = Lane::Running; // Pending -> Running // Tie "set_finalizer()" to the state - lua_pushcfunction(L, LG_set_finalizer); - populate_func_lookup_table(L, -1, "set_finalizer"); - lua_setglobal(L, "set_finalizer"); + lua_pushcfunction(_L, LG_set_finalizer); + populate_func_lookup_table(_L, -1, "set_finalizer"); + lua_setglobal(_L, "set_finalizer"); // Tie "set_debug_threadname()" to the state // But don't register it in the lookup database because of the Lane pointer upvalue - lua_pushlightuserdata(L, lane_); - lua_pushcclosure(L, LG_set_debug_threadname, 1); - lua_setglobal(L, "set_debug_threadname"); + lua_pushlightuserdata(_L, lane_); + lua_pushcclosure(_L, LG_set_debug_threadname, 1); + lua_setglobal(_L, "set_debug_threadname"); // Tie "cancel_test()" to the state - lua_pushcfunction(L, LG_cancel_test); - populate_func_lookup_table(L, -1, "cancel_test"); - lua_setglobal(L, "cancel_test"); + lua_pushcfunction(_L, LG_cancel_test); + populate_func_lookup_table(_L, -1, "cancel_test"); + lua_setglobal(_L, "cancel_test"); // this could be done in lane_new before the lane body function is pushed on the stack to avoid unnecessary stack slot shifting around #if ERROR_FULL_STACK // Tie "set_error_reporting()" to the state - lua_pushcfunction(L, LG_set_error_reporting); - populate_func_lookup_table(L, -1, "set_error_reporting"); - lua_setglobal(L, "set_error_reporting"); + lua_pushcfunction(_L, LG_set_error_reporting); + populate_func_lookup_table(_L, -1, "set_error_reporting"); + lua_setglobal(_L, "set_error_reporting"); - STACK_GROW(L, 1); - lua_pushcfunction(L, lane_error); // L: func args handler - lua_insert(L, 1); // L: handler func args + STACK_GROW(_L, 1); + lua_pushcfunction(_L, lane_error); // L: func args handler + lua_insert(_L, 1); // L: handler func args #endif // L: ERROR_FULL_STACK - rc = lua_pcall(L, nargs, LUA_MULTRET, ERROR_FULL_STACK); // L: retvals|err + _rc = lua_pcall(_L, nargs, LUA_MULTRET, ERROR_FULL_STACK); // L: retvals|err #if ERROR_FULL_STACK - lua_remove(L, 1); // L: retvals|error + lua_remove(_L, 1); // L: retvals|error #endif // ERROR_FULL_STACK // in case of error and if it exists, fetch stack trace from registry and push it - push_stack_trace(L, rc, 1); // L: retvals|error [trace] + push_stack_trace(_L, _rc, 1); // L: retvals|error [trace] - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "Lane %p body: %s (%s)\n" INDENT_END(U), L, get_errcode_name(rc), kCancelError.equals(L, 1) ? "cancelled" : lua_typename(L, lua_type(L, 1)))); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "Lane %p body: %s (%s)\n" INDENT_END(U), _L, get_errcode_name(_rc), kCancelError.equals(_L, 1) ? "cancelled" : lua_typename(_L, lua_type(_L, 1)))); // Call finalizers, if the script has set them up. // - int rc2{ run_finalizers(L, rc) }; - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "Lane %p finalizer: %s\n" INDENT_END(U), L, get_errcode_name(rc2))); - if (rc2 != LUA_OK) { // Error within a finalizer! + int _rc2{ run_finalizers(_L, _rc) }; + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "Lane %p finalizer: %s\n" INDENT_END(U), _L, get_errcode_name(_rc2))); + if (_rc2 != LUA_OK) { // Error within a finalizer! // the finalizer generated an error, and left its own error message [and stack trace] on the stack - rc = rc2; // we're overruling the earlier script error or normal return + _rc = _rc2; // we're overruling the earlier script error or normal return } lane_->waiting_on = nullptr; // just in case if (selfdestruct_remove(lane_)) { // check and remove (under lock!) @@ -750,12 +750,12 @@ static void lane_main(Lane* lane_) if (lane_) { // leave results (1..top) or error message + stack trace (1..2) on the stack - master will copy them - Lane::Status const st = (rc == LUA_OK) ? Lane::Done : kCancelError.equals(L, 1) ? Lane::Cancelled : Lane::Error; + Lane::Status const _st = (_rc == LUA_OK) ? Lane::Done : kCancelError.equals(_L, 1) ? Lane::Cancelled : Lane::Error; { // 'doneMutex' protects the -> Done|Error|Cancelled state change std::lock_guard lock{ lane_->doneMutex }; - lane_->status = st; + lane_->status = _st; lane_->doneCondVar.notify_one(); // wake up master (while 'lane_->doneMutex' is on) } } @@ -769,17 +769,17 @@ static void lane_main(Lane* lane_) // upvalue[1]: _G.require LUAG_FUNC(require) { - char const* name = lua_tostring(L_, 1); // L_: "name" ... - int const nargs{ lua_gettop(L_) }; - DEBUGSPEW_CODE(Universe* U = universe_get(L_)); + char const* _name{ lua_tostring(L_, 1) }; // L_: "name" ... + int const _nargs{ lua_gettop(L_) }; + DEBUGSPEW_CODE(Universe * _U{ universe_get(L_) }); STACK_CHECK_START_REL(L_, 0); - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lanes.require %s BEGIN\n" INDENT_END(U), name)); - DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U }); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lanes.require %s BEGIN\n" INDENT_END(_U), _name)); + DEBUGSPEW_CODE(DebugSpewIndentScope _scope{ _U }); lua_pushvalue(L_, lua_upvalueindex(1)); // L_: "name" ... require lua_insert(L_, 1); // L_: require "name" ... - lua_call(L_, nargs, 1); // L_: module - populate_func_lookup_table(L_, -1, name); - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lanes.require %s END\n" INDENT_END(U), name)); + lua_call(L_, _nargs, 1); // L_: module + populate_func_lookup_table(L_, -1, _name); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lanes.require %s END\n" INDENT_END(_U), _name)); STACK_CHECK(L_, 0); return 1; } @@ -791,17 +791,17 @@ LUAG_FUNC(require) // lanes.register( "modname", module) LUAG_FUNC(register) { - char const* name = luaL_checkstring(L_, 1); - LuaType const mod_type{ lua_type_as_enum(L_, 2) }; + char const* _name{ luaL_checkstring(L_, 1) }; + LuaType const _mod_type{ lua_type_as_enum(L_, 2) }; // ignore extra parameters, just in case lua_settop(L_, 2); - luaL_argcheck(L_, (mod_type == LuaType::TABLE) || (mod_type == LuaType::FUNCTION), 2, "unexpected module type"); + luaL_argcheck(L_, (_mod_type == LuaType::TABLE) || (_mod_type == LuaType::FUNCTION), 2, "unexpected module type"); DEBUGSPEW_CODE(Universe* U = universe_get(L_)); STACK_CHECK_START_REL(L_, 0); // "name" mod_table - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lanes.register %s BEGIN\n" INDENT_END(U), name)); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lanes.register %s BEGIN\n" INDENT_END(U), _name)); DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U }); - populate_func_lookup_table(L_, -1, name); - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lanes.register %s END\n" INDENT_END(U), name)); + populate_func_lookup_table(L_, -1, _name); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lanes.register %s END\n" INDENT_END(U), _name)); STACK_CHECK(L_, 0); return 0; } @@ -827,37 +827,37 @@ static constexpr UniqueKey kLaneGC{ 0x5D6122141727F960ull }; LUAG_FUNC(lane_new) { // first 8 args: func libs priority globals package required gc_cb name - char const* const libs_str{ lua_tostring(L_, 2) }; - bool const have_priority{ !lua_isnoneornil(L_, 3) }; - int const priority{ have_priority ? static_cast(lua_tointeger(L_, 3)) : kThreadPrioDefault }; - int const globals_idx{ lua_isnoneornil(L_, 4) ? 0 : 4 }; - int const package_idx{ lua_isnoneornil(L_, 5) ? 0 : 5 }; - int const required_idx{ lua_isnoneornil(L_, 6) ? 0 : 6 }; - int const gc_cb_idx{ lua_isnoneornil(L_, 7) ? 0 : 7 }; - int const name_idx{ lua_isnoneornil(L_, 8) ? 0 : 8 }; + char const* const _libs_str{ lua_tostring(L_, 2) }; + bool const _have_priority{ !lua_isnoneornil(L_, 3) }; + int const _priority{ _have_priority ? static_cast(lua_tointeger(L_, 3)) : kThreadPrioDefault }; + int const _globals_idx{ lua_isnoneornil(L_, 4) ? 0 : 4 }; + int const _package_idx{ lua_isnoneornil(L_, 5) ? 0 : 5 }; + int const _required_idx{ lua_isnoneornil(L_, 6) ? 0 : 6 }; + int const _gc_cb_idx{ lua_isnoneornil(L_, 7) ? 0 : 7 }; + int const _name_idx{ lua_isnoneornil(L_, 8) ? 0 : 8 }; static constexpr int kFixedArgsIdx{ 8 }; - int const nargs{ lua_gettop(L_) - kFixedArgsIdx }; - Universe* const U{ universe_get(L_) }; - LUA_ASSERT(L_, nargs >= 0); + int const _nargs{ lua_gettop(L_) - kFixedArgsIdx }; + Universe* const _U{ universe_get(L_) }; + LUA_ASSERT(L_, _nargs >= 0); // public Lanes API accepts a generic range -3/+3 // that will be remapped into the platform-specific scheduler priority scheme // On some platforms, -3 is equivalent to -2 and +3 to +2 - if (have_priority && (priority < kThreadPrioMin || priority > kThreadPrioMax)) { - raise_luaL_error(L_, "Priority out of range: %d..+%d (%d)", kThreadPrioMin, kThreadPrioMax, priority); + if (_have_priority && (_priority < kThreadPrioMin || _priority > kThreadPrioMax)) { + raise_luaL_error(L_, "Priority out of range: %d..+%d (%d)", kThreadPrioMin, kThreadPrioMax, _priority); } /* --- Create and prepare the sub state --- */ - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: setup\n" INDENT_END(U))); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: setup\n" INDENT_END(_U))); // populate with selected libraries at the same time. - lua_State* const L2{ luaG_newstate(U, SourceState{ L_ }, libs_str) }; // L_: [8 args] ... L2: - STACK_CHECK_START_REL(L2, 0); + lua_State* const _L2{ luaG_newstate(_U, SourceState{ L_ }, _libs_str) }; // L_: [8 args] ... L2: + STACK_CHECK_START_REL(_L2, 0); // 'lane' is allocated from heap, not Lua, since its life span may surpass the handle's (if free running thread) - Lane* const lane{ new (U) Lane{ U, L2 } }; - if (lane == nullptr) { + Lane* const _lane{ new (_U) Lane{ _U, _L2 } }; + if (_lane == nullptr) { raise_luaL_error(L_, "could not create lane: out of memory"); } @@ -959,135 +959,135 @@ LUAG_FUNC(lane_new) m_lane->ready.count_down(); m_lane = nullptr; } - } onExit{ L_, lane, gc_cb_idx, name_idx DEBUGSPEW_COMMA_PARAM(U) }; + } onExit{ L_, _lane, _gc_cb_idx, _name_idx DEBUGSPEW_COMMA_PARAM(_U) }; // launch the thread early, it will sync with a std::latch to parallelize OS thread warmup and L2 preparation - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: launching thread\n" INDENT_END(U))); - lane->startThread(priority); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: launching thread\n" INDENT_END(_U))); + _lane->startThread(_priority); - STACK_GROW(L2, nargs + 3); + STACK_GROW(_L2, _nargs + 3); STACK_GROW(L_, 3); STACK_CHECK_START_REL(L_, 0); // package - if (package_idx != 0) { - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: update 'package'\n" INDENT_END(U))); + if (_package_idx != 0) { + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: update 'package'\n" INDENT_END(_U))); // when copying with mode LookupMode::LaneBody, should raise an error in case of problem, not leave it one the stack - InterCopyContext c{ U, DestState{ L2 }, SourceState{ L_ }, {}, SourceIndex{ package_idx }, {}, {}, {} }; + InterCopyContext c{ _U, DestState{ _L2 }, SourceState{ L_ }, {}, SourceIndex{ _package_idx }, {}, {}, {} }; [[maybe_unused]] InterCopyResult const ret{ c.inter_copy_package() }; LUA_ASSERT(L_, ret == InterCopyResult::Success); // either all went well, or we should not even get here } // modules to require in the target lane *before* the function is transfered! - if (required_idx != 0) { - int nbRequired = 1; - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: require 'required' list\n" INDENT_END(U))); - DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U }); + if (_required_idx != 0) { + int _nbRequired{ 1 }; + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: require 'required' list\n" INDENT_END(_U))); + DEBUGSPEW_CODE(DebugSpewIndentScope scope{ _U }); // should not happen, was checked in lanes.lua before calling lane_new() - if (lua_type(L_, required_idx) != LUA_TTABLE) { - raise_luaL_error(L_, "expected required module list as a table, got %s", luaL_typename(L_, required_idx)); + if (lua_type(L_, _required_idx) != LUA_TTABLE) { + raise_luaL_error(L_, "expected required module list as a table, got %s", luaL_typename(L_, _required_idx)); } lua_pushnil(L_); // L_: [8 args] args... nil L2: - while (lua_next(L_, required_idx) != 0) { // L_: [8 args] args... n "modname" L2: - if (lua_type(L_, -1) != LUA_TSTRING || lua_type(L_, -2) != LUA_TNUMBER || lua_tonumber(L_, -2) != nbRequired) { + while (lua_next(L_, _required_idx) != 0) { // L_: [8 args] args... n "modname" L2: + if (lua_type(L_, -1) != LUA_TSTRING || lua_type(L_, -2) != LUA_TNUMBER || lua_tonumber(L_, -2) != _nbRequired) { raise_luaL_error(L_, "required module list should be a list of strings"); } else { // require the module in the target state, and populate the lookup table there too size_t len; char const* name = lua_tolstring(L_, -1, &len); - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: require '%s'\n" INDENT_END(U), name)); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: require '%s'\n" INDENT_END(_U), name)); // require the module in the target lane - lua_getglobal(L2, "require"); // L_: [8 args] args... n "modname" L2: require()? - if (lua_isnil(L2, -1)) { - lua_pop(L2, 1); // L_: [8 args] args... n "modname" L2: + lua_getglobal(_L2, "require"); // L_: [8 args] args... n "modname" L2: require()? + if (lua_isnil(_L2, -1)) { + lua_pop(_L2, 1); // L_: [8 args] args... n "modname" L2: raise_luaL_error(L_, "cannot pre-require modules without loading 'package' library first"); } else { - lua_pushlstring(L2, name, len); // L_: [8 args] args... n "modname" L2: require() name - if (lua_pcall(L2, 1, 1, 0) != LUA_OK) { // L_: [8 args] args... n "modname" L2: ret/errcode + lua_pushlstring(_L2, name, len); // L_: [8 args] args... n "modname" L2: require() name + if (lua_pcall(_L2, 1, 1, 0) != LUA_OK) { // L_: [8 args] args... n "modname" L2: ret/errcode // propagate error to main state if any - InterCopyContext c{ U, DestState{ L_ }, SourceState{ L2 }, {}, {}, {}, {}, {} }; - std::ignore = c.inter_move(1); // L_: [8 args] args... n "modname" error L2: + InterCopyContext _c{ _U, DestState{ L_ }, SourceState{ _L2 }, {}, {}, {}, {}, {} }; + std::ignore = _c.inter_move(1); // L_: [8 args] args... n "modname" error L2: raise_lua_error(L_); } // here the module was successfully required // L_: [8 args] args... n "modname" L2: ret // after requiring the module, register the functions it exported in our name<->function database - populate_func_lookup_table(L2, -1, name); - lua_pop(L2, 1); // L_: [8 args] args... n "modname" L2: + populate_func_lookup_table(_L2, -1, name); + lua_pop(_L2, 1); // L_: [8 args] args... n "modname" L2: } } lua_pop(L_, 1); // L_: func libs priority globals package required gc_cb [... args ...] n - ++nbRequired; + ++_nbRequired; } // L_: [8 args] args... } STACK_CHECK(L_, 0); - STACK_CHECK(L2, 0); // L_: [8 args] args... L2: + STACK_CHECK(_L2, 0); // L_: [8 args] args... L2: // Appending the specified globals to the global environment // *after* stdlibs have been loaded and modules required, in case we transfer references to native functions they exposed... // - if (globals_idx != 0) { - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: transfer globals\n" INDENT_END(U))); - if (!lua_istable(L_, globals_idx)) { - raise_luaL_error(L_, "Expected table, got %s", luaL_typename(L_, globals_idx)); + if (_globals_idx != 0) { + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: transfer globals\n" INDENT_END(_U))); + if (!lua_istable(L_, _globals_idx)) { + raise_luaL_error(L_, "Expected table, got %s", luaL_typename(L_, _globals_idx)); } - DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U }); + DEBUGSPEW_CODE(DebugSpewIndentScope _scope{ _U }); lua_pushnil(L_); // L_: [8 args] args... nil L2: // Lua 5.2 wants us to push the globals table on the stack - InterCopyContext c{ U, DestState{ L2 }, SourceState{ L_ }, {}, {}, {}, {}, {} }; - lua_pushglobaltable(L2); // L_: [8 args] args... nil L2: _G - while (lua_next(L_, globals_idx)) { // L_: [8 args] args... k v L2: _G - std::ignore = c.inter_copy(2); // L_: [8 args] args... k v L2: _G k v + InterCopyContext _c{ _U, DestState{ _L2 }, SourceState{ L_ }, {}, {}, {}, {}, {} }; + lua_pushglobaltable(_L2); // L_: [8 args] args... nil L2: _G + while (lua_next(L_, _globals_idx)) { // L_: [8 args] args... k v L2: _G + std::ignore = _c.inter_copy(2); // L_: [8 args] args... k v L2: _G k v // assign it in L2's globals table - lua_rawset(L2, -3); // L_: [8 args] args... k v L2: _G + lua_rawset(_L2, -3); // L_: [8 args] args... k v L2: _G lua_pop(L_, 1); // L_: [8 args] args... k } // L_: [8 args] args... - lua_pop(L2, 1); // L_: [8 args] args... L2: + lua_pop(_L2, 1); // L_: [8 args] args... L2: } STACK_CHECK(L_, 0); - STACK_CHECK(L2, 0); + STACK_CHECK(_L2, 0); // Lane main function - LuaType const func_type{ lua_type_as_enum(L_, 1) }; - if (func_type == LuaType::FUNCTION) { - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: transfer lane body\n" INDENT_END(U))); - DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U }); + LuaType const _func_type{ lua_type_as_enum(L_, 1) }; + if (_func_type == LuaType::FUNCTION) { + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: transfer lane body\n" INDENT_END(_U))); + DEBUGSPEW_CODE(DebugSpewIndentScope _scope{ _U }); lua_pushvalue(L_, 1); // L_: [8 args] args... func L2: - InterCopyContext c{ U, DestState{ L2 }, SourceState{ L_ }, {}, {}, {}, {}, {} }; - InterCopyResult const res{ c.inter_move(1) }; // L_: [8 args] args... L2: func - if (res != InterCopyResult::Success) { + InterCopyContext _c{ _U, DestState{ _L2 }, SourceState{ L_ }, {}, {}, {}, {}, {} }; + InterCopyResult const _res{ _c.inter_move(1) }; // L_: [8 args] args... L2: func + if (_res != InterCopyResult::Success) { raise_luaL_error(L_, "tried to copy unsupported types"); } - } else if (func_type == LuaType::STRING) { - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: compile lane body\n" INDENT_END(U))); + } else if (_func_type == LuaType::STRING) { + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: compile lane body\n" INDENT_END(_U))); // compile the string - if (luaL_loadstring(L2, lua_tostring(L_, 1)) != 0) { // L_: [8 args] args... L2: func + if (luaL_loadstring(_L2, lua_tostring(L_, 1)) != 0) { // L_: [8 args] args... L2: func raise_luaL_error(L_, "error when parsing lane function code"); } } else { - raise_luaL_error(L_, "Expected function, got %s", lua_typename(L_, func_type)); + raise_luaL_error(L_, "Expected function, got %s", lua_typename(L_, _func_type)); } STACK_CHECK(L_, 0); - STACK_CHECK(L2, 1); - LUA_ASSERT(L_, lua_isfunction(L2, 1)); + STACK_CHECK(_L2, 1); + LUA_ASSERT(L_, lua_isfunction(_L2, 1)); // revive arguments - if (nargs > 0) { - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: transfer lane arguments\n" INDENT_END(U))); - DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U }); - InterCopyContext c{ U, DestState{ L2 }, SourceState{ L_ }, {}, {}, {}, {}, {} }; - InterCopyResult const res{ c.inter_move(nargs) }; // L_: [8 args] L2: func args... + if (_nargs > 0) { + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "lane_new: transfer lane arguments\n" INDENT_END(_U))); + DEBUGSPEW_CODE(DebugSpewIndentScope _scope{ _U }); + InterCopyContext _c{ _U, DestState{ _L2 }, SourceState{ L_ }, {}, {}, {}, {}, {} }; + InterCopyResult const res{ _c.inter_move(_nargs) }; // L_: [8 args] L2: func args... if (res != InterCopyResult::Success) { raise_luaL_error(L_, "tried to copy unsupported types"); } } - STACK_CHECK(L_, -nargs); + STACK_CHECK(L_, -_nargs); LUA_ASSERT(L_, lua_gettop(L_) == kFixedArgsIdx); // Store 'lane' in the lane's registry, for 'cancel_test()' (we do cancel tests at pending send/receive). - kLanePointerRegKey.setValue(L2, [lane](lua_State* L_) { lua_pushlightuserdata(L_, lane); }); // L_: [8 args] L2: func args... - STACK_CHECK(L2, 1 + nargs); + kLanePointerRegKey.setValue(_L2, [lane = _lane](lua_State* L_) { lua_pushlightuserdata(L_, lane); });// L_: [8 args] L2: func args... + STACK_CHECK(_L2, 1 + _nargs); STACK_CHECK_RESET_REL(L_, 0); // all went well, the lane's thread can start working @@ -1112,8 +1112,8 @@ LUAG_FUNC(lane_new) // [[nodiscard]] static int lane_gc(lua_State* L_) { - bool have_gc_cb{ false }; - Lane* const lane{ ToLane(L_, 1) }; // L_: ud + bool _have_gc_cb{ false }; + Lane* const _lane{ ToLane(L_, 1) }; // L_: ud // if there a gc callback? lua_getiuservalue(L_, 1, 1); // L_: ud uservalue @@ -1121,35 +1121,35 @@ LUAG_FUNC(lane_new) lua_rawget(L_, -2); // L_: ud uservalue gc_cb|nil if (!lua_isnil(L_, -1)) { lua_remove(L_, -2); // L_: ud gc_cb|nil - lua_pushstring(L_, lane->debugName); // L_: ud gc_cb name - have_gc_cb = true; + lua_pushstring(L_, _lane->debugName); // L_: ud gc_cb name + _have_gc_cb = true; } else { lua_pop(L_, 2); // L_: ud } // We can read 'lane->status' without locks, but not wait for it - if (lane->status < Lane::Done) { + if (_lane->status < Lane::Done) { // still running: will have to be cleaned up later - selfdestruct_add(lane); - assert(lane->selfdestruct_next); - if (have_gc_cb) { + selfdestruct_add(_lane); + assert(_lane->selfdestruct_next); + if (_have_gc_cb) { lua_pushliteral(L_, "selfdestruct"); // L_: ud gc_cb name status lua_call(L_, 2, 0); // L_: ud } return 0; - } else if (lane->L) { + } else if (_lane->L) { // no longer accessing the Lua VM: we can close right now - lua_close(lane->L); - lane->L = nullptr; + lua_close(_lane->L); + _lane->L = nullptr; // just in case, but s will be freed soon so... - lane->debugName = ""; + _lane->debugName = ""; } // Clean up after a (finished) thread - delete lane; + delete _lane; // do this after lane cleanup in case the callback triggers an error - if (have_gc_cb) { + if (_have_gc_cb) { lua_pushliteral(L_, "closed"); // L_: ud gc_cb name status lua_call(L_, 2, 0); // L_: ud } @@ -1170,7 +1170,7 @@ LUAG_FUNC(lane_new) // [[nodiscard]] static char const* thread_status_string(Lane::Status status_) { - char const* const str{ + char const* const _str{ (status_ == Lane::Pending) ? "pending" : (status_ == Lane::Running) ? "running" : // like in 'co.status()' (status_ == Lane::Waiting) ? "waiting" : @@ -1179,17 +1179,17 @@ LUAG_FUNC(lane_new) (status_ == Lane::Cancelled) ? "cancelled" : nullptr }; - return str; + return _str; } // ################################################################################################# void Lane::pushThreadStatus(lua_State* L_) { - char const* const str{ thread_status_string(status) }; - LUA_ASSERT(L_, str); + char const* const _str{ thread_status_string(status) }; + LUA_ASSERT(L_, _str); - lua_pushstring(L_, str); + lua_pushstring(L_, _str); } // ################################################################################################# @@ -1204,14 +1204,14 @@ void Lane::pushThreadStatus(lua_State* L_) // LUAG_FUNC(thread_join) { - Lane* const lane{ ToLane(L_, 1) }; - lua_State* const L2{ lane->L }; + Lane* const _lane{ ToLane(L_, 1) }; + lua_State* const _L2{ _lane->L }; - std::chrono::time_point until{ std::chrono::time_point::max() }; + std::chrono::time_point _until{ std::chrono::time_point::max() }; if (lua_type(L_, 2) == LUA_TNUMBER) { // we don't want to use lua_isnumber() because of autocoercion lua_Duration const duration{ lua_tonumber(L_, 2) }; if (duration.count() >= 0.0) { - until = std::chrono::steady_clock::now() + std::chrono::duration_cast(duration); + _until = std::chrono::steady_clock::now() + std::chrono::duration_cast(duration); } else { raise_luaL_argerror(L_, 2, "duration cannot be < 0"); } @@ -1220,9 +1220,9 @@ LUAG_FUNC(thread_join) raise_luaL_argerror(L_, 2, "incorrect duration type"); } - bool const done{ !lane->thread.joinable() || lane->waitForCompletion(until) }; + bool const done{ !_lane->thread.joinable() || _lane->waitForCompletion(_until) }; lua_settop(L_, 1); // L_: lane - if (!done || !L2) { + if (!done || !_L2) { lua_pushnil(L_); // L_: lane nil lua_pushliteral(L_, "timeout"); // L_: lane nil "timeout" return 2; @@ -1231,51 +1231,51 @@ LUAG_FUNC(thread_join) STACK_CHECK_START_REL(L_, 0); // L_: lane // Thread is Done/Error/Cancelled; all ours now - int ret{ 0 }; + int _ret{ 0 }; // debugName is a pointer to string possibly interned in the lane's state, that no longer exists when the state is closed // so store it in the userdata uservalue at a key that can't possibly collide - lane->securizeDebugName(L_); - switch (lane->status) { + _lane->securizeDebugName(L_); + switch (_lane->status) { case Lane::Done: { - int const n{ lua_gettop(L2) }; // whole L2 stack + int const _n{ lua_gettop(_L2) }; // whole L2 stack if ( - (n > 0) && - (InterCopyContext{ lane->U, DestState{ L_ }, SourceState{ L2 }, {}, {}, {}, {}, {} }.inter_move(n) != InterCopyResult::Success) + (_n > 0) && + (InterCopyContext{ _lane->U, DestState{ L_ }, SourceState{ _L2 }, {}, {}, {}, {}, {} }.inter_move(_n) != InterCopyResult::Success) ) { // L_: lane results L2: raise_luaL_error(L_, "tried to copy unsupported types"); } - ret = n; + _ret = _n; } break; case Lane::Error: { - int const n{ lua_gettop(L2) }; // L_: lane L2: "err" [trace] + int const _n{ lua_gettop(_L2) }; // L_: lane L2: "err" [trace] STACK_GROW(L_, 3); lua_pushnil(L_); // L_: lane nil // even when ERROR_FULL_STACK, if the error is not LUA_ERRRUN, the handler wasn't called, and we only have 1 error message on the stack ... - InterCopyContext c{ lane->U, DestState{ L_ }, SourceState{ L2 }, {}, {}, {}, {}, {} }; - if (c.inter_move(n) != InterCopyResult::Success) { // L_: lane nil "err" [trace] L2: - raise_luaL_error(L_, "tried to copy unsupported types: %s", lua_tostring(L_, -n)); + InterCopyContext _c{ _lane->U, DestState{ L_ }, SourceState{ _L2 }, {}, {}, {}, {}, {} }; + if (_c.inter_move(_n) != InterCopyResult::Success) { // L_: lane nil "err" [trace] L2: + raise_luaL_error(L_, "tried to copy unsupported types: %s", lua_tostring(L_, -_n)); } - ret = 1 + n; + _ret = 1 + _n; } break; case Lane::Cancelled: - ret = 0; + _ret = 0; break; default: - DEBUGSPEW_CODE(fprintf(stderr, "Status: %d\n", lane->status)); + DEBUGSPEW_CODE(fprintf(stderr, "Status: %d\n", _lane->status)); LUA_ASSERT(L_, false); - ret = 0; + _ret = 0; } - lua_close(L2); - lane->L = nullptr; - STACK_CHECK(L_, ret); - return ret; + lua_close(_L2); + _lane->L = nullptr; + STACK_CHECK(L_, _ret); + return _ret; } // ################################################################################################# @@ -1291,7 +1291,7 @@ LUAG_FUNC(thread_index) { static constexpr int kSelf{ 1 }; static constexpr int kKey{ 2 }; - Lane* const lane{ ToLane(L_, kSelf) }; + Lane* const _lane{ ToLane(L_, kSelf) }; LUA_ASSERT(L_, lua_gettop(L_) == 2); STACK_GROW(L_, 8); // up to 8 positions are needed in case of error propagation @@ -1314,9 +1314,9 @@ LUAG_FUNC(thread_index) // check if we already fetched the values from the thread or not lua_pushinteger(L_, 0); lua_rawget(L_, kUsr); - bool const fetched{ !lua_isnil(L_, -1) }; + bool const _fetched{ !lua_isnil(L_, -1) }; lua_pop(L_, 1); // back to our 2 args + uservalue on the stack - if (!fetched) { + if (!_fetched) { lua_pushinteger(L_, 0); lua_pushboolean(L_, 1); lua_rawset(L_, kUsr); @@ -1324,22 +1324,22 @@ LUAG_FUNC(thread_index) lua_pushcfunction(L_, LG_thread_join); lua_pushvalue(L_, kSelf); lua_call(L_, 1, LUA_MULTRET); // all return values are on the stack, at slots 4+ - switch (lane->status) { + switch (_lane->status) { default: // this is an internal error, we probably never get here lua_settop(L_, 0); lua_pushliteral(L_, "Unexpected status: "); - lua_pushstring(L_, thread_status_string(lane->status)); + lua_pushstring(L_, thread_status_string(_lane->status)); lua_concat(L_, 2); raise_lua_error(L_); [[fallthrough]]; // fall through if we are killed, as we got nil, "killed" on the stack case Lane::Done: // got regular return values { - int const nvalues{ lua_gettop(L_) - 3 }; - for (int i = nvalues; i > 0; --i) { + int const _nvalues{ lua_gettop(L_) - 3 }; + for (int _i = _nvalues; _i > 0; --_i) { // pop the last element of the stack, to store it in the uservalue at its proper index - lua_rawseti(L_, kUsr, i); + lua_rawseti(L_, kUsr, _i); } } break; @@ -1361,8 +1361,8 @@ LUAG_FUNC(thread_index) } } lua_settop(L_, 3); // L_: self KEY ENV - int const key{ static_cast(lua_tointeger(L_, kKey)) }; - if (key != -1) { + int const _key{ static_cast(lua_tointeger(L_, kKey)) }; + if (_key != -1) { lua_pushnumber(L_, -1); // L_: self KEY ENV -1 lua_rawget(L_, kUsr); // L_: self KEY ENV "error"|nil if (!lua_isnil(L_, -1)) { // L_: an error was stored @@ -1388,15 +1388,15 @@ LUAG_FUNC(thread_index) lua_pop(L_, 1); // L_: self KEY ENV } } - lua_rawgeti(L_, kUsr, key); + lua_rawgeti(L_, kUsr, _key); } return 1; } if (lua_type(L_, kKey) == LUA_TSTRING) { - char const* const keystr{ lua_tostring(L_, kKey) }; + char const* const _keystr{ lua_tostring(L_, kKey) }; lua_settop(L_, 2); // keep only our original arguments on the stack - if (strcmp(keystr, "status") == 0) { - lane->pushThreadStatus(L_); // push the string representing the status + if (strcmp(_keystr, "status") == 0) { + _lane->pushThreadStatus(L_); // push the string representing the status return 1; } // return self.metatable[key] @@ -1405,7 +1405,7 @@ LUAG_FUNC(thread_index) lua_rawget(L_, -2); // L_: mt value // only "cancel" and "join" are registered as functions, any other string will raise an error if (!lua_iscfunction(L_, -1)) { - raise_luaL_error(L_, "can't index a lane with '%s'", keystr); + raise_luaL_error(L_, "can't index a lane with '%s'", _keystr); } return 1; } @@ -1428,27 +1428,27 @@ LUAG_FUNC(thread_index) // Return a list of all known lanes LUAG_FUNC(threads) { - int const top{ lua_gettop(L_) }; - Universe* const U{ universe_get(L_) }; + int const _top{ lua_gettop(L_) }; + Universe* const _U{ universe_get(L_) }; // List _all_ still running threads - std::lock_guard guard{ U->trackingMutex }; - if (U->trackingFirst && U->trackingFirst != TRACKING_END) { - Lane* lane{ U->trackingFirst }; - int index{ 0 }; + std::lock_guard _guard{ _U->trackingMutex }; + if (_U->trackingFirst && _U->trackingFirst != TRACKING_END) { + Lane* _lane{ _U->trackingFirst }; + int _index{ 0 }; lua_newtable(L_); // L_: {} - while (lane != TRACKING_END) { + while (_lane != TRACKING_END) { // insert a { name='', status='' } tuple, so that several lanes with the same name can't clobber each other lua_createtable(L_, 0, 2); // L_: {} {} - lua_pushstring(L_, lane->debugName); // L_: {} {} "name" + lua_pushstring(L_, _lane->debugName); // L_: {} {} "name" lua_setfield(L_, -2, "name"); // L_: {} {} - lane->pushThreadStatus(L_); // L_: {} {} "status" + _lane->pushThreadStatus(L_); // L_: {} {} "status" lua_setfield(L_, -2, "status"); // L_: {} {} - lua_rawseti(L_, -2, ++index); // L_: {} - lane = lane->tracking_next; + lua_rawseti(L_, -2, ++_index); // L_: {} + _lane = _lane->tracking_next; } } - return lua_gettop(L_) - top; // L_: 0 or 1 + return lua_gettop(L_) - _top; // L_: 0 or 1 } #endif // HAVE_LANE_TRACKING() @@ -1464,8 +1464,8 @@ LUAG_FUNC(threads) */ LUAG_FUNC(now_secs) { - auto const now{ std::chrono::system_clock::now() }; - lua_Duration duration{ now.time_since_epoch() }; + auto const _now{ std::chrono::system_clock::now() }; + lua_Duration duration{ _now.time_since_epoch() }; lua_pushnumber(L_, duration.count()); return 1; @@ -1487,38 +1487,38 @@ LUAG_FUNC(wakeup_conv) // .isdst (daylight saving on/off) STACK_CHECK_START_REL(L_, 0); - auto readInteger = [L = L_](char const* name_) { + auto _readInteger = [L = L_](char const* name_) { lua_getfield(L, 1, name_); lua_Integer const val{ lua_tointeger(L, -1) }; lua_pop(L, 1); return static_cast(val); }; - int const year{ readInteger("year") }; - int const month{ readInteger("month") }; - int const day{ readInteger("day") }; - int const hour{ readInteger("hour") }; - int const min{ readInteger("min") }; - int const sec{ readInteger("sec") }; + int const _year{ _readInteger("year") }; + int const _month{ _readInteger("month") }; + int const _day{ _readInteger("day") }; + int const _hour{ _readInteger("hour") }; + int const _min{ _readInteger("min") }; + int const _sec{ _readInteger("sec") }; STACK_CHECK(L_, 0); // If Lua table has '.isdst' we trust that. If it does not, we'll let // 'mktime' decide on whether the time is within DST or not (value -1). // lua_getfield(L_, 1, "isdst"); - int const isdst{ lua_isboolean(L_, -1) ? lua_toboolean(L_, -1) : -1 }; + int const _isdst{ lua_isboolean(L_, -1) ? lua_toboolean(L_, -1) : -1 }; lua_pop(L_, 1); STACK_CHECK(L_, 0); - std::tm t{}; - t.tm_year = year - 1900; - t.tm_mon = month - 1; // 0..11 - t.tm_mday = day; // 1..31 - t.tm_hour = hour; // 0..23 - t.tm_min = min; // 0..59 - t.tm_sec = sec; // 0..60 - t.tm_isdst = isdst; // 0/1/negative + std::tm _t{}; + _t.tm_year = _year - 1900; + _t.tm_mon = _month - 1; // 0..11 + _t.tm_mday = _day; // 1..31 + _t.tm_hour = _hour; // 0..23 + _t.tm_min = _min; // 0..59 + _t.tm_sec = _sec; // 0..60 + _t.tm_isdst = _isdst; // 0/1/negative - lua_pushnumber(L_, static_cast(std::mktime(&t))); // resolution: 1 second + lua_pushnumber(L_, static_cast(std::mktime(&_t))); // resolution: 1 second return 1; } @@ -1527,7 +1527,7 @@ LUAG_FUNC(wakeup_conv) // ################################################################################################# // same as PUC-Lua l_alloc -extern "C" [[nodiscard]] static void* libc_lua_Alloc([[maybe_unused]] void* ud, [[maybe_unused]] void* ptr_, [[maybe_unused]] size_t osize_, size_t nsize_) +extern "C" [[nodiscard]] static void* libc_lua_Alloc([[maybe_unused]] void* ud_, [[maybe_unused]] void* ptr_, [[maybe_unused]] size_t osize_, size_t nsize_) { if (nsize_ == 0) { free(ptr_); @@ -1541,9 +1541,9 @@ extern "C" [[nodiscard]] static void* libc_lua_Alloc([[maybe_unused]] void* ud, [[nodiscard]] static int luaG_provide_protected_allocator(lua_State* L_) { - Universe* const U{ universe_get(L_) }; + Universe* const _U{ universe_get(L_) }; // push a new full userdata on the stack, giving access to the universe's protected allocator - [[maybe_unused]] AllocatorDefinition* const def{ new (L_) AllocatorDefinition{ U->protectedAllocator.makeDefinition() } }; + [[maybe_unused]] AllocatorDefinition* const def{ new (L_) AllocatorDefinition{ _U->protectedAllocator.makeDefinition() } }; return 1; } @@ -1585,8 +1585,8 @@ static void initialize_allocator_function(Universe* U_, lua_State* L_) lua_getfield(L_, -1, "internal_allocator"); // L_: settings "libc"|"allocator" { - char const* allocator = lua_tostring(L_, -1); - if (strcmp(allocator, "libc") == 0) { + char const* const _allocator{ lua_tostring(L_, -1) }; + if (strcmp(_allocator, "libc") == 0) { U_->internalAllocator = AllocatorDefinition{ libc_lua_Alloc, nullptr }; } else if (U_->provideAllocator == luaG_provide_protected_allocator) { // user wants mutex protection on the state's allocator. Use protection for our own allocations too, just in case. @@ -1639,20 +1639,20 @@ LUAG_FUNC(configure) }); } - Universe* U = universe_get(L_); - bool const from_master_state{ U == nullptr }; - char const* name = luaL_checkstring(L_, lua_upvalueindex(1)); + Universe* _U{ universe_get(L_) }; + bool const _from_master_state{ _U == nullptr }; + char const* const _name{ luaL_checkstring(L_, lua_upvalueindex(1)) }; LUA_ASSERT(L_, lua_type(L_, 1) == LUA_TTABLE); STACK_GROW(L_, 4); STACK_CHECK_START_ABS(L_, 1); // L_: settings - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "%p: lanes.configure() BEGIN\n" INDENT_END(U), L_)); - DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U }); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "%p: lanes.configure() BEGIN\n" INDENT_END(_U), L_)); + DEBUGSPEW_CODE(DebugSpewIndentScope scope{ _U }); - if (U == nullptr) { - U = universe_create(L_); // L_: settings universe - DEBUGSPEW_CODE(DebugSpewIndentScope scope2{ U }); + if (_U == nullptr) { + _U = universe_create(L_); // L_: settings universe + DEBUGSPEW_CODE(DebugSpewIndentScope _scope2{ _U }); lua_createtable(L_, 0, 1); // L_: settings universe {mt} lua_getfield(L_, 1, "shutdown_timeout"); // L_: settings universe {mt} shutdown_timeout lua_getfield(L_, 1, "shutdown_mode"); // L_: settings universe {mt} shutdown_timeout shutdown_mode @@ -1661,21 +1661,21 @@ LUAG_FUNC(configure) lua_setmetatable(L_, -2); // L_: settings universe lua_pop(L_, 1); // L_: settings lua_getfield(L_, 1, "verbose_errors"); // L_: settings verbose_errors - U->verboseErrors = lua_toboolean(L_, -1) ? true : false; + _U->verboseErrors = lua_toboolean(L_, -1) ? true : false; lua_pop(L_, 1); // L_: settings lua_getfield(L_, 1, "demote_full_userdata"); // L_: settings demote_full_userdata - U->demoteFullUserdata = lua_toboolean(L_, -1) ? true : false; + _U->demoteFullUserdata = lua_toboolean(L_, -1) ? true : false; lua_pop(L_, 1); // L_: settings #if HAVE_LANE_TRACKING() lua_getfield(L_, 1, "track_lanes"); // L_: settings track_lanes - U->trackingFirst = lua_toboolean(L_, -1) ? TRACKING_END : nullptr; + _U->trackingFirst = lua_toboolean(L_, -1) ? TRACKING_END : nullptr; lua_pop(L_, 1); // L_: settings #endif // HAVE_LANE_TRACKING() // Linked chains handling - U->selfdestructFirst = SELFDESTRUCT_END; - initialize_allocator_function(U, L_); - initializeOnStateCreate(U, L_); - init_keepers(U, L_); + _U->selfdestructFirst = SELFDESTRUCT_END; + initialize_allocator_function(_U, L_); + initializeOnStateCreate(_U, L_); + init_keepers(_U, L_); STACK_CHECK(L_, 1); // Initialize 'timerLinda'; a common Linda object shared by all states @@ -1685,15 +1685,15 @@ LUAG_FUNC(configure) STACK_CHECK(L_, 2); // Proxy userdata contents is only a 'DeepPrelude*' pointer - U->timerLinda = *lua_tofulluserdata(L_, -1); + _U->timerLinda = *lua_tofulluserdata(L_, -1); // increment refcount so that this linda remains alive as long as the universe exists. - U->timerLinda->refcount.fetch_add(1, std::memory_order_relaxed); + _U->timerLinda->refcount.fetch_add(1, std::memory_order_relaxed); lua_pop(L_, 1); // L_: settings } STACK_CHECK(L_, 1); // Serialize calls to 'require' from now on, also in the primary state - serialize_require(DEBUGSPEW_PARAM_COMMA(U) L_); + serialize_require(DEBUGSPEW_PARAM_COMMA(_U) L_); // Retrieve main module interface table lua_pushvalue(L_, lua_upvalueindex(2)); // L_: settings M @@ -1704,7 +1704,7 @@ LUAG_FUNC(configure) luaG_registerlibfuncs(L_, global::sLanesFunctions); #if HAVE_LANE_TRACKING() // register core.threads() only if settings say it should be available - if (U->trackingFirst != nullptr) { + if (_U->trackingFirst != nullptr) { lua_pushcfunction(L_, LG_threads); // L_: settings M LG_threads() lua_setfield(L_, -2, "threads"); // L_: settings M } @@ -1712,11 +1712,11 @@ LUAG_FUNC(configure) STACK_CHECK(L_, 2); { - char const* errmsg{ - DeepFactory::PushDeepProxy(DestState{ L_ }, U->timerLinda, 0, LookupMode::LaneBody) + char const* _errmsg{ + DeepFactory::PushDeepProxy(DestState{ L_ }, _U->timerLinda, 0, LookupMode::LaneBody) }; // L_: settings M timerLinda - if (errmsg != nullptr) { - raise_luaL_error(L_, errmsg); + if (_errmsg != nullptr) { + raise_luaL_error(L_, _errmsg); } lua_setfield(L_, -2, "timer_gateway"); // L_: settings M } @@ -1780,12 +1780,12 @@ LUAG_FUNC(configure) // register all native functions found in that module in the transferable functions database // we process it before _G because we don't want to find the module when scanning _G (this would generate longer names) // for example in package.loaded["lanes.core"].* - populate_func_lookup_table(L_, -1, name); + populate_func_lookup_table(L_, -1, _name); STACK_CHECK(L_, 2); // record all existing C/JIT-fast functions // Lua 5.2 no longer has LUA_GLOBALSINDEX: we must push globals table on the stack - if (from_master_state) { + if (_from_master_state) { // don't do this when called during the initialization of a new lane, // because we will do it after on_state_create() is called, // and we don't want to skip _G because of caching in case globals are created then @@ -1798,7 +1798,7 @@ LUAG_FUNC(configure) // set _R[kConfigRegKey] = settings kConfigRegKey.setValue(L_, [](lua_State* L_) { lua_pushvalue(L_, -2); }); STACK_CHECK(L_, 1); - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "%p: lanes.configure() END\n" INDENT_END(U), L_)); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "%p: lanes.configure() END\n" INDENT_END(_U), L_)); // Return the settings table return 1; } @@ -1809,9 +1809,9 @@ LUAG_FUNC(configure) #include #include -void signal_handler(int signal) +void signal_handler(int signal_) { - if (signal == SIGABRT) { + if (signal_ == SIGABRT) { _cprintf("caught abnormal termination!"); abort(); } @@ -1830,18 +1830,18 @@ static void EnableCrashingOnCrashes(void) typedef BOOL(WINAPI * tSetPolicy)(DWORD dwFlags); const DWORD EXCEPTION_SWALLOWING = 0x1; - HMODULE kernel32 = LoadLibraryA("kernel32.dll"); - if (kernel32) { - tGetPolicy pGetPolicy = (tGetPolicy) GetProcAddress(kernel32, "GetProcessUserModeExceptionPolicy"); - tSetPolicy pSetPolicy = (tSetPolicy) GetProcAddress(kernel32, "SetProcessUserModeExceptionPolicy"); + HMODULE _kernel32 = LoadLibraryA("kernel32.dll"); + if (_kernel32) { + tGetPolicy pGetPolicy = (tGetPolicy) GetProcAddress(_kernel32, "GetProcessUserModeExceptionPolicy"); + tSetPolicy pSetPolicy = (tSetPolicy) GetProcAddress(_kernel32, "SetProcessUserModeExceptionPolicy"); if (pGetPolicy && pSetPolicy) { - DWORD dwFlags; - if (pGetPolicy(&dwFlags)) { + DWORD _dwFlags; + if (pGetPolicy(&_dwFlags)) { // Turn off the filter - pSetPolicy(dwFlags & ~EXCEPTION_SWALLOWING); + pSetPolicy(_dwFlags & ~EXCEPTION_SWALLOWING); } } - FreeLibrary(kernel32); + FreeLibrary(_kernel32); } // typedef void (* SignalHandlerPointer)( int); /*SignalHandlerPointer previousHandler =*/signal(SIGABRT, signal_handler); @@ -1902,8 +1902,8 @@ LANES_API int luaopen_lanes_core(lua_State* L_) [[nodiscard]] static int default_luaopen_lanes(lua_State* L_) { - int const rc{ luaL_loadfile(L_, "lanes.lua") || lua_pcall(L_, 0, 1, 0) }; - if (rc != LUA_OK) { + int const _rc{ luaL_loadfile(L_, "lanes.lua") || lua_pcall(L_, 0, 1, 0) }; + if (_rc != LUA_OK) { raise_luaL_error(L_, "failed to initialize embedded Lanes"); } return 1; diff --git a/src/lanesconf.h b/src/lanesconf.h index 7b4ff93..aae4f5b 100644 --- a/src/lanesconf.h +++ b/src/lanesconf.h @@ -23,7 +23,7 @@ // regular class member/method: no prefix, start with a lowercase letter // function argument: suffix _ // static function variable: prefix s, followed by an uppercase letter -// function local variable: prefix l, followed by an uppercase letter +// function local variable: prefix _, followed by an uppercase letter // named lambda capture: no prefix, start with a lowercase letter #if (defined PLATFORM_WIN32) || (defined PLATFORM_POCKETPC) diff --git a/src/linda.cpp b/src/linda.cpp index 07911b3..fedcd01 100644 --- a/src/linda.cpp +++ b/src/linda.cpp @@ -59,8 +59,8 @@ Linda::Linda(Universe* U_, LindaGroup group_, char const* name_, size_t len_) Linda::~Linda() { if (std::holds_alternative(nameVariant)) { - AllocatedName& name = std::get(nameVariant); - U->internalAllocator.free(name.name, name.len); + AllocatedName& _name = std::get(nameVariant); + U->internalAllocator.free(_name.name, _name.len); } } @@ -75,13 +75,13 @@ void Linda::setName(char const* name_, size_t len_) ++len_; // don't forget terminating 0 if (len_ < kEmbeddedNameLength) { nameVariant.emplace(); - char* const name{ std::get(nameVariant).data() }; - memcpy(name, name_, len_); + char* const _name{ std::get(nameVariant).data() }; + memcpy(_name, name_, len_); } else { - AllocatedName& name = std::get(nameVariant); - name.name = static_cast(U->internalAllocator.alloc(len_)); - name.len = len_; - memcpy(name.name, name_, len_); + AllocatedName& _name = std::get(nameVariant); + _name.name = static_cast(U->internalAllocator.alloc(len_)); + _name.len = len_; + memcpy(_name.name, name_, len_); } } @@ -90,12 +90,12 @@ void Linda::setName(char const* name_, size_t len_) char const* Linda::getName() const { if (std::holds_alternative(nameVariant)) { - AllocatedName const& name = std::get(nameVariant); - return name.name; + AllocatedName const& _name = std::get(nameVariant); + return _name.name; } if (std::holds_alternative(nameVariant)) { - char const* const name{ std::get(nameVariant).data() }; - return name; + char const* const _name{ std::get(nameVariant).data() }; + return _name; } return nullptr; } @@ -105,20 +105,20 @@ char const* Linda::getName() const template [[nodiscard]] static inline Linda* ToLinda(lua_State* L_, int idx_) { - Linda* const linda{ static_cast(LindaFactory::Instance.toDeep(L_, idx_)) }; + Linda* const _linda{ static_cast(LindaFactory::Instance.toDeep(L_, idx_)) }; if constexpr (!OPT) { - luaL_argcheck(L_, linda != nullptr, idx_, "expecting a linda object"); // doesn't return if linda is nullptr - LUA_ASSERT(L_, linda->U == universe_get(L_)); + luaL_argcheck(L_, _linda != nullptr, idx_, "expecting a linda object"); // doesn't return if linda is nullptr + LUA_ASSERT(L_, _linda->U == universe_get(L_)); } - return linda; + return _linda; } // ################################################################################################# static void check_key_types(lua_State* L_, int start_, int end_) { - for (int i{ start_ }; i <= end_; ++i) { - LuaType const t{ lua_type_as_enum(L_, i) }; + for (int _i{ start_ }; _i <= end_; ++_i) { + LuaType const t{ lua_type_as_enum(L_, _i) }; switch (t) { case LuaType::BOOLEAN: case LuaType::NUMBER: @@ -128,14 +128,14 @@ static void check_key_types(lua_State* L_, int start_, int end_) case LuaType::LIGHTUSERDATA: static constexpr std::array, 3> kKeysToCheck{ kLindaBatched, kCancelError, kNilSentinel }; for (UniqueKey const& key : kKeysToCheck) { - if (key.equals(L_, i)) { - raise_luaL_error(L_, "argument #%d: can't use %s as a key", i, key.debugName); + if (key.equals(L_, _i)) { + raise_luaL_error(L_, "argument #%d: can't use %s as a key", _i, key.debugName); break; } } break; } - raise_luaL_error(L_, "argument #%d: invalid key type (not a boolean, string, number or light userdata)", i); + raise_luaL_error(L_, "argument #%d: invalid key type (not a boolean, string, number or light userdata)", _i); } } @@ -144,29 +144,29 @@ static void check_key_types(lua_State* L_, int start_, int end_) // used to perform all linda operations that access keepers int Linda::ProtectedCall(lua_State* L_, lua_CFunction f_) { - Linda* const linda{ ToLinda(L_, 1) }; + Linda* const _linda{ ToLinda(L_, 1) }; // acquire the keeper - Keeper* const K{ linda->acquireKeeper() }; - lua_State* const KL{ K ? K->L : nullptr }; - if (KL == nullptr) + Keeper* const _K{ _linda->acquireKeeper() }; + lua_State* const _KL{ _K ? _K->L : nullptr }; + if (_KL == nullptr) return 0; // if we didn't do anything wrong, the keeper stack should be clean - LUA_ASSERT(L_, lua_gettop(KL) == 0); + LUA_ASSERT(L_, lua_gettop(_KL) == 0); // push the function to be called and move it before the arguments lua_pushcfunction(L_, f_); lua_insert(L_, 1); // do a protected call - int const rc{ lua_pcall(L_, lua_gettop(L_) - 1, LUA_MULTRET, 0) }; + int const _rc{ lua_pcall(L_, lua_gettop(L_) - 1, LUA_MULTRET, 0) }; // whatever happens, the keeper state stack must be empty when we are done - lua_settop(KL, 0); + lua_settop(_KL, 0); // release the keeper - linda->releaseKeeper(K); + _linda->releaseKeeper(_K); // if there was an error, forward it - if (rc != LUA_OK) { + if (_rc != LUA_OK) { raise_lua_error(L_); } // return whatever the actual operation provided @@ -186,108 +186,108 @@ int Linda::ProtectedCall(lua_State* L_, lua_CFunction f_) */ LUAG_FUNC(linda_send) { - auto send = [](lua_State* L_) { - Linda* const linda{ ToLinda(L_, 1) }; - int key_i{ 2 }; // index of first key, if timeout not there + auto _send = [](lua_State* L_) { + Linda* const _linda{ ToLinda(L_, 1) }; + int _key_i{ 2 }; // index of first key, if timeout not there - std::chrono::time_point until{ std::chrono::time_point::max() }; + std::chrono::time_point _until{ std::chrono::time_point::max() }; if (lua_type(L_, 2) == LUA_TNUMBER) { // we don't want to use lua_isnumber() because of autocoercion - lua_Duration const duration{ lua_tonumber(L_, 2) }; - if (duration.count() >= 0.0) { - until = std::chrono::steady_clock::now() + std::chrono::duration_cast(duration); + lua_Duration const _duration{ lua_tonumber(L_, 2) }; + if (_duration.count() >= 0.0) { + _until = std::chrono::steady_clock::now() + std::chrono::duration_cast(_duration); } else { raise_luaL_argerror(L_, 2, "duration cannot be < 0"); } - ++key_i; + ++_key_i; } else if (lua_isnil(L_, 2)) { // alternate explicit "infinite timeout" by passing nil before the key - ++key_i; + ++_key_i; } // make sure the key is of a valid type - check_key_types(L_, key_i, key_i); + check_key_types(L_, _key_i, _key_i); STACK_GROW(L_, 1); // make sure there is something to send - if (lua_gettop(L_) == key_i) { + if (lua_gettop(L_) == _key_i) { raise_luaL_error(L_, "no data to send"); } // convert nils to some special non-nil sentinel in sent values - keeper_toggle_nil_sentinels(L_, key_i + 1, LookupMode::ToKeeper); - bool ret{ false }; - CancelRequest cancel{ CancelRequest::None }; - KeeperCallResult pushed; + keeper_toggle_nil_sentinels(L_, _key_i + 1, LookupMode::ToKeeper); + bool _ret{ false }; + CancelRequest _cancel{ CancelRequest::None }; + KeeperCallResult _pushed; { - Lane* const lane{ kLanePointerRegKey.readLightUserDataValue(L_) }; - Keeper* const K{ linda->whichKeeper() }; - KeeperState const KL{ K ? K->L : nullptr }; - if (KL == nullptr) + Lane* const _lane{ kLanePointerRegKey.readLightUserDataValue(L_) }; + Keeper* const _K{ _linda->whichKeeper() }; + KeeperState const _KL{ _K ? _K->L : nullptr }; + if (_KL == nullptr) return 0; - STACK_CHECK_START_REL(KL, 0); - for (bool try_again{ true };;) { - if (lane != nullptr) { - cancel = lane->cancelRequest; + STACK_CHECK_START_REL(_KL, 0); + for (bool _try_again{ true };;) { + if (_lane != nullptr) { + _cancel = _lane->cancelRequest; } - cancel = (cancel != CancelRequest::None) ? cancel : linda->cancelRequest; + _cancel = (_cancel != CancelRequest::None) ? _cancel : _linda->cancelRequest; // if user wants to cancel, or looped because of a timeout, the call returns without sending anything - if (!try_again || cancel != CancelRequest::None) { - pushed.emplace(0); + if (!_try_again || _cancel != CancelRequest::None) { + _pushed.emplace(0); break; } - STACK_CHECK(KL, 0); - pushed = keeper_call(linda->U, KL, KEEPER_API(send), L_, linda, key_i); - if (!pushed.has_value()) { + STACK_CHECK(_KL, 0); + _pushed = keeper_call(_KL, KEEPER_API(send), L_, _linda, _key_i); + if (!_pushed.has_value()) { break; } - LUA_ASSERT(L_, pushed.value() == 1); + LUA_ASSERT(L_, _pushed.value() == 1); - ret = lua_toboolean(L_, -1) ? true : false; + _ret = lua_toboolean(L_, -1) ? true : false; lua_pop(L_, 1); - if (ret) { + if (_ret) { // Wake up ALL waiting threads - linda->writeHappened.notify_all(); + _linda->writeHappened.notify_all(); break; } // instant timout to bypass the wait syscall - if (std::chrono::steady_clock::now() >= until) { + if (std::chrono::steady_clock::now() >= _until) { break; /* no wait; instant timeout */ } // storage limit hit, wait until timeout or signalled that we should try again { - Lane::Status prev_status{ Lane::Error }; // prevent 'might be used uninitialized' warnings - if (lane != nullptr) { + Lane::Status _prev_status{ Lane::Error }; // prevent 'might be used uninitialized' warnings + if (_lane != nullptr) { // change status of lane to "waiting" - prev_status = lane->status; // Running, most likely - LUA_ASSERT(L_, prev_status == Lane::Running); // but check, just in case - lane->status = Lane::Waiting; - LUA_ASSERT(L_, lane->waiting_on == nullptr); - lane->waiting_on = &linda->readHappened; + _prev_status = _lane->status; // Running, most likely + LUA_ASSERT(L_, _prev_status == Lane::Running); // but check, just in case + _lane->status = Lane::Waiting; + LUA_ASSERT(L_, _lane->waiting_on == nullptr); + _lane->waiting_on = &_linda->readHappened; } // could not send because no room: wait until some data was read before trying again, or until timeout is reached - std::unique_lock keeper_lock{ K->mutex, std::adopt_lock }; - std::cv_status const status{ linda->readHappened.wait_until(keeper_lock, until) }; - keeper_lock.release(); // we don't want to release the lock! - try_again = (status == std::cv_status::no_timeout); // detect spurious wakeups - if (lane != nullptr) { - lane->waiting_on = nullptr; - lane->status = prev_status; + std::unique_lock _keeper_lock{ _K->mutex, std::adopt_lock }; + std::cv_status const status{ _linda->readHappened.wait_until(_keeper_lock, _until) }; + _keeper_lock.release(); // we don't want to release the lock! + _try_again = (status == std::cv_status::no_timeout); // detect spurious wakeups + if (_lane != nullptr) { + _lane->waiting_on = nullptr; + _lane->status = _prev_status; } } } - STACK_CHECK(KL, 0); + STACK_CHECK(_KL, 0); } - if (!pushed.has_value()) { + if (!_pushed.has_value()) { raise_luaL_error(L_, "tried to copy unsupported types"); } - switch (cancel) { + switch (_cancel) { case CancelRequest::Soft: // if user wants to soft-cancel, the call returns lanes.cancel_error kCancelError.pushKey(L_); @@ -298,11 +298,11 @@ LUAG_FUNC(linda_send) raise_cancel_error(L_); // raises an error and doesn't return default: - lua_pushboolean(L_, ret); // true (success) or false (timeout) + lua_pushboolean(L_, _ret); // true (success) or false (timeout) return 1; } }; - return Linda::ProtectedCall(L_, send); + return Linda::ProtectedCall(L_, _send); } // ################################################################################################# @@ -320,122 +320,122 @@ LUAG_FUNC(linda_send) */ LUAG_FUNC(linda_receive) { - auto receive = [](lua_State* L_) { - Linda* const linda{ ToLinda(L_, 1) }; - int key_i{ 2 }; // index of first key, if timeout not there + auto _receive = [](lua_State* L_) { + Linda* const _linda{ ToLinda(L_, 1) }; + int _key_i{ 2 }; // index of first key, if timeout not there - std::chrono::time_point until{ std::chrono::time_point::max() }; + std::chrono::time_point _until{ std::chrono::time_point::max() }; if (lua_type(L_, 2) == LUA_TNUMBER) { // we don't want to use lua_isnumber() because of autocoercion - lua_Duration const duration{ lua_tonumber(L_, 2) }; - if (duration.count() >= 0.0) { - until = std::chrono::steady_clock::now() + std::chrono::duration_cast(duration); + lua_Duration const _duration{ lua_tonumber(L_, 2) }; + if (_duration.count() >= 0.0) { + _until = std::chrono::steady_clock::now() + std::chrono::duration_cast(_duration); } else { raise_luaL_argerror(L_, 2, "duration cannot be < 0"); } - ++key_i; + ++_key_i; } else if (lua_isnil(L_, 2)) { // alternate explicit "infinite timeout" by passing nil before the key - ++key_i; + ++_key_i; } - keeper_api_t selected_keeper_receive{ nullptr }; - int expected_pushed_min{ 0 }, expected_pushed_max{ 0 }; + keeper_api_t _selected_keeper_receive{ nullptr }; + int _expected_pushed_min{ 0 }, _expected_pushed_max{ 0 }; // are we in batched mode? kLindaBatched.pushKey(L_); - int const is_batched{ lua501_equal(L_, key_i, -1) }; + int const _is_batched{ lua501_equal(L_, _key_i, -1) }; lua_pop(L_, 1); - if (is_batched) { + if (_is_batched) { // no need to pass linda.batched in the keeper state - ++key_i; + ++_key_i; // make sure the keys are of a valid type - check_key_types(L_, key_i, key_i); + check_key_types(L_, _key_i, _key_i); // receive multiple values from a single slot - selected_keeper_receive = KEEPER_API(receive_batched); + _selected_keeper_receive = KEEPER_API(receive_batched); // we expect a user-defined amount of return value - expected_pushed_min = (int) luaL_checkinteger(L_, key_i + 1); - expected_pushed_max = (int) luaL_optinteger(L_, key_i + 2, expected_pushed_min); + _expected_pushed_min = (int) luaL_checkinteger(L_, _key_i + 1); + _expected_pushed_max = (int) luaL_optinteger(L_, _key_i + 2, _expected_pushed_min); // don't forget to count the key in addition to the values - ++expected_pushed_min; - ++expected_pushed_max; - if (expected_pushed_min > expected_pushed_max) { + ++_expected_pushed_min; + ++_expected_pushed_max; + if (_expected_pushed_min > _expected_pushed_max) { raise_luaL_error(L_, "batched min/max error"); } } else { // make sure the keys are of a valid type - check_key_types(L_, key_i, lua_gettop(L_)); + check_key_types(L_, _key_i, lua_gettop(L_)); // receive a single value, checking multiple slots - selected_keeper_receive = KEEPER_API(receive); + _selected_keeper_receive = KEEPER_API(receive); // we expect a single (value, key) pair of returned values - expected_pushed_min = expected_pushed_max = 2; + _expected_pushed_min = _expected_pushed_max = 2; } - Lane* const lane{ kLanePointerRegKey.readLightUserDataValue(L_) }; - Keeper* const K{ linda->whichKeeper() }; - KeeperState const KL{ K ? K->L : nullptr }; - if (KL == nullptr) + Lane* const _lane{ kLanePointerRegKey.readLightUserDataValue(L_) }; + Keeper* const _K{ _linda->whichKeeper() }; + KeeperState const _KL{ _K ? _K->L : nullptr }; + if (_KL == nullptr) return 0; - CancelRequest cancel{ CancelRequest::None }; - KeeperCallResult pushed; - STACK_CHECK_START_REL(KL, 0); - for (bool try_again{ true };;) { - if (lane != nullptr) { - cancel = lane->cancelRequest; + CancelRequest _cancel{ CancelRequest::None }; + KeeperCallResult _pushed; + STACK_CHECK_START_REL(_KL, 0); + for (bool _try_again{ true };;) { + if (_lane != nullptr) { + _cancel = _lane->cancelRequest; } - cancel = (cancel != CancelRequest::None) ? cancel : linda->cancelRequest; + _cancel = (_cancel != CancelRequest::None) ? _cancel : _linda->cancelRequest; // if user wants to cancel, or looped because of a timeout, the call returns without sending anything - if (!try_again || cancel != CancelRequest::None) { - pushed.emplace(0); + if (!_try_again || _cancel != CancelRequest::None) { + _pushed.emplace(0); break; } // all arguments of receive() but the first are passed to the keeper's receive function - pushed = keeper_call(linda->U, KL, selected_keeper_receive, L_, linda, key_i); - if (!pushed.has_value()) { + _pushed = keeper_call(_KL, _selected_keeper_receive, L_, _linda, _key_i); + if (!_pushed.has_value()) { break; } - if (pushed.value() > 0) { - LUA_ASSERT(L_, pushed.value() >= expected_pushed_min && pushed.value() <= expected_pushed_max); + if (_pushed.value() > 0) { + LUA_ASSERT(L_, _pushed.value() >= _expected_pushed_min && _pushed.value() <= _expected_pushed_max); // replace sentinels with real nils - keeper_toggle_nil_sentinels(L_, lua_gettop(L_) - pushed.value(), LookupMode::FromKeeper); + keeper_toggle_nil_sentinels(L_, lua_gettop(L_) - _pushed.value(), LookupMode::FromKeeper); // To be done from within the 'K' locking area // - linda->readHappened.notify_all(); + _linda->readHappened.notify_all(); break; } - if (std::chrono::steady_clock::now() >= until) { + if (std::chrono::steady_clock::now() >= _until) { break; /* instant timeout */ } // nothing received, wait until timeout or signalled that we should try again { - Lane::Status prev_status{ Lane::Error }; // prevent 'might be used uninitialized' warnings - if (lane != nullptr) { + Lane::Status _prev_status{ Lane::Error }; // prevent 'might be used uninitialized' warnings + if (_lane != nullptr) { // change status of lane to "waiting" - prev_status = lane->status; // Running, most likely - LUA_ASSERT(L_, prev_status == Lane::Running); // but check, just in case - lane->status = Lane::Waiting; - LUA_ASSERT(L_, lane->waiting_on == nullptr); - lane->waiting_on = &linda->writeHappened; + _prev_status = _lane->status; // Running, most likely + LUA_ASSERT(L_, _prev_status == Lane::Running); // but check, just in case + _lane->status = Lane::Waiting; + LUA_ASSERT(L_, _lane->waiting_on == nullptr); + _lane->waiting_on = &_linda->writeHappened; } // not enough data to read: wakeup when data was sent, or when timeout is reached - std::unique_lock keeper_lock{ K->mutex, std::adopt_lock }; - std::cv_status const status{ linda->writeHappened.wait_until(keeper_lock, until) }; - keeper_lock.release(); // we don't want to release the lock! - try_again = (status == std::cv_status::no_timeout); // detect spurious wakeups - if (lane != nullptr) { - lane->waiting_on = nullptr; - lane->status = prev_status; + std::unique_lock _keeper_lock{ _K->mutex, std::adopt_lock }; + std::cv_status const _status{ _linda->writeHappened.wait_until(_keeper_lock, _until) }; + _keeper_lock.release(); // we don't want to release the lock! + _try_again = (_status == std::cv_status::no_timeout); // detect spurious wakeups + if (_lane != nullptr) { + _lane->waiting_on = nullptr; + _lane->status = _prev_status; } } } - STACK_CHECK(KL, 0); + STACK_CHECK(_KL, 0); - if (!pushed.has_value()) { + if (!_pushed.has_value()) { raise_luaL_error(L_, "tried to copy unsupported types"); } - switch (cancel) { + switch (_cancel) { case CancelRequest::Soft: // if user wants to soft-cancel, the call returns kCancelError kCancelError.pushKey(L_); @@ -446,10 +446,10 @@ LUAG_FUNC(linda_receive) raise_cancel_error(L_); // raises an error and doesn't return default: - return pushed.value(); + return _pushed.value(); } }; - return Linda::ProtectedCall(L_, receive); + return Linda::ProtectedCall(L_, _receive); } // ################################################################################################# @@ -465,40 +465,40 @@ LUAG_FUNC(linda_receive) LUAG_FUNC(linda_set) { auto set = [](lua_State* L_) { - Linda* const linda{ ToLinda(L_, 1) }; - bool const has_value{ lua_gettop(L_) > 2 }; + Linda* const _linda{ ToLinda(L_, 1) }; + bool const _has_value{ lua_gettop(L_) > 2 }; // make sure the key is of a valid type (throws an error if not the case) check_key_types(L_, 2, 2); - Keeper* const K{ linda->whichKeeper() }; - KeeperCallResult pushed; - if (linda->cancelRequest == CancelRequest::None) { - if (has_value) { + Keeper* const _K{ _linda->whichKeeper() }; + KeeperCallResult _pushed; + if (_linda->cancelRequest == CancelRequest::None) { + if (_has_value) { // convert nils to some special non-nil sentinel in sent values keeper_toggle_nil_sentinels(L_, 3, LookupMode::ToKeeper); } - pushed = keeper_call(linda->U, K->L, KEEPER_API(set), L_, linda, 2); - if (pushed.has_value()) { // no error? - LUA_ASSERT(L_, pushed.value() == 0 || pushed.value() == 1); + _pushed = keeper_call(_K->L, KEEPER_API(set), L_, _linda, 2); + if (_pushed.has_value()) { // no error? + LUA_ASSERT(L_, _pushed.value() == 0 || _pushed.value() == 1); - if (has_value) { + if (_has_value) { // we put some data in the slot, tell readers that they should wake - linda->writeHappened.notify_all(); // To be done from within the 'K' locking area + _linda->writeHappened.notify_all(); // To be done from within the 'K' locking area } - if (pushed.value() == 1) { + if (_pushed.value() == 1) { // the key was full, but it is no longer the case, tell writers they should wake LUA_ASSERT(L_, lua_type(L_, -1) == LUA_TBOOLEAN && lua_toboolean(L_, -1) == 1); - linda->readHappened.notify_all(); // To be done from within the 'K' locking area + _linda->readHappened.notify_all(); // To be done from within the 'K' locking area } } } else { // linda is cancelled // do nothing and return lanes.cancel_error kCancelError.pushKey(L_); - pushed.emplace(1); + _pushed.emplace(1); } // must trigger any error after keeper state has been released - return OptionalValue(pushed, L_, "tried to copy unsupported types"); + return OptionalValue(_pushed, L_, "tried to copy unsupported types"); }; return Linda::ProtectedCall(L_, set); } @@ -512,16 +512,16 @@ LUAG_FUNC(linda_set) */ LUAG_FUNC(linda_count) { - auto count = [](lua_State* L_) { - Linda* const linda{ ToLinda(L_, 1) }; + auto _count = [](lua_State* L_) { + Linda* const _linda{ ToLinda(L_, 1) }; // make sure the keys are of a valid type check_key_types(L_, 2, lua_gettop(L_)); - Keeper* const K{ linda->whichKeeper() }; - KeeperCallResult const pushed{ keeper_call(linda->U, K->L, KEEPER_API(count), L_, linda, 2) }; - return OptionalValue(pushed, L_, "tried to count an invalid key"); + Keeper* const _K{ _linda->whichKeeper() }; + KeeperCallResult const _pushed{ keeper_call(_K->L, KEEPER_API(count), L_, _linda, 2) }; + return OptionalValue(_pushed, L_, "tried to count an invalid key"); }; - return Linda::ProtectedCall(L_, count); + return Linda::ProtectedCall(L_, _count); } // ################################################################################################# @@ -534,27 +534,27 @@ LUAG_FUNC(linda_count) LUAG_FUNC(linda_get) { auto get = [](lua_State* L_) { - Linda* const linda{ ToLinda(L_, 1) }; - lua_Integer const count{ luaL_optinteger(L_, 3, 1) }; - luaL_argcheck(L_, count >= 1, 3, "count should be >= 1"); + Linda* const _linda{ ToLinda(L_, 1) }; + lua_Integer const _count{ luaL_optinteger(L_, 3, 1) }; + luaL_argcheck(L_, _count >= 1, 3, "count should be >= 1"); luaL_argcheck(L_, lua_gettop(L_) <= 3, 4, "too many arguments"); // make sure the key is of a valid type (throws an error if not the case) check_key_types(L_, 2, 2); - KeeperCallResult pushed; - if (linda->cancelRequest == CancelRequest::None) { - Keeper* const K{ linda->whichKeeper() }; - pushed = keeper_call(linda->U, K->L, KEEPER_API(get), L_, linda, 2); - if (pushed.value_or(0) > 0) { - keeper_toggle_nil_sentinels(L_, lua_gettop(L_) - pushed.value(), LookupMode::FromKeeper); + KeeperCallResult _pushed; + if (_linda->cancelRequest == CancelRequest::None) { + Keeper* const _K{ _linda->whichKeeper() }; + _pushed = keeper_call(_K->L, KEEPER_API(get), L_, _linda, 2); + if (_pushed.value_or(0) > 0) { + keeper_toggle_nil_sentinels(L_, lua_gettop(L_) - _pushed.value(), LookupMode::FromKeeper); } } else { // linda is cancelled // do nothing and return lanes.cancel_error kCancelError.pushKey(L_); - pushed.emplace(1); + _pushed.emplace(1); } // an error can be raised if we attempt to read an unregistered function - return OptionalValue(pushed, L_, "tried to copy unsupported types"); + return OptionalValue(_pushed, L_, "tried to copy unsupported types"); }; return Linda::ProtectedCall(L_, get); } @@ -569,8 +569,8 @@ LUAG_FUNC(linda_get) */ LUAG_FUNC(linda_limit) { - auto limit = [](lua_State* L_) { - Linda* const linda{ ToLinda(L_, 1) }; + auto _limit = [](lua_State* L_) { + Linda* const _linda{ ToLinda(L_, 1) }; // make sure we got 3 arguments: the linda, a key and a limit luaL_argcheck(L_, lua_gettop(L_) == 3, 2, "wrong number of arguments"); // make sure we got a numeric limit @@ -578,24 +578,24 @@ LUAG_FUNC(linda_limit) // make sure the key is of a valid type check_key_types(L_, 2, 2); - KeeperCallResult pushed; - if (linda->cancelRequest == CancelRequest::None) { - Keeper* const K{ linda->whichKeeper() }; - pushed = keeper_call(linda->U, K->L, KEEPER_API(limit), L_, linda, 2); - LUA_ASSERT(L_, pushed.has_value() && (pushed.value() == 0 || pushed.value() == 1)); // no error, optional boolean value saying if we should wake blocked writer threads - if (pushed.value() == 1) { + KeeperCallResult _pushed; + if (_linda->cancelRequest == CancelRequest::None) { + Keeper* const _K{ _linda->whichKeeper() }; + _pushed = keeper_call(_K->L, KEEPER_API(limit), L_, _linda, 2); + LUA_ASSERT(L_, _pushed.has_value() && (_pushed.value() == 0 || _pushed.value() == 1)); // no error, optional boolean value saying if we should wake blocked writer threads + if (_pushed.value() == 1) { LUA_ASSERT(L_, lua_type(L_, -1) == LUA_TBOOLEAN && lua_toboolean(L_, -1) == 1); - linda->readHappened.notify_all(); // To be done from within the 'K' locking area + _linda->readHappened.notify_all(); // To be done from within the 'K' locking area } } else { // linda is cancelled // do nothing and return lanes.cancel_error kCancelError.pushKey(L_); - pushed.emplace(1); + _pushed.emplace(1); } // propagate pushed boolean if any - return pushed.value(); + return _pushed.value(); }; - return Linda::ProtectedCall(L_, limit); + return Linda::ProtectedCall(L_, _limit); } // ################################################################################################# @@ -607,23 +607,23 @@ LUAG_FUNC(linda_limit) */ LUAG_FUNC(linda_cancel) { - Linda* const linda{ ToLinda(L_, 1) }; - char const* who = luaL_optstring(L_, 2, "both"); + Linda* const _linda{ ToLinda(L_, 1) }; + char const* _who{ luaL_optstring(L_, 2, "both") }; // make sure we got 3 arguments: the linda, a key and a limit luaL_argcheck(L_, lua_gettop(L_) <= 2, 2, "wrong number of arguments"); - linda->cancelRequest = CancelRequest::Soft; - if (strcmp(who, "both") == 0) { // tell everyone writers to wake up - linda->writeHappened.notify_all(); - linda->readHappened.notify_all(); - } else if (strcmp(who, "none") == 0) { // reset flag - linda->cancelRequest = CancelRequest::None; - } else if (strcmp(who, "read") == 0) { // tell blocked readers to wake up - linda->writeHappened.notify_all(); - } else if (strcmp(who, "write") == 0) { // tell blocked writers to wake up - linda->readHappened.notify_all(); + _linda->cancelRequest = CancelRequest::Soft; + if (strcmp(_who, "both") == 0) { // tell everyone writers to wake up + _linda->writeHappened.notify_all(); + _linda->readHappened.notify_all(); + } else if (strcmp(_who, "none") == 0) { // reset flag + _linda->cancelRequest = CancelRequest::None; + } else if (strcmp(_who, "read") == 0) { // tell blocked readers to wake up + _linda->writeHappened.notify_all(); + } else if (strcmp(_who, "write") == 0) { // tell blocked writers to wake up + _linda->readHappened.notify_all(); } else { - raise_luaL_error(L_, "unknown wake hint '%s'", who); + raise_luaL_error(L_, "unknown wake hint '%s'", _who); } return 0; } @@ -642,8 +642,8 @@ LUAG_FUNC(linda_cancel) */ LUAG_FUNC(linda_deep) { - Linda* const linda{ ToLinda(L_, 1) }; - lua_pushlightuserdata(L_, linda); // just the address + Linda* const _linda{ ToLinda(L_, 1) }; + lua_pushlightuserdata(L_, _linda); // just the address return 1; } @@ -660,15 +660,15 @@ LUAG_FUNC(linda_deep) template [[nodiscard]] static int LindaToString(lua_State* L_, int idx_) { - Linda* const linda{ ToLinda(L_, idx_) }; - if (linda != nullptr) { - char text[128]; - int len; - if (linda->getName()) - len = sprintf(text, "Linda: %.*s", (int) sizeof(text) - 8, linda->getName()); + Linda* const _linda{ ToLinda(L_, idx_) }; + if (_linda != nullptr) { + char _text[128]; + int _len; + if (_linda->getName()) + _len = sprintf(_text, "Linda: %.*s", (int) sizeof(_text) - 8, _linda->getName()); else - len = sprintf(text, "Linda: %p", linda); - lua_pushlstring(L_, text, len); + _len = sprintf(_text, "Linda: %p", _linda); + lua_pushlstring(L_, _text, _len); return 1; } return 0; @@ -692,17 +692,17 @@ LUAG_FUNC(linda_tostring) */ LUAG_FUNC(linda_concat) { // L_: linda1? linda2? - bool atLeastOneLinda{ false }; + bool _atLeastOneLinda{ false }; // Lua semantics enforce that one of the 2 arguments is a Linda, but not necessarily both. if (LindaToString(L_, 1)) { - atLeastOneLinda = true; + _atLeastOneLinda = true; lua_replace(L_, 1); } if (LindaToString(L_, 2)) { - atLeastOneLinda = true; + _atLeastOneLinda = true; lua_replace(L_, 2); } - if (!atLeastOneLinda) { // should not be possible + if (!_atLeastOneLinda) { // should not be possible raise_luaL_error(L_, "internal error: linda_concat called on non-Linda"); } lua_concat(L_, 2); @@ -717,11 +717,11 @@ LUAG_FUNC(linda_concat) */ LUAG_FUNC(linda_dump) { - auto dump = [](lua_State* L_) { - Linda* const linda{ ToLinda(L_, 1) }; - return keeper_push_linda_storage(*linda, DestState{ L_ }); + auto _dump = [](lua_State* L_) { + Linda* const _linda{ ToLinda(L_, 1) }; + return keeper_push_linda_storage(*_linda, DestState{ L_ }); }; - return Linda::ProtectedCall(L_, dump); + return Linda::ProtectedCall(L_, _dump); } // ################################################################################################# @@ -732,13 +732,13 @@ LUAG_FUNC(linda_dump) */ LUAG_FUNC(linda_towatch) { - Linda* const linda{ ToLinda(L_, 1) }; - int pushed{ keeper_push_linda_storage(*linda, DestState{ L_ }) }; - if (pushed == 0) { + Linda* const _linda{ ToLinda(L_, 1) }; + int _pushed{ keeper_push_linda_storage(*_linda, DestState{ L_ }) }; + if (_pushed == 0) { // if the linda is empty, don't return nil - pushed = LindaToString(L_, 1); + _pushed = LindaToString(L_, 1); } - return pushed; + return _pushed; } // ################################################################################################# @@ -773,12 +773,12 @@ namespace global { */ LUAG_FUNC(linda) { - int const top{ lua_gettop(L_) }; - luaL_argcheck(L_, top <= 2, top, "too many arguments"); - if (top == 1) { - LuaType const t{ lua_type_as_enum(L_, 1) }; - luaL_argcheck(L_, t == LuaType::STRING || t == LuaType::NUMBER, 1, "wrong parameter (should be a string or a number)"); - } else if (top == 2) { + int const _top{ lua_gettop(L_) }; + luaL_argcheck(L_, _top <= 2, _top, "too many arguments"); + if (_top == 1) { + LuaType const _t{ lua_type_as_enum(L_, 1) }; + luaL_argcheck(L_, _t == LuaType::STRING || _t == LuaType::NUMBER, 1, "wrong parameter (should be a string or a number)"); + } else if (_top == 2) { luaL_checktype(L_, 1, LUA_TSTRING); luaL_checktype(L_, 2, LUA_TNUMBER); } diff --git a/src/lindafactory.cpp b/src/lindafactory.cpp index 0ec5a0a..16c653f 100644 --- a/src/lindafactory.cpp +++ b/src/lindafactory.cpp @@ -68,25 +68,25 @@ void LindaFactory::createMetatable(lua_State* L_) const void LindaFactory::deleteDeepObjectInternal(lua_State* L_, DeepPrelude* o_) const { - Linda* const linda{ static_cast(o_) }; - LUA_ASSERT(L_, linda); - Keeper* const myK{ linda->whichKeeper() }; + Linda* const _linda{ static_cast(o_) }; + LUA_ASSERT(L_, _linda); + Keeper* const _myK{ _linda->whichKeeper() }; // if collected after the universe, keepers are already destroyed, and there is nothing to clear - if (myK) { + if (_myK) { // if collected from my own keeper, we can't acquire/release it // because we are already inside a protected area, and trying to do so would deadlock! - bool const need_acquire_release{ myK->L != L_ }; + bool const _need_acquire_release{ _myK->L != L_ }; // Clean associated structures in the keeper state. - Keeper* const K{ need_acquire_release ? linda->acquireKeeper() : myK }; + Keeper* const _K{ _need_acquire_release ? _linda->acquireKeeper() : _myK }; // hopefully this won't ever raise an error as we would jump to the closest pcall site while forgetting to release the keeper mutex... - [[maybe_unused]] KeeperCallResult const result{ keeper_call(linda->U, K->L, KEEPER_API(clear), L_, linda, 0) }; + [[maybe_unused]] KeeperCallResult const result{ keeper_call(_K->L, KEEPER_API(clear), L_, _linda, 0) }; LUA_ASSERT(L_, result.has_value() && result.value() == 0); - if (need_acquire_release) { - linda->releaseKeeper(K); + if (_need_acquire_release) { + _linda->releaseKeeper(_K); } } - delete linda; // operator delete overload ensures things go as expected + delete _linda; // operator delete overload ensures things go as expected } // ################################################################################################# @@ -103,9 +103,9 @@ char const* LindaFactory::moduleName() const DeepPrelude* LindaFactory::newDeepObjectInternal(lua_State* L_) const { - size_t name_len{ 0 }; - char const* linda_name{ nullptr }; - LindaGroup linda_group{ 0 }; + size_t _name_len{ 0 }; + char const* _linda_name{ nullptr }; + LindaGroup _linda_group{ 0 }; // should have a string and/or a number of the stack as parameters (name and group) switch (lua_gettop(L_)) { default: // 0 @@ -113,21 +113,21 @@ DeepPrelude* LindaFactory::newDeepObjectInternal(lua_State* L_) const case 1: // 1 parameter, either a name or a group if (lua_type(L_, -1) == LUA_TSTRING) { - linda_name = lua_tolstring(L_, -1, &name_len); + _linda_name = lua_tolstring(L_, -1, &_name_len); } else { - linda_group = LindaGroup{ static_cast(lua_tointeger(L_, -1)) }; + _linda_group = LindaGroup{ static_cast(lua_tointeger(L_, -1)) }; } break; case 2: // 2 parameters, a name and group, in that order - linda_name = lua_tolstring(L_, -2, &name_len); - linda_group = LindaGroup{ static_cast(lua_tointeger(L_, -1)) }; + _linda_name = lua_tolstring(L_, -2, &_name_len); + _linda_group = LindaGroup{ static_cast(lua_tointeger(L_, -1)) }; break; } // The deep data is allocated separately of Lua stack; we might no longer be around when last reference to it is being released. // One can use any memory allocation scheme. Just don't use L's allocF because we don't know which state will get the honor of GCing the linda - Universe* const U{ universe_get(L_) }; - Linda* const linda{ new (U) Linda{ U, linda_group, linda_name, name_len } }; - return linda; + Universe* const _U{ universe_get(L_) }; + Linda* const _linda{ new (_U) Linda{ _U, _linda_group, _linda_name, _name_len } }; + return _linda; } diff --git a/src/macros_and_utils.h b/src/macros_and_utils.h index a8738a8..aa81db4 100644 --- a/src/macros_and_utils.h +++ b/src/macros_and_utils.h @@ -61,7 +61,7 @@ template // ################################################################################################# -#define USE_DEBUG_SPEW() 1 +#define USE_DEBUG_SPEW() 0 #if USE_DEBUG_SPEW() #define INDENT_BEGIN "%.*s " #define INDENT_END(U_) , (U_ ? U_->debugspewIndentDepth.load(std::memory_order_relaxed) : 0), DebugSpewIndentScope::debugspew_indent diff --git a/src/state.cpp b/src/state.cpp index 7252885..563fbc2 100644 --- a/src/state.cpp +++ b/src/state.cpp @@ -53,9 +53,8 @@ THE SOFTWARE. // [[nodiscard]] static int luaG_new_require(lua_State* L_) { - int rc; - int const args = lua_gettop(L_); // L_: args - Universe* U = universe_get(L_); + int const _args{ lua_gettop(L_) }; // L_: args + Universe* const _U{ universe_get(L_) }; // char const* modname = luaL_checkstring(L_, 1); STACK_GROW(L_, 1); @@ -66,18 +65,18 @@ THE SOFTWARE. // Using 'lua_pcall()' to catch errors; otherwise a failing 'require' would // leave us locked, blocking any future 'require' calls from other lanes. - U->requireMutex.lock(); + _U->requireMutex.lock(); // starting with Lua 5.4, require may return a second optional value, so we need LUA_MULTRET - rc = lua_pcall(L_, args, LUA_MULTRET, 0 /*errfunc*/); // L_: err|result(s) - U->requireMutex.unlock(); + int _rc{ lua_pcall(L_, _args, LUA_MULTRET, 0 /*errfunc*/) }; // L_: err|result(s) + _U->requireMutex.unlock(); // the required module (or an error message) is left on the stack as returned value by original require function - if (rc != LUA_OK) { // LUA_ERRRUN / LUA_ERRMEM ? + if (_rc != LUA_OK) { // LUA_ERRRUN / LUA_ERRMEM ? raise_lua_error(L_); } // should be 1 for Lua <= 5.3, 1 or 2 starting with Lua 5.4 - return lua_gettop(L_); // L_: result(s) + return lua_gettop(L_); // L_: result(s) } // ################################################################################################# @@ -149,9 +148,7 @@ namespace global { LUA_JITLIBNAME, luaopen_jit }, #endif // LUAJIT_FLAVOR() - { kLanesCoreLibName, require_lanes_core }, // So that we can open it like any base library (possible since we have access to the init function) - // - { nullptr, nullptr } + { kLanesCoreLibName, require_lanes_core } // So that we can open it like any base library (possible since we have access to the init function) }; } // namespace global @@ -160,18 +157,18 @@ namespace global static void open1lib(DEBUGSPEW_PARAM_COMMA(Universe* U_) lua_State* L_, char const* name_, size_t len_) { - for (int i{ 0 }; global::sLibs[i].name; ++i) { - if (strncmp(name_, global::sLibs[i].name, len_) == 0) { - lua_CFunction const libfunc{ global::sLibs[i].func }; - if (!libfunc) { + for (luaL_Reg const& _entry : global::sLibs) { + if (strncmp(name_, _entry.name, len_) == 0) { + lua_CFunction const _libfunc{ _entry.func }; + if (!_libfunc) { continue; } - name_ = global::sLibs[i].name; // note that the provided name_ doesn't necessarily ends with '\0', hence len_ + name_ = _entry.name; // note that the provided name_ doesn't necessarily ends with '\0', hence len_ DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "opening %.*s library\n" INDENT_END(U_), (int) len_, name_)); STACK_CHECK_START_REL(L_, 0); // open the library as if through require(), and create a global as well if necessary (the library table is left on the stack) - bool const isLanesCore{ libfunc == require_lanes_core }; // don't want to create a global for "lanes.core" - luaL_requiref(L_, name_, libfunc, !isLanesCore); // L_: {lib} + bool const isLanesCore{ _libfunc == require_lanes_core }; // don't want to create a global for "lanes.core" + luaL_requiref(L_, name_, _libfunc, !isLanesCore); // L_: {lib} // lanes.core doesn't declare a global, so scan it here and now if (isLanesCore) { populate_func_lookup_table(L_, -1, name_); @@ -196,7 +193,7 @@ static inline void open1lib(DEBUGSPEW_PARAM_COMMA(Universe* U_) lua_State* L_, c // just like lua_xmove, args are (from, to) static void copy_one_time_settings(Universe* U_, SourceState L1_, DestState L2_) { - DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U_ }); + DEBUGSPEW_CODE(DebugSpewIndentScope _scope{ U_ }); STACK_GROW(L1_, 2); STACK_CHECK_START_REL(L1_, 0); @@ -206,8 +203,8 @@ static void copy_one_time_settings(Universe* U_, SourceState L1_, DestState L2_) kConfigRegKey.pushValue(L1_); // L1_: config // copy settings from from source to destination registry - InterCopyContext c{ U_, L2_, L1_, {}, {}, {}, {}, {} }; - if (c.inter_move(1) != InterCopyResult::Success) { // L1_: L2_: config + InterCopyContext _c{ U_, L2_, L1_, {}, {}, {}, {}, {} }; + if (_c.inter_move(1) != InterCopyResult::Success) { // L1_: L2_: config raise_luaL_error(L1_, "failed to copy settings when loading " kLanesCoreLibName); } // set L2:_R[kConfigRegKey] = settings @@ -227,8 +224,8 @@ void initializeOnStateCreate(Universe* U_, lua_State* L_) U_->onStateCreateFunc = lua_tocfunction(L_, -1); // L_: settings on_state_create if (U_->onStateCreateFunc != nullptr) { // make sure the function doesn't have upvalues - char const* upname = lua_getupvalue(L_, -1, 1); // L_: settings on_state_create upval? - if (upname != nullptr) { // should be "" for C functions with upvalues if any + char const* _upname{ lua_getupvalue(L_, -1, 1) }; // L_: settings on_state_create upval? + if (_upname != nullptr) { // should be "" for C functions with upvalues if any raise_luaL_error(L_, "on_state_create shouldn't have upvalues"); } // remove this C function from the config table so that it doesn't cause problems @@ -248,29 +245,29 @@ void initializeOnStateCreate(Universe* U_, lua_State* L_) lua_State* create_state([[maybe_unused]] Universe* U_, lua_State* from_) { - lua_State* L; + lua_State* _L; #if LUAJIT_FLAVOR() == 64 // for some reason, LuaJIT 64 bits does not support creating a state with lua_newstate... - L = luaL_newstate(); + _L = luaL_newstate(); #else // LUAJIT_FLAVOR() == 64 if (U_->provideAllocator != nullptr) { // we have a function we can call to obtain an allocator lua_pushcclosure(from_, U_->provideAllocator, 0); lua_call(from_, 0, 1); { AllocatorDefinition* const def{ lua_tofulluserdata(from_, -1) }; - L = lua_newstate(def->allocF, def->allocUD); + _L = lua_newstate(def->allocF, def->allocUD); } lua_pop(from_, 1); } else { // reuse the allocator provided when the master state was created - L = lua_newstate(U_->protectedAllocator.allocF, U_->protectedAllocator.allocUD); + _L = lua_newstate(U_->protectedAllocator.allocF, U_->protectedAllocator.allocUD); } #endif // LUAJIT_FLAVOR() == 64 - if (L == nullptr) { + if (_L == nullptr) { raise_luaL_error(from_, "luaG_newstate() failed while creating state; out of memory"); } - return L; + return _L; } // ################################################################################################# @@ -321,34 +318,34 @@ void callOnStateCreate(Universe* U_, lua_State* L_, lua_State* from_, LookupMode */ lua_State* luaG_newstate(Universe* U_, SourceState from_, char const* libs_) { - DestState const L{ create_state(U_, from_) }; + DestState const _L{ create_state(U_, from_) }; - STACK_GROW(L, 2); - STACK_CHECK_START_ABS(L, 0); + STACK_GROW(_L, 2); + STACK_CHECK_START_ABS(_L, 0); // copy the universe as a light userdata (only the master state holds the full userdata) // that way, if Lanes is required in this new state, we'll know we are part of this universe - universe_store(L, U_); - STACK_CHECK(L, 0); + universe_store(_L, U_); + STACK_CHECK(_L, 0); // we'll need this every time we transfer some C function from/to this state - kLookupRegKey.setValue(L, [](lua_State* L_) { lua_newtable(L_); }); - STACK_CHECK(L, 0); + kLookupRegKey.setValue(_L, [](lua_State* L_) { lua_newtable(L_); }); + STACK_CHECK(_L, 0); // neither libs (not even 'base') nor special init func: we are done if (libs_ == nullptr && U_->onStateCreateFunc == nullptr) { DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "luaG_newstate(nullptr)\n" INDENT_END(U_))); - return L; + return _L; } DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "luaG_newstate()\n" INDENT_END(U_))); DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U_ }); // copy settings (for example because it may contain a Lua on_state_create function) - copy_one_time_settings(U_, from_, L); + copy_one_time_settings(U_, from_, _L); // 'lua.c' stops GC during initialization so perhaps it is a good idea. :) - lua_gc(L, LUA_GCSTOP, 0); + lua_gc(_L, LUA_GCSTOP, 0); // Anything causes 'base' to be taken in if (libs_ != nullptr) { @@ -356,24 +353,24 @@ lua_State* luaG_newstate(Universe* U_, SourceState from_, char const* libs_) // as we are called from luaopen_lanes_core() already, and that would deadlock if (libs_[0] == '*' && libs_[1] == 0) { DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "opening ALL standard libraries\n" INDENT_END(U_))); - luaL_openlibs(L); + luaL_openlibs(_L); // don't forget lanes.core for regular lane states - open1lib(DEBUGSPEW_PARAM_COMMA(U_) L, kLanesCoreLibName); + open1lib(DEBUGSPEW_PARAM_COMMA(U_) _L, kLanesCoreLibName); libs_ = nullptr; // done with libs } else { DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "opening base library\n" INDENT_END(U_))); #if LUA_VERSION_NUM >= 502 // open base library the same way as in luaL_openlibs() - luaL_requiref(L, "_G", luaopen_base, 1); - lua_pop(L, 1); + luaL_requiref(_L, "_G", luaopen_base, 1); + lua_pop(_L, 1); #else // LUA_VERSION_NUM - lua_pushcfunction(L, luaopen_base); - lua_pushstring(L, ""); - lua_call(L, 1, 0); + lua_pushcfunction(_L, luaopen_base); + lua_pushstring(_L, ""); + lua_call(_L, 1, 0); #endif // LUA_VERSION_NUM } } - STACK_CHECK(L, 0); + STACK_CHECK(_L, 0); // scan all libraries, open them one by one if (libs_) { @@ -387,40 +384,40 @@ lua_State* luaG_newstate(Universe* U_, SourceState from_, char const* libs_) while (isalnum(p[len]) || p[len] == '.') ++len; // open library - open1lib(DEBUGSPEW_PARAM_COMMA(U_) L, p, len); + open1lib(DEBUGSPEW_PARAM_COMMA(U_) _L, p, len); } } - lua_gc(L, LUA_GCRESTART, 0); + lua_gc(_L, LUA_GCRESTART, 0); - serialize_require(DEBUGSPEW_PARAM_COMMA(U_) L); + serialize_require(DEBUGSPEW_PARAM_COMMA(U_) _L); // call this after the base libraries are loaded and GC is restarted // will raise an error in from_ in case of problem - callOnStateCreate(U_, L, from_, LookupMode::LaneBody); + callOnStateCreate(U_, _L, from_, LookupMode::LaneBody); - STACK_CHECK(L, 0); + STACK_CHECK(_L, 0); // after all this, register everything we find in our name<->function database - lua_pushglobaltable(L); // Lua 5.2 no longer has LUA_GLOBALSINDEX: we must push globals table on the stack - STACK_CHECK(L, 1); - populate_func_lookup_table(L, -1, nullptr); + lua_pushglobaltable(_L); // Lua 5.2 no longer has LUA_GLOBALSINDEX: we must push globals table on the stack + STACK_CHECK(_L, 1); + populate_func_lookup_table(_L, -1, nullptr); #if 1 && USE_DEBUG_SPEW() // dump the lookup database contents - kLookupRegKey.pushValue(L); // L: {} - lua_pushnil(L); // L: {} nil - while (lua_next(L, -2)) { // L: {} k v - lua_getglobal(L, "print"); // L: {} k v print + kLookupRegKey.pushValue(_L); // L: {} + lua_pushnil(_L); // L: {} nil + while (lua_next(_L, -2)) { // L: {} k v + lua_getglobal(_L, "print"); // L: {} k v print int const indent{ U_->debugspewIndentDepth.load(std::memory_order_relaxed) }; - lua_pushlstring(L, DebugSpewIndentScope::debugspew_indent, indent); // L: {} k v print " " - lua_pushvalue(L, -4); // L: {} k v print " " k - lua_pushvalue(L, -4); // L: {} k v print " " k v - lua_call(L, 3, 0); // L: {} k v - lua_pop(L, 1); // L: {} k + lua_pushlstring(_L, DebugSpewIndentScope::debugspew_indent, indent); // L: {} k v print " " + lua_pushvalue(_L, -4); // L: {} k v print " " k + lua_pushvalue(_L, -4); // L: {} k v print " " k v + lua_call(_L, 3, 0); // L: {} k v + lua_pop(_L, 1); // L: {} k } - lua_pop(L, 1); // L: {} + lua_pop(_L, 1); // L: {} #endif // USE_DEBUG_SPEW() - lua_pop(L, 1); - STACK_CHECK(L, 0); - return L; + lua_pop(_L, 1); + STACK_CHECK(_L, 0); + return _L; } diff --git a/src/tools.cpp b/src/tools.cpp index 2623da6..0cfe1ab 100644 --- a/src/tools.cpp +++ b/src/tools.cpp @@ -69,16 +69,16 @@ static constexpr RegistryUniqueKey kLookupCacheRegKey{ 0x9BF75F84E54B691Bull }; return FuncSubType::Native; } { - int mustpush{ 0 }; + int _mustpush{ 0 }; if (lua_absindex(L_, _i) != lua_gettop(L_)) { lua_pushvalue(L_, _i); - mustpush = 1; + _mustpush = 1; } // the provided writer fails with code 666 // therefore, anytime we get 666, this means that lua_dump() attempted a dump // all other cases mean this is either a C or LuaJIT-fast function int const dumpres{ lua504_dump(L_, dummy_writer, nullptr, 0) }; - lua_pop(L_, mustpush); + lua_pop(L_, _mustpush); if (dumpres == 666) { return FuncSubType::Bytecode; } @@ -91,22 +91,22 @@ static constexpr RegistryUniqueKey kLookupCacheRegKey{ 0x9BF75F84E54B691Bull }; // inspired from tconcat() in ltablib.c [[nodiscard]] static char const* luaG_pushFQN(lua_State* L_, int t_, int last_, size_t* length_) { - luaL_Buffer b; + luaL_Buffer _b; STACK_CHECK_START_REL(L_, 0); // Lua 5.4 pushes &b as light userdata on the stack. be aware of it... - luaL_buffinit(L_, &b); // L_: ... {} ... &b? + luaL_buffinit(L_, &_b); // L_: ... {} ... &b? int i = 1; for (; i < last_; ++i) { lua_rawgeti(L_, t_, i); - luaL_addvalue(&b); - luaL_addlstring(&b, "/", 1); + luaL_addvalue(&_b); + luaL_addlstring(&_b, "/", 1); } if (i == last_) { // add last value (if interval was not empty) lua_rawgeti(L_, t_, i); - luaL_addvalue(&b); + luaL_addvalue(&_b); } // &b is popped at that point (-> replaced by the result) - luaL_pushresult(&b); // L_: ... {} ... "" + luaL_pushresult(&_b); // L_: ... {} ... "" STACK_CHECK(L_, 1); return lua_tolstring(L_, -1, length_); } @@ -124,28 +124,28 @@ static constexpr RegistryUniqueKey kLookupCacheRegKey{ 0x9BF75F84E54B691Bull }; static void update_lookup_entry(DEBUGSPEW_PARAM_COMMA(Universe* U_) lua_State* L_, int ctxBase_, int depth_) { // slot 1 in the stack contains the table that receives everything we found - int const dest{ ctxBase_ }; + int const _dest{ ctxBase_ }; // slot 2 contains a table that, when concatenated, produces the fully qualified name of scanned elements in the table provided at slot _i - int const fqn{ ctxBase_ + 1 }; + int const _fqn{ ctxBase_ + 1 }; - size_t prevNameLength, newNameLength; - char const* prevName; - DEBUGSPEW_CODE(char const* newName); + DEBUGSPEW_CODE(char const* _newName); DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "update_lookup_entry()\n" INDENT_END(U_))); DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U_ }); STACK_CHECK_START_REL(L_, 0); // first, raise an error if the function is already known lua_pushvalue(L_, -1); // L_: ... {bfc} k o o - lua_rawget(L_, dest); // L_: ... {bfc} k o name? - prevName = lua_tolstring(L_, -1, &prevNameLength); // nullptr if we got nil (first encounter of this object) + lua_rawget(L_, _dest); // L_: ... {bfc} k o name? + size_t _prevNameLength; + char const* const _prevName{ lua_tolstring(L_, -1, &_prevNameLength) }; // nullptr if we got nil (first encounter of this object) // push name in fqn stack (note that concatenation will crash if name is a not string or a number) lua_pushvalue(L_, -3); // L_: ... {bfc} k o name? k LUA_ASSERT(L_, lua_type(L_, -1) == LUA_TNUMBER || lua_type(L_, -1) == LUA_TSTRING); ++depth_; - lua_rawseti(L_, fqn, depth_); // L_: ... {bfc} k o name? + lua_rawseti(L_, _fqn, depth_); // L_: ... {bfc} k o name? // generate name - DEBUGSPEW_OR_NOT(newName, std::ignore) = luaG_pushFQN(L_, fqn, depth_, &newNameLength); // L_: ... {bfc} k o name? "f.q.n" + size_t _newNameLength; + DEBUGSPEW_OR_NOT(_newName, std::ignore) = luaG_pushFQN(L_, _fqn, depth_, &_newNameLength); // L_: ... {bfc} k o name? "f.q.n" // Lua 5.2 introduced a hash randomizer seed which causes table iteration to yield a different key order // on different VMs even when the tables are populated the exact same way. // When Lua is built with compatibility options (such as LUA_COMPAT_ALL), @@ -155,34 +155,34 @@ static void update_lookup_entry(DEBUGSPEW_PARAM_COMMA(Universe* U_) lua_State* L // Also, nothing prevents any external module from exposing a given object under several names, so... // Therefore, when we encounter an object for which a name was previously registered, we need to select the names // based on some sorting order so that we end up with the same name in all databases whatever order the table walk yielded - if (prevName != nullptr && (prevNameLength < newNameLength || lua_lessthan(L_, -2, -1))) { - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "%s '%s' remained named '%s'\n" INDENT_END(U_), lua_typename(L_, lua_type(L_, -3)), newName, prevName)); + if (_prevName != nullptr && (_prevNameLength < _newNameLength || lua_lessthan(L_, -2, -1))) { + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "%s '%s' remained named '%s'\n" INDENT_END(U_), lua_typename(L_, lua_type(L_, -3)), _newName, _prevName)); // the previous name is 'smaller' than the one we just generated: keep it! lua_pop(L_, 3); // L_: ... {bfc} k } else { // the name we generated is either the first one, or a better fit for our purposes - if (prevName) { + if (_prevName) { // clear the previous name for the database to avoid clutter lua_insert(L_, -2); // L_: ... {bfc} k o "f.q.n" prevName // t[prevName] = nil lua_pushnil(L_); // L_: ... {bfc} k o "f.q.n" prevName nil - lua_rawset(L_, dest); // L_: ... {bfc} k o "f.q.n" + lua_rawset(L_, _dest); // L_: ... {bfc} k o "f.q.n" } else { lua_remove(L_, -2); // L_: ... {bfc} k o "f.q.n" } - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "%s '%s'\n" INDENT_END(U_), lua_typename(L_, lua_type(L_, -2)), newName)); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "%s '%s'\n" INDENT_END(U_), lua_typename(L_, lua_type(L_, -2)), _newName)); // prepare the stack for database feed lua_pushvalue(L_, -1); // L_: ... {bfc} k o "f.q.n" "f.q.n" lua_pushvalue(L_, -3); // L_: ... {bfc} k o "f.q.n" "f.q.n" o LUA_ASSERT(L_, lua_rawequal(L_, -1, -4)); LUA_ASSERT(L_, lua_rawequal(L_, -2, -3)); // t["f.q.n"] = o - lua_rawset(L_, dest); // L_: ... {bfc} k o "f.q.n" + lua_rawset(L_, _dest); // L_: ... {bfc} k o "f.q.n" // t[o] = "f.q.n" - lua_rawset(L_, dest); // L_: ... {bfc} k + lua_rawset(L_, _dest); // L_: ... {bfc} k // remove table name from fqn stack lua_pushnil(L_); // L_: ... {bfc} k nil - lua_rawseti(L_, fqn, depth_); // L_: ... {bfc} k + lua_rawseti(L_, _fqn, depth_); // L_: ... {bfc} k } --depth_; STACK_CHECK(L_, -1); @@ -194,9 +194,9 @@ static void populate_func_lookup_table_recur(DEBUGSPEW_PARAM_COMMA(Universe* U_) { // slot dbIdx_ contains the lookup database table // slot dbIdx_ + 1 contains a table that, when concatenated, produces the fully qualified name of scanned elements in the table provided at slot i_ - int const fqn{ dbIdx_ + 1 }; + int const _fqn{ dbIdx_ + 1 }; // slot dbIdx_ + 2 contains a cache that stores all already visited tables to avoid infinite recursion loops - int const cache{ dbIdx_ + 2 }; + int const _cache{ dbIdx_ + 2 }; DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "populate_func_lookup_table_recur()\n" INDENT_END(U_))); DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U_ }); @@ -212,19 +212,19 @@ static void populate_func_lookup_table_recur(DEBUGSPEW_PARAM_COMMA(Universe* U_) // if table is already visited, we are done lua_pushvalue(L_, i_); // L_: ... {i_} {} - lua_rawget(L_, cache); // L_: ... {i_} nil|n - lua_Integer visit_count{ lua_tointeger(L_, -1) }; // 0 if nil, else n + lua_rawget(L_, _cache); // L_: ... {i_} nil|n + lua_Integer _visit_count{ lua_tointeger(L_, -1) }; // 0 if nil, else n lua_pop(L_, 1); // L_: ... {i_} STACK_CHECK(L_, 0); - if (visit_count > 0) { + if (_visit_count > 0) { DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "already visited\n" INDENT_END(U_))); return; } // remember we visited this table (1-visit count) lua_pushvalue(L_, i_); // L_: ... {i_} {} - lua_pushinteger(L_, visit_count + 1); // L_: ... {i_} {} 1 - lua_rawset(L_, cache); // L_: ... {i_} + lua_pushinteger(L_, _visit_count + 1); // L_: ... {i_} {} 1 + lua_rawset(L_, _cache); // L_: ... {i_} STACK_CHECK(L_, 0); // we need to remember subtables to process them after functions encountered at the current depth (breadth-first search) @@ -240,11 +240,11 @@ static void populate_func_lookup_table_recur(DEBUGSPEW_PARAM_COMMA(Universe* U_) // increment visit count to make sure we will actually scan it at this recursive level lua_pushvalue(L_, -1); // L_: ... {i_} {bfc} k {} {} lua_pushvalue(L_, -1); // L_: ... {i_} {bfc} k {} {} {} - lua_rawget(L_, cache); // L_: ... {i_} {bfc} k {} {} n? - visit_count = lua_tointeger(L_, -1) + 1; // 1 if we got nil, else n+1 + lua_rawget(L_, _cache); // L_: ... {i_} {bfc} k {} {} n? + _visit_count = lua_tointeger(L_, -1) + 1; // 1 if we got nil, else n+1 lua_pop(L_, 1); // L_: ... {i_} {bfc} k {} {} - lua_pushinteger(L_, visit_count); // L_: ... {i_} {bfc} k {} {} n - lua_rawset(L_, cache); // L_: ... {i_} {bfc} k {} + lua_pushinteger(L_, _visit_count); // L_: ... {i_} {bfc} k {} {} n + lua_rawset(L_, _cache); // L_: ... {i_} {bfc} k {} // store the table in the breadth-first cache lua_pushvalue(L_, -2); // L_: ... {i_} {bfc} k {} k lua_pushvalue(L_, -2); // L_: ... {i_} {bfc} k {} k {} @@ -269,27 +269,27 @@ static void populate_func_lookup_table_recur(DEBUGSPEW_PARAM_COMMA(Universe* U_) DEBUGSPEW_CODE(DebugSpewIndentScope scope2{ U_ }); // un-visit this table in case we do need to process it lua_pushvalue(L_, -1); // L_: ... {i_} {bfc} k {} {} - lua_rawget(L_, cache); // L_: ... {i_} {bfc} k {} n + lua_rawget(L_, _cache); // L_: ... {i_} {bfc} k {} n LUA_ASSERT(L_, lua_type(L_, -1) == LUA_TNUMBER); - visit_count = lua_tointeger(L_, -1) - 1; + _visit_count = lua_tointeger(L_, -1) - 1; lua_pop(L_, 1); // L_: ... {i_} {bfc} k {} lua_pushvalue(L_, -1); // L_: ... {i_} {bfc} k {} {} - if (visit_count > 0) { - lua_pushinteger(L_, visit_count); // L_: ... {i_} {bfc} k {} {} n + if (_visit_count > 0) { + lua_pushinteger(L_, _visit_count); // L_: ... {i_} {bfc} k {} {} n } else { lua_pushnil(L_); // L_: ... {i_} {bfc} k {} {} nil } - lua_rawset(L_, cache); // L_: ... {i_} {bfc} k {} + lua_rawset(L_, _cache); // L_: ... {i_} {bfc} k {} // push table name in fqn stack (note that concatenation will crash if name is a not string!) lua_pushvalue(L_, -2); // L_: ... {i_} {bfc} k {} k - lua_rawseti(L_, fqn, depth_); // L_: ... {i_} {bfc} k {} + lua_rawseti(L_, _fqn, depth_); // L_: ... {i_} {bfc} k {} populate_func_lookup_table_recur(DEBUGSPEW_PARAM_COMMA(U_) L_, dbIdx_, lua_gettop(L_), depth_); lua_pop(L_, 1); // L_: ... {i_} {bfc} k STACK_CHECK(L_, 2); } // remove table name from fqn stack lua_pushnil(L_); // L_: ... {i_} {bfc} nil - lua_rawseti(L_, fqn, depth_); // L_: ... {i_} {bfc} + lua_rawseti(L_, _fqn, depth_); // L_: ... {i_} {bfc} --depth_; // we are done with our cache lua_pop(L_, 1); // L_: ... {i_} @@ -302,46 +302,46 @@ static void populate_func_lookup_table_recur(DEBUGSPEW_PARAM_COMMA(Universe* U_) // create a "fully.qualified.name" <-> function equivalence database void populate_func_lookup_table(lua_State* L_, int i_, char const* name_) { - int const in_base = lua_absindex(L_, i_); - DEBUGSPEW_CODE(Universe* U = universe_get(L_)); - DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "%p: populate_func_lookup_table('%s')\n" INDENT_END(U), L_, name_ ? name_ : "nullptr")); - DEBUGSPEW_CODE(DebugSpewIndentScope scope{ U }); + int const _in_base = lua_absindex(L_, i_); + DEBUGSPEW_CODE(Universe* _U = universe_get(L_)); + DEBUGSPEW_CODE(fprintf(stderr, INDENT_BEGIN "%p: populate_func_lookup_table('%s')\n" INDENT_END(_U), L_, name_ ? name_ : "nullptr")); + DEBUGSPEW_CODE(DebugSpewIndentScope _scope{ _U }); STACK_GROW(L_, 3); STACK_CHECK_START_REL(L_, 0); kLookupRegKey.pushValue(L_); // L_: {} - int const dbIdx{ lua_gettop(L_) }; + int const _dbIdx{ lua_gettop(L_) }; STACK_CHECK(L_, 1); LUA_ASSERT(L_, lua_istable(L_, -1)); - if (lua_type(L_, in_base) == LUA_TFUNCTION) { // for example when a module is a simple function + if (lua_type(L_, _in_base) == LUA_TFUNCTION) { // for example when a module is a simple function name_ = name_ ? name_ : "nullptr"; - lua_pushvalue(L_, in_base); // L_: {} f + lua_pushvalue(L_, _in_base); // L_: {} f lua_pushstring(L_, name_); // L_: {} f _name lua_rawset(L_, -3); // L_: {} lua_pushstring(L_, name_); // L_: {} _name - lua_pushvalue(L_, in_base); // L_: {} _name f + lua_pushvalue(L_, _in_base); // L_: {} _name f lua_rawset(L_, -3); // L_: {} lua_pop(L_, 1); // L_: - } else if (lua_type(L_, in_base) == LUA_TTABLE) { + } else if (lua_type(L_, _in_base) == LUA_TTABLE) { lua_newtable(L_); // L_: {} {fqn} - int startDepth{ 0 }; + int _startDepth{ 0 }; if (name_) { STACK_CHECK(L_, 2); lua_pushstring(L_, name_); // L_: {} {fqn} "name" // generate a name, and if we already had one name, keep whichever is the shorter - lua_pushvalue(L_, in_base); // L_: {} {fqn} "name" t - update_lookup_entry(DEBUGSPEW_PARAM_COMMA(U) L_, dbIdx, startDepth); // L_: {} {fqn} "name" + lua_pushvalue(L_, _in_base); // L_: {} {fqn} "name" t + update_lookup_entry(DEBUGSPEW_PARAM_COMMA(_U) L_, _dbIdx, _startDepth); // L_: {} {fqn} "name" // don't forget to store the name at the bottom of the fqn stack - lua_rawseti(L_, -2, ++startDepth); // L_: {} {fqn} + lua_rawseti(L_, -2, ++_startDepth); // L_: {} {fqn} STACK_CHECK(L_, 2); } // retrieve the cache, create it if we haven't done it yet std::ignore = kLookupCacheRegKey.getSubTable(L_, 0, 0); // L_: {} {fqn} {cache} // process everything we find in that table, filling in lookup data for all functions and tables we see there - populate_func_lookup_table_recur(DEBUGSPEW_PARAM_COMMA(U) L_, dbIdx, in_base, startDepth); + populate_func_lookup_table_recur(DEBUGSPEW_PARAM_COMMA(_U) L_, _dbIdx, _in_base, _startDepth); lua_pop(L_, 3); // L_: } else { lua_pop(L_, 1); // L_: - raise_luaL_error(L_, "unsupported module type %s", lua_typename(L_, lua_type(L_, in_base))); + raise_luaL_error(L_, "unsupported module type %s", lua_typename(L_, lua_type(L_, _in_base))); } STACK_CHECK(L_, 0); } @@ -484,9 +484,9 @@ void populate_func_lookup_table(lua_State* L_, int i_, char const* name_) // "type", "name" = lanes.nameof(o) int luaG_nameof(lua_State* L_) { - int const what{ lua_gettop(L_) }; - if (what > 1) { - raise_luaL_argerror(L_, what, "too many arguments."); + int const _what{ lua_gettop(L_) }; + if (_what > 1) { + raise_luaL_argerror(L_, _what, "too many arguments."); } // nil, boolean, light userdata, number and string aren't identifiable diff --git a/src/universe.cpp b/src/universe.cpp index a5c28f0..f05cc6f 100644 --- a/src/universe.cpp +++ b/src/universe.cpp @@ -68,13 +68,13 @@ Universe::Universe() [[nodiscard]] Universe* universe_create(lua_State* L_) { LUA_ASSERT(L_, universe_get(L_) == nullptr); - Universe* const U{ lua_newuserdatauv(L_, 0) }; // universe - U->Universe::Universe(); + Universe* const _U{ lua_newuserdatauv(L_, 0) }; // universe + _U->Universe::Universe(); STACK_CHECK_START_REL(L_, 1); kUniverseFullRegKey.setValue(L_, [](lua_State* L_) { lua_pushvalue(L_, -2); }); - kUniverseLightRegKey.setValue(L_, [U](lua_State* L_) { lua_pushlightuserdata(L_, U); }); + kUniverseLightRegKey.setValue(L_, [U = _U](lua_State* L_) { lua_pushlightuserdata(L_, U); }); STACK_CHECK(L_, 1); - return U; + return _U; } // ################################################################################################# @@ -84,22 +84,22 @@ void Universe::terminateFreeRunningLanes(lua_State* L_, lua_Duration shutdownTim if (selfdestructFirst != SELFDESTRUCT_END) { // Signal _all_ still running threads to exit (including the timer thread) { - std::lock_guard guard{ selfdestructMutex }; - Lane* lane{ selfdestructFirst }; - while (lane != SELFDESTRUCT_END) { + std::lock_guard _guard{ selfdestructMutex }; + Lane* _lane{ selfdestructFirst }; + while (_lane != SELFDESTRUCT_END) { // attempt the requested cancel with a small timeout. // if waiting on a linda, they will raise a cancel_error. // if a cancellation hook is desired, it will be installed to try to raise an error - if (lane->thread.joinable()) { - std::ignore = thread_cancel(lane, op_, 1, std::chrono::steady_clock::now() + 1us, true); + if (_lane->thread.joinable()) { + std::ignore = thread_cancel(_lane, op_, 1, std::chrono::steady_clock::now() + 1us, true); } - lane = lane->selfdestruct_next; + _lane = _lane->selfdestruct_next; } } // When noticing their cancel, the lanes will remove themselves from the selfdestruct chain. { - std::chrono::time_point t_until{ std::chrono::steady_clock::now() + std::chrono::duration_cast(shutdownTimeout_) }; + std::chrono::time_point _until{ std::chrono::steady_clock::now() + std::chrono::duration_cast(shutdownTimeout_) }; while (selfdestructFirst != SELFDESTRUCT_END) { // give threads time to act on their cancel @@ -107,17 +107,17 @@ void Universe::terminateFreeRunningLanes(lua_State* L_, lua_Duration shutdownTim // count the number of cancelled thread that didn't have the time to act yet int n{ 0 }; { - std::lock_guard guard{ selfdestructMutex }; - Lane* lane{ selfdestructFirst }; - while (lane != SELFDESTRUCT_END) { - if (lane->cancelRequest != CancelRequest::None) + std::lock_guard _guard{ selfdestructMutex }; + Lane* _lane{ selfdestructFirst }; + while (_lane != SELFDESTRUCT_END) { + if (_lane->cancelRequest != CancelRequest::None) ++n; - lane = lane->selfdestruct_next; + _lane = _lane->selfdestruct_next; } } // if timeout elapsed, or we know all threads have acted, stop waiting - std::chrono::time_point t_now = std::chrono::steady_clock::now(); - if (n == 0 || (t_now >= t_until)) { + std::chrono::time_point _now = std::chrono::steady_clock::now(); + if (n == 0 || (_now >= _until)) { DEBUGSPEW_CODE(fprintf(stderr, "%d uncancelled lane(s) remain after waiting %fs at process end.\n", n, shutdownTimeout_.count())); break; } @@ -133,11 +133,11 @@ void Universe::terminateFreeRunningLanes(lua_State* L_, lua_Duration shutdownTim // If after all this, we still have some free-running lanes, it's an external user error, they should have stopped appropriately { - std::lock_guard guard{ selfdestructMutex }; - Lane* lane{ selfdestructFirst }; - if (lane != SELFDESTRUCT_END) { + std::lock_guard _guard{ selfdestructMutex }; + Lane* _lane{ selfdestructFirst }; + if (_lane != SELFDESTRUCT_END) { // this causes a leak because we don't call U's destructor (which could be bad if the still running lanes are accessing it) - raise_luaL_error(L_, "Zombie thread %s refuses to die!", lane->debugName); + raise_luaL_error(L_, "Zombie thread %s refuses to die!", _lane->debugName); } } } @@ -147,25 +147,25 @@ void Universe::terminateFreeRunningLanes(lua_State* L_, lua_Duration shutdownTim // process end: cancel any still free-running threads int universe_gc(lua_State* L_) { - lua_Duration const shutdown_timeout{ lua_tonumber(L_, lua_upvalueindex(1)) }; - [[maybe_unused]] char const* const op_string{ lua_tostring(L_, lua_upvalueindex(2)) }; - Universe* const U{ lua_tofulluserdata(L_, 1) }; - U->terminateFreeRunningLanes(L_, shutdown_timeout, which_cancel_op(op_string)); + lua_Duration const _shutdown_timeout{ lua_tonumber(L_, lua_upvalueindex(1)) }; + [[maybe_unused]] char const* const _op_string{ lua_tostring(L_, lua_upvalueindex(2)) }; + Universe* const _U{ lua_tofulluserdata(L_, 1) }; + _U->terminateFreeRunningLanes(L_, _shutdown_timeout, which_cancel_op(_op_string)); // no need to mutex-protect this as all threads in the universe are gone at that point - if (U->timerLinda != nullptr) { // test in case some early internal error prevented Lanes from creating the deep timer - [[maybe_unused]] int const prev_ref_count{ U->timerLinda->refcount.fetch_sub(1, std::memory_order_relaxed) }; + if (_U->timerLinda != nullptr) { // test in case some early internal error prevented Lanes from creating the deep timer + [[maybe_unused]] int const prev_ref_count{ _U->timerLinda->refcount.fetch_sub(1, std::memory_order_relaxed) }; LUA_ASSERT(L_, prev_ref_count == 1); // this should be the last reference - DeepFactory::DeleteDeepObject(L_, U->timerLinda); - U->timerLinda = nullptr; + DeepFactory::DeleteDeepObject(L_, _U->timerLinda); + _U->timerLinda = nullptr; } - close_keepers(U); + close_keepers(_U); // remove the protected allocator, if any - U->protectedAllocator.removeFrom(L_); + _U->protectedAllocator.removeFrom(L_); - U->Universe::~Universe(); + _U->Universe::~Universe(); return 0; } -- cgit v1.2.3-55-g6feb