aboutsummaryrefslogtreecommitdiff
path: root/src/macros_and_utils.h
blob: edda76eeddea43a3ed92d9f37ae814c250ca8abf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#pragma once

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#ifdef __cplusplus
}
#endif // __cplusplus

#include <cassert>
#include <chrono>
#include <tuple>
#include <type_traits>

using namespace std::chrono_literals;

#define USE_DEBUG_SPEW() 0
#if USE_DEBUG_SPEW()
#define INDENT_BEGIN "%.*s "
#define INDENT_END , (U ? U->debugspew_indent_depth.load(std::memory_order_relaxed) : 0), DebugSpewIndentScope::debugspew_indent
#define DEBUGSPEW_CODE(_code) _code
#define DEBUGSPEW_OR_NOT(a_, b_) a_
#define DEBUGSPEW_PARAM_COMMA(param_) param_,
#define DEBUGSPEW_COMMA_PARAM( param_) , param_
#else // USE_DEBUG_SPEW()
#define DEBUGSPEW_CODE(_code)
#define DEBUGSPEW_OR_NOT(a_, b_) b_
#define DEBUGSPEW_PARAM_COMMA(param_)
#define DEBUGSPEW_COMMA_PARAM( param_)
#endif // USE_DEBUG_SPEW()

#ifdef NDEBUG

#define LUA_ASSERT(L,c) ; //nothing

#define STACK_CHECK_START_REL(L, offset_)
#define STACK_CHECK_START_ABS(L, offset_)
#define STACK_CHECK_RESET_REL(L, offset_)
#define STACK_CHECK_RESET_ABS(L, offset_)
#define STACK_CHECK(L, offset_)

#else // NDEBUG

inline void LUA_ASSERT_IMPL(lua_State* L_, bool cond_, char const* file_, size_t const line_, char const* txt_)
{
    if (!cond_)
    {
        luaL_error(L_, "LUA_ASSERT %s:%llu '%s'", file_, line_, txt_); // doesn't return
    }
}

#define LUA_ASSERT(L_, cond_) LUA_ASSERT_IMPL(L_, cond_, __FILE__, __LINE__, #cond_)

class StackChecker
{
    private:
    lua_State* const m_L;
    int m_oldtop;

    public:
    struct Relative
    {
        int const m_offset;

        operator int() const { return m_offset; }
    };

    struct Absolute
    {
        int const m_offset;

        operator int() const { return m_offset; }
    };

    StackChecker(lua_State* const L_, Relative offset_, char const* file_, size_t const line_)
    : m_L{ L_ }
    , m_oldtop{ lua_gettop(L_) - offset_ }
    {
        if ((offset_ < 0) || (m_oldtop < 0))
        {
            assert(false);
            luaL_error(m_L, "STACK INIT ASSERT failed (%d not %d): %s:%llu", lua_gettop(m_L), offset_, file_, line_); // doesn't return
        }
    }

    StackChecker(lua_State* const L_, Absolute pos_, char const* file_, size_t const line_)
    : m_L{ L_ }
    , m_oldtop{ 0 }
    {
        if (lua_gettop(m_L) != pos_)
        {
            assert(false);
            luaL_error(m_L, "STACK INIT ASSERT failed (%d not %d): %s:%llu", lua_gettop(m_L), pos_, file_, line_); // doesn't return
        }
    }

    StackChecker& operator=(StackChecker const& rhs_)
    {
        assert(m_L == rhs_.m_L);
        m_oldtop = rhs_.m_oldtop;
        return *this;
    }

    // verify if the distance between the current top and the initial one is what we expect
    void check(int expected_, char const* file_, size_t const line_)
    {
        if (expected_ != LUA_MULTRET)
        {
            int const actual{ lua_gettop(m_L) - m_oldtop };
            if (actual != expected_)
            {
                assert(false);
                luaL_error(m_L, "STACK ASSERT failed (%d not %d): %s:%llu", actual, expected_, file_, line_); // doesn't return
            }
        }
    }
};

#define STACK_CHECK_START_REL(L, offset_) StackChecker stackChecker_##L{L, StackChecker::Relative{ offset_ }, __FILE__, __LINE__}
#define STACK_CHECK_START_ABS(L, offset_) StackChecker stackChecker_##L{L, StackChecker::Absolute{ offset_ }, __FILE__, __LINE__}
#define STACK_CHECK_RESET_REL(L, offset_) stackChecker_##L = StackChecker{L, StackChecker::Relative{ offset_ }, __FILE__, __LINE__}
#define STACK_CHECK_RESET_ABS(L, offset_) stackChecker_##L = StackChecker{L, StackChecker::Absolute{ offset_ }, __FILE__, __LINE__}
#define STACK_CHECK(L, offset_) stackChecker_##L.check(offset_, __FILE__, __LINE__)

#endif // NDEBUG

inline void STACK_GROW(lua_State* L, int n_)
{
    if (!lua_checkstack(L, n_))
    {
        luaL_error(L, "Cannot grow stack!"); // doesn't return
    }
}

#define LUAG_FUNC(func_name) [[nodiscard]] int LG_##func_name(lua_State* L)

// #################################################################################################

// a small helper to extract a full userdata pointer from the stack in a safe way
template<typename T>
[[nodiscard]] T* lua_tofulluserdata(lua_State* L, int index_)
{
    LUA_ASSERT(L, lua_isnil(L, index_) || lua_type(L, index_) == LUA_TUSERDATA);
    return static_cast<T*>(lua_touserdata(L, index_));
}

template<typename T>
[[nodiscard]] auto lua_tolightuserdata(lua_State* L, int index_)
{
    LUA_ASSERT(L, lua_isnil(L, index_) || lua_islightuserdata(L, index_));
    if constexpr (std::is_pointer_v<T>)
    {
        return static_cast<T>(lua_touserdata(L, index_));
    }
    else
    {
        return static_cast<T*>(lua_touserdata(L, index_));
    }
}

template <typename T>
[[nodiscard]] T* lua_newuserdatauv(lua_State* L, int nuvalue_)
{
    return static_cast<T*>(lua_newuserdatauv(L, sizeof(T), nuvalue_));
}

// #################################################################################################

// use this instead of Lua's lua_error if possible
[[noreturn]] static inline void raise_lua_error(lua_State* L)
{
    std::ignore = lua_error(L); // doesn't return
    assert(false); // we should never get here, but i'm paranoid
}

using lua_Duration = std::chrono::template duration<lua_Number>;

// #################################################################################################

// A unique type generator
template <typename T, auto = [] {}, typename specialization = void>
class Unique
{
    private:

    T m_val;

    public:

    Unique() = default;
    operator T() const { return m_val; }
    explicit Unique(T b_) : m_val{ b_ } {}
};

template <typename T, auto lambda>
class Unique<T, lambda, std::enable_if_t<!std::is_scalar_v<T>>> : public T
{
    public:

    using T::T;
    explicit Unique(T const& b_) : T{ b_ } {}
};

// #################################################################################################

using Source = Unique<lua_State*>;
using Dest = Unique<lua_State*>;

// #################################################################################################

// A helper to issue an error if the provided optional doesn't contain a value
// we can't use std::optional::value_or(luaL_error(...)), because the 'or' value is always evaluated
template <typename T>
concept IsOptional = requires(T x){ x.value_or(T{}); };

template<typename T, typename ...Ts>
requires IsOptional<T>
typename T::value_type const& OptionalValue(T const& x_, Ts... args_)
{
    if (!x_.has_value())
    {
        luaL_error(std::forward<Ts>(args_)...); // doesn't return
    }
    return x_.value();
}