aboutsummaryrefslogblamecommitdiffstats
path: root/library/cpp/lua/wrapper.h
blob: 0d568f049ad9a882e98cf23d567ffd894693b30b (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565



















































































































































































































































































































































































































































































































































































                                                                                                   
#pragma once

#include <library/cpp/string_utils/ztstrbuf/ztstrbuf.h>

#include <util/memory/alloc.h>
#include <util/generic/ptr.h>
#include <util/generic/string.h>
#include <util/generic/yexception.h>
#include <util/generic/buffer.h>
#include <util/datetime/base.h>
#include <functional>

#include <contrib/libs/lua/lua.h>

class IInputStream;
class IOutputStream;

class TLuaStateHolder {
    struct TDeleteState {
        static inline void Destroy(lua_State* state) {
            lua_close(state);
        }
    };

public:
    class TError: public yexception {
    };

    inline TLuaStateHolder(size_t memory_limit = 0)
        : AllocFree(memory_limit)
        , MyState_(lua_newstate(memory_limit ? AllocLimit : Alloc, (void*)this))
        , State_(MyState_.Get())
    {
        if (!State_) {
            ythrow TError() << "can not construct lua state: not enough memory";
        }
    }

    inline TLuaStateHolder(lua_State* state) noexcept
        : State_(state)
    {
    }

    inline operator lua_State*() noexcept {
        return State_;
    }

    inline void BootStrap() {
        luaL_openlibs(State_);
    }

    inline void error() {
        ythrow TError() << "lua error: " << pop_string();
    }

    inline bool is_string(int index) {
        return lua_isstring(State_, index);
    }

    inline void is_string_strict(int index) {
        if (!is_string(index)) {
            ythrow TError() << "internal lua error (not a string)";
        }
    }

    inline TStringBuf to_string(int index) {
        size_t len = 0;
        const char* data = lua_tolstring(State_, index, &len);
        return TStringBuf(data, len);
    }

    inline TStringBuf to_string(int index, TStringBuf defaultValue) {
        return is_string(index) ? to_string(index) : defaultValue;
    }

    inline TStringBuf to_string_strict(int index) {
        is_string_strict(index);
        return to_string(index);
    }

    inline TString pop_string() {
        TString ret(to_string(-1));
        pop();
        return ret;
    }

    inline TString pop_string(TStringBuf defaultValue) {
        TString ret(to_string(-1, defaultValue));
        pop();
        return ret;
    }

    inline TString pop_string_strict() {
        require(1);
        TString ret(to_string_strict(-1));
        pop();
        return ret;
    }

    inline TString pop_value() {
        require(1);
        if (is_bool(-1)) {
            return pop_bool() ? "true" : "false";
        }
        return pop_string_strict();
    }

    inline void push_string(const char* st) {
        lua_pushstring(State_, st ? st : "");
    }

    inline void push_string(TStringBuf st) {
        lua_pushlstring(State_, st.data(), st.size());
    }

    inline bool is_number(int index) {
        return lua_isnumber(State_, index);
    }

    inline void is_number_strict(int index) {
        if (!is_number(index)) {
            ythrow TError() << "internal lua error (not a number)";
        }
    }

    template <typename T>
    inline T to_number(int index) {
        return static_cast<T>(lua_tonumber(State_, index));
    }

    template <typename T>
    inline T to_number(int index, T defaultValue) {
        return is_number(index) ? to_number<T>(index) : defaultValue;
    }

    template <typename T>
    inline T to_number_strict(int index) {
        is_number_strict(index);
        return to_number<T>(index);
    }

    template <typename T>
    inline T pop_number() {
        const T ret = to_number<T>(-1);
        pop();
        return ret;
    }

    template <typename T>
    inline T pop_number(T defaultValue) {
        const T ret = to_number<T>(-1, defaultValue);
        pop();
        return ret;
    }

    template <typename T>
    inline T pop_number_strict() {
        require(1);
        const T ret = to_number_strict<T>(-1);
        pop();
        return ret;
    }

    template <typename T>
    inline void push_number(T val) {
        lua_pushnumber(State_, static_cast<lua_Number>(val));
    }

    inline bool is_bool(int index) {
        return lua_isboolean(State_, index);
    }

    inline void is_bool_strict(int index) {
        if (!is_bool(index)) {
            ythrow TError() << "internal lua error (not a boolean)";
        }
    }

    inline bool to_bool(int index) {
        return lua_toboolean(State_, index);
    }

    inline bool to_bool(int index, bool defaultValue) {
        return is_bool(index) ? to_bool(index) : defaultValue;
    }

    inline bool to_bool_strict(int index) {
        is_bool_strict(index);
        return to_bool(index);
    }

    inline bool pop_bool() {
        const bool ret = to_bool(-1);
        pop();
        return ret;
    }

    inline bool pop_bool(bool defaultValue) {
        const bool ret = to_bool(-1, defaultValue);
        pop();
        return ret;
    }

    inline bool pop_bool_strict() {
        require(1);
        const bool ret = to_bool_strict(-1);
        pop();
        return ret;
    }

    inline void push_bool(bool val) {
        lua_pushboolean(State_, val);
    }

    inline bool is_nil(int index) {
        return lua_isnil(State_, index);
    }

    inline void is_nil_strict(int index) {
        if (!is_nil(index)) {
            ythrow TError() << "internal lua error (not a nil)";
        }
    }

    inline bool pop_nil() {
        const bool ret = is_nil(-1);
        pop();
        return ret;
    }

    inline void pop_nil_strict() {
        require(1);
        is_nil_strict(-1);
        pop();
    }

    inline void push_nil() {
        lua_pushnil(State_);
    }

    inline bool is_void(int index) {
        return lua_islightuserdata(State_, index);
    }

    inline void is_void_strict(int index) {
        if (!is_void(index)) {
            ythrow TError() << "internal lua error (not a void*)";
        }
    }

    inline void* to_void(int index) {
        return lua_touserdata(State_, index);
    }

    inline void* to_void(int index, void* defaultValue) {
        return is_void(index) ? to_void(index) : defaultValue;
    }

    inline void* to_void_strict(int index) {
        is_void_strict(index);
        return to_void(index);
    }

    inline void* pop_void() {
        void* ret = to_void(-1);
        pop();
        return ret;
    }

    inline void* pop_void(void* defaultValue) {
        void* ret = to_void(-1, defaultValue);
        pop();
        return ret;
    }

    inline void* pop_void_strict() {
        require(1);
        void* ret = to_void_strict(-1);
        pop();
        return ret;
    }

    inline void push_void(void* ptr) {
        lua_pushlightuserdata(State_, ptr);
    }

    template <typename T>
    inline bool is_userdata(int index) {
        return to_userdata<T>(index) != NULL;
    }

    template <typename T>
    inline void is_userdata_strict(int index) {
        to_userdata_strict<T>(index);
    }

    template <typename T>
    inline T* to_userdata(int index) {
        return static_cast<T*>(luaL_testudata(State_, index, T::LUA_METATABLE_NAME));
    }

    template <typename T>
    inline T* to_userdata_strict(int index) {
        T* ret = to_userdata<T>(index);
        if (ret == nullptr) {
            ythrow TError() << "internal error (not a userdata '" << T::LUA_METATABLE_NAME << "')";
        }
        return ret;
    }

    template <typename T>
    inline T pop_userdata_strict() {
        require(1);
        const T ret(*to_userdata_strict<T>(-1));
        pop();
        return ret;
    }

    template <typename T>
    inline T* push_userdata(const T& x) {
        // copy constructor
        return new (new_userdata<T>()) T(x);
    }

    template <typename T, typename... R>
    inline T* push_userdata(const R&... r) {
        return new (new_userdata<T>()) T(r...);
    }

    inline void push_global(const char* name) {
        lua_getglobal(State_, name);
    }

    inline void set_global(const char* name, const char* value) {
        lua_pushstring(State_, value);
        set_global(name);
    }

    inline void set_global(const char* name, const double value) {
        lua_pushnumber(State_, value);
        set_global(name);
    }

    inline void set_global(const char* name) {
        lua_setglobal(State_, name);
    }

    inline void register_function(const char* name, lua_CFunction func) {
        lua_register(State_, name, func);
    }

    inline bool is_table(int index) {
        return lua_istable(State_, index);
    }

    inline void is_table_strict(int index) {
        if (!is_table(index)) {
            ythrow TError() << "internal lua error (not a table)";
        }
    }

    inline void create_table(int narr = 0, int nrec = 0) {
        lua_createtable(State_, narr, nrec);
    }

    inline void set_table(int index) {
        lua_settable(State_, index);
    }

    inline void get_field(int index, const char* key) {
        lua_getfield(State_, index, key);
    }

    inline void set_field(int index, const char* key) {
        lua_setfield(State_, index, key);
    }

    inline void rawseti(int index, int arr_index) {
        lua_rawseti(State_, index, arr_index);
    }

    inline int check_stack(int extra) {
        return lua_checkstack(State_, extra);
    }

    inline void ensure_stack(int extra) {
        if (!check_stack(extra)) {
            ythrow TError() << "cannot allocate more lua stack space";
        };
    }

    inline void require(int n) {
        if (on_stack() < n) {
            ythrow TError() << "lua requirement failed";
        }
    }

    inline void call(int args, int rets) {
        if (lua_pcall(State_, args, rets, 0)) {
            error();
        }
    }

    void call(int args, int rets, TDuration time_limit, int count = 1000);
    void call(int args, int rets, int limit);

    inline void remove(int index) {
        lua_remove(State_, index);
    }

    inline int next(int index) {
        return lua_next(State_, index);
    }

    inline void pop(int n = 1) {
        lua_pop(State_, Min(n, on_stack()));
    }

    inline void push_value(int index) {
        lua_pushvalue(State_, index);
    }

    inline int on_stack() {
        return lua_gettop(State_);
    }

    inline void gc() {
        lua_gc(State_, LUA_GCCOLLECT, 0);
    }

    inline TLuaStateHolder new_thread() {
        return lua_newthread(State_);
    }

    inline bool is_thread(int index) {
        return lua_isthread(State_, index);
    }

    inline void is_thread_strict(int index) {
        if (!is_thread(index)) {
            ythrow TError() << "internal lua error (not a thread)";
        }
    }

    inline TLuaStateHolder to_thread(int index) {
        return lua_tothread(State_, index);
    }

    inline TLuaStateHolder to_thread_strict(int index) {
        is_thread_strict(index);
        return to_thread(index);
    }

    void Load(IInputStream* in, TZtStringBuf name);
    void Dump(IOutputStream* out);
    void DumpStack(IOutputStream* out);

private:
    template <typename T>
    inline void set_metatable() {
        if (luaL_newmetatable(State_, T::LUA_METATABLE_NAME)) {
            // metatable isn't registered yet
            push_string("__index");
            push_value(-2); // pushes the metatable
            set_table(-3);  // metatable.__index = metatable
            luaL_setfuncs(State_, T::LUA_FUNCTIONS, 0);
        }
        lua_setmetatable(State_, -2);
    }

    template <typename T>
    inline void* new_userdata() {
        void* p = lua_newuserdata(State_, sizeof(T));
        set_metatable<T>();
        return p;
    }

private:
    static void* Alloc(void* ud, void* ptr, size_t osize, size_t nsize);
    static void* AllocLimit(void* ud, void* ptr, size_t osize, size_t nsize);

private:
    size_t AllocFree = 0;
    THolder<lua_State, TDeleteState> MyState_;
    lua_State* State_ = nullptr;
};

namespace NLua {
    template <int func(TLuaStateHolder&)>
    int FunctionHandler(lua_State* L) {
        try {
            TLuaStateHolder state(L);
            return func(state);
        } catch (const yexception& e) {
            lua_pushstring(L, e.what());
        }
        return lua_error(L);
    }

    template <class T, int (T::*Method)(TLuaStateHolder&)>
    int MethodHandler(lua_State* L) {
        T* x = static_cast<T*>(luaL_checkudata(L, 1, T::LUA_METATABLE_NAME));
        try {
            TLuaStateHolder state(L);
            return (x->*Method)(state);
        } catch (const yexception& e) {
            lua_pushstring(L, e.what());
        }
        return lua_error(L);
    }

    template <class T, int (T::*Method)(TLuaStateHolder&) const>
    int MethodConstHandler(lua_State* L) {
        const T* x = static_cast<const T*>(luaL_checkudata(L, 1, T::LUA_METATABLE_NAME));
        try {
            TLuaStateHolder state(L);
            return (x->*Method)(state);
        } catch (const yexception& e) {
            lua_pushstring(L, e.what());
        }
        return lua_error(L);
    }

    template <class T>
    int Destructor(lua_State* L) {
        T* x = static_cast<T*>(luaL_checkudata(L, 1, T::LUA_METATABLE_NAME));
        try {
            x->~T();
            return 0;
        } catch (const yexception& e) {
            lua_pushstring(L, e.what());
        }
        return lua_error(L);
    }

    TBuffer& Compile(TStringBuf script, TBuffer& buffer);

    struct TStackDumper {
        TStackDumper(TLuaStateHolder& state)
            : State(state)
        {
        }

        TLuaStateHolder& State;
    };

    struct TMarkedStackDumper: public TStackDumper {
        TMarkedStackDumper(TLuaStateHolder& state, TStringBuf mark)
            : TStackDumper(state)
            , Mark(mark)
        {
        }

        TStringBuf Mark;
    };

    inline TMarkedStackDumper DumpStack(TLuaStateHolder& state, TStringBuf mark) {
        return TMarkedStackDumper(state, mark);
    }

    inline TStackDumper DumpStack(TLuaStateHolder& state) {
        return TStackDumper(state);
    }

}