aboutsummaryrefslogtreecommitdiff
path: root/vendor/lua-5.4.8
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/lua-5.4.8')
-rw-r--r--vendor/lua-5.4.8/Makefile106
-rw-r--r--vendor/lua-5.4.8/src/Makefile225
-rw-r--r--vendor/lua-5.4.8/src/lapi.c1463
-rw-r--r--vendor/lua-5.4.8/src/lapi.h52
-rw-r--r--vendor/lua-5.4.8/src/lauxlib.c1126
-rw-r--r--vendor/lua-5.4.8/src/lauxlib.h301
-rw-r--r--vendor/lua-5.4.8/src/lbaselib.c549
-rw-r--r--vendor/lua-5.4.8/src/lcode.c1875
-rw-r--r--vendor/lua-5.4.8/src/lcode.h101
-rw-r--r--vendor/lua-5.4.8/src/lcorolib.c210
-rw-r--r--vendor/lua-5.4.8/src/lctype.c64
-rw-r--r--vendor/lua-5.4.8/src/lctype.h101
-rw-r--r--vendor/lua-5.4.8/src/ldblib.c483
-rw-r--r--vendor/lua-5.4.8/src/ldebug.c971
-rw-r--r--vendor/lua-5.4.8/src/ldebug.h64
-rw-r--r--vendor/lua-5.4.8/src/ldo.c1035
-rw-r--r--vendor/lua-5.4.8/src/ldo.h88
-rw-r--r--vendor/lua-5.4.8/src/ldump.c230
-rw-r--r--vendor/lua-5.4.8/src/lfunc.c294
-rw-r--r--vendor/lua-5.4.8/src/lfunc.h64
-rw-r--r--vendor/lua-5.4.8/src/lgc.c1743
-rw-r--r--vendor/lua-5.4.8/src/lgc.h202
-rw-r--r--vendor/lua-5.4.8/src/linit.c65
-rw-r--r--vendor/lua-5.4.8/src/liolib.c841
-rw-r--r--vendor/lua-5.4.8/src/ljumptab.h112
-rw-r--r--vendor/lua-5.4.8/src/llex.c581
-rw-r--r--vendor/lua-5.4.8/src/llex.h91
-rw-r--r--vendor/lua-5.4.8/src/llimits.h380
-rw-r--r--vendor/lua-5.4.8/src/lmathlib.c781
-rw-r--r--vendor/lua-5.4.8/src/lmem.c215
-rw-r--r--vendor/lua-5.4.8/src/lmem.h93
-rw-r--r--vendor/lua-5.4.8/src/loadlib.c758
-rw-r--r--vendor/lua-5.4.8/src/lobject.c602
-rw-r--r--vendor/lua-5.4.8/src/lobject.h813
-rw-r--r--vendor/lua-5.4.8/src/lopcodes.c104
-rw-r--r--vendor/lua-5.4.8/src/lopcodes.h405
-rw-r--r--vendor/lua-5.4.8/src/lopnames.h103
-rw-r--r--vendor/lua-5.4.8/src/loslib.c430
-rw-r--r--vendor/lua-5.4.8/src/lparser.c1966
-rw-r--r--vendor/lua-5.4.8/src/lparser.h171
-rw-r--r--vendor/lua-5.4.8/src/lprefix.h45
-rw-r--r--vendor/lua-5.4.8/src/lstate.c448
-rw-r--r--vendor/lua-5.4.8/src/lstate.h408
-rw-r--r--vendor/lua-5.4.8/src/lstring.c274
-rw-r--r--vendor/lua-5.4.8/src/lstring.h57
-rw-r--r--vendor/lua-5.4.8/src/lstrlib.c1874
-rw-r--r--vendor/lua-5.4.8/src/ltable.c995
-rw-r--r--vendor/lua-5.4.8/src/ltable.h63
-rw-r--r--vendor/lua-5.4.8/src/ltablib.c430
-rw-r--r--vendor/lua-5.4.8/src/ltm.c271
-rw-r--r--vendor/lua-5.4.8/src/ltm.h103
-rwxr-xr-xvendor/lua-5.4.8/src/luabin0 -> 319624 bytes
-rw-r--r--vendor/lua-5.4.8/src/lua.c687
-rw-r--r--vendor/lua-5.4.8/src/lua.h523
-rw-r--r--vendor/lua-5.4.8/src/lua.hpp9
-rwxr-xr-xvendor/lua-5.4.8/src/luacbin0 -> 230552 bytes
-rw-r--r--vendor/lua-5.4.8/src/luac.c723
-rw-r--r--vendor/lua-5.4.8/src/luaconf.h802
-rw-r--r--vendor/lua-5.4.8/src/lualib.h52
-rw-r--r--vendor/lua-5.4.8/src/lundump.c335
-rw-r--r--vendor/lua-5.4.8/src/lundump.h35
-rw-r--r--vendor/lua-5.4.8/src/lutf8lib.c291
-rw-r--r--vendor/lua-5.4.8/src/lvm.c1902
-rw-r--r--vendor/lua-5.4.8/src/lvm.h141
-rw-r--r--vendor/lua-5.4.8/src/lzio.c68
-rw-r--r--vendor/lua-5.4.8/src/lzio.h66
66 files changed, 30460 insertions, 0 deletions
diff --git a/vendor/lua-5.4.8/Makefile b/vendor/lua-5.4.8/Makefile
new file mode 100644
index 0000000..6e21588
--- /dev/null
+++ b/vendor/lua-5.4.8/Makefile
@@ -0,0 +1,106 @@
1# Makefile for installing Lua
2# See doc/readme.html for installation and customization instructions.
3
4# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================
5
6# Your platform. See PLATS for possible values.
7PLAT= guess
8
9# Where to install. The installation starts in the src and doc directories,
10# so take care if INSTALL_TOP is not an absolute path. See the local target.
11# You may want to make INSTALL_LMOD and INSTALL_CMOD consistent with
12# LUA_ROOT, LUA_LDIR, and LUA_CDIR in luaconf.h.
13INSTALL_TOP= /usr/local
14INSTALL_BIN= $(INSTALL_TOP)/bin
15INSTALL_INC= $(INSTALL_TOP)/include
16INSTALL_LIB= $(INSTALL_TOP)/lib
17INSTALL_MAN= $(INSTALL_TOP)/man/man1
18INSTALL_LMOD= $(INSTALL_TOP)/share/lua/$V
19INSTALL_CMOD= $(INSTALL_TOP)/lib/lua/$V
20
21# How to install. If your install program does not support "-p", then
22# you may have to run ranlib on the installed liblua.a.
23INSTALL= install -p
24INSTALL_EXEC= $(INSTALL) -m 0755
25INSTALL_DATA= $(INSTALL) -m 0644
26#
27# If you don't have "install" you can use "cp" instead.
28# INSTALL= cp -p
29# INSTALL_EXEC= $(INSTALL)
30# INSTALL_DATA= $(INSTALL)
31
32# Other utilities.
33MKDIR= mkdir -p
34RM= rm -f
35
36# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
37
38# Convenience platforms targets.
39PLATS= guess aix bsd c89 freebsd generic ios linux linux-readline macosx mingw posix solaris
40
41# What to install.
42TO_BIN= lua luac
43TO_INC= lua.h luaconf.h lualib.h lauxlib.h lua.hpp
44TO_LIB= liblua.a
45TO_MAN= lua.1 luac.1
46
47# Lua version and release.
48V= 5.4
49R= $V.8
50
51# Targets start here.
52all: $(PLAT)
53
54$(PLATS) help test clean:
55 @cd src && $(MAKE) $@
56
57install: dummy
58 cd src && $(MKDIR) $(INSTALL_BIN) $(INSTALL_INC) $(INSTALL_LIB) $(INSTALL_MAN) $(INSTALL_LMOD) $(INSTALL_CMOD)
59 cd src && $(INSTALL_EXEC) $(TO_BIN) $(INSTALL_BIN)
60 cd src && $(INSTALL_DATA) $(TO_INC) $(INSTALL_INC)
61 cd src && $(INSTALL_DATA) $(TO_LIB) $(INSTALL_LIB)
62 cd doc && $(INSTALL_DATA) $(TO_MAN) $(INSTALL_MAN)
63
64uninstall:
65 cd src && cd $(INSTALL_BIN) && $(RM) $(TO_BIN)
66 cd src && cd $(INSTALL_INC) && $(RM) $(TO_INC)
67 cd src && cd $(INSTALL_LIB) && $(RM) $(TO_LIB)
68 cd doc && cd $(INSTALL_MAN) && $(RM) $(TO_MAN)
69
70local:
71 $(MAKE) install INSTALL_TOP=../install
72
73# make may get confused with install/ if it does not support .PHONY.
74dummy:
75
76# Echo config parameters.
77echo:
78 @cd src && $(MAKE) -s echo
79 @echo "PLAT= $(PLAT)"
80 @echo "V= $V"
81 @echo "R= $R"
82 @echo "TO_BIN= $(TO_BIN)"
83 @echo "TO_INC= $(TO_INC)"
84 @echo "TO_LIB= $(TO_LIB)"
85 @echo "TO_MAN= $(TO_MAN)"
86 @echo "INSTALL_TOP= $(INSTALL_TOP)"
87 @echo "INSTALL_BIN= $(INSTALL_BIN)"
88 @echo "INSTALL_INC= $(INSTALL_INC)"
89 @echo "INSTALL_LIB= $(INSTALL_LIB)"
90 @echo "INSTALL_MAN= $(INSTALL_MAN)"
91 @echo "INSTALL_LMOD= $(INSTALL_LMOD)"
92 @echo "INSTALL_CMOD= $(INSTALL_CMOD)"
93 @echo "INSTALL_EXEC= $(INSTALL_EXEC)"
94 @echo "INSTALL_DATA= $(INSTALL_DATA)"
95
96# Echo pkg-config data.
97pc:
98 @echo "version=$R"
99 @echo "prefix=$(INSTALL_TOP)"
100 @echo "libdir=$(INSTALL_LIB)"
101 @echo "includedir=$(INSTALL_INC)"
102
103# Targets that do not create files (not all makes understand .PHONY).
104.PHONY: all $(PLATS) help test clean install uninstall local dummy echo pc
105
106# (end of Makefile)
diff --git a/vendor/lua-5.4.8/src/Makefile b/vendor/lua-5.4.8/src/Makefile
new file mode 100644
index 0000000..b771196
--- /dev/null
+++ b/vendor/lua-5.4.8/src/Makefile
@@ -0,0 +1,225 @@
1# Makefile for building Lua
2# See ../doc/readme.html for installation and customization instructions.
3
4# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================
5
6# Your platform. See PLATS for possible values.
7PLAT= guess
8
9CC= gcc -std=gnu99
10CFLAGS= -O2 -Wall -Wextra -DLUA_COMPAT_5_3 $(SYSCFLAGS) $(MYCFLAGS)
11LDFLAGS= $(SYSLDFLAGS) $(MYLDFLAGS)
12LIBS= -lm $(SYSLIBS) $(MYLIBS)
13
14AR= ar rcu
15RANLIB= ranlib
16RM= rm -f
17UNAME= uname
18
19SYSCFLAGS=
20SYSLDFLAGS=
21SYSLIBS=
22
23MYCFLAGS=
24MYLDFLAGS=
25MYLIBS=
26MYOBJS=
27
28# Special flags for compiler modules; -Os reduces code size.
29CMCFLAGS=
30
31# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
32
33PLATS= guess aix bsd c89 freebsd generic ios linux linux-readline macosx mingw posix solaris
34
35LUA_A= liblua.a
36CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o
37LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o
38BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS)
39
40LUA_T= lua
41LUA_O= lua.o
42
43LUAC_T= luac
44LUAC_O= luac.o
45
46ALL_O= $(BASE_O) $(LUA_O) $(LUAC_O)
47ALL_T= $(LUA_A) $(LUA_T) $(LUAC_T)
48ALL_A= $(LUA_A)
49
50# Targets start here.
51default: $(PLAT)
52
53all: $(ALL_T)
54
55o: $(ALL_O)
56
57a: $(ALL_A)
58
59$(LUA_A): $(BASE_O)
60 $(AR) $@ $(BASE_O)
61 $(RANLIB) $@
62
63$(LUA_T): $(LUA_O) $(LUA_A)
64 $(CC) -o $@ $(LDFLAGS) $(LUA_O) $(LUA_A) $(LIBS)
65
66$(LUAC_T): $(LUAC_O) $(LUA_A)
67 $(CC) -o $@ $(LDFLAGS) $(LUAC_O) $(LUA_A) $(LIBS)
68
69test:
70 ./$(LUA_T) -v
71
72clean:
73 $(RM) $(ALL_T) $(ALL_O)
74
75depend:
76 @$(CC) $(CFLAGS) -MM l*.c
77
78echo:
79 @echo "PLAT= $(PLAT)"
80 @echo "CC= $(CC)"
81 @echo "CFLAGS= $(CFLAGS)"
82 @echo "LDFLAGS= $(LDFLAGS)"
83 @echo "LIBS= $(LIBS)"
84 @echo "AR= $(AR)"
85 @echo "RANLIB= $(RANLIB)"
86 @echo "RM= $(RM)"
87 @echo "UNAME= $(UNAME)"
88
89# Convenience targets for popular platforms.
90ALL= all
91
92help:
93 @echo "Do 'make PLATFORM' where PLATFORM is one of these:"
94 @echo " $(PLATS)"
95 @echo "See doc/readme.html for complete instructions."
96
97guess:
98 @echo Guessing `$(UNAME)`
99 @$(MAKE) `$(UNAME)`
100
101AIX aix:
102 $(MAKE) $(ALL) CC="xlc" CFLAGS="-O2 -DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-ldl" SYSLDFLAGS="-brtl -bexpall"
103
104bsd:
105 $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-Wl,-E"
106
107c89:
108 $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_C89" CC="gcc -std=c89"
109 @echo ''
110 @echo '*** C89 does not guarantee 64-bit integers for Lua.'
111 @echo '*** Make sure to compile all external Lua libraries'
112 @echo '*** with LUA_USE_C89 to ensure consistency'
113 @echo ''
114
115FreeBSD NetBSD OpenBSD freebsd:
116 $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_LINUX -DLUA_USE_READLINE -I/usr/include/edit" SYSLIBS="-Wl,-E -ledit" CC="cc"
117
118generic: $(ALL)
119
120ios:
121 $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_IOS"
122
123Linux linux: linux-noreadline
124
125linux-noreadline:
126 $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_LINUX" SYSLIBS="-Wl,-E -ldl"
127
128linux-readline:
129 $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_LINUX -DLUA_USE_READLINE" SYSLIBS="-Wl,-E -ldl -lreadline"
130
131Darwin macos macosx:
132 $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_MACOSX -DLUA_USE_READLINE" SYSLIBS="-lreadline"
133
134mingw:
135 $(MAKE) "LUA_A=lua54.dll" "LUA_T=lua.exe" \
136 "AR=$(CC) -shared -o" "RANLIB=strip --strip-unneeded" \
137 "SYSCFLAGS=-DLUA_BUILD_AS_DLL" "SYSLIBS=" "SYSLDFLAGS=-s" lua.exe
138 $(MAKE) "LUAC_T=luac.exe" luac.exe
139
140posix:
141 $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX"
142
143SunOS solaris:
144 $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN -D_REENTRANT" SYSLIBS="-ldl"
145
146# Targets that do not create files (not all makes understand .PHONY).
147.PHONY: all $(PLATS) help test clean default o a depend echo
148
149# Compiler modules may use special flags.
150llex.o:
151 $(CC) $(CFLAGS) $(CMCFLAGS) -c llex.c
152
153lparser.o:
154 $(CC) $(CFLAGS) $(CMCFLAGS) -c lparser.c
155
156lcode.o:
157 $(CC) $(CFLAGS) $(CMCFLAGS) -c lcode.c
158
159# DO NOT DELETE
160
161lapi.o: lapi.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
162 lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h \
163 ltable.h lundump.h lvm.h
164lauxlib.o: lauxlib.c lprefix.h lua.h luaconf.h lauxlib.h
165lbaselib.o: lbaselib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
166lcode.o: lcode.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \
167 llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \
168 ldo.h lgc.h lstring.h ltable.h lvm.h
169lcorolib.o: lcorolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
170lctype.o: lctype.c lprefix.h lctype.h lua.h luaconf.h llimits.h
171ldblib.o: ldblib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
172ldebug.o: ldebug.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
173 lobject.h ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h \
174 ldebug.h ldo.h lfunc.h lstring.h lgc.h ltable.h lvm.h
175ldo.o: ldo.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
176 lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h \
177 lparser.h lstring.h ltable.h lundump.h lvm.h
178ldump.o: ldump.c lprefix.h lua.h luaconf.h lobject.h llimits.h lstate.h \
179 ltm.h lzio.h lmem.h lundump.h
180lfunc.o: lfunc.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
181 llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h
182lgc.o: lgc.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
183 llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h
184linit.o: linit.c lprefix.h lua.h luaconf.h lualib.h lauxlib.h
185liolib.o: liolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
186llex.o: llex.c lprefix.h lua.h luaconf.h lctype.h llimits.h ldebug.h \
187 lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lgc.h llex.h lparser.h \
188 lstring.h ltable.h
189lmathlib.o: lmathlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
190lmem.o: lmem.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
191 llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h
192loadlib.o: loadlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
193lobject.o: lobject.c lprefix.h lua.h luaconf.h lctype.h llimits.h \
194 ldebug.h lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h \
195 lvm.h
196lopcodes.o: lopcodes.c lprefix.h lopcodes.h llimits.h lua.h luaconf.h
197loslib.o: loslib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
198lparser.o: lparser.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \
199 llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \
200 ldo.h lfunc.h lstring.h lgc.h ltable.h
201lstate.o: lstate.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
202 lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h \
203 lstring.h ltable.h
204lstring.o: lstring.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \
205 lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h
206lstrlib.o: lstrlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
207ltable.o: ltable.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
208 llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
209ltablib.o: ltablib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
210ltm.o: ltm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
211 llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
212lua.o: lua.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
213luac.o: luac.c lprefix.h lua.h luaconf.h lauxlib.h ldebug.h lstate.h \
214 lobject.h llimits.h ltm.h lzio.h lmem.h lopcodes.h lopnames.h lundump.h
215lundump.o: lundump.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \
216 lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h \
217 lundump.h
218lutf8lib.o: lutf8lib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
219lvm.o: lvm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
220 llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h \
221 ltable.h lvm.h ljumptab.h
222lzio.o: lzio.c lprefix.h lua.h luaconf.h llimits.h lmem.h lstate.h \
223 lobject.h ltm.h lzio.h
224
225# (end of Makefile)
diff --git a/vendor/lua-5.4.8/src/lapi.c b/vendor/lua-5.4.8/src/lapi.c
new file mode 100644
index 0000000..04e09cf
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lapi.c
@@ -0,0 +1,1463 @@
1/*
2** $Id: lapi.c $
3** Lua API
4** See Copyright Notice in lua.h
5*/
6
7#define lapi_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <limits.h>
14#include <stdarg.h>
15#include <string.h>
16
17#include "lua.h"
18
19#include "lapi.h"
20#include "ldebug.h"
21#include "ldo.h"
22#include "lfunc.h"
23#include "lgc.h"
24#include "lmem.h"
25#include "lobject.h"
26#include "lstate.h"
27#include "lstring.h"
28#include "ltable.h"
29#include "ltm.h"
30#include "lundump.h"
31#include "lvm.h"
32
33
34
35const char lua_ident[] =
36 "$LuaVersion: " LUA_COPYRIGHT " $"
37 "$LuaAuthors: " LUA_AUTHORS " $";
38
39
40
41/*
42** Test for a valid index (one that is not the 'nilvalue').
43** '!ttisnil(o)' implies 'o != &G(L)->nilvalue', so it is not needed.
44** However, it covers the most common cases in a faster way.
45*/
46#define isvalid(L, o) (!ttisnil(o) || o != &G(L)->nilvalue)
47
48
49/* test for pseudo index */
50#define ispseudo(i) ((i) <= LUA_REGISTRYINDEX)
51
52/* test for upvalue */
53#define isupvalue(i) ((i) < LUA_REGISTRYINDEX)
54
55
56/*
57** Convert an acceptable index to a pointer to its respective value.
58** Non-valid indices return the special nil value 'G(L)->nilvalue'.
59*/
60static TValue *index2value (lua_State *L, int idx) {
61 CallInfo *ci = L->ci;
62 if (idx > 0) {
63 StkId o = ci->func.p + idx;
64 api_check(L, idx <= ci->top.p - (ci->func.p + 1), "unacceptable index");
65 if (o >= L->top.p) return &G(L)->nilvalue;
66 else return s2v(o);
67 }
68 else if (!ispseudo(idx)) { /* negative index */
69 api_check(L, idx != 0 && -idx <= L->top.p - (ci->func.p + 1),
70 "invalid index");
71 return s2v(L->top.p + idx);
72 }
73 else if (idx == LUA_REGISTRYINDEX)
74 return &G(L)->l_registry;
75 else { /* upvalues */
76 idx = LUA_REGISTRYINDEX - idx;
77 api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large");
78 if (ttisCclosure(s2v(ci->func.p))) { /* C closure? */
79 CClosure *func = clCvalue(s2v(ci->func.p));
80 return (idx <= func->nupvalues) ? &func->upvalue[idx-1]
81 : &G(L)->nilvalue;
82 }
83 else { /* light C function or Lua function (through a hook)?) */
84 api_check(L, ttislcf(s2v(ci->func.p)), "caller not a C function");
85 return &G(L)->nilvalue; /* no upvalues */
86 }
87 }
88}
89
90
91
92/*
93** Convert a valid actual index (not a pseudo-index) to its address.
94*/
95l_sinline StkId index2stack (lua_State *L, int idx) {
96 CallInfo *ci = L->ci;
97 if (idx > 0) {
98 StkId o = ci->func.p + idx;
99 api_check(L, o < L->top.p, "invalid index");
100 return o;
101 }
102 else { /* non-positive index */
103 api_check(L, idx != 0 && -idx <= L->top.p - (ci->func.p + 1),
104 "invalid index");
105 api_check(L, !ispseudo(idx), "invalid index");
106 return L->top.p + idx;
107 }
108}
109
110
111LUA_API int lua_checkstack (lua_State *L, int n) {
112 int res;
113 CallInfo *ci;
114 lua_lock(L);
115 ci = L->ci;
116 api_check(L, n >= 0, "negative 'n'");
117 if (L->stack_last.p - L->top.p > n) /* stack large enough? */
118 res = 1; /* yes; check is OK */
119 else /* need to grow stack */
120 res = luaD_growstack(L, n, 0);
121 if (res && ci->top.p < L->top.p + n)
122 ci->top.p = L->top.p + n; /* adjust frame top */
123 lua_unlock(L);
124 return res;
125}
126
127
128LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
129 int i;
130 if (from == to) return;
131 lua_lock(to);
132 api_checknelems(from, n);
133 api_check(from, G(from) == G(to), "moving among independent states");
134 api_check(from, to->ci->top.p - to->top.p >= n, "stack overflow");
135 from->top.p -= n;
136 for (i = 0; i < n; i++) {
137 setobjs2s(to, to->top.p, from->top.p + i);
138 to->top.p++; /* stack already checked by previous 'api_check' */
139 }
140 lua_unlock(to);
141}
142
143
144LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {
145 lua_CFunction old;
146 lua_lock(L);
147 old = G(L)->panic;
148 G(L)->panic = panicf;
149 lua_unlock(L);
150 return old;
151}
152
153
154LUA_API lua_Number lua_version (lua_State *L) {
155 UNUSED(L);
156 return LUA_VERSION_NUM;
157}
158
159
160
161/*
162** basic stack manipulation
163*/
164
165
166/*
167** convert an acceptable stack index into an absolute index
168*/
169LUA_API int lua_absindex (lua_State *L, int idx) {
170 return (idx > 0 || ispseudo(idx))
171 ? idx
172 : cast_int(L->top.p - L->ci->func.p) + idx;
173}
174
175
176LUA_API int lua_gettop (lua_State *L) {
177 return cast_int(L->top.p - (L->ci->func.p + 1));
178}
179
180
181LUA_API void lua_settop (lua_State *L, int idx) {
182 CallInfo *ci;
183 StkId func, newtop;
184 ptrdiff_t diff; /* difference for new top */
185 lua_lock(L);
186 ci = L->ci;
187 func = ci->func.p;
188 if (idx >= 0) {
189 api_check(L, idx <= ci->top.p - (func + 1), "new top too large");
190 diff = ((func + 1) + idx) - L->top.p;
191 for (; diff > 0; diff--)
192 setnilvalue(s2v(L->top.p++)); /* clear new slots */
193 }
194 else {
195 api_check(L, -(idx+1) <= (L->top.p - (func + 1)), "invalid new top");
196 diff = idx + 1; /* will "subtract" index (as it is negative) */
197 }
198 api_check(L, L->tbclist.p < L->top.p, "previous pop of an unclosed slot");
199 newtop = L->top.p + diff;
200 if (diff < 0 && L->tbclist.p >= newtop) {
201 lua_assert(hastocloseCfunc(ci->nresults));
202 newtop = luaF_close(L, newtop, CLOSEKTOP, 0);
203 }
204 L->top.p = newtop; /* correct top only after closing any upvalue */
205 lua_unlock(L);
206}
207
208
209LUA_API void lua_closeslot (lua_State *L, int idx) {
210 StkId level;
211 lua_lock(L);
212 level = index2stack(L, idx);
213 api_check(L, hastocloseCfunc(L->ci->nresults) && L->tbclist.p == level,
214 "no variable to close at given level");
215 level = luaF_close(L, level, CLOSEKTOP, 0);
216 setnilvalue(s2v(level));
217 lua_unlock(L);
218}
219
220
221/*
222** Reverse the stack segment from 'from' to 'to'
223** (auxiliary to 'lua_rotate')
224** Note that we move(copy) only the value inside the stack.
225** (We do not move additional fields that may exist.)
226*/
227l_sinline void reverse (lua_State *L, StkId from, StkId to) {
228 for (; from < to; from++, to--) {
229 TValue temp;
230 setobj(L, &temp, s2v(from));
231 setobjs2s(L, from, to);
232 setobj2s(L, to, &temp);
233 }
234}
235
236
237/*
238** Let x = AB, where A is a prefix of length 'n'. Then,
239** rotate x n == BA. But BA == (A^r . B^r)^r.
240*/
241LUA_API void lua_rotate (lua_State *L, int idx, int n) {
242 StkId p, t, m;
243 lua_lock(L);
244 t = L->top.p - 1; /* end of stack segment being rotated */
245 p = index2stack(L, idx); /* start of segment */
246 api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'");
247 m = (n >= 0 ? t - n : p - n - 1); /* end of prefix */
248 reverse(L, p, m); /* reverse the prefix with length 'n' */
249 reverse(L, m + 1, t); /* reverse the suffix */
250 reverse(L, p, t); /* reverse the entire segment */
251 lua_unlock(L);
252}
253
254
255LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {
256 TValue *fr, *to;
257 lua_lock(L);
258 fr = index2value(L, fromidx);
259 to = index2value(L, toidx);
260 api_check(L, isvalid(L, to), "invalid index");
261 setobj(L, to, fr);
262 if (isupvalue(toidx)) /* function upvalue? */
263 luaC_barrier(L, clCvalue(s2v(L->ci->func.p)), fr);
264 /* LUA_REGISTRYINDEX does not need gc barrier
265 (collector revisits it before finishing collection) */
266 lua_unlock(L);
267}
268
269
270LUA_API void lua_pushvalue (lua_State *L, int idx) {
271 lua_lock(L);
272 setobj2s(L, L->top.p, index2value(L, idx));
273 api_incr_top(L);
274 lua_unlock(L);
275}
276
277
278
279/*
280** access functions (stack -> C)
281*/
282
283
284LUA_API int lua_type (lua_State *L, int idx) {
285 const TValue *o = index2value(L, idx);
286 return (isvalid(L, o) ? ttype(o) : LUA_TNONE);
287}
288
289
290LUA_API const char *lua_typename (lua_State *L, int t) {
291 UNUSED(L);
292 api_check(L, LUA_TNONE <= t && t < LUA_NUMTYPES, "invalid type");
293 return ttypename(t);
294}
295
296
297LUA_API int lua_iscfunction (lua_State *L, int idx) {
298 const TValue *o = index2value(L, idx);
299 return (ttislcf(o) || (ttisCclosure(o)));
300}
301
302
303LUA_API int lua_isinteger (lua_State *L, int idx) {
304 const TValue *o = index2value(L, idx);
305 return ttisinteger(o);
306}
307
308
309LUA_API int lua_isnumber (lua_State *L, int idx) {
310 lua_Number n;
311 const TValue *o = index2value(L, idx);
312 return tonumber(o, &n);
313}
314
315
316LUA_API int lua_isstring (lua_State *L, int idx) {
317 const TValue *o = index2value(L, idx);
318 return (ttisstring(o) || cvt2str(o));
319}
320
321
322LUA_API int lua_isuserdata (lua_State *L, int idx) {
323 const TValue *o = index2value(L, idx);
324 return (ttisfulluserdata(o) || ttislightuserdata(o));
325}
326
327
328LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
329 const TValue *o1 = index2value(L, index1);
330 const TValue *o2 = index2value(L, index2);
331 return (isvalid(L, o1) && isvalid(L, o2)) ? luaV_rawequalobj(o1, o2) : 0;
332}
333
334
335LUA_API void lua_arith (lua_State *L, int op) {
336 lua_lock(L);
337 if (op != LUA_OPUNM && op != LUA_OPBNOT)
338 api_checknelems(L, 2); /* all other operations expect two operands */
339 else { /* for unary operations, add fake 2nd operand */
340 api_checknelems(L, 1);
341 setobjs2s(L, L->top.p, L->top.p - 1);
342 api_incr_top(L);
343 }
344 /* first operand at top - 2, second at top - 1; result go to top - 2 */
345 luaO_arith(L, op, s2v(L->top.p - 2), s2v(L->top.p - 1), L->top.p - 2);
346 L->top.p--; /* remove second operand */
347 lua_unlock(L);
348}
349
350
351LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {
352 const TValue *o1;
353 const TValue *o2;
354 int i = 0;
355 lua_lock(L); /* may call tag method */
356 o1 = index2value(L, index1);
357 o2 = index2value(L, index2);
358 if (isvalid(L, o1) && isvalid(L, o2)) {
359 switch (op) {
360 case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break;
361 case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;
362 case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;
363 default: api_check(L, 0, "invalid option");
364 }
365 }
366 lua_unlock(L);
367 return i;
368}
369
370
371LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) {
372 size_t sz = luaO_str2num(s, s2v(L->top.p));
373 if (sz != 0)
374 api_incr_top(L);
375 return sz;
376}
377
378
379LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {
380 lua_Number n = 0;
381 const TValue *o = index2value(L, idx);
382 int isnum = tonumber(o, &n);
383 if (pisnum)
384 *pisnum = isnum;
385 return n;
386}
387
388
389LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {
390 lua_Integer res = 0;
391 const TValue *o = index2value(L, idx);
392 int isnum = tointeger(o, &res);
393 if (pisnum)
394 *pisnum = isnum;
395 return res;
396}
397
398
399LUA_API int lua_toboolean (lua_State *L, int idx) {
400 const TValue *o = index2value(L, idx);
401 return !l_isfalse(o);
402}
403
404
405LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
406 TValue *o;
407 lua_lock(L);
408 o = index2value(L, idx);
409 if (!ttisstring(o)) {
410 if (!cvt2str(o)) { /* not convertible? */
411 if (len != NULL) *len = 0;
412 lua_unlock(L);
413 return NULL;
414 }
415 luaO_tostring(L, o);
416 luaC_checkGC(L);
417 o = index2value(L, idx); /* previous call may reallocate the stack */
418 }
419 if (len != NULL)
420 *len = tsslen(tsvalue(o));
421 lua_unlock(L);
422 return getstr(tsvalue(o));
423}
424
425
426LUA_API lua_Unsigned lua_rawlen (lua_State *L, int idx) {
427 const TValue *o = index2value(L, idx);
428 switch (ttypetag(o)) {
429 case LUA_VSHRSTR: return tsvalue(o)->shrlen;
430 case LUA_VLNGSTR: return tsvalue(o)->u.lnglen;
431 case LUA_VUSERDATA: return uvalue(o)->len;
432 case LUA_VTABLE: return luaH_getn(hvalue(o));
433 default: return 0;
434 }
435}
436
437
438LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
439 const TValue *o = index2value(L, idx);
440 if (ttislcf(o)) return fvalue(o);
441 else if (ttisCclosure(o))
442 return clCvalue(o)->f;
443 else return NULL; /* not a C function */
444}
445
446
447l_sinline void *touserdata (const TValue *o) {
448 switch (ttype(o)) {
449 case LUA_TUSERDATA: return getudatamem(uvalue(o));
450 case LUA_TLIGHTUSERDATA: return pvalue(o);
451 default: return NULL;
452 }
453}
454
455
456LUA_API void *lua_touserdata (lua_State *L, int idx) {
457 const TValue *o = index2value(L, idx);
458 return touserdata(o);
459}
460
461
462LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
463 const TValue *o = index2value(L, idx);
464 return (!ttisthread(o)) ? NULL : thvalue(o);
465}
466
467
468/*
469** Returns a pointer to the internal representation of an object.
470** Note that ANSI C does not allow the conversion of a pointer to
471** function to a 'void*', so the conversion here goes through
472** a 'size_t'. (As the returned pointer is only informative, this
473** conversion should not be a problem.)
474*/
475LUA_API const void *lua_topointer (lua_State *L, int idx) {
476 const TValue *o = index2value(L, idx);
477 switch (ttypetag(o)) {
478 case LUA_VLCF: return cast_voidp(cast_sizet(fvalue(o)));
479 case LUA_VUSERDATA: case LUA_VLIGHTUSERDATA:
480 return touserdata(o);
481 default: {
482 if (iscollectable(o))
483 return gcvalue(o);
484 else
485 return NULL;
486 }
487 }
488}
489
490
491
492/*
493** push functions (C -> stack)
494*/
495
496
497LUA_API void lua_pushnil (lua_State *L) {
498 lua_lock(L);
499 setnilvalue(s2v(L->top.p));
500 api_incr_top(L);
501 lua_unlock(L);
502}
503
504
505LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
506 lua_lock(L);
507 setfltvalue(s2v(L->top.p), n);
508 api_incr_top(L);
509 lua_unlock(L);
510}
511
512
513LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
514 lua_lock(L);
515 setivalue(s2v(L->top.p), n);
516 api_incr_top(L);
517 lua_unlock(L);
518}
519
520
521/*
522** Pushes on the stack a string with given length. Avoid using 's' when
523** 'len' == 0 (as 's' can be NULL in that case), due to later use of
524** 'memcmp' and 'memcpy'.
525*/
526LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) {
527 TString *ts;
528 lua_lock(L);
529 ts = (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len);
530 setsvalue2s(L, L->top.p, ts);
531 api_incr_top(L);
532 luaC_checkGC(L);
533 lua_unlock(L);
534 return getstr(ts);
535}
536
537
538LUA_API const char *lua_pushstring (lua_State *L, const char *s) {
539 lua_lock(L);
540 if (s == NULL)
541 setnilvalue(s2v(L->top.p));
542 else {
543 TString *ts;
544 ts = luaS_new(L, s);
545 setsvalue2s(L, L->top.p, ts);
546 s = getstr(ts); /* internal copy's address */
547 }
548 api_incr_top(L);
549 luaC_checkGC(L);
550 lua_unlock(L);
551 return s;
552}
553
554
555LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
556 va_list argp) {
557 const char *ret;
558 lua_lock(L);
559 ret = luaO_pushvfstring(L, fmt, argp);
560 luaC_checkGC(L);
561 lua_unlock(L);
562 return ret;
563}
564
565
566LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {
567 const char *ret;
568 va_list argp;
569 lua_lock(L);
570 va_start(argp, fmt);
571 ret = luaO_pushvfstring(L, fmt, argp);
572 va_end(argp);
573 luaC_checkGC(L);
574 lua_unlock(L);
575 return ret;
576}
577
578
579LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
580 lua_lock(L);
581 if (n == 0) {
582 setfvalue(s2v(L->top.p), fn);
583 api_incr_top(L);
584 }
585 else {
586 CClosure *cl;
587 api_checknelems(L, n);
588 api_check(L, n <= MAXUPVAL, "upvalue index too large");
589 cl = luaF_newCclosure(L, n);
590 cl->f = fn;
591 L->top.p -= n;
592 while (n--) {
593 setobj2n(L, &cl->upvalue[n], s2v(L->top.p + n));
594 /* does not need barrier because closure is white */
595 lua_assert(iswhite(cl));
596 }
597 setclCvalue(L, s2v(L->top.p), cl);
598 api_incr_top(L);
599 luaC_checkGC(L);
600 }
601 lua_unlock(L);
602}
603
604
605LUA_API void lua_pushboolean (lua_State *L, int b) {
606 lua_lock(L);
607 if (b)
608 setbtvalue(s2v(L->top.p));
609 else
610 setbfvalue(s2v(L->top.p));
611 api_incr_top(L);
612 lua_unlock(L);
613}
614
615
616LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {
617 lua_lock(L);
618 setpvalue(s2v(L->top.p), p);
619 api_incr_top(L);
620 lua_unlock(L);
621}
622
623
624LUA_API int lua_pushthread (lua_State *L) {
625 lua_lock(L);
626 setthvalue(L, s2v(L->top.p), L);
627 api_incr_top(L);
628 lua_unlock(L);
629 return (G(L)->mainthread == L);
630}
631
632
633
634/*
635** get functions (Lua -> stack)
636*/
637
638
639l_sinline int auxgetstr (lua_State *L, const TValue *t, const char *k) {
640 const TValue *slot;
641 TString *str = luaS_new(L, k);
642 if (luaV_fastget(L, t, str, slot, luaH_getstr)) {
643 setobj2s(L, L->top.p, slot);
644 api_incr_top(L);
645 }
646 else {
647 setsvalue2s(L, L->top.p, str);
648 api_incr_top(L);
649 luaV_finishget(L, t, s2v(L->top.p - 1), L->top.p - 1, slot);
650 }
651 lua_unlock(L);
652 return ttype(s2v(L->top.p - 1));
653}
654
655
656/*
657** Get the global table in the registry. Since all predefined
658** indices in the registry were inserted right when the registry
659** was created and never removed, they must always be in the array
660** part of the registry.
661*/
662#define getGtable(L) \
663 (&hvalue(&G(L)->l_registry)->array[LUA_RIDX_GLOBALS - 1])
664
665
666LUA_API int lua_getglobal (lua_State *L, const char *name) {
667 const TValue *G;
668 lua_lock(L);
669 G = getGtable(L);
670 return auxgetstr(L, G, name);
671}
672
673
674LUA_API int lua_gettable (lua_State *L, int idx) {
675 const TValue *slot;
676 TValue *t;
677 lua_lock(L);
678 t = index2value(L, idx);
679 if (luaV_fastget(L, t, s2v(L->top.p - 1), slot, luaH_get)) {
680 setobj2s(L, L->top.p - 1, slot);
681 }
682 else
683 luaV_finishget(L, t, s2v(L->top.p - 1), L->top.p - 1, slot);
684 lua_unlock(L);
685 return ttype(s2v(L->top.p - 1));
686}
687
688
689LUA_API int lua_getfield (lua_State *L, int idx, const char *k) {
690 lua_lock(L);
691 return auxgetstr(L, index2value(L, idx), k);
692}
693
694
695LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {
696 TValue *t;
697 const TValue *slot;
698 lua_lock(L);
699 t = index2value(L, idx);
700 if (luaV_fastgeti(L, t, n, slot)) {
701 setobj2s(L, L->top.p, slot);
702 }
703 else {
704 TValue aux;
705 setivalue(&aux, n);
706 luaV_finishget(L, t, &aux, L->top.p, slot);
707 }
708 api_incr_top(L);
709 lua_unlock(L);
710 return ttype(s2v(L->top.p - 1));
711}
712
713
714l_sinline int finishrawget (lua_State *L, const TValue *val) {
715 if (isempty(val)) /* avoid copying empty items to the stack */
716 setnilvalue(s2v(L->top.p));
717 else
718 setobj2s(L, L->top.p, val);
719 api_incr_top(L);
720 lua_unlock(L);
721 return ttype(s2v(L->top.p - 1));
722}
723
724
725static Table *gettable (lua_State *L, int idx) {
726 TValue *t = index2value(L, idx);
727 api_check(L, ttistable(t), "table expected");
728 return hvalue(t);
729}
730
731
732LUA_API int lua_rawget (lua_State *L, int idx) {
733 Table *t;
734 const TValue *val;
735 lua_lock(L);
736 api_checknelems(L, 1);
737 t = gettable(L, idx);
738 val = luaH_get(t, s2v(L->top.p - 1));
739 L->top.p--; /* remove key */
740 return finishrawget(L, val);
741}
742
743
744LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {
745 Table *t;
746 lua_lock(L);
747 t = gettable(L, idx);
748 return finishrawget(L, luaH_getint(t, n));
749}
750
751
752LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {
753 Table *t;
754 TValue k;
755 lua_lock(L);
756 t = gettable(L, idx);
757 setpvalue(&k, cast_voidp(p));
758 return finishrawget(L, luaH_get(t, &k));
759}
760
761
762LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
763 Table *t;
764 lua_lock(L);
765 t = luaH_new(L);
766 sethvalue2s(L, L->top.p, t);
767 api_incr_top(L);
768 if (narray > 0 || nrec > 0)
769 luaH_resize(L, t, narray, nrec);
770 luaC_checkGC(L);
771 lua_unlock(L);
772}
773
774
775LUA_API int lua_getmetatable (lua_State *L, int objindex) {
776 const TValue *obj;
777 Table *mt;
778 int res = 0;
779 lua_lock(L);
780 obj = index2value(L, objindex);
781 switch (ttype(obj)) {
782 case LUA_TTABLE:
783 mt = hvalue(obj)->metatable;
784 break;
785 case LUA_TUSERDATA:
786 mt = uvalue(obj)->metatable;
787 break;
788 default:
789 mt = G(L)->mt[ttype(obj)];
790 break;
791 }
792 if (mt != NULL) {
793 sethvalue2s(L, L->top.p, mt);
794 api_incr_top(L);
795 res = 1;
796 }
797 lua_unlock(L);
798 return res;
799}
800
801
802LUA_API int lua_getiuservalue (lua_State *L, int idx, int n) {
803 TValue *o;
804 int t;
805 lua_lock(L);
806 o = index2value(L, idx);
807 api_check(L, ttisfulluserdata(o), "full userdata expected");
808 if (n <= 0 || n > uvalue(o)->nuvalue) {
809 setnilvalue(s2v(L->top.p));
810 t = LUA_TNONE;
811 }
812 else {
813 setobj2s(L, L->top.p, &uvalue(o)->uv[n - 1].uv);
814 t = ttype(s2v(L->top.p));
815 }
816 api_incr_top(L);
817 lua_unlock(L);
818 return t;
819}
820
821
822/*
823** set functions (stack -> Lua)
824*/
825
826/*
827** t[k] = value at the top of the stack (where 'k' is a string)
828*/
829static void auxsetstr (lua_State *L, const TValue *t, const char *k) {
830 const TValue *slot;
831 TString *str = luaS_new(L, k);
832 api_checknelems(L, 1);
833 if (luaV_fastget(L, t, str, slot, luaH_getstr)) {
834 luaV_finishfastset(L, t, slot, s2v(L->top.p - 1));
835 L->top.p--; /* pop value */
836 }
837 else {
838 setsvalue2s(L, L->top.p, str); /* push 'str' (to make it a TValue) */
839 api_incr_top(L);
840 luaV_finishset(L, t, s2v(L->top.p - 1), s2v(L->top.p - 2), slot);
841 L->top.p -= 2; /* pop value and key */
842 }
843 lua_unlock(L); /* lock done by caller */
844}
845
846
847LUA_API void lua_setglobal (lua_State *L, const char *name) {
848 const TValue *G;
849 lua_lock(L); /* unlock done in 'auxsetstr' */
850 G = getGtable(L);
851 auxsetstr(L, G, name);
852}
853
854
855LUA_API void lua_settable (lua_State *L, int idx) {
856 TValue *t;
857 const TValue *slot;
858 lua_lock(L);
859 api_checknelems(L, 2);
860 t = index2value(L, idx);
861 if (luaV_fastget(L, t, s2v(L->top.p - 2), slot, luaH_get)) {
862 luaV_finishfastset(L, t, slot, s2v(L->top.p - 1));
863 }
864 else
865 luaV_finishset(L, t, s2v(L->top.p - 2), s2v(L->top.p - 1), slot);
866 L->top.p -= 2; /* pop index and value */
867 lua_unlock(L);
868}
869
870
871LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
872 lua_lock(L); /* unlock done in 'auxsetstr' */
873 auxsetstr(L, index2value(L, idx), k);
874}
875
876
877LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {
878 TValue *t;
879 const TValue *slot;
880 lua_lock(L);
881 api_checknelems(L, 1);
882 t = index2value(L, idx);
883 if (luaV_fastgeti(L, t, n, slot)) {
884 luaV_finishfastset(L, t, slot, s2v(L->top.p - 1));
885 }
886 else {
887 TValue aux;
888 setivalue(&aux, n);
889 luaV_finishset(L, t, &aux, s2v(L->top.p - 1), slot);
890 }
891 L->top.p--; /* pop value */
892 lua_unlock(L);
893}
894
895
896static void aux_rawset (lua_State *L, int idx, TValue *key, int n) {
897 Table *t;
898 lua_lock(L);
899 api_checknelems(L, n);
900 t = gettable(L, idx);
901 luaH_set(L, t, key, s2v(L->top.p - 1));
902 invalidateTMcache(t);
903 luaC_barrierback(L, obj2gco(t), s2v(L->top.p - 1));
904 L->top.p -= n;
905 lua_unlock(L);
906}
907
908
909LUA_API void lua_rawset (lua_State *L, int idx) {
910 aux_rawset(L, idx, s2v(L->top.p - 2), 2);
911}
912
913
914LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
915 TValue k;
916 setpvalue(&k, cast_voidp(p));
917 aux_rawset(L, idx, &k, 1);
918}
919
920
921LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {
922 Table *t;
923 lua_lock(L);
924 api_checknelems(L, 1);
925 t = gettable(L, idx);
926 luaH_setint(L, t, n, s2v(L->top.p - 1));
927 luaC_barrierback(L, obj2gco(t), s2v(L->top.p - 1));
928 L->top.p--;
929 lua_unlock(L);
930}
931
932
933LUA_API int lua_setmetatable (lua_State *L, int objindex) {
934 TValue *obj;
935 Table *mt;
936 lua_lock(L);
937 api_checknelems(L, 1);
938 obj = index2value(L, objindex);
939 if (ttisnil(s2v(L->top.p - 1)))
940 mt = NULL;
941 else {
942 api_check(L, ttistable(s2v(L->top.p - 1)), "table expected");
943 mt = hvalue(s2v(L->top.p - 1));
944 }
945 switch (ttype(obj)) {
946 case LUA_TTABLE: {
947 hvalue(obj)->metatable = mt;
948 if (mt) {
949 luaC_objbarrier(L, gcvalue(obj), mt);
950 luaC_checkfinalizer(L, gcvalue(obj), mt);
951 }
952 break;
953 }
954 case LUA_TUSERDATA: {
955 uvalue(obj)->metatable = mt;
956 if (mt) {
957 luaC_objbarrier(L, uvalue(obj), mt);
958 luaC_checkfinalizer(L, gcvalue(obj), mt);
959 }
960 break;
961 }
962 default: {
963 G(L)->mt[ttype(obj)] = mt;
964 break;
965 }
966 }
967 L->top.p--;
968 lua_unlock(L);
969 return 1;
970}
971
972
973LUA_API int lua_setiuservalue (lua_State *L, int idx, int n) {
974 TValue *o;
975 int res;
976 lua_lock(L);
977 api_checknelems(L, 1);
978 o = index2value(L, idx);
979 api_check(L, ttisfulluserdata(o), "full userdata expected");
980 if (!(cast_uint(n) - 1u < cast_uint(uvalue(o)->nuvalue)))
981 res = 0; /* 'n' not in [1, uvalue(o)->nuvalue] */
982 else {
983 setobj(L, &uvalue(o)->uv[n - 1].uv, s2v(L->top.p - 1));
984 luaC_barrierback(L, gcvalue(o), s2v(L->top.p - 1));
985 res = 1;
986 }
987 L->top.p--;
988 lua_unlock(L);
989 return res;
990}
991
992
993/*
994** 'load' and 'call' functions (run Lua code)
995*/
996
997
998#define checkresults(L,na,nr) \
999 api_check(L, (nr) == LUA_MULTRET \
1000 || (L->ci->top.p - L->top.p >= (nr) - (na)), \
1001 "results from function overflow current stack size")
1002
1003
1004LUA_API void lua_callk (lua_State *L, int nargs, int nresults,
1005 lua_KContext ctx, lua_KFunction k) {
1006 StkId func;
1007 lua_lock(L);
1008 api_check(L, k == NULL || !isLua(L->ci),
1009 "cannot use continuations inside hooks");
1010 api_checknelems(L, nargs+1);
1011 api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
1012 checkresults(L, nargs, nresults);
1013 func = L->top.p - (nargs+1);
1014 if (k != NULL && yieldable(L)) { /* need to prepare continuation? */
1015 L->ci->u.c.k = k; /* save continuation */
1016 L->ci->u.c.ctx = ctx; /* save context */
1017 luaD_call(L, func, nresults); /* do the call */
1018 }
1019 else /* no continuation or no yieldable */
1020 luaD_callnoyield(L, func, nresults); /* just do the call */
1021 adjustresults(L, nresults);
1022 lua_unlock(L);
1023}
1024
1025
1026
1027/*
1028** Execute a protected call.
1029*/
1030struct CallS { /* data to 'f_call' */
1031 StkId func;
1032 int nresults;
1033};
1034
1035
1036static void f_call (lua_State *L, void *ud) {
1037 struct CallS *c = cast(struct CallS *, ud);
1038 luaD_callnoyield(L, c->func, c->nresults);
1039}
1040
1041
1042
1043LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,
1044 lua_KContext ctx, lua_KFunction k) {
1045 struct CallS c;
1046 int status;
1047 ptrdiff_t func;
1048 lua_lock(L);
1049 api_check(L, k == NULL || !isLua(L->ci),
1050 "cannot use continuations inside hooks");
1051 api_checknelems(L, nargs+1);
1052 api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
1053 checkresults(L, nargs, nresults);
1054 if (errfunc == 0)
1055 func = 0;
1056 else {
1057 StkId o = index2stack(L, errfunc);
1058 api_check(L, ttisfunction(s2v(o)), "error handler must be a function");
1059 func = savestack(L, o);
1060 }
1061 c.func = L->top.p - (nargs+1); /* function to be called */
1062 if (k == NULL || !yieldable(L)) { /* no continuation or no yieldable? */
1063 c.nresults = nresults; /* do a 'conventional' protected call */
1064 status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
1065 }
1066 else { /* prepare continuation (call is already protected by 'resume') */
1067 CallInfo *ci = L->ci;
1068 ci->u.c.k = k; /* save continuation */
1069 ci->u.c.ctx = ctx; /* save context */
1070 /* save information for error recovery */
1071 ci->u2.funcidx = cast_int(savestack(L, c.func));
1072 ci->u.c.old_errfunc = L->errfunc;
1073 L->errfunc = func;
1074 setoah(ci->callstatus, L->allowhook); /* save value of 'allowhook' */
1075 ci->callstatus |= CIST_YPCALL; /* function can do error recovery */
1076 luaD_call(L, c.func, nresults); /* do the call */
1077 ci->callstatus &= ~CIST_YPCALL;
1078 L->errfunc = ci->u.c.old_errfunc;
1079 status = LUA_OK; /* if it is here, there were no errors */
1080 }
1081 adjustresults(L, nresults);
1082 lua_unlock(L);
1083 return status;
1084}
1085
1086
1087LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
1088 const char *chunkname, const char *mode) {
1089 ZIO z;
1090 int status;
1091 lua_lock(L);
1092 if (!chunkname) chunkname = "?";
1093 luaZ_init(L, &z, reader, data);
1094 status = luaD_protectedparser(L, &z, chunkname, mode);
1095 if (status == LUA_OK) { /* no errors? */
1096 LClosure *f = clLvalue(s2v(L->top.p - 1)); /* get new function */
1097 if (f->nupvalues >= 1) { /* does it have an upvalue? */
1098 /* get global table from registry */
1099 const TValue *gt = getGtable(L);
1100 /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
1101 setobj(L, f->upvals[0]->v.p, gt);
1102 luaC_barrier(L, f->upvals[0], gt);
1103 }
1104 }
1105 lua_unlock(L);
1106 return status;
1107}
1108
1109
1110LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) {
1111 int status;
1112 TValue *o;
1113 lua_lock(L);
1114 api_checknelems(L, 1);
1115 o = s2v(L->top.p - 1);
1116 if (isLfunction(o))
1117 status = luaU_dump(L, getproto(o), writer, data, strip);
1118 else
1119 status = 1;
1120 lua_unlock(L);
1121 return status;
1122}
1123
1124
1125LUA_API int lua_status (lua_State *L) {
1126 return L->status;
1127}
1128
1129
1130/*
1131** Garbage-collection function
1132*/
1133LUA_API int lua_gc (lua_State *L, int what, ...) {
1134 va_list argp;
1135 int res = 0;
1136 global_State *g = G(L);
1137 if (g->gcstp & GCSTPGC) /* internal stop? */
1138 return -1; /* all options are invalid when stopped */
1139 lua_lock(L);
1140 va_start(argp, what);
1141 switch (what) {
1142 case LUA_GCSTOP: {
1143 g->gcstp = GCSTPUSR; /* stopped by the user */
1144 break;
1145 }
1146 case LUA_GCRESTART: {
1147 luaE_setdebt(g, 0);
1148 g->gcstp = 0; /* (GCSTPGC must be already zero here) */
1149 break;
1150 }
1151 case LUA_GCCOLLECT: {
1152 luaC_fullgc(L, 0);
1153 break;
1154 }
1155 case LUA_GCCOUNT: {
1156 /* GC values are expressed in Kbytes: #bytes/2^10 */
1157 res = cast_int(gettotalbytes(g) >> 10);
1158 break;
1159 }
1160 case LUA_GCCOUNTB: {
1161 res = cast_int(gettotalbytes(g) & 0x3ff);
1162 break;
1163 }
1164 case LUA_GCSTEP: {
1165 int data = va_arg(argp, int);
1166 l_mem debt = 1; /* =1 to signal that it did an actual step */
1167 lu_byte oldstp = g->gcstp;
1168 g->gcstp = 0; /* allow GC to run (GCSTPGC must be zero here) */
1169 if (data == 0) {
1170 luaE_setdebt(g, 0); /* do a basic step */
1171 luaC_step(L);
1172 }
1173 else { /* add 'data' to total debt */
1174 debt = cast(l_mem, data) * 1024 + g->GCdebt;
1175 luaE_setdebt(g, debt);
1176 luaC_checkGC(L);
1177 }
1178 g->gcstp = oldstp; /* restore previous state */
1179 if (debt > 0 && g->gcstate == GCSpause) /* end of cycle? */
1180 res = 1; /* signal it */
1181 break;
1182 }
1183 case LUA_GCSETPAUSE: {
1184 int data = va_arg(argp, int);
1185 res = getgcparam(g->gcpause);
1186 setgcparam(g->gcpause, data);
1187 break;
1188 }
1189 case LUA_GCSETSTEPMUL: {
1190 int data = va_arg(argp, int);
1191 res = getgcparam(g->gcstepmul);
1192 setgcparam(g->gcstepmul, data);
1193 break;
1194 }
1195 case LUA_GCISRUNNING: {
1196 res = gcrunning(g);
1197 break;
1198 }
1199 case LUA_GCGEN: {
1200 int minormul = va_arg(argp, int);
1201 int majormul = va_arg(argp, int);
1202 res = isdecGCmodegen(g) ? LUA_GCGEN : LUA_GCINC;
1203 if (minormul != 0)
1204 g->genminormul = minormul;
1205 if (majormul != 0)
1206 setgcparam(g->genmajormul, majormul);
1207 luaC_changemode(L, KGC_GEN);
1208 break;
1209 }
1210 case LUA_GCINC: {
1211 int pause = va_arg(argp, int);
1212 int stepmul = va_arg(argp, int);
1213 int stepsize = va_arg(argp, int);
1214 res = isdecGCmodegen(g) ? LUA_GCGEN : LUA_GCINC;
1215 if (pause != 0)
1216 setgcparam(g->gcpause, pause);
1217 if (stepmul != 0)
1218 setgcparam(g->gcstepmul, stepmul);
1219 if (stepsize != 0)
1220 g->gcstepsize = stepsize;
1221 luaC_changemode(L, KGC_INC);
1222 break;
1223 }
1224 default: res = -1; /* invalid option */
1225 }
1226 va_end(argp);
1227 lua_unlock(L);
1228 return res;
1229}
1230
1231
1232
1233/*
1234** miscellaneous functions
1235*/
1236
1237
1238LUA_API int lua_error (lua_State *L) {
1239 TValue *errobj;
1240 lua_lock(L);
1241 errobj = s2v(L->top.p - 1);
1242 api_checknelems(L, 1);
1243 /* error object is the memory error message? */
1244 if (ttisshrstring(errobj) && eqshrstr(tsvalue(errobj), G(L)->memerrmsg))
1245 luaM_error(L); /* raise a memory error */
1246 else
1247 luaG_errormsg(L); /* raise a regular error */
1248 /* code unreachable; will unlock when control actually leaves the kernel */
1249 return 0; /* to avoid warnings */
1250}
1251
1252
1253LUA_API int lua_next (lua_State *L, int idx) {
1254 Table *t;
1255 int more;
1256 lua_lock(L);
1257 api_checknelems(L, 1);
1258 t = gettable(L, idx);
1259 more = luaH_next(L, t, L->top.p - 1);
1260 if (more) {
1261 api_incr_top(L);
1262 }
1263 else /* no more elements */
1264 L->top.p -= 1; /* remove key */
1265 lua_unlock(L);
1266 return more;
1267}
1268
1269
1270LUA_API void lua_toclose (lua_State *L, int idx) {
1271 int nresults;
1272 StkId o;
1273 lua_lock(L);
1274 o = index2stack(L, idx);
1275 nresults = L->ci->nresults;
1276 api_check(L, L->tbclist.p < o, "given index below or equal a marked one");
1277 luaF_newtbcupval(L, o); /* create new to-be-closed upvalue */
1278 if (!hastocloseCfunc(nresults)) /* function not marked yet? */
1279 L->ci->nresults = codeNresults(nresults); /* mark it */
1280 lua_assert(hastocloseCfunc(L->ci->nresults));
1281 lua_unlock(L);
1282}
1283
1284
1285LUA_API void lua_concat (lua_State *L, int n) {
1286 lua_lock(L);
1287 api_checknelems(L, n);
1288 if (n > 0)
1289 luaV_concat(L, n);
1290 else { /* nothing to concatenate */
1291 setsvalue2s(L, L->top.p, luaS_newlstr(L, "", 0)); /* push empty string */
1292 api_incr_top(L);
1293 }
1294 luaC_checkGC(L);
1295 lua_unlock(L);
1296}
1297
1298
1299LUA_API void lua_len (lua_State *L, int idx) {
1300 TValue *t;
1301 lua_lock(L);
1302 t = index2value(L, idx);
1303 luaV_objlen(L, L->top.p, t);
1304 api_incr_top(L);
1305 lua_unlock(L);
1306}
1307
1308
1309LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {
1310 lua_Alloc f;
1311 lua_lock(L);
1312 if (ud) *ud = G(L)->ud;
1313 f = G(L)->frealloc;
1314 lua_unlock(L);
1315 return f;
1316}
1317
1318
1319LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {
1320 lua_lock(L);
1321 G(L)->ud = ud;
1322 G(L)->frealloc = f;
1323 lua_unlock(L);
1324}
1325
1326
1327void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud) {
1328 lua_lock(L);
1329 G(L)->ud_warn = ud;
1330 G(L)->warnf = f;
1331 lua_unlock(L);
1332}
1333
1334
1335void lua_warning (lua_State *L, const char *msg, int tocont) {
1336 lua_lock(L);
1337 luaE_warning(L, msg, tocont);
1338 lua_unlock(L);
1339}
1340
1341
1342
1343LUA_API void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue) {
1344 Udata *u;
1345 lua_lock(L);
1346 api_check(L, 0 <= nuvalue && nuvalue < SHRT_MAX, "invalid value");
1347 u = luaS_newudata(L, size, nuvalue);
1348 setuvalue(L, s2v(L->top.p), u);
1349 api_incr_top(L);
1350 luaC_checkGC(L);
1351 lua_unlock(L);
1352 return getudatamem(u);
1353}
1354
1355
1356
1357static const char *aux_upvalue (TValue *fi, int n, TValue **val,
1358 GCObject **owner) {
1359 switch (ttypetag(fi)) {
1360 case LUA_VCCL: { /* C closure */
1361 CClosure *f = clCvalue(fi);
1362 if (!(cast_uint(n) - 1u < cast_uint(f->nupvalues)))
1363 return NULL; /* 'n' not in [1, f->nupvalues] */
1364 *val = &f->upvalue[n-1];
1365 if (owner) *owner = obj2gco(f);
1366 return "";
1367 }
1368 case LUA_VLCL: { /* Lua closure */
1369 LClosure *f = clLvalue(fi);
1370 TString *name;
1371 Proto *p = f->p;
1372 if (!(cast_uint(n) - 1u < cast_uint(p->sizeupvalues)))
1373 return NULL; /* 'n' not in [1, p->sizeupvalues] */
1374 *val = f->upvals[n-1]->v.p;
1375 if (owner) *owner = obj2gco(f->upvals[n - 1]);
1376 name = p->upvalues[n-1].name;
1377 return (name == NULL) ? "(no name)" : getstr(name);
1378 }
1379 default: return NULL; /* not a closure */
1380 }
1381}
1382
1383
1384LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
1385 const char *name;
1386 TValue *val = NULL; /* to avoid warnings */
1387 lua_lock(L);
1388 name = aux_upvalue(index2value(L, funcindex), n, &val, NULL);
1389 if (name) {
1390 setobj2s(L, L->top.p, val);
1391 api_incr_top(L);
1392 }
1393 lua_unlock(L);
1394 return name;
1395}
1396
1397
1398LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
1399 const char *name;
1400 TValue *val = NULL; /* to avoid warnings */
1401 GCObject *owner = NULL; /* to avoid warnings */
1402 TValue *fi;
1403 lua_lock(L);
1404 fi = index2value(L, funcindex);
1405 api_checknelems(L, 1);
1406 name = aux_upvalue(fi, n, &val, &owner);
1407 if (name) {
1408 L->top.p--;
1409 setobj(L, val, s2v(L->top.p));
1410 luaC_barrier(L, owner, val);
1411 }
1412 lua_unlock(L);
1413 return name;
1414}
1415
1416
1417static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
1418 static const UpVal *const nullup = NULL;
1419 LClosure *f;
1420 TValue *fi = index2value(L, fidx);
1421 api_check(L, ttisLclosure(fi), "Lua function expected");
1422 f = clLvalue(fi);
1423 if (pf) *pf = f;
1424 if (1 <= n && n <= f->p->sizeupvalues)
1425 return &f->upvals[n - 1]; /* get its upvalue pointer */
1426 else
1427 return (UpVal**)&nullup;
1428}
1429
1430
1431LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
1432 TValue *fi = index2value(L, fidx);
1433 switch (ttypetag(fi)) {
1434 case LUA_VLCL: { /* lua closure */
1435 return *getupvalref(L, fidx, n, NULL);
1436 }
1437 case LUA_VCCL: { /* C closure */
1438 CClosure *f = clCvalue(fi);
1439 if (1 <= n && n <= f->nupvalues)
1440 return &f->upvalue[n - 1];
1441 /* else */
1442 } /* FALLTHROUGH */
1443 case LUA_VLCF:
1444 return NULL; /* light C functions have no upvalues */
1445 default: {
1446 api_check(L, 0, "function expected");
1447 return NULL;
1448 }
1449 }
1450}
1451
1452
1453LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,
1454 int fidx2, int n2) {
1455 LClosure *f1;
1456 UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
1457 UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
1458 api_check(L, *up1 != NULL && *up2 != NULL, "invalid upvalue index");
1459 *up1 = *up2;
1460 luaC_objbarrier(L, f1, *up1);
1461}
1462
1463
diff --git a/vendor/lua-5.4.8/src/lapi.h b/vendor/lua-5.4.8/src/lapi.h
new file mode 100644
index 0000000..a742427
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lapi.h
@@ -0,0 +1,52 @@
1/*
2** $Id: lapi.h $
3** Auxiliary functions from Lua API
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lapi_h
8#define lapi_h
9
10
11#include "llimits.h"
12#include "lstate.h"
13
14
15/* Increments 'L->top.p', checking for stack overflows */
16#define api_incr_top(L) {L->top.p++; \
17 api_check(L, L->top.p <= L->ci->top.p, \
18 "stack overflow");}
19
20
21/*
22** If a call returns too many multiple returns, the callee may not have
23** stack space to accommodate all results. In this case, this macro
24** increases its stack space ('L->ci->top.p').
25*/
26#define adjustresults(L,nres) \
27 { if ((nres) <= LUA_MULTRET && L->ci->top.p < L->top.p) \
28 L->ci->top.p = L->top.p; }
29
30
31/* Ensure the stack has at least 'n' elements */
32#define api_checknelems(L,n) \
33 api_check(L, (n) < (L->top.p - L->ci->func.p), \
34 "not enough elements in the stack")
35
36
37/*
38** To reduce the overhead of returning from C functions, the presence of
39** to-be-closed variables in these functions is coded in the CallInfo's
40** field 'nresults', in a way that functions with no to-be-closed variables
41** with zero, one, or "all" wanted results have no overhead. Functions
42** with other number of wanted results, as well as functions with
43** variables to be closed, have an extra check.
44*/
45
46#define hastocloseCfunc(n) ((n) < LUA_MULTRET)
47
48/* Map [-1, inf) (range of 'nresults') into (-inf, -2] */
49#define codeNresults(n) (-(n) - 3)
50#define decodeNresults(n) (-(n) - 3)
51
52#endif
diff --git a/vendor/lua-5.4.8/src/lauxlib.c b/vendor/lua-5.4.8/src/lauxlib.c
new file mode 100644
index 0000000..923105e
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lauxlib.c
@@ -0,0 +1,1126 @@
1/*
2** $Id: lauxlib.c $
3** Auxiliary functions for building Lua libraries
4** See Copyright Notice in lua.h
5*/
6
7#define lauxlib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <errno.h>
14#include <stdarg.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18
19
20/*
21** This file uses only the official API of Lua.
22** Any function declared here could be written as an application function.
23*/
24
25#include "lua.h"
26
27#include "lauxlib.h"
28
29
30#if !defined(MAX_SIZET)
31/* maximum value for size_t */
32#define MAX_SIZET ((size_t)(~(size_t)0))
33#endif
34
35
36/*
37** {======================================================
38** Traceback
39** =======================================================
40*/
41
42
43#define LEVELS1 10 /* size of the first part of the stack */
44#define LEVELS2 11 /* size of the second part of the stack */
45
46
47
48/*
49** Search for 'objidx' in table at index -1. ('objidx' must be an
50** absolute index.) Return 1 + string at top if it found a good name.
51*/
52static int findfield (lua_State *L, int objidx, int level) {
53 if (level == 0 || !lua_istable(L, -1))
54 return 0; /* not found */
55 lua_pushnil(L); /* start 'next' loop */
56 while (lua_next(L, -2)) { /* for each pair in table */
57 if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
58 if (lua_rawequal(L, objidx, -1)) { /* found object? */
59 lua_pop(L, 1); /* remove value (but keep name) */
60 return 1;
61 }
62 else if (findfield(L, objidx, level - 1)) { /* try recursively */
63 /* stack: lib_name, lib_table, field_name (top) */
64 lua_pushliteral(L, "."); /* place '.' between the two names */
65 lua_replace(L, -3); /* (in the slot occupied by table) */
66 lua_concat(L, 3); /* lib_name.field_name */
67 return 1;
68 }
69 }
70 lua_pop(L, 1); /* remove value */
71 }
72 return 0; /* not found */
73}
74
75
76/*
77** Search for a name for a function in all loaded modules
78*/
79static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
80 int top = lua_gettop(L);
81 lua_getinfo(L, "f", ar); /* push function */
82 lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
83 luaL_checkstack(L, 6, "not enough stack"); /* slots for 'findfield' */
84 if (findfield(L, top + 1, 2)) {
85 const char *name = lua_tostring(L, -1);
86 if (strncmp(name, LUA_GNAME ".", 3) == 0) { /* name start with '_G.'? */
87 lua_pushstring(L, name + 3); /* push name without prefix */
88 lua_remove(L, -2); /* remove original name */
89 }
90 lua_copy(L, -1, top + 1); /* copy name to proper place */
91 lua_settop(L, top + 1); /* remove table "loaded" and name copy */
92 return 1;
93 }
94 else {
95 lua_settop(L, top); /* remove function and global table */
96 return 0;
97 }
98}
99
100
101static void pushfuncname (lua_State *L, lua_Debug *ar) {
102 if (pushglobalfuncname(L, ar)) { /* try first a global name */
103 lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
104 lua_remove(L, -2); /* remove name */
105 }
106 else if (*ar->namewhat != '\0') /* is there a name from code? */
107 lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
108 else if (*ar->what == 'm') /* main? */
109 lua_pushliteral(L, "main chunk");
110 else if (*ar->what != 'C') /* for Lua functions, use <file:line> */
111 lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
112 else /* nothing left... */
113 lua_pushliteral(L, "?");
114}
115
116
117static int lastlevel (lua_State *L) {
118 lua_Debug ar;
119 int li = 1, le = 1;
120 /* find an upper bound */
121 while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
122 /* do a binary search */
123 while (li < le) {
124 int m = (li + le)/2;
125 if (lua_getstack(L, m, &ar)) li = m + 1;
126 else le = m;
127 }
128 return le - 1;
129}
130
131
132LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
133 const char *msg, int level) {
134 luaL_Buffer b;
135 lua_Debug ar;
136 int last = lastlevel(L1);
137 int limit2show = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;
138 luaL_buffinit(L, &b);
139 if (msg) {
140 luaL_addstring(&b, msg);
141 luaL_addchar(&b, '\n');
142 }
143 luaL_addstring(&b, "stack traceback:");
144 while (lua_getstack(L1, level++, &ar)) {
145 if (limit2show-- == 0) { /* too many levels? */
146 int n = last - level - LEVELS2 + 1; /* number of levels to skip */
147 lua_pushfstring(L, "\n\t...\t(skipping %d levels)", n);
148 luaL_addvalue(&b); /* add warning about skip */
149 level += n; /* and skip to last levels */
150 }
151 else {
152 lua_getinfo(L1, "Slnt", &ar);
153 if (ar.currentline <= 0)
154 lua_pushfstring(L, "\n\t%s: in ", ar.short_src);
155 else
156 lua_pushfstring(L, "\n\t%s:%d: in ", ar.short_src, ar.currentline);
157 luaL_addvalue(&b);
158 pushfuncname(L, &ar);
159 luaL_addvalue(&b);
160 if (ar.istailcall)
161 luaL_addstring(&b, "\n\t(...tail calls...)");
162 }
163 }
164 luaL_pushresult(&b);
165}
166
167/* }====================================================== */
168
169
170/*
171** {======================================================
172** Error-report functions
173** =======================================================
174*/
175
176LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
177 lua_Debug ar;
178 if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
179 return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
180 lua_getinfo(L, "n", &ar);
181 if (strcmp(ar.namewhat, "method") == 0) {
182 arg--; /* do not count 'self' */
183 if (arg == 0) /* error is in the self argument itself? */
184 return luaL_error(L, "calling '%s' on bad self (%s)",
185 ar.name, extramsg);
186 }
187 if (ar.name == NULL)
188 ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
189 return luaL_error(L, "bad argument #%d to '%s' (%s)",
190 arg, ar.name, extramsg);
191}
192
193
194LUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) {
195 const char *msg;
196 const char *typearg; /* name for the type of the actual argument */
197 if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
198 typearg = lua_tostring(L, -1); /* use the given type name */
199 else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
200 typearg = "light userdata"; /* special name for messages */
201 else
202 typearg = luaL_typename(L, arg); /* standard name */
203 msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
204 return luaL_argerror(L, arg, msg);
205}
206
207
208static void tag_error (lua_State *L, int arg, int tag) {
209 luaL_typeerror(L, arg, lua_typename(L, tag));
210}
211
212
213/*
214** The use of 'lua_pushfstring' ensures this function does not
215** need reserved stack space when called.
216*/
217LUALIB_API void luaL_where (lua_State *L, int level) {
218 lua_Debug ar;
219 if (lua_getstack(L, level, &ar)) { /* check function at level */
220 lua_getinfo(L, "Sl", &ar); /* get info about it */
221 if (ar.currentline > 0) { /* is there info? */
222 lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
223 return;
224 }
225 }
226 lua_pushfstring(L, ""); /* else, no information available... */
227}
228
229
230/*
231** Again, the use of 'lua_pushvfstring' ensures this function does
232** not need reserved stack space when called. (At worst, it generates
233** an error with "stack overflow" instead of the given message.)
234*/
235LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
236 va_list argp;
237 va_start(argp, fmt);
238 luaL_where(L, 1);
239 lua_pushvfstring(L, fmt, argp);
240 va_end(argp);
241 lua_concat(L, 2);
242 return lua_error(L);
243}
244
245
246LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
247 int en = errno; /* calls to Lua API may change this value */
248 if (stat) {
249 lua_pushboolean(L, 1);
250 return 1;
251 }
252 else {
253 const char *msg;
254 luaL_pushfail(L);
255 msg = (en != 0) ? strerror(en) : "(no extra info)";
256 if (fname)
257 lua_pushfstring(L, "%s: %s", fname, msg);
258 else
259 lua_pushstring(L, msg);
260 lua_pushinteger(L, en);
261 return 3;
262 }
263}
264
265
266#if !defined(l_inspectstat) /* { */
267
268#if defined(LUA_USE_POSIX)
269
270#include <sys/wait.h>
271
272/*
273** use appropriate macros to interpret 'pclose' return status
274*/
275#define l_inspectstat(stat,what) \
276 if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
277 else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
278
279#else
280
281#define l_inspectstat(stat,what) /* no op */
282
283#endif
284
285#endif /* } */
286
287
288LUALIB_API int luaL_execresult (lua_State *L, int stat) {
289 if (stat != 0 && errno != 0) /* error with an 'errno'? */
290 return luaL_fileresult(L, 0, NULL);
291 else {
292 const char *what = "exit"; /* type of termination */
293 l_inspectstat(stat, what); /* interpret result */
294 if (*what == 'e' && stat == 0) /* successful termination? */
295 lua_pushboolean(L, 1);
296 else
297 luaL_pushfail(L);
298 lua_pushstring(L, what);
299 lua_pushinteger(L, stat);
300 return 3; /* return true/fail,what,code */
301 }
302}
303
304/* }====================================================== */
305
306
307
308/*
309** {======================================================
310** Userdata's metatable manipulation
311** =======================================================
312*/
313
314LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
315 if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */
316 return 0; /* leave previous value on top, but return 0 */
317 lua_pop(L, 1);
318 lua_createtable(L, 0, 2); /* create metatable */
319 lua_pushstring(L, tname);
320 lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
321 lua_pushvalue(L, -1);
322 lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
323 return 1;
324}
325
326
327LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
328 luaL_getmetatable(L, tname);
329 lua_setmetatable(L, -2);
330}
331
332
333LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
334 void *p = lua_touserdata(L, ud);
335 if (p != NULL) { /* value is a userdata? */
336 if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
337 luaL_getmetatable(L, tname); /* get correct metatable */
338 if (!lua_rawequal(L, -1, -2)) /* not the same? */
339 p = NULL; /* value is a userdata with wrong metatable */
340 lua_pop(L, 2); /* remove both metatables */
341 return p;
342 }
343 }
344 return NULL; /* value is not a userdata with a metatable */
345}
346
347
348LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
349 void *p = luaL_testudata(L, ud, tname);
350 luaL_argexpected(L, p != NULL, ud, tname);
351 return p;
352}
353
354/* }====================================================== */
355
356
357/*
358** {======================================================
359** Argument check functions
360** =======================================================
361*/
362
363LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
364 const char *const lst[]) {
365 const char *name = (def) ? luaL_optstring(L, arg, def) :
366 luaL_checkstring(L, arg);
367 int i;
368 for (i=0; lst[i]; i++)
369 if (strcmp(lst[i], name) == 0)
370 return i;
371 return luaL_argerror(L, arg,
372 lua_pushfstring(L, "invalid option '%s'", name));
373}
374
375
376/*
377** Ensures the stack has at least 'space' extra slots, raising an error
378** if it cannot fulfill the request. (The error handling needs a few
379** extra slots to format the error message. In case of an error without
380** this extra space, Lua will generate the same 'stack overflow' error,
381** but without 'msg'.)
382*/
383LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
384 if (l_unlikely(!lua_checkstack(L, space))) {
385 if (msg)
386 luaL_error(L, "stack overflow (%s)", msg);
387 else
388 luaL_error(L, "stack overflow");
389 }
390}
391
392
393LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
394 if (l_unlikely(lua_type(L, arg) != t))
395 tag_error(L, arg, t);
396}
397
398
399LUALIB_API void luaL_checkany (lua_State *L, int arg) {
400 if (l_unlikely(lua_type(L, arg) == LUA_TNONE))
401 luaL_argerror(L, arg, "value expected");
402}
403
404
405LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
406 const char *s = lua_tolstring(L, arg, len);
407 if (l_unlikely(!s)) tag_error(L, arg, LUA_TSTRING);
408 return s;
409}
410
411
412LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
413 const char *def, size_t *len) {
414 if (lua_isnoneornil(L, arg)) {
415 if (len)
416 *len = (def ? strlen(def) : 0);
417 return def;
418 }
419 else return luaL_checklstring(L, arg, len);
420}
421
422
423LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
424 int isnum;
425 lua_Number d = lua_tonumberx(L, arg, &isnum);
426 if (l_unlikely(!isnum))
427 tag_error(L, arg, LUA_TNUMBER);
428 return d;
429}
430
431
432LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
433 return luaL_opt(L, luaL_checknumber, arg, def);
434}
435
436
437static void interror (lua_State *L, int arg) {
438 if (lua_isnumber(L, arg))
439 luaL_argerror(L, arg, "number has no integer representation");
440 else
441 tag_error(L, arg, LUA_TNUMBER);
442}
443
444
445LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
446 int isnum;
447 lua_Integer d = lua_tointegerx(L, arg, &isnum);
448 if (l_unlikely(!isnum)) {
449 interror(L, arg);
450 }
451 return d;
452}
453
454
455LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
456 lua_Integer def) {
457 return luaL_opt(L, luaL_checkinteger, arg, def);
458}
459
460/* }====================================================== */
461
462
463/*
464** {======================================================
465** Generic Buffer manipulation
466** =======================================================
467*/
468
469/* userdata to box arbitrary data */
470typedef struct UBox {
471 void *box;
472 size_t bsize;
473} UBox;
474
475
476static void *resizebox (lua_State *L, int idx, size_t newsize) {
477 void *ud;
478 lua_Alloc allocf = lua_getallocf(L, &ud);
479 UBox *box = (UBox *)lua_touserdata(L, idx);
480 void *temp = allocf(ud, box->box, box->bsize, newsize);
481 if (l_unlikely(temp == NULL && newsize > 0)) { /* allocation error? */
482 lua_pushliteral(L, "not enough memory");
483 lua_error(L); /* raise a memory error */
484 }
485 box->box = temp;
486 box->bsize = newsize;
487 return temp;
488}
489
490
491static int boxgc (lua_State *L) {
492 resizebox(L, 1, 0);
493 return 0;
494}
495
496
497static const luaL_Reg boxmt[] = { /* box metamethods */
498 {"__gc", boxgc},
499 {"__close", boxgc},
500 {NULL, NULL}
501};
502
503
504static void newbox (lua_State *L) {
505 UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0);
506 box->box = NULL;
507 box->bsize = 0;
508 if (luaL_newmetatable(L, "_UBOX*")) /* creating metatable? */
509 luaL_setfuncs(L, boxmt, 0); /* set its metamethods */
510 lua_setmetatable(L, -2);
511}
512
513
514/*
515** check whether buffer is using a userdata on the stack as a temporary
516** buffer
517*/
518#define buffonstack(B) ((B)->b != (B)->init.b)
519
520
521/*
522** Whenever buffer is accessed, slot 'idx' must either be a box (which
523** cannot be NULL) or it is a placeholder for the buffer.
524*/
525#define checkbufferlevel(B,idx) \
526 lua_assert(buffonstack(B) ? lua_touserdata(B->L, idx) != NULL \
527 : lua_touserdata(B->L, idx) == (void*)B)
528
529
530/*
531** Compute new size for buffer 'B', enough to accommodate extra 'sz'
532** bytes. (The test for "not big enough" also gets the case when the
533** computation of 'newsize' overflows.)
534*/
535static size_t newbuffsize (luaL_Buffer *B, size_t sz) {
536 size_t newsize = (B->size / 2) * 3; /* buffer size * 1.5 */
537 if (l_unlikely(MAX_SIZET - sz < B->n)) /* overflow in (B->n + sz)? */
538 return luaL_error(B->L, "buffer too large");
539 if (newsize < B->n + sz) /* not big enough? */
540 newsize = B->n + sz;
541 return newsize;
542}
543
544
545/*
546** Returns a pointer to a free area with at least 'sz' bytes in buffer
547** 'B'. 'boxidx' is the relative position in the stack where is the
548** buffer's box or its placeholder.
549*/
550static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) {
551 checkbufferlevel(B, boxidx);
552 if (B->size - B->n >= sz) /* enough space? */
553 return B->b + B->n;
554 else {
555 lua_State *L = B->L;
556 char *newbuff;
557 size_t newsize = newbuffsize(B, sz);
558 /* create larger buffer */
559 if (buffonstack(B)) /* buffer already has a box? */
560 newbuff = (char *)resizebox(L, boxidx, newsize); /* resize it */
561 else { /* no box yet */
562 lua_remove(L, boxidx); /* remove placeholder */
563 newbox(L); /* create a new box */
564 lua_insert(L, boxidx); /* move box to its intended position */
565 lua_toclose(L, boxidx);
566 newbuff = (char *)resizebox(L, boxidx, newsize);
567 memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
568 }
569 B->b = newbuff;
570 B->size = newsize;
571 return newbuff + B->n;
572 }
573}
574
575/*
576** returns a pointer to a free area with at least 'sz' bytes
577*/
578LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
579 return prepbuffsize(B, sz, -1);
580}
581
582
583LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
584 if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
585 char *b = prepbuffsize(B, l, -1);
586 memcpy(b, s, l * sizeof(char));
587 luaL_addsize(B, l);
588 }
589}
590
591
592LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
593 luaL_addlstring(B, s, strlen(s));
594}
595
596
597LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
598 lua_State *L = B->L;
599 checkbufferlevel(B, -1);
600 lua_pushlstring(L, B->b, B->n);
601 if (buffonstack(B))
602 lua_closeslot(L, -2); /* close the box */
603 lua_remove(L, -2); /* remove box or placeholder from the stack */
604}
605
606
607LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
608 luaL_addsize(B, sz);
609 luaL_pushresult(B);
610}
611
612
613/*
614** 'luaL_addvalue' is the only function in the Buffer system where the
615** box (if existent) is not on the top of the stack. So, instead of
616** calling 'luaL_addlstring', it replicates the code using -2 as the
617** last argument to 'prepbuffsize', signaling that the box is (or will
618** be) below the string being added to the buffer. (Box creation can
619** trigger an emergency GC, so we should not remove the string from the
620** stack before we have the space guaranteed.)
621*/
622LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
623 lua_State *L = B->L;
624 size_t len;
625 const char *s = lua_tolstring(L, -1, &len);
626 char *b = prepbuffsize(B, len, -2);
627 memcpy(b, s, len * sizeof(char));
628 luaL_addsize(B, len);
629 lua_pop(L, 1); /* pop string */
630}
631
632
633LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
634 B->L = L;
635 B->b = B->init.b;
636 B->n = 0;
637 B->size = LUAL_BUFFERSIZE;
638 lua_pushlightuserdata(L, (void*)B); /* push placeholder */
639}
640
641
642LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
643 luaL_buffinit(L, B);
644 return prepbuffsize(B, sz, -1);
645}
646
647/* }====================================================== */
648
649
650/*
651** {======================================================
652** Reference system
653** =======================================================
654*/
655
656/* index of free-list header (after the predefined values) */
657#define freelist (LUA_RIDX_LAST + 1)
658
659/*
660** The previously freed references form a linked list:
661** t[freelist] is the index of a first free index, or zero if list is
662** empty; t[t[freelist]] is the index of the second element; etc.
663*/
664LUALIB_API int luaL_ref (lua_State *L, int t) {
665 int ref;
666 if (lua_isnil(L, -1)) {
667 lua_pop(L, 1); /* remove from stack */
668 return LUA_REFNIL; /* 'nil' has a unique fixed reference */
669 }
670 t = lua_absindex(L, t);
671 if (lua_rawgeti(L, t, freelist) == LUA_TNIL) { /* first access? */
672 ref = 0; /* list is empty */
673 lua_pushinteger(L, 0); /* initialize as an empty list */
674 lua_rawseti(L, t, freelist); /* ref = t[freelist] = 0 */
675 }
676 else { /* already initialized */
677 lua_assert(lua_isinteger(L, -1));
678 ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
679 }
680 lua_pop(L, 1); /* remove element from stack */
681 if (ref != 0) { /* any free element? */
682 lua_rawgeti(L, t, ref); /* remove it from list */
683 lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
684 }
685 else /* no free elements */
686 ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
687 lua_rawseti(L, t, ref);
688 return ref;
689}
690
691
692LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
693 if (ref >= 0) {
694 t = lua_absindex(L, t);
695 lua_rawgeti(L, t, freelist);
696 lua_assert(lua_isinteger(L, -1));
697 lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
698 lua_pushinteger(L, ref);
699 lua_rawseti(L, t, freelist); /* t[freelist] = ref */
700 }
701}
702
703/* }====================================================== */
704
705
706/*
707** {======================================================
708** Load functions
709** =======================================================
710*/
711
712typedef struct LoadF {
713 int n; /* number of pre-read characters */
714 FILE *f; /* file being read */
715 char buff[BUFSIZ]; /* area for reading file */
716} LoadF;
717
718
719static const char *getF (lua_State *L, void *ud, size_t *size) {
720 LoadF *lf = (LoadF *)ud;
721 (void)L; /* not used */
722 if (lf->n > 0) { /* are there pre-read characters to be read? */
723 *size = lf->n; /* return them (chars already in buffer) */
724 lf->n = 0; /* no more pre-read characters */
725 }
726 else { /* read a block from file */
727 /* 'fread' can return > 0 *and* set the EOF flag. If next call to
728 'getF' called 'fread', it might still wait for user input.
729 The next check avoids this problem. */
730 if (feof(lf->f)) return NULL;
731 *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
732 }
733 return lf->buff;
734}
735
736
737static int errfile (lua_State *L, const char *what, int fnameindex) {
738 int err = errno;
739 const char *filename = lua_tostring(L, fnameindex) + 1;
740 if (err != 0)
741 lua_pushfstring(L, "cannot %s %s: %s", what, filename, strerror(err));
742 else
743 lua_pushfstring(L, "cannot %s %s", what, filename);
744 lua_remove(L, fnameindex);
745 return LUA_ERRFILE;
746}
747
748
749/*
750** Skip an optional BOM at the start of a stream. If there is an
751** incomplete BOM (the first character is correct but the rest is
752** not), returns the first character anyway to force an error
753** (as no chunk can start with 0xEF).
754*/
755static int skipBOM (FILE *f) {
756 int c = getc(f); /* read first character */
757 if (c == 0xEF && getc(f) == 0xBB && getc(f) == 0xBF) /* correct BOM? */
758 return getc(f); /* ignore BOM and return next char */
759 else /* no (valid) BOM */
760 return c; /* return first character */
761}
762
763
764/*
765** reads the first character of file 'f' and skips an optional BOM mark
766** in its beginning plus its first line if it starts with '#'. Returns
767** true if it skipped the first line. In any case, '*cp' has the
768** first "valid" character of the file (after the optional BOM and
769** a first-line comment).
770*/
771static int skipcomment (FILE *f, int *cp) {
772 int c = *cp = skipBOM(f);
773 if (c == '#') { /* first line is a comment (Unix exec. file)? */
774 do { /* skip first line */
775 c = getc(f);
776 } while (c != EOF && c != '\n');
777 *cp = getc(f); /* next character after comment, if present */
778 return 1; /* there was a comment */
779 }
780 else return 0; /* no comment */
781}
782
783
784LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
785 const char *mode) {
786 LoadF lf;
787 int status, readstatus;
788 int c;
789 int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
790 if (filename == NULL) {
791 lua_pushliteral(L, "=stdin");
792 lf.f = stdin;
793 }
794 else {
795 lua_pushfstring(L, "@%s", filename);
796 errno = 0;
797 lf.f = fopen(filename, "r");
798 if (lf.f == NULL) return errfile(L, "open", fnameindex);
799 }
800 lf.n = 0;
801 if (skipcomment(lf.f, &c)) /* read initial portion */
802 lf.buff[lf.n++] = '\n'; /* add newline to correct line numbers */
803 if (c == LUA_SIGNATURE[0]) { /* binary file? */
804 lf.n = 0; /* remove possible newline */
805 if (filename) { /* "real" file? */
806 errno = 0;
807 lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
808 if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
809 skipcomment(lf.f, &c); /* re-read initial portion */
810 }
811 }
812 if (c != EOF)
813 lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
814 errno = 0;
815 status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
816 readstatus = ferror(lf.f);
817 if (filename) fclose(lf.f); /* close file (even in case of errors) */
818 if (readstatus) {
819 lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
820 return errfile(L, "read", fnameindex);
821 }
822 lua_remove(L, fnameindex);
823 return status;
824}
825
826
827typedef struct LoadS {
828 const char *s;
829 size_t size;
830} LoadS;
831
832
833static const char *getS (lua_State *L, void *ud, size_t *size) {
834 LoadS *ls = (LoadS *)ud;
835 (void)L; /* not used */
836 if (ls->size == 0) return NULL;
837 *size = ls->size;
838 ls->size = 0;
839 return ls->s;
840}
841
842
843LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
844 const char *name, const char *mode) {
845 LoadS ls;
846 ls.s = buff;
847 ls.size = size;
848 return lua_load(L, getS, &ls, name, mode);
849}
850
851
852LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
853 return luaL_loadbuffer(L, s, strlen(s), s);
854}
855
856/* }====================================================== */
857
858
859
860LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
861 if (!lua_getmetatable(L, obj)) /* no metatable? */
862 return LUA_TNIL;
863 else {
864 int tt;
865 lua_pushstring(L, event);
866 tt = lua_rawget(L, -2);
867 if (tt == LUA_TNIL) /* is metafield nil? */
868 lua_pop(L, 2); /* remove metatable and metafield */
869 else
870 lua_remove(L, -2); /* remove only metatable */
871 return tt; /* return metafield type */
872 }
873}
874
875
876LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
877 obj = lua_absindex(L, obj);
878 if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
879 return 0;
880 lua_pushvalue(L, obj);
881 lua_call(L, 1, 1);
882 return 1;
883}
884
885
886LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
887 lua_Integer l;
888 int isnum;
889 lua_len(L, idx);
890 l = lua_tointegerx(L, -1, &isnum);
891 if (l_unlikely(!isnum))
892 luaL_error(L, "object length is not an integer");
893 lua_pop(L, 1); /* remove object */
894 return l;
895}
896
897
898LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
899 idx = lua_absindex(L,idx);
900 if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */
901 if (!lua_isstring(L, -1))
902 luaL_error(L, "'__tostring' must return a string");
903 }
904 else {
905 switch (lua_type(L, idx)) {
906 case LUA_TNUMBER: {
907 if (lua_isinteger(L, idx))
908 lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx));
909 else
910 lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx));
911 break;
912 }
913 case LUA_TSTRING:
914 lua_pushvalue(L, idx);
915 break;
916 case LUA_TBOOLEAN:
917 lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
918 break;
919 case LUA_TNIL:
920 lua_pushliteral(L, "nil");
921 break;
922 default: {
923 int tt = luaL_getmetafield(L, idx, "__name"); /* try name */
924 const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :
925 luaL_typename(L, idx);
926 lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx));
927 if (tt != LUA_TNIL)
928 lua_remove(L, -2); /* remove '__name' */
929 break;
930 }
931 }
932 }
933 return lua_tolstring(L, -1, len);
934}
935
936
937/*
938** set functions from list 'l' into table at top - 'nup'; each
939** function gets the 'nup' elements at the top as upvalues.
940** Returns with only the table at the stack.
941*/
942LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
943 luaL_checkstack(L, nup, "too many upvalues");
944 for (; l->name != NULL; l++) { /* fill the table with given functions */
945 if (l->func == NULL) /* placeholder? */
946 lua_pushboolean(L, 0);
947 else {
948 int i;
949 for (i = 0; i < nup; i++) /* copy upvalues to the top */
950 lua_pushvalue(L, -nup);
951 lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
952 }
953 lua_setfield(L, -(nup + 2), l->name);
954 }
955 lua_pop(L, nup); /* remove upvalues */
956}
957
958
959/*
960** ensure that stack[idx][fname] has a table and push that table
961** into the stack
962*/
963LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
964 if (lua_getfield(L, idx, fname) == LUA_TTABLE)
965 return 1; /* table already there */
966 else {
967 lua_pop(L, 1); /* remove previous result */
968 idx = lua_absindex(L, idx);
969 lua_newtable(L);
970 lua_pushvalue(L, -1); /* copy to be left at top */
971 lua_setfield(L, idx, fname); /* assign new table to field */
972 return 0; /* false, because did not find table there */
973 }
974}
975
976
977/*
978** Stripped-down 'require': After checking "loaded" table, calls 'openf'
979** to open a module, registers the result in 'package.loaded' table and,
980** if 'glb' is true, also registers the result in the global table.
981** Leaves resulting module on the top.
982*/
983LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
984 lua_CFunction openf, int glb) {
985 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
986 lua_getfield(L, -1, modname); /* LOADED[modname] */
987 if (!lua_toboolean(L, -1)) { /* package not already loaded? */
988 lua_pop(L, 1); /* remove field */
989 lua_pushcfunction(L, openf);
990 lua_pushstring(L, modname); /* argument to open function */
991 lua_call(L, 1, 1); /* call 'openf' to open module */
992 lua_pushvalue(L, -1); /* make copy of module (call result) */
993 lua_setfield(L, -3, modname); /* LOADED[modname] = module */
994 }
995 lua_remove(L, -2); /* remove LOADED table */
996 if (glb) {
997 lua_pushvalue(L, -1); /* copy of module */
998 lua_setglobal(L, modname); /* _G[modname] = module */
999 }
1000}
1001
1002
1003LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s,
1004 const char *p, const char *r) {
1005 const char *wild;
1006 size_t l = strlen(p);
1007 while ((wild = strstr(s, p)) != NULL) {
1008 luaL_addlstring(b, s, wild - s); /* push prefix */
1009 luaL_addstring(b, r); /* push replacement in place of pattern */
1010 s = wild + l; /* continue after 'p' */
1011 }
1012 luaL_addstring(b, s); /* push last suffix */
1013}
1014
1015
1016LUALIB_API const char *luaL_gsub (lua_State *L, const char *s,
1017 const char *p, const char *r) {
1018 luaL_Buffer b;
1019 luaL_buffinit(L, &b);
1020 luaL_addgsub(&b, s, p, r);
1021 luaL_pushresult(&b);
1022 return lua_tostring(L, -1);
1023}
1024
1025
1026static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
1027 (void)ud; (void)osize; /* not used */
1028 if (nsize == 0) {
1029 free(ptr);
1030 return NULL;
1031 }
1032 else
1033 return realloc(ptr, nsize);
1034}
1035
1036
1037/*
1038** Standard panic funcion just prints an error message. The test
1039** with 'lua_type' avoids possible memory errors in 'lua_tostring'.
1040*/
1041static int panic (lua_State *L) {
1042 const char *msg = (lua_type(L, -1) == LUA_TSTRING)
1043 ? lua_tostring(L, -1)
1044 : "error object is not a string";
1045 lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
1046 msg);
1047 return 0; /* return to Lua to abort */
1048}
1049
1050
1051/*
1052** Warning functions:
1053** warnfoff: warning system is off
1054** warnfon: ready to start a new message
1055** warnfcont: previous message is to be continued
1056*/
1057static void warnfoff (void *ud, const char *message, int tocont);
1058static void warnfon (void *ud, const char *message, int tocont);
1059static void warnfcont (void *ud, const char *message, int tocont);
1060
1061
1062/*
1063** Check whether message is a control message. If so, execute the
1064** control or ignore it if unknown.
1065*/
1066static int checkcontrol (lua_State *L, const char *message, int tocont) {
1067 if (tocont || *(message++) != '@') /* not a control message? */
1068 return 0;
1069 else {
1070 if (strcmp(message, "off") == 0)
1071 lua_setwarnf(L, warnfoff, L); /* turn warnings off */
1072 else if (strcmp(message, "on") == 0)
1073 lua_setwarnf(L, warnfon, L); /* turn warnings on */
1074 return 1; /* it was a control message */
1075 }
1076}
1077
1078
1079static void warnfoff (void *ud, const char *message, int tocont) {
1080 checkcontrol((lua_State *)ud, message, tocont);
1081}
1082
1083
1084/*
1085** Writes the message and handle 'tocont', finishing the message
1086** if needed and setting the next warn function.
1087*/
1088static void warnfcont (void *ud, const char *message, int tocont) {
1089 lua_State *L = (lua_State *)ud;
1090 lua_writestringerror("%s", message); /* write message */
1091 if (tocont) /* not the last part? */
1092 lua_setwarnf(L, warnfcont, L); /* to be continued */
1093 else { /* last part */
1094 lua_writestringerror("%s", "\n"); /* finish message with end-of-line */
1095 lua_setwarnf(L, warnfon, L); /* next call is a new message */
1096 }
1097}
1098
1099
1100static void warnfon (void *ud, const char *message, int tocont) {
1101 if (checkcontrol((lua_State *)ud, message, tocont)) /* control message? */
1102 return; /* nothing else to be done */
1103 lua_writestringerror("%s", "Lua warning: "); /* start a new warning */
1104 warnfcont(ud, message, tocont); /* finish processing */
1105}
1106
1107
1108LUALIB_API lua_State *luaL_newstate (void) {
1109 lua_State *L = lua_newstate(l_alloc, NULL);
1110 if (l_likely(L)) {
1111 lua_atpanic(L, &panic);
1112 lua_setwarnf(L, warnfoff, L); /* default is warnings off */
1113 }
1114 return L;
1115}
1116
1117
1118LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
1119 lua_Number v = lua_version(L);
1120 if (sz != LUAL_NUMSIZES) /* check numeric types */
1121 luaL_error(L, "core and library have incompatible numeric types");
1122 else if (v != ver)
1123 luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
1124 (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v);
1125}
1126
diff --git a/vendor/lua-5.4.8/src/lauxlib.h b/vendor/lua-5.4.8/src/lauxlib.h
new file mode 100644
index 0000000..5b977e2
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lauxlib.h
@@ -0,0 +1,301 @@
1/*
2** $Id: lauxlib.h $
3** Auxiliary functions for building Lua libraries
4** See Copyright Notice in lua.h
5*/
6
7
8#ifndef lauxlib_h
9#define lauxlib_h
10
11
12#include <stddef.h>
13#include <stdio.h>
14
15#include "luaconf.h"
16#include "lua.h"
17
18
19/* global table */
20#define LUA_GNAME "_G"
21
22
23typedef struct luaL_Buffer luaL_Buffer;
24
25
26/* extra error code for 'luaL_loadfilex' */
27#define LUA_ERRFILE (LUA_ERRERR+1)
28
29
30/* key, in the registry, for table of loaded modules */
31#define LUA_LOADED_TABLE "_LOADED"
32
33
34/* key, in the registry, for table of preloaded loaders */
35#define LUA_PRELOAD_TABLE "_PRELOAD"
36
37
38typedef struct luaL_Reg {
39 const char *name;
40 lua_CFunction func;
41} luaL_Reg;
42
43
44#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number))
45
46LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz);
47#define luaL_checkversion(L) \
48 luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES)
49
50LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
51LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
52LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);
53LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg);
54LUALIB_API int (luaL_typeerror) (lua_State *L, int arg, const char *tname);
55LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg,
56 size_t *l);
57LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg,
58 const char *def, size_t *l);
59LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg);
60LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def);
61
62LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg);
63LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg,
64 lua_Integer def);
65
66LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);
67LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t);
68LUALIB_API void (luaL_checkany) (lua_State *L, int arg);
69
70LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname);
71LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname);
72LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname);
73LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname);
74
75LUALIB_API void (luaL_where) (lua_State *L, int lvl);
76LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
77
78LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def,
79 const char *const lst[]);
80
81LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);
82LUALIB_API int (luaL_execresult) (lua_State *L, int stat);
83
84
85/* predefined references */
86#define LUA_NOREF (-2)
87#define LUA_REFNIL (-1)
88
89LUALIB_API int (luaL_ref) (lua_State *L, int t);
90LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref);
91
92LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename,
93 const char *mode);
94
95#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL)
96
97LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz,
98 const char *name, const char *mode);
99LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);
100
101LUALIB_API lua_State *(luaL_newstate) (void);
102
103LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx);
104
105LUALIB_API void (luaL_addgsub) (luaL_Buffer *b, const char *s,
106 const char *p, const char *r);
107LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s,
108 const char *p, const char *r);
109
110LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);
111
112LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname);
113
114LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1,
115 const char *msg, int level);
116
117LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,
118 lua_CFunction openf, int glb);
119
120/*
121** ===============================================================
122** some useful macros
123** ===============================================================
124*/
125
126
127#define luaL_newlibtable(L,l) \
128 lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)
129
130#define luaL_newlib(L,l) \
131 (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
132
133#define luaL_argcheck(L, cond,arg,extramsg) \
134 ((void)(luai_likely(cond) || luaL_argerror(L, (arg), (extramsg))))
135
136#define luaL_argexpected(L,cond,arg,tname) \
137 ((void)(luai_likely(cond) || luaL_typeerror(L, (arg), (tname))))
138
139#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
140#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
141
142#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i)))
143
144#define luaL_dofile(L, fn) \
145 (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))
146
147#define luaL_dostring(L, s) \
148 (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))
149
150#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n)))
151
152#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))
153
154#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL)
155
156
157/*
158** Perform arithmetic operations on lua_Integer values with wrap-around
159** semantics, as the Lua core does.
160*/
161#define luaL_intop(op,v1,v2) \
162 ((lua_Integer)((lua_Unsigned)(v1) op (lua_Unsigned)(v2)))
163
164
165/* push the value used to represent failure/error */
166#define luaL_pushfail(L) lua_pushnil(L)
167
168
169/*
170** Internal assertions for in-house debugging
171*/
172#if !defined(lua_assert)
173
174#if defined LUAI_ASSERT
175 #include <assert.h>
176 #define lua_assert(c) assert(c)
177#else
178 #define lua_assert(c) ((void)0)
179#endif
180
181#endif
182
183
184
185/*
186** {======================================================
187** Generic Buffer manipulation
188** =======================================================
189*/
190
191struct luaL_Buffer {
192 char *b; /* buffer address */
193 size_t size; /* buffer size */
194 size_t n; /* number of characters in buffer */
195 lua_State *L;
196 union {
197 LUAI_MAXALIGN; /* ensure maximum alignment for buffer */
198 char b[LUAL_BUFFERSIZE]; /* initial buffer */
199 } init;
200};
201
202
203#define luaL_bufflen(bf) ((bf)->n)
204#define luaL_buffaddr(bf) ((bf)->b)
205
206
207#define luaL_addchar(B,c) \
208 ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \
209 ((B)->b[(B)->n++] = (c)))
210
211#define luaL_addsize(B,s) ((B)->n += (s))
212
213#define luaL_buffsub(B,s) ((B)->n -= (s))
214
215LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
216LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);
217LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
218LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s);
219LUALIB_API void (luaL_addvalue) (luaL_Buffer *B);
220LUALIB_API void (luaL_pushresult) (luaL_Buffer *B);
221LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz);
222LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz);
223
224#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
225
226/* }====================================================== */
227
228
229
230/*
231** {======================================================
232** File handles for IO library
233** =======================================================
234*/
235
236/*
237** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and
238** initial structure 'luaL_Stream' (it may contain other fields
239** after that initial structure).
240*/
241
242#define LUA_FILEHANDLE "FILE*"
243
244
245typedef struct luaL_Stream {
246 FILE *f; /* stream (NULL for incompletely created streams) */
247 lua_CFunction closef; /* to close stream (NULL for closed streams) */
248} luaL_Stream;
249
250/* }====================================================== */
251
252/*
253** {==================================================================
254** "Abstraction Layer" for basic report of messages and errors
255** ===================================================================
256*/
257
258/* print a string */
259#if !defined(lua_writestring)
260#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
261#endif
262
263/* print a newline and flush the output */
264#if !defined(lua_writeline)
265#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout))
266#endif
267
268/* print an error message */
269#if !defined(lua_writestringerror)
270#define lua_writestringerror(s,p) \
271 (fprintf(stderr, (s), (p)), fflush(stderr))
272#endif
273
274/* }================================================================== */
275
276
277/*
278** {============================================================
279** Compatibility with deprecated conversions
280** =============================================================
281*/
282#if defined(LUA_COMPAT_APIINTCASTS)
283
284#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a))
285#define luaL_optunsigned(L,a,d) \
286 ((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d)))
287
288#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n)))
289#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d)))
290
291#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n)))
292#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d)))
293
294#endif
295/* }============================================================ */
296
297
298
299#endif
300
301
diff --git a/vendor/lua-5.4.8/src/lbaselib.c b/vendor/lua-5.4.8/src/lbaselib.c
new file mode 100644
index 0000000..1d60c9d
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lbaselib.c
@@ -0,0 +1,549 @@
1/*
2** $Id: lbaselib.c $
3** Basic library
4** See Copyright Notice in lua.h
5*/
6
7#define lbaselib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <ctype.h>
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17
18#include "lua.h"
19
20#include "lauxlib.h"
21#include "lualib.h"
22
23
24static int luaB_print (lua_State *L) {
25 int n = lua_gettop(L); /* number of arguments */
26 int i;
27 for (i = 1; i <= n; i++) { /* for each argument */
28 size_t l;
29 const char *s = luaL_tolstring(L, i, &l); /* convert it to string */
30 if (i > 1) /* not the first element? */
31 lua_writestring("\t", 1); /* add a tab before it */
32 lua_writestring(s, l); /* print it */
33 lua_pop(L, 1); /* pop result */
34 }
35 lua_writeline();
36 return 0;
37}
38
39
40/*
41** Creates a warning with all given arguments.
42** Check first for errors; otherwise an error may interrupt
43** the composition of a warning, leaving it unfinished.
44*/
45static int luaB_warn (lua_State *L) {
46 int n = lua_gettop(L); /* number of arguments */
47 int i;
48 luaL_checkstring(L, 1); /* at least one argument */
49 for (i = 2; i <= n; i++)
50 luaL_checkstring(L, i); /* make sure all arguments are strings */
51 for (i = 1; i < n; i++) /* compose warning */
52 lua_warning(L, lua_tostring(L, i), 1);
53 lua_warning(L, lua_tostring(L, n), 0); /* close warning */
54 return 0;
55}
56
57
58#define SPACECHARS " \f\n\r\t\v"
59
60static const char *b_str2int (const char *s, int base, lua_Integer *pn) {
61 lua_Unsigned n = 0;
62 int neg = 0;
63 s += strspn(s, SPACECHARS); /* skip initial spaces */
64 if (*s == '-') { s++; neg = 1; } /* handle sign */
65 else if (*s == '+') s++;
66 if (!isalnum((unsigned char)*s)) /* no digit? */
67 return NULL;
68 do {
69 int digit = (isdigit((unsigned char)*s)) ? *s - '0'
70 : (toupper((unsigned char)*s) - 'A') + 10;
71 if (digit >= base) return NULL; /* invalid numeral */
72 n = n * base + digit;
73 s++;
74 } while (isalnum((unsigned char)*s));
75 s += strspn(s, SPACECHARS); /* skip trailing spaces */
76 *pn = (lua_Integer)((neg) ? (0u - n) : n);
77 return s;
78}
79
80
81static int luaB_tonumber (lua_State *L) {
82 if (lua_isnoneornil(L, 2)) { /* standard conversion? */
83 if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */
84 lua_settop(L, 1); /* yes; return it */
85 return 1;
86 }
87 else {
88 size_t l;
89 const char *s = lua_tolstring(L, 1, &l);
90 if (s != NULL && lua_stringtonumber(L, s) == l + 1)
91 return 1; /* successful conversion to number */
92 /* else not a number */
93 luaL_checkany(L, 1); /* (but there must be some parameter) */
94 }
95 }
96 else {
97 size_t l;
98 const char *s;
99 lua_Integer n = 0; /* to avoid warnings */
100 lua_Integer base = luaL_checkinteger(L, 2);
101 luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */
102 s = lua_tolstring(L, 1, &l);
103 luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
104 if (b_str2int(s, (int)base, &n) == s + l) {
105 lua_pushinteger(L, n);
106 return 1;
107 } /* else not a number */
108 } /* else not a number */
109 luaL_pushfail(L); /* not a number */
110 return 1;
111}
112
113
114static int luaB_error (lua_State *L) {
115 int level = (int)luaL_optinteger(L, 2, 1);
116 lua_settop(L, 1);
117 if (lua_type(L, 1) == LUA_TSTRING && level > 0) {
118 luaL_where(L, level); /* add extra information */
119 lua_pushvalue(L, 1);
120 lua_concat(L, 2);
121 }
122 return lua_error(L);
123}
124
125
126static int luaB_getmetatable (lua_State *L) {
127 luaL_checkany(L, 1);
128 if (!lua_getmetatable(L, 1)) {
129 lua_pushnil(L);
130 return 1; /* no metatable */
131 }
132 luaL_getmetafield(L, 1, "__metatable");
133 return 1; /* returns either __metatable field (if present) or metatable */
134}
135
136
137static int luaB_setmetatable (lua_State *L) {
138 int t = lua_type(L, 2);
139 luaL_checktype(L, 1, LUA_TTABLE);
140 luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table");
141 if (l_unlikely(luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL))
142 return luaL_error(L, "cannot change a protected metatable");
143 lua_settop(L, 2);
144 lua_setmetatable(L, 1);
145 return 1;
146}
147
148
149static int luaB_rawequal (lua_State *L) {
150 luaL_checkany(L, 1);
151 luaL_checkany(L, 2);
152 lua_pushboolean(L, lua_rawequal(L, 1, 2));
153 return 1;
154}
155
156
157static int luaB_rawlen (lua_State *L) {
158 int t = lua_type(L, 1);
159 luaL_argexpected(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
160 "table or string");
161 lua_pushinteger(L, lua_rawlen(L, 1));
162 return 1;
163}
164
165
166static int luaB_rawget (lua_State *L) {
167 luaL_checktype(L, 1, LUA_TTABLE);
168 luaL_checkany(L, 2);
169 lua_settop(L, 2);
170 lua_rawget(L, 1);
171 return 1;
172}
173
174static int luaB_rawset (lua_State *L) {
175 luaL_checktype(L, 1, LUA_TTABLE);
176 luaL_checkany(L, 2);
177 luaL_checkany(L, 3);
178 lua_settop(L, 3);
179 lua_rawset(L, 1);
180 return 1;
181}
182
183
184static int pushmode (lua_State *L, int oldmode) {
185 if (oldmode == -1)
186 luaL_pushfail(L); /* invalid call to 'lua_gc' */
187 else
188 lua_pushstring(L, (oldmode == LUA_GCINC) ? "incremental"
189 : "generational");
190 return 1;
191}
192
193
194/*
195** check whether call to 'lua_gc' was valid (not inside a finalizer)
196*/
197#define checkvalres(res) { if (res == -1) break; }
198
199static int luaB_collectgarbage (lua_State *L) {
200 static const char *const opts[] = {"stop", "restart", "collect",
201 "count", "step", "setpause", "setstepmul",
202 "isrunning", "generational", "incremental", NULL};
203 static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
204 LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
205 LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC};
206 int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
207 switch (o) {
208 case LUA_GCCOUNT: {
209 int k = lua_gc(L, o);
210 int b = lua_gc(L, LUA_GCCOUNTB);
211 checkvalres(k);
212 lua_pushnumber(L, (lua_Number)k + ((lua_Number)b/1024));
213 return 1;
214 }
215 case LUA_GCSTEP: {
216 int step = (int)luaL_optinteger(L, 2, 0);
217 int res = lua_gc(L, o, step);
218 checkvalres(res);
219 lua_pushboolean(L, res);
220 return 1;
221 }
222 case LUA_GCSETPAUSE:
223 case LUA_GCSETSTEPMUL: {
224 int p = (int)luaL_optinteger(L, 2, 0);
225 int previous = lua_gc(L, o, p);
226 checkvalres(previous);
227 lua_pushinteger(L, previous);
228 return 1;
229 }
230 case LUA_GCISRUNNING: {
231 int res = lua_gc(L, o);
232 checkvalres(res);
233 lua_pushboolean(L, res);
234 return 1;
235 }
236 case LUA_GCGEN: {
237 int minormul = (int)luaL_optinteger(L, 2, 0);
238 int majormul = (int)luaL_optinteger(L, 3, 0);
239 return pushmode(L, lua_gc(L, o, minormul, majormul));
240 }
241 case LUA_GCINC: {
242 int pause = (int)luaL_optinteger(L, 2, 0);
243 int stepmul = (int)luaL_optinteger(L, 3, 0);
244 int stepsize = (int)luaL_optinteger(L, 4, 0);
245 return pushmode(L, lua_gc(L, o, pause, stepmul, stepsize));
246 }
247 default: {
248 int res = lua_gc(L, o);
249 checkvalres(res);
250 lua_pushinteger(L, res);
251 return 1;
252 }
253 }
254 luaL_pushfail(L); /* invalid call (inside a finalizer) */
255 return 1;
256}
257
258
259static int luaB_type (lua_State *L) {
260 int t = lua_type(L, 1);
261 luaL_argcheck(L, t != LUA_TNONE, 1, "value expected");
262 lua_pushstring(L, lua_typename(L, t));
263 return 1;
264}
265
266
267static int luaB_next (lua_State *L) {
268 luaL_checktype(L, 1, LUA_TTABLE);
269 lua_settop(L, 2); /* create a 2nd argument if there isn't one */
270 if (lua_next(L, 1))
271 return 2;
272 else {
273 lua_pushnil(L);
274 return 1;
275 }
276}
277
278
279static int pairscont (lua_State *L, int status, lua_KContext k) {
280 (void)L; (void)status; (void)k; /* unused */
281 return 3;
282}
283
284static int luaB_pairs (lua_State *L) {
285 luaL_checkany(L, 1);
286 if (luaL_getmetafield(L, 1, "__pairs") == LUA_TNIL) { /* no metamethod? */
287 lua_pushcfunction(L, luaB_next); /* will return generator, */
288 lua_pushvalue(L, 1); /* state, */
289 lua_pushnil(L); /* and initial value */
290 }
291 else {
292 lua_pushvalue(L, 1); /* argument 'self' to metamethod */
293 lua_callk(L, 1, 3, 0, pairscont); /* get 3 values from metamethod */
294 }
295 return 3;
296}
297
298
299/*
300** Traversal function for 'ipairs'
301*/
302static int ipairsaux (lua_State *L) {
303 lua_Integer i = luaL_checkinteger(L, 2);
304 i = luaL_intop(+, i, 1);
305 lua_pushinteger(L, i);
306 return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
307}
308
309
310/*
311** 'ipairs' function. Returns 'ipairsaux', given "table", 0.
312** (The given "table" may not be a table.)
313*/
314static int luaB_ipairs (lua_State *L) {
315 luaL_checkany(L, 1);
316 lua_pushcfunction(L, ipairsaux); /* iteration function */
317 lua_pushvalue(L, 1); /* state */
318 lua_pushinteger(L, 0); /* initial value */
319 return 3;
320}
321
322
323static int load_aux (lua_State *L, int status, int envidx) {
324 if (l_likely(status == LUA_OK)) {
325 if (envidx != 0) { /* 'env' parameter? */
326 lua_pushvalue(L, envidx); /* environment for loaded function */
327 if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */
328 lua_pop(L, 1); /* remove 'env' if not used by previous call */
329 }
330 return 1;
331 }
332 else { /* error (message is on top of the stack) */
333 luaL_pushfail(L);
334 lua_insert(L, -2); /* put before error message */
335 return 2; /* return fail plus error message */
336 }
337}
338
339
340static int luaB_loadfile (lua_State *L) {
341 const char *fname = luaL_optstring(L, 1, NULL);
342 const char *mode = luaL_optstring(L, 2, NULL);
343 int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */
344 int status = luaL_loadfilex(L, fname, mode);
345 return load_aux(L, status, env);
346}
347
348
349/*
350** {======================================================
351** Generic Read function
352** =======================================================
353*/
354
355
356/*
357** reserved slot, above all arguments, to hold a copy of the returned
358** string to avoid it being collected while parsed. 'load' has four
359** optional arguments (chunk, source name, mode, and environment).
360*/
361#define RESERVEDSLOT 5
362
363
364/*
365** Reader for generic 'load' function: 'lua_load' uses the
366** stack for internal stuff, so the reader cannot change the
367** stack top. Instead, it keeps its resulting string in a
368** reserved slot inside the stack.
369*/
370static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
371 (void)(ud); /* not used */
372 luaL_checkstack(L, 2, "too many nested functions");
373 lua_pushvalue(L, 1); /* get function */
374 lua_call(L, 0, 1); /* call it */
375 if (lua_isnil(L, -1)) {
376 lua_pop(L, 1); /* pop result */
377 *size = 0;
378 return NULL;
379 }
380 else if (l_unlikely(!lua_isstring(L, -1)))
381 luaL_error(L, "reader function must return a string");
382 lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
383 return lua_tolstring(L, RESERVEDSLOT, size);
384}
385
386
387static int luaB_load (lua_State *L) {
388 int status;
389 size_t l;
390 const char *s = lua_tolstring(L, 1, &l);
391 const char *mode = luaL_optstring(L, 3, "bt");
392 int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */
393 if (s != NULL) { /* loading a string? */
394 const char *chunkname = luaL_optstring(L, 2, s);
395 status = luaL_loadbufferx(L, s, l, chunkname, mode);
396 }
397 else { /* loading from a reader function */
398 const char *chunkname = luaL_optstring(L, 2, "=(load)");
399 luaL_checktype(L, 1, LUA_TFUNCTION);
400 lua_settop(L, RESERVEDSLOT); /* create reserved slot */
401 status = lua_load(L, generic_reader, NULL, chunkname, mode);
402 }
403 return load_aux(L, status, env);
404}
405
406/* }====================================================== */
407
408
409static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
410 (void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */
411 return lua_gettop(L) - 1;
412}
413
414
415static int luaB_dofile (lua_State *L) {
416 const char *fname = luaL_optstring(L, 1, NULL);
417 lua_settop(L, 1);
418 if (l_unlikely(luaL_loadfile(L, fname) != LUA_OK))
419 return lua_error(L);
420 lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
421 return dofilecont(L, 0, 0);
422}
423
424
425static int luaB_assert (lua_State *L) {
426 if (l_likely(lua_toboolean(L, 1))) /* condition is true? */
427 return lua_gettop(L); /* return all arguments */
428 else { /* error */
429 luaL_checkany(L, 1); /* there must be a condition */
430 lua_remove(L, 1); /* remove it */
431 lua_pushliteral(L, "assertion failed!"); /* default message */
432 lua_settop(L, 1); /* leave only message (default if no other one) */
433 return luaB_error(L); /* call 'error' */
434 }
435}
436
437
438static int luaB_select (lua_State *L) {
439 int n = lua_gettop(L);
440 if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
441 lua_pushinteger(L, n-1);
442 return 1;
443 }
444 else {
445 lua_Integer i = luaL_checkinteger(L, 1);
446 if (i < 0) i = n + i;
447 else if (i > n) i = n;
448 luaL_argcheck(L, 1 <= i, 1, "index out of range");
449 return n - (int)i;
450 }
451}
452
453
454/*
455** Continuation function for 'pcall' and 'xpcall'. Both functions
456** already pushed a 'true' before doing the call, so in case of success
457** 'finishpcall' only has to return everything in the stack minus
458** 'extra' values (where 'extra' is exactly the number of items to be
459** ignored).
460*/
461static int finishpcall (lua_State *L, int status, lua_KContext extra) {
462 if (l_unlikely(status != LUA_OK && status != LUA_YIELD)) { /* error? */
463 lua_pushboolean(L, 0); /* first result (false) */
464 lua_pushvalue(L, -2); /* error message */
465 return 2; /* return false, msg */
466 }
467 else
468 return lua_gettop(L) - (int)extra; /* return all results */
469}
470
471
472static int luaB_pcall (lua_State *L) {
473 int status;
474 luaL_checkany(L, 1);
475 lua_pushboolean(L, 1); /* first result if no errors */
476 lua_insert(L, 1); /* put it in place */
477 status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall);
478 return finishpcall(L, status, 0);
479}
480
481
482/*
483** Do a protected call with error handling. After 'lua_rotate', the
484** stack will have <f, err, true, f, [args...]>; so, the function passes
485** 2 to 'finishpcall' to skip the 2 first values when returning results.
486*/
487static int luaB_xpcall (lua_State *L) {
488 int status;
489 int n = lua_gettop(L);
490 luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */
491 lua_pushboolean(L, 1); /* first result */
492 lua_pushvalue(L, 1); /* function */
493 lua_rotate(L, 3, 2); /* move them below function's arguments */
494 status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);
495 return finishpcall(L, status, 2);
496}
497
498
499static int luaB_tostring (lua_State *L) {
500 luaL_checkany(L, 1);
501 luaL_tolstring(L, 1, NULL);
502 return 1;
503}
504
505
506static const luaL_Reg base_funcs[] = {
507 {"assert", luaB_assert},
508 {"collectgarbage", luaB_collectgarbage},
509 {"dofile", luaB_dofile},
510 {"error", luaB_error},
511 {"getmetatable", luaB_getmetatable},
512 {"ipairs", luaB_ipairs},
513 {"loadfile", luaB_loadfile},
514 {"load", luaB_load},
515 {"next", luaB_next},
516 {"pairs", luaB_pairs},
517 {"pcall", luaB_pcall},
518 {"print", luaB_print},
519 {"warn", luaB_warn},
520 {"rawequal", luaB_rawequal},
521 {"rawlen", luaB_rawlen},
522 {"rawget", luaB_rawget},
523 {"rawset", luaB_rawset},
524 {"select", luaB_select},
525 {"setmetatable", luaB_setmetatable},
526 {"tonumber", luaB_tonumber},
527 {"tostring", luaB_tostring},
528 {"type", luaB_type},
529 {"xpcall", luaB_xpcall},
530 /* placeholders */
531 {LUA_GNAME, NULL},
532 {"_VERSION", NULL},
533 {NULL, NULL}
534};
535
536
537LUAMOD_API int luaopen_base (lua_State *L) {
538 /* open lib into global table */
539 lua_pushglobaltable(L);
540 luaL_setfuncs(L, base_funcs, 0);
541 /* set global _G */
542 lua_pushvalue(L, -1);
543 lua_setfield(L, -2, LUA_GNAME);
544 /* set global _VERSION */
545 lua_pushliteral(L, LUA_VERSION);
546 lua_setfield(L, -2, "_VERSION");
547 return 1;
548}
549
diff --git a/vendor/lua-5.4.8/src/lcode.c b/vendor/lua-5.4.8/src/lcode.c
new file mode 100644
index 0000000..3f78370
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lcode.c
@@ -0,0 +1,1875 @@
1/*
2** $Id: lcode.c $
3** Code generator for Lua
4** See Copyright Notice in lua.h
5*/
6
7#define lcode_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <float.h>
14#include <limits.h>
15#include <math.h>
16#include <stdlib.h>
17
18#include "lua.h"
19
20#include "lcode.h"
21#include "ldebug.h"
22#include "ldo.h"
23#include "lgc.h"
24#include "llex.h"
25#include "lmem.h"
26#include "lobject.h"
27#include "lopcodes.h"
28#include "lparser.h"
29#include "lstring.h"
30#include "ltable.h"
31#include "lvm.h"
32
33
34/* Maximum number of registers in a Lua function (must fit in 8 bits) */
35#define MAXREGS 255
36
37
38/* (note that expressions VJMP also have jumps.) */
39#define hasjumps(e) ((e)->t != (e)->f)
40
41
42static int codesJ (FuncState *fs, OpCode o, int sj, int k);
43
44
45
46/* semantic error */
47l_noret luaK_semerror (LexState *ls, const char *msg) {
48 ls->t.token = 0; /* remove "near <token>" from final message */
49 luaX_syntaxerror(ls, msg);
50}
51
52
53/*
54** If expression is a numeric constant, fills 'v' with its value
55** and returns 1. Otherwise, returns 0.
56*/
57static int tonumeral (const expdesc *e, TValue *v) {
58 if (hasjumps(e))
59 return 0; /* not a numeral */
60 switch (e->k) {
61 case VKINT:
62 if (v) setivalue(v, e->u.ival);
63 return 1;
64 case VKFLT:
65 if (v) setfltvalue(v, e->u.nval);
66 return 1;
67 default: return 0;
68 }
69}
70
71
72/*
73** Get the constant value from a constant expression
74*/
75static TValue *const2val (FuncState *fs, const expdesc *e) {
76 lua_assert(e->k == VCONST);
77 return &fs->ls->dyd->actvar.arr[e->u.info].k;
78}
79
80
81/*
82** If expression is a constant, fills 'v' with its value
83** and returns 1. Otherwise, returns 0.
84*/
85int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) {
86 if (hasjumps(e))
87 return 0; /* not a constant */
88 switch (e->k) {
89 case VFALSE:
90 setbfvalue(v);
91 return 1;
92 case VTRUE:
93 setbtvalue(v);
94 return 1;
95 case VNIL:
96 setnilvalue(v);
97 return 1;
98 case VKSTR: {
99 setsvalue(fs->ls->L, v, e->u.strval);
100 return 1;
101 }
102 case VCONST: {
103 setobj(fs->ls->L, v, const2val(fs, e));
104 return 1;
105 }
106 default: return tonumeral(e, v);
107 }
108}
109
110
111/*
112** Return the previous instruction of the current code. If there
113** may be a jump target between the current instruction and the
114** previous one, return an invalid instruction (to avoid wrong
115** optimizations).
116*/
117static Instruction *previousinstruction (FuncState *fs) {
118 static const Instruction invalidinstruction = ~(Instruction)0;
119 if (fs->pc > fs->lasttarget)
120 return &fs->f->code[fs->pc - 1]; /* previous instruction */
121 else
122 return cast(Instruction*, &invalidinstruction);
123}
124
125
126/*
127** Create a OP_LOADNIL instruction, but try to optimize: if the previous
128** instruction is also OP_LOADNIL and ranges are compatible, adjust
129** range of previous instruction instead of emitting a new one. (For
130** instance, 'local a; local b' will generate a single opcode.)
131*/
132void luaK_nil (FuncState *fs, int from, int n) {
133 int l = from + n - 1; /* last register to set nil */
134 Instruction *previous = previousinstruction(fs);
135 if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */
136 int pfrom = GETARG_A(*previous); /* get previous range */
137 int pl = pfrom + GETARG_B(*previous);
138 if ((pfrom <= from && from <= pl + 1) ||
139 (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */
140 if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */
141 if (pl > l) l = pl; /* l = max(l, pl) */
142 SETARG_A(*previous, from);
143 SETARG_B(*previous, l - from);
144 return;
145 } /* else go through */
146 }
147 luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */
148}
149
150
151/*
152** Gets the destination address of a jump instruction. Used to traverse
153** a list of jumps.
154*/
155static int getjump (FuncState *fs, int pc) {
156 int offset = GETARG_sJ(fs->f->code[pc]);
157 if (offset == NO_JUMP) /* point to itself represents end of list */
158 return NO_JUMP; /* end of list */
159 else
160 return (pc+1)+offset; /* turn offset into absolute position */
161}
162
163
164/*
165** Fix jump instruction at position 'pc' to jump to 'dest'.
166** (Jump addresses are relative in Lua)
167*/
168static void fixjump (FuncState *fs, int pc, int dest) {
169 Instruction *jmp = &fs->f->code[pc];
170 int offset = dest - (pc + 1);
171 lua_assert(dest != NO_JUMP);
172 if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ))
173 luaX_syntaxerror(fs->ls, "control structure too long");
174 lua_assert(GET_OPCODE(*jmp) == OP_JMP);
175 SETARG_sJ(*jmp, offset);
176}
177
178
179/*
180** Concatenate jump-list 'l2' into jump-list 'l1'
181*/
182void luaK_concat (FuncState *fs, int *l1, int l2) {
183 if (l2 == NO_JUMP) return; /* nothing to concatenate? */
184 else if (*l1 == NO_JUMP) /* no original list? */
185 *l1 = l2; /* 'l1' points to 'l2' */
186 else {
187 int list = *l1;
188 int next;
189 while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */
190 list = next;
191 fixjump(fs, list, l2); /* last element links to 'l2' */
192 }
193}
194
195
196/*
197** Create a jump instruction and return its position, so its destination
198** can be fixed later (with 'fixjump').
199*/
200int luaK_jump (FuncState *fs) {
201 return codesJ(fs, OP_JMP, NO_JUMP, 0);
202}
203
204
205/*
206** Code a 'return' instruction
207*/
208void luaK_ret (FuncState *fs, int first, int nret) {
209 OpCode op;
210 switch (nret) {
211 case 0: op = OP_RETURN0; break;
212 case 1: op = OP_RETURN1; break;
213 default: op = OP_RETURN; break;
214 }
215 luaK_codeABC(fs, op, first, nret + 1, 0);
216}
217
218
219/*
220** Code a "conditional jump", that is, a test or comparison opcode
221** followed by a jump. Return jump position.
222*/
223static int condjump (FuncState *fs, OpCode op, int A, int B, int C, int k) {
224 luaK_codeABCk(fs, op, A, B, C, k);
225 return luaK_jump(fs);
226}
227
228
229/*
230** returns current 'pc' and marks it as a jump target (to avoid wrong
231** optimizations with consecutive instructions not in the same basic block).
232*/
233int luaK_getlabel (FuncState *fs) {
234 fs->lasttarget = fs->pc;
235 return fs->pc;
236}
237
238
239/*
240** Returns the position of the instruction "controlling" a given
241** jump (that is, its condition), or the jump itself if it is
242** unconditional.
243*/
244static Instruction *getjumpcontrol (FuncState *fs, int pc) {
245 Instruction *pi = &fs->f->code[pc];
246 if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))
247 return pi-1;
248 else
249 return pi;
250}
251
252
253/*
254** Patch destination register for a TESTSET instruction.
255** If instruction in position 'node' is not a TESTSET, return 0 ("fails").
256** Otherwise, if 'reg' is not 'NO_REG', set it as the destination
257** register. Otherwise, change instruction to a simple 'TEST' (produces
258** no register value)
259*/
260static int patchtestreg (FuncState *fs, int node, int reg) {
261 Instruction *i = getjumpcontrol(fs, node);
262 if (GET_OPCODE(*i) != OP_TESTSET)
263 return 0; /* cannot patch other instructions */
264 if (reg != NO_REG && reg != GETARG_B(*i))
265 SETARG_A(*i, reg);
266 else {
267 /* no register to put value or register already has the value;
268 change instruction to simple test */
269 *i = CREATE_ABCk(OP_TEST, GETARG_B(*i), 0, 0, GETARG_k(*i));
270 }
271 return 1;
272}
273
274
275/*
276** Traverse a list of tests ensuring no one produces a value
277*/
278static void removevalues (FuncState *fs, int list) {
279 for (; list != NO_JUMP; list = getjump(fs, list))
280 patchtestreg(fs, list, NO_REG);
281}
282
283
284/*
285** Traverse a list of tests, patching their destination address and
286** registers: tests producing values jump to 'vtarget' (and put their
287** values in 'reg'), other tests jump to 'dtarget'.
288*/
289static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
290 int dtarget) {
291 while (list != NO_JUMP) {
292 int next = getjump(fs, list);
293 if (patchtestreg(fs, list, reg))
294 fixjump(fs, list, vtarget);
295 else
296 fixjump(fs, list, dtarget); /* jump to default target */
297 list = next;
298 }
299}
300
301
302/*
303** Path all jumps in 'list' to jump to 'target'.
304** (The assert means that we cannot fix a jump to a forward address
305** because we only know addresses once code is generated.)
306*/
307void luaK_patchlist (FuncState *fs, int list, int target) {
308 lua_assert(target <= fs->pc);
309 patchlistaux(fs, list, target, NO_REG, target);
310}
311
312
313void luaK_patchtohere (FuncState *fs, int list) {
314 int hr = luaK_getlabel(fs); /* mark "here" as a jump target */
315 luaK_patchlist(fs, list, hr);
316}
317
318
319/* limit for difference between lines in relative line info. */
320#define LIMLINEDIFF 0x80
321
322
323/*
324** Save line info for a new instruction. If difference from last line
325** does not fit in a byte, of after that many instructions, save a new
326** absolute line info; (in that case, the special value 'ABSLINEINFO'
327** in 'lineinfo' signals the existence of this absolute information.)
328** Otherwise, store the difference from last line in 'lineinfo'.
329*/
330static void savelineinfo (FuncState *fs, Proto *f, int line) {
331 int linedif = line - fs->previousline;
332 int pc = fs->pc - 1; /* last instruction coded */
333 if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ >= MAXIWTHABS) {
334 luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo,
335 f->sizeabslineinfo, AbsLineInfo, MAX_INT, "lines");
336 f->abslineinfo[fs->nabslineinfo].pc = pc;
337 f->abslineinfo[fs->nabslineinfo++].line = line;
338 linedif = ABSLINEINFO; /* signal that there is absolute information */
339 fs->iwthabs = 1; /* restart counter */
340 }
341 luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte,
342 MAX_INT, "opcodes");
343 f->lineinfo[pc] = linedif;
344 fs->previousline = line; /* last line saved */
345}
346
347
348/*
349** Remove line information from the last instruction.
350** If line information for that instruction is absolute, set 'iwthabs'
351** above its max to force the new (replacing) instruction to have
352** absolute line info, too.
353*/
354static void removelastlineinfo (FuncState *fs) {
355 Proto *f = fs->f;
356 int pc = fs->pc - 1; /* last instruction coded */
357 if (f->lineinfo[pc] != ABSLINEINFO) { /* relative line info? */
358 fs->previousline -= f->lineinfo[pc]; /* correct last line saved */
359 fs->iwthabs--; /* undo previous increment */
360 }
361 else { /* absolute line information */
362 lua_assert(f->abslineinfo[fs->nabslineinfo - 1].pc == pc);
363 fs->nabslineinfo--; /* remove it */
364 fs->iwthabs = MAXIWTHABS + 1; /* force next line info to be absolute */
365 }
366}
367
368
369/*
370** Remove the last instruction created, correcting line information
371** accordingly.
372*/
373static void removelastinstruction (FuncState *fs) {
374 removelastlineinfo(fs);
375 fs->pc--;
376}
377
378
379/*
380** Emit instruction 'i', checking for array sizes and saving also its
381** line information. Return 'i' position.
382*/
383int luaK_code (FuncState *fs, Instruction i) {
384 Proto *f = fs->f;
385 /* put new instruction in code array */
386 luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
387 MAX_INT, "opcodes");
388 f->code[fs->pc++] = i;
389 savelineinfo(fs, f, fs->ls->lastline);
390 return fs->pc - 1; /* index of new instruction */
391}
392
393
394/*
395** Format and emit an 'iABC' instruction. (Assertions check consistency
396** of parameters versus opcode.)
397*/
398int luaK_codeABCk (FuncState *fs, OpCode o, int a, int b, int c, int k) {
399 lua_assert(getOpMode(o) == iABC);
400 lua_assert(a <= MAXARG_A && b <= MAXARG_B &&
401 c <= MAXARG_C && (k & ~1) == 0);
402 return luaK_code(fs, CREATE_ABCk(o, a, b, c, k));
403}
404
405
406/*
407** Format and emit an 'iABx' instruction.
408*/
409int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {
410 lua_assert(getOpMode(o) == iABx);
411 lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx);
412 return luaK_code(fs, CREATE_ABx(o, a, bc));
413}
414
415
416/*
417** Format and emit an 'iAsBx' instruction.
418*/
419static int codeAsBx (FuncState *fs, OpCode o, int a, int bc) {
420 unsigned int b = bc + OFFSET_sBx;
421 lua_assert(getOpMode(o) == iAsBx);
422 lua_assert(a <= MAXARG_A && b <= MAXARG_Bx);
423 return luaK_code(fs, CREATE_ABx(o, a, b));
424}
425
426
427/*
428** Format and emit an 'isJ' instruction.
429*/
430static int codesJ (FuncState *fs, OpCode o, int sj, int k) {
431 unsigned int j = sj + OFFSET_sJ;
432 lua_assert(getOpMode(o) == isJ);
433 lua_assert(j <= MAXARG_sJ && (k & ~1) == 0);
434 return luaK_code(fs, CREATE_sJ(o, j, k));
435}
436
437
438/*
439** Emit an "extra argument" instruction (format 'iAx')
440*/
441static int codeextraarg (FuncState *fs, int a) {
442 lua_assert(a <= MAXARG_Ax);
443 return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a));
444}
445
446
447/*
448** Emit a "load constant" instruction, using either 'OP_LOADK'
449** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX'
450** instruction with "extra argument".
451*/
452static int luaK_codek (FuncState *fs, int reg, int k) {
453 if (k <= MAXARG_Bx)
454 return luaK_codeABx(fs, OP_LOADK, reg, k);
455 else {
456 int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);
457 codeextraarg(fs, k);
458 return p;
459 }
460}
461
462
463/*
464** Check register-stack level, keeping track of its maximum size
465** in field 'maxstacksize'
466*/
467void luaK_checkstack (FuncState *fs, int n) {
468 int newstack = fs->freereg + n;
469 if (newstack > fs->f->maxstacksize) {
470 if (newstack >= MAXREGS)
471 luaX_syntaxerror(fs->ls,
472 "function or expression needs too many registers");
473 fs->f->maxstacksize = cast_byte(newstack);
474 }
475}
476
477
478/*
479** Reserve 'n' registers in register stack
480*/
481void luaK_reserveregs (FuncState *fs, int n) {
482 luaK_checkstack(fs, n);
483 fs->freereg += n;
484}
485
486
487/*
488** Free register 'reg', if it is neither a constant index nor
489** a local variable.
490)
491*/
492static void freereg (FuncState *fs, int reg) {
493 if (reg >= luaY_nvarstack(fs)) {
494 fs->freereg--;
495 lua_assert(reg == fs->freereg);
496 }
497}
498
499
500/*
501** Free two registers in proper order
502*/
503static void freeregs (FuncState *fs, int r1, int r2) {
504 if (r1 > r2) {
505 freereg(fs, r1);
506 freereg(fs, r2);
507 }
508 else {
509 freereg(fs, r2);
510 freereg(fs, r1);
511 }
512}
513
514
515/*
516** Free register used by expression 'e' (if any)
517*/
518static void freeexp (FuncState *fs, expdesc *e) {
519 if (e->k == VNONRELOC)
520 freereg(fs, e->u.info);
521}
522
523
524/*
525** Free registers used by expressions 'e1' and 'e2' (if any) in proper
526** order.
527*/
528static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) {
529 int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1;
530 int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1;
531 freeregs(fs, r1, r2);
532}
533
534
535/*
536** Add constant 'v' to prototype's list of constants (field 'k').
537** Use scanner's table to cache position of constants in constant list
538** and try to reuse constants. Because some values should not be used
539** as keys (nil cannot be a key, integer keys can collapse with float
540** keys), the caller must provide a useful 'key' for indexing the cache.
541** Note that all functions share the same table, so entering or exiting
542** a function can make some indices wrong.
543*/
544static int addk (FuncState *fs, TValue *key, TValue *v) {
545 TValue val;
546 lua_State *L = fs->ls->L;
547 Proto *f = fs->f;
548 const TValue *idx = luaH_get(fs->ls->h, key); /* query scanner table */
549 int k, oldsize;
550 if (ttisinteger(idx)) { /* is there an index there? */
551 k = cast_int(ivalue(idx));
552 /* correct value? (warning: must distinguish floats from integers!) */
553 if (k < fs->nk && ttypetag(&f->k[k]) == ttypetag(v) &&
554 luaV_rawequalobj(&f->k[k], v))
555 return k; /* reuse index */
556 }
557 /* constant not found; create a new entry */
558 oldsize = f->sizek;
559 k = fs->nk;
560 /* numerical value does not need GC barrier;
561 table has no metatable, so it does not need to invalidate cache */
562 setivalue(&val, k);
563 luaH_finishset(L, fs->ls->h, key, idx, &val);
564 luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
565 while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
566 setobj(L, &f->k[k], v);
567 fs->nk++;
568 luaC_barrier(L, f, v);
569 return k;
570}
571
572
573/*
574** Add a string to list of constants and return its index.
575*/
576static int stringK (FuncState *fs, TString *s) {
577 TValue o;
578 setsvalue(fs->ls->L, &o, s);
579 return addk(fs, &o, &o); /* use string itself as key */
580}
581
582
583/*
584** Add an integer to list of constants and return its index.
585*/
586static int luaK_intK (FuncState *fs, lua_Integer n) {
587 TValue o;
588 setivalue(&o, n);
589 return addk(fs, &o, &o); /* use integer itself as key */
590}
591
592/*
593** Add a float to list of constants and return its index. Floats
594** with integral values need a different key, to avoid collision
595** with actual integers. To that, we add to the number its smaller
596** power-of-two fraction that is still significant in its scale.
597** For doubles, that would be 1/2^52.
598** (This method is not bulletproof: there may be another float
599** with that value, and for floats larger than 2^53 the result is
600** still an integer. At worst, this only wastes an entry with
601** a duplicate.)
602*/
603static int luaK_numberK (FuncState *fs, lua_Number r) {
604 TValue o;
605 lua_Integer ik;
606 setfltvalue(&o, r);
607 if (!luaV_flttointeger(r, &ik, F2Ieq)) /* not an integral value? */
608 return addk(fs, &o, &o); /* use number itself as key */
609 else { /* must build an alternative key */
610 const int nbm = l_floatatt(MANT_DIG);
611 const lua_Number q = l_mathop(ldexp)(l_mathop(1.0), -nbm + 1);
612 const lua_Number k = (ik == 0) ? q : r + r*q; /* new key */
613 TValue kv;
614 setfltvalue(&kv, k);
615 /* result is not an integral value, unless value is too large */
616 lua_assert(!luaV_flttointeger(k, &ik, F2Ieq) ||
617 l_mathop(fabs)(r) >= l_mathop(1e6));
618 return addk(fs, &kv, &o);
619 }
620}
621
622
623/*
624** Add a false to list of constants and return its index.
625*/
626static int boolF (FuncState *fs) {
627 TValue o;
628 setbfvalue(&o);
629 return addk(fs, &o, &o); /* use boolean itself as key */
630}
631
632
633/*
634** Add a true to list of constants and return its index.
635*/
636static int boolT (FuncState *fs) {
637 TValue o;
638 setbtvalue(&o);
639 return addk(fs, &o, &o); /* use boolean itself as key */
640}
641
642
643/*
644** Add nil to list of constants and return its index.
645*/
646static int nilK (FuncState *fs) {
647 TValue k, v;
648 setnilvalue(&v);
649 /* cannot use nil as key; instead use table itself to represent nil */
650 sethvalue(fs->ls->L, &k, fs->ls->h);
651 return addk(fs, &k, &v);
652}
653
654
655/*
656** Check whether 'i' can be stored in an 'sC' operand. Equivalent to
657** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of
658** overflows in the hidden addition inside 'int2sC'.
659*/
660static int fitsC (lua_Integer i) {
661 return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C));
662}
663
664
665/*
666** Check whether 'i' can be stored in an 'sBx' operand.
667*/
668static int fitsBx (lua_Integer i) {
669 return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx);
670}
671
672
673void luaK_int (FuncState *fs, int reg, lua_Integer i) {
674 if (fitsBx(i))
675 codeAsBx(fs, OP_LOADI, reg, cast_int(i));
676 else
677 luaK_codek(fs, reg, luaK_intK(fs, i));
678}
679
680
681static void luaK_float (FuncState *fs, int reg, lua_Number f) {
682 lua_Integer fi;
683 if (luaV_flttointeger(f, &fi, F2Ieq) && fitsBx(fi))
684 codeAsBx(fs, OP_LOADF, reg, cast_int(fi));
685 else
686 luaK_codek(fs, reg, luaK_numberK(fs, f));
687}
688
689
690/*
691** Convert a constant in 'v' into an expression description 'e'
692*/
693static void const2exp (TValue *v, expdesc *e) {
694 switch (ttypetag(v)) {
695 case LUA_VNUMINT:
696 e->k = VKINT; e->u.ival = ivalue(v);
697 break;
698 case LUA_VNUMFLT:
699 e->k = VKFLT; e->u.nval = fltvalue(v);
700 break;
701 case LUA_VFALSE:
702 e->k = VFALSE;
703 break;
704 case LUA_VTRUE:
705 e->k = VTRUE;
706 break;
707 case LUA_VNIL:
708 e->k = VNIL;
709 break;
710 case LUA_VSHRSTR: case LUA_VLNGSTR:
711 e->k = VKSTR; e->u.strval = tsvalue(v);
712 break;
713 default: lua_assert(0);
714 }
715}
716
717
718/*
719** Fix an expression to return the number of results 'nresults'.
720** 'e' must be a multi-ret expression (function call or vararg).
721*/
722void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
723 Instruction *pc = &getinstruction(fs, e);
724 if (e->k == VCALL) /* expression is an open function call? */
725 SETARG_C(*pc, nresults + 1);
726 else {
727 lua_assert(e->k == VVARARG);
728 SETARG_C(*pc, nresults + 1);
729 SETARG_A(*pc, fs->freereg);
730 luaK_reserveregs(fs, 1);
731 }
732}
733
734
735/*
736** Convert a VKSTR to a VK
737*/
738static void str2K (FuncState *fs, expdesc *e) {
739 lua_assert(e->k == VKSTR);
740 e->u.info = stringK(fs, e->u.strval);
741 e->k = VK;
742}
743
744
745/*
746** Fix an expression to return one result.
747** If expression is not a multi-ret expression (function call or
748** vararg), it already returns one result, so nothing needs to be done.
749** Function calls become VNONRELOC expressions (as its result comes
750** fixed in the base register of the call), while vararg expressions
751** become VRELOC (as OP_VARARG puts its results where it wants).
752** (Calls are created returning one result, so that does not need
753** to be fixed.)
754*/
755void luaK_setoneret (FuncState *fs, expdesc *e) {
756 if (e->k == VCALL) { /* expression is an open function call? */
757 /* already returns 1 value */
758 lua_assert(GETARG_C(getinstruction(fs, e)) == 2);
759 e->k = VNONRELOC; /* result has fixed position */
760 e->u.info = GETARG_A(getinstruction(fs, e));
761 }
762 else if (e->k == VVARARG) {
763 SETARG_C(getinstruction(fs, e), 2);
764 e->k = VRELOC; /* can relocate its simple result */
765 }
766}
767
768
769/*
770** Ensure that expression 'e' is not a variable (nor a <const>).
771** (Expression still may have jump lists.)
772*/
773void luaK_dischargevars (FuncState *fs, expdesc *e) {
774 switch (e->k) {
775 case VCONST: {
776 const2exp(const2val(fs, e), e);
777 break;
778 }
779 case VLOCAL: { /* already in a register */
780 int temp = e->u.var.ridx;
781 e->u.info = temp; /* (can't do a direct assignment; values overlap) */
782 e->k = VNONRELOC; /* becomes a non-relocatable value */
783 break;
784 }
785 case VUPVAL: { /* move value to some (pending) register */
786 e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0);
787 e->k = VRELOC;
788 break;
789 }
790 case VINDEXUP: {
791 e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx);
792 e->k = VRELOC;
793 break;
794 }
795 case VINDEXI: {
796 freereg(fs, e->u.ind.t);
797 e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx);
798 e->k = VRELOC;
799 break;
800 }
801 case VINDEXSTR: {
802 freereg(fs, e->u.ind.t);
803 e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx);
804 e->k = VRELOC;
805 break;
806 }
807 case VINDEXED: {
808 freeregs(fs, e->u.ind.t, e->u.ind.idx);
809 e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx);
810 e->k = VRELOC;
811 break;
812 }
813 case VVARARG: case VCALL: {
814 luaK_setoneret(fs, e);
815 break;
816 }
817 default: break; /* there is one value available (somewhere) */
818 }
819}
820
821
822/*
823** Ensure expression value is in register 'reg', making 'e' a
824** non-relocatable expression.
825** (Expression still may have jump lists.)
826*/
827static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
828 luaK_dischargevars(fs, e);
829 switch (e->k) {
830 case VNIL: {
831 luaK_nil(fs, reg, 1);
832 break;
833 }
834 case VFALSE: {
835 luaK_codeABC(fs, OP_LOADFALSE, reg, 0, 0);
836 break;
837 }
838 case VTRUE: {
839 luaK_codeABC(fs, OP_LOADTRUE, reg, 0, 0);
840 break;
841 }
842 case VKSTR: {
843 str2K(fs, e);
844 } /* FALLTHROUGH */
845 case VK: {
846 luaK_codek(fs, reg, e->u.info);
847 break;
848 }
849 case VKFLT: {
850 luaK_float(fs, reg, e->u.nval);
851 break;
852 }
853 case VKINT: {
854 luaK_int(fs, reg, e->u.ival);
855 break;
856 }
857 case VRELOC: {
858 Instruction *pc = &getinstruction(fs, e);
859 SETARG_A(*pc, reg); /* instruction will put result in 'reg' */
860 break;
861 }
862 case VNONRELOC: {
863 if (reg != e->u.info)
864 luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0);
865 break;
866 }
867 default: {
868 lua_assert(e->k == VJMP);
869 return; /* nothing to do... */
870 }
871 }
872 e->u.info = reg;
873 e->k = VNONRELOC;
874}
875
876
877/*
878** Ensure expression value is in a register, making 'e' a
879** non-relocatable expression.
880** (Expression still may have jump lists.)
881*/
882static void discharge2anyreg (FuncState *fs, expdesc *e) {
883 if (e->k != VNONRELOC) { /* no fixed register yet? */
884 luaK_reserveregs(fs, 1); /* get a register */
885 discharge2reg(fs, e, fs->freereg-1); /* put value there */
886 }
887}
888
889
890static int code_loadbool (FuncState *fs, int A, OpCode op) {
891 luaK_getlabel(fs); /* those instructions may be jump targets */
892 return luaK_codeABC(fs, op, A, 0, 0);
893}
894
895
896/*
897** check whether list has any jump that do not produce a value
898** or produce an inverted value
899*/
900static int need_value (FuncState *fs, int list) {
901 for (; list != NO_JUMP; list = getjump(fs, list)) {
902 Instruction i = *getjumpcontrol(fs, list);
903 if (GET_OPCODE(i) != OP_TESTSET) return 1;
904 }
905 return 0; /* not found */
906}
907
908
909/*
910** Ensures final expression result (which includes results from its
911** jump lists) is in register 'reg'.
912** If expression has jumps, need to patch these jumps either to
913** its final position or to "load" instructions (for those tests
914** that do not produce values).
915*/
916static void exp2reg (FuncState *fs, expdesc *e, int reg) {
917 discharge2reg(fs, e, reg);
918 if (e->k == VJMP) /* expression itself is a test? */
919 luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */
920 if (hasjumps(e)) {
921 int final; /* position after whole expression */
922 int p_f = NO_JUMP; /* position of an eventual LOAD false */
923 int p_t = NO_JUMP; /* position of an eventual LOAD true */
924 if (need_value(fs, e->t) || need_value(fs, e->f)) {
925 int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
926 p_f = code_loadbool(fs, reg, OP_LFALSESKIP); /* skip next inst. */
927 p_t = code_loadbool(fs, reg, OP_LOADTRUE);
928 /* jump around these booleans if 'e' is not a test */
929 luaK_patchtohere(fs, fj);
930 }
931 final = luaK_getlabel(fs);
932 patchlistaux(fs, e->f, final, reg, p_f);
933 patchlistaux(fs, e->t, final, reg, p_t);
934 }
935 e->f = e->t = NO_JUMP;
936 e->u.info = reg;
937 e->k = VNONRELOC;
938}
939
940
941/*
942** Ensures final expression result is in next available register.
943*/
944void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
945 luaK_dischargevars(fs, e);
946 freeexp(fs, e);
947 luaK_reserveregs(fs, 1);
948 exp2reg(fs, e, fs->freereg - 1);
949}
950
951
952/*
953** Ensures final expression result is in some (any) register
954** and return that register.
955*/
956int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
957 luaK_dischargevars(fs, e);
958 if (e->k == VNONRELOC) { /* expression already has a register? */
959 if (!hasjumps(e)) /* no jumps? */
960 return e->u.info; /* result is already in a register */
961 if (e->u.info >= luaY_nvarstack(fs)) { /* reg. is not a local? */
962 exp2reg(fs, e, e->u.info); /* put final result in it */
963 return e->u.info;
964 }
965 /* else expression has jumps and cannot change its register
966 to hold the jump values, because it is a local variable.
967 Go through to the default case. */
968 }
969 luaK_exp2nextreg(fs, e); /* default: use next available register */
970 return e->u.info;
971}
972
973
974/*
975** Ensures final expression result is either in a register
976** or in an upvalue.
977*/
978void luaK_exp2anyregup (FuncState *fs, expdesc *e) {
979 if (e->k != VUPVAL || hasjumps(e))
980 luaK_exp2anyreg(fs, e);
981}
982
983
984/*
985** Ensures final expression result is either in a register
986** or it is a constant.
987*/
988void luaK_exp2val (FuncState *fs, expdesc *e) {
989 if (e->k == VJMP || hasjumps(e))
990 luaK_exp2anyreg(fs, e);
991 else
992 luaK_dischargevars(fs, e);
993}
994
995
996/*
997** Try to make 'e' a K expression with an index in the range of R/K
998** indices. Return true iff succeeded.
999*/
1000static int luaK_exp2K (FuncState *fs, expdesc *e) {
1001 if (!hasjumps(e)) {
1002 int info;
1003 switch (e->k) { /* move constants to 'k' */
1004 case VTRUE: info = boolT(fs); break;
1005 case VFALSE: info = boolF(fs); break;
1006 case VNIL: info = nilK(fs); break;
1007 case VKINT: info = luaK_intK(fs, e->u.ival); break;
1008 case VKFLT: info = luaK_numberK(fs, e->u.nval); break;
1009 case VKSTR: info = stringK(fs, e->u.strval); break;
1010 case VK: info = e->u.info; break;
1011 default: return 0; /* not a constant */
1012 }
1013 if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */
1014 e->k = VK; /* make expression a 'K' expression */
1015 e->u.info = info;
1016 return 1;
1017 }
1018 }
1019 /* else, expression doesn't fit; leave it unchanged */
1020 return 0;
1021}
1022
1023
1024/*
1025** Ensures final expression result is in a valid R/K index
1026** (that is, it is either in a register or in 'k' with an index
1027** in the range of R/K indices).
1028** Returns 1 iff expression is K.
1029*/
1030static int exp2RK (FuncState *fs, expdesc *e) {
1031 if (luaK_exp2K(fs, e))
1032 return 1;
1033 else { /* not a constant in the right range: put it in a register */
1034 luaK_exp2anyreg(fs, e);
1035 return 0;
1036 }
1037}
1038
1039
1040static void codeABRK (FuncState *fs, OpCode o, int a, int b,
1041 expdesc *ec) {
1042 int k = exp2RK(fs, ec);
1043 luaK_codeABCk(fs, o, a, b, ec->u.info, k);
1044}
1045
1046
1047/*
1048** Generate code to store result of expression 'ex' into variable 'var'.
1049*/
1050void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
1051 switch (var->k) {
1052 case VLOCAL: {
1053 freeexp(fs, ex);
1054 exp2reg(fs, ex, var->u.var.ridx); /* compute 'ex' into proper place */
1055 return;
1056 }
1057 case VUPVAL: {
1058 int e = luaK_exp2anyreg(fs, ex);
1059 luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0);
1060 break;
1061 }
1062 case VINDEXUP: {
1063 codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex);
1064 break;
1065 }
1066 case VINDEXI: {
1067 codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex);
1068 break;
1069 }
1070 case VINDEXSTR: {
1071 codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex);
1072 break;
1073 }
1074 case VINDEXED: {
1075 codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex);
1076 break;
1077 }
1078 default: lua_assert(0); /* invalid var kind to store */
1079 }
1080 freeexp(fs, ex);
1081}
1082
1083
1084/*
1085** Emit SELF instruction (convert expression 'e' into 'e:key(e,').
1086*/
1087void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
1088 int ereg;
1089 luaK_exp2anyreg(fs, e);
1090 ereg = e->u.info; /* register where 'e' was placed */
1091 freeexp(fs, e);
1092 e->u.info = fs->freereg; /* base register for op_self */
1093 e->k = VNONRELOC; /* self expression has a fixed register */
1094 luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */
1095 codeABRK(fs, OP_SELF, e->u.info, ereg, key);
1096 freeexp(fs, key);
1097}
1098
1099
1100/*
1101** Negate condition 'e' (where 'e' is a comparison).
1102*/
1103static void negatecondition (FuncState *fs, expdesc *e) {
1104 Instruction *pc = getjumpcontrol(fs, e->u.info);
1105 lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
1106 GET_OPCODE(*pc) != OP_TEST);
1107 SETARG_k(*pc, (GETARG_k(*pc) ^ 1));
1108}
1109
1110
1111/*
1112** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond'
1113** is true, code will jump if 'e' is true.) Return jump position.
1114** Optimize when 'e' is 'not' something, inverting the condition
1115** and removing the 'not'.
1116*/
1117static int jumponcond (FuncState *fs, expdesc *e, int cond) {
1118 if (e->k == VRELOC) {
1119 Instruction ie = getinstruction(fs, e);
1120 if (GET_OPCODE(ie) == OP_NOT) {
1121 removelastinstruction(fs); /* remove previous OP_NOT */
1122 return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond);
1123 }
1124 /* else go through */
1125 }
1126 discharge2anyreg(fs, e);
1127 freeexp(fs, e);
1128 return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond);
1129}
1130
1131
1132/*
1133** Emit code to go through if 'e' is true, jump otherwise.
1134*/
1135void luaK_goiftrue (FuncState *fs, expdesc *e) {
1136 int pc; /* pc of new jump */
1137 luaK_dischargevars(fs, e);
1138 switch (e->k) {
1139 case VJMP: { /* condition? */
1140 negatecondition(fs, e); /* jump when it is false */
1141 pc = e->u.info; /* save jump position */
1142 break;
1143 }
1144 case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
1145 pc = NO_JUMP; /* always true; do nothing */
1146 break;
1147 }
1148 default: {
1149 pc = jumponcond(fs, e, 0); /* jump when false */
1150 break;
1151 }
1152 }
1153 luaK_concat(fs, &e->f, pc); /* insert new jump in false list */
1154 luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */
1155 e->t = NO_JUMP;
1156}
1157
1158
1159/*
1160** Emit code to go through if 'e' is false, jump otherwise.
1161*/
1162void luaK_goiffalse (FuncState *fs, expdesc *e) {
1163 int pc; /* pc of new jump */
1164 luaK_dischargevars(fs, e);
1165 switch (e->k) {
1166 case VJMP: {
1167 pc = e->u.info; /* already jump if true */
1168 break;
1169 }
1170 case VNIL: case VFALSE: {
1171 pc = NO_JUMP; /* always false; do nothing */
1172 break;
1173 }
1174 default: {
1175 pc = jumponcond(fs, e, 1); /* jump if true */
1176 break;
1177 }
1178 }
1179 luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */
1180 luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */
1181 e->f = NO_JUMP;
1182}
1183
1184
1185/*
1186** Code 'not e', doing constant folding.
1187*/
1188static void codenot (FuncState *fs, expdesc *e) {
1189 switch (e->k) {
1190 case VNIL: case VFALSE: {
1191 e->k = VTRUE; /* true == not nil == not false */
1192 break;
1193 }
1194 case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
1195 e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */
1196 break;
1197 }
1198 case VJMP: {
1199 negatecondition(fs, e);
1200 break;
1201 }
1202 case VRELOC:
1203 case VNONRELOC: {
1204 discharge2anyreg(fs, e);
1205 freeexp(fs, e);
1206 e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0);
1207 e->k = VRELOC;
1208 break;
1209 }
1210 default: lua_assert(0); /* cannot happen */
1211 }
1212 /* interchange true and false lists */
1213 { int temp = e->f; e->f = e->t; e->t = temp; }
1214 removevalues(fs, e->f); /* values are useless when negated */
1215 removevalues(fs, e->t);
1216}
1217
1218
1219/*
1220** Check whether expression 'e' is a short literal string
1221*/
1222static int isKstr (FuncState *fs, expdesc *e) {
1223 return (e->k == VK && !hasjumps(e) && e->u.info <= MAXARG_B &&
1224 ttisshrstring(&fs->f->k[e->u.info]));
1225}
1226
1227/*
1228** Check whether expression 'e' is a literal integer.
1229*/
1230static int isKint (expdesc *e) {
1231 return (e->k == VKINT && !hasjumps(e));
1232}
1233
1234
1235/*
1236** Check whether expression 'e' is a literal integer in
1237** proper range to fit in register C
1238*/
1239static int isCint (expdesc *e) {
1240 return isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C));
1241}
1242
1243
1244/*
1245** Check whether expression 'e' is a literal integer in
1246** proper range to fit in register sC
1247*/
1248static int isSCint (expdesc *e) {
1249 return isKint(e) && fitsC(e->u.ival);
1250}
1251
1252
1253/*
1254** Check whether expression 'e' is a literal integer or float in
1255** proper range to fit in a register (sB or sC).
1256*/
1257static int isSCnumber (expdesc *e, int *pi, int *isfloat) {
1258 lua_Integer i;
1259 if (e->k == VKINT)
1260 i = e->u.ival;
1261 else if (e->k == VKFLT && luaV_flttointeger(e->u.nval, &i, F2Ieq))
1262 *isfloat = 1;
1263 else
1264 return 0; /* not a number */
1265 if (!hasjumps(e) && fitsC(i)) {
1266 *pi = int2sC(cast_int(i));
1267 return 1;
1268 }
1269 else
1270 return 0;
1271}
1272
1273
1274/*
1275** Create expression 't[k]'. 't' must have its final result already in a
1276** register or upvalue. Upvalues can only be indexed by literal strings.
1277** Keys can be literal strings in the constant table or arbitrary
1278** values in registers.
1279*/
1280void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
1281 if (k->k == VKSTR)
1282 str2K(fs, k);
1283 lua_assert(!hasjumps(t) &&
1284 (t->k == VLOCAL || t->k == VNONRELOC || t->k == VUPVAL));
1285 if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non 'Kstr'? */
1286 luaK_exp2anyreg(fs, t); /* put it in a register */
1287 if (t->k == VUPVAL) {
1288 int temp = t->u.info; /* upvalue index */
1289 lua_assert(isKstr(fs, k));
1290 t->u.ind.t = temp; /* (can't do a direct assignment; values overlap) */
1291 t->u.ind.idx = k->u.info; /* literal short string */
1292 t->k = VINDEXUP;
1293 }
1294 else {
1295 /* register index of the table */
1296 t->u.ind.t = (t->k == VLOCAL) ? t->u.var.ridx: t->u.info;
1297 if (isKstr(fs, k)) {
1298 t->u.ind.idx = k->u.info; /* literal short string */
1299 t->k = VINDEXSTR;
1300 }
1301 else if (isCint(k)) {
1302 t->u.ind.idx = cast_int(k->u.ival); /* int. constant in proper range */
1303 t->k = VINDEXI;
1304 }
1305 else {
1306 t->u.ind.idx = luaK_exp2anyreg(fs, k); /* register */
1307 t->k = VINDEXED;
1308 }
1309 }
1310}
1311
1312
1313/*
1314** Return false if folding can raise an error.
1315** Bitwise operations need operands convertible to integers; division
1316** operations cannot have 0 as divisor.
1317*/
1318static int validop (int op, TValue *v1, TValue *v2) {
1319 switch (op) {
1320 case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
1321 case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */
1322 lua_Integer i;
1323 return (luaV_tointegerns(v1, &i, LUA_FLOORN2I) &&
1324 luaV_tointegerns(v2, &i, LUA_FLOORN2I));
1325 }
1326 case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */
1327 return (nvalue(v2) != 0);
1328 default: return 1; /* everything else is valid */
1329 }
1330}
1331
1332
1333/*
1334** Try to "constant-fold" an operation; return 1 iff successful.
1335** (In this case, 'e1' has the final result.)
1336*/
1337static int constfolding (FuncState *fs, int op, expdesc *e1,
1338 const expdesc *e2) {
1339 TValue v1, v2, res;
1340 if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
1341 return 0; /* non-numeric operands or not safe to fold */
1342 luaO_rawarith(fs->ls->L, op, &v1, &v2, &res); /* does operation */
1343 if (ttisinteger(&res)) {
1344 e1->k = VKINT;
1345 e1->u.ival = ivalue(&res);
1346 }
1347 else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */
1348 lua_Number n = fltvalue(&res);
1349 if (luai_numisnan(n) || n == 0)
1350 return 0;
1351 e1->k = VKFLT;
1352 e1->u.nval = n;
1353 }
1354 return 1;
1355}
1356
1357
1358/*
1359** Convert a BinOpr to an OpCode (ORDER OPR - ORDER OP)
1360*/
1361l_sinline OpCode binopr2op (BinOpr opr, BinOpr baser, OpCode base) {
1362 lua_assert(baser <= opr &&
1363 ((baser == OPR_ADD && opr <= OPR_SHR) ||
1364 (baser == OPR_LT && opr <= OPR_LE)));
1365 return cast(OpCode, (cast_int(opr) - cast_int(baser)) + cast_int(base));
1366}
1367
1368
1369/*
1370** Convert a UnOpr to an OpCode (ORDER OPR - ORDER OP)
1371*/
1372l_sinline OpCode unopr2op (UnOpr opr) {
1373 return cast(OpCode, (cast_int(opr) - cast_int(OPR_MINUS)) +
1374 cast_int(OP_UNM));
1375}
1376
1377
1378/*
1379** Convert a BinOpr to a tag method (ORDER OPR - ORDER TM)
1380*/
1381l_sinline TMS binopr2TM (BinOpr opr) {
1382 lua_assert(OPR_ADD <= opr && opr <= OPR_SHR);
1383 return cast(TMS, (cast_int(opr) - cast_int(OPR_ADD)) + cast_int(TM_ADD));
1384}
1385
1386
1387/*
1388** Emit code for unary expressions that "produce values"
1389** (everything but 'not').
1390** Expression to produce final result will be encoded in 'e'.
1391*/
1392static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) {
1393 int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */
1394 freeexp(fs, e);
1395 e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */
1396 e->k = VRELOC; /* all those operations are relocatable */
1397 luaK_fixline(fs, line);
1398}
1399
1400
1401/*
1402** Emit code for binary expressions that "produce values"
1403** (everything but logical operators 'and'/'or' and comparison
1404** operators).
1405** Expression to produce final result will be encoded in 'e1'.
1406*/
1407static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2,
1408 OpCode op, int v2, int flip, int line,
1409 OpCode mmop, TMS event) {
1410 int v1 = luaK_exp2anyreg(fs, e1);
1411 int pc = luaK_codeABCk(fs, op, 0, v1, v2, 0);
1412 freeexps(fs, e1, e2);
1413 e1->u.info = pc;
1414 e1->k = VRELOC; /* all those operations are relocatable */
1415 luaK_fixline(fs, line);
1416 luaK_codeABCk(fs, mmop, v1, v2, event, flip); /* to call metamethod */
1417 luaK_fixline(fs, line);
1418}
1419
1420
1421/*
1422** Emit code for binary expressions that "produce values" over
1423** two registers.
1424*/
1425static void codebinexpval (FuncState *fs, BinOpr opr,
1426 expdesc *e1, expdesc *e2, int line) {
1427 OpCode op = binopr2op(opr, OPR_ADD, OP_ADD);
1428 int v2 = luaK_exp2anyreg(fs, e2); /* make sure 'e2' is in a register */
1429 /* 'e1' must be already in a register or it is a constant */
1430 lua_assert((VNIL <= e1->k && e1->k <= VKSTR) ||
1431 e1->k == VNONRELOC || e1->k == VRELOC);
1432 lua_assert(OP_ADD <= op && op <= OP_SHR);
1433 finishbinexpval(fs, e1, e2, op, v2, 0, line, OP_MMBIN, binopr2TM(opr));
1434}
1435
1436
1437/*
1438** Code binary operators with immediate operands.
1439*/
1440static void codebini (FuncState *fs, OpCode op,
1441 expdesc *e1, expdesc *e2, int flip, int line,
1442 TMS event) {
1443 int v2 = int2sC(cast_int(e2->u.ival)); /* immediate operand */
1444 lua_assert(e2->k == VKINT);
1445 finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINI, event);
1446}
1447
1448
1449/*
1450** Code binary operators with K operand.
1451*/
1452static void codebinK (FuncState *fs, BinOpr opr,
1453 expdesc *e1, expdesc *e2, int flip, int line) {
1454 TMS event = binopr2TM(opr);
1455 int v2 = e2->u.info; /* K index */
1456 OpCode op = binopr2op(opr, OPR_ADD, OP_ADDK);
1457 finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, event);
1458}
1459
1460
1461/* Try to code a binary operator negating its second operand.
1462** For the metamethod, 2nd operand must keep its original value.
1463*/
1464static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2,
1465 OpCode op, int line, TMS event) {
1466 if (!isKint(e2))
1467 return 0; /* not an integer constant */
1468 else {
1469 lua_Integer i2 = e2->u.ival;
1470 if (!(fitsC(i2) && fitsC(-i2)))
1471 return 0; /* not in the proper range */
1472 else { /* operating a small integer constant */
1473 int v2 = cast_int(i2);
1474 finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event);
1475 /* correct metamethod argument */
1476 SETARG_B(fs->f->code[fs->pc - 1], int2sC(v2));
1477 return 1; /* successfully coded */
1478 }
1479 }
1480}
1481
1482
1483static void swapexps (expdesc *e1, expdesc *e2) {
1484 expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */
1485}
1486
1487
1488/*
1489** Code binary operators with no constant operand.
1490*/
1491static void codebinNoK (FuncState *fs, BinOpr opr,
1492 expdesc *e1, expdesc *e2, int flip, int line) {
1493 if (flip)
1494 swapexps(e1, e2); /* back to original order */
1495 codebinexpval(fs, opr, e1, e2, line); /* use standard operators */
1496}
1497
1498
1499/*
1500** Code arithmetic operators ('+', '-', ...). If second operand is a
1501** constant in the proper range, use variant opcodes with K operands.
1502*/
1503static void codearith (FuncState *fs, BinOpr opr,
1504 expdesc *e1, expdesc *e2, int flip, int line) {
1505 if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) /* K operand? */
1506 codebinK(fs, opr, e1, e2, flip, line);
1507 else /* 'e2' is neither an immediate nor a K operand */
1508 codebinNoK(fs, opr, e1, e2, flip, line);
1509}
1510
1511
1512/*
1513** Code commutative operators ('+', '*'). If first operand is a
1514** numeric constant, change order of operands to try to use an
1515** immediate or K operator.
1516*/
1517static void codecommutative (FuncState *fs, BinOpr op,
1518 expdesc *e1, expdesc *e2, int line) {
1519 int flip = 0;
1520 if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */
1521 swapexps(e1, e2); /* change order */
1522 flip = 1;
1523 }
1524 if (op == OPR_ADD && isSCint(e2)) /* immediate operand? */
1525 codebini(fs, OP_ADDI, e1, e2, flip, line, TM_ADD);
1526 else
1527 codearith(fs, op, e1, e2, flip, line);
1528}
1529
1530
1531/*
1532** Code bitwise operations; they are all commutative, so the function
1533** tries to put an integer constant as the 2nd operand (a K operand).
1534*/
1535static void codebitwise (FuncState *fs, BinOpr opr,
1536 expdesc *e1, expdesc *e2, int line) {
1537 int flip = 0;
1538 if (e1->k == VKINT) {
1539 swapexps(e1, e2); /* 'e2' will be the constant operand */
1540 flip = 1;
1541 }
1542 if (e2->k == VKINT && luaK_exp2K(fs, e2)) /* K operand? */
1543 codebinK(fs, opr, e1, e2, flip, line);
1544 else /* no constants */
1545 codebinNoK(fs, opr, e1, e2, flip, line);
1546}
1547
1548
1549/*
1550** Emit code for order comparisons. When using an immediate operand,
1551** 'isfloat' tells whether the original value was a float.
1552*/
1553static void codeorder (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {
1554 int r1, r2;
1555 int im;
1556 int isfloat = 0;
1557 OpCode op;
1558 if (isSCnumber(e2, &im, &isfloat)) {
1559 /* use immediate operand */
1560 r1 = luaK_exp2anyreg(fs, e1);
1561 r2 = im;
1562 op = binopr2op(opr, OPR_LT, OP_LTI);
1563 }
1564 else if (isSCnumber(e1, &im, &isfloat)) {
1565 /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */
1566 r1 = luaK_exp2anyreg(fs, e2);
1567 r2 = im;
1568 op = binopr2op(opr, OPR_LT, OP_GTI);
1569 }
1570 else { /* regular case, compare two registers */
1571 r1 = luaK_exp2anyreg(fs, e1);
1572 r2 = luaK_exp2anyreg(fs, e2);
1573 op = binopr2op(opr, OPR_LT, OP_LT);
1574 }
1575 freeexps(fs, e1, e2);
1576 e1->u.info = condjump(fs, op, r1, r2, isfloat, 1);
1577 e1->k = VJMP;
1578}
1579
1580
1581/*
1582** Emit code for equality comparisons ('==', '~=').
1583** 'e1' was already put as RK by 'luaK_infix'.
1584*/
1585static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {
1586 int r1, r2;
1587 int im;
1588 int isfloat = 0; /* not needed here, but kept for symmetry */
1589 OpCode op;
1590 if (e1->k != VNONRELOC) {
1591 lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT);
1592 swapexps(e1, e2);
1593 }
1594 r1 = luaK_exp2anyreg(fs, e1); /* 1st expression must be in register */
1595 if (isSCnumber(e2, &im, &isfloat)) {
1596 op = OP_EQI;
1597 r2 = im; /* immediate operand */
1598 }
1599 else if (exp2RK(fs, e2)) { /* 2nd expression is constant? */
1600 op = OP_EQK;
1601 r2 = e2->u.info; /* constant index */
1602 }
1603 else {
1604 op = OP_EQ; /* will compare two registers */
1605 r2 = luaK_exp2anyreg(fs, e2);
1606 }
1607 freeexps(fs, e1, e2);
1608 e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ));
1609 e1->k = VJMP;
1610}
1611
1612
1613/*
1614** Apply prefix operation 'op' to expression 'e'.
1615*/
1616void luaK_prefix (FuncState *fs, UnOpr opr, expdesc *e, int line) {
1617 static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP};
1618 luaK_dischargevars(fs, e);
1619 switch (opr) {
1620 case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */
1621 if (constfolding(fs, opr + LUA_OPUNM, e, &ef))
1622 break;
1623 /* else */ /* FALLTHROUGH */
1624 case OPR_LEN:
1625 codeunexpval(fs, unopr2op(opr), e, line);
1626 break;
1627 case OPR_NOT: codenot(fs, e); break;
1628 default: lua_assert(0);
1629 }
1630}
1631
1632
1633/*
1634** Process 1st operand 'v' of binary operation 'op' before reading
1635** 2nd operand.
1636*/
1637void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
1638 luaK_dischargevars(fs, v);
1639 switch (op) {
1640 case OPR_AND: {
1641 luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */
1642 break;
1643 }
1644 case OPR_OR: {
1645 luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */
1646 break;
1647 }
1648 case OPR_CONCAT: {
1649 luaK_exp2nextreg(fs, v); /* operand must be on the stack */
1650 break;
1651 }
1652 case OPR_ADD: case OPR_SUB:
1653 case OPR_MUL: case OPR_DIV: case OPR_IDIV:
1654 case OPR_MOD: case OPR_POW:
1655 case OPR_BAND: case OPR_BOR: case OPR_BXOR:
1656 case OPR_SHL: case OPR_SHR: {
1657 if (!tonumeral(v, NULL))
1658 luaK_exp2anyreg(fs, v);
1659 /* else keep numeral, which may be folded or used as an immediate
1660 operand */
1661 break;
1662 }
1663 case OPR_EQ: case OPR_NE: {
1664 if (!tonumeral(v, NULL))
1665 exp2RK(fs, v);
1666 /* else keep numeral, which may be an immediate operand */
1667 break;
1668 }
1669 case OPR_LT: case OPR_LE:
1670 case OPR_GT: case OPR_GE: {
1671 int dummy, dummy2;
1672 if (!isSCnumber(v, &dummy, &dummy2))
1673 luaK_exp2anyreg(fs, v);
1674 /* else keep numeral, which may be an immediate operand */
1675 break;
1676 }
1677 default: lua_assert(0);
1678 }
1679}
1680
1681/*
1682** Create code for '(e1 .. e2)'.
1683** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))',
1684** because concatenation is right associative), merge both CONCATs.
1685*/
1686static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) {
1687 Instruction *ie2 = previousinstruction(fs);
1688 if (GET_OPCODE(*ie2) == OP_CONCAT) { /* is 'e2' a concatenation? */
1689 int n = GETARG_B(*ie2); /* # of elements concatenated in 'e2' */
1690 lua_assert(e1->u.info + 1 == GETARG_A(*ie2));
1691 freeexp(fs, e2);
1692 SETARG_A(*ie2, e1->u.info); /* correct first element ('e1') */
1693 SETARG_B(*ie2, n + 1); /* will concatenate one more element */
1694 }
1695 else { /* 'e2' is not a concatenation */
1696 luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0); /* new concat opcode */
1697 freeexp(fs, e2);
1698 luaK_fixline(fs, line);
1699 }
1700}
1701
1702
1703/*
1704** Finalize code for binary operation, after reading 2nd operand.
1705*/
1706void luaK_posfix (FuncState *fs, BinOpr opr,
1707 expdesc *e1, expdesc *e2, int line) {
1708 luaK_dischargevars(fs, e2);
1709 if (foldbinop(opr) && constfolding(fs, opr + LUA_OPADD, e1, e2))
1710 return; /* done by folding */
1711 switch (opr) {
1712 case OPR_AND: {
1713 lua_assert(e1->t == NO_JUMP); /* list closed by 'luaK_infix' */
1714 luaK_concat(fs, &e2->f, e1->f);
1715 *e1 = *e2;
1716 break;
1717 }
1718 case OPR_OR: {
1719 lua_assert(e1->f == NO_JUMP); /* list closed by 'luaK_infix' */
1720 luaK_concat(fs, &e2->t, e1->t);
1721 *e1 = *e2;
1722 break;
1723 }
1724 case OPR_CONCAT: { /* e1 .. e2 */
1725 luaK_exp2nextreg(fs, e2);
1726 codeconcat(fs, e1, e2, line);
1727 break;
1728 }
1729 case OPR_ADD: case OPR_MUL: {
1730 codecommutative(fs, opr, e1, e2, line);
1731 break;
1732 }
1733 case OPR_SUB: {
1734 if (finishbinexpneg(fs, e1, e2, OP_ADDI, line, TM_SUB))
1735 break; /* coded as (r1 + -I) */
1736 /* ELSE */
1737 } /* FALLTHROUGH */
1738 case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: {
1739 codearith(fs, opr, e1, e2, 0, line);
1740 break;
1741 }
1742 case OPR_BAND: case OPR_BOR: case OPR_BXOR: {
1743 codebitwise(fs, opr, e1, e2, line);
1744 break;
1745 }
1746 case OPR_SHL: {
1747 if (isSCint(e1)) {
1748 swapexps(e1, e2);
1749 codebini(fs, OP_SHLI, e1, e2, 1, line, TM_SHL); /* I << r2 */
1750 }
1751 else if (finishbinexpneg(fs, e1, e2, OP_SHRI, line, TM_SHL)) {
1752 /* coded as (r1 >> -I) */;
1753 }
1754 else /* regular case (two registers) */
1755 codebinexpval(fs, opr, e1, e2, line);
1756 break;
1757 }
1758 case OPR_SHR: {
1759 if (isSCint(e2))
1760 codebini(fs, OP_SHRI, e1, e2, 0, line, TM_SHR); /* r1 >> I */
1761 else /* regular case (two registers) */
1762 codebinexpval(fs, opr, e1, e2, line);
1763 break;
1764 }
1765 case OPR_EQ: case OPR_NE: {
1766 codeeq(fs, opr, e1, e2);
1767 break;
1768 }
1769 case OPR_GT: case OPR_GE: {
1770 /* '(a > b)' <=> '(b < a)'; '(a >= b)' <=> '(b <= a)' */
1771 swapexps(e1, e2);
1772 opr = cast(BinOpr, (opr - OPR_GT) + OPR_LT);
1773 } /* FALLTHROUGH */
1774 case OPR_LT: case OPR_LE: {
1775 codeorder(fs, opr, e1, e2);
1776 break;
1777 }
1778 default: lua_assert(0);
1779 }
1780}
1781
1782
1783/*
1784** Change line information associated with current position, by removing
1785** previous info and adding it again with new line.
1786*/
1787void luaK_fixline (FuncState *fs, int line) {
1788 removelastlineinfo(fs);
1789 savelineinfo(fs, fs->f, line);
1790}
1791
1792
1793void luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize) {
1794 Instruction *inst = &fs->f->code[pc];
1795 int rb = (hsize != 0) ? luaO_ceillog2(hsize) + 1 : 0; /* hash size */
1796 int extra = asize / (MAXARG_C + 1); /* higher bits of array size */
1797 int rc = asize % (MAXARG_C + 1); /* lower bits of array size */
1798 int k = (extra > 0); /* true iff needs extra argument */
1799 *inst = CREATE_ABCk(OP_NEWTABLE, ra, rb, rc, k);
1800 *(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra);
1801}
1802
1803
1804/*
1805** Emit a SETLIST instruction.
1806** 'base' is register that keeps table;
1807** 'nelems' is #table plus those to be stored now;
1808** 'tostore' is number of values (in registers 'base + 1',...) to add to
1809** table (or LUA_MULTRET to add up to stack top).
1810*/
1811void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
1812 lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH);
1813 if (tostore == LUA_MULTRET)
1814 tostore = 0;
1815 if (nelems <= MAXARG_C)
1816 luaK_codeABC(fs, OP_SETLIST, base, tostore, nelems);
1817 else {
1818 int extra = nelems / (MAXARG_C + 1);
1819 nelems %= (MAXARG_C + 1);
1820 luaK_codeABCk(fs, OP_SETLIST, base, tostore, nelems, 1);
1821 codeextraarg(fs, extra);
1822 }
1823 fs->freereg = base + 1; /* free registers with list values */
1824}
1825
1826
1827/*
1828** return the final target of a jump (skipping jumps to jumps)
1829*/
1830static int finaltarget (Instruction *code, int i) {
1831 int count;
1832 for (count = 0; count < 100; count++) { /* avoid infinite loops */
1833 Instruction pc = code[i];
1834 if (GET_OPCODE(pc) != OP_JMP)
1835 break;
1836 else
1837 i += GETARG_sJ(pc) + 1;
1838 }
1839 return i;
1840}
1841
1842
1843/*
1844** Do a final pass over the code of a function, doing small peephole
1845** optimizations and adjustments.
1846*/
1847void luaK_finish (FuncState *fs) {
1848 int i;
1849 Proto *p = fs->f;
1850 for (i = 0; i < fs->pc; i++) {
1851 Instruction *pc = &p->code[i];
1852 lua_assert(i == 0 || isOT(*(pc - 1)) == isIT(*pc));
1853 switch (GET_OPCODE(*pc)) {
1854 case OP_RETURN0: case OP_RETURN1: {
1855 if (!(fs->needclose || p->is_vararg))
1856 break; /* no extra work */
1857 /* else use OP_RETURN to do the extra work */
1858 SET_OPCODE(*pc, OP_RETURN);
1859 } /* FALLTHROUGH */
1860 case OP_RETURN: case OP_TAILCALL: {
1861 if (fs->needclose)
1862 SETARG_k(*pc, 1); /* signal that it needs to close */
1863 if (p->is_vararg)
1864 SETARG_C(*pc, p->numparams + 1); /* signal that it is vararg */
1865 break;
1866 }
1867 case OP_JMP: {
1868 int target = finaltarget(p->code, i);
1869 fixjump(fs, i, target);
1870 break;
1871 }
1872 default: break;
1873 }
1874 }
1875}
diff --git a/vendor/lua-5.4.8/src/lcode.h b/vendor/lua-5.4.8/src/lcode.h
new file mode 100644
index 0000000..0b971fc
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lcode.h
@@ -0,0 +1,101 @@
1/*
2** $Id: lcode.h $
3** Code generator for Lua
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lcode_h
8#define lcode_h
9
10#include "llex.h"
11#include "lobject.h"
12#include "lopcodes.h"
13#include "lparser.h"
14
15
16/*
17** Marks the end of a patch list. It is an invalid value both as an absolute
18** address, and as a list link (would link an element to itself).
19*/
20#define NO_JUMP (-1)
21
22
23/*
24** grep "ORDER OPR" if you change these enums (ORDER OP)
25*/
26typedef enum BinOpr {
27 /* arithmetic operators */
28 OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW,
29 OPR_DIV, OPR_IDIV,
30 /* bitwise operators */
31 OPR_BAND, OPR_BOR, OPR_BXOR,
32 OPR_SHL, OPR_SHR,
33 /* string operator */
34 OPR_CONCAT,
35 /* comparison operators */
36 OPR_EQ, OPR_LT, OPR_LE,
37 OPR_NE, OPR_GT, OPR_GE,
38 /* logical operators */
39 OPR_AND, OPR_OR,
40 OPR_NOBINOPR
41} BinOpr;
42
43
44/* true if operation is foldable (that is, it is arithmetic or bitwise) */
45#define foldbinop(op) ((op) <= OPR_SHR)
46
47
48#define luaK_codeABC(fs,o,a,b,c) luaK_codeABCk(fs,o,a,b,c,0)
49
50
51typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
52
53
54/* get (pointer to) instruction of given 'expdesc' */
55#define getinstruction(fs,e) ((fs)->f->code[(e)->u.info])
56
57
58#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET)
59
60#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t)
61
62LUAI_FUNC int luaK_code (FuncState *fs, Instruction i);
63LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);
64LUAI_FUNC int luaK_codeABCk (FuncState *fs, OpCode o, int A,
65 int B, int C, int k);
66LUAI_FUNC int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v);
67LUAI_FUNC void luaK_fixline (FuncState *fs, int line);
68LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);
69LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);
70LUAI_FUNC void luaK_checkstack (FuncState *fs, int n);
71LUAI_FUNC void luaK_int (FuncState *fs, int reg, lua_Integer n);
72LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);
73LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e);
74LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e);
75LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e);
76LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e);
77LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key);
78LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k);
79LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e);
80LUAI_FUNC void luaK_goiffalse (FuncState *fs, expdesc *e);
81LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e);
82LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults);
83LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e);
84LUAI_FUNC int luaK_jump (FuncState *fs);
85LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret);
86LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target);
87LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list);
88LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);
89LUAI_FUNC int luaK_getlabel (FuncState *fs);
90LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line);
91LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v);
92LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1,
93 expdesc *v2, int line);
94LUAI_FUNC void luaK_settablesize (FuncState *fs, int pc,
95 int ra, int asize, int hsize);
96LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore);
97LUAI_FUNC void luaK_finish (FuncState *fs);
98LUAI_FUNC l_noret luaK_semerror (LexState *ls, const char *msg);
99
100
101#endif
diff --git a/vendor/lua-5.4.8/src/lcorolib.c b/vendor/lua-5.4.8/src/lcorolib.c
new file mode 100644
index 0000000..c64adf0
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lcorolib.c
@@ -0,0 +1,210 @@
1/*
2** $Id: lcorolib.c $
3** Coroutine Library
4** See Copyright Notice in lua.h
5*/
6
7#define lcorolib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <stdlib.h>
14
15#include "lua.h"
16
17#include "lauxlib.h"
18#include "lualib.h"
19
20
21static lua_State *getco (lua_State *L) {
22 lua_State *co = lua_tothread(L, 1);
23 luaL_argexpected(L, co, 1, "thread");
24 return co;
25}
26
27
28/*
29** Resumes a coroutine. Returns the number of results for non-error
30** cases or -1 for errors.
31*/
32static int auxresume (lua_State *L, lua_State *co, int narg) {
33 int status, nres;
34 if (l_unlikely(!lua_checkstack(co, narg))) {
35 lua_pushliteral(L, "too many arguments to resume");
36 return -1; /* error flag */
37 }
38 lua_xmove(L, co, narg);
39 status = lua_resume(co, L, narg, &nres);
40 if (l_likely(status == LUA_OK || status == LUA_YIELD)) {
41 if (l_unlikely(!lua_checkstack(L, nres + 1))) {
42 lua_pop(co, nres); /* remove results anyway */
43 lua_pushliteral(L, "too many results to resume");
44 return -1; /* error flag */
45 }
46 lua_xmove(co, L, nres); /* move yielded values */
47 return nres;
48 }
49 else {
50 lua_xmove(co, L, 1); /* move error message */
51 return -1; /* error flag */
52 }
53}
54
55
56static int luaB_coresume (lua_State *L) {
57 lua_State *co = getco(L);
58 int r;
59 r = auxresume(L, co, lua_gettop(L) - 1);
60 if (l_unlikely(r < 0)) {
61 lua_pushboolean(L, 0);
62 lua_insert(L, -2);
63 return 2; /* return false + error message */
64 }
65 else {
66 lua_pushboolean(L, 1);
67 lua_insert(L, -(r + 1));
68 return r + 1; /* return true + 'resume' returns */
69 }
70}
71
72
73static int luaB_auxwrap (lua_State *L) {
74 lua_State *co = lua_tothread(L, lua_upvalueindex(1));
75 int r = auxresume(L, co, lua_gettop(L));
76 if (l_unlikely(r < 0)) { /* error? */
77 int stat = lua_status(co);
78 if (stat != LUA_OK && stat != LUA_YIELD) { /* error in the coroutine? */
79 stat = lua_closethread(co, L); /* close its tbc variables */
80 lua_assert(stat != LUA_OK);
81 lua_xmove(co, L, 1); /* move error message to the caller */
82 }
83 if (stat != LUA_ERRMEM && /* not a memory error and ... */
84 lua_type(L, -1) == LUA_TSTRING) { /* ... error object is a string? */
85 luaL_where(L, 1); /* add extra info, if available */
86 lua_insert(L, -2);
87 lua_concat(L, 2);
88 }
89 return lua_error(L); /* propagate error */
90 }
91 return r;
92}
93
94
95static int luaB_cocreate (lua_State *L) {
96 lua_State *NL;
97 luaL_checktype(L, 1, LUA_TFUNCTION);
98 NL = lua_newthread(L);
99 lua_pushvalue(L, 1); /* move function to top */
100 lua_xmove(L, NL, 1); /* move function from L to NL */
101 return 1;
102}
103
104
105static int luaB_cowrap (lua_State *L) {
106 luaB_cocreate(L);
107 lua_pushcclosure(L, luaB_auxwrap, 1);
108 return 1;
109}
110
111
112static int luaB_yield (lua_State *L) {
113 return lua_yield(L, lua_gettop(L));
114}
115
116
117#define COS_RUN 0
118#define COS_DEAD 1
119#define COS_YIELD 2
120#define COS_NORM 3
121
122
123static const char *const statname[] =
124 {"running", "dead", "suspended", "normal"};
125
126
127static int auxstatus (lua_State *L, lua_State *co) {
128 if (L == co) return COS_RUN;
129 else {
130 switch (lua_status(co)) {
131 case LUA_YIELD:
132 return COS_YIELD;
133 case LUA_OK: {
134 lua_Debug ar;
135 if (lua_getstack(co, 0, &ar)) /* does it have frames? */
136 return COS_NORM; /* it is running */
137 else if (lua_gettop(co) == 0)
138 return COS_DEAD;
139 else
140 return COS_YIELD; /* initial state */
141 }
142 default: /* some error occurred */
143 return COS_DEAD;
144 }
145 }
146}
147
148
149static int luaB_costatus (lua_State *L) {
150 lua_State *co = getco(L);
151 lua_pushstring(L, statname[auxstatus(L, co)]);
152 return 1;
153}
154
155
156static int luaB_yieldable (lua_State *L) {
157 lua_State *co = lua_isnone(L, 1) ? L : getco(L);
158 lua_pushboolean(L, lua_isyieldable(co));
159 return 1;
160}
161
162
163static int luaB_corunning (lua_State *L) {
164 int ismain = lua_pushthread(L);
165 lua_pushboolean(L, ismain);
166 return 2;
167}
168
169
170static int luaB_close (lua_State *L) {
171 lua_State *co = getco(L);
172 int status = auxstatus(L, co);
173 switch (status) {
174 case COS_DEAD: case COS_YIELD: {
175 status = lua_closethread(co, L);
176 if (status == LUA_OK) {
177 lua_pushboolean(L, 1);
178 return 1;
179 }
180 else {
181 lua_pushboolean(L, 0);
182 lua_xmove(co, L, 1); /* move error message */
183 return 2;
184 }
185 }
186 default: /* normal or running coroutine */
187 return luaL_error(L, "cannot close a %s coroutine", statname[status]);
188 }
189}
190
191
192static const luaL_Reg co_funcs[] = {
193 {"create", luaB_cocreate},
194 {"resume", luaB_coresume},
195 {"running", luaB_corunning},
196 {"status", luaB_costatus},
197 {"wrap", luaB_cowrap},
198 {"yield", luaB_yield},
199 {"isyieldable", luaB_yieldable},
200 {"close", luaB_close},
201 {NULL, NULL}
202};
203
204
205
206LUAMOD_API int luaopen_coroutine (lua_State *L) {
207 luaL_newlib(L, co_funcs);
208 return 1;
209}
210
diff --git a/vendor/lua-5.4.8/src/lctype.c b/vendor/lua-5.4.8/src/lctype.c
new file mode 100644
index 0000000..9542280
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lctype.c
@@ -0,0 +1,64 @@
1/*
2** $Id: lctype.c $
3** 'ctype' functions for Lua
4** See Copyright Notice in lua.h
5*/
6
7#define lctype_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include "lctype.h"
14
15#if !LUA_USE_CTYPE /* { */
16
17#include <limits.h>
18
19
20#if defined (LUA_UCID) /* accept UniCode IDentifiers? */
21/* consider all non-ascii codepoints to be alphabetic */
22#define NONA 0x01
23#else
24#define NONA 0x00 /* default */
25#endif
26
27
28LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = {
29 0x00, /* EOZ */
30 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */
31 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00,
32 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1. */
33 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
34 0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */
35 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
36 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */
37 0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
38 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */
39 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
40 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */
41 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05,
42 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */
43 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
44 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */
45 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00,
46 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 8. */
47 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
48 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 9. */
49 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
50 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* a. */
51 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
52 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* b. */
53 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
54 0x00, 0x00, NONA, NONA, NONA, NONA, NONA, NONA, /* c. */
55 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
56 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* d. */
57 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
58 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* e. */
59 NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
60 NONA, NONA, NONA, NONA, NONA, 0x00, 0x00, 0x00, /* f. */
61 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
62};
63
64#endif /* } */
diff --git a/vendor/lua-5.4.8/src/lctype.h b/vendor/lua-5.4.8/src/lctype.h
new file mode 100644
index 0000000..864e190
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lctype.h
@@ -0,0 +1,101 @@
1/*
2** $Id: lctype.h $
3** 'ctype' functions for Lua
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lctype_h
8#define lctype_h
9
10#include "lua.h"
11
12
13/*
14** WARNING: the functions defined here do not necessarily correspond
15** to the similar functions in the standard C ctype.h. They are
16** optimized for the specific needs of Lua.
17*/
18
19#if !defined(LUA_USE_CTYPE)
20
21#if 'A' == 65 && '0' == 48
22/* ASCII case: can use its own tables; faster and fixed */
23#define LUA_USE_CTYPE 0
24#else
25/* must use standard C ctype */
26#define LUA_USE_CTYPE 1
27#endif
28
29#endif
30
31
32#if !LUA_USE_CTYPE /* { */
33
34#include <limits.h>
35
36#include "llimits.h"
37
38
39#define ALPHABIT 0
40#define DIGITBIT 1
41#define PRINTBIT 2
42#define SPACEBIT 3
43#define XDIGITBIT 4
44
45
46#define MASK(B) (1 << (B))
47
48
49/*
50** add 1 to char to allow index -1 (EOZ)
51*/
52#define testprop(c,p) (luai_ctype_[(c)+1] & (p))
53
54/*
55** 'lalpha' (Lua alphabetic) and 'lalnum' (Lua alphanumeric) both include '_'
56*/
57#define lislalpha(c) testprop(c, MASK(ALPHABIT))
58#define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT)))
59#define lisdigit(c) testprop(c, MASK(DIGITBIT))
60#define lisspace(c) testprop(c, MASK(SPACEBIT))
61#define lisprint(c) testprop(c, MASK(PRINTBIT))
62#define lisxdigit(c) testprop(c, MASK(XDIGITBIT))
63
64
65/*
66** In ASCII, this 'ltolower' is correct for alphabetic characters and
67** for '.'. That is enough for Lua needs. ('check_exp' ensures that
68** the character either is an upper-case letter or is unchanged by
69** the transformation, which holds for lower-case letters and '.'.)
70*/
71#define ltolower(c) \
72 check_exp(('A' <= (c) && (c) <= 'Z') || (c) == ((c) | ('A' ^ 'a')), \
73 (c) | ('A' ^ 'a'))
74
75
76/* one entry for each character and for -1 (EOZ) */
77LUAI_DDEC(const lu_byte luai_ctype_[UCHAR_MAX + 2];)
78
79
80#else /* }{ */
81
82/*
83** use standard C ctypes
84*/
85
86#include <ctype.h>
87
88
89#define lislalpha(c) (isalpha(c) || (c) == '_')
90#define lislalnum(c) (isalnum(c) || (c) == '_')
91#define lisdigit(c) (isdigit(c))
92#define lisspace(c) (isspace(c))
93#define lisprint(c) (isprint(c))
94#define lisxdigit(c) (isxdigit(c))
95
96#define ltolower(c) (tolower(c))
97
98#endif /* } */
99
100#endif
101
diff --git a/vendor/lua-5.4.8/src/ldblib.c b/vendor/lua-5.4.8/src/ldblib.c
new file mode 100644
index 0000000..6dcbaa9
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ldblib.c
@@ -0,0 +1,483 @@
1/*
2** $Id: ldblib.c $
3** Interface from Lua to its debug API
4** See Copyright Notice in lua.h
5*/
6
7#define ldblib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <stdio.h>
14#include <stdlib.h>
15#include <string.h>
16
17#include "lua.h"
18
19#include "lauxlib.h"
20#include "lualib.h"
21
22
23/*
24** The hook table at registry[HOOKKEY] maps threads to their current
25** hook function.
26*/
27static const char *const HOOKKEY = "_HOOKKEY";
28
29
30/*
31** If L1 != L, L1 can be in any state, and therefore there are no
32** guarantees about its stack space; any push in L1 must be
33** checked.
34*/
35static void checkstack (lua_State *L, lua_State *L1, int n) {
36 if (l_unlikely(L != L1 && !lua_checkstack(L1, n)))
37 luaL_error(L, "stack overflow");
38}
39
40
41static int db_getregistry (lua_State *L) {
42 lua_pushvalue(L, LUA_REGISTRYINDEX);
43 return 1;
44}
45
46
47static int db_getmetatable (lua_State *L) {
48 luaL_checkany(L, 1);
49 if (!lua_getmetatable(L, 1)) {
50 lua_pushnil(L); /* no metatable */
51 }
52 return 1;
53}
54
55
56static int db_setmetatable (lua_State *L) {
57 int t = lua_type(L, 2);
58 luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table");
59 lua_settop(L, 2);
60 lua_setmetatable(L, 1);
61 return 1; /* return 1st argument */
62}
63
64
65static int db_getuservalue (lua_State *L) {
66 int n = (int)luaL_optinteger(L, 2, 1);
67 if (lua_type(L, 1) != LUA_TUSERDATA)
68 luaL_pushfail(L);
69 else if (lua_getiuservalue(L, 1, n) != LUA_TNONE) {
70 lua_pushboolean(L, 1);
71 return 2;
72 }
73 return 1;
74}
75
76
77static int db_setuservalue (lua_State *L) {
78 int n = (int)luaL_optinteger(L, 3, 1);
79 luaL_checktype(L, 1, LUA_TUSERDATA);
80 luaL_checkany(L, 2);
81 lua_settop(L, 2);
82 if (!lua_setiuservalue(L, 1, n))
83 luaL_pushfail(L);
84 return 1;
85}
86
87
88/*
89** Auxiliary function used by several library functions: check for
90** an optional thread as function's first argument and set 'arg' with
91** 1 if this argument is present (so that functions can skip it to
92** access their other arguments)
93*/
94static lua_State *getthread (lua_State *L, int *arg) {
95 if (lua_isthread(L, 1)) {
96 *arg = 1;
97 return lua_tothread(L, 1);
98 }
99 else {
100 *arg = 0;
101 return L; /* function will operate over current thread */
102 }
103}
104
105
106/*
107** Variations of 'lua_settable', used by 'db_getinfo' to put results
108** from 'lua_getinfo' into result table. Key is always a string;
109** value can be a string, an int, or a boolean.
110*/
111static void settabss (lua_State *L, const char *k, const char *v) {
112 lua_pushstring(L, v);
113 lua_setfield(L, -2, k);
114}
115
116static void settabsi (lua_State *L, const char *k, int v) {
117 lua_pushinteger(L, v);
118 lua_setfield(L, -2, k);
119}
120
121static void settabsb (lua_State *L, const char *k, int v) {
122 lua_pushboolean(L, v);
123 lua_setfield(L, -2, k);
124}
125
126
127/*
128** In function 'db_getinfo', the call to 'lua_getinfo' may push
129** results on the stack; later it creates the result table to put
130** these objects. Function 'treatstackoption' puts the result from
131** 'lua_getinfo' on top of the result table so that it can call
132** 'lua_setfield'.
133*/
134static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) {
135 if (L == L1)
136 lua_rotate(L, -2, 1); /* exchange object and table */
137 else
138 lua_xmove(L1, L, 1); /* move object to the "main" stack */
139 lua_setfield(L, -2, fname); /* put object into table */
140}
141
142
143/*
144** Calls 'lua_getinfo' and collects all results in a new table.
145** L1 needs stack space for an optional input (function) plus
146** two optional outputs (function and line table) from function
147** 'lua_getinfo'.
148*/
149static int db_getinfo (lua_State *L) {
150 lua_Debug ar;
151 int arg;
152 lua_State *L1 = getthread(L, &arg);
153 const char *options = luaL_optstring(L, arg+2, "flnSrtu");
154 checkstack(L, L1, 3);
155 luaL_argcheck(L, options[0] != '>', arg + 2, "invalid option '>'");
156 if (lua_isfunction(L, arg + 1)) { /* info about a function? */
157 options = lua_pushfstring(L, ">%s", options); /* add '>' to 'options' */
158 lua_pushvalue(L, arg + 1); /* move function to 'L1' stack */
159 lua_xmove(L, L1, 1);
160 }
161 else { /* stack level */
162 if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) {
163 luaL_pushfail(L); /* level out of range */
164 return 1;
165 }
166 }
167 if (!lua_getinfo(L1, options, &ar))
168 return luaL_argerror(L, arg+2, "invalid option");
169 lua_newtable(L); /* table to collect results */
170 if (strchr(options, 'S')) {
171 lua_pushlstring(L, ar.source, ar.srclen);
172 lua_setfield(L, -2, "source");
173 settabss(L, "short_src", ar.short_src);
174 settabsi(L, "linedefined", ar.linedefined);
175 settabsi(L, "lastlinedefined", ar.lastlinedefined);
176 settabss(L, "what", ar.what);
177 }
178 if (strchr(options, 'l'))
179 settabsi(L, "currentline", ar.currentline);
180 if (strchr(options, 'u')) {
181 settabsi(L, "nups", ar.nups);
182 settabsi(L, "nparams", ar.nparams);
183 settabsb(L, "isvararg", ar.isvararg);
184 }
185 if (strchr(options, 'n')) {
186 settabss(L, "name", ar.name);
187 settabss(L, "namewhat", ar.namewhat);
188 }
189 if (strchr(options, 'r')) {
190 settabsi(L, "ftransfer", ar.ftransfer);
191 settabsi(L, "ntransfer", ar.ntransfer);
192 }
193 if (strchr(options, 't'))
194 settabsb(L, "istailcall", ar.istailcall);
195 if (strchr(options, 'L'))
196 treatstackoption(L, L1, "activelines");
197 if (strchr(options, 'f'))
198 treatstackoption(L, L1, "func");
199 return 1; /* return table */
200}
201
202
203static int db_getlocal (lua_State *L) {
204 int arg;
205 lua_State *L1 = getthread(L, &arg);
206 int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */
207 if (lua_isfunction(L, arg + 1)) { /* function argument? */
208 lua_pushvalue(L, arg + 1); /* push function */
209 lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */
210 return 1; /* return only name (there is no value) */
211 }
212 else { /* stack-level argument */
213 lua_Debug ar;
214 const char *name;
215 int level = (int)luaL_checkinteger(L, arg + 1);
216 if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */
217 return luaL_argerror(L, arg+1, "level out of range");
218 checkstack(L, L1, 1);
219 name = lua_getlocal(L1, &ar, nvar);
220 if (name) {
221 lua_xmove(L1, L, 1); /* move local value */
222 lua_pushstring(L, name); /* push name */
223 lua_rotate(L, -2, 1); /* re-order */
224 return 2;
225 }
226 else {
227 luaL_pushfail(L); /* no name (nor value) */
228 return 1;
229 }
230 }
231}
232
233
234static int db_setlocal (lua_State *L) {
235 int arg;
236 const char *name;
237 lua_State *L1 = getthread(L, &arg);
238 lua_Debug ar;
239 int level = (int)luaL_checkinteger(L, arg + 1);
240 int nvar = (int)luaL_checkinteger(L, arg + 2);
241 if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */
242 return luaL_argerror(L, arg+1, "level out of range");
243 luaL_checkany(L, arg+3);
244 lua_settop(L, arg+3);
245 checkstack(L, L1, 1);
246 lua_xmove(L, L1, 1);
247 name = lua_setlocal(L1, &ar, nvar);
248 if (name == NULL)
249 lua_pop(L1, 1); /* pop value (if not popped by 'lua_setlocal') */
250 lua_pushstring(L, name);
251 return 1;
252}
253
254
255/*
256** get (if 'get' is true) or set an upvalue from a closure
257*/
258static int auxupvalue (lua_State *L, int get) {
259 const char *name;
260 int n = (int)luaL_checkinteger(L, 2); /* upvalue index */
261 luaL_checktype(L, 1, LUA_TFUNCTION); /* closure */
262 name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);
263 if (name == NULL) return 0;
264 lua_pushstring(L, name);
265 lua_insert(L, -(get+1)); /* no-op if get is false */
266 return get + 1;
267}
268
269
270static int db_getupvalue (lua_State *L) {
271 return auxupvalue(L, 1);
272}
273
274
275static int db_setupvalue (lua_State *L) {
276 luaL_checkany(L, 3);
277 return auxupvalue(L, 0);
278}
279
280
281/*
282** Check whether a given upvalue from a given closure exists and
283** returns its index
284*/
285static void *checkupval (lua_State *L, int argf, int argnup, int *pnup) {
286 void *id;
287 int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */
288 luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */
289 id = lua_upvalueid(L, argf, nup);
290 if (pnup) {
291 luaL_argcheck(L, id != NULL, argnup, "invalid upvalue index");
292 *pnup = nup;
293 }
294 return id;
295}
296
297
298static int db_upvalueid (lua_State *L) {
299 void *id = checkupval(L, 1, 2, NULL);
300 if (id != NULL)
301 lua_pushlightuserdata(L, id);
302 else
303 luaL_pushfail(L);
304 return 1;
305}
306
307
308static int db_upvaluejoin (lua_State *L) {
309 int n1, n2;
310 checkupval(L, 1, 2, &n1);
311 checkupval(L, 3, 4, &n2);
312 luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected");
313 luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected");
314 lua_upvaluejoin(L, 1, n1, 3, n2);
315 return 0;
316}
317
318
319/*
320** Call hook function registered at hook table for the current
321** thread (if there is one)
322*/
323static void hookf (lua_State *L, lua_Debug *ar) {
324 static const char *const hooknames[] =
325 {"call", "return", "line", "count", "tail call"};
326 lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY);
327 lua_pushthread(L);
328 if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */
329 lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */
330 if (ar->currentline >= 0)
331 lua_pushinteger(L, ar->currentline); /* push current line */
332 else lua_pushnil(L);
333 lua_assert(lua_getinfo(L, "lS", ar));
334 lua_call(L, 2, 0); /* call hook function */
335 }
336}
337
338
339/*
340** Convert a string mask (for 'sethook') into a bit mask
341*/
342static int makemask (const char *smask, int count) {
343 int mask = 0;
344 if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
345 if (strchr(smask, 'r')) mask |= LUA_MASKRET;
346 if (strchr(smask, 'l')) mask |= LUA_MASKLINE;
347 if (count > 0) mask |= LUA_MASKCOUNT;
348 return mask;
349}
350
351
352/*
353** Convert a bit mask (for 'gethook') into a string mask
354*/
355static char *unmakemask (int mask, char *smask) {
356 int i = 0;
357 if (mask & LUA_MASKCALL) smask[i++] = 'c';
358 if (mask & LUA_MASKRET) smask[i++] = 'r';
359 if (mask & LUA_MASKLINE) smask[i++] = 'l';
360 smask[i] = '\0';
361 return smask;
362}
363
364
365static int db_sethook (lua_State *L) {
366 int arg, mask, count;
367 lua_Hook func;
368 lua_State *L1 = getthread(L, &arg);
369 if (lua_isnoneornil(L, arg+1)) { /* no hook? */
370 lua_settop(L, arg+1);
371 func = NULL; mask = 0; count = 0; /* turn off hooks */
372 }
373 else {
374 const char *smask = luaL_checkstring(L, arg+2);
375 luaL_checktype(L, arg+1, LUA_TFUNCTION);
376 count = (int)luaL_optinteger(L, arg + 3, 0);
377 func = hookf; mask = makemask(smask, count);
378 }
379 if (!luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY)) {
380 /* table just created; initialize it */
381 lua_pushliteral(L, "k");
382 lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */
383 lua_pushvalue(L, -1);
384 lua_setmetatable(L, -2); /* metatable(hooktable) = hooktable */
385 }
386 checkstack(L, L1, 1);
387 lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */
388 lua_pushvalue(L, arg + 1); /* value (hook function) */
389 lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */
390 lua_sethook(L1, func, mask, count);
391 return 0;
392}
393
394
395static int db_gethook (lua_State *L) {
396 int arg;
397 lua_State *L1 = getthread(L, &arg);
398 char buff[5];
399 int mask = lua_gethookmask(L1);
400 lua_Hook hook = lua_gethook(L1);
401 if (hook == NULL) { /* no hook? */
402 luaL_pushfail(L);
403 return 1;
404 }
405 else if (hook != hookf) /* external hook? */
406 lua_pushliteral(L, "external hook");
407 else { /* hook table must exist */
408 lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY);
409 checkstack(L, L1, 1);
410 lua_pushthread(L1); lua_xmove(L1, L, 1);
411 lua_rawget(L, -2); /* 1st result = hooktable[L1] */
412 lua_remove(L, -2); /* remove hook table */
413 }
414 lua_pushstring(L, unmakemask(mask, buff)); /* 2nd result = mask */
415 lua_pushinteger(L, lua_gethookcount(L1)); /* 3rd result = count */
416 return 3;
417}
418
419
420static int db_debug (lua_State *L) {
421 for (;;) {
422 char buffer[250];
423 lua_writestringerror("%s", "lua_debug> ");
424 if (fgets(buffer, sizeof(buffer), stdin) == NULL ||
425 strcmp(buffer, "cont\n") == 0)
426 return 0;
427 if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") ||
428 lua_pcall(L, 0, 0, 0))
429 lua_writestringerror("%s\n", luaL_tolstring(L, -1, NULL));
430 lua_settop(L, 0); /* remove eventual returns */
431 }
432}
433
434
435static int db_traceback (lua_State *L) {
436 int arg;
437 lua_State *L1 = getthread(L, &arg);
438 const char *msg = lua_tostring(L, arg + 1);
439 if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */
440 lua_pushvalue(L, arg + 1); /* return it untouched */
441 else {
442 int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0);
443 luaL_traceback(L, L1, msg, level);
444 }
445 return 1;
446}
447
448
449static int db_setcstacklimit (lua_State *L) {
450 int limit = (int)luaL_checkinteger(L, 1);
451 int res = lua_setcstacklimit(L, limit);
452 lua_pushinteger(L, res);
453 return 1;
454}
455
456
457static const luaL_Reg dblib[] = {
458 {"debug", db_debug},
459 {"getuservalue", db_getuservalue},
460 {"gethook", db_gethook},
461 {"getinfo", db_getinfo},
462 {"getlocal", db_getlocal},
463 {"getregistry", db_getregistry},
464 {"getmetatable", db_getmetatable},
465 {"getupvalue", db_getupvalue},
466 {"upvaluejoin", db_upvaluejoin},
467 {"upvalueid", db_upvalueid},
468 {"setuservalue", db_setuservalue},
469 {"sethook", db_sethook},
470 {"setlocal", db_setlocal},
471 {"setmetatable", db_setmetatable},
472 {"setupvalue", db_setupvalue},
473 {"traceback", db_traceback},
474 {"setcstacklimit", db_setcstacklimit},
475 {NULL, NULL}
476};
477
478
479LUAMOD_API int luaopen_debug (lua_State *L) {
480 luaL_newlib(L, dblib);
481 return 1;
482}
483
diff --git a/vendor/lua-5.4.8/src/ldebug.c b/vendor/lua-5.4.8/src/ldebug.c
new file mode 100644
index 0000000..7264fce
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ldebug.c
@@ -0,0 +1,971 @@
1/*
2** $Id: ldebug.c $
3** Debug Interface
4** See Copyright Notice in lua.h
5*/
6
7#define ldebug_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <stdarg.h>
14#include <stddef.h>
15#include <string.h>
16
17#include "lua.h"
18
19#include "lapi.h"
20#include "lcode.h"
21#include "ldebug.h"
22#include "ldo.h"
23#include "lfunc.h"
24#include "lobject.h"
25#include "lopcodes.h"
26#include "lstate.h"
27#include "lstring.h"
28#include "ltable.h"
29#include "ltm.h"
30#include "lvm.h"
31
32
33
34#define LuaClosure(f) ((f) != NULL && (f)->c.tt == LUA_VLCL)
35
36
37static const char *funcnamefromcall (lua_State *L, CallInfo *ci,
38 const char **name);
39
40static const char strlocal[] = "local";
41static const char strupval[] = "upvalue";
42
43
44static int currentpc (CallInfo *ci) {
45 lua_assert(isLua(ci));
46 return pcRel(ci->u.l.savedpc, ci_func(ci)->p);
47}
48
49
50/*
51** Get a "base line" to find the line corresponding to an instruction.
52** Base lines are regularly placed at MAXIWTHABS intervals, so usually
53** an integer division gets the right place. When the source file has
54** large sequences of empty/comment lines, it may need extra entries,
55** so the original estimate needs a correction.
56** If the original estimate is -1, the initial 'if' ensures that the
57** 'while' will run at least once.
58** The assertion that the estimate is a lower bound for the correct base
59** is valid as long as the debug info has been generated with the same
60** value for MAXIWTHABS or smaller. (Previous releases use a little
61** smaller value.)
62*/
63static int getbaseline (const Proto *f, int pc, int *basepc) {
64 if (f->sizeabslineinfo == 0 || pc < f->abslineinfo[0].pc) {
65 *basepc = -1; /* start from the beginning */
66 return f->linedefined;
67 }
68 else {
69 int i = cast_uint(pc) / MAXIWTHABS - 1; /* get an estimate */
70 /* estimate must be a lower bound of the correct base */
71 lua_assert(i < 0 ||
72 (i < f->sizeabslineinfo && f->abslineinfo[i].pc <= pc));
73 while (i + 1 < f->sizeabslineinfo && pc >= f->abslineinfo[i + 1].pc)
74 i++; /* low estimate; adjust it */
75 *basepc = f->abslineinfo[i].pc;
76 return f->abslineinfo[i].line;
77 }
78}
79
80
81/*
82** Get the line corresponding to instruction 'pc' in function 'f';
83** first gets a base line and from there does the increments until
84** the desired instruction.
85*/
86int luaG_getfuncline (const Proto *f, int pc) {
87 if (f->lineinfo == NULL) /* no debug information? */
88 return -1;
89 else {
90 int basepc;
91 int baseline = getbaseline(f, pc, &basepc);
92 while (basepc++ < pc) { /* walk until given instruction */
93 lua_assert(f->lineinfo[basepc] != ABSLINEINFO);
94 baseline += f->lineinfo[basepc]; /* correct line */
95 }
96 return baseline;
97 }
98}
99
100
101static int getcurrentline (CallInfo *ci) {
102 return luaG_getfuncline(ci_func(ci)->p, currentpc(ci));
103}
104
105
106/*
107** Set 'trap' for all active Lua frames.
108** This function can be called during a signal, under "reasonable"
109** assumptions. A new 'ci' is completely linked in the list before it
110** becomes part of the "active" list, and we assume that pointers are
111** atomic; see comment in next function.
112** (A compiler doing interprocedural optimizations could, theoretically,
113** reorder memory writes in such a way that the list could be
114** temporarily broken while inserting a new element. We simply assume it
115** has no good reasons to do that.)
116*/
117static void settraps (CallInfo *ci) {
118 for (; ci != NULL; ci = ci->previous)
119 if (isLua(ci))
120 ci->u.l.trap = 1;
121}
122
123
124/*
125** This function can be called during a signal, under "reasonable"
126** assumptions.
127** Fields 'basehookcount' and 'hookcount' (set by 'resethookcount')
128** are for debug only, and it is no problem if they get arbitrary
129** values (causes at most one wrong hook call). 'hookmask' is an atomic
130** value. We assume that pointers are atomic too (e.g., gcc ensures that
131** for all platforms where it runs). Moreover, 'hook' is always checked
132** before being called (see 'luaD_hook').
133*/
134LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
135 if (func == NULL || mask == 0) { /* turn off hooks? */
136 mask = 0;
137 func = NULL;
138 }
139 L->hook = func;
140 L->basehookcount = count;
141 resethookcount(L);
142 L->hookmask = cast_byte(mask);
143 if (mask)
144 settraps(L->ci); /* to trace inside 'luaV_execute' */
145}
146
147
148LUA_API lua_Hook lua_gethook (lua_State *L) {
149 return L->hook;
150}
151
152
153LUA_API int lua_gethookmask (lua_State *L) {
154 return L->hookmask;
155}
156
157
158LUA_API int lua_gethookcount (lua_State *L) {
159 return L->basehookcount;
160}
161
162
163LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
164 int status;
165 CallInfo *ci;
166 if (level < 0) return 0; /* invalid (negative) level */
167 lua_lock(L);
168 for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous)
169 level--;
170 if (level == 0 && ci != &L->base_ci) { /* level found? */
171 status = 1;
172 ar->i_ci = ci;
173 }
174 else status = 0; /* no such level */
175 lua_unlock(L);
176 return status;
177}
178
179
180static const char *upvalname (const Proto *p, int uv) {
181 TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name);
182 if (s == NULL) return "?";
183 else return getstr(s);
184}
185
186
187static const char *findvararg (CallInfo *ci, int n, StkId *pos) {
188 if (clLvalue(s2v(ci->func.p))->p->is_vararg) {
189 int nextra = ci->u.l.nextraargs;
190 if (n >= -nextra) { /* 'n' is negative */
191 *pos = ci->func.p - nextra - (n + 1);
192 return "(vararg)"; /* generic name for any vararg */
193 }
194 }
195 return NULL; /* no such vararg */
196}
197
198
199const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) {
200 StkId base = ci->func.p + 1;
201 const char *name = NULL;
202 if (isLua(ci)) {
203 if (n < 0) /* access to vararg values? */
204 return findvararg(ci, n, pos);
205 else
206 name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
207 }
208 if (name == NULL) { /* no 'standard' name? */
209 StkId limit = (ci == L->ci) ? L->top.p : ci->next->func.p;
210 if (limit - base >= n && n > 0) { /* is 'n' inside 'ci' stack? */
211 /* generic name for any valid slot */
212 name = isLua(ci) ? "(temporary)" : "(C temporary)";
213 }
214 else
215 return NULL; /* no name */
216 }
217 if (pos)
218 *pos = base + (n - 1);
219 return name;
220}
221
222
223LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
224 const char *name;
225 lua_lock(L);
226 if (ar == NULL) { /* information about non-active function? */
227 if (!isLfunction(s2v(L->top.p - 1))) /* not a Lua function? */
228 name = NULL;
229 else /* consider live variables at function start (parameters) */
230 name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, n, 0);
231 }
232 else { /* active function; get information through 'ar' */
233 StkId pos = NULL; /* to avoid warnings */
234 name = luaG_findlocal(L, ar->i_ci, n, &pos);
235 if (name) {
236 setobjs2s(L, L->top.p, pos);
237 api_incr_top(L);
238 }
239 }
240 lua_unlock(L);
241 return name;
242}
243
244
245LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
246 StkId pos = NULL; /* to avoid warnings */
247 const char *name;
248 lua_lock(L);
249 name = luaG_findlocal(L, ar->i_ci, n, &pos);
250 if (name) {
251 setobjs2s(L, pos, L->top.p - 1);
252 L->top.p--; /* pop value */
253 }
254 lua_unlock(L);
255 return name;
256}
257
258
259static void funcinfo (lua_Debug *ar, Closure *cl) {
260 if (!LuaClosure(cl)) {
261 ar->source = "=[C]";
262 ar->srclen = LL("=[C]");
263 ar->linedefined = -1;
264 ar->lastlinedefined = -1;
265 ar->what = "C";
266 }
267 else {
268 const Proto *p = cl->l.p;
269 if (p->source) {
270 ar->source = getstr(p->source);
271 ar->srclen = tsslen(p->source);
272 }
273 else {
274 ar->source = "=?";
275 ar->srclen = LL("=?");
276 }
277 ar->linedefined = p->linedefined;
278 ar->lastlinedefined = p->lastlinedefined;
279 ar->what = (ar->linedefined == 0) ? "main" : "Lua";
280 }
281 luaO_chunkid(ar->short_src, ar->source, ar->srclen);
282}
283
284
285static int nextline (const Proto *p, int currentline, int pc) {
286 if (p->lineinfo[pc] != ABSLINEINFO)
287 return currentline + p->lineinfo[pc];
288 else
289 return luaG_getfuncline(p, pc);
290}
291
292
293static void collectvalidlines (lua_State *L, Closure *f) {
294 if (!LuaClosure(f)) {
295 setnilvalue(s2v(L->top.p));
296 api_incr_top(L);
297 }
298 else {
299 const Proto *p = f->l.p;
300 int currentline = p->linedefined;
301 Table *t = luaH_new(L); /* new table to store active lines */
302 sethvalue2s(L, L->top.p, t); /* push it on stack */
303 api_incr_top(L);
304 if (p->lineinfo != NULL) { /* proto with debug information? */
305 int i;
306 TValue v;
307 setbtvalue(&v); /* boolean 'true' to be the value of all indices */
308 if (!p->is_vararg) /* regular function? */
309 i = 0; /* consider all instructions */
310 else { /* vararg function */
311 lua_assert(GET_OPCODE(p->code[0]) == OP_VARARGPREP);
312 currentline = nextline(p, currentline, 0);
313 i = 1; /* skip first instruction (OP_VARARGPREP) */
314 }
315 for (; i < p->sizelineinfo; i++) { /* for each instruction */
316 currentline = nextline(p, currentline, i); /* get its line */
317 luaH_setint(L, t, currentline, &v); /* table[line] = true */
318 }
319 }
320 }
321}
322
323
324static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
325 /* calling function is a known function? */
326 if (ci != NULL && !(ci->callstatus & CIST_TAIL))
327 return funcnamefromcall(L, ci->previous, name);
328 else return NULL; /* no way to find a name */
329}
330
331
332static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
333 Closure *f, CallInfo *ci) {
334 int status = 1;
335 for (; *what; what++) {
336 switch (*what) {
337 case 'S': {
338 funcinfo(ar, f);
339 break;
340 }
341 case 'l': {
342 ar->currentline = (ci && isLua(ci)) ? getcurrentline(ci) : -1;
343 break;
344 }
345 case 'u': {
346 ar->nups = (f == NULL) ? 0 : f->c.nupvalues;
347 if (!LuaClosure(f)) {
348 ar->isvararg = 1;
349 ar->nparams = 0;
350 }
351 else {
352 ar->isvararg = f->l.p->is_vararg;
353 ar->nparams = f->l.p->numparams;
354 }
355 break;
356 }
357 case 't': {
358 ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0;
359 break;
360 }
361 case 'n': {
362 ar->namewhat = getfuncname(L, ci, &ar->name);
363 if (ar->namewhat == NULL) {
364 ar->namewhat = ""; /* not found */
365 ar->name = NULL;
366 }
367 break;
368 }
369 case 'r': {
370 if (ci == NULL || !(ci->callstatus & CIST_TRAN))
371 ar->ftransfer = ar->ntransfer = 0;
372 else {
373 ar->ftransfer = ci->u2.transferinfo.ftransfer;
374 ar->ntransfer = ci->u2.transferinfo.ntransfer;
375 }
376 break;
377 }
378 case 'L':
379 case 'f': /* handled by lua_getinfo */
380 break;
381 default: status = 0; /* invalid option */
382 }
383 }
384 return status;
385}
386
387
388LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
389 int status;
390 Closure *cl;
391 CallInfo *ci;
392 TValue *func;
393 lua_lock(L);
394 if (*what == '>') {
395 ci = NULL;
396 func = s2v(L->top.p - 1);
397 api_check(L, ttisfunction(func), "function expected");
398 what++; /* skip the '>' */
399 L->top.p--; /* pop function */
400 }
401 else {
402 ci = ar->i_ci;
403 func = s2v(ci->func.p);
404 lua_assert(ttisfunction(func));
405 }
406 cl = ttisclosure(func) ? clvalue(func) : NULL;
407 status = auxgetinfo(L, what, ar, cl, ci);
408 if (strchr(what, 'f')) {
409 setobj2s(L, L->top.p, func);
410 api_incr_top(L);
411 }
412 if (strchr(what, 'L'))
413 collectvalidlines(L, cl);
414 lua_unlock(L);
415 return status;
416}
417
418
419/*
420** {======================================================
421** Symbolic Execution
422** =======================================================
423*/
424
425
426static int filterpc (int pc, int jmptarget) {
427 if (pc < jmptarget) /* is code conditional (inside a jump)? */
428 return -1; /* cannot know who sets that register */
429 else return pc; /* current position sets that register */
430}
431
432
433/*
434** Try to find last instruction before 'lastpc' that modified register 'reg'.
435*/
436static int findsetreg (const Proto *p, int lastpc, int reg) {
437 int pc;
438 int setreg = -1; /* keep last instruction that changed 'reg' */
439 int jmptarget = 0; /* any code before this address is conditional */
440 if (testMMMode(GET_OPCODE(p->code[lastpc])))
441 lastpc--; /* previous instruction was not actually executed */
442 for (pc = 0; pc < lastpc; pc++) {
443 Instruction i = p->code[pc];
444 OpCode op = GET_OPCODE(i);
445 int a = GETARG_A(i);
446 int change; /* true if current instruction changed 'reg' */
447 switch (op) {
448 case OP_LOADNIL: { /* set registers from 'a' to 'a+b' */
449 int b = GETARG_B(i);
450 change = (a <= reg && reg <= a + b);
451 break;
452 }
453 case OP_TFORCALL: { /* affect all regs above its base */
454 change = (reg >= a + 2);
455 break;
456 }
457 case OP_CALL:
458 case OP_TAILCALL: { /* affect all registers above base */
459 change = (reg >= a);
460 break;
461 }
462 case OP_JMP: { /* doesn't change registers, but changes 'jmptarget' */
463 int b = GETARG_sJ(i);
464 int dest = pc + 1 + b;
465 /* jump does not skip 'lastpc' and is larger than current one? */
466 if (dest <= lastpc && dest > jmptarget)
467 jmptarget = dest; /* update 'jmptarget' */
468 change = 0;
469 break;
470 }
471 default: /* any instruction that sets A */
472 change = (testAMode(op) && reg == a);
473 break;
474 }
475 if (change)
476 setreg = filterpc(pc, jmptarget);
477 }
478 return setreg;
479}
480
481
482/*
483** Find a "name" for the constant 'c'.
484*/
485static const char *kname (const Proto *p, int index, const char **name) {
486 TValue *kvalue = &p->k[index];
487 if (ttisstring(kvalue)) {
488 *name = getstr(tsvalue(kvalue));
489 return "constant";
490 }
491 else {
492 *name = "?";
493 return NULL;
494 }
495}
496
497
498static const char *basicgetobjname (const Proto *p, int *ppc, int reg,
499 const char **name) {
500 int pc = *ppc;
501 *name = luaF_getlocalname(p, reg + 1, pc);
502 if (*name) /* is a local? */
503 return strlocal;
504 /* else try symbolic execution */
505 *ppc = pc = findsetreg(p, pc, reg);
506 if (pc != -1) { /* could find instruction? */
507 Instruction i = p->code[pc];
508 OpCode op = GET_OPCODE(i);
509 switch (op) {
510 case OP_MOVE: {
511 int b = GETARG_B(i); /* move from 'b' to 'a' */
512 if (b < GETARG_A(i))
513 return basicgetobjname(p, ppc, b, name); /* get name for 'b' */
514 break;
515 }
516 case OP_GETUPVAL: {
517 *name = upvalname(p, GETARG_B(i));
518 return strupval;
519 }
520 case OP_LOADK: return kname(p, GETARG_Bx(i), name);
521 case OP_LOADKX: return kname(p, GETARG_Ax(p->code[pc + 1]), name);
522 default: break;
523 }
524 }
525 return NULL; /* could not find reasonable name */
526}
527
528
529/*
530** Find a "name" for the register 'c'.
531*/
532static void rname (const Proto *p, int pc, int c, const char **name) {
533 const char *what = basicgetobjname(p, &pc, c, name); /* search for 'c' */
534 if (!(what && *what == 'c')) /* did not find a constant name? */
535 *name = "?";
536}
537
538
539/*
540** Find a "name" for a 'C' value in an RK instruction.
541*/
542static void rkname (const Proto *p, int pc, Instruction i, const char **name) {
543 int c = GETARG_C(i); /* key index */
544 if (GETARG_k(i)) /* is 'c' a constant? */
545 kname(p, c, name);
546 else /* 'c' is a register */
547 rname(p, pc, c, name);
548}
549
550
551/*
552** Check whether table being indexed by instruction 'i' is the
553** environment '_ENV'. If the table is an upvalue, get its name;
554** otherwise, find some "name" for the table and check whether
555** that name is the name of a local variable (and not, for instance,
556** a string). Then check that, if there is a name, it is '_ENV'.
557*/
558static const char *isEnv (const Proto *p, int pc, Instruction i, int isup) {
559 int t = GETARG_B(i); /* table index */
560 const char *name; /* name of indexed variable */
561 if (isup) /* is 't' an upvalue? */
562 name = upvalname(p, t);
563 else { /* 't' is a register */
564 const char *what = basicgetobjname(p, &pc, t, &name);
565 if (what != strlocal && what != strupval)
566 name = NULL; /* cannot be the variable _ENV */
567 }
568 return (name && strcmp(name, LUA_ENV) == 0) ? "global" : "field";
569}
570
571
572/*
573** Extend 'basicgetobjname' to handle table accesses
574*/
575static const char *getobjname (const Proto *p, int lastpc, int reg,
576 const char **name) {
577 const char *kind = basicgetobjname(p, &lastpc, reg, name);
578 if (kind != NULL)
579 return kind;
580 else if (lastpc != -1) { /* could find instruction? */
581 Instruction i = p->code[lastpc];
582 OpCode op = GET_OPCODE(i);
583 switch (op) {
584 case OP_GETTABUP: {
585 int k = GETARG_C(i); /* key index */
586 kname(p, k, name);
587 return isEnv(p, lastpc, i, 1);
588 }
589 case OP_GETTABLE: {
590 int k = GETARG_C(i); /* key index */
591 rname(p, lastpc, k, name);
592 return isEnv(p, lastpc, i, 0);
593 }
594 case OP_GETI: {
595 *name = "integer index";
596 return "field";
597 }
598 case OP_GETFIELD: {
599 int k = GETARG_C(i); /* key index */
600 kname(p, k, name);
601 return isEnv(p, lastpc, i, 0);
602 }
603 case OP_SELF: {
604 rkname(p, lastpc, i, name);
605 return "method";
606 }
607 default: break; /* go through to return NULL */
608 }
609 }
610 return NULL; /* could not find reasonable name */
611}
612
613
614/*
615** Try to find a name for a function based on the code that called it.
616** (Only works when function was called by a Lua function.)
617** Returns what the name is (e.g., "for iterator", "method",
618** "metamethod") and sets '*name' to point to the name.
619*/
620static const char *funcnamefromcode (lua_State *L, const Proto *p,
621 int pc, const char **name) {
622 TMS tm = (TMS)0; /* (initial value avoids warnings) */
623 Instruction i = p->code[pc]; /* calling instruction */
624 switch (GET_OPCODE(i)) {
625 case OP_CALL:
626 case OP_TAILCALL:
627 return getobjname(p, pc, GETARG_A(i), name); /* get function name */
628 case OP_TFORCALL: { /* for iterator */
629 *name = "for iterator";
630 return "for iterator";
631 }
632 /* other instructions can do calls through metamethods */
633 case OP_SELF: case OP_GETTABUP: case OP_GETTABLE:
634 case OP_GETI: case OP_GETFIELD:
635 tm = TM_INDEX;
636 break;
637 case OP_SETTABUP: case OP_SETTABLE: case OP_SETI: case OP_SETFIELD:
638 tm = TM_NEWINDEX;
639 break;
640 case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {
641 tm = cast(TMS, GETARG_C(i));
642 break;
643 }
644 case OP_UNM: tm = TM_UNM; break;
645 case OP_BNOT: tm = TM_BNOT; break;
646 case OP_LEN: tm = TM_LEN; break;
647 case OP_CONCAT: tm = TM_CONCAT; break;
648 case OP_EQ: tm = TM_EQ; break;
649 /* no cases for OP_EQI and OP_EQK, as they don't call metamethods */
650 case OP_LT: case OP_LTI: case OP_GTI: tm = TM_LT; break;
651 case OP_LE: case OP_LEI: case OP_GEI: tm = TM_LE; break;
652 case OP_CLOSE: case OP_RETURN: tm = TM_CLOSE; break;
653 default:
654 return NULL; /* cannot find a reasonable name */
655 }
656 *name = getshrstr(G(L)->tmname[tm]) + 2;
657 return "metamethod";
658}
659
660
661/*
662** Try to find a name for a function based on how it was called.
663*/
664static const char *funcnamefromcall (lua_State *L, CallInfo *ci,
665 const char **name) {
666 if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */
667 *name = "?";
668 return "hook";
669 }
670 else if (ci->callstatus & CIST_FIN) { /* was it called as a finalizer? */
671 *name = "__gc";
672 return "metamethod"; /* report it as such */
673 }
674 else if (isLua(ci))
675 return funcnamefromcode(L, ci_func(ci)->p, currentpc(ci), name);
676 else
677 return NULL;
678}
679
680/* }====================================================== */
681
682
683
684/*
685** Check whether pointer 'o' points to some value in the stack frame of
686** the current function and, if so, returns its index. Because 'o' may
687** not point to a value in this stack, we cannot compare it with the
688** region boundaries (undefined behavior in ISO C).
689*/
690static int instack (CallInfo *ci, const TValue *o) {
691 int pos;
692 StkId base = ci->func.p + 1;
693 for (pos = 0; base + pos < ci->top.p; pos++) {
694 if (o == s2v(base + pos))
695 return pos;
696 }
697 return -1; /* not found */
698}
699
700
701/*
702** Checks whether value 'o' came from an upvalue. (That can only happen
703** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on
704** upvalues.)
705*/
706static const char *getupvalname (CallInfo *ci, const TValue *o,
707 const char **name) {
708 LClosure *c = ci_func(ci);
709 int i;
710 for (i = 0; i < c->nupvalues; i++) {
711 if (c->upvals[i]->v.p == o) {
712 *name = upvalname(c->p, i);
713 return strupval;
714 }
715 }
716 return NULL;
717}
718
719
720static const char *formatvarinfo (lua_State *L, const char *kind,
721 const char *name) {
722 if (kind == NULL)
723 return ""; /* no information */
724 else
725 return luaO_pushfstring(L, " (%s '%s')", kind, name);
726}
727
728/*
729** Build a string with a "description" for the value 'o', such as
730** "variable 'x'" or "upvalue 'y'".
731*/
732static const char *varinfo (lua_State *L, const TValue *o) {
733 CallInfo *ci = L->ci;
734 const char *name = NULL; /* to avoid warnings */
735 const char *kind = NULL;
736 if (isLua(ci)) {
737 kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */
738 if (!kind) { /* not an upvalue? */
739 int reg = instack(ci, o); /* try a register */
740 if (reg >= 0) /* is 'o' a register? */
741 kind = getobjname(ci_func(ci)->p, currentpc(ci), reg, &name);
742 }
743 }
744 return formatvarinfo(L, kind, name);
745}
746
747
748/*
749** Raise a type error
750*/
751static l_noret typeerror (lua_State *L, const TValue *o, const char *op,
752 const char *extra) {
753 const char *t = luaT_objtypename(L, o);
754 luaG_runerror(L, "attempt to %s a %s value%s", op, t, extra);
755}
756
757
758/*
759** Raise a type error with "standard" information about the faulty
760** object 'o' (using 'varinfo').
761*/
762l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
763 typeerror(L, o, op, varinfo(L, o));
764}
765
766
767/*
768** Raise an error for calling a non-callable object. Try to find a name
769** for the object based on how it was called ('funcnamefromcall'); if it
770** cannot get a name there, try 'varinfo'.
771*/
772l_noret luaG_callerror (lua_State *L, const TValue *o) {
773 CallInfo *ci = L->ci;
774 const char *name = NULL; /* to avoid warnings */
775 const char *kind = funcnamefromcall(L, ci, &name);
776 const char *extra = kind ? formatvarinfo(L, kind, name) : varinfo(L, o);
777 typeerror(L, o, "call", extra);
778}
779
780
781l_noret luaG_forerror (lua_State *L, const TValue *o, const char *what) {
782 luaG_runerror(L, "bad 'for' %s (number expected, got %s)",
783 what, luaT_objtypename(L, o));
784}
785
786
787l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) {
788 if (ttisstring(p1) || cvt2str(p1)) p1 = p2;
789 luaG_typeerror(L, p1, "concatenate");
790}
791
792
793l_noret luaG_opinterror (lua_State *L, const TValue *p1,
794 const TValue *p2, const char *msg) {
795 if (!ttisnumber(p1)) /* first operand is wrong? */
796 p2 = p1; /* now second is wrong */
797 luaG_typeerror(L, p2, msg);
798}
799
800
801/*
802** Error when both values are convertible to numbers, but not to integers
803*/
804l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
805 lua_Integer temp;
806 if (!luaV_tointegerns(p1, &temp, LUA_FLOORN2I))
807 p2 = p1;
808 luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
809}
810
811
812l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
813 const char *t1 = luaT_objtypename(L, p1);
814 const char *t2 = luaT_objtypename(L, p2);
815 if (strcmp(t1, t2) == 0)
816 luaG_runerror(L, "attempt to compare two %s values", t1);
817 else
818 luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
819}
820
821
822/* add src:line information to 'msg' */
823const char *luaG_addinfo (lua_State *L, const char *msg, TString *src,
824 int line) {
825 char buff[LUA_IDSIZE];
826 if (src)
827 luaO_chunkid(buff, getstr(src), tsslen(src));
828 else { /* no source available; use "?" instead */
829 buff[0] = '?'; buff[1] = '\0';
830 }
831 return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
832}
833
834
835l_noret luaG_errormsg (lua_State *L) {
836 if (L->errfunc != 0) { /* is there an error handling function? */
837 StkId errfunc = restorestack(L, L->errfunc);
838 lua_assert(ttisfunction(s2v(errfunc)));
839 setobjs2s(L, L->top.p, L->top.p - 1); /* move argument */
840 setobjs2s(L, L->top.p - 1, errfunc); /* push function */
841 L->top.p++; /* assume EXTRA_STACK */
842 luaD_callnoyield(L, L->top.p - 2, 1); /* call it */
843 }
844 luaD_throw(L, LUA_ERRRUN);
845}
846
847
848l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
849 CallInfo *ci = L->ci;
850 const char *msg;
851 va_list argp;
852 luaC_checkGC(L); /* error message uses memory */
853 va_start(argp, fmt);
854 msg = luaO_pushvfstring(L, fmt, argp); /* format message */
855 va_end(argp);
856 if (isLua(ci)) { /* if Lua function, add source:line information */
857 luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));
858 setobjs2s(L, L->top.p - 2, L->top.p - 1); /* remove 'msg' */
859 L->top.p--;
860 }
861 luaG_errormsg(L);
862}
863
864
865/*
866** Check whether new instruction 'newpc' is in a different line from
867** previous instruction 'oldpc'. More often than not, 'newpc' is only
868** one or a few instructions after 'oldpc' (it must be after, see
869** caller), so try to avoid calling 'luaG_getfuncline'. If they are
870** too far apart, there is a good chance of a ABSLINEINFO in the way,
871** so it goes directly to 'luaG_getfuncline'.
872*/
873static int changedline (const Proto *p, int oldpc, int newpc) {
874 if (p->lineinfo == NULL) /* no debug information? */
875 return 0;
876 if (newpc - oldpc < MAXIWTHABS / 2) { /* not too far apart? */
877 int delta = 0; /* line difference */
878 int pc = oldpc;
879 for (;;) {
880 int lineinfo = p->lineinfo[++pc];
881 if (lineinfo == ABSLINEINFO)
882 break; /* cannot compute delta; fall through */
883 delta += lineinfo;
884 if (pc == newpc)
885 return (delta != 0); /* delta computed successfully */
886 }
887 }
888 /* either instructions are too far apart or there is an absolute line
889 info in the way; compute line difference explicitly */
890 return (luaG_getfuncline(p, oldpc) != luaG_getfuncline(p, newpc));
891}
892
893
894/*
895** Traces Lua calls. If code is running the first instruction of a function,
896** and function is not vararg, and it is not coming from an yield,
897** calls 'luaD_hookcall'. (Vararg functions will call 'luaD_hookcall'
898** after adjusting its variable arguments; otherwise, they could call
899** a line/count hook before the call hook. Functions coming from
900** an yield already called 'luaD_hookcall' before yielding.)
901*/
902int luaG_tracecall (lua_State *L) {
903 CallInfo *ci = L->ci;
904 Proto *p = ci_func(ci)->p;
905 ci->u.l.trap = 1; /* ensure hooks will be checked */
906 if (ci->u.l.savedpc == p->code) { /* first instruction (not resuming)? */
907 if (p->is_vararg)
908 return 0; /* hooks will start at VARARGPREP instruction */
909 else if (!(ci->callstatus & CIST_HOOKYIELD)) /* not yieded? */
910 luaD_hookcall(L, ci); /* check 'call' hook */
911 }
912 return 1; /* keep 'trap' on */
913}
914
915
916/*
917** Traces the execution of a Lua function. Called before the execution
918** of each opcode, when debug is on. 'L->oldpc' stores the last
919** instruction traced, to detect line changes. When entering a new
920** function, 'npci' will be zero and will test as a new line whatever
921** the value of 'oldpc'. Some exceptional conditions may return to
922** a function without setting 'oldpc'. In that case, 'oldpc' may be
923** invalid; if so, use zero as a valid value. (A wrong but valid 'oldpc'
924** at most causes an extra call to a line hook.)
925** This function is not "Protected" when called, so it should correct
926** 'L->top.p' before calling anything that can run the GC.
927*/
928int luaG_traceexec (lua_State *L, const Instruction *pc) {
929 CallInfo *ci = L->ci;
930 lu_byte mask = L->hookmask;
931 const Proto *p = ci_func(ci)->p;
932 int counthook;
933 if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */
934 ci->u.l.trap = 0; /* don't need to stop again */
935 return 0; /* turn off 'trap' */
936 }
937 pc++; /* reference is always next instruction */
938 ci->u.l.savedpc = pc; /* save 'pc' */
939 counthook = (mask & LUA_MASKCOUNT) && (--L->hookcount == 0);
940 if (counthook)
941 resethookcount(L); /* reset count */
942 else if (!(mask & LUA_MASKLINE))
943 return 1; /* no line hook and count != 0; nothing to be done now */
944 if (ci->callstatus & CIST_HOOKYIELD) { /* hook yielded last time? */
945 ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */
946 return 1; /* do not call hook again (VM yielded, so it did not move) */
947 }
948 if (!isIT(*(ci->u.l.savedpc - 1))) /* top not being used? */
949 L->top.p = ci->top.p; /* correct top */
950 if (counthook)
951 luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */
952 if (mask & LUA_MASKLINE) {
953 /* 'L->oldpc' may be invalid; use zero in this case */
954 int oldpc = (L->oldpc < p->sizecode) ? L->oldpc : 0;
955 int npci = pcRel(pc, p);
956 if (npci <= oldpc || /* call hook when jump back (loop), */
957 changedline(p, oldpc, npci)) { /* or when enter new line */
958 int newline = luaG_getfuncline(p, npci);
959 luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */
960 }
961 L->oldpc = npci; /* 'pc' of last call to line hook */
962 }
963 if (L->status == LUA_YIELD) { /* did hook yield? */
964 if (counthook)
965 L->hookcount = 1; /* undo decrement to zero */
966 ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */
967 luaD_throw(L, LUA_YIELD);
968 }
969 return 1; /* keep 'trap' on */
970}
971
diff --git a/vendor/lua-5.4.8/src/ldebug.h b/vendor/lua-5.4.8/src/ldebug.h
new file mode 100644
index 0000000..2bfce3c
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ldebug.h
@@ -0,0 +1,64 @@
1/*
2** $Id: ldebug.h $
3** Auxiliary functions from Debug Interface module
4** See Copyright Notice in lua.h
5*/
6
7#ifndef ldebug_h
8#define ldebug_h
9
10
11#include "lstate.h"
12
13
14#define pcRel(pc, p) (cast_int((pc) - (p)->code) - 1)
15
16
17/* Active Lua function (given call info) */
18#define ci_func(ci) (clLvalue(s2v((ci)->func.p)))
19
20
21#define resethookcount(L) (L->hookcount = L->basehookcount)
22
23/*
24** mark for entries in 'lineinfo' array that has absolute information in
25** 'abslineinfo' array
26*/
27#define ABSLINEINFO (-0x80)
28
29
30/*
31** MAXimum number of successive Instructions WiTHout ABSolute line
32** information. (A power of two allows fast divisions.)
33*/
34#if !defined(MAXIWTHABS)
35#define MAXIWTHABS 128
36#endif
37
38
39LUAI_FUNC int luaG_getfuncline (const Proto *f, int pc);
40LUAI_FUNC const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n,
41 StkId *pos);
42LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o,
43 const char *opname);
44LUAI_FUNC l_noret luaG_callerror (lua_State *L, const TValue *o);
45LUAI_FUNC l_noret luaG_forerror (lua_State *L, const TValue *o,
46 const char *what);
47LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1,
48 const TValue *p2);
49LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1,
50 const TValue *p2,
51 const char *msg);
52LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1,
53 const TValue *p2);
54LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1,
55 const TValue *p2);
56LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...);
57LUAI_FUNC const char *luaG_addinfo (lua_State *L, const char *msg,
58 TString *src, int line);
59LUAI_FUNC l_noret luaG_errormsg (lua_State *L);
60LUAI_FUNC int luaG_traceexec (lua_State *L, const Instruction *pc);
61LUAI_FUNC int luaG_tracecall (lua_State *L);
62
63
64#endif
diff --git a/vendor/lua-5.4.8/src/ldo.c b/vendor/lua-5.4.8/src/ldo.c
new file mode 100644
index 0000000..c92573d
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ldo.c
@@ -0,0 +1,1035 @@
1/*
2** $Id: ldo.c $
3** Stack and Call structure of Lua
4** See Copyright Notice in lua.h
5*/
6
7#define ldo_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <setjmp.h>
14#include <stdlib.h>
15#include <string.h>
16
17#include "lua.h"
18
19#include "lapi.h"
20#include "ldebug.h"
21#include "ldo.h"
22#include "lfunc.h"
23#include "lgc.h"
24#include "lmem.h"
25#include "lobject.h"
26#include "lopcodes.h"
27#include "lparser.h"
28#include "lstate.h"
29#include "lstring.h"
30#include "ltable.h"
31#include "ltm.h"
32#include "lundump.h"
33#include "lvm.h"
34#include "lzio.h"
35
36
37
38#define errorstatus(s) ((s) > LUA_YIELD)
39
40
41/*
42** {======================================================
43** Error-recovery functions
44** =======================================================
45*/
46
47/*
48** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
49** default, Lua handles errors with exceptions when compiling as
50** C++ code, with _longjmp/_setjmp when asked to use them, and with
51** longjmp/setjmp otherwise.
52*/
53#if !defined(LUAI_THROW) /* { */
54
55#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
56
57/* C++ exceptions */
58#define LUAI_THROW(L,c) throw(c)
59#define LUAI_TRY(L,c,a) \
60 try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
61#define luai_jmpbuf int /* dummy variable */
62
63#elif defined(LUA_USE_POSIX) /* }{ */
64
65/* in POSIX, try _longjmp/_setjmp (more efficient) */
66#define LUAI_THROW(L,c) _longjmp((c)->b, 1)
67#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
68#define luai_jmpbuf jmp_buf
69
70#else /* }{ */
71
72/* ISO C handling with long jumps */
73#define LUAI_THROW(L,c) longjmp((c)->b, 1)
74#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
75#define luai_jmpbuf jmp_buf
76
77#endif /* } */
78
79#endif /* } */
80
81
82
83/* chain list of long jump buffers */
84struct lua_longjmp {
85 struct lua_longjmp *previous;
86 luai_jmpbuf b;
87 volatile int status; /* error code */
88};
89
90
91void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
92 switch (errcode) {
93 case LUA_ERRMEM: { /* memory error? */
94 setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
95 break;
96 }
97 case LUA_OK: { /* special case only for closing upvalues */
98 setnilvalue(s2v(oldtop)); /* no error message */
99 break;
100 }
101 default: {
102 lua_assert(errorstatus(errcode)); /* real error */
103 setobjs2s(L, oldtop, L->top.p - 1); /* error message on current top */
104 break;
105 }
106 }
107 L->top.p = oldtop + 1;
108}
109
110
111l_noret luaD_throw (lua_State *L, int errcode) {
112 if (L->errorJmp) { /* thread has an error handler? */
113 L->errorJmp->status = errcode; /* set status */
114 LUAI_THROW(L, L->errorJmp); /* jump to it */
115 }
116 else { /* thread has no error handler */
117 global_State *g = G(L);
118 errcode = luaE_resetthread(L, errcode); /* close all upvalues */
119 L->status = errcode;
120 if (g->mainthread->errorJmp) { /* main thread has a handler? */
121 setobjs2s(L, g->mainthread->top.p++, L->top.p - 1); /* copy error obj. */
122 luaD_throw(g->mainthread, errcode); /* re-throw in main thread */
123 }
124 else { /* no handler at all; abort */
125 if (g->panic) { /* panic function? */
126 lua_unlock(L);
127 g->panic(L); /* call panic function (last chance to jump out) */
128 }
129 abort();
130 }
131 }
132}
133
134
135int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
136 l_uint32 oldnCcalls = L->nCcalls;
137 struct lua_longjmp lj;
138 lj.status = LUA_OK;
139 lj.previous = L->errorJmp; /* chain new error handler */
140 L->errorJmp = &lj;
141 LUAI_TRY(L, &lj,
142 (*f)(L, ud);
143 );
144 L->errorJmp = lj.previous; /* restore old error handler */
145 L->nCcalls = oldnCcalls;
146 return lj.status;
147}
148
149/* }====================================================== */
150
151
152/*
153** {==================================================================
154** Stack reallocation
155** ===================================================================
156*/
157
158
159/*
160** Change all pointers to the stack into offsets.
161*/
162static void relstack (lua_State *L) {
163 CallInfo *ci;
164 UpVal *up;
165 L->top.offset = savestack(L, L->top.p);
166 L->tbclist.offset = savestack(L, L->tbclist.p);
167 for (up = L->openupval; up != NULL; up = up->u.open.next)
168 up->v.offset = savestack(L, uplevel(up));
169 for (ci = L->ci; ci != NULL; ci = ci->previous) {
170 ci->top.offset = savestack(L, ci->top.p);
171 ci->func.offset = savestack(L, ci->func.p);
172 }
173}
174
175
176/*
177** Change back all offsets into pointers.
178*/
179static void correctstack (lua_State *L) {
180 CallInfo *ci;
181 UpVal *up;
182 L->top.p = restorestack(L, L->top.offset);
183 L->tbclist.p = restorestack(L, L->tbclist.offset);
184 for (up = L->openupval; up != NULL; up = up->u.open.next)
185 up->v.p = s2v(restorestack(L, up->v.offset));
186 for (ci = L->ci; ci != NULL; ci = ci->previous) {
187 ci->top.p = restorestack(L, ci->top.offset);
188 ci->func.p = restorestack(L, ci->func.offset);
189 if (isLua(ci))
190 ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
191 }
192}
193
194
195/* some space for error handling */
196#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
197
198
199/* raise an error while running the message handler */
200l_noret luaD_errerr (lua_State *L) {
201 TString *msg = luaS_newliteral(L, "error in error handling");
202 setsvalue2s(L, L->top.p, msg);
203 L->top.p++; /* assume EXTRA_STACK */
204 luaD_throw(L, LUA_ERRERR);
205}
206
207
208/*
209** Reallocate the stack to a new size, correcting all pointers into it.
210** In ISO C, any pointer use after the pointer has been deallocated is
211** undefined behavior. So, before the reallocation, all pointers are
212** changed to offsets, and after the reallocation they are changed back
213** to pointers. As during the reallocation the pointers are invalid, the
214** reallocation cannot run emergency collections.
215**
216** In case of allocation error, raise an error or return false according
217** to 'raiseerror'.
218*/
219int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
220 int oldsize = stacksize(L);
221 int i;
222 StkId newstack;
223 int oldgcstop = G(L)->gcstopem;
224 lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
225 relstack(L); /* change pointers to offsets */
226 G(L)->gcstopem = 1; /* stop emergency collection */
227 newstack = luaM_reallocvector(L, L->stack.p, oldsize + EXTRA_STACK,
228 newsize + EXTRA_STACK, StackValue);
229 G(L)->gcstopem = oldgcstop; /* restore emergency collection */
230 if (l_unlikely(newstack == NULL)) { /* reallocation failed? */
231 correctstack(L); /* change offsets back to pointers */
232 if (raiseerror)
233 luaM_error(L);
234 else return 0; /* do not raise an error */
235 }
236 L->stack.p = newstack;
237 correctstack(L); /* change offsets back to pointers */
238 L->stack_last.p = L->stack.p + newsize;
239 for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++)
240 setnilvalue(s2v(newstack + i)); /* erase new segment */
241 return 1;
242}
243
244
245/*
246** Try to grow the stack by at least 'n' elements. When 'raiseerror'
247** is true, raises any error; otherwise, return 0 in case of errors.
248*/
249int luaD_growstack (lua_State *L, int n, int raiseerror) {
250 int size = stacksize(L);
251 if (l_unlikely(size > LUAI_MAXSTACK)) {
252 /* if stack is larger than maximum, thread is already using the
253 extra space reserved for errors, that is, thread is handling
254 a stack error; cannot grow further than that. */
255 lua_assert(stacksize(L) == ERRORSTACKSIZE);
256 if (raiseerror)
257 luaD_errerr(L); /* error inside message handler */
258 return 0; /* if not 'raiseerror', just signal it */
259 }
260 else if (n < LUAI_MAXSTACK) { /* avoids arithmetic overflows */
261 int newsize = 2 * size; /* tentative new size */
262 int needed = cast_int(L->top.p - L->stack.p) + n;
263 if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */
264 newsize = LUAI_MAXSTACK;
265 if (newsize < needed) /* but must respect what was asked for */
266 newsize = needed;
267 if (l_likely(newsize <= LUAI_MAXSTACK))
268 return luaD_reallocstack(L, newsize, raiseerror);
269 }
270 /* else stack overflow */
271 /* add extra size to be able to handle the error message */
272 luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
273 if (raiseerror)
274 luaG_runerror(L, "stack overflow");
275 return 0;
276}
277
278
279/*
280** Compute how much of the stack is being used, by computing the
281** maximum top of all call frames in the stack and the current top.
282*/
283static int stackinuse (lua_State *L) {
284 CallInfo *ci;
285 int res;
286 StkId lim = L->top.p;
287 for (ci = L->ci; ci != NULL; ci = ci->previous) {
288 if (lim < ci->top.p) lim = ci->top.p;
289 }
290 lua_assert(lim <= L->stack_last.p + EXTRA_STACK);
291 res = cast_int(lim - L->stack.p) + 1; /* part of stack in use */
292 if (res < LUA_MINSTACK)
293 res = LUA_MINSTACK; /* ensure a minimum size */
294 return res;
295}
296
297
298/*
299** If stack size is more than 3 times the current use, reduce that size
300** to twice the current use. (So, the final stack size is at most 2/3 the
301** previous size, and half of its entries are empty.)
302** As a particular case, if stack was handling a stack overflow and now
303** it is not, 'max' (limited by LUAI_MAXSTACK) will be smaller than
304** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack
305** will be reduced to a "regular" size.
306*/
307void luaD_shrinkstack (lua_State *L) {
308 int inuse = stackinuse(L);
309 int max = (inuse > LUAI_MAXSTACK / 3) ? LUAI_MAXSTACK : inuse * 3;
310 /* if thread is currently not handling a stack overflow and its
311 size is larger than maximum "reasonable" size, shrink it */
312 if (inuse <= LUAI_MAXSTACK && stacksize(L) > max) {
313 int nsize = (inuse > LUAI_MAXSTACK / 2) ? LUAI_MAXSTACK : inuse * 2;
314 luaD_reallocstack(L, nsize, 0); /* ok if that fails */
315 }
316 else /* don't change stack */
317 condmovestack(L,{},{}); /* (change only for debugging) */
318 luaE_shrinkCI(L); /* shrink CI list */
319}
320
321
322void luaD_inctop (lua_State *L) {
323 luaD_checkstack(L, 1);
324 L->top.p++;
325}
326
327/* }================================================================== */
328
329
330/*
331** Call a hook for the given event. Make sure there is a hook to be
332** called. (Both 'L->hook' and 'L->hookmask', which trigger this
333** function, can be changed asynchronously by signals.)
334*/
335void luaD_hook (lua_State *L, int event, int line,
336 int ftransfer, int ntransfer) {
337 lua_Hook hook = L->hook;
338 if (hook && L->allowhook) { /* make sure there is a hook */
339 int mask = CIST_HOOKED;
340 CallInfo *ci = L->ci;
341 ptrdiff_t top = savestack(L, L->top.p); /* preserve original 'top' */
342 ptrdiff_t ci_top = savestack(L, ci->top.p); /* idem for 'ci->top' */
343 lua_Debug ar;
344 ar.event = event;
345 ar.currentline = line;
346 ar.i_ci = ci;
347 if (ntransfer != 0) {
348 mask |= CIST_TRAN; /* 'ci' has transfer information */
349 ci->u2.transferinfo.ftransfer = ftransfer;
350 ci->u2.transferinfo.ntransfer = ntransfer;
351 }
352 if (isLua(ci) && L->top.p < ci->top.p)
353 L->top.p = ci->top.p; /* protect entire activation register */
354 luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
355 if (ci->top.p < L->top.p + LUA_MINSTACK)
356 ci->top.p = L->top.p + LUA_MINSTACK;
357 L->allowhook = 0; /* cannot call hooks inside a hook */
358 ci->callstatus |= mask;
359 lua_unlock(L);
360 (*hook)(L, &ar);
361 lua_lock(L);
362 lua_assert(!L->allowhook);
363 L->allowhook = 1;
364 ci->top.p = restorestack(L, ci_top);
365 L->top.p = restorestack(L, top);
366 ci->callstatus &= ~mask;
367 }
368}
369
370
371/*
372** Executes a call hook for Lua functions. This function is called
373** whenever 'hookmask' is not zero, so it checks whether call hooks are
374** active.
375*/
376void luaD_hookcall (lua_State *L, CallInfo *ci) {
377 L->oldpc = 0; /* set 'oldpc' for new function */
378 if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */
379 int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL
380 : LUA_HOOKCALL;
381 Proto *p = ci_func(ci)->p;
382 ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
383 luaD_hook(L, event, -1, 1, p->numparams);
384 ci->u.l.savedpc--; /* correct 'pc' */
385 }
386}
387
388
389/*
390** Executes a return hook for Lua and C functions and sets/corrects
391** 'oldpc'. (Note that this correction is needed by the line hook, so it
392** is done even when return hooks are off.)
393*/
394static void rethook (lua_State *L, CallInfo *ci, int nres) {
395 if (L->hookmask & LUA_MASKRET) { /* is return hook on? */
396 StkId firstres = L->top.p - nres; /* index of first result */
397 int delta = 0; /* correction for vararg functions */
398 int ftransfer;
399 if (isLua(ci)) {
400 Proto *p = ci_func(ci)->p;
401 if (p->is_vararg)
402 delta = ci->u.l.nextraargs + p->numparams + 1;
403 }
404 ci->func.p += delta; /* if vararg, back to virtual 'func' */
405 ftransfer = cast(unsigned short, firstres - ci->func.p);
406 luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */
407 ci->func.p -= delta;
408 }
409 if (isLua(ci = ci->previous))
410 L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* set 'oldpc' */
411}
412
413
414/*
415** Check whether 'func' has a '__call' metafield. If so, put it in the
416** stack, below original 'func', so that 'luaD_precall' can call it. Raise
417** an error if there is no '__call' metafield.
418*/
419static StkId tryfuncTM (lua_State *L, StkId func) {
420 const TValue *tm;
421 StkId p;
422 checkstackGCp(L, 1, func); /* space for metamethod */
423 tm = luaT_gettmbyobj(L, s2v(func), TM_CALL); /* (after previous GC) */
424 if (l_unlikely(ttisnil(tm)))
425 luaG_callerror(L, s2v(func)); /* nothing to call */
426 for (p = L->top.p; p > func; p--) /* open space for metamethod */
427 setobjs2s(L, p, p-1);
428 L->top.p++; /* stack space pre-allocated by the caller */
429 setobj2s(L, func, tm); /* metamethod is the new function to be called */
430 return func;
431}
432
433
434/*
435** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
436** Handle most typical cases (zero results for commands, one result for
437** expressions, multiple results for tail calls/single parameters)
438** separated.
439*/
440l_sinline void moveresults (lua_State *L, StkId res, int nres, int wanted) {
441 StkId firstresult;
442 int i;
443 switch (wanted) { /* handle typical cases separately */
444 case 0: /* no values needed */
445 L->top.p = res;
446 return;
447 case 1: /* one value needed */
448 if (nres == 0) /* no results? */
449 setnilvalue(s2v(res)); /* adjust with nil */
450 else /* at least one result */
451 setobjs2s(L, res, L->top.p - nres); /* move it to proper place */
452 L->top.p = res + 1;
453 return;
454 case LUA_MULTRET:
455 wanted = nres; /* we want all results */
456 break;
457 default: /* two/more results and/or to-be-closed variables */
458 if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */
459 L->ci->callstatus |= CIST_CLSRET; /* in case of yields */
460 L->ci->u2.nres = nres;
461 res = luaF_close(L, res, CLOSEKTOP, 1);
462 L->ci->callstatus &= ~CIST_CLSRET;
463 if (L->hookmask) { /* if needed, call hook after '__close's */
464 ptrdiff_t savedres = savestack(L, res);
465 rethook(L, L->ci, nres);
466 res = restorestack(L, savedres); /* hook can move stack */
467 }
468 wanted = decodeNresults(wanted);
469 if (wanted == LUA_MULTRET)
470 wanted = nres; /* we want all results */
471 }
472 break;
473 }
474 /* generic case */
475 firstresult = L->top.p - nres; /* index of first result */
476 if (nres > wanted) /* extra results? */
477 nres = wanted; /* don't need them */
478 for (i = 0; i < nres; i++) /* move all results to correct place */
479 setobjs2s(L, res + i, firstresult + i);
480 for (; i < wanted; i++) /* complete wanted number of results */
481 setnilvalue(s2v(res + i));
482 L->top.p = res + wanted; /* top points after the last result */
483}
484
485
486/*
487** Finishes a function call: calls hook if necessary, moves current
488** number of results to proper place, and returns to previous call
489** info. If function has to close variables, hook must be called after
490** that.
491*/
492void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
493 int wanted = ci->nresults;
494 if (l_unlikely(L->hookmask && !hastocloseCfunc(wanted)))
495 rethook(L, ci, nres);
496 /* move results to proper place */
497 moveresults(L, ci->func.p, nres, wanted);
498 /* function cannot be in any of these cases when returning */
499 lua_assert(!(ci->callstatus &
500 (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_TRAN | CIST_CLSRET)));
501 L->ci = ci->previous; /* back to caller (after closing variables) */
502}
503
504
505
506#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L))
507
508
509l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, int nret,
510 int mask, StkId top) {
511 CallInfo *ci = L->ci = next_ci(L); /* new frame */
512 ci->func.p = func;
513 ci->nresults = nret;
514 ci->callstatus = mask;
515 ci->top.p = top;
516 return ci;
517}
518
519
520/*
521** precall for C functions
522*/
523l_sinline int precallC (lua_State *L, StkId func, int nresults,
524 lua_CFunction f) {
525 int n; /* number of returns */
526 CallInfo *ci;
527 checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
528 L->ci = ci = prepCallInfo(L, func, nresults, CIST_C,
529 L->top.p + LUA_MINSTACK);
530 lua_assert(ci->top.p <= L->stack_last.p);
531 if (l_unlikely(L->hookmask & LUA_MASKCALL)) {
532 int narg = cast_int(L->top.p - func) - 1;
533 luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
534 }
535 lua_unlock(L);
536 n = (*f)(L); /* do the actual call */
537 lua_lock(L);
538 api_checknelems(L, n);
539 luaD_poscall(L, ci, n);
540 return n;
541}
542
543
544/*
545** Prepare a function for a tail call, building its call info on top
546** of the current call info. 'narg1' is the number of arguments plus 1
547** (so that it includes the function itself). Return the number of
548** results, if it was a C function, or -1 for a Lua function.
549*/
550int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,
551 int narg1, int delta) {
552 retry:
553 switch (ttypetag(s2v(func))) {
554 case LUA_VCCL: /* C closure */
555 return precallC(L, func, LUA_MULTRET, clCvalue(s2v(func))->f);
556 case LUA_VLCF: /* light C function */
557 return precallC(L, func, LUA_MULTRET, fvalue(s2v(func)));
558 case LUA_VLCL: { /* Lua function */
559 Proto *p = clLvalue(s2v(func))->p;
560 int fsize = p->maxstacksize; /* frame size */
561 int nfixparams = p->numparams;
562 int i;
563 checkstackGCp(L, fsize - delta, func);
564 ci->func.p -= delta; /* restore 'func' (if vararg) */
565 for (i = 0; i < narg1; i++) /* move down function and arguments */
566 setobjs2s(L, ci->func.p + i, func + i);
567 func = ci->func.p; /* moved-down function */
568 for (; narg1 <= nfixparams; narg1++)
569 setnilvalue(s2v(func + narg1)); /* complete missing arguments */
570 ci->top.p = func + 1 + fsize; /* top for new function */
571 lua_assert(ci->top.p <= L->stack_last.p);
572 ci->u.l.savedpc = p->code; /* starting point */
573 ci->callstatus |= CIST_TAIL;
574 L->top.p = func + narg1; /* set top */
575 return -1;
576 }
577 default: { /* not a function */
578 func = tryfuncTM(L, func); /* try to get '__call' metamethod */
579 /* return luaD_pretailcall(L, ci, func, narg1 + 1, delta); */
580 narg1++;
581 goto retry; /* try again */
582 }
583 }
584}
585
586
587/*
588** Prepares the call to a function (C or Lua). For C functions, also do
589** the call. The function to be called is at '*func'. The arguments
590** are on the stack, right after the function. Returns the CallInfo
591** to be executed, if it was a Lua function. Otherwise (a C function)
592** returns NULL, with all the results on the stack, starting at the
593** original function position.
594*/
595CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
596 retry:
597 switch (ttypetag(s2v(func))) {
598 case LUA_VCCL: /* C closure */
599 precallC(L, func, nresults, clCvalue(s2v(func))->f);
600 return NULL;
601 case LUA_VLCF: /* light C function */
602 precallC(L, func, nresults, fvalue(s2v(func)));
603 return NULL;
604 case LUA_VLCL: { /* Lua function */
605 CallInfo *ci;
606 Proto *p = clLvalue(s2v(func))->p;
607 int narg = cast_int(L->top.p - func) - 1; /* number of real arguments */
608 int nfixparams = p->numparams;
609 int fsize = p->maxstacksize; /* frame size */
610 checkstackGCp(L, fsize, func);
611 L->ci = ci = prepCallInfo(L, func, nresults, 0, func + 1 + fsize);
612 ci->u.l.savedpc = p->code; /* starting point */
613 for (; narg < nfixparams; narg++)
614 setnilvalue(s2v(L->top.p++)); /* complete missing arguments */
615 lua_assert(ci->top.p <= L->stack_last.p);
616 return ci;
617 }
618 default: { /* not a function */
619 func = tryfuncTM(L, func); /* try to get '__call' metamethod */
620 /* return luaD_precall(L, func, nresults); */
621 goto retry; /* try again with metamethod */
622 }
623 }
624}
625
626
627/*
628** Call a function (C or Lua) through C. 'inc' can be 1 (increment
629** number of recursive invocations in the C stack) or nyci (the same
630** plus increment number of non-yieldable calls).
631** This function can be called with some use of EXTRA_STACK, so it should
632** check the stack before doing anything else. 'luaD_precall' already
633** does that.
634*/
635l_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) {
636 CallInfo *ci;
637 L->nCcalls += inc;
638 if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) {
639 checkstackp(L, 0, func); /* free any use of EXTRA_STACK */
640 luaE_checkcstack(L);
641 }
642 if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */
643 ci->callstatus = CIST_FRESH; /* mark that it is a "fresh" execute */
644 luaV_execute(L, ci); /* call it */
645 }
646 L->nCcalls -= inc;
647}
648
649
650/*
651** External interface for 'ccall'
652*/
653void luaD_call (lua_State *L, StkId func, int nResults) {
654 ccall(L, func, nResults, 1);
655}
656
657
658/*
659** Similar to 'luaD_call', but does not allow yields during the call.
660*/
661void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
662 ccall(L, func, nResults, nyci);
663}
664
665
666/*
667** Finish the job of 'lua_pcallk' after it was interrupted by an yield.
668** (The caller, 'finishCcall', does the final call to 'adjustresults'.)
669** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.
670** If a '__close' method yields here, eventually control will be back
671** to 'finishCcall' (when that '__close' method finally returns) and
672** 'finishpcallk' will run again and close any still pending '__close'
673** methods. Similarly, if a '__close' method errs, 'precover' calls
674** 'unroll' which calls ''finishCcall' and we are back here again, to
675** close any pending '__close' methods.
676** Note that, up to the call to 'luaF_close', the corresponding
677** 'CallInfo' is not modified, so that this repeated run works like the
678** first one (except that it has at least one less '__close' to do). In
679** particular, field CIST_RECST preserves the error status across these
680** multiple runs, changing only if there is a new error.
681*/
682static int finishpcallk (lua_State *L, CallInfo *ci) {
683 int status = getcistrecst(ci); /* get original status */
684 if (l_likely(status == LUA_OK)) /* no error? */
685 status = LUA_YIELD; /* was interrupted by an yield */
686 else { /* error */
687 StkId func = restorestack(L, ci->u2.funcidx);
688 L->allowhook = getoah(ci->callstatus); /* restore 'allowhook' */
689 func = luaF_close(L, func, status, 1); /* can yield or raise an error */
690 luaD_seterrorobj(L, status, func);
691 luaD_shrinkstack(L); /* restore stack size in case of overflow */
692 setcistrecst(ci, LUA_OK); /* clear original status */
693 }
694 ci->callstatus &= ~CIST_YPCALL;
695 L->errfunc = ci->u.c.old_errfunc;
696 /* if it is here, there were errors or yields; unlike 'lua_pcallk',
697 do not change status */
698 return status;
699}
700
701
702/*
703** Completes the execution of a C function interrupted by an yield.
704** The interruption must have happened while the function was either
705** closing its tbc variables in 'moveresults' or executing
706** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes
707** 'luaD_poscall'. In the second case, the call to 'finishpcallk'
708** finishes the interrupted execution of 'lua_pcallk'. After that, it
709** calls the continuation of the interrupted function and finally it
710** completes the job of the 'luaD_call' that called the function. In
711** the call to 'adjustresults', we do not know the number of results
712** of the function called by 'lua_callk'/'lua_pcallk', so we are
713** conservative and use LUA_MULTRET (always adjust).
714*/
715static void finishCcall (lua_State *L, CallInfo *ci) {
716 int n; /* actual number of results from C function */
717 if (ci->callstatus & CIST_CLSRET) { /* was returning? */
718 lua_assert(hastocloseCfunc(ci->nresults));
719 n = ci->u2.nres; /* just redo 'luaD_poscall' */
720 /* don't need to reset CIST_CLSRET, as it will be set again anyway */
721 }
722 else {
723 int status = LUA_YIELD; /* default if there were no errors */
724 /* must have a continuation and must be able to call it */
725 lua_assert(ci->u.c.k != NULL && yieldable(L));
726 if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */
727 status = finishpcallk(L, ci); /* finish it */
728 adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */
729 lua_unlock(L);
730 n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation */
731 lua_lock(L);
732 api_checknelems(L, n);
733 }
734 luaD_poscall(L, ci, n); /* finish 'luaD_call' */
735}
736
737
738/*
739** Executes "full continuation" (everything in the stack) of a
740** previously interrupted coroutine until the stack is empty (or another
741** interruption long-jumps out of the loop).
742*/
743static void unroll (lua_State *L, void *ud) {
744 CallInfo *ci;
745 UNUSED(ud);
746 while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
747 if (!isLua(ci)) /* C function? */
748 finishCcall(L, ci); /* complete its execution */
749 else { /* Lua function */
750 luaV_finishOp(L); /* finish interrupted instruction */
751 luaV_execute(L, ci); /* execute down to higher C 'boundary' */
752 }
753 }
754}
755
756
757/*
758** Try to find a suspended protected call (a "recover point") for the
759** given thread.
760*/
761static CallInfo *findpcall (lua_State *L) {
762 CallInfo *ci;
763 for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
764 if (ci->callstatus & CIST_YPCALL)
765 return ci;
766 }
767 return NULL; /* no pending pcall */
768}
769
770
771/*
772** Signal an error in the call to 'lua_resume', not in the execution
773** of the coroutine itself. (Such errors should not be handled by any
774** coroutine error handler and should not kill the coroutine.)
775*/
776static int resume_error (lua_State *L, const char *msg, int narg) {
777 L->top.p -= narg; /* remove args from the stack */
778 setsvalue2s(L, L->top.p, luaS_new(L, msg)); /* push error message */
779 api_incr_top(L);
780 lua_unlock(L);
781 return LUA_ERRRUN;
782}
783
784
785/*
786** Do the work for 'lua_resume' in protected mode. Most of the work
787** depends on the status of the coroutine: initial state, suspended
788** inside a hook, or regularly suspended (optionally with a continuation
789** function), plus erroneous cases: non-suspended coroutine or dead
790** coroutine.
791*/
792static void resume (lua_State *L, void *ud) {
793 int n = *(cast(int*, ud)); /* number of arguments */
794 StkId firstArg = L->top.p - n; /* first argument */
795 CallInfo *ci = L->ci;
796 if (L->status == LUA_OK) /* starting a coroutine? */
797 ccall(L, firstArg - 1, LUA_MULTRET, 0); /* just call its body */
798 else { /* resuming from previous yield */
799 lua_assert(L->status == LUA_YIELD);
800 L->status = LUA_OK; /* mark that it is running (again) */
801 if (isLua(ci)) { /* yielded inside a hook? */
802 /* undo increment made by 'luaG_traceexec': instruction was not
803 executed yet */
804 lua_assert(ci->callstatus & CIST_HOOKYIELD);
805 ci->u.l.savedpc--;
806 L->top.p = firstArg; /* discard arguments */
807 luaV_execute(L, ci); /* just continue running Lua code */
808 }
809 else { /* 'common' yield */
810 if (ci->u.c.k != NULL) { /* does it have a continuation function? */
811 lua_unlock(L);
812 n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
813 lua_lock(L);
814 api_checknelems(L, n);
815 }
816 luaD_poscall(L, ci, n); /* finish 'luaD_call' */
817 }
818 unroll(L, NULL); /* run continuation */
819 }
820}
821
822
823/*
824** Unrolls a coroutine in protected mode while there are recoverable
825** errors, that is, errors inside a protected call. (Any error
826** interrupts 'unroll', and this loop protects it again so it can
827** continue.) Stops with a normal end (status == LUA_OK), an yield
828** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't
829** find a recover point).
830*/
831static int precover (lua_State *L, int status) {
832 CallInfo *ci;
833 while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
834 L->ci = ci; /* go down to recovery functions */
835 setcistrecst(ci, status); /* status to finish 'pcall' */
836 status = luaD_rawrunprotected(L, unroll, NULL);
837 }
838 return status;
839}
840
841
842LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
843 int *nresults) {
844 int status;
845 lua_lock(L);
846 if (L->status == LUA_OK) { /* may be starting a coroutine */
847 if (L->ci != &L->base_ci) /* not in base level? */
848 return resume_error(L, "cannot resume non-suspended coroutine", nargs);
849 else if (L->top.p - (L->ci->func.p + 1) == nargs) /* no function? */
850 return resume_error(L, "cannot resume dead coroutine", nargs);
851 }
852 else if (L->status != LUA_YIELD) /* ended with errors? */
853 return resume_error(L, "cannot resume dead coroutine", nargs);
854 L->nCcalls = (from) ? getCcalls(from) : 0;
855 if (getCcalls(L) >= LUAI_MAXCCALLS)
856 return resume_error(L, "C stack overflow", nargs);
857 L->nCcalls++;
858 luai_userstateresume(L, nargs);
859 api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
860 status = luaD_rawrunprotected(L, resume, &nargs);
861 /* continue running after recoverable errors */
862 status = precover(L, status);
863 if (l_likely(!errorstatus(status)))
864 lua_assert(status == L->status); /* normal end or yield */
865 else { /* unrecoverable error */
866 L->status = cast_byte(status); /* mark thread as 'dead' */
867 luaD_seterrorobj(L, status, L->top.p); /* push error message */
868 L->ci->top.p = L->top.p;
869 }
870 *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
871 : cast_int(L->top.p - (L->ci->func.p + 1));
872 lua_unlock(L);
873 return status;
874}
875
876
877LUA_API int lua_isyieldable (lua_State *L) {
878 return yieldable(L);
879}
880
881
882LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
883 lua_KFunction k) {
884 CallInfo *ci;
885 luai_userstateyield(L, nresults);
886 lua_lock(L);
887 ci = L->ci;
888 api_checknelems(L, nresults);
889 if (l_unlikely(!yieldable(L))) {
890 if (L != G(L)->mainthread)
891 luaG_runerror(L, "attempt to yield across a C-call boundary");
892 else
893 luaG_runerror(L, "attempt to yield from outside a coroutine");
894 }
895 L->status = LUA_YIELD;
896 ci->u2.nyield = nresults; /* save number of results */
897 if (isLua(ci)) { /* inside a hook? */
898 lua_assert(!isLuacode(ci));
899 api_check(L, nresults == 0, "hooks cannot yield values");
900 api_check(L, k == NULL, "hooks cannot continue after yielding");
901 }
902 else {
903 if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
904 ci->u.c.ctx = ctx; /* save context */
905 luaD_throw(L, LUA_YIELD);
906 }
907 lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
908 lua_unlock(L);
909 return 0; /* return to 'luaD_hook' */
910}
911
912
913/*
914** Auxiliary structure to call 'luaF_close' in protected mode.
915*/
916struct CloseP {
917 StkId level;
918 int status;
919};
920
921
922/*
923** Auxiliary function to call 'luaF_close' in protected mode.
924*/
925static void closepaux (lua_State *L, void *ud) {
926 struct CloseP *pcl = cast(struct CloseP *, ud);
927 luaF_close(L, pcl->level, pcl->status, 0);
928}
929
930
931/*
932** Calls 'luaF_close' in protected mode. Return the original status
933** or, in case of errors, the new status.
934*/
935int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status) {
936 CallInfo *old_ci = L->ci;
937 lu_byte old_allowhooks = L->allowhook;
938 for (;;) { /* keep closing upvalues until no more errors */
939 struct CloseP pcl;
940 pcl.level = restorestack(L, level); pcl.status = status;
941 status = luaD_rawrunprotected(L, &closepaux, &pcl);
942 if (l_likely(status == LUA_OK)) /* no more errors? */
943 return pcl.status;
944 else { /* an error occurred; restore saved state and repeat */
945 L->ci = old_ci;
946 L->allowhook = old_allowhooks;
947 }
948 }
949}
950
951
952/*
953** Call the C function 'func' in protected mode, restoring basic
954** thread information ('allowhook', etc.) and in particular
955** its stack level in case of errors.
956*/
957int luaD_pcall (lua_State *L, Pfunc func, void *u,
958 ptrdiff_t old_top, ptrdiff_t ef) {
959 int status;
960 CallInfo *old_ci = L->ci;
961 lu_byte old_allowhooks = L->allowhook;
962 ptrdiff_t old_errfunc = L->errfunc;
963 L->errfunc = ef;
964 status = luaD_rawrunprotected(L, func, u);
965 if (l_unlikely(status != LUA_OK)) { /* an error occurred? */
966 L->ci = old_ci;
967 L->allowhook = old_allowhooks;
968 status = luaD_closeprotected(L, old_top, status);
969 luaD_seterrorobj(L, status, restorestack(L, old_top));
970 luaD_shrinkstack(L); /* restore stack size in case of overflow */
971 }
972 L->errfunc = old_errfunc;
973 return status;
974}
975
976
977
978/*
979** Execute a protected parser.
980*/
981struct SParser { /* data to 'f_parser' */
982 ZIO *z;
983 Mbuffer buff; /* dynamic structure used by the scanner */
984 Dyndata dyd; /* dynamic structures used by the parser */
985 const char *mode;
986 const char *name;
987};
988
989
990static void checkmode (lua_State *L, const char *mode, const char *x) {
991 if (mode && strchr(mode, x[0]) == NULL) {
992 luaO_pushfstring(L,
993 "attempt to load a %s chunk (mode is '%s')", x, mode);
994 luaD_throw(L, LUA_ERRSYNTAX);
995 }
996}
997
998
999static void f_parser (lua_State *L, void *ud) {
1000 LClosure *cl;
1001 struct SParser *p = cast(struct SParser *, ud);
1002 int c = zgetc(p->z); /* read first character */
1003 if (c == LUA_SIGNATURE[0]) {
1004 checkmode(L, p->mode, "binary");
1005 cl = luaU_undump(L, p->z, p->name);
1006 }
1007 else {
1008 checkmode(L, p->mode, "text");
1009 cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
1010 }
1011 lua_assert(cl->nupvalues == cl->p->sizeupvalues);
1012 luaF_initupvals(L, cl);
1013}
1014
1015
1016int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
1017 const char *mode) {
1018 struct SParser p;
1019 int status;
1020 incnny(L); /* cannot yield during parsing */
1021 p.z = z; p.name = name; p.mode = mode;
1022 p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
1023 p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
1024 p.dyd.label.arr = NULL; p.dyd.label.size = 0;
1025 luaZ_initbuffer(L, &p.buff);
1026 status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc);
1027 luaZ_freebuffer(L, &p.buff);
1028 luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
1029 luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
1030 luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
1031 decnny(L);
1032 return status;
1033}
1034
1035
diff --git a/vendor/lua-5.4.8/src/ldo.h b/vendor/lua-5.4.8/src/ldo.h
new file mode 100644
index 0000000..4de9540
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ldo.h
@@ -0,0 +1,88 @@
1/*
2** $Id: ldo.h $
3** Stack and Call structure of Lua
4** See Copyright Notice in lua.h
5*/
6
7#ifndef ldo_h
8#define ldo_h
9
10
11#include "llimits.h"
12#include "lobject.h"
13#include "lstate.h"
14#include "lzio.h"
15
16
17/*
18** Macro to check stack size and grow stack if needed. Parameters
19** 'pre'/'pos' allow the macro to preserve a pointer into the
20** stack across reallocations, doing the work only when needed.
21** It also allows the running of one GC step when the stack is
22** reallocated.
23** 'condmovestack' is used in heavy tests to force a stack reallocation
24** at every check.
25*/
26#define luaD_checkstackaux(L,n,pre,pos) \
27 if (l_unlikely(L->stack_last.p - L->top.p <= (n))) \
28 { pre; luaD_growstack(L, n, 1); pos; } \
29 else { condmovestack(L,pre,pos); }
30
31/* In general, 'pre'/'pos' are empty (nothing to save) */
32#define luaD_checkstack(L,n) luaD_checkstackaux(L,n,(void)0,(void)0)
33
34
35
36#define savestack(L,pt) (cast_charp(pt) - cast_charp(L->stack.p))
37#define restorestack(L,n) cast(StkId, cast_charp(L->stack.p) + (n))
38
39
40/* macro to check stack size, preserving 'p' */
41#define checkstackp(L,n,p) \
42 luaD_checkstackaux(L, n, \
43 ptrdiff_t t__ = savestack(L, p), /* save 'p' */ \
44 p = restorestack(L, t__)) /* 'pos' part: restore 'p' */
45
46
47/* macro to check stack size and GC, preserving 'p' */
48#define checkstackGCp(L,n,p) \
49 luaD_checkstackaux(L, n, \
50 ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \
51 luaC_checkGC(L), /* stack grow uses memory */ \
52 p = restorestack(L, t__)) /* 'pos' part: restore 'p' */
53
54
55/* macro to check stack size and GC */
56#define checkstackGC(L,fsize) \
57 luaD_checkstackaux(L, (fsize), luaC_checkGC(L), (void)0)
58
59
60/* type of protected functions, to be ran by 'runprotected' */
61typedef void (*Pfunc) (lua_State *L, void *ud);
62
63LUAI_FUNC l_noret luaD_errerr (lua_State *L);
64LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop);
65LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
66 const char *mode);
67LUAI_FUNC void luaD_hook (lua_State *L, int event, int line,
68 int fTransfer, int nTransfer);
69LUAI_FUNC void luaD_hookcall (lua_State *L, CallInfo *ci);
70LUAI_FUNC int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,
71 int narg1, int delta);
72LUAI_FUNC CallInfo *luaD_precall (lua_State *L, StkId func, int nResults);
73LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults);
74LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults);
75LUAI_FUNC int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status);
76LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u,
77 ptrdiff_t oldtop, ptrdiff_t ef);
78LUAI_FUNC void luaD_poscall (lua_State *L, CallInfo *ci, int nres);
79LUAI_FUNC int luaD_reallocstack (lua_State *L, int newsize, int raiseerror);
80LUAI_FUNC int luaD_growstack (lua_State *L, int n, int raiseerror);
81LUAI_FUNC void luaD_shrinkstack (lua_State *L);
82LUAI_FUNC void luaD_inctop (lua_State *L);
83
84LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode);
85LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);
86
87#endif
88
diff --git a/vendor/lua-5.4.8/src/ldump.c b/vendor/lua-5.4.8/src/ldump.c
new file mode 100644
index 0000000..f231691
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ldump.c
@@ -0,0 +1,230 @@
1/*
2** $Id: ldump.c $
3** save precompiled Lua chunks
4** See Copyright Notice in lua.h
5*/
6
7#define ldump_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <limits.h>
14#include <stddef.h>
15
16#include "lua.h"
17
18#include "lobject.h"
19#include "lstate.h"
20#include "lundump.h"
21
22
23typedef struct {
24 lua_State *L;
25 lua_Writer writer;
26 void *data;
27 int strip;
28 int status;
29} DumpState;
30
31
32/*
33** All high-level dumps go through dumpVector; you can change it to
34** change the endianness of the result
35*/
36#define dumpVector(D,v,n) dumpBlock(D,v,(n)*sizeof((v)[0]))
37
38#define dumpLiteral(D, s) dumpBlock(D,s,sizeof(s) - sizeof(char))
39
40
41static void dumpBlock (DumpState *D, const void *b, size_t size) {
42 if (D->status == 0 && size > 0) {
43 lua_unlock(D->L);
44 D->status = (*D->writer)(D->L, b, size, D->data);
45 lua_lock(D->L);
46 }
47}
48
49
50#define dumpVar(D,x) dumpVector(D,&x,1)
51
52
53static void dumpByte (DumpState *D, int y) {
54 lu_byte x = (lu_byte)y;
55 dumpVar(D, x);
56}
57
58
59/*
60** 'dumpSize' buffer size: each byte can store up to 7 bits. (The "+6"
61** rounds up the division.)
62*/
63#define DIBS ((sizeof(size_t) * CHAR_BIT + 6) / 7)
64
65static void dumpSize (DumpState *D, size_t x) {
66 lu_byte buff[DIBS];
67 int n = 0;
68 do {
69 buff[DIBS - (++n)] = x & 0x7f; /* fill buffer in reverse order */
70 x >>= 7;
71 } while (x != 0);
72 buff[DIBS - 1] |= 0x80; /* mark last byte */
73 dumpVector(D, buff + DIBS - n, n);
74}
75
76
77static void dumpInt (DumpState *D, int x) {
78 dumpSize(D, x);
79}
80
81
82static void dumpNumber (DumpState *D, lua_Number x) {
83 dumpVar(D, x);
84}
85
86
87static void dumpInteger (DumpState *D, lua_Integer x) {
88 dumpVar(D, x);
89}
90
91
92static void dumpString (DumpState *D, const TString *s) {
93 if (s == NULL)
94 dumpSize(D, 0);
95 else {
96 size_t size = tsslen(s);
97 const char *str = getstr(s);
98 dumpSize(D, size + 1);
99 dumpVector(D, str, size);
100 }
101}
102
103
104static void dumpCode (DumpState *D, const Proto *f) {
105 dumpInt(D, f->sizecode);
106 dumpVector(D, f->code, f->sizecode);
107}
108
109
110static void dumpFunction(DumpState *D, const Proto *f, TString *psource);
111
112static void dumpConstants (DumpState *D, const Proto *f) {
113 int i;
114 int n = f->sizek;
115 dumpInt(D, n);
116 for (i = 0; i < n; i++) {
117 const TValue *o = &f->k[i];
118 int tt = ttypetag(o);
119 dumpByte(D, tt);
120 switch (tt) {
121 case LUA_VNUMFLT:
122 dumpNumber(D, fltvalue(o));
123 break;
124 case LUA_VNUMINT:
125 dumpInteger(D, ivalue(o));
126 break;
127 case LUA_VSHRSTR:
128 case LUA_VLNGSTR:
129 dumpString(D, tsvalue(o));
130 break;
131 default:
132 lua_assert(tt == LUA_VNIL || tt == LUA_VFALSE || tt == LUA_VTRUE);
133 }
134 }
135}
136
137
138static void dumpProtos (DumpState *D, const Proto *f) {
139 int i;
140 int n = f->sizep;
141 dumpInt(D, n);
142 for (i = 0; i < n; i++)
143 dumpFunction(D, f->p[i], f->source);
144}
145
146
147static void dumpUpvalues (DumpState *D, const Proto *f) {
148 int i, n = f->sizeupvalues;
149 dumpInt(D, n);
150 for (i = 0; i < n; i++) {
151 dumpByte(D, f->upvalues[i].instack);
152 dumpByte(D, f->upvalues[i].idx);
153 dumpByte(D, f->upvalues[i].kind);
154 }
155}
156
157
158static void dumpDebug (DumpState *D, const Proto *f) {
159 int i, n;
160 n = (D->strip) ? 0 : f->sizelineinfo;
161 dumpInt(D, n);
162 dumpVector(D, f->lineinfo, n);
163 n = (D->strip) ? 0 : f->sizeabslineinfo;
164 dumpInt(D, n);
165 for (i = 0; i < n; i++) {
166 dumpInt(D, f->abslineinfo[i].pc);
167 dumpInt(D, f->abslineinfo[i].line);
168 }
169 n = (D->strip) ? 0 : f->sizelocvars;
170 dumpInt(D, n);
171 for (i = 0; i < n; i++) {
172 dumpString(D, f->locvars[i].varname);
173 dumpInt(D, f->locvars[i].startpc);
174 dumpInt(D, f->locvars[i].endpc);
175 }
176 n = (D->strip) ? 0 : f->sizeupvalues;
177 dumpInt(D, n);
178 for (i = 0; i < n; i++)
179 dumpString(D, f->upvalues[i].name);
180}
181
182
183static void dumpFunction (DumpState *D, const Proto *f, TString *psource) {
184 if (D->strip || f->source == psource)
185 dumpString(D, NULL); /* no debug info or same source as its parent */
186 else
187 dumpString(D, f->source);
188 dumpInt(D, f->linedefined);
189 dumpInt(D, f->lastlinedefined);
190 dumpByte(D, f->numparams);
191 dumpByte(D, f->is_vararg);
192 dumpByte(D, f->maxstacksize);
193 dumpCode(D, f);
194 dumpConstants(D, f);
195 dumpUpvalues(D, f);
196 dumpProtos(D, f);
197 dumpDebug(D, f);
198}
199
200
201static void dumpHeader (DumpState *D) {
202 dumpLiteral(D, LUA_SIGNATURE);
203 dumpByte(D, LUAC_VERSION);
204 dumpByte(D, LUAC_FORMAT);
205 dumpLiteral(D, LUAC_DATA);
206 dumpByte(D, sizeof(Instruction));
207 dumpByte(D, sizeof(lua_Integer));
208 dumpByte(D, sizeof(lua_Number));
209 dumpInteger(D, LUAC_INT);
210 dumpNumber(D, LUAC_NUM);
211}
212
213
214/*
215** dump Lua function as precompiled chunk
216*/
217int luaU_dump(lua_State *L, const Proto *f, lua_Writer w, void *data,
218 int strip) {
219 DumpState D;
220 D.L = L;
221 D.writer = w;
222 D.data = data;
223 D.strip = strip;
224 D.status = 0;
225 dumpHeader(&D);
226 dumpByte(&D, f->sizeupvalues);
227 dumpFunction(&D, f, NULL);
228 return D.status;
229}
230
diff --git a/vendor/lua-5.4.8/src/lfunc.c b/vendor/lua-5.4.8/src/lfunc.c
new file mode 100644
index 0000000..0945f24
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lfunc.c
@@ -0,0 +1,294 @@
1/*
2** $Id: lfunc.c $
3** Auxiliary functions to manipulate prototypes and closures
4** See Copyright Notice in lua.h
5*/
6
7#define lfunc_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <stddef.h>
14
15#include "lua.h"
16
17#include "ldebug.h"
18#include "ldo.h"
19#include "lfunc.h"
20#include "lgc.h"
21#include "lmem.h"
22#include "lobject.h"
23#include "lstate.h"
24
25
26
27CClosure *luaF_newCclosure (lua_State *L, int nupvals) {
28 GCObject *o = luaC_newobj(L, LUA_VCCL, sizeCclosure(nupvals));
29 CClosure *c = gco2ccl(o);
30 c->nupvalues = cast_byte(nupvals);
31 return c;
32}
33
34
35LClosure *luaF_newLclosure (lua_State *L, int nupvals) {
36 GCObject *o = luaC_newobj(L, LUA_VLCL, sizeLclosure(nupvals));
37 LClosure *c = gco2lcl(o);
38 c->p = NULL;
39 c->nupvalues = cast_byte(nupvals);
40 while (nupvals--) c->upvals[nupvals] = NULL;
41 return c;
42}
43
44
45/*
46** fill a closure with new closed upvalues
47*/
48void luaF_initupvals (lua_State *L, LClosure *cl) {
49 int i;
50 for (i = 0; i < cl->nupvalues; i++) {
51 GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));
52 UpVal *uv = gco2upv(o);
53 uv->v.p = &uv->u.value; /* make it closed */
54 setnilvalue(uv->v.p);
55 cl->upvals[i] = uv;
56 luaC_objbarrier(L, cl, uv);
57 }
58}
59
60
61/*
62** Create a new upvalue at the given level, and link it to the list of
63** open upvalues of 'L' after entry 'prev'.
64**/
65static UpVal *newupval (lua_State *L, StkId level, UpVal **prev) {
66 GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));
67 UpVal *uv = gco2upv(o);
68 UpVal *next = *prev;
69 uv->v.p = s2v(level); /* current value lives in the stack */
70 uv->u.open.next = next; /* link it to list of open upvalues */
71 uv->u.open.previous = prev;
72 if (next)
73 next->u.open.previous = &uv->u.open.next;
74 *prev = uv;
75 if (!isintwups(L)) { /* thread not in list of threads with upvalues? */
76 L->twups = G(L)->twups; /* link it to the list */
77 G(L)->twups = L;
78 }
79 return uv;
80}
81
82
83/*
84** Find and reuse, or create if it does not exist, an upvalue
85** at the given level.
86*/
87UpVal *luaF_findupval (lua_State *L, StkId level) {
88 UpVal **pp = &L->openupval;
89 UpVal *p;
90 lua_assert(isintwups(L) || L->openupval == NULL);
91 while ((p = *pp) != NULL && uplevel(p) >= level) { /* search for it */
92 lua_assert(!isdead(G(L), p));
93 if (uplevel(p) == level) /* corresponding upvalue? */
94 return p; /* return it */
95 pp = &p->u.open.next;
96 }
97 /* not found: create a new upvalue after 'pp' */
98 return newupval(L, level, pp);
99}
100
101
102/*
103** Call closing method for object 'obj' with error message 'err'. The
104** boolean 'yy' controls whether the call is yieldable.
105** (This function assumes EXTRA_STACK.)
106*/
107static void callclosemethod (lua_State *L, TValue *obj, TValue *err, int yy) {
108 StkId top = L->top.p;
109 const TValue *tm = luaT_gettmbyobj(L, obj, TM_CLOSE);
110 setobj2s(L, top, tm); /* will call metamethod... */
111 setobj2s(L, top + 1, obj); /* with 'self' as the 1st argument */
112 setobj2s(L, top + 2, err); /* and error msg. as 2nd argument */
113 L->top.p = top + 3; /* add function and arguments */
114 if (yy)
115 luaD_call(L, top, 0);
116 else
117 luaD_callnoyield(L, top, 0);
118}
119
120
121/*
122** Check whether object at given level has a close metamethod and raise
123** an error if not.
124*/
125static void checkclosemth (lua_State *L, StkId level) {
126 const TValue *tm = luaT_gettmbyobj(L, s2v(level), TM_CLOSE);
127 if (ttisnil(tm)) { /* no metamethod? */
128 int idx = cast_int(level - L->ci->func.p); /* variable index */
129 const char *vname = luaG_findlocal(L, L->ci, idx, NULL);
130 if (vname == NULL) vname = "?";
131 luaG_runerror(L, "variable '%s' got a non-closable value", vname);
132 }
133}
134
135
136/*
137** Prepare and call a closing method.
138** If status is CLOSEKTOP, the call to the closing method will be pushed
139** at the top of the stack. Otherwise, values can be pushed right after
140** the 'level' of the upvalue being closed, as everything after that
141** won't be used again.
142*/
143static void prepcallclosemth (lua_State *L, StkId level, int status, int yy) {
144 TValue *uv = s2v(level); /* value being closed */
145 TValue *errobj;
146 if (status == CLOSEKTOP)
147 errobj = &G(L)->nilvalue; /* error object is nil */
148 else { /* 'luaD_seterrorobj' will set top to level + 2 */
149 errobj = s2v(level + 1); /* error object goes after 'uv' */
150 luaD_seterrorobj(L, status, level + 1); /* set error object */
151 }
152 callclosemethod(L, uv, errobj, yy);
153}
154
155
156/*
157** Maximum value for deltas in 'tbclist', dependent on the type
158** of delta. (This macro assumes that an 'L' is in scope where it
159** is used.)
160*/
161#define MAXDELTA \
162 ((256ul << ((sizeof(L->stack.p->tbclist.delta) - 1) * 8)) - 1)
163
164
165/*
166** Insert a variable in the list of to-be-closed variables.
167*/
168void luaF_newtbcupval (lua_State *L, StkId level) {
169 lua_assert(level > L->tbclist.p);
170 if (l_isfalse(s2v(level)))
171 return; /* false doesn't need to be closed */
172 checkclosemth(L, level); /* value must have a close method */
173 while (cast_uint(level - L->tbclist.p) > MAXDELTA) {
174 L->tbclist.p += MAXDELTA; /* create a dummy node at maximum delta */
175 L->tbclist.p->tbclist.delta = 0;
176 }
177 level->tbclist.delta = cast(unsigned short, level - L->tbclist.p);
178 L->tbclist.p = level;
179}
180
181
182void luaF_unlinkupval (UpVal *uv) {
183 lua_assert(upisopen(uv));
184 *uv->u.open.previous = uv->u.open.next;
185 if (uv->u.open.next)
186 uv->u.open.next->u.open.previous = uv->u.open.previous;
187}
188
189
190/*
191** Close all upvalues up to the given stack level.
192*/
193void luaF_closeupval (lua_State *L, StkId level) {
194 UpVal *uv;
195 StkId upl; /* stack index pointed by 'uv' */
196 while ((uv = L->openupval) != NULL && (upl = uplevel(uv)) >= level) {
197 TValue *slot = &uv->u.value; /* new position for value */
198 lua_assert(uplevel(uv) < L->top.p);
199 luaF_unlinkupval(uv); /* remove upvalue from 'openupval' list */
200 setobj(L, slot, uv->v.p); /* move value to upvalue slot */
201 uv->v.p = slot; /* now current value lives here */
202 if (!iswhite(uv)) { /* neither white nor dead? */
203 nw2black(uv); /* closed upvalues cannot be gray */
204 luaC_barrier(L, uv, slot);
205 }
206 }
207}
208
209
210/*
211** Remove first element from the tbclist plus its dummy nodes.
212*/
213static void poptbclist (lua_State *L) {
214 StkId tbc = L->tbclist.p;
215 lua_assert(tbc->tbclist.delta > 0); /* first element cannot be dummy */
216 tbc -= tbc->tbclist.delta;
217 while (tbc > L->stack.p && tbc->tbclist.delta == 0)
218 tbc -= MAXDELTA; /* remove dummy nodes */
219 L->tbclist.p = tbc;
220}
221
222
223/*
224** Close all upvalues and to-be-closed variables up to the given stack
225** level. Return restored 'level'.
226*/
227StkId luaF_close (lua_State *L, StkId level, int status, int yy) {
228 ptrdiff_t levelrel = savestack(L, level);
229 luaF_closeupval(L, level); /* first, close the upvalues */
230 while (L->tbclist.p >= level) { /* traverse tbc's down to that level */
231 StkId tbc = L->tbclist.p; /* get variable index */
232 poptbclist(L); /* remove it from list */
233 prepcallclosemth(L, tbc, status, yy); /* close variable */
234 level = restorestack(L, levelrel);
235 }
236 return level;
237}
238
239
240Proto *luaF_newproto (lua_State *L) {
241 GCObject *o = luaC_newobj(L, LUA_VPROTO, sizeof(Proto));
242 Proto *f = gco2p(o);
243 f->k = NULL;
244 f->sizek = 0;
245 f->p = NULL;
246 f->sizep = 0;
247 f->code = NULL;
248 f->sizecode = 0;
249 f->lineinfo = NULL;
250 f->sizelineinfo = 0;
251 f->abslineinfo = NULL;
252 f->sizeabslineinfo = 0;
253 f->upvalues = NULL;
254 f->sizeupvalues = 0;
255 f->numparams = 0;
256 f->is_vararg = 0;
257 f->maxstacksize = 0;
258 f->locvars = NULL;
259 f->sizelocvars = 0;
260 f->linedefined = 0;
261 f->lastlinedefined = 0;
262 f->source = NULL;
263 return f;
264}
265
266
267void luaF_freeproto (lua_State *L, Proto *f) {
268 luaM_freearray(L, f->code, f->sizecode);
269 luaM_freearray(L, f->p, f->sizep);
270 luaM_freearray(L, f->k, f->sizek);
271 luaM_freearray(L, f->lineinfo, f->sizelineinfo);
272 luaM_freearray(L, f->abslineinfo, f->sizeabslineinfo);
273 luaM_freearray(L, f->locvars, f->sizelocvars);
274 luaM_freearray(L, f->upvalues, f->sizeupvalues);
275 luaM_free(L, f);
276}
277
278
279/*
280** Look for n-th local variable at line 'line' in function 'func'.
281** Returns NULL if not found.
282*/
283const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
284 int i;
285 for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {
286 if (pc < f->locvars[i].endpc) { /* is variable active? */
287 local_number--;
288 if (local_number == 0)
289 return getstr(f->locvars[i].varname);
290 }
291 }
292 return NULL; /* not found */
293}
294
diff --git a/vendor/lua-5.4.8/src/lfunc.h b/vendor/lua-5.4.8/src/lfunc.h
new file mode 100644
index 0000000..3be265e
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lfunc.h
@@ -0,0 +1,64 @@
1/*
2** $Id: lfunc.h $
3** Auxiliary functions to manipulate prototypes and closures
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lfunc_h
8#define lfunc_h
9
10
11#include "lobject.h"
12
13
14#define sizeCclosure(n) (cast_int(offsetof(CClosure, upvalue)) + \
15 cast_int(sizeof(TValue)) * (n))
16
17#define sizeLclosure(n) (cast_int(offsetof(LClosure, upvals)) + \
18 cast_int(sizeof(TValue *)) * (n))
19
20
21/* test whether thread is in 'twups' list */
22#define isintwups(L) (L->twups != L)
23
24
25/*
26** maximum number of upvalues in a closure (both C and Lua). (Value
27** must fit in a VM register.)
28*/
29#define MAXUPVAL 255
30
31
32#define upisopen(up) ((up)->v.p != &(up)->u.value)
33
34
35#define uplevel(up) check_exp(upisopen(up), cast(StkId, (up)->v.p))
36
37
38/*
39** maximum number of misses before giving up the cache of closures
40** in prototypes
41*/
42#define MAXMISS 10
43
44
45
46/* special status to close upvalues preserving the top of the stack */
47#define CLOSEKTOP (-1)
48
49
50LUAI_FUNC Proto *luaF_newproto (lua_State *L);
51LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nupvals);
52LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nupvals);
53LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl);
54LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
55LUAI_FUNC void luaF_newtbcupval (lua_State *L, StkId level);
56LUAI_FUNC void luaF_closeupval (lua_State *L, StkId level);
57LUAI_FUNC StkId luaF_close (lua_State *L, StkId level, int status, int yy);
58LUAI_FUNC void luaF_unlinkupval (UpVal *uv);
59LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
60LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
61 int pc);
62
63
64#endif
diff --git a/vendor/lua-5.4.8/src/lgc.c b/vendor/lua-5.4.8/src/lgc.c
new file mode 100644
index 0000000..5817f9e
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lgc.c
@@ -0,0 +1,1743 @@
1/*
2** $Id: lgc.c $
3** Garbage Collector
4** See Copyright Notice in lua.h
5*/
6
7#define lgc_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12#include <stdio.h>
13#include <string.h>
14
15
16#include "lua.h"
17
18#include "ldebug.h"
19#include "ldo.h"
20#include "lfunc.h"
21#include "lgc.h"
22#include "lmem.h"
23#include "lobject.h"
24#include "lstate.h"
25#include "lstring.h"
26#include "ltable.h"
27#include "ltm.h"
28
29
30/*
31** Maximum number of elements to sweep in each single step.
32** (Large enough to dissipate fixed overheads but small enough
33** to allow small steps for the collector.)
34*/
35#define GCSWEEPMAX 100
36
37/*
38** Maximum number of finalizers to call in each single step.
39*/
40#define GCFINMAX 10
41
42
43/*
44** Cost of calling one finalizer.
45*/
46#define GCFINALIZECOST 50
47
48
49/*
50** The equivalent, in bytes, of one unit of "work" (visiting a slot,
51** sweeping an object, etc.)
52*/
53#define WORK2MEM sizeof(TValue)
54
55
56/*
57** macro to adjust 'pause': 'pause' is actually used like
58** 'pause / PAUSEADJ' (value chosen by tests)
59*/
60#define PAUSEADJ 100
61
62
63/* mask with all color bits */
64#define maskcolors (bitmask(BLACKBIT) | WHITEBITS)
65
66/* mask with all GC bits */
67#define maskgcbits (maskcolors | AGEBITS)
68
69
70/* macro to erase all color bits then set only the current white bit */
71#define makewhite(g,x) \
72 (x->marked = cast_byte((x->marked & ~maskcolors) | luaC_white(g)))
73
74/* make an object gray (neither white nor black) */
75#define set2gray(x) resetbits(x->marked, maskcolors)
76
77
78/* make an object black (coming from any color) */
79#define set2black(x) \
80 (x->marked = cast_byte((x->marked & ~WHITEBITS) | bitmask(BLACKBIT)))
81
82
83#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
84
85#define keyiswhite(n) (keyiscollectable(n) && iswhite(gckey(n)))
86
87
88/*
89** Protected access to objects in values
90*/
91#define gcvalueN(o) (iscollectable(o) ? gcvalue(o) : NULL)
92
93
94#define markvalue(g,o) { checkliveness(g->mainthread,o); \
95 if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
96
97#define markkey(g, n) { if keyiswhite(n) reallymarkobject(g,gckey(n)); }
98
99#define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); }
100
101/*
102** mark an object that can be NULL (either because it is really optional,
103** or it was stripped as debug info, or inside an uncompleted structure)
104*/
105#define markobjectN(g,t) { if (t) markobject(g,t); }
106
107static void reallymarkobject (global_State *g, GCObject *o);
108static lu_mem atomic (lua_State *L);
109static void entersweep (lua_State *L);
110
111
112/*
113** {======================================================
114** Generic functions
115** =======================================================
116*/
117
118
119/*
120** one after last element in a hash array
121*/
122#define gnodelast(h) gnode(h, cast_sizet(sizenode(h)))
123
124
125static GCObject **getgclist (GCObject *o) {
126 switch (o->tt) {
127 case LUA_VTABLE: return &gco2t(o)->gclist;
128 case LUA_VLCL: return &gco2lcl(o)->gclist;
129 case LUA_VCCL: return &gco2ccl(o)->gclist;
130 case LUA_VTHREAD: return &gco2th(o)->gclist;
131 case LUA_VPROTO: return &gco2p(o)->gclist;
132 case LUA_VUSERDATA: {
133 Udata *u = gco2u(o);
134 lua_assert(u->nuvalue > 0);
135 return &u->gclist;
136 }
137 default: lua_assert(0); return 0;
138 }
139}
140
141
142/*
143** Link a collectable object 'o' with a known type into the list 'p'.
144** (Must be a macro to access the 'gclist' field in different types.)
145*/
146#define linkgclist(o,p) linkgclist_(obj2gco(o), &(o)->gclist, &(p))
147
148static void linkgclist_ (GCObject *o, GCObject **pnext, GCObject **list) {
149 lua_assert(!isgray(o)); /* cannot be in a gray list */
150 *pnext = *list;
151 *list = o;
152 set2gray(o); /* now it is */
153}
154
155
156/*
157** Link a generic collectable object 'o' into the list 'p'.
158*/
159#define linkobjgclist(o,p) linkgclist_(obj2gco(o), getgclist(o), &(p))
160
161
162
163/*
164** Clear keys for empty entries in tables. If entry is empty, mark its
165** entry as dead. This allows the collection of the key, but keeps its
166** entry in the table: its removal could break a chain and could break
167** a table traversal. Other places never manipulate dead keys, because
168** its associated empty value is enough to signal that the entry is
169** logically empty.
170*/
171static void clearkey (Node *n) {
172 lua_assert(isempty(gval(n)));
173 if (keyiscollectable(n))
174 setdeadkey(n); /* unused key; remove it */
175}
176
177
178/*
179** tells whether a key or value can be cleared from a weak
180** table. Non-collectable objects are never removed from weak
181** tables. Strings behave as 'values', so are never removed too. for
182** other objects: if really collected, cannot keep them; for objects
183** being finalized, keep them in keys, but not in values
184*/
185static int iscleared (global_State *g, const GCObject *o) {
186 if (o == NULL) return 0; /* non-collectable value */
187 else if (novariant(o->tt) == LUA_TSTRING) {
188 markobject(g, o); /* strings are 'values', so are never weak */
189 return 0;
190 }
191 else return iswhite(o);
192}
193
194
195/*
196** Barrier that moves collector forward, that is, marks the white object
197** 'v' being pointed by the black object 'o'. In the generational
198** mode, 'v' must also become old, if 'o' is old; however, it cannot
199** be changed directly to OLD, because it may still point to non-old
200** objects. So, it is marked as OLD0. In the next cycle it will become
201** OLD1, and in the next it will finally become OLD (regular old). By
202** then, any object it points to will also be old. If called in the
203** incremental sweep phase, it clears the black object to white (sweep
204** it) to avoid other barrier calls for this same object. (That cannot
205** be done is generational mode, as its sweep does not distinguish
206** whites from deads.)
207*/
208void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
209 global_State *g = G(L);
210 lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
211 if (keepinvariant(g)) { /* must keep invariant? */
212 reallymarkobject(g, v); /* restore invariant */
213 if (isold(o)) {
214 lua_assert(!isold(v)); /* white object could not be old */
215 setage(v, G_OLD0); /* restore generational invariant */
216 }
217 }
218 else { /* sweep phase */
219 lua_assert(issweepphase(g));
220 if (g->gckind == KGC_INC) /* incremental mode? */
221 makewhite(g, o); /* mark 'o' as white to avoid other barriers */
222 }
223}
224
225
226/*
227** barrier that moves collector backward, that is, mark the black object
228** pointing to a white object as gray again.
229*/
230void luaC_barrierback_ (lua_State *L, GCObject *o) {
231 global_State *g = G(L);
232 lua_assert(isblack(o) && !isdead(g, o));
233 lua_assert((g->gckind == KGC_GEN) == (isold(o) && getage(o) != G_TOUCHED1));
234 if (getage(o) == G_TOUCHED2) /* already in gray list? */
235 set2gray(o); /* make it gray to become touched1 */
236 else /* link it in 'grayagain' and paint it gray */
237 linkobjgclist(o, g->grayagain);
238 if (isold(o)) /* generational mode? */
239 setage(o, G_TOUCHED1); /* touched in current cycle */
240}
241
242
243void luaC_fix (lua_State *L, GCObject *o) {
244 global_State *g = G(L);
245 lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */
246 set2gray(o); /* they will be gray forever */
247 setage(o, G_OLD); /* and old forever */
248 g->allgc = o->next; /* remove object from 'allgc' list */
249 o->next = g->fixedgc; /* link it to 'fixedgc' list */
250 g->fixedgc = o;
251}
252
253
254/*
255** create a new collectable object (with given type, size, and offset)
256** and link it to 'allgc' list.
257*/
258GCObject *luaC_newobjdt (lua_State *L, int tt, size_t sz, size_t offset) {
259 global_State *g = G(L);
260 char *p = cast_charp(luaM_newobject(L, novariant(tt), sz));
261 GCObject *o = cast(GCObject *, p + offset);
262 o->marked = luaC_white(g);
263 o->tt = tt;
264 o->next = g->allgc;
265 g->allgc = o;
266 return o;
267}
268
269
270GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
271 return luaC_newobjdt(L, tt, sz, 0);
272}
273
274/* }====================================================== */
275
276
277
278/*
279** {======================================================
280** Mark functions
281** =======================================================
282*/
283
284
285/*
286** Mark an object. Userdata with no user values, strings, and closed
287** upvalues are visited and turned black here. Open upvalues are
288** already indirectly linked through their respective threads in the
289** 'twups' list, so they don't go to the gray list; nevertheless, they
290** are kept gray to avoid barriers, as their values will be revisited
291** by the thread or by 'remarkupvals'. Other objects are added to the
292** gray list to be visited (and turned black) later. Both userdata and
293** upvalues can call this function recursively, but this recursion goes
294** for at most two levels: An upvalue cannot refer to another upvalue
295** (only closures can), and a userdata's metatable must be a table.
296*/
297static void reallymarkobject (global_State *g, GCObject *o) {
298 switch (o->tt) {
299 case LUA_VSHRSTR:
300 case LUA_VLNGSTR: {
301 set2black(o); /* nothing to visit */
302 break;
303 }
304 case LUA_VUPVAL: {
305 UpVal *uv = gco2upv(o);
306 if (upisopen(uv))
307 set2gray(uv); /* open upvalues are kept gray */
308 else
309 set2black(uv); /* closed upvalues are visited here */
310 markvalue(g, uv->v.p); /* mark its content */
311 break;
312 }
313 case LUA_VUSERDATA: {
314 Udata *u = gco2u(o);
315 if (u->nuvalue == 0) { /* no user values? */
316 markobjectN(g, u->metatable); /* mark its metatable */
317 set2black(u); /* nothing else to mark */
318 break;
319 }
320 /* else... */
321 } /* FALLTHROUGH */
322 case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE:
323 case LUA_VTHREAD: case LUA_VPROTO: {
324 linkobjgclist(o, g->gray); /* to be visited later */
325 break;
326 }
327 default: lua_assert(0); break;
328 }
329}
330
331
332/*
333** mark metamethods for basic types
334*/
335static void markmt (global_State *g) {
336 int i;
337 for (i=0; i < LUA_NUMTAGS; i++)
338 markobjectN(g, g->mt[i]);
339}
340
341
342/*
343** mark all objects in list of being-finalized
344*/
345static lu_mem markbeingfnz (global_State *g) {
346 GCObject *o;
347 lu_mem count = 0;
348 for (o = g->tobefnz; o != NULL; o = o->next) {
349 count++;
350 markobject(g, o);
351 }
352 return count;
353}
354
355
356/*
357** For each non-marked thread, simulates a barrier between each open
358** upvalue and its value. (If the thread is collected, the value will be
359** assigned to the upvalue, but then it can be too late for the barrier
360** to act. The "barrier" does not need to check colors: A non-marked
361** thread must be young; upvalues cannot be older than their threads; so
362** any visited upvalue must be young too.) Also removes the thread from
363** the list, as it was already visited. Removes also threads with no
364** upvalues, as they have nothing to be checked. (If the thread gets an
365** upvalue later, it will be linked in the list again.)
366*/
367static int remarkupvals (global_State *g) {
368 lua_State *thread;
369 lua_State **p = &g->twups;
370 int work = 0; /* estimate of how much work was done here */
371 while ((thread = *p) != NULL) {
372 work++;
373 if (!iswhite(thread) && thread->openupval != NULL)
374 p = &thread->twups; /* keep marked thread with upvalues in the list */
375 else { /* thread is not marked or without upvalues */
376 UpVal *uv;
377 lua_assert(!isold(thread) || thread->openupval == NULL);
378 *p = thread->twups; /* remove thread from the list */
379 thread->twups = thread; /* mark that it is out of list */
380 for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
381 lua_assert(getage(uv) <= getage(thread));
382 work++;
383 if (!iswhite(uv)) { /* upvalue already visited? */
384 lua_assert(upisopen(uv) && isgray(uv));
385 markvalue(g, uv->v.p); /* mark its value */
386 }
387 }
388 }
389 }
390 return work;
391}
392
393
394static void cleargraylists (global_State *g) {
395 g->gray = g->grayagain = NULL;
396 g->weak = g->allweak = g->ephemeron = NULL;
397}
398
399
400/*
401** mark root set and reset all gray lists, to start a new collection
402*/
403static void restartcollection (global_State *g) {
404 cleargraylists(g);
405 markobject(g, g->mainthread);
406 markvalue(g, &g->l_registry);
407 markmt(g);
408 markbeingfnz(g); /* mark any finalizing object left from previous cycle */
409}
410
411/* }====================================================== */
412
413
414/*
415** {======================================================
416** Traverse functions
417** =======================================================
418*/
419
420
421/*
422** Check whether object 'o' should be kept in the 'grayagain' list for
423** post-processing by 'correctgraylist'. (It could put all old objects
424** in the list and leave all the work to 'correctgraylist', but it is
425** more efficient to avoid adding elements that will be removed.) Only
426** TOUCHED1 objects need to be in the list. TOUCHED2 doesn't need to go
427** back to a gray list, but then it must become OLD. (That is what
428** 'correctgraylist' does when it finds a TOUCHED2 object.)
429*/
430static void genlink (global_State *g, GCObject *o) {
431 lua_assert(isblack(o));
432 if (getage(o) == G_TOUCHED1) { /* touched in this cycle? */
433 linkobjgclist(o, g->grayagain); /* link it back in 'grayagain' */
434 } /* everything else do not need to be linked back */
435 else if (getage(o) == G_TOUCHED2)
436 changeage(o, G_TOUCHED2, G_OLD); /* advance age */
437}
438
439
440/*
441** Traverse a table with weak values and link it to proper list. During
442** propagate phase, keep it in 'grayagain' list, to be revisited in the
443** atomic phase. In the atomic phase, if table has any white value,
444** put it in 'weak' list, to be cleared.
445*/
446static void traverseweakvalue (global_State *g, Table *h) {
447 Node *n, *limit = gnodelast(h);
448 /* if there is array part, assume it may have white values (it is not
449 worth traversing it now just to check) */
450 int hasclears = (h->alimit > 0);
451 for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
452 if (isempty(gval(n))) /* entry is empty? */
453 clearkey(n); /* clear its key */
454 else {
455 lua_assert(!keyisnil(n));
456 markkey(g, n);
457 if (!hasclears && iscleared(g, gcvalueN(gval(n)))) /* a white value? */
458 hasclears = 1; /* table will have to be cleared */
459 }
460 }
461 if (g->gcstate == GCSatomic && hasclears)
462 linkgclist(h, g->weak); /* has to be cleared later */
463 else
464 linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
465}
466
467
468/*
469** Traverse an ephemeron table and link it to proper list. Returns true
470** iff any object was marked during this traversal (which implies that
471** convergence has to continue). During propagation phase, keep table
472** in 'grayagain' list, to be visited again in the atomic phase. In
473** the atomic phase, if table has any white->white entry, it has to
474** be revisited during ephemeron convergence (as that key may turn
475** black). Otherwise, if it has any white key, table has to be cleared
476** (in the atomic phase). In generational mode, some tables
477** must be kept in some gray list for post-processing; this is done
478** by 'genlink'.
479*/
480static int traverseephemeron (global_State *g, Table *h, int inv) {
481 int marked = 0; /* true if an object is marked in this traversal */
482 int hasclears = 0; /* true if table has white keys */
483 int hasww = 0; /* true if table has entry "white-key -> white-value" */
484 unsigned int i;
485 unsigned int asize = luaH_realasize(h);
486 unsigned int nsize = sizenode(h);
487 /* traverse array part */
488 for (i = 0; i < asize; i++) {
489 if (valiswhite(&h->array[i])) {
490 marked = 1;
491 reallymarkobject(g, gcvalue(&h->array[i]));
492 }
493 }
494 /* traverse hash part; if 'inv', traverse descending
495 (see 'convergeephemerons') */
496 for (i = 0; i < nsize; i++) {
497 Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i);
498 if (isempty(gval(n))) /* entry is empty? */
499 clearkey(n); /* clear its key */
500 else if (iscleared(g, gckeyN(n))) { /* key is not marked (yet)? */
501 hasclears = 1; /* table must be cleared */
502 if (valiswhite(gval(n))) /* value not marked yet? */
503 hasww = 1; /* white-white entry */
504 }
505 else if (valiswhite(gval(n))) { /* value not marked yet? */
506 marked = 1;
507 reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
508 }
509 }
510 /* link table into proper list */
511 if (g->gcstate == GCSpropagate)
512 linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
513 else if (hasww) /* table has white->white entries? */
514 linkgclist(h, g->ephemeron); /* have to propagate again */
515 else if (hasclears) /* table has white keys? */
516 linkgclist(h, g->allweak); /* may have to clean white keys */
517 else
518 genlink(g, obj2gco(h)); /* check whether collector still needs to see it */
519 return marked;
520}
521
522
523static void traversestrongtable (global_State *g, Table *h) {
524 Node *n, *limit = gnodelast(h);
525 unsigned int i;
526 unsigned int asize = luaH_realasize(h);
527 for (i = 0; i < asize; i++) /* traverse array part */
528 markvalue(g, &h->array[i]);
529 for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
530 if (isempty(gval(n))) /* entry is empty? */
531 clearkey(n); /* clear its key */
532 else {
533 lua_assert(!keyisnil(n));
534 markkey(g, n);
535 markvalue(g, gval(n));
536 }
537 }
538 genlink(g, obj2gco(h));
539}
540
541
542static lu_mem traversetable (global_State *g, Table *h) {
543 const char *weakkey, *weakvalue;
544 const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
545 TString *smode;
546 markobjectN(g, h->metatable);
547 if (mode && ttisshrstring(mode) && /* is there a weak mode? */
548 (cast_void(smode = tsvalue(mode)),
549 cast_void(weakkey = strchr(getshrstr(smode), 'k')),
550 cast_void(weakvalue = strchr(getshrstr(smode), 'v')),
551 (weakkey || weakvalue))) { /* is really weak? */
552 if (!weakkey) /* strong keys? */
553 traverseweakvalue(g, h);
554 else if (!weakvalue) /* strong values? */
555 traverseephemeron(g, h, 0);
556 else /* all weak */
557 linkgclist(h, g->allweak); /* nothing to traverse now */
558 }
559 else /* not weak */
560 traversestrongtable(g, h);
561 return 1 + h->alimit + 2 * allocsizenode(h);
562}
563
564
565static int traverseudata (global_State *g, Udata *u) {
566 int i;
567 markobjectN(g, u->metatable); /* mark its metatable */
568 for (i = 0; i < u->nuvalue; i++)
569 markvalue(g, &u->uv[i].uv);
570 genlink(g, obj2gco(u));
571 return 1 + u->nuvalue;
572}
573
574
575/*
576** Traverse a prototype. (While a prototype is being build, its
577** arrays can be larger than needed; the extra slots are filled with
578** NULL, so the use of 'markobjectN')
579*/
580static int traverseproto (global_State *g, Proto *f) {
581 int i;
582 markobjectN(g, f->source);
583 for (i = 0; i < f->sizek; i++) /* mark literals */
584 markvalue(g, &f->k[i]);
585 for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
586 markobjectN(g, f->upvalues[i].name);
587 for (i = 0; i < f->sizep; i++) /* mark nested protos */
588 markobjectN(g, f->p[i]);
589 for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
590 markobjectN(g, f->locvars[i].varname);
591 return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars;
592}
593
594
595static int traverseCclosure (global_State *g, CClosure *cl) {
596 int i;
597 for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
598 markvalue(g, &cl->upvalue[i]);
599 return 1 + cl->nupvalues;
600}
601
602/*
603** Traverse a Lua closure, marking its prototype and its upvalues.
604** (Both can be NULL while closure is being created.)
605*/
606static int traverseLclosure (global_State *g, LClosure *cl) {
607 int i;
608 markobjectN(g, cl->p); /* mark its prototype */
609 for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */
610 UpVal *uv = cl->upvals[i];
611 markobjectN(g, uv); /* mark upvalue */
612 }
613 return 1 + cl->nupvalues;
614}
615
616
617/*
618** Traverse a thread, marking the elements in the stack up to its top
619** and cleaning the rest of the stack in the final traversal. That
620** ensures that the entire stack have valid (non-dead) objects.
621** Threads have no barriers. In gen. mode, old threads must be visited
622** at every cycle, because they might point to young objects. In inc.
623** mode, the thread can still be modified before the end of the cycle,
624** and therefore it must be visited again in the atomic phase. To ensure
625** these visits, threads must return to a gray list if they are not new
626** (which can only happen in generational mode) or if the traverse is in
627** the propagate phase (which can only happen in incremental mode).
628*/
629static int traversethread (global_State *g, lua_State *th) {
630 UpVal *uv;
631 StkId o = th->stack.p;
632 if (isold(th) || g->gcstate == GCSpropagate)
633 linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
634 if (o == NULL)
635 return 1; /* stack not completely built yet */
636 lua_assert(g->gcstate == GCSatomic ||
637 th->openupval == NULL || isintwups(th));
638 for (; o < th->top.p; o++) /* mark live elements in the stack */
639 markvalue(g, s2v(o));
640 for (uv = th->openupval; uv != NULL; uv = uv->u.open.next)
641 markobject(g, uv); /* open upvalues cannot be collected */
642 if (g->gcstate == GCSatomic) { /* final traversal? */
643 if (!g->gcemergency)
644 luaD_shrinkstack(th); /* do not change stack in emergency cycle */
645 for (o = th->top.p; o < th->stack_last.p + EXTRA_STACK; o++)
646 setnilvalue(s2v(o)); /* clear dead stack slice */
647 /* 'remarkupvals' may have removed thread from 'twups' list */
648 if (!isintwups(th) && th->openupval != NULL) {
649 th->twups = g->twups; /* link it back to the list */
650 g->twups = th;
651 }
652 }
653 return 1 + stacksize(th);
654}
655
656
657/*
658** traverse one gray object, turning it to black.
659*/
660static lu_mem propagatemark (global_State *g) {
661 GCObject *o = g->gray;
662 nw2black(o);
663 g->gray = *getgclist(o); /* remove from 'gray' list */
664 switch (o->tt) {
665 case LUA_VTABLE: return traversetable(g, gco2t(o));
666 case LUA_VUSERDATA: return traverseudata(g, gco2u(o));
667 case LUA_VLCL: return traverseLclosure(g, gco2lcl(o));
668 case LUA_VCCL: return traverseCclosure(g, gco2ccl(o));
669 case LUA_VPROTO: return traverseproto(g, gco2p(o));
670 case LUA_VTHREAD: return traversethread(g, gco2th(o));
671 default: lua_assert(0); return 0;
672 }
673}
674
675
676static lu_mem propagateall (global_State *g) {
677 lu_mem tot = 0;
678 while (g->gray)
679 tot += propagatemark(g);
680 return tot;
681}
682
683
684/*
685** Traverse all ephemeron tables propagating marks from keys to values.
686** Repeat until it converges, that is, nothing new is marked. 'dir'
687** inverts the direction of the traversals, trying to speed up
688** convergence on chains in the same table.
689**
690*/
691static void convergeephemerons (global_State *g) {
692 int changed;
693 int dir = 0;
694 do {
695 GCObject *w;
696 GCObject *next = g->ephemeron; /* get ephemeron list */
697 g->ephemeron = NULL; /* tables may return to this list when traversed */
698 changed = 0;
699 while ((w = next) != NULL) { /* for each ephemeron table */
700 Table *h = gco2t(w);
701 next = h->gclist; /* list is rebuilt during loop */
702 nw2black(h); /* out of the list (for now) */
703 if (traverseephemeron(g, h, dir)) { /* marked some value? */
704 propagateall(g); /* propagate changes */
705 changed = 1; /* will have to revisit all ephemeron tables */
706 }
707 }
708 dir = !dir; /* invert direction next time */
709 } while (changed); /* repeat until no more changes */
710}
711
712/* }====================================================== */
713
714
715/*
716** {======================================================
717** Sweep Functions
718** =======================================================
719*/
720
721
722/*
723** clear entries with unmarked keys from all weaktables in list 'l'
724*/
725static void clearbykeys (global_State *g, GCObject *l) {
726 for (; l; l = gco2t(l)->gclist) {
727 Table *h = gco2t(l);
728 Node *limit = gnodelast(h);
729 Node *n;
730 for (n = gnode(h, 0); n < limit; n++) {
731 if (iscleared(g, gckeyN(n))) /* unmarked key? */
732 setempty(gval(n)); /* remove entry */
733 if (isempty(gval(n))) /* is entry empty? */
734 clearkey(n); /* clear its key */
735 }
736 }
737}
738
739
740/*
741** clear entries with unmarked values from all weaktables in list 'l' up
742** to element 'f'
743*/
744static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) {
745 for (; l != f; l = gco2t(l)->gclist) {
746 Table *h = gco2t(l);
747 Node *n, *limit = gnodelast(h);
748 unsigned int i;
749 unsigned int asize = luaH_realasize(h);
750 for (i = 0; i < asize; i++) {
751 TValue *o = &h->array[i];
752 if (iscleared(g, gcvalueN(o))) /* value was collected? */
753 setempty(o); /* remove entry */
754 }
755 for (n = gnode(h, 0); n < limit; n++) {
756 if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */
757 setempty(gval(n)); /* remove entry */
758 if (isempty(gval(n))) /* is entry empty? */
759 clearkey(n); /* clear its key */
760 }
761 }
762}
763
764
765static void freeupval (lua_State *L, UpVal *uv) {
766 if (upisopen(uv))
767 luaF_unlinkupval(uv);
768 luaM_free(L, uv);
769}
770
771
772static void freeobj (lua_State *L, GCObject *o) {
773 switch (o->tt) {
774 case LUA_VPROTO:
775 luaF_freeproto(L, gco2p(o));
776 break;
777 case LUA_VUPVAL:
778 freeupval(L, gco2upv(o));
779 break;
780 case LUA_VLCL: {
781 LClosure *cl = gco2lcl(o);
782 luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
783 break;
784 }
785 case LUA_VCCL: {
786 CClosure *cl = gco2ccl(o);
787 luaM_freemem(L, cl, sizeCclosure(cl->nupvalues));
788 break;
789 }
790 case LUA_VTABLE:
791 luaH_free(L, gco2t(o));
792 break;
793 case LUA_VTHREAD:
794 luaE_freethread(L, gco2th(o));
795 break;
796 case LUA_VUSERDATA: {
797 Udata *u = gco2u(o);
798 luaM_freemem(L, o, sizeudata(u->nuvalue, u->len));
799 break;
800 }
801 case LUA_VSHRSTR: {
802 TString *ts = gco2ts(o);
803 luaS_remove(L, ts); /* remove it from hash table */
804 luaM_freemem(L, ts, sizelstring(ts->shrlen));
805 break;
806 }
807 case LUA_VLNGSTR: {
808 TString *ts = gco2ts(o);
809 luaM_freemem(L, ts, sizelstring(ts->u.lnglen));
810 break;
811 }
812 default: lua_assert(0);
813 }
814}
815
816
817/*
818** sweep at most 'countin' elements from a list of GCObjects erasing dead
819** objects, where a dead object is one marked with the old (non current)
820** white; change all non-dead objects back to white, preparing for next
821** collection cycle. Return where to continue the traversal or NULL if
822** list is finished. ('*countout' gets the number of elements traversed.)
823*/
824static GCObject **sweeplist (lua_State *L, GCObject **p, int countin,
825 int *countout) {
826 global_State *g = G(L);
827 int ow = otherwhite(g);
828 int i;
829 int white = luaC_white(g); /* current white */
830 for (i = 0; *p != NULL && i < countin; i++) {
831 GCObject *curr = *p;
832 int marked = curr->marked;
833 if (isdeadm(ow, marked)) { /* is 'curr' dead? */
834 *p = curr->next; /* remove 'curr' from list */
835 freeobj(L, curr); /* erase 'curr' */
836 }
837 else { /* change mark to 'white' */
838 curr->marked = cast_byte((marked & ~maskgcbits) | white);
839 p = &curr->next; /* go to next element */
840 }
841 }
842 if (countout)
843 *countout = i; /* number of elements traversed */
844 return (*p == NULL) ? NULL : p;
845}
846
847
848/*
849** sweep a list until a live object (or end of list)
850*/
851static GCObject **sweeptolive (lua_State *L, GCObject **p) {
852 GCObject **old = p;
853 do {
854 p = sweeplist(L, p, 1, NULL);
855 } while (p == old);
856 return p;
857}
858
859/* }====================================================== */
860
861
862/*
863** {======================================================
864** Finalization
865** =======================================================
866*/
867
868/*
869** If possible, shrink string table.
870*/
871static void checkSizes (lua_State *L, global_State *g) {
872 if (!g->gcemergency) {
873 if (g->strt.nuse < g->strt.size / 4) { /* string table too big? */
874 l_mem olddebt = g->GCdebt;
875 luaS_resize(L, g->strt.size / 2);
876 g->GCestimate += g->GCdebt - olddebt; /* correct estimate */
877 }
878 }
879}
880
881
882/*
883** Get the next udata to be finalized from the 'tobefnz' list, and
884** link it back into the 'allgc' list.
885*/
886static GCObject *udata2finalize (global_State *g) {
887 GCObject *o = g->tobefnz; /* get first element */
888 lua_assert(tofinalize(o));
889 g->tobefnz = o->next; /* remove it from 'tobefnz' list */
890 o->next = g->allgc; /* return it to 'allgc' list */
891 g->allgc = o;
892 resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
893 if (issweepphase(g))
894 makewhite(g, o); /* "sweep" object */
895 else if (getage(o) == G_OLD1)
896 g->firstold1 = o; /* it is the first OLD1 object in the list */
897 return o;
898}
899
900
901static void dothecall (lua_State *L, void *ud) {
902 UNUSED(ud);
903 luaD_callnoyield(L, L->top.p - 2, 0);
904}
905
906
907static void GCTM (lua_State *L) {
908 global_State *g = G(L);
909 const TValue *tm;
910 TValue v;
911 lua_assert(!g->gcemergency);
912 setgcovalue(L, &v, udata2finalize(g));
913 tm = luaT_gettmbyobj(L, &v, TM_GC);
914 if (!notm(tm)) { /* is there a finalizer? */
915 int status;
916 lu_byte oldah = L->allowhook;
917 int oldgcstp = g->gcstp;
918 g->gcstp |= GCSTPGC; /* avoid GC steps */
919 L->allowhook = 0; /* stop debug hooks during GC metamethod */
920 setobj2s(L, L->top.p++, tm); /* push finalizer... */
921 setobj2s(L, L->top.p++, &v); /* ... and its argument */
922 L->ci->callstatus |= CIST_FIN; /* will run a finalizer */
923 status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top.p - 2), 0);
924 L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */
925 L->allowhook = oldah; /* restore hooks */
926 g->gcstp = oldgcstp; /* restore state */
927 if (l_unlikely(status != LUA_OK)) { /* error while running __gc? */
928 luaE_warnerror(L, "__gc");
929 L->top.p--; /* pops error object */
930 }
931 }
932}
933
934
935/*
936** Call a few finalizers
937*/
938static int runafewfinalizers (lua_State *L, int n) {
939 global_State *g = G(L);
940 int i;
941 for (i = 0; i < n && g->tobefnz; i++)
942 GCTM(L); /* call one finalizer */
943 return i;
944}
945
946
947/*
948** call all pending finalizers
949*/
950static void callallpendingfinalizers (lua_State *L) {
951 global_State *g = G(L);
952 while (g->tobefnz)
953 GCTM(L);
954}
955
956
957/*
958** find last 'next' field in list 'p' list (to add elements in its end)
959*/
960static GCObject **findlast (GCObject **p) {
961 while (*p != NULL)
962 p = &(*p)->next;
963 return p;
964}
965
966
967/*
968** Move all unreachable objects (or 'all' objects) that need
969** finalization from list 'finobj' to list 'tobefnz' (to be finalized).
970** (Note that objects after 'finobjold1' cannot be white, so they
971** don't need to be traversed. In incremental mode, 'finobjold1' is NULL,
972** so the whole list is traversed.)
973*/
974static void separatetobefnz (global_State *g, int all) {
975 GCObject *curr;
976 GCObject **p = &g->finobj;
977 GCObject **lastnext = findlast(&g->tobefnz);
978 while ((curr = *p) != g->finobjold1) { /* traverse all finalizable objects */
979 lua_assert(tofinalize(curr));
980 if (!(iswhite(curr) || all)) /* not being collected? */
981 p = &curr->next; /* don't bother with it */
982 else {
983 if (curr == g->finobjsur) /* removing 'finobjsur'? */
984 g->finobjsur = curr->next; /* correct it */
985 *p = curr->next; /* remove 'curr' from 'finobj' list */
986 curr->next = *lastnext; /* link at the end of 'tobefnz' list */
987 *lastnext = curr;
988 lastnext = &curr->next;
989 }
990 }
991}
992
993
994/*
995** If pointer 'p' points to 'o', move it to the next element.
996*/
997static void checkpointer (GCObject **p, GCObject *o) {
998 if (o == *p)
999 *p = o->next;
1000}
1001
1002
1003/*
1004** Correct pointers to objects inside 'allgc' list when
1005** object 'o' is being removed from the list.
1006*/
1007static void correctpointers (global_State *g, GCObject *o) {
1008 checkpointer(&g->survival, o);
1009 checkpointer(&g->old1, o);
1010 checkpointer(&g->reallyold, o);
1011 checkpointer(&g->firstold1, o);
1012}
1013
1014
1015/*
1016** if object 'o' has a finalizer, remove it from 'allgc' list (must
1017** search the list to find it) and link it in 'finobj' list.
1018*/
1019void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
1020 global_State *g = G(L);
1021 if (tofinalize(o) || /* obj. is already marked... */
1022 gfasttm(g, mt, TM_GC) == NULL || /* or has no finalizer... */
1023 (g->gcstp & GCSTPCLS)) /* or closing state? */
1024 return; /* nothing to be done */
1025 else { /* move 'o' to 'finobj' list */
1026 GCObject **p;
1027 if (issweepphase(g)) {
1028 makewhite(g, o); /* "sweep" object 'o' */
1029 if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
1030 g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */
1031 }
1032 else
1033 correctpointers(g, o);
1034 /* search for pointer pointing to 'o' */
1035 for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
1036 *p = o->next; /* remove 'o' from 'allgc' list */
1037 o->next = g->finobj; /* link it in 'finobj' list */
1038 g->finobj = o;
1039 l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
1040 }
1041}
1042
1043/* }====================================================== */
1044
1045
1046/*
1047** {======================================================
1048** Generational Collector
1049** =======================================================
1050*/
1051
1052
1053/*
1054** Set the "time" to wait before starting a new GC cycle; cycle will
1055** start when memory use hits the threshold of ('estimate' * pause /
1056** PAUSEADJ). (Division by 'estimate' should be OK: it cannot be zero,
1057** because Lua cannot even start with less than PAUSEADJ bytes).
1058*/
1059static void setpause (global_State *g) {
1060 l_mem threshold, debt;
1061 int pause = getgcparam(g->gcpause);
1062 l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */
1063 lua_assert(estimate > 0);
1064 threshold = (pause < MAX_LMEM / estimate) /* overflow? */
1065 ? estimate * pause /* no overflow */
1066 : MAX_LMEM; /* overflow; truncate to maximum */
1067 debt = gettotalbytes(g) - threshold;
1068 if (debt > 0) debt = 0;
1069 luaE_setdebt(g, debt);
1070}
1071
1072
1073/*
1074** Sweep a list of objects to enter generational mode. Deletes dead
1075** objects and turns the non dead to old. All non-dead threads---which
1076** are now old---must be in a gray list. Everything else is not in a
1077** gray list. Open upvalues are also kept gray.
1078*/
1079static void sweep2old (lua_State *L, GCObject **p) {
1080 GCObject *curr;
1081 global_State *g = G(L);
1082 while ((curr = *p) != NULL) {
1083 if (iswhite(curr)) { /* is 'curr' dead? */
1084 lua_assert(isdead(g, curr));
1085 *p = curr->next; /* remove 'curr' from list */
1086 freeobj(L, curr); /* erase 'curr' */
1087 }
1088 else { /* all surviving objects become old */
1089 setage(curr, G_OLD);
1090 if (curr->tt == LUA_VTHREAD) { /* threads must be watched */
1091 lua_State *th = gco2th(curr);
1092 linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
1093 }
1094 else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr)))
1095 set2gray(curr); /* open upvalues are always gray */
1096 else /* everything else is black */
1097 nw2black(curr);
1098 p = &curr->next; /* go to next element */
1099 }
1100 }
1101}
1102
1103
1104/*
1105** Sweep for generational mode. Delete dead objects. (Because the
1106** collection is not incremental, there are no "new white" objects
1107** during the sweep. So, any white object must be dead.) For
1108** non-dead objects, advance their ages and clear the color of
1109** new objects. (Old objects keep their colors.)
1110** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced
1111** here, because these old-generation objects are usually not swept
1112** here. They will all be advanced in 'correctgraylist'. That function
1113** will also remove objects turned white here from any gray list.
1114*/
1115static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p,
1116 GCObject *limit, GCObject **pfirstold1) {
1117 static const lu_byte nextage[] = {
1118 G_SURVIVAL, /* from G_NEW */
1119 G_OLD1, /* from G_SURVIVAL */
1120 G_OLD1, /* from G_OLD0 */
1121 G_OLD, /* from G_OLD1 */
1122 G_OLD, /* from G_OLD (do not change) */
1123 G_TOUCHED1, /* from G_TOUCHED1 (do not change) */
1124 G_TOUCHED2 /* from G_TOUCHED2 (do not change) */
1125 };
1126 int white = luaC_white(g);
1127 GCObject *curr;
1128 while ((curr = *p) != limit) {
1129 if (iswhite(curr)) { /* is 'curr' dead? */
1130 lua_assert(!isold(curr) && isdead(g, curr));
1131 *p = curr->next; /* remove 'curr' from list */
1132 freeobj(L, curr); /* erase 'curr' */
1133 }
1134 else { /* correct mark and age */
1135 if (getage(curr) == G_NEW) { /* new objects go back to white */
1136 int marked = curr->marked & ~maskgcbits; /* erase GC bits */
1137 curr->marked = cast_byte(marked | G_SURVIVAL | white);
1138 }
1139 else { /* all other objects will be old, and so keep their color */
1140 setage(curr, nextage[getage(curr)]);
1141 if (getage(curr) == G_OLD1 && *pfirstold1 == NULL)
1142 *pfirstold1 = curr; /* first OLD1 object in the list */
1143 }
1144 p = &curr->next; /* go to next element */
1145 }
1146 }
1147 return p;
1148}
1149
1150
1151/*
1152** Traverse a list making all its elements white and clearing their
1153** age. In incremental mode, all objects are 'new' all the time,
1154** except for fixed strings (which are always old).
1155*/
1156static void whitelist (global_State *g, GCObject *p) {
1157 int white = luaC_white(g);
1158 for (; p != NULL; p = p->next)
1159 p->marked = cast_byte((p->marked & ~maskgcbits) | white);
1160}
1161
1162
1163/*
1164** Correct a list of gray objects. Return pointer to where rest of the
1165** list should be linked.
1166** Because this correction is done after sweeping, young objects might
1167** be turned white and still be in the list. They are only removed.
1168** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list;
1169** Non-white threads also remain on the list; 'TOUCHED2' objects become
1170** regular old; they and anything else are removed from the list.
1171*/
1172static GCObject **correctgraylist (GCObject **p) {
1173 GCObject *curr;
1174 while ((curr = *p) != NULL) {
1175 GCObject **next = getgclist(curr);
1176 if (iswhite(curr))
1177 goto remove; /* remove all white objects */
1178 else if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */
1179 lua_assert(isgray(curr));
1180 nw2black(curr); /* make it black, for next barrier */
1181 changeage(curr, G_TOUCHED1, G_TOUCHED2);
1182 goto remain; /* keep it in the list and go to next element */
1183 }
1184 else if (curr->tt == LUA_VTHREAD) {
1185 lua_assert(isgray(curr));
1186 goto remain; /* keep non-white threads on the list */
1187 }
1188 else { /* everything else is removed */
1189 lua_assert(isold(curr)); /* young objects should be white here */
1190 if (getage(curr) == G_TOUCHED2) /* advance from TOUCHED2... */
1191 changeage(curr, G_TOUCHED2, G_OLD); /* ... to OLD */
1192 nw2black(curr); /* make object black (to be removed) */
1193 goto remove;
1194 }
1195 remove: *p = *next; continue;
1196 remain: p = next; continue;
1197 }
1198 return p;
1199}
1200
1201
1202/*
1203** Correct all gray lists, coalescing them into 'grayagain'.
1204*/
1205static void correctgraylists (global_State *g) {
1206 GCObject **list = correctgraylist(&g->grayagain);
1207 *list = g->weak; g->weak = NULL;
1208 list = correctgraylist(list);
1209 *list = g->allweak; g->allweak = NULL;
1210 list = correctgraylist(list);
1211 *list = g->ephemeron; g->ephemeron = NULL;
1212 correctgraylist(list);
1213}
1214
1215
1216/*
1217** Mark black 'OLD1' objects when starting a new young collection.
1218** Gray objects are already in some gray list, and so will be visited
1219** in the atomic step.
1220*/
1221static void markold (global_State *g, GCObject *from, GCObject *to) {
1222 GCObject *p;
1223 for (p = from; p != to; p = p->next) {
1224 if (getage(p) == G_OLD1) {
1225 lua_assert(!iswhite(p));
1226 changeage(p, G_OLD1, G_OLD); /* now they are old */
1227 if (isblack(p))
1228 reallymarkobject(g, p);
1229 }
1230 }
1231}
1232
1233
1234/*
1235** Finish a young-generation collection.
1236*/
1237static void finishgencycle (lua_State *L, global_State *g) {
1238 correctgraylists(g);
1239 checkSizes(L, g);
1240 g->gcstate = GCSpropagate; /* skip restart */
1241 if (!g->gcemergency)
1242 callallpendingfinalizers(L);
1243}
1244
1245
1246/*
1247** Does a young collection. First, mark 'OLD1' objects. Then does the
1248** atomic step. Then, sweep all lists and advance pointers. Finally,
1249** finish the collection.
1250*/
1251static void youngcollection (lua_State *L, global_State *g) {
1252 GCObject **psurvival; /* to point to first non-dead survival object */
1253 GCObject *dummy; /* dummy out parameter to 'sweepgen' */
1254 lua_assert(g->gcstate == GCSpropagate);
1255 if (g->firstold1) { /* are there regular OLD1 objects? */
1256 markold(g, g->firstold1, g->reallyold); /* mark them */
1257 g->firstold1 = NULL; /* no more OLD1 objects (for now) */
1258 }
1259 markold(g, g->finobj, g->finobjrold);
1260 markold(g, g->tobefnz, NULL);
1261 atomic(L);
1262
1263 /* sweep nursery and get a pointer to its last live element */
1264 g->gcstate = GCSswpallgc;
1265 psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1);
1266 /* sweep 'survival' */
1267 sweepgen(L, g, psurvival, g->old1, &g->firstold1);
1268 g->reallyold = g->old1;
1269 g->old1 = *psurvival; /* 'survival' survivals are old now */
1270 g->survival = g->allgc; /* all news are survivals */
1271
1272 /* repeat for 'finobj' lists */
1273 dummy = NULL; /* no 'firstold1' optimization for 'finobj' lists */
1274 psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy);
1275 /* sweep 'survival' */
1276 sweepgen(L, g, psurvival, g->finobjold1, &dummy);
1277 g->finobjrold = g->finobjold1;
1278 g->finobjold1 = *psurvival; /* 'survival' survivals are old now */
1279 g->finobjsur = g->finobj; /* all news are survivals */
1280
1281 sweepgen(L, g, &g->tobefnz, NULL, &dummy);
1282 finishgencycle(L, g);
1283}
1284
1285
1286/*
1287** Clears all gray lists, sweeps objects, and prepare sublists to enter
1288** generational mode. The sweeps remove dead objects and turn all
1289** surviving objects to old. Threads go back to 'grayagain'; everything
1290** else is turned black (not in any gray list).
1291*/
1292static void atomic2gen (lua_State *L, global_State *g) {
1293 cleargraylists(g);
1294 /* sweep all elements making them old */
1295 g->gcstate = GCSswpallgc;
1296 sweep2old(L, &g->allgc);
1297 /* everything alive now is old */
1298 g->reallyold = g->old1 = g->survival = g->allgc;
1299 g->firstold1 = NULL; /* there are no OLD1 objects anywhere */
1300
1301 /* repeat for 'finobj' lists */
1302 sweep2old(L, &g->finobj);
1303 g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj;
1304
1305 sweep2old(L, &g->tobefnz);
1306
1307 g->gckind = KGC_GEN;
1308 g->lastatomic = 0;
1309 g->GCestimate = gettotalbytes(g); /* base for memory control */
1310 finishgencycle(L, g);
1311}
1312
1313
1314/*
1315** Set debt for the next minor collection, which will happen when
1316** memory grows 'genminormul'%.
1317*/
1318static void setminordebt (global_State *g) {
1319 luaE_setdebt(g, -(cast(l_mem, (gettotalbytes(g) / 100)) * g->genminormul));
1320}
1321
1322
1323/*
1324** Enter generational mode. Must go until the end of an atomic cycle
1325** to ensure that all objects are correctly marked and weak tables
1326** are cleared. Then, turn all objects into old and finishes the
1327** collection.
1328*/
1329static lu_mem entergen (lua_State *L, global_State *g) {
1330 lu_mem numobjs;
1331 luaC_runtilstate(L, bitmask(GCSpause)); /* prepare to start a new cycle */
1332 luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */
1333 numobjs = atomic(L); /* propagates all and then do the atomic stuff */
1334 atomic2gen(L, g);
1335 setminordebt(g); /* set debt assuming next cycle will be minor */
1336 return numobjs;
1337}
1338
1339
1340/*
1341** Enter incremental mode. Turn all objects white, make all
1342** intermediate lists point to NULL (to avoid invalid pointers),
1343** and go to the pause state.
1344*/
1345static void enterinc (global_State *g) {
1346 whitelist(g, g->allgc);
1347 g->reallyold = g->old1 = g->survival = NULL;
1348 whitelist(g, g->finobj);
1349 whitelist(g, g->tobefnz);
1350 g->finobjrold = g->finobjold1 = g->finobjsur = NULL;
1351 g->gcstate = GCSpause;
1352 g->gckind = KGC_INC;
1353 g->lastatomic = 0;
1354}
1355
1356
1357/*
1358** Change collector mode to 'newmode'.
1359*/
1360void luaC_changemode (lua_State *L, int newmode) {
1361 global_State *g = G(L);
1362 if (newmode != g->gckind) {
1363 if (newmode == KGC_GEN) /* entering generational mode? */
1364 entergen(L, g);
1365 else
1366 enterinc(g); /* entering incremental mode */
1367 }
1368 g->lastatomic = 0;
1369}
1370
1371
1372/*
1373** Does a full collection in generational mode.
1374*/
1375static lu_mem fullgen (lua_State *L, global_State *g) {
1376 enterinc(g);
1377 return entergen(L, g);
1378}
1379
1380
1381/*
1382** Does a major collection after last collection was a "bad collection".
1383**
1384** When the program is building a big structure, it allocates lots of
1385** memory but generates very little garbage. In those scenarios,
1386** the generational mode just wastes time doing small collections, and
1387** major collections are frequently what we call a "bad collection", a
1388** collection that frees too few objects. To avoid the cost of switching
1389** between generational mode and the incremental mode needed for full
1390** (major) collections, the collector tries to stay in incremental mode
1391** after a bad collection, and to switch back to generational mode only
1392** after a "good" collection (one that traverses less than 9/8 objects
1393** of the previous one).
1394** The collector must choose whether to stay in incremental mode or to
1395** switch back to generational mode before sweeping. At this point, it
1396** does not know the real memory in use, so it cannot use memory to
1397** decide whether to return to generational mode. Instead, it uses the
1398** number of objects traversed (returned by 'atomic') as a proxy. The
1399** field 'g->lastatomic' keeps this count from the last collection.
1400** ('g->lastatomic != 0' also means that the last collection was bad.)
1401*/
1402static void stepgenfull (lua_State *L, global_State *g) {
1403 lu_mem newatomic; /* count of traversed objects */
1404 lu_mem lastatomic = g->lastatomic; /* count from last collection */
1405 if (g->gckind == KGC_GEN) /* still in generational mode? */
1406 enterinc(g); /* enter incremental mode */
1407 luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */
1408 newatomic = atomic(L); /* mark everybody */
1409 if (newatomic < lastatomic + (lastatomic >> 3)) { /* good collection? */
1410 atomic2gen(L, g); /* return to generational mode */
1411 setminordebt(g);
1412 }
1413 else { /* another bad collection; stay in incremental mode */
1414 g->GCestimate = gettotalbytes(g); /* first estimate */
1415 entersweep(L);
1416 luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
1417 setpause(g);
1418 g->lastatomic = newatomic;
1419 }
1420}
1421
1422
1423/*
1424** Does a generational "step".
1425** Usually, this means doing a minor collection and setting the debt to
1426** make another collection when memory grows 'genminormul'% larger.
1427**
1428** However, there are exceptions. If memory grows 'genmajormul'%
1429** larger than it was at the end of the last major collection (kept
1430** in 'g->GCestimate'), the function does a major collection. At the
1431** end, it checks whether the major collection was able to free a
1432** decent amount of memory (at least half the growth in memory since
1433** previous major collection). If so, the collector keeps its state,
1434** and the next collection will probably be minor again. Otherwise,
1435** we have what we call a "bad collection". In that case, set the field
1436** 'g->lastatomic' to signal that fact, so that the next collection will
1437** go to 'stepgenfull'.
1438**
1439** 'GCdebt <= 0' means an explicit call to GC step with "size" zero;
1440** in that case, do a minor collection.
1441*/
1442static void genstep (lua_State *L, global_State *g) {
1443 if (g->lastatomic != 0) /* last collection was a bad one? */
1444 stepgenfull(L, g); /* do a full step */
1445 else {
1446 lu_mem majorbase = g->GCestimate; /* memory after last major collection */
1447 lu_mem majorinc = (majorbase / 100) * getgcparam(g->genmajormul);
1448 if (g->GCdebt > 0 && gettotalbytes(g) > majorbase + majorinc) {
1449 lu_mem numobjs = fullgen(L, g); /* do a major collection */
1450 if (gettotalbytes(g) < majorbase + (majorinc / 2)) {
1451 /* collected at least half of memory growth since last major
1452 collection; keep doing minor collections. */
1453 lua_assert(g->lastatomic == 0);
1454 }
1455 else { /* bad collection */
1456 g->lastatomic = numobjs; /* signal that last collection was bad */
1457 setpause(g); /* do a long wait for next (major) collection */
1458 }
1459 }
1460 else { /* regular case; do a minor collection */
1461 youngcollection(L, g);
1462 setminordebt(g);
1463 g->GCestimate = majorbase; /* preserve base value */
1464 }
1465 }
1466 lua_assert(isdecGCmodegen(g));
1467}
1468
1469/* }====================================================== */
1470
1471
1472/*
1473** {======================================================
1474** GC control
1475** =======================================================
1476*/
1477
1478
1479/*
1480** Enter first sweep phase.
1481** The call to 'sweeptolive' makes the pointer point to an object
1482** inside the list (instead of to the header), so that the real sweep do
1483** not need to skip objects created between "now" and the start of the
1484** real sweep.
1485*/
1486static void entersweep (lua_State *L) {
1487 global_State *g = G(L);
1488 g->gcstate = GCSswpallgc;
1489 lua_assert(g->sweepgc == NULL);
1490 g->sweepgc = sweeptolive(L, &g->allgc);
1491}
1492
1493
1494/*
1495** Delete all objects in list 'p' until (but not including) object
1496** 'limit'.
1497*/
1498static void deletelist (lua_State *L, GCObject *p, GCObject *limit) {
1499 while (p != limit) {
1500 GCObject *next = p->next;
1501 freeobj(L, p);
1502 p = next;
1503 }
1504}
1505
1506
1507/*
1508** Call all finalizers of the objects in the given Lua state, and
1509** then free all objects, except for the main thread.
1510*/
1511void luaC_freeallobjects (lua_State *L) {
1512 global_State *g = G(L);
1513 g->gcstp = GCSTPCLS; /* no extra finalizers after here */
1514 luaC_changemode(L, KGC_INC);
1515 separatetobefnz(g, 1); /* separate all objects with finalizers */
1516 lua_assert(g->finobj == NULL);
1517 callallpendingfinalizers(L);
1518 deletelist(L, g->allgc, obj2gco(g->mainthread));
1519 lua_assert(g->finobj == NULL); /* no new finalizers */
1520 deletelist(L, g->fixedgc, NULL); /* collect fixed objects */
1521 lua_assert(g->strt.nuse == 0);
1522}
1523
1524
1525static lu_mem atomic (lua_State *L) {
1526 global_State *g = G(L);
1527 lu_mem work = 0;
1528 GCObject *origweak, *origall;
1529 GCObject *grayagain = g->grayagain; /* save original list */
1530 g->grayagain = NULL;
1531 lua_assert(g->ephemeron == NULL && g->weak == NULL);
1532 lua_assert(!iswhite(g->mainthread));
1533 g->gcstate = GCSatomic;
1534 markobject(g, L); /* mark running thread */
1535 /* registry and global metatables may be changed by API */
1536 markvalue(g, &g->l_registry);
1537 markmt(g); /* mark global metatables */
1538 work += propagateall(g); /* empties 'gray' list */
1539 /* remark occasional upvalues of (maybe) dead threads */
1540 work += remarkupvals(g);
1541 work += propagateall(g); /* propagate changes */
1542 g->gray = grayagain;
1543 work += propagateall(g); /* traverse 'grayagain' list */
1544 convergeephemerons(g);
1545 /* at this point, all strongly accessible objects are marked. */
1546 /* Clear values from weak tables, before checking finalizers */
1547 clearbyvalues(g, g->weak, NULL);
1548 clearbyvalues(g, g->allweak, NULL);
1549 origweak = g->weak; origall = g->allweak;
1550 separatetobefnz(g, 0); /* separate objects to be finalized */
1551 work += markbeingfnz(g); /* mark objects that will be finalized */
1552 work += propagateall(g); /* remark, to propagate 'resurrection' */
1553 convergeephemerons(g);
1554 /* at this point, all resurrected objects are marked. */
1555 /* remove dead objects from weak tables */
1556 clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron tables */
1557 clearbykeys(g, g->allweak); /* clear keys from all 'allweak' tables */
1558 /* clear values from resurrected weak tables */
1559 clearbyvalues(g, g->weak, origweak);
1560 clearbyvalues(g, g->allweak, origall);
1561 luaS_clearcache(g);
1562 g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
1563 lua_assert(g->gray == NULL);
1564 return work; /* estimate of slots marked by 'atomic' */
1565}
1566
1567
1568static int sweepstep (lua_State *L, global_State *g,
1569 int nextstate, GCObject **nextlist) {
1570 if (g->sweepgc) {
1571 l_mem olddebt = g->GCdebt;
1572 int count;
1573 g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX, &count);
1574 g->GCestimate += g->GCdebt - olddebt; /* update estimate */
1575 return count;
1576 }
1577 else { /* enter next state */
1578 g->gcstate = nextstate;
1579 g->sweepgc = nextlist;
1580 return 0; /* no work done */
1581 }
1582}
1583
1584
1585static lu_mem singlestep (lua_State *L) {
1586 global_State *g = G(L);
1587 lu_mem work;
1588 lua_assert(!g->gcstopem); /* collector is not reentrant */
1589 g->gcstopem = 1; /* no emergency collections while collecting */
1590 switch (g->gcstate) {
1591 case GCSpause: {
1592 restartcollection(g);
1593 g->gcstate = GCSpropagate;
1594 work = 1;
1595 break;
1596 }
1597 case GCSpropagate: {
1598 if (g->gray == NULL) { /* no more gray objects? */
1599 g->gcstate = GCSenteratomic; /* finish propagate phase */
1600 work = 0;
1601 }
1602 else
1603 work = propagatemark(g); /* traverse one gray object */
1604 break;
1605 }
1606 case GCSenteratomic: {
1607 work = atomic(L); /* work is what was traversed by 'atomic' */
1608 entersweep(L);
1609 g->GCestimate = gettotalbytes(g); /* first estimate */
1610 break;
1611 }
1612 case GCSswpallgc: { /* sweep "regular" objects */
1613 work = sweepstep(L, g, GCSswpfinobj, &g->finobj);
1614 break;
1615 }
1616 case GCSswpfinobj: { /* sweep objects with finalizers */
1617 work = sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
1618 break;
1619 }
1620 case GCSswptobefnz: { /* sweep objects to be finalized */
1621 work = sweepstep(L, g, GCSswpend, NULL);
1622 break;
1623 }
1624 case GCSswpend: { /* finish sweeps */
1625 checkSizes(L, g);
1626 g->gcstate = GCScallfin;
1627 work = 0;
1628 break;
1629 }
1630 case GCScallfin: { /* call remaining finalizers */
1631 if (g->tobefnz && !g->gcemergency) {
1632 g->gcstopem = 0; /* ok collections during finalizers */
1633 work = runafewfinalizers(L, GCFINMAX) * GCFINALIZECOST;
1634 }
1635 else { /* emergency mode or no more finalizers */
1636 g->gcstate = GCSpause; /* finish collection */
1637 work = 0;
1638 }
1639 break;
1640 }
1641 default: lua_assert(0); return 0;
1642 }
1643 g->gcstopem = 0;
1644 return work;
1645}
1646
1647
1648/*
1649** advances the garbage collector until it reaches a state allowed
1650** by 'statemask'
1651*/
1652void luaC_runtilstate (lua_State *L, int statesmask) {
1653 global_State *g = G(L);
1654 while (!testbit(statesmask, g->gcstate))
1655 singlestep(L);
1656}
1657
1658
1659
1660/*
1661** Performs a basic incremental step. The debt and step size are
1662** converted from bytes to "units of work"; then the function loops
1663** running single steps until adding that many units of work or
1664** finishing a cycle (pause state). Finally, it sets the debt that
1665** controls when next step will be performed.
1666*/
1667static void incstep (lua_State *L, global_State *g) {
1668 int stepmul = (getgcparam(g->gcstepmul) | 1); /* avoid division by 0 */
1669 l_mem debt = (g->GCdebt / WORK2MEM) * stepmul;
1670 l_mem stepsize = (g->gcstepsize <= log2maxs(l_mem))
1671 ? ((cast(l_mem, 1) << g->gcstepsize) / WORK2MEM) * stepmul
1672 : MAX_LMEM; /* overflow; keep maximum value */
1673 do { /* repeat until pause or enough "credit" (negative debt) */
1674 lu_mem work = singlestep(L); /* perform one single step */
1675 debt -= work;
1676 } while (debt > -stepsize && g->gcstate != GCSpause);
1677 if (g->gcstate == GCSpause)
1678 setpause(g); /* pause until next cycle */
1679 else {
1680 debt = (debt / stepmul) * WORK2MEM; /* convert 'work units' to bytes */
1681 luaE_setdebt(g, debt);
1682 }
1683}
1684
1685/*
1686** Performs a basic GC step if collector is running. (If collector is
1687** not running, set a reasonable debt to avoid it being called at
1688** every single check.)
1689*/
1690void luaC_step (lua_State *L) {
1691 global_State *g = G(L);
1692 if (!gcrunning(g)) /* not running? */
1693 luaE_setdebt(g, -2000);
1694 else {
1695 if(isdecGCmodegen(g))
1696 genstep(L, g);
1697 else
1698 incstep(L, g);
1699 }
1700}
1701
1702
1703/*
1704** Perform a full collection in incremental mode.
1705** Before running the collection, check 'keepinvariant'; if it is true,
1706** there may be some objects marked as black, so the collector has
1707** to sweep all objects to turn them back to white (as white has not
1708** changed, nothing will be collected).
1709*/
1710static void fullinc (lua_State *L, global_State *g) {
1711 if (keepinvariant(g)) /* black objects? */
1712 entersweep(L); /* sweep everything to turn them back to white */
1713 /* finish any pending sweep phase to start a new cycle */
1714 luaC_runtilstate(L, bitmask(GCSpause));
1715 luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */
1716 g->gcstate = GCSenteratomic; /* go straight to atomic phase */
1717 luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */
1718 /* estimate must be correct after a full GC cycle */
1719 lua_assert(g->GCestimate == gettotalbytes(g));
1720 luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
1721 setpause(g);
1722}
1723
1724
1725/*
1726** Performs a full GC cycle; if 'isemergency', set a flag to avoid
1727** some operations which could change the interpreter state in some
1728** unexpected ways (running finalizers and shrinking some structures).
1729*/
1730void luaC_fullgc (lua_State *L, int isemergency) {
1731 global_State *g = G(L);
1732 lua_assert(!g->gcemergency);
1733 g->gcemergency = isemergency; /* set flag */
1734 if (g->gckind == KGC_INC)
1735 fullinc(L, g);
1736 else
1737 fullgen(L, g);
1738 g->gcemergency = 0;
1739}
1740
1741/* }====================================================== */
1742
1743
diff --git a/vendor/lua-5.4.8/src/lgc.h b/vendor/lua-5.4.8/src/lgc.h
new file mode 100644
index 0000000..538f6ed
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lgc.h
@@ -0,0 +1,202 @@
1/*
2** $Id: lgc.h $
3** Garbage Collector
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lgc_h
8#define lgc_h
9
10
11#include "lobject.h"
12#include "lstate.h"
13
14/*
15** Collectable objects may have one of three colors: white, which means
16** the object is not marked; gray, which means the object is marked, but
17** its references may be not marked; and black, which means that the
18** object and all its references are marked. The main invariant of the
19** garbage collector, while marking objects, is that a black object can
20** never point to a white one. Moreover, any gray object must be in a
21** "gray list" (gray, grayagain, weak, allweak, ephemeron) so that it
22** can be visited again before finishing the collection cycle. (Open
23** upvalues are an exception to this rule.) These lists have no meaning
24** when the invariant is not being enforced (e.g., sweep phase).
25*/
26
27
28/*
29** Possible states of the Garbage Collector
30*/
31#define GCSpropagate 0
32#define GCSenteratomic 1
33#define GCSatomic 2
34#define GCSswpallgc 3
35#define GCSswpfinobj 4
36#define GCSswptobefnz 5
37#define GCSswpend 6
38#define GCScallfin 7
39#define GCSpause 8
40
41
42#define issweepphase(g) \
43 (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend)
44
45
46/*
47** macro to tell when main invariant (white objects cannot point to black
48** ones) must be kept. During a collection, the sweep
49** phase may break the invariant, as objects turned white may point to
50** still-black objects. The invariant is restored when sweep ends and
51** all objects are white again.
52*/
53
54#define keepinvariant(g) ((g)->gcstate <= GCSatomic)
55
56
57/*
58** some useful bit tricks
59*/
60#define resetbits(x,m) ((x) &= cast_byte(~(m)))
61#define setbits(x,m) ((x) |= (m))
62#define testbits(x,m) ((x) & (m))
63#define bitmask(b) (1<<(b))
64#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2))
65#define l_setbit(x,b) setbits(x, bitmask(b))
66#define resetbit(x,b) resetbits(x, bitmask(b))
67#define testbit(x,b) testbits(x, bitmask(b))
68
69
70/*
71** Layout for bit use in 'marked' field. First three bits are
72** used for object "age" in generational mode. Last bit is used
73** by tests.
74*/
75#define WHITE0BIT 3 /* object is white (type 0) */
76#define WHITE1BIT 4 /* object is white (type 1) */
77#define BLACKBIT 5 /* object is black */
78#define FINALIZEDBIT 6 /* object has been marked for finalization */
79
80#define TESTBIT 7
81
82
83
84#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)
85
86
87#define iswhite(x) testbits((x)->marked, WHITEBITS)
88#define isblack(x) testbit((x)->marked, BLACKBIT)
89#define isgray(x) /* neither white nor black */ \
90 (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT)))
91
92#define tofinalize(x) testbit((x)->marked, FINALIZEDBIT)
93
94#define otherwhite(g) ((g)->currentwhite ^ WHITEBITS)
95#define isdeadm(ow,m) ((m) & (ow))
96#define isdead(g,v) isdeadm(otherwhite(g), (v)->marked)
97
98#define changewhite(x) ((x)->marked ^= WHITEBITS)
99#define nw2black(x) \
100 check_exp(!iswhite(x), l_setbit((x)->marked, BLACKBIT))
101
102#define luaC_white(g) cast_byte((g)->currentwhite & WHITEBITS)
103
104
105/* object age in generational mode */
106#define G_NEW 0 /* created in current cycle */
107#define G_SURVIVAL 1 /* created in previous cycle */
108#define G_OLD0 2 /* marked old by frw. barrier in this cycle */
109#define G_OLD1 3 /* first full cycle as old */
110#define G_OLD 4 /* really old object (not to be visited) */
111#define G_TOUCHED1 5 /* old object touched this cycle */
112#define G_TOUCHED2 6 /* old object touched in previous cycle */
113
114#define AGEBITS 7 /* all age bits (111) */
115
116#define getage(o) ((o)->marked & AGEBITS)
117#define setage(o,a) ((o)->marked = cast_byte(((o)->marked & (~AGEBITS)) | a))
118#define isold(o) (getage(o) > G_SURVIVAL)
119
120#define changeage(o,f,t) \
121 check_exp(getage(o) == (f), (o)->marked ^= ((f)^(t)))
122
123
124/* Default Values for GC parameters */
125#define LUAI_GENMAJORMUL 100
126#define LUAI_GENMINORMUL 20
127
128/* wait memory to double before starting new cycle */
129#define LUAI_GCPAUSE 200
130
131/*
132** some gc parameters are stored divided by 4 to allow a maximum value
133** up to 1023 in a 'lu_byte'.
134*/
135#define getgcparam(p) ((p) * 4)
136#define setgcparam(p,v) ((p) = (v) / 4)
137
138#define LUAI_GCMUL 100
139
140/* how much to allocate before next GC step (log2) */
141#define LUAI_GCSTEPSIZE 13 /* 8 KB */
142
143
144/*
145** Check whether the declared GC mode is generational. While in
146** generational mode, the collector can go temporarily to incremental
147** mode to improve performance. This is signaled by 'g->lastatomic != 0'.
148*/
149#define isdecGCmodegen(g) (g->gckind == KGC_GEN || g->lastatomic != 0)
150
151
152/*
153** Control when GC is running:
154*/
155#define GCSTPUSR 1 /* bit true when GC stopped by user */
156#define GCSTPGC 2 /* bit true when GC stopped by itself */
157#define GCSTPCLS 4 /* bit true when closing Lua state */
158#define gcrunning(g) ((g)->gcstp == 0)
159
160
161/*
162** Does one step of collection when debt becomes positive. 'pre'/'pos'
163** allows some adjustments to be done only when needed. macro
164** 'condchangemem' is used only for heavy tests (forcing a full
165** GC cycle on every opportunity)
166*/
167#define luaC_condGC(L,pre,pos) \
168 { if (G(L)->GCdebt > 0) { pre; luaC_step(L); pos;}; \
169 condchangemem(L,pre,pos); }
170
171/* more often than not, 'pre'/'pos' are empty */
172#define luaC_checkGC(L) luaC_condGC(L,(void)0,(void)0)
173
174
175#define luaC_objbarrier(L,p,o) ( \
176 (isblack(p) && iswhite(o)) ? \
177 luaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0))
178
179#define luaC_barrier(L,p,v) ( \
180 iscollectable(v) ? luaC_objbarrier(L,p,gcvalue(v)) : cast_void(0))
181
182#define luaC_objbarrierback(L,p,o) ( \
183 (isblack(p) && iswhite(o)) ? luaC_barrierback_(L,p) : cast_void(0))
184
185#define luaC_barrierback(L,p,v) ( \
186 iscollectable(v) ? luaC_objbarrierback(L, p, gcvalue(v)) : cast_void(0))
187
188LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o);
189LUAI_FUNC void luaC_freeallobjects (lua_State *L);
190LUAI_FUNC void luaC_step (lua_State *L);
191LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask);
192LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);
193LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz);
194LUAI_FUNC GCObject *luaC_newobjdt (lua_State *L, int tt, size_t sz,
195 size_t offset);
196LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);
197LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);
198LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);
199LUAI_FUNC void luaC_changemode (lua_State *L, int newmode);
200
201
202#endif
diff --git a/vendor/lua-5.4.8/src/linit.c b/vendor/lua-5.4.8/src/linit.c
new file mode 100644
index 0000000..69808f8
--- /dev/null
+++ b/vendor/lua-5.4.8/src/linit.c
@@ -0,0 +1,65 @@
1/*
2** $Id: linit.c $
3** Initialization of libraries for lua.c and other clients
4** See Copyright Notice in lua.h
5*/
6
7
8#define linit_c
9#define LUA_LIB
10
11/*
12** If you embed Lua in your program and need to open the standard
13** libraries, call luaL_openlibs in your program. If you need a
14** different set of libraries, copy this file to your project and edit
15** it to suit your needs.
16**
17** You can also *preload* libraries, so that a later 'require' can
18** open the library, which is already linked to the application.
19** For that, do the following code:
20**
21** luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
22** lua_pushcfunction(L, luaopen_modname);
23** lua_setfield(L, -2, modname);
24** lua_pop(L, 1); // remove PRELOAD table
25*/
26
27#include "lprefix.h"
28
29
30#include <stddef.h>
31
32#include "lua.h"
33
34#include "lualib.h"
35#include "lauxlib.h"
36
37
38/*
39** these libs are loaded by lua.c and are readily available to any Lua
40** program
41*/
42static const luaL_Reg loadedlibs[] = {
43 {LUA_GNAME, luaopen_base},
44 {LUA_LOADLIBNAME, luaopen_package},
45 {LUA_COLIBNAME, luaopen_coroutine},
46 {LUA_TABLIBNAME, luaopen_table},
47 {LUA_IOLIBNAME, luaopen_io},
48 {LUA_OSLIBNAME, luaopen_os},
49 {LUA_STRLIBNAME, luaopen_string},
50 {LUA_MATHLIBNAME, luaopen_math},
51 {LUA_UTF8LIBNAME, luaopen_utf8},
52 {LUA_DBLIBNAME, luaopen_debug},
53 {NULL, NULL}
54};
55
56
57LUALIB_API void luaL_openlibs (lua_State *L) {
58 const luaL_Reg *lib;
59 /* "require" functions from 'loadedlibs' and set results to global table */
60 for (lib = loadedlibs; lib->func; lib++) {
61 luaL_requiref(L, lib->name, lib->func, 1);
62 lua_pop(L, 1); /* remove lib */
63 }
64}
65
diff --git a/vendor/lua-5.4.8/src/liolib.c b/vendor/lua-5.4.8/src/liolib.c
new file mode 100644
index 0000000..c5075f3
--- /dev/null
+++ b/vendor/lua-5.4.8/src/liolib.c
@@ -0,0 +1,841 @@
1/*
2** $Id: liolib.c $
3** Standard I/O (and system) library
4** See Copyright Notice in lua.h
5*/
6
7#define liolib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <ctype.h>
14#include <errno.h>
15#include <locale.h>
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19
20#include "lua.h"
21
22#include "lauxlib.h"
23#include "lualib.h"
24
25
26
27
28/*
29** Change this macro to accept other modes for 'fopen' besides
30** the standard ones.
31*/
32#if !defined(l_checkmode)
33
34/* accepted extensions to 'mode' in 'fopen' */
35#if !defined(L_MODEEXT)
36#define L_MODEEXT "b"
37#endif
38
39/* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */
40static int l_checkmode (const char *mode) {
41 return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&
42 (*mode != '+' || ((void)(++mode), 1)) && /* skip if char is '+' */
43 (strspn(mode, L_MODEEXT) == strlen(mode))); /* check extensions */
44}
45
46#endif
47
48/*
49** {======================================================
50** l_popen spawns a new process connected to the current
51** one through the file streams.
52** =======================================================
53*/
54
55#if !defined(l_popen) /* { */
56
57#if defined(LUA_USE_POSIX) /* { */
58
59#define l_popen(L,c,m) (fflush(NULL), popen(c,m))
60#define l_pclose(L,file) (pclose(file))
61
62#elif defined(LUA_USE_WINDOWS) /* }{ */
63
64#define l_popen(L,c,m) (_popen(c,m))
65#define l_pclose(L,file) (_pclose(file))
66
67#if !defined(l_checkmodep)
68/* Windows accepts "[rw][bt]?" as valid modes */
69#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && \
70 (m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0')))
71#endif
72
73#else /* }{ */
74
75/* ISO C definitions */
76#define l_popen(L,c,m) \
77 ((void)c, (void)m, \
78 luaL_error(L, "'popen' not supported"), \
79 (FILE*)0)
80#define l_pclose(L,file) ((void)L, (void)file, -1)
81
82#endif /* } */
83
84#endif /* } */
85
86
87#if !defined(l_checkmodep)
88/* By default, Lua accepts only "r" or "w" as valid modes */
89#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0')
90#endif
91
92/* }====================================================== */
93
94
95#if !defined(l_getc) /* { */
96
97#if defined(LUA_USE_POSIX)
98#define l_getc(f) getc_unlocked(f)
99#define l_lockfile(f) flockfile(f)
100#define l_unlockfile(f) funlockfile(f)
101#else
102#define l_getc(f) getc(f)
103#define l_lockfile(f) ((void)0)
104#define l_unlockfile(f) ((void)0)
105#endif
106
107#endif /* } */
108
109
110/*
111** {======================================================
112** l_fseek: configuration for longer offsets
113** =======================================================
114*/
115
116#if !defined(l_fseek) /* { */
117
118#if defined(LUA_USE_POSIX) /* { */
119
120#include <sys/types.h>
121
122#define l_fseek(f,o,w) fseeko(f,o,w)
123#define l_ftell(f) ftello(f)
124#define l_seeknum off_t
125
126#elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
127 && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
128
129/* Windows (but not DDK) and Visual C++ 2005 or higher */
130#define l_fseek(f,o,w) _fseeki64(f,o,w)
131#define l_ftell(f) _ftelli64(f)
132#define l_seeknum __int64
133
134#else /* }{ */
135
136/* ISO C definitions */
137#define l_fseek(f,o,w) fseek(f,o,w)
138#define l_ftell(f) ftell(f)
139#define l_seeknum long
140
141#endif /* } */
142
143#endif /* } */
144
145/* }====================================================== */
146
147
148
149#define IO_PREFIX "_IO_"
150#define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
151#define IO_INPUT (IO_PREFIX "input")
152#define IO_OUTPUT (IO_PREFIX "output")
153
154
155typedef luaL_Stream LStream;
156
157
158#define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
159
160#define isclosed(p) ((p)->closef == NULL)
161
162
163static int io_type (lua_State *L) {
164 LStream *p;
165 luaL_checkany(L, 1);
166 p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
167 if (p == NULL)
168 luaL_pushfail(L); /* not a file */
169 else if (isclosed(p))
170 lua_pushliteral(L, "closed file");
171 else
172 lua_pushliteral(L, "file");
173 return 1;
174}
175
176
177static int f_tostring (lua_State *L) {
178 LStream *p = tolstream(L);
179 if (isclosed(p))
180 lua_pushliteral(L, "file (closed)");
181 else
182 lua_pushfstring(L, "file (%p)", p->f);
183 return 1;
184}
185
186
187static FILE *tofile (lua_State *L) {
188 LStream *p = tolstream(L);
189 if (l_unlikely(isclosed(p)))
190 luaL_error(L, "attempt to use a closed file");
191 lua_assert(p->f);
192 return p->f;
193}
194
195
196/*
197** When creating file handles, always creates a 'closed' file handle
198** before opening the actual file; so, if there is a memory error, the
199** handle is in a consistent state.
200*/
201static LStream *newprefile (lua_State *L) {
202 LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0);
203 p->closef = NULL; /* mark file handle as 'closed' */
204 luaL_setmetatable(L, LUA_FILEHANDLE);
205 return p;
206}
207
208
209/*
210** Calls the 'close' function from a file handle. The 'volatile' avoids
211** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
212** 32 bits).
213*/
214static int aux_close (lua_State *L) {
215 LStream *p = tolstream(L);
216 volatile lua_CFunction cf = p->closef;
217 p->closef = NULL; /* mark stream as closed */
218 return (*cf)(L); /* close it */
219}
220
221
222static int f_close (lua_State *L) {
223 tofile(L); /* make sure argument is an open stream */
224 return aux_close(L);
225}
226
227
228static int io_close (lua_State *L) {
229 if (lua_isnone(L, 1)) /* no argument? */
230 lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use default output */
231 return f_close(L);
232}
233
234
235static int f_gc (lua_State *L) {
236 LStream *p = tolstream(L);
237 if (!isclosed(p) && p->f != NULL)
238 aux_close(L); /* ignore closed and incompletely open files */
239 return 0;
240}
241
242
243/*
244** function to close regular files
245*/
246static int io_fclose (lua_State *L) {
247 LStream *p = tolstream(L);
248 errno = 0;
249 return luaL_fileresult(L, (fclose(p->f) == 0), NULL);
250}
251
252
253static LStream *newfile (lua_State *L) {
254 LStream *p = newprefile(L);
255 p->f = NULL;
256 p->closef = &io_fclose;
257 return p;
258}
259
260
261static void opencheck (lua_State *L, const char *fname, const char *mode) {
262 LStream *p = newfile(L);
263 p->f = fopen(fname, mode);
264 if (l_unlikely(p->f == NULL))
265 luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
266}
267
268
269static int io_open (lua_State *L) {
270 const char *filename = luaL_checkstring(L, 1);
271 const char *mode = luaL_optstring(L, 2, "r");
272 LStream *p = newfile(L);
273 const char *md = mode; /* to traverse/check mode */
274 luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
275 errno = 0;
276 p->f = fopen(filename, mode);
277 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
278}
279
280
281/*
282** function to close 'popen' files
283*/
284static int io_pclose (lua_State *L) {
285 LStream *p = tolstream(L);
286 errno = 0;
287 return luaL_execresult(L, l_pclose(L, p->f));
288}
289
290
291static int io_popen (lua_State *L) {
292 const char *filename = luaL_checkstring(L, 1);
293 const char *mode = luaL_optstring(L, 2, "r");
294 LStream *p = newprefile(L);
295 luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode");
296 errno = 0;
297 p->f = l_popen(L, filename, mode);
298 p->closef = &io_pclose;
299 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
300}
301
302
303static int io_tmpfile (lua_State *L) {
304 LStream *p = newfile(L);
305 errno = 0;
306 p->f = tmpfile();
307 return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
308}
309
310
311static FILE *getiofile (lua_State *L, const char *findex) {
312 LStream *p;
313 lua_getfield(L, LUA_REGISTRYINDEX, findex);
314 p = (LStream *)lua_touserdata(L, -1);
315 if (l_unlikely(isclosed(p)))
316 luaL_error(L, "default %s file is closed", findex + IOPREF_LEN);
317 return p->f;
318}
319
320
321static int g_iofile (lua_State *L, const char *f, const char *mode) {
322 if (!lua_isnoneornil(L, 1)) {
323 const char *filename = lua_tostring(L, 1);
324 if (filename)
325 opencheck(L, filename, mode);
326 else {
327 tofile(L); /* check that it's a valid file handle */
328 lua_pushvalue(L, 1);
329 }
330 lua_setfield(L, LUA_REGISTRYINDEX, f);
331 }
332 /* return current value */
333 lua_getfield(L, LUA_REGISTRYINDEX, f);
334 return 1;
335}
336
337
338static int io_input (lua_State *L) {
339 return g_iofile(L, IO_INPUT, "r");
340}
341
342
343static int io_output (lua_State *L) {
344 return g_iofile(L, IO_OUTPUT, "w");
345}
346
347
348static int io_readline (lua_State *L);
349
350
351/*
352** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
353** in the limit for upvalues of a closure)
354*/
355#define MAXARGLINE 250
356
357/*
358** Auxiliary function to create the iteration function for 'lines'.
359** The iteration function is a closure over 'io_readline', with
360** the following upvalues:
361** 1) The file being read (first value in the stack)
362** 2) the number of arguments to read
363** 3) a boolean, true iff file has to be closed when finished ('toclose')
364** *) a variable number of format arguments (rest of the stack)
365*/
366static void aux_lines (lua_State *L, int toclose) {
367 int n = lua_gettop(L) - 1; /* number of arguments to read */
368 luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
369 lua_pushvalue(L, 1); /* file */
370 lua_pushinteger(L, n); /* number of arguments to read */
371 lua_pushboolean(L, toclose); /* close/not close file when finished */
372 lua_rotate(L, 2, 3); /* move the three values to their positions */
373 lua_pushcclosure(L, io_readline, 3 + n);
374}
375
376
377static int f_lines (lua_State *L) {
378 tofile(L); /* check that it's a valid file handle */
379 aux_lines(L, 0);
380 return 1;
381}
382
383
384/*
385** Return an iteration function for 'io.lines'. If file has to be
386** closed, also returns the file itself as a second result (to be
387** closed as the state at the exit of a generic for).
388*/
389static int io_lines (lua_State *L) {
390 int toclose;
391 if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
392 if (lua_isnil(L, 1)) { /* no file name? */
393 lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
394 lua_replace(L, 1); /* put it at index 1 */
395 tofile(L); /* check that it's a valid file handle */
396 toclose = 0; /* do not close it after iteration */
397 }
398 else { /* open a new file */
399 const char *filename = luaL_checkstring(L, 1);
400 opencheck(L, filename, "r");
401 lua_replace(L, 1); /* put file at index 1 */
402 toclose = 1; /* close it after iteration */
403 }
404 aux_lines(L, toclose); /* push iteration function */
405 if (toclose) {
406 lua_pushnil(L); /* state */
407 lua_pushnil(L); /* control */
408 lua_pushvalue(L, 1); /* file is the to-be-closed variable (4th result) */
409 return 4;
410 }
411 else
412 return 1;
413}
414
415
416/*
417** {======================================================
418** READ
419** =======================================================
420*/
421
422
423/* maximum length of a numeral */
424#if !defined (L_MAXLENNUM)
425#define L_MAXLENNUM 200
426#endif
427
428
429/* auxiliary structure used by 'read_number' */
430typedef struct {
431 FILE *f; /* file being read */
432 int c; /* current character (look ahead) */
433 int n; /* number of elements in buffer 'buff' */
434 char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */
435} RN;
436
437
438/*
439** Add current char to buffer (if not out of space) and read next one
440*/
441static int nextc (RN *rn) {
442 if (l_unlikely(rn->n >= L_MAXLENNUM)) { /* buffer overflow? */
443 rn->buff[0] = '\0'; /* invalidate result */
444 return 0; /* fail */
445 }
446 else {
447 rn->buff[rn->n++] = rn->c; /* save current char */
448 rn->c = l_getc(rn->f); /* read next one */
449 return 1;
450 }
451}
452
453
454/*
455** Accept current char if it is in 'set' (of size 2)
456*/
457static int test2 (RN *rn, const char *set) {
458 if (rn->c == set[0] || rn->c == set[1])
459 return nextc(rn);
460 else return 0;
461}
462
463
464/*
465** Read a sequence of (hex)digits
466*/
467static int readdigits (RN *rn, int hex) {
468 int count = 0;
469 while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
470 count++;
471 return count;
472}
473
474
475/*
476** Read a number: first reads a valid prefix of a numeral into a buffer.
477** Then it calls 'lua_stringtonumber' to check whether the format is
478** correct and to convert it to a Lua number.
479*/
480static int read_number (lua_State *L, FILE *f) {
481 RN rn;
482 int count = 0;
483 int hex = 0;
484 char decp[2];
485 rn.f = f; rn.n = 0;
486 decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
487 decp[1] = '.'; /* always accept a dot */
488 l_lockfile(rn.f);
489 do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
490 test2(&rn, "-+"); /* optional sign */
491 if (test2(&rn, "00")) {
492 if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
493 else count = 1; /* count initial '0' as a valid digit */
494 }
495 count += readdigits(&rn, hex); /* integral part */
496 if (test2(&rn, decp)) /* decimal point? */
497 count += readdigits(&rn, hex); /* fractional part */
498 if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
499 test2(&rn, "-+"); /* exponent sign */
500 readdigits(&rn, 0); /* exponent digits */
501 }
502 ungetc(rn.c, rn.f); /* unread look-ahead char */
503 l_unlockfile(rn.f);
504 rn.buff[rn.n] = '\0'; /* finish string */
505 if (l_likely(lua_stringtonumber(L, rn.buff)))
506 return 1; /* ok, it is a valid number */
507 else { /* invalid format */
508 lua_pushnil(L); /* "result" to be removed */
509 return 0; /* read fails */
510 }
511}
512
513
514static int test_eof (lua_State *L, FILE *f) {
515 int c = getc(f);
516 ungetc(c, f); /* no-op when c == EOF */
517 lua_pushliteral(L, "");
518 return (c != EOF);
519}
520
521
522static int read_line (lua_State *L, FILE *f, int chop) {
523 luaL_Buffer b;
524 int c;
525 luaL_buffinit(L, &b);
526 do { /* may need to read several chunks to get whole line */
527 char *buff = luaL_prepbuffer(&b); /* preallocate buffer space */
528 int i = 0;
529 l_lockfile(f); /* no memory errors can happen inside the lock */
530 while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
531 buff[i++] = c; /* read up to end of line or buffer limit */
532 l_unlockfile(f);
533 luaL_addsize(&b, i);
534 } while (c != EOF && c != '\n'); /* repeat until end of line */
535 if (!chop && c == '\n') /* want a newline and have one? */
536 luaL_addchar(&b, c); /* add ending newline to result */
537 luaL_pushresult(&b); /* close buffer */
538 /* return ok if read something (either a newline or something else) */
539 return (c == '\n' || lua_rawlen(L, -1) > 0);
540}
541
542
543static void read_all (lua_State *L, FILE *f) {
544 size_t nr;
545 luaL_Buffer b;
546 luaL_buffinit(L, &b);
547 do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
548 char *p = luaL_prepbuffer(&b);
549 nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
550 luaL_addsize(&b, nr);
551 } while (nr == LUAL_BUFFERSIZE);
552 luaL_pushresult(&b); /* close buffer */
553}
554
555
556static int read_chars (lua_State *L, FILE *f, size_t n) {
557 size_t nr; /* number of chars actually read */
558 char *p;
559 luaL_Buffer b;
560 luaL_buffinit(L, &b);
561 p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
562 nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
563 luaL_addsize(&b, nr);
564 luaL_pushresult(&b); /* close buffer */
565 return (nr > 0); /* true iff read something */
566}
567
568
569static int g_read (lua_State *L, FILE *f, int first) {
570 int nargs = lua_gettop(L) - 1;
571 int n, success;
572 clearerr(f);
573 errno = 0;
574 if (nargs == 0) { /* no arguments? */
575 success = read_line(L, f, 1);
576 n = first + 1; /* to return 1 result */
577 }
578 else {
579 /* ensure stack space for all results and for auxlib's buffer */
580 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
581 success = 1;
582 for (n = first; nargs-- && success; n++) {
583 if (lua_type(L, n) == LUA_TNUMBER) {
584 size_t l = (size_t)luaL_checkinteger(L, n);
585 success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
586 }
587 else {
588 const char *p = luaL_checkstring(L, n);
589 if (*p == '*') p++; /* skip optional '*' (for compatibility) */
590 switch (*p) {
591 case 'n': /* number */
592 success = read_number(L, f);
593 break;
594 case 'l': /* line */
595 success = read_line(L, f, 1);
596 break;
597 case 'L': /* line with end-of-line */
598 success = read_line(L, f, 0);
599 break;
600 case 'a': /* file */
601 read_all(L, f); /* read entire file */
602 success = 1; /* always success */
603 break;
604 default:
605 return luaL_argerror(L, n, "invalid format");
606 }
607 }
608 }
609 }
610 if (ferror(f))
611 return luaL_fileresult(L, 0, NULL);
612 if (!success) {
613 lua_pop(L, 1); /* remove last result */
614 luaL_pushfail(L); /* push nil instead */
615 }
616 return n - first;
617}
618
619
620static int io_read (lua_State *L) {
621 return g_read(L, getiofile(L, IO_INPUT), 1);
622}
623
624
625static int f_read (lua_State *L) {
626 return g_read(L, tofile(L), 2);
627}
628
629
630/*
631** Iteration function for 'lines'.
632*/
633static int io_readline (lua_State *L) {
634 LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
635 int i;
636 int n = (int)lua_tointeger(L, lua_upvalueindex(2));
637 if (isclosed(p)) /* file is already closed? */
638 return luaL_error(L, "file is already closed");
639 lua_settop(L , 1);
640 luaL_checkstack(L, n, "too many arguments");
641 for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
642 lua_pushvalue(L, lua_upvalueindex(3 + i));
643 n = g_read(L, p->f, 2); /* 'n' is number of results */
644 lua_assert(n > 0); /* should return at least a nil */
645 if (lua_toboolean(L, -n)) /* read at least one value? */
646 return n; /* return them */
647 else { /* first result is false: EOF or error */
648 if (n > 1) { /* is there error information? */
649 /* 2nd result is error message */
650 return luaL_error(L, "%s", lua_tostring(L, -n + 1));
651 }
652 if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
653 lua_settop(L, 0); /* clear stack */
654 lua_pushvalue(L, lua_upvalueindex(1)); /* push file at index 1 */
655 aux_close(L); /* close it */
656 }
657 return 0;
658 }
659}
660
661/* }====================================================== */
662
663
664static int g_write (lua_State *L, FILE *f, int arg) {
665 int nargs = lua_gettop(L) - arg;
666 int status = 1;
667 errno = 0;
668 for (; nargs--; arg++) {
669 if (lua_type(L, arg) == LUA_TNUMBER) {
670 /* optimization: could be done exactly as for strings */
671 int len = lua_isinteger(L, arg)
672 ? fprintf(f, LUA_INTEGER_FMT,
673 (LUAI_UACINT)lua_tointeger(L, arg))
674 : fprintf(f, LUA_NUMBER_FMT,
675 (LUAI_UACNUMBER)lua_tonumber(L, arg));
676 status = status && (len > 0);
677 }
678 else {
679 size_t l;
680 const char *s = luaL_checklstring(L, arg, &l);
681 status = status && (fwrite(s, sizeof(char), l, f) == l);
682 }
683 }
684 if (l_likely(status))
685 return 1; /* file handle already on stack top */
686 else
687 return luaL_fileresult(L, status, NULL);
688}
689
690
691static int io_write (lua_State *L) {
692 return g_write(L, getiofile(L, IO_OUTPUT), 1);
693}
694
695
696static int f_write (lua_State *L) {
697 FILE *f = tofile(L);
698 lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
699 return g_write(L, f, 2);
700}
701
702
703static int f_seek (lua_State *L) {
704 static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
705 static const char *const modenames[] = {"set", "cur", "end", NULL};
706 FILE *f = tofile(L);
707 int op = luaL_checkoption(L, 2, "cur", modenames);
708 lua_Integer p3 = luaL_optinteger(L, 3, 0);
709 l_seeknum offset = (l_seeknum)p3;
710 luaL_argcheck(L, (lua_Integer)offset == p3, 3,
711 "not an integer in proper range");
712 errno = 0;
713 op = l_fseek(f, offset, mode[op]);
714 if (l_unlikely(op))
715 return luaL_fileresult(L, 0, NULL); /* error */
716 else {
717 lua_pushinteger(L, (lua_Integer)l_ftell(f));
718 return 1;
719 }
720}
721
722
723static int f_setvbuf (lua_State *L) {
724 static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
725 static const char *const modenames[] = {"no", "full", "line", NULL};
726 FILE *f = tofile(L);
727 int op = luaL_checkoption(L, 2, NULL, modenames);
728 lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
729 int res;
730 errno = 0;
731 res = setvbuf(f, NULL, mode[op], (size_t)sz);
732 return luaL_fileresult(L, res == 0, NULL);
733}
734
735
736
737static int io_flush (lua_State *L) {
738 FILE *f = getiofile(L, IO_OUTPUT);
739 errno = 0;
740 return luaL_fileresult(L, fflush(f) == 0, NULL);
741}
742
743
744static int f_flush (lua_State *L) {
745 FILE *f = tofile(L);
746 errno = 0;
747 return luaL_fileresult(L, fflush(f) == 0, NULL);
748}
749
750
751/*
752** functions for 'io' library
753*/
754static const luaL_Reg iolib[] = {
755 {"close", io_close},
756 {"flush", io_flush},
757 {"input", io_input},
758 {"lines", io_lines},
759 {"open", io_open},
760 {"output", io_output},
761 {"popen", io_popen},
762 {"read", io_read},
763 {"tmpfile", io_tmpfile},
764 {"type", io_type},
765 {"write", io_write},
766 {NULL, NULL}
767};
768
769
770/*
771** methods for file handles
772*/
773static const luaL_Reg meth[] = {
774 {"read", f_read},
775 {"write", f_write},
776 {"lines", f_lines},
777 {"flush", f_flush},
778 {"seek", f_seek},
779 {"close", f_close},
780 {"setvbuf", f_setvbuf},
781 {NULL, NULL}
782};
783
784
785/*
786** metamethods for file handles
787*/
788static const luaL_Reg metameth[] = {
789 {"__index", NULL}, /* placeholder */
790 {"__gc", f_gc},
791 {"__close", f_gc},
792 {"__tostring", f_tostring},
793 {NULL, NULL}
794};
795
796
797static void createmeta (lua_State *L) {
798 luaL_newmetatable(L, LUA_FILEHANDLE); /* metatable for file handles */
799 luaL_setfuncs(L, metameth, 0); /* add metamethods to new metatable */
800 luaL_newlibtable(L, meth); /* create method table */
801 luaL_setfuncs(L, meth, 0); /* add file methods to method table */
802 lua_setfield(L, -2, "__index"); /* metatable.__index = method table */
803 lua_pop(L, 1); /* pop metatable */
804}
805
806
807/*
808** function to (not) close the standard files stdin, stdout, and stderr
809*/
810static int io_noclose (lua_State *L) {
811 LStream *p = tolstream(L);
812 p->closef = &io_noclose; /* keep file opened */
813 luaL_pushfail(L);
814 lua_pushliteral(L, "cannot close standard file");
815 return 2;
816}
817
818
819static void createstdfile (lua_State *L, FILE *f, const char *k,
820 const char *fname) {
821 LStream *p = newprefile(L);
822 p->f = f;
823 p->closef = &io_noclose;
824 if (k != NULL) {
825 lua_pushvalue(L, -1);
826 lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
827 }
828 lua_setfield(L, -2, fname); /* add file to module */
829}
830
831
832LUAMOD_API int luaopen_io (lua_State *L) {
833 luaL_newlib(L, iolib); /* new module */
834 createmeta(L);
835 /* create (and set) default files */
836 createstdfile(L, stdin, IO_INPUT, "stdin");
837 createstdfile(L, stdout, IO_OUTPUT, "stdout");
838 createstdfile(L, stderr, NULL, "stderr");
839 return 1;
840}
841
diff --git a/vendor/lua-5.4.8/src/ljumptab.h b/vendor/lua-5.4.8/src/ljumptab.h
new file mode 100644
index 0000000..8306f25
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ljumptab.h
@@ -0,0 +1,112 @@
1/*
2** $Id: ljumptab.h $
3** Jump Table for the Lua interpreter
4** See Copyright Notice in lua.h
5*/
6
7
8#undef vmdispatch
9#undef vmcase
10#undef vmbreak
11
12#define vmdispatch(x) goto *disptab[x];
13
14#define vmcase(l) L_##l:
15
16#define vmbreak vmfetch(); vmdispatch(GET_OPCODE(i));
17
18
19static const void *const disptab[NUM_OPCODES] = {
20
21#if 0
22** you can update the following list with this command:
23**
24** sed -n '/^OP_/\!d; s/OP_/\&\&L_OP_/ ; s/,.*/,/ ; s/\/.*// ; p' lopcodes.h
25**
26#endif
27
28&&L_OP_MOVE,
29&&L_OP_LOADI,
30&&L_OP_LOADF,
31&&L_OP_LOADK,
32&&L_OP_LOADKX,
33&&L_OP_LOADFALSE,
34&&L_OP_LFALSESKIP,
35&&L_OP_LOADTRUE,
36&&L_OP_LOADNIL,
37&&L_OP_GETUPVAL,
38&&L_OP_SETUPVAL,
39&&L_OP_GETTABUP,
40&&L_OP_GETTABLE,
41&&L_OP_GETI,
42&&L_OP_GETFIELD,
43&&L_OP_SETTABUP,
44&&L_OP_SETTABLE,
45&&L_OP_SETI,
46&&L_OP_SETFIELD,
47&&L_OP_NEWTABLE,
48&&L_OP_SELF,
49&&L_OP_ADDI,
50&&L_OP_ADDK,
51&&L_OP_SUBK,
52&&L_OP_MULK,
53&&L_OP_MODK,
54&&L_OP_POWK,
55&&L_OP_DIVK,
56&&L_OP_IDIVK,
57&&L_OP_BANDK,
58&&L_OP_BORK,
59&&L_OP_BXORK,
60&&L_OP_SHRI,
61&&L_OP_SHLI,
62&&L_OP_ADD,
63&&L_OP_SUB,
64&&L_OP_MUL,
65&&L_OP_MOD,
66&&L_OP_POW,
67&&L_OP_DIV,
68&&L_OP_IDIV,
69&&L_OP_BAND,
70&&L_OP_BOR,
71&&L_OP_BXOR,
72&&L_OP_SHL,
73&&L_OP_SHR,
74&&L_OP_MMBIN,
75&&L_OP_MMBINI,
76&&L_OP_MMBINK,
77&&L_OP_UNM,
78&&L_OP_BNOT,
79&&L_OP_NOT,
80&&L_OP_LEN,
81&&L_OP_CONCAT,
82&&L_OP_CLOSE,
83&&L_OP_TBC,
84&&L_OP_JMP,
85&&L_OP_EQ,
86&&L_OP_LT,
87&&L_OP_LE,
88&&L_OP_EQK,
89&&L_OP_EQI,
90&&L_OP_LTI,
91&&L_OP_LEI,
92&&L_OP_GTI,
93&&L_OP_GEI,
94&&L_OP_TEST,
95&&L_OP_TESTSET,
96&&L_OP_CALL,
97&&L_OP_TAILCALL,
98&&L_OP_RETURN,
99&&L_OP_RETURN0,
100&&L_OP_RETURN1,
101&&L_OP_FORLOOP,
102&&L_OP_FORPREP,
103&&L_OP_TFORPREP,
104&&L_OP_TFORCALL,
105&&L_OP_TFORLOOP,
106&&L_OP_SETLIST,
107&&L_OP_CLOSURE,
108&&L_OP_VARARG,
109&&L_OP_VARARGPREP,
110&&L_OP_EXTRAARG
111
112};
diff --git a/vendor/lua-5.4.8/src/llex.c b/vendor/lua-5.4.8/src/llex.c
new file mode 100644
index 0000000..5fc39a5
--- /dev/null
+++ b/vendor/lua-5.4.8/src/llex.c
@@ -0,0 +1,581 @@
1/*
2** $Id: llex.c $
3** Lexical Analyzer
4** See Copyright Notice in lua.h
5*/
6
7#define llex_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <locale.h>
14#include <string.h>
15
16#include "lua.h"
17
18#include "lctype.h"
19#include "ldebug.h"
20#include "ldo.h"
21#include "lgc.h"
22#include "llex.h"
23#include "lobject.h"
24#include "lparser.h"
25#include "lstate.h"
26#include "lstring.h"
27#include "ltable.h"
28#include "lzio.h"
29
30
31
32#define next(ls) (ls->current = zgetc(ls->z))
33
34
35
36#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r')
37
38
39/* ORDER RESERVED */
40static const char *const luaX_tokens [] = {
41 "and", "break", "do", "else", "elseif",
42 "end", "false", "for", "function", "goto", "if",
43 "in", "local", "nil", "not", "or", "repeat",
44 "return", "then", "true", "until", "while",
45 "//", "..", "...", "==", ">=", "<=", "~=",
46 "<<", ">>", "::", "<eof>",
47 "<number>", "<integer>", "<name>", "<string>"
48};
49
50
51#define save_and_next(ls) (save(ls, ls->current), next(ls))
52
53
54static l_noret lexerror (LexState *ls, const char *msg, int token);
55
56
57static void save (LexState *ls, int c) {
58 Mbuffer *b = ls->buff;
59 if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {
60 size_t newsize;
61 if (luaZ_sizebuffer(b) >= MAX_SIZE/2)
62 lexerror(ls, "lexical element too long", 0);
63 newsize = luaZ_sizebuffer(b) * 2;
64 luaZ_resizebuffer(ls->L, b, newsize);
65 }
66 b->buffer[luaZ_bufflen(b)++] = cast_char(c);
67}
68
69
70void luaX_init (lua_State *L) {
71 int i;
72 TString *e = luaS_newliteral(L, LUA_ENV); /* create env name */
73 luaC_fix(L, obj2gco(e)); /* never collect this name */
74 for (i=0; i<NUM_RESERVED; i++) {
75 TString *ts = luaS_new(L, luaX_tokens[i]);
76 luaC_fix(L, obj2gco(ts)); /* reserved words are never collected */
77 ts->extra = cast_byte(i+1); /* reserved word */
78 }
79}
80
81
82const char *luaX_token2str (LexState *ls, int token) {
83 if (token < FIRST_RESERVED) { /* single-byte symbols? */
84 if (lisprint(token))
85 return luaO_pushfstring(ls->L, "'%c'", token);
86 else /* control character */
87 return luaO_pushfstring(ls->L, "'<\\%d>'", token);
88 }
89 else {
90 const char *s = luaX_tokens[token - FIRST_RESERVED];
91 if (token < TK_EOS) /* fixed format (symbols and reserved words)? */
92 return luaO_pushfstring(ls->L, "'%s'", s);
93 else /* names, strings, and numerals */
94 return s;
95 }
96}
97
98
99static const char *txtToken (LexState *ls, int token) {
100 switch (token) {
101 case TK_NAME: case TK_STRING:
102 case TK_FLT: case TK_INT:
103 save(ls, '\0');
104 return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff));
105 default:
106 return luaX_token2str(ls, token);
107 }
108}
109
110
111static l_noret lexerror (LexState *ls, const char *msg, int token) {
112 msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber);
113 if (token)
114 luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token));
115 luaD_throw(ls->L, LUA_ERRSYNTAX);
116}
117
118
119l_noret luaX_syntaxerror (LexState *ls, const char *msg) {
120 lexerror(ls, msg, ls->t.token);
121}
122
123
124/*
125** Creates a new string and anchors it in scanner's table so that it
126** will not be collected until the end of the compilation; by that time
127** it should be anchored somewhere. It also internalizes long strings,
128** ensuring there is only one copy of each unique string. The table
129** here is used as a set: the string enters as the key, while its value
130** is irrelevant. We use the string itself as the value only because it
131** is a TValue readily available. Later, the code generation can change
132** this value.
133*/
134TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
135 lua_State *L = ls->L;
136 TString *ts = luaS_newlstr(L, str, l); /* create new string */
137 const TValue *o = luaH_getstr(ls->h, ts);
138 if (!ttisnil(o)) /* string already present? */
139 ts = keystrval(nodefromval(o)); /* get saved copy */
140 else { /* not in use yet */
141 TValue *stv = s2v(L->top.p++); /* reserve stack space for string */
142 setsvalue(L, stv, ts); /* temporarily anchor the string */
143 luaH_finishset(L, ls->h, stv, o, stv); /* t[string] = string */
144 /* table is not a metatable, so it does not need to invalidate cache */
145 luaC_checkGC(L);
146 L->top.p--; /* remove string from stack */
147 }
148 return ts;
149}
150
151
152/*
153** increment line number and skips newline sequence (any of
154** \n, \r, \n\r, or \r\n)
155*/
156static void inclinenumber (LexState *ls) {
157 int old = ls->current;
158 lua_assert(currIsNewline(ls));
159 next(ls); /* skip '\n' or '\r' */
160 if (currIsNewline(ls) && ls->current != old)
161 next(ls); /* skip '\n\r' or '\r\n' */
162 if (++ls->linenumber >= MAX_INT)
163 lexerror(ls, "chunk has too many lines", 0);
164}
165
166
167void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
168 int firstchar) {
169 ls->t.token = 0;
170 ls->L = L;
171 ls->current = firstchar;
172 ls->lookahead.token = TK_EOS; /* no look-ahead token */
173 ls->z = z;
174 ls->fs = NULL;
175 ls->linenumber = 1;
176 ls->lastline = 1;
177 ls->source = source;
178 ls->envn = luaS_newliteral(L, LUA_ENV); /* get env name */
179 luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
180}
181
182
183
184/*
185** =======================================================
186** LEXICAL ANALYZER
187** =======================================================
188*/
189
190
191static int check_next1 (LexState *ls, int c) {
192 if (ls->current == c) {
193 next(ls);
194 return 1;
195 }
196 else return 0;
197}
198
199
200/*
201** Check whether current char is in set 'set' (with two chars) and
202** saves it
203*/
204static int check_next2 (LexState *ls, const char *set) {
205 lua_assert(set[2] == '\0');
206 if (ls->current == set[0] || ls->current == set[1]) {
207 save_and_next(ls);
208 return 1;
209 }
210 else return 0;
211}
212
213
214/* LUA_NUMBER */
215/*
216** This function is quite liberal in what it accepts, as 'luaO_str2num'
217** will reject ill-formed numerals. Roughly, it accepts the following
218** pattern:
219**
220** %d(%x|%.|([Ee][+-]?))* | 0[Xx](%x|%.|([Pp][+-]?))*
221**
222** The only tricky part is to accept [+-] only after a valid exponent
223** mark, to avoid reading '3-4' or '0xe+1' as a single number.
224**
225** The caller might have already read an initial dot.
226*/
227static int read_numeral (LexState *ls, SemInfo *seminfo) {
228 TValue obj;
229 const char *expo = "Ee";
230 int first = ls->current;
231 lua_assert(lisdigit(ls->current));
232 save_and_next(ls);
233 if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */
234 expo = "Pp";
235 for (;;) {
236 if (check_next2(ls, expo)) /* exponent mark? */
237 check_next2(ls, "-+"); /* optional exponent sign */
238 else if (lisxdigit(ls->current) || ls->current == '.') /* '%x|%.' */
239 save_and_next(ls);
240 else break;
241 }
242 if (lislalpha(ls->current)) /* is numeral touching a letter? */
243 save_and_next(ls); /* force an error */
244 save(ls, '\0');
245 if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */
246 lexerror(ls, "malformed number", TK_FLT);
247 if (ttisinteger(&obj)) {
248 seminfo->i = ivalue(&obj);
249 return TK_INT;
250 }
251 else {
252 lua_assert(ttisfloat(&obj));
253 seminfo->r = fltvalue(&obj);
254 return TK_FLT;
255 }
256}
257
258
259/*
260** read a sequence '[=*[' or ']=*]', leaving the last bracket. If
261** sequence is well formed, return its number of '='s + 2; otherwise,
262** return 1 if it is a single bracket (no '='s and no 2nd bracket);
263** otherwise (an unfinished '[==...') return 0.
264*/
265static size_t skip_sep (LexState *ls) {
266 size_t count = 0;
267 int s = ls->current;
268 lua_assert(s == '[' || s == ']');
269 save_and_next(ls);
270 while (ls->current == '=') {
271 save_and_next(ls);
272 count++;
273 }
274 return (ls->current == s) ? count + 2
275 : (count == 0) ? 1
276 : 0;
277}
278
279
280static void read_long_string (LexState *ls, SemInfo *seminfo, size_t sep) {
281 int line = ls->linenumber; /* initial line (for error message) */
282 save_and_next(ls); /* skip 2nd '[' */
283 if (currIsNewline(ls)) /* string starts with a newline? */
284 inclinenumber(ls); /* skip it */
285 for (;;) {
286 switch (ls->current) {
287 case EOZ: { /* error */
288 const char *what = (seminfo ? "string" : "comment");
289 const char *msg = luaO_pushfstring(ls->L,
290 "unfinished long %s (starting at line %d)", what, line);
291 lexerror(ls, msg, TK_EOS);
292 break; /* to avoid warnings */
293 }
294 case ']': {
295 if (skip_sep(ls) == sep) {
296 save_and_next(ls); /* skip 2nd ']' */
297 goto endloop;
298 }
299 break;
300 }
301 case '\n': case '\r': {
302 save(ls, '\n');
303 inclinenumber(ls);
304 if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */
305 break;
306 }
307 default: {
308 if (seminfo) save_and_next(ls);
309 else next(ls);
310 }
311 }
312 } endloop:
313 if (seminfo)
314 seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + sep,
315 luaZ_bufflen(ls->buff) - 2 * sep);
316}
317
318
319static void esccheck (LexState *ls, int c, const char *msg) {
320 if (!c) {
321 if (ls->current != EOZ)
322 save_and_next(ls); /* add current to buffer for error message */
323 lexerror(ls, msg, TK_STRING);
324 }
325}
326
327
328static int gethexa (LexState *ls) {
329 save_and_next(ls);
330 esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected");
331 return luaO_hexavalue(ls->current);
332}
333
334
335static int readhexaesc (LexState *ls) {
336 int r = gethexa(ls);
337 r = (r << 4) + gethexa(ls);
338 luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */
339 return r;
340}
341
342
343static unsigned long readutf8esc (LexState *ls) {
344 unsigned long r;
345 int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */
346 save_and_next(ls); /* skip 'u' */
347 esccheck(ls, ls->current == '{', "missing '{'");
348 r = gethexa(ls); /* must have at least one digit */
349 while (cast_void(save_and_next(ls)), lisxdigit(ls->current)) {
350 i++;
351 esccheck(ls, r <= (0x7FFFFFFFu >> 4), "UTF-8 value too large");
352 r = (r << 4) + luaO_hexavalue(ls->current);
353 }
354 esccheck(ls, ls->current == '}', "missing '}'");
355 next(ls); /* skip '}' */
356 luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */
357 return r;
358}
359
360
361static void utf8esc (LexState *ls) {
362 char buff[UTF8BUFFSZ];
363 int n = luaO_utf8esc(buff, readutf8esc(ls));
364 for (; n > 0; n--) /* add 'buff' to string */
365 save(ls, buff[UTF8BUFFSZ - n]);
366}
367
368
369static int readdecesc (LexState *ls) {
370 int i;
371 int r = 0; /* result accumulator */
372 for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
373 r = 10*r + ls->current - '0';
374 save_and_next(ls);
375 }
376 esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
377 luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */
378 return r;
379}
380
381
382static void read_string (LexState *ls, int del, SemInfo *seminfo) {
383 save_and_next(ls); /* keep delimiter (for error messages) */
384 while (ls->current != del) {
385 switch (ls->current) {
386 case EOZ:
387 lexerror(ls, "unfinished string", TK_EOS);
388 break; /* to avoid warnings */
389 case '\n':
390 case '\r':
391 lexerror(ls, "unfinished string", TK_STRING);
392 break; /* to avoid warnings */
393 case '\\': { /* escape sequences */
394 int c; /* final character to be saved */
395 save_and_next(ls); /* keep '\\' for error messages */
396 switch (ls->current) {
397 case 'a': c = '\a'; goto read_save;
398 case 'b': c = '\b'; goto read_save;
399 case 'f': c = '\f'; goto read_save;
400 case 'n': c = '\n'; goto read_save;
401 case 'r': c = '\r'; goto read_save;
402 case 't': c = '\t'; goto read_save;
403 case 'v': c = '\v'; goto read_save;
404 case 'x': c = readhexaesc(ls); goto read_save;
405 case 'u': utf8esc(ls); goto no_save;
406 case '\n': case '\r':
407 inclinenumber(ls); c = '\n'; goto only_save;
408 case '\\': case '\"': case '\'':
409 c = ls->current; goto read_save;
410 case EOZ: goto no_save; /* will raise an error next loop */
411 case 'z': { /* zap following span of spaces */
412 luaZ_buffremove(ls->buff, 1); /* remove '\\' */
413 next(ls); /* skip the 'z' */
414 while (lisspace(ls->current)) {
415 if (currIsNewline(ls)) inclinenumber(ls);
416 else next(ls);
417 }
418 goto no_save;
419 }
420 default: {
421 esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
422 c = readdecesc(ls); /* digital escape '\ddd' */
423 goto only_save;
424 }
425 }
426 read_save:
427 next(ls);
428 /* go through */
429 only_save:
430 luaZ_buffremove(ls->buff, 1); /* remove '\\' */
431 save(ls, c);
432 /* go through */
433 no_save: break;
434 }
435 default:
436 save_and_next(ls);
437 }
438 }
439 save_and_next(ls); /* skip delimiter */
440 seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
441 luaZ_bufflen(ls->buff) - 2);
442}
443
444
445static int llex (LexState *ls, SemInfo *seminfo) {
446 luaZ_resetbuffer(ls->buff);
447 for (;;) {
448 switch (ls->current) {
449 case '\n': case '\r': { /* line breaks */
450 inclinenumber(ls);
451 break;
452 }
453 case ' ': case '\f': case '\t': case '\v': { /* spaces */
454 next(ls);
455 break;
456 }
457 case '-': { /* '-' or '--' (comment) */
458 next(ls);
459 if (ls->current != '-') return '-';
460 /* else is a comment */
461 next(ls);
462 if (ls->current == '[') { /* long comment? */
463 size_t sep = skip_sep(ls);
464 luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */
465 if (sep >= 2) {
466 read_long_string(ls, NULL, sep); /* skip long comment */
467 luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
468 break;
469 }
470 }
471 /* else short comment */
472 while (!currIsNewline(ls) && ls->current != EOZ)
473 next(ls); /* skip until end of line (or end of file) */
474 break;
475 }
476 case '[': { /* long string or simply '[' */
477 size_t sep = skip_sep(ls);
478 if (sep >= 2) {
479 read_long_string(ls, seminfo, sep);
480 return TK_STRING;
481 }
482 else if (sep == 0) /* '[=...' missing second bracket? */
483 lexerror(ls, "invalid long string delimiter", TK_STRING);
484 return '[';
485 }
486 case '=': {
487 next(ls);
488 if (check_next1(ls, '=')) return TK_EQ; /* '==' */
489 else return '=';
490 }
491 case '<': {
492 next(ls);
493 if (check_next1(ls, '=')) return TK_LE; /* '<=' */
494 else if (check_next1(ls, '<')) return TK_SHL; /* '<<' */
495 else return '<';
496 }
497 case '>': {
498 next(ls);
499 if (check_next1(ls, '=')) return TK_GE; /* '>=' */
500 else if (check_next1(ls, '>')) return TK_SHR; /* '>>' */
501 else return '>';
502 }
503 case '/': {
504 next(ls);
505 if (check_next1(ls, '/')) return TK_IDIV; /* '//' */
506 else return '/';
507 }
508 case '~': {
509 next(ls);
510 if (check_next1(ls, '=')) return TK_NE; /* '~=' */
511 else return '~';
512 }
513 case ':': {
514 next(ls);
515 if (check_next1(ls, ':')) return TK_DBCOLON; /* '::' */
516 else return ':';
517 }
518 case '"': case '\'': { /* short literal strings */
519 read_string(ls, ls->current, seminfo);
520 return TK_STRING;
521 }
522 case '.': { /* '.', '..', '...', or number */
523 save_and_next(ls);
524 if (check_next1(ls, '.')) {
525 if (check_next1(ls, '.'))
526 return TK_DOTS; /* '...' */
527 else return TK_CONCAT; /* '..' */
528 }
529 else if (!lisdigit(ls->current)) return '.';
530 else return read_numeral(ls, seminfo);
531 }
532 case '0': case '1': case '2': case '3': case '4':
533 case '5': case '6': case '7': case '8': case '9': {
534 return read_numeral(ls, seminfo);
535 }
536 case EOZ: {
537 return TK_EOS;
538 }
539 default: {
540 if (lislalpha(ls->current)) { /* identifier or reserved word? */
541 TString *ts;
542 do {
543 save_and_next(ls);
544 } while (lislalnum(ls->current));
545 ts = luaX_newstring(ls, luaZ_buffer(ls->buff),
546 luaZ_bufflen(ls->buff));
547 seminfo->ts = ts;
548 if (isreserved(ts)) /* reserved word? */
549 return ts->extra - 1 + FIRST_RESERVED;
550 else {
551 return TK_NAME;
552 }
553 }
554 else { /* single-char tokens ('+', '*', '%', '{', '}', ...) */
555 int c = ls->current;
556 next(ls);
557 return c;
558 }
559 }
560 }
561 }
562}
563
564
565void luaX_next (LexState *ls) {
566 ls->lastline = ls->linenumber;
567 if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
568 ls->t = ls->lookahead; /* use this one */
569 ls->lookahead.token = TK_EOS; /* and discharge it */
570 }
571 else
572 ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */
573}
574
575
576int luaX_lookahead (LexState *ls) {
577 lua_assert(ls->lookahead.token == TK_EOS);
578 ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);
579 return ls->lookahead.token;
580}
581
diff --git a/vendor/lua-5.4.8/src/llex.h b/vendor/lua-5.4.8/src/llex.h
new file mode 100644
index 0000000..389d2f8
--- /dev/null
+++ b/vendor/lua-5.4.8/src/llex.h
@@ -0,0 +1,91 @@
1/*
2** $Id: llex.h $
3** Lexical Analyzer
4** See Copyright Notice in lua.h
5*/
6
7#ifndef llex_h
8#define llex_h
9
10#include <limits.h>
11
12#include "lobject.h"
13#include "lzio.h"
14
15
16/*
17** Single-char tokens (terminal symbols) are represented by their own
18** numeric code. Other tokens start at the following value.
19*/
20#define FIRST_RESERVED (UCHAR_MAX + 1)
21
22
23#if !defined(LUA_ENV)
24#define LUA_ENV "_ENV"
25#endif
26
27
28/*
29* WARNING: if you change the order of this enumeration,
30* grep "ORDER RESERVED"
31*/
32enum RESERVED {
33 /* terminal symbols denoted by reserved words */
34 TK_AND = FIRST_RESERVED, TK_BREAK,
35 TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,
36 TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
37 TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
38 /* other terminal symbols */
39 TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE,
40 TK_SHL, TK_SHR,
41 TK_DBCOLON, TK_EOS,
42 TK_FLT, TK_INT, TK_NAME, TK_STRING
43};
44
45/* number of reserved words */
46#define NUM_RESERVED (cast_int(TK_WHILE-FIRST_RESERVED + 1))
47
48
49typedef union {
50 lua_Number r;
51 lua_Integer i;
52 TString *ts;
53} SemInfo; /* semantics information */
54
55
56typedef struct Token {
57 int token;
58 SemInfo seminfo;
59} Token;
60
61
62/* state of the lexer plus state of the parser when shared by all
63 functions */
64typedef struct LexState {
65 int current; /* current character (charint) */
66 int linenumber; /* input line counter */
67 int lastline; /* line of last token 'consumed' */
68 Token t; /* current token */
69 Token lookahead; /* look ahead token */
70 struct FuncState *fs; /* current function (parser) */
71 struct lua_State *L;
72 ZIO *z; /* input stream */
73 Mbuffer *buff; /* buffer for tokens */
74 Table *h; /* to avoid collection/reuse strings */
75 struct Dyndata *dyd; /* dynamic structures used by the parser */
76 TString *source; /* current source name */
77 TString *envn; /* environment variable name */
78} LexState;
79
80
81LUAI_FUNC void luaX_init (lua_State *L);
82LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z,
83 TString *source, int firstchar);
84LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l);
85LUAI_FUNC void luaX_next (LexState *ls);
86LUAI_FUNC int luaX_lookahead (LexState *ls);
87LUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s);
88LUAI_FUNC const char *luaX_token2str (LexState *ls, int token);
89
90
91#endif
diff --git a/vendor/lua-5.4.8/src/llimits.h b/vendor/lua-5.4.8/src/llimits.h
new file mode 100644
index 0000000..1c826f7
--- /dev/null
+++ b/vendor/lua-5.4.8/src/llimits.h
@@ -0,0 +1,380 @@
1/*
2** $Id: llimits.h $
3** Limits, basic types, and some other 'installation-dependent' definitions
4** See Copyright Notice in lua.h
5*/
6
7#ifndef llimits_h
8#define llimits_h
9
10
11#include <limits.h>
12#include <stddef.h>
13
14
15#include "lua.h"
16
17
18/*
19** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count
20** the total memory used by Lua (in bytes). Usually, 'size_t' and
21** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines.
22*/
23#if defined(LUAI_MEM) /* { external definitions? */
24typedef LUAI_UMEM lu_mem;
25typedef LUAI_MEM l_mem;
26#elif LUAI_IS32INT /* }{ */
27typedef size_t lu_mem;
28typedef ptrdiff_t l_mem;
29#else /* 16-bit ints */ /* }{ */
30typedef unsigned long lu_mem;
31typedef long l_mem;
32#endif /* } */
33
34
35/* chars used as small naturals (so that 'char' is reserved for characters) */
36typedef unsigned char lu_byte;
37typedef signed char ls_byte;
38
39
40/* maximum value for size_t */
41#define MAX_SIZET ((size_t)(~(size_t)0))
42
43/* maximum size visible for Lua (must be representable in a lua_Integer) */
44#define MAX_SIZE (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \
45 : (size_t)(LUA_MAXINTEGER))
46
47
48#define MAX_LUMEM ((lu_mem)(~(lu_mem)0))
49
50#define MAX_LMEM ((l_mem)(MAX_LUMEM >> 1))
51
52
53#define MAX_INT INT_MAX /* maximum value of an int */
54
55
56/*
57** floor of the log2 of the maximum signed value for integral type 't'.
58** (That is, maximum 'n' such that '2^n' fits in the given signed type.)
59*/
60#define log2maxs(t) (sizeof(t) * 8 - 2)
61
62
63/*
64** test whether an unsigned value is a power of 2 (or zero)
65*/
66#define ispow2(x) (((x) & ((x) - 1)) == 0)
67
68
69/* number of chars of a literal string without the ending \0 */
70#define LL(x) (sizeof(x)/sizeof(char) - 1)
71
72
73/*
74** conversion of pointer to unsigned integer: this is for hashing only;
75** there is no problem if the integer cannot hold the whole pointer
76** value. (In strict ISO C this may cause undefined behavior, but no
77** actual machine seems to bother.)
78*/
79#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \
80 __STDC_VERSION__ >= 199901L
81#include <stdint.h>
82#if defined(UINTPTR_MAX) /* even in C99 this type is optional */
83#define L_P2I uintptr_t
84#else /* no 'intptr'? */
85#define L_P2I uintmax_t /* use the largest available integer */
86#endif
87#else /* C89 option */
88#define L_P2I size_t
89#endif
90
91#define point2uint(p) ((unsigned int)((L_P2I)(p) & UINT_MAX))
92
93
94
95/* types of 'usual argument conversions' for lua_Number and lua_Integer */
96typedef LUAI_UACNUMBER l_uacNumber;
97typedef LUAI_UACINT l_uacInt;
98
99
100/*
101** Internal assertions for in-house debugging
102*/
103#if defined LUAI_ASSERT
104#undef NDEBUG
105#include <assert.h>
106#define lua_assert(c) assert(c)
107#endif
108
109#if defined(lua_assert)
110#define check_exp(c,e) (lua_assert(c), (e))
111/* to avoid problems with conditions too long */
112#define lua_longassert(c) ((c) ? (void)0 : lua_assert(0))
113#else
114#define lua_assert(c) ((void)0)
115#define check_exp(c,e) (e)
116#define lua_longassert(c) ((void)0)
117#endif
118
119/*
120** assertion for checking API calls
121*/
122#if !defined(luai_apicheck)
123#define luai_apicheck(l,e) ((void)l, lua_assert(e))
124#endif
125
126#define api_check(l,e,msg) luai_apicheck(l,(e) && msg)
127
128
129/* macro to avoid warnings about unused variables */
130#if !defined(UNUSED)
131#define UNUSED(x) ((void)(x))
132#endif
133
134
135/* type casts (a macro highlights casts in the code) */
136#define cast(t, exp) ((t)(exp))
137
138#define cast_void(i) cast(void, (i))
139#define cast_voidp(i) cast(void *, (i))
140#define cast_num(i) cast(lua_Number, (i))
141#define cast_int(i) cast(int, (i))
142#define cast_uint(i) cast(unsigned int, (i))
143#define cast_byte(i) cast(lu_byte, (i))
144#define cast_uchar(i) cast(unsigned char, (i))
145#define cast_char(i) cast(char, (i))
146#define cast_charp(i) cast(char *, (i))
147#define cast_sizet(i) cast(size_t, (i))
148
149
150/* cast a signed lua_Integer to lua_Unsigned */
151#if !defined(l_castS2U)
152#define l_castS2U(i) ((lua_Unsigned)(i))
153#endif
154
155/*
156** cast a lua_Unsigned to a signed lua_Integer; this cast is
157** not strict ISO C, but two-complement architectures should
158** work fine.
159*/
160#if !defined(l_castU2S)
161#define l_castU2S(i) ((lua_Integer)(i))
162#endif
163
164
165/*
166** non-return type
167*/
168#if !defined(l_noret)
169
170#if defined(__GNUC__)
171#define l_noret void __attribute__((noreturn))
172#elif defined(_MSC_VER) && _MSC_VER >= 1200
173#define l_noret void __declspec(noreturn)
174#else
175#define l_noret void
176#endif
177
178#endif
179
180
181/*
182** Inline functions
183*/
184#if !defined(LUA_USE_C89)
185#define l_inline inline
186#elif defined(__GNUC__)
187#define l_inline __inline__
188#else
189#define l_inline /* empty */
190#endif
191
192#define l_sinline static l_inline
193
194
195/*
196** type for virtual-machine instructions;
197** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
198*/
199#if LUAI_IS32INT
200typedef unsigned int l_uint32;
201#else
202typedef unsigned long l_uint32;
203#endif
204
205typedef l_uint32 Instruction;
206
207
208
209/*
210** Maximum length for short strings, that is, strings that are
211** internalized. (Cannot be smaller than reserved words or tags for
212** metamethods, as these strings must be internalized;
213** #("function") = 8, #("__newindex") = 10.)
214*/
215#if !defined(LUAI_MAXSHORTLEN)
216#define LUAI_MAXSHORTLEN 40
217#endif
218
219
220/*
221** Initial size for the string table (must be power of 2).
222** The Lua core alone registers ~50 strings (reserved words +
223** metaevent keys + a few others). Libraries would typically add
224** a few dozens more.
225*/
226#if !defined(MINSTRTABSIZE)
227#define MINSTRTABSIZE 128
228#endif
229
230
231/*
232** Size of cache for strings in the API. 'N' is the number of
233** sets (better be a prime) and "M" is the size of each set (M == 1
234** makes a direct cache.)
235*/
236#if !defined(STRCACHE_N)
237#define STRCACHE_N 53
238#define STRCACHE_M 2
239#endif
240
241
242/* minimum size for string buffer */
243#if !defined(LUA_MINBUFFER)
244#define LUA_MINBUFFER 32
245#endif
246
247
248/*
249** Maximum depth for nested C calls, syntactical nested non-terminals,
250** and other features implemented through recursion in C. (Value must
251** fit in a 16-bit unsigned integer. It must also be compatible with
252** the size of the C stack.)
253*/
254#if !defined(LUAI_MAXCCALLS)
255#define LUAI_MAXCCALLS 200
256#endif
257
258
259/*
260** macros that are executed whenever program enters the Lua core
261** ('lua_lock') and leaves the core ('lua_unlock')
262*/
263#if !defined(lua_lock)
264#define lua_lock(L) ((void) 0)
265#define lua_unlock(L) ((void) 0)
266#endif
267
268/*
269** macro executed during Lua functions at points where the
270** function can yield.
271*/
272#if !defined(luai_threadyield)
273#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}
274#endif
275
276
277/*
278** these macros allow user-specific actions when a thread is
279** created/deleted/resumed/yielded.
280*/
281#if !defined(luai_userstateopen)
282#define luai_userstateopen(L) ((void)L)
283#endif
284
285#if !defined(luai_userstateclose)
286#define luai_userstateclose(L) ((void)L)
287#endif
288
289#if !defined(luai_userstatethread)
290#define luai_userstatethread(L,L1) ((void)L)
291#endif
292
293#if !defined(luai_userstatefree)
294#define luai_userstatefree(L,L1) ((void)L)
295#endif
296
297#if !defined(luai_userstateresume)
298#define luai_userstateresume(L,n) ((void)L)
299#endif
300
301#if !defined(luai_userstateyield)
302#define luai_userstateyield(L,n) ((void)L)
303#endif
304
305
306
307/*
308** The luai_num* macros define the primitive operations over numbers.
309*/
310
311/* floor division (defined as 'floor(a/b)') */
312#if !defined(luai_numidiv)
313#define luai_numidiv(L,a,b) ((void)L, l_floor(luai_numdiv(L,a,b)))
314#endif
315
316/* float division */
317#if !defined(luai_numdiv)
318#define luai_numdiv(L,a,b) ((a)/(b))
319#endif
320
321/*
322** modulo: defined as 'a - floor(a/b)*b'; the direct computation
323** using this definition has several problems with rounding errors,
324** so it is better to use 'fmod'. 'fmod' gives the result of
325** 'a - trunc(a/b)*b', and therefore must be corrected when
326** 'trunc(a/b) ~= floor(a/b)'. That happens when the division has a
327** non-integer negative result: non-integer result is equivalent to
328** a non-zero remainder 'm'; negative result is equivalent to 'a' and
329** 'b' with different signs, or 'm' and 'b' with different signs
330** (as the result 'm' of 'fmod' has the same sign of 'a').
331*/
332#if !defined(luai_nummod)
333#define luai_nummod(L,a,b,m) \
334 { (void)L; (m) = l_mathop(fmod)(a,b); \
335 if (((m) > 0) ? (b) < 0 : ((m) < 0 && (b) > 0)) (m) += (b); }
336#endif
337
338/* exponentiation */
339#if !defined(luai_numpow)
340#define luai_numpow(L,a,b) \
341 ((void)L, (b == 2) ? (a)*(a) : l_mathop(pow)(a,b))
342#endif
343
344/* the others are quite standard operations */
345#if !defined(luai_numadd)
346#define luai_numadd(L,a,b) ((a)+(b))
347#define luai_numsub(L,a,b) ((a)-(b))
348#define luai_nummul(L,a,b) ((a)*(b))
349#define luai_numunm(L,a) (-(a))
350#define luai_numeq(a,b) ((a)==(b))
351#define luai_numlt(a,b) ((a)<(b))
352#define luai_numle(a,b) ((a)<=(b))
353#define luai_numgt(a,b) ((a)>(b))
354#define luai_numge(a,b) ((a)>=(b))
355#define luai_numisnan(a) (!luai_numeq((a), (a)))
356#endif
357
358
359
360
361
362/*
363** macro to control inclusion of some hard tests on stack reallocation
364*/
365#if !defined(HARDSTACKTESTS)
366#define condmovestack(L,pre,pos) ((void)0)
367#else
368/* realloc stack keeping its size */
369#define condmovestack(L,pre,pos) \
370 { int sz_ = stacksize(L); pre; luaD_reallocstack((L), sz_, 0); pos; }
371#endif
372
373#if !defined(HARDMEMTESTS)
374#define condchangemem(L,pre,pos) ((void)0)
375#else
376#define condchangemem(L,pre,pos) \
377 { if (gcrunning(G(L))) { pre; luaC_fullgc(L, 0); pos; } }
378#endif
379
380#endif
diff --git a/vendor/lua-5.4.8/src/lmathlib.c b/vendor/lua-5.4.8/src/lmathlib.c
new file mode 100644
index 0000000..4381063
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lmathlib.c
@@ -0,0 +1,781 @@
1/*
2** $Id: lmathlib.c $
3** Standard mathematical library
4** See Copyright Notice in lua.h
5*/
6
7#define lmathlib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <float.h>
14#include <limits.h>
15#include <math.h>
16#include <stdlib.h>
17#include <time.h>
18
19#include "lua.h"
20
21#include "lauxlib.h"
22#include "lualib.h"
23
24
25#undef PI
26#define PI (l_mathop(3.141592653589793238462643383279502884))
27
28
29static int math_abs (lua_State *L) {
30 if (lua_isinteger(L, 1)) {
31 lua_Integer n = lua_tointeger(L, 1);
32 if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n);
33 lua_pushinteger(L, n);
34 }
35 else
36 lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1)));
37 return 1;
38}
39
40static int math_sin (lua_State *L) {
41 lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1)));
42 return 1;
43}
44
45static int math_cos (lua_State *L) {
46 lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1)));
47 return 1;
48}
49
50static int math_tan (lua_State *L) {
51 lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1)));
52 return 1;
53}
54
55static int math_asin (lua_State *L) {
56 lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1)));
57 return 1;
58}
59
60static int math_acos (lua_State *L) {
61 lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1)));
62 return 1;
63}
64
65static int math_atan (lua_State *L) {
66 lua_Number y = luaL_checknumber(L, 1);
67 lua_Number x = luaL_optnumber(L, 2, 1);
68 lua_pushnumber(L, l_mathop(atan2)(y, x));
69 return 1;
70}
71
72
73static int math_toint (lua_State *L) {
74 int valid;
75 lua_Integer n = lua_tointegerx(L, 1, &valid);
76 if (l_likely(valid))
77 lua_pushinteger(L, n);
78 else {
79 luaL_checkany(L, 1);
80 luaL_pushfail(L); /* value is not convertible to integer */
81 }
82 return 1;
83}
84
85
86static void pushnumint (lua_State *L, lua_Number d) {
87 lua_Integer n;
88 if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */
89 lua_pushinteger(L, n); /* result is integer */
90 else
91 lua_pushnumber(L, d); /* result is float */
92}
93
94
95static int math_floor (lua_State *L) {
96 if (lua_isinteger(L, 1))
97 lua_settop(L, 1); /* integer is its own floor */
98 else {
99 lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1));
100 pushnumint(L, d);
101 }
102 return 1;
103}
104
105
106static int math_ceil (lua_State *L) {
107 if (lua_isinteger(L, 1))
108 lua_settop(L, 1); /* integer is its own ceil */
109 else {
110 lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1));
111 pushnumint(L, d);
112 }
113 return 1;
114}
115
116
117static int math_fmod (lua_State *L) {
118 if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) {
119 lua_Integer d = lua_tointeger(L, 2);
120 if ((lua_Unsigned)d + 1u <= 1u) { /* special cases: -1 or 0 */
121 luaL_argcheck(L, d != 0, 2, "zero");
122 lua_pushinteger(L, 0); /* avoid overflow with 0x80000... / -1 */
123 }
124 else
125 lua_pushinteger(L, lua_tointeger(L, 1) % d);
126 }
127 else
128 lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1),
129 luaL_checknumber(L, 2)));
130 return 1;
131}
132
133
134/*
135** next function does not use 'modf', avoiding problems with 'double*'
136** (which is not compatible with 'float*') when lua_Number is not
137** 'double'.
138*/
139static int math_modf (lua_State *L) {
140 if (lua_isinteger(L ,1)) {
141 lua_settop(L, 1); /* number is its own integer part */
142 lua_pushnumber(L, 0); /* no fractional part */
143 }
144 else {
145 lua_Number n = luaL_checknumber(L, 1);
146 /* integer part (rounds toward zero) */
147 lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n);
148 pushnumint(L, ip);
149 /* fractional part (test needed for inf/-inf) */
150 lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip));
151 }
152 return 2;
153}
154
155
156static int math_sqrt (lua_State *L) {
157 lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1)));
158 return 1;
159}
160
161
162static int math_ult (lua_State *L) {
163 lua_Integer a = luaL_checkinteger(L, 1);
164 lua_Integer b = luaL_checkinteger(L, 2);
165 lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b);
166 return 1;
167}
168
169static int math_log (lua_State *L) {
170 lua_Number x = luaL_checknumber(L, 1);
171 lua_Number res;
172 if (lua_isnoneornil(L, 2))
173 res = l_mathop(log)(x);
174 else {
175 lua_Number base = luaL_checknumber(L, 2);
176#if !defined(LUA_USE_C89)
177 if (base == l_mathop(2.0))
178 res = l_mathop(log2)(x);
179 else
180#endif
181 if (base == l_mathop(10.0))
182 res = l_mathop(log10)(x);
183 else
184 res = l_mathop(log)(x)/l_mathop(log)(base);
185 }
186 lua_pushnumber(L, res);
187 return 1;
188}
189
190static int math_exp (lua_State *L) {
191 lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1)));
192 return 1;
193}
194
195static int math_deg (lua_State *L) {
196 lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI));
197 return 1;
198}
199
200static int math_rad (lua_State *L) {
201 lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0)));
202 return 1;
203}
204
205
206static int math_min (lua_State *L) {
207 int n = lua_gettop(L); /* number of arguments */
208 int imin = 1; /* index of current minimum value */
209 int i;
210 luaL_argcheck(L, n >= 1, 1, "value expected");
211 for (i = 2; i <= n; i++) {
212 if (lua_compare(L, i, imin, LUA_OPLT))
213 imin = i;
214 }
215 lua_pushvalue(L, imin);
216 return 1;
217}
218
219
220static int math_max (lua_State *L) {
221 int n = lua_gettop(L); /* number of arguments */
222 int imax = 1; /* index of current maximum value */
223 int i;
224 luaL_argcheck(L, n >= 1, 1, "value expected");
225 for (i = 2; i <= n; i++) {
226 if (lua_compare(L, imax, i, LUA_OPLT))
227 imax = i;
228 }
229 lua_pushvalue(L, imax);
230 return 1;
231}
232
233
234static int math_type (lua_State *L) {
235 if (lua_type(L, 1) == LUA_TNUMBER)
236 lua_pushstring(L, (lua_isinteger(L, 1)) ? "integer" : "float");
237 else {
238 luaL_checkany(L, 1);
239 luaL_pushfail(L);
240 }
241 return 1;
242}
243
244
245
246/*
247** {==================================================================
248** Pseudo-Random Number Generator based on 'xoshiro256**'.
249** ===================================================================
250*/
251
252/*
253** This code uses lots of shifts. ANSI C does not allow shifts greater
254** than or equal to the width of the type being shifted, so some shifts
255** are written in convoluted ways to match that restriction. For
256** preprocessor tests, it assumes a width of 32 bits, so the maximum
257** shift there is 31 bits.
258*/
259
260
261/* number of binary digits in the mantissa of a float */
262#define FIGS l_floatatt(MANT_DIG)
263
264#if FIGS > 64
265/* there are only 64 random bits; use them all */
266#undef FIGS
267#define FIGS 64
268#endif
269
270
271/*
272** LUA_RAND32 forces the use of 32-bit integers in the implementation
273** of the PRN generator (mainly for testing).
274*/
275#if !defined(LUA_RAND32) && !defined(Rand64)
276
277/* try to find an integer type with at least 64 bits */
278
279#if ((ULONG_MAX >> 31) >> 31) >= 3
280
281/* 'long' has at least 64 bits */
282#define Rand64 unsigned long
283#define SRand64 long
284
285#elif !defined(LUA_USE_C89) && defined(LLONG_MAX)
286
287/* there is a 'long long' type (which must have at least 64 bits) */
288#define Rand64 unsigned long long
289#define SRand64 long long
290
291#elif ((LUA_MAXUNSIGNED >> 31) >> 31) >= 3
292
293/* 'lua_Unsigned' has at least 64 bits */
294#define Rand64 lua_Unsigned
295#define SRand64 lua_Integer
296
297#endif
298
299#endif
300
301
302#if defined(Rand64) /* { */
303
304/*
305** Standard implementation, using 64-bit integers.
306** If 'Rand64' has more than 64 bits, the extra bits do not interfere
307** with the 64 initial bits, except in a right shift. Moreover, the
308** final result has to discard the extra bits.
309*/
310
311/* avoid using extra bits when needed */
312#define trim64(x) ((x) & 0xffffffffffffffffu)
313
314
315/* rotate left 'x' by 'n' bits */
316static Rand64 rotl (Rand64 x, int n) {
317 return (x << n) | (trim64(x) >> (64 - n));
318}
319
320static Rand64 nextrand (Rand64 *state) {
321 Rand64 state0 = state[0];
322 Rand64 state1 = state[1];
323 Rand64 state2 = state[2] ^ state0;
324 Rand64 state3 = state[3] ^ state1;
325 Rand64 res = rotl(state1 * 5, 7) * 9;
326 state[0] = state0 ^ state3;
327 state[1] = state1 ^ state2;
328 state[2] = state2 ^ (state1 << 17);
329 state[3] = rotl(state3, 45);
330 return res;
331}
332
333
334/*
335** Convert bits from a random integer into a float in the
336** interval [0,1), getting the higher FIG bits from the
337** random unsigned integer and converting that to a float.
338** Some old Microsoft compilers cannot cast an unsigned long
339** to a floating-point number, so we use a signed long as an
340** intermediary. When lua_Number is float or double, the shift ensures
341** that 'sx' is non negative; in that case, a good compiler will remove
342** the correction.
343*/
344
345/* must throw out the extra (64 - FIGS) bits */
346#define shift64_FIG (64 - FIGS)
347
348/* 2^(-FIGS) == 2^-1 / 2^(FIGS-1) */
349#define scaleFIG (l_mathop(0.5) / ((Rand64)1 << (FIGS - 1)))
350
351static lua_Number I2d (Rand64 x) {
352 SRand64 sx = (SRand64)(trim64(x) >> shift64_FIG);
353 lua_Number res = (lua_Number)(sx) * scaleFIG;
354 if (sx < 0)
355 res += l_mathop(1.0); /* correct the two's complement if negative */
356 lua_assert(0 <= res && res < 1);
357 return res;
358}
359
360/* convert a 'Rand64' to a 'lua_Unsigned' */
361#define I2UInt(x) ((lua_Unsigned)trim64(x))
362
363/* convert a 'lua_Unsigned' to a 'Rand64' */
364#define Int2I(x) ((Rand64)(x))
365
366
367#else /* no 'Rand64' }{ */
368
369/* get an integer with at least 32 bits */
370#if LUAI_IS32INT
371typedef unsigned int lu_int32;
372#else
373typedef unsigned long lu_int32;
374#endif
375
376
377/*
378** Use two 32-bit integers to represent a 64-bit quantity.
379*/
380typedef struct Rand64 {
381 lu_int32 h; /* higher half */
382 lu_int32 l; /* lower half */
383} Rand64;
384
385
386/*
387** If 'lu_int32' has more than 32 bits, the extra bits do not interfere
388** with the 32 initial bits, except in a right shift and comparisons.
389** Moreover, the final result has to discard the extra bits.
390*/
391
392/* avoid using extra bits when needed */
393#define trim32(x) ((x) & 0xffffffffu)
394
395
396/*
397** basic operations on 'Rand64' values
398*/
399
400/* build a new Rand64 value */
401static Rand64 packI (lu_int32 h, lu_int32 l) {
402 Rand64 result;
403 result.h = h;
404 result.l = l;
405 return result;
406}
407
408/* return i << n */
409static Rand64 Ishl (Rand64 i, int n) {
410 lua_assert(n > 0 && n < 32);
411 return packI((i.h << n) | (trim32(i.l) >> (32 - n)), i.l << n);
412}
413
414/* i1 ^= i2 */
415static void Ixor (Rand64 *i1, Rand64 i2) {
416 i1->h ^= i2.h;
417 i1->l ^= i2.l;
418}
419
420/* return i1 + i2 */
421static Rand64 Iadd (Rand64 i1, Rand64 i2) {
422 Rand64 result = packI(i1.h + i2.h, i1.l + i2.l);
423 if (trim32(result.l) < trim32(i1.l)) /* carry? */
424 result.h++;
425 return result;
426}
427
428/* return i * 5 */
429static Rand64 times5 (Rand64 i) {
430 return Iadd(Ishl(i, 2), i); /* i * 5 == (i << 2) + i */
431}
432
433/* return i * 9 */
434static Rand64 times9 (Rand64 i) {
435 return Iadd(Ishl(i, 3), i); /* i * 9 == (i << 3) + i */
436}
437
438/* return 'i' rotated left 'n' bits */
439static Rand64 rotl (Rand64 i, int n) {
440 lua_assert(n > 0 && n < 32);
441 return packI((i.h << n) | (trim32(i.l) >> (32 - n)),
442 (trim32(i.h) >> (32 - n)) | (i.l << n));
443}
444
445/* for offsets larger than 32, rotate right by 64 - offset */
446static Rand64 rotl1 (Rand64 i, int n) {
447 lua_assert(n > 32 && n < 64);
448 n = 64 - n;
449 return packI((trim32(i.h) >> n) | (i.l << (32 - n)),
450 (i.h << (32 - n)) | (trim32(i.l) >> n));
451}
452
453/*
454** implementation of 'xoshiro256**' algorithm on 'Rand64' values
455*/
456static Rand64 nextrand (Rand64 *state) {
457 Rand64 res = times9(rotl(times5(state[1]), 7));
458 Rand64 t = Ishl(state[1], 17);
459 Ixor(&state[2], state[0]);
460 Ixor(&state[3], state[1]);
461 Ixor(&state[1], state[2]);
462 Ixor(&state[0], state[3]);
463 Ixor(&state[2], t);
464 state[3] = rotl1(state[3], 45);
465 return res;
466}
467
468
469/*
470** Converts a 'Rand64' into a float.
471*/
472
473/* an unsigned 1 with proper type */
474#define UONE ((lu_int32)1)
475
476
477#if FIGS <= 32
478
479/* 2^(-FIGS) */
480#define scaleFIG (l_mathop(0.5) / (UONE << (FIGS - 1)))
481
482/*
483** get up to 32 bits from higher half, shifting right to
484** throw out the extra bits.
485*/
486static lua_Number I2d (Rand64 x) {
487 lua_Number h = (lua_Number)(trim32(x.h) >> (32 - FIGS));
488 return h * scaleFIG;
489}
490
491#else /* 32 < FIGS <= 64 */
492
493/* 2^(-FIGS) = 1.0 / 2^30 / 2^3 / 2^(FIGS-33) */
494#define scaleFIG \
495 (l_mathop(1.0) / (UONE << 30) / l_mathop(8.0) / (UONE << (FIGS - 33)))
496
497/*
498** use FIGS - 32 bits from lower half, throwing out the other
499** (32 - (FIGS - 32)) = (64 - FIGS) bits
500*/
501#define shiftLOW (64 - FIGS)
502
503/*
504** higher 32 bits go after those (FIGS - 32) bits: shiftHI = 2^(FIGS - 32)
505*/
506#define shiftHI ((lua_Number)(UONE << (FIGS - 33)) * l_mathop(2.0))
507
508
509static lua_Number I2d (Rand64 x) {
510 lua_Number h = (lua_Number)trim32(x.h) * shiftHI;
511 lua_Number l = (lua_Number)(trim32(x.l) >> shiftLOW);
512 return (h + l) * scaleFIG;
513}
514
515#endif
516
517
518/* convert a 'Rand64' to a 'lua_Unsigned' */
519static lua_Unsigned I2UInt (Rand64 x) {
520 return (((lua_Unsigned)trim32(x.h) << 31) << 1) | (lua_Unsigned)trim32(x.l);
521}
522
523/* convert a 'lua_Unsigned' to a 'Rand64' */
524static Rand64 Int2I (lua_Unsigned n) {
525 return packI((lu_int32)((n >> 31) >> 1), (lu_int32)n);
526}
527
528#endif /* } */
529
530
531/*
532** A state uses four 'Rand64' values.
533*/
534typedef struct {
535 Rand64 s[4];
536} RanState;
537
538
539/*
540** Project the random integer 'ran' into the interval [0, n].
541** Because 'ran' has 2^B possible values, the projection can only be
542** uniform when the size of the interval is a power of 2 (exact
543** division). Otherwise, to get a uniform projection into [0, n], we
544** first compute 'lim', the smallest Mersenne number not smaller than
545** 'n'. We then project 'ran' into the interval [0, lim]. If the result
546** is inside [0, n], we are done. Otherwise, we try with another 'ran',
547** until we have a result inside the interval.
548*/
549static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n,
550 RanState *state) {
551 if ((n & (n + 1)) == 0) /* is 'n + 1' a power of 2? */
552 return ran & n; /* no bias */
553 else {
554 lua_Unsigned lim = n;
555 /* compute the smallest (2^b - 1) not smaller than 'n' */
556 lim |= (lim >> 1);
557 lim |= (lim >> 2);
558 lim |= (lim >> 4);
559 lim |= (lim >> 8);
560 lim |= (lim >> 16);
561#if (LUA_MAXUNSIGNED >> 31) >= 3
562 lim |= (lim >> 32); /* integer type has more than 32 bits */
563#endif
564 lua_assert((lim & (lim + 1)) == 0 /* 'lim + 1' is a power of 2, */
565 && lim >= n /* not smaller than 'n', */
566 && (lim >> 1) < n); /* and it is the smallest one */
567 while ((ran &= lim) > n) /* project 'ran' into [0..lim] */
568 ran = I2UInt(nextrand(state->s)); /* not inside [0..n]? try again */
569 return ran;
570 }
571}
572
573
574static int math_random (lua_State *L) {
575 lua_Integer low, up;
576 lua_Unsigned p;
577 RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));
578 Rand64 rv = nextrand(state->s); /* next pseudo-random value */
579 switch (lua_gettop(L)) { /* check number of arguments */
580 case 0: { /* no arguments */
581 lua_pushnumber(L, I2d(rv)); /* float between 0 and 1 */
582 return 1;
583 }
584 case 1: { /* only upper limit */
585 low = 1;
586 up = luaL_checkinteger(L, 1);
587 if (up == 0) { /* single 0 as argument? */
588 lua_pushinteger(L, I2UInt(rv)); /* full random integer */
589 return 1;
590 }
591 break;
592 }
593 case 2: { /* lower and upper limits */
594 low = luaL_checkinteger(L, 1);
595 up = luaL_checkinteger(L, 2);
596 break;
597 }
598 default: return luaL_error(L, "wrong number of arguments");
599 }
600 /* random integer in the interval [low, up] */
601 luaL_argcheck(L, low <= up, 1, "interval is empty");
602 /* project random integer into the interval [0, up - low] */
603 p = project(I2UInt(rv), (lua_Unsigned)up - (lua_Unsigned)low, state);
604 lua_pushinteger(L, p + (lua_Unsigned)low);
605 return 1;
606}
607
608
609static void setseed (lua_State *L, Rand64 *state,
610 lua_Unsigned n1, lua_Unsigned n2) {
611 int i;
612 state[0] = Int2I(n1);
613 state[1] = Int2I(0xff); /* avoid a zero state */
614 state[2] = Int2I(n2);
615 state[3] = Int2I(0);
616 for (i = 0; i < 16; i++)
617 nextrand(state); /* discard initial values to "spread" seed */
618 lua_pushinteger(L, n1);
619 lua_pushinteger(L, n2);
620}
621
622
623/*
624** Set a "random" seed. To get some randomness, use the current time
625** and the address of 'L' (in case the machine does address space layout
626** randomization).
627*/
628static void randseed (lua_State *L, RanState *state) {
629 lua_Unsigned seed1 = (lua_Unsigned)time(NULL);
630 lua_Unsigned seed2 = (lua_Unsigned)(size_t)L;
631 setseed(L, state->s, seed1, seed2);
632}
633
634
635static int math_randomseed (lua_State *L) {
636 RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));
637 if (lua_isnone(L, 1)) {
638 randseed(L, state);
639 }
640 else {
641 lua_Integer n1 = luaL_checkinteger(L, 1);
642 lua_Integer n2 = luaL_optinteger(L, 2, 0);
643 setseed(L, state->s, n1, n2);
644 }
645 return 2; /* return seeds */
646}
647
648
649static const luaL_Reg randfuncs[] = {
650 {"random", math_random},
651 {"randomseed", math_randomseed},
652 {NULL, NULL}
653};
654
655
656/*
657** Register the random functions and initialize their state.
658*/
659static void setrandfunc (lua_State *L) {
660 RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0);
661 randseed(L, state); /* initialize with a "random" seed */
662 lua_pop(L, 2); /* remove pushed seeds */
663 luaL_setfuncs(L, randfuncs, 1);
664}
665
666/* }================================================================== */
667
668
669/*
670** {==================================================================
671** Deprecated functions (for compatibility only)
672** ===================================================================
673*/
674#if defined(LUA_COMPAT_MATHLIB)
675
676static int math_cosh (lua_State *L) {
677 lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));
678 return 1;
679}
680
681static int math_sinh (lua_State *L) {
682 lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));
683 return 1;
684}
685
686static int math_tanh (lua_State *L) {
687 lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));
688 return 1;
689}
690
691static int math_pow (lua_State *L) {
692 lua_Number x = luaL_checknumber(L, 1);
693 lua_Number y = luaL_checknumber(L, 2);
694 lua_pushnumber(L, l_mathop(pow)(x, y));
695 return 1;
696}
697
698static int math_frexp (lua_State *L) {
699 int e;
700 lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e));
701 lua_pushinteger(L, e);
702 return 2;
703}
704
705static int math_ldexp (lua_State *L) {
706 lua_Number x = luaL_checknumber(L, 1);
707 int ep = (int)luaL_checkinteger(L, 2);
708 lua_pushnumber(L, l_mathop(ldexp)(x, ep));
709 return 1;
710}
711
712static int math_log10 (lua_State *L) {
713 lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1)));
714 return 1;
715}
716
717#endif
718/* }================================================================== */
719
720
721
722static const luaL_Reg mathlib[] = {
723 {"abs", math_abs},
724 {"acos", math_acos},
725 {"asin", math_asin},
726 {"atan", math_atan},
727 {"ceil", math_ceil},
728 {"cos", math_cos},
729 {"deg", math_deg},
730 {"exp", math_exp},
731 {"tointeger", math_toint},
732 {"floor", math_floor},
733 {"fmod", math_fmod},
734 {"ult", math_ult},
735 {"log", math_log},
736 {"max", math_max},
737 {"min", math_min},
738 {"modf", math_modf},
739 {"rad", math_rad},
740 {"sin", math_sin},
741 {"sqrt", math_sqrt},
742 {"tan", math_tan},
743 {"type", math_type},
744#if defined(LUA_COMPAT_MATHLIB)
745 {"atan2", math_atan},
746 {"cosh", math_cosh},
747 {"sinh", math_sinh},
748 {"tanh", math_tanh},
749 {"pow", math_pow},
750 {"frexp", math_frexp},
751 {"ldexp", math_ldexp},
752 {"log10", math_log10},
753#endif
754 /* placeholders */
755 {"random", NULL},
756 {"randomseed", NULL},
757 {"pi", NULL},
758 {"huge", NULL},
759 {"maxinteger", NULL},
760 {"mininteger", NULL},
761 {NULL, NULL}
762};
763
764
765/*
766** Open math library
767*/
768LUAMOD_API int luaopen_math (lua_State *L) {
769 luaL_newlib(L, mathlib);
770 lua_pushnumber(L, PI);
771 lua_setfield(L, -2, "pi");
772 lua_pushnumber(L, (lua_Number)HUGE_VAL);
773 lua_setfield(L, -2, "huge");
774 lua_pushinteger(L, LUA_MAXINTEGER);
775 lua_setfield(L, -2, "maxinteger");
776 lua_pushinteger(L, LUA_MININTEGER);
777 lua_setfield(L, -2, "mininteger");
778 setrandfunc(L);
779 return 1;
780}
781
diff --git a/vendor/lua-5.4.8/src/lmem.c b/vendor/lua-5.4.8/src/lmem.c
new file mode 100644
index 0000000..9800a86
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lmem.c
@@ -0,0 +1,215 @@
1/*
2** $Id: lmem.c $
3** Interface to Memory Manager
4** See Copyright Notice in lua.h
5*/
6
7#define lmem_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <stddef.h>
14
15#include "lua.h"
16
17#include "ldebug.h"
18#include "ldo.h"
19#include "lgc.h"
20#include "lmem.h"
21#include "lobject.h"
22#include "lstate.h"
23
24
25
26/*
27** About the realloc function:
28** void *frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
29** ('osize' is the old size, 'nsize' is the new size)
30**
31** - frealloc(ud, p, x, 0) frees the block 'p' and returns NULL.
32** Particularly, frealloc(ud, NULL, 0, 0) does nothing,
33** which is equivalent to free(NULL) in ISO C.
34**
35** - frealloc(ud, NULL, x, s) creates a new block of size 's'
36** (no matter 'x'). Returns NULL if it cannot create the new block.
37**
38** - otherwise, frealloc(ud, b, x, y) reallocates the block 'b' from
39** size 'x' to size 'y'. Returns NULL if it cannot reallocate the
40** block to the new size.
41*/
42
43
44/*
45** Macro to call the allocation function.
46*/
47#define callfrealloc(g,block,os,ns) ((*g->frealloc)(g->ud, block, os, ns))
48
49
50/*
51** When an allocation fails, it will try again after an emergency
52** collection, except when it cannot run a collection. The GC should
53** not be called while the state is not fully built, as the collector
54** is not yet fully initialized. Also, it should not be called when
55** 'gcstopem' is true, because then the interpreter is in the middle of
56** a collection step.
57*/
58#define cantryagain(g) (completestate(g) && !g->gcstopem)
59
60
61
62
63#if defined(EMERGENCYGCTESTS)
64/*
65** First allocation will fail except when freeing a block (frees never
66** fail) and when it cannot try again; this fail will trigger 'tryagain'
67** and a full GC cycle at every allocation.
68*/
69static void *firsttry (global_State *g, void *block, size_t os, size_t ns) {
70 if (ns > 0 && cantryagain(g))
71 return NULL; /* fail */
72 else /* normal allocation */
73 return callfrealloc(g, block, os, ns);
74}
75#else
76#define firsttry(g,block,os,ns) callfrealloc(g, block, os, ns)
77#endif
78
79
80
81
82
83/*
84** {==================================================================
85** Functions to allocate/deallocate arrays for the Parser
86** ===================================================================
87*/
88
89/*
90** Minimum size for arrays during parsing, to avoid overhead of
91** reallocating to size 1, then 2, and then 4. All these arrays
92** will be reallocated to exact sizes or erased when parsing ends.
93*/
94#define MINSIZEARRAY 4
95
96
97void *luaM_growaux_ (lua_State *L, void *block, int nelems, int *psize,
98 int size_elems, int limit, const char *what) {
99 void *newblock;
100 int size = *psize;
101 if (nelems + 1 <= size) /* does one extra element still fit? */
102 return block; /* nothing to be done */
103 if (size >= limit / 2) { /* cannot double it? */
104 if (l_unlikely(size >= limit)) /* cannot grow even a little? */
105 luaG_runerror(L, "too many %s (limit is %d)", what, limit);
106 size = limit; /* still have at least one free place */
107 }
108 else {
109 size *= 2;
110 if (size < MINSIZEARRAY)
111 size = MINSIZEARRAY; /* minimum size */
112 }
113 lua_assert(nelems + 1 <= size && size <= limit);
114 /* 'limit' ensures that multiplication will not overflow */
115 newblock = luaM_saferealloc_(L, block, cast_sizet(*psize) * size_elems,
116 cast_sizet(size) * size_elems);
117 *psize = size; /* update only when everything else is OK */
118 return newblock;
119}
120
121
122/*
123** In prototypes, the size of the array is also its number of
124** elements (to save memory). So, if it cannot shrink an array
125** to its number of elements, the only option is to raise an
126** error.
127*/
128void *luaM_shrinkvector_ (lua_State *L, void *block, int *size,
129 int final_n, int size_elem) {
130 void *newblock;
131 size_t oldsize = cast_sizet((*size) * size_elem);
132 size_t newsize = cast_sizet(final_n * size_elem);
133 lua_assert(newsize <= oldsize);
134 newblock = luaM_saferealloc_(L, block, oldsize, newsize);
135 *size = final_n;
136 return newblock;
137}
138
139/* }================================================================== */
140
141
142l_noret luaM_toobig (lua_State *L) {
143 luaG_runerror(L, "memory allocation error: block too big");
144}
145
146
147/*
148** Free memory
149*/
150void luaM_free_ (lua_State *L, void *block, size_t osize) {
151 global_State *g = G(L);
152 lua_assert((osize == 0) == (block == NULL));
153 callfrealloc(g, block, osize, 0);
154 g->GCdebt -= osize;
155}
156
157
158/*
159** In case of allocation fail, this function will do an emergency
160** collection to free some memory and then try the allocation again.
161*/
162static void *tryagain (lua_State *L, void *block,
163 size_t osize, size_t nsize) {
164 global_State *g = G(L);
165 if (cantryagain(g)) {
166 luaC_fullgc(L, 1); /* try to free some memory... */
167 return callfrealloc(g, block, osize, nsize); /* try again */
168 }
169 else return NULL; /* cannot run an emergency collection */
170}
171
172
173/*
174** Generic allocation routine.
175*/
176void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
177 void *newblock;
178 global_State *g = G(L);
179 lua_assert((osize == 0) == (block == NULL));
180 newblock = firsttry(g, block, osize, nsize);
181 if (l_unlikely(newblock == NULL && nsize > 0)) {
182 newblock = tryagain(L, block, osize, nsize);
183 if (newblock == NULL) /* still no memory? */
184 return NULL; /* do not update 'GCdebt' */
185 }
186 lua_assert((nsize == 0) == (newblock == NULL));
187 g->GCdebt = (g->GCdebt + nsize) - osize;
188 return newblock;
189}
190
191
192void *luaM_saferealloc_ (lua_State *L, void *block, size_t osize,
193 size_t nsize) {
194 void *newblock = luaM_realloc_(L, block, osize, nsize);
195 if (l_unlikely(newblock == NULL && nsize > 0)) /* allocation failed? */
196 luaM_error(L);
197 return newblock;
198}
199
200
201void *luaM_malloc_ (lua_State *L, size_t size, int tag) {
202 if (size == 0)
203 return NULL; /* that's all */
204 else {
205 global_State *g = G(L);
206 void *newblock = firsttry(g, NULL, tag, size);
207 if (l_unlikely(newblock == NULL)) {
208 newblock = tryagain(L, NULL, tag, size);
209 if (newblock == NULL)
210 luaM_error(L);
211 }
212 g->GCdebt += size;
213 return newblock;
214 }
215}
diff --git a/vendor/lua-5.4.8/src/lmem.h b/vendor/lua-5.4.8/src/lmem.h
new file mode 100644
index 0000000..8c75a44
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lmem.h
@@ -0,0 +1,93 @@
1/*
2** $Id: lmem.h $
3** Interface to Memory Manager
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lmem_h
8#define lmem_h
9
10
11#include <stddef.h>
12
13#include "llimits.h"
14#include "lua.h"
15
16
17#define luaM_error(L) luaD_throw(L, LUA_ERRMEM)
18
19
20/*
21** This macro tests whether it is safe to multiply 'n' by the size of
22** type 't' without overflows. Because 'e' is always constant, it avoids
23** the runtime division MAX_SIZET/(e).
24** (The macro is somewhat complex to avoid warnings: The 'sizeof'
25** comparison avoids a runtime comparison when overflow cannot occur.
26** The compiler should be able to optimize the real test by itself, but
27** when it does it, it may give a warning about "comparison is always
28** false due to limited range of data type"; the +1 tricks the compiler,
29** avoiding this warning but also this optimization.)
30*/
31#define luaM_testsize(n,e) \
32 (sizeof(n) >= sizeof(size_t) && cast_sizet((n)) + 1 > MAX_SIZET/(e))
33
34#define luaM_checksize(L,n,e) \
35 (luaM_testsize(n,e) ? luaM_toobig(L) : cast_void(0))
36
37
38/*
39** Computes the minimum between 'n' and 'MAX_SIZET/sizeof(t)', so that
40** the result is not larger than 'n' and cannot overflow a 'size_t'
41** when multiplied by the size of type 't'. (Assumes that 'n' is an
42** 'int' or 'unsigned int' and that 'int' is not larger than 'size_t'.)
43*/
44#define luaM_limitN(n,t) \
45 ((cast_sizet(n) <= MAX_SIZET/sizeof(t)) ? (n) : \
46 cast_uint((MAX_SIZET/sizeof(t))))
47
48
49/*
50** Arrays of chars do not need any test
51*/
52#define luaM_reallocvchar(L,b,on,n) \
53 cast_charp(luaM_saferealloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char)))
54
55#define luaM_freemem(L, b, s) luaM_free_(L, (b), (s))
56#define luaM_free(L, b) luaM_free_(L, (b), sizeof(*(b)))
57#define luaM_freearray(L, b, n) luaM_free_(L, (b), (n)*sizeof(*(b)))
58
59#define luaM_new(L,t) cast(t*, luaM_malloc_(L, sizeof(t), 0))
60#define luaM_newvector(L,n,t) cast(t*, luaM_malloc_(L, (n)*sizeof(t), 0))
61#define luaM_newvectorchecked(L,n,t) \
62 (luaM_checksize(L,n,sizeof(t)), luaM_newvector(L,n,t))
63
64#define luaM_newobject(L,tag,s) luaM_malloc_(L, (s), tag)
65
66#define luaM_growvector(L,v,nelems,size,t,limit,e) \
67 ((v)=cast(t *, luaM_growaux_(L,v,nelems,&(size),sizeof(t), \
68 luaM_limitN(limit,t),e)))
69
70#define luaM_reallocvector(L, v,oldn,n,t) \
71 (cast(t *, luaM_realloc_(L, v, cast_sizet(oldn) * sizeof(t), \
72 cast_sizet(n) * sizeof(t))))
73
74#define luaM_shrinkvector(L,v,size,fs,t) \
75 ((v)=cast(t *, luaM_shrinkvector_(L, v, &(size), fs, sizeof(t))))
76
77LUAI_FUNC l_noret luaM_toobig (lua_State *L);
78
79/* not to be called directly */
80LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,
81 size_t size);
82LUAI_FUNC void *luaM_saferealloc_ (lua_State *L, void *block, size_t oldsize,
83 size_t size);
84LUAI_FUNC void luaM_free_ (lua_State *L, void *block, size_t osize);
85LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int nelems,
86 int *size, int size_elem, int limit,
87 const char *what);
88LUAI_FUNC void *luaM_shrinkvector_ (lua_State *L, void *block, int *nelem,
89 int final_n, int size_elem);
90LUAI_FUNC void *luaM_malloc_ (lua_State *L, size_t size, int tag);
91
92#endif
93
diff --git a/vendor/lua-5.4.8/src/loadlib.c b/vendor/lua-5.4.8/src/loadlib.c
new file mode 100644
index 0000000..6d289fc
--- /dev/null
+++ b/vendor/lua-5.4.8/src/loadlib.c
@@ -0,0 +1,758 @@
1/*
2** $Id: loadlib.c $
3** Dynamic library loader for Lua
4** See Copyright Notice in lua.h
5**
6** This module contains an implementation of loadlib for Unix systems
7** that have dlfcn, an implementation for Windows, and a stub for other
8** systems.
9*/
10
11#define loadlib_c
12#define LUA_LIB
13
14#include "lprefix.h"
15
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <string.h>
20
21#include "lua.h"
22
23#include "lauxlib.h"
24#include "lualib.h"
25
26
27/*
28** LUA_CSUBSEP is the character that replaces dots in submodule names
29** when searching for a C loader.
30** LUA_LSUBSEP is the character that replaces dots in submodule names
31** when searching for a Lua loader.
32*/
33#if !defined(LUA_CSUBSEP)
34#define LUA_CSUBSEP LUA_DIRSEP
35#endif
36
37#if !defined(LUA_LSUBSEP)
38#define LUA_LSUBSEP LUA_DIRSEP
39#endif
40
41
42/* prefix for open functions in C libraries */
43#define LUA_POF "luaopen_"
44
45/* separator for open functions in C libraries */
46#define LUA_OFSEP "_"
47
48
49/*
50** key for table in the registry that keeps handles
51** for all loaded C libraries
52*/
53static const char *const CLIBS = "_CLIBS";
54
55#define LIB_FAIL "open"
56
57
58#define setprogdir(L) ((void)0)
59
60
61/*
62** Special type equivalent to '(void*)' for functions in gcc
63** (to suppress warnings when converting function pointers)
64*/
65typedef void (*voidf)(void);
66
67
68/*
69** system-dependent functions
70*/
71
72/*
73** unload library 'lib'
74*/
75static void lsys_unloadlib (void *lib);
76
77/*
78** load C library in file 'path'. If 'seeglb', load with all names in
79** the library global.
80** Returns the library; in case of error, returns NULL plus an
81** error string in the stack.
82*/
83static void *lsys_load (lua_State *L, const char *path, int seeglb);
84
85/*
86** Try to find a function named 'sym' in library 'lib'.
87** Returns the function; in case of error, returns NULL plus an
88** error string in the stack.
89*/
90static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym);
91
92
93
94
95#if defined(LUA_USE_DLOPEN) /* { */
96/*
97** {========================================================================
98** This is an implementation of loadlib based on the dlfcn interface.
99** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
100** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
101** as an emulation layer on top of native functions.
102** =========================================================================
103*/
104
105#include <dlfcn.h>
106
107/*
108** Macro to convert pointer-to-void* to pointer-to-function. This cast
109** is undefined according to ISO C, but POSIX assumes that it works.
110** (The '__extension__' in gnu compilers is only to avoid warnings.)
111*/
112#if defined(__GNUC__)
113#define cast_func(p) (__extension__ (lua_CFunction)(p))
114#else
115#define cast_func(p) ((lua_CFunction)(p))
116#endif
117
118
119static void lsys_unloadlib (void *lib) {
120 dlclose(lib);
121}
122
123
124static void *lsys_load (lua_State *L, const char *path, int seeglb) {
125 void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
126 if (l_unlikely(lib == NULL))
127 lua_pushstring(L, dlerror());
128 return lib;
129}
130
131
132static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
133 lua_CFunction f = cast_func(dlsym(lib, sym));
134 if (l_unlikely(f == NULL))
135 lua_pushstring(L, dlerror());
136 return f;
137}
138
139/* }====================================================== */
140
141
142
143#elif defined(LUA_DL_DLL) /* }{ */
144/*
145** {======================================================================
146** This is an implementation of loadlib for Windows using native functions.
147** =======================================================================
148*/
149
150#include <windows.h>
151
152
153/*
154** optional flags for LoadLibraryEx
155*/
156#if !defined(LUA_LLE_FLAGS)
157#define LUA_LLE_FLAGS 0
158#endif
159
160
161#undef setprogdir
162
163
164/*
165** Replace in the path (on the top of the stack) any occurrence
166** of LUA_EXEC_DIR with the executable's path.
167*/
168static void setprogdir (lua_State *L) {
169 char buff[MAX_PATH + 1];
170 char *lb;
171 DWORD nsize = sizeof(buff)/sizeof(char);
172 DWORD n = GetModuleFileNameA(NULL, buff, nsize); /* get exec. name */
173 if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
174 luaL_error(L, "unable to get ModuleFileName");
175 else {
176 *lb = '\0'; /* cut name on the last '\\' to get the path */
177 luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff);
178 lua_remove(L, -2); /* remove original string */
179 }
180}
181
182
183
184
185static void pusherror (lua_State *L) {
186 int error = GetLastError();
187 char buffer[128];
188 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
189 NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL))
190 lua_pushstring(L, buffer);
191 else
192 lua_pushfstring(L, "system error %d\n", error);
193}
194
195static void lsys_unloadlib (void *lib) {
196 FreeLibrary((HMODULE)lib);
197}
198
199
200static void *lsys_load (lua_State *L, const char *path, int seeglb) {
201 HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);
202 (void)(seeglb); /* not used: symbols are 'global' by default */
203 if (lib == NULL) pusherror(L);
204 return lib;
205}
206
207
208static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
209 lua_CFunction f = (lua_CFunction)(voidf)GetProcAddress((HMODULE)lib, sym);
210 if (f == NULL) pusherror(L);
211 return f;
212}
213
214/* }====================================================== */
215
216
217#else /* }{ */
218/*
219** {======================================================
220** Fallback for other systems
221** =======================================================
222*/
223
224#undef LIB_FAIL
225#define LIB_FAIL "absent"
226
227
228#define DLMSG "dynamic libraries not enabled; check your Lua installation"
229
230
231static void lsys_unloadlib (void *lib) {
232 (void)(lib); /* not used */
233}
234
235
236static void *lsys_load (lua_State *L, const char *path, int seeglb) {
237 (void)(path); (void)(seeglb); /* not used */
238 lua_pushliteral(L, DLMSG);
239 return NULL;
240}
241
242
243static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
244 (void)(lib); (void)(sym); /* not used */
245 lua_pushliteral(L, DLMSG);
246 return NULL;
247}
248
249/* }====================================================== */
250#endif /* } */
251
252
253/*
254** {==================================================================
255** Set Paths
256** ===================================================================
257*/
258
259/*
260** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
261** variables that Lua check to set its paths.
262*/
263#if !defined(LUA_PATH_VAR)
264#define LUA_PATH_VAR "LUA_PATH"
265#endif
266
267#if !defined(LUA_CPATH_VAR)
268#define LUA_CPATH_VAR "LUA_CPATH"
269#endif
270
271
272
273/*
274** return registry.LUA_NOENV as a boolean
275*/
276static int noenv (lua_State *L) {
277 int b;
278 lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
279 b = lua_toboolean(L, -1);
280 lua_pop(L, 1); /* remove value */
281 return b;
282}
283
284
285/*
286** Set a path
287*/
288static void setpath (lua_State *L, const char *fieldname,
289 const char *envname,
290 const char *dft) {
291 const char *dftmark;
292 const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX);
293 const char *path = getenv(nver); /* try versioned name */
294 if (path == NULL) /* no versioned environment variable? */
295 path = getenv(envname); /* try unversioned name */
296 if (path == NULL || noenv(L)) /* no environment variable? */
297 lua_pushstring(L, dft); /* use default */
298 else if ((dftmark = strstr(path, LUA_PATH_SEP LUA_PATH_SEP)) == NULL)
299 lua_pushstring(L, path); /* nothing to change */
300 else { /* path contains a ";;": insert default path in its place */
301 size_t len = strlen(path);
302 luaL_Buffer b;
303 luaL_buffinit(L, &b);
304 if (path < dftmark) { /* is there a prefix before ';;'? */
305 luaL_addlstring(&b, path, dftmark - path); /* add it */
306 luaL_addchar(&b, *LUA_PATH_SEP);
307 }
308 luaL_addstring(&b, dft); /* add default */
309 if (dftmark < path + len - 2) { /* is there a suffix after ';;'? */
310 luaL_addchar(&b, *LUA_PATH_SEP);
311 luaL_addlstring(&b, dftmark + 2, (path + len - 2) - dftmark);
312 }
313 luaL_pushresult(&b);
314 }
315 setprogdir(L);
316 lua_setfield(L, -3, fieldname); /* package[fieldname] = path value */
317 lua_pop(L, 1); /* pop versioned variable name ('nver') */
318}
319
320/* }================================================================== */
321
322
323/*
324** return registry.CLIBS[path]
325*/
326static void *checkclib (lua_State *L, const char *path) {
327 void *plib;
328 lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
329 lua_getfield(L, -1, path);
330 plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */
331 lua_pop(L, 2); /* pop CLIBS table and 'plib' */
332 return plib;
333}
334
335
336/*
337** registry.CLIBS[path] = plib -- for queries
338** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries
339*/
340static void addtoclib (lua_State *L, const char *path, void *plib) {
341 lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
342 lua_pushlightuserdata(L, plib);
343 lua_pushvalue(L, -1);
344 lua_setfield(L, -3, path); /* CLIBS[path] = plib */
345 lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */
346 lua_pop(L, 1); /* pop CLIBS table */
347}
348
349
350/*
351** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib
352** handles in list CLIBS
353*/
354static int gctm (lua_State *L) {
355 lua_Integer n = luaL_len(L, 1);
356 for (; n >= 1; n--) { /* for each handle, in reverse order */
357 lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */
358 lsys_unloadlib(lua_touserdata(L, -1));
359 lua_pop(L, 1); /* pop handle */
360 }
361 return 0;
362}
363
364
365
366/* error codes for 'lookforfunc' */
367#define ERRLIB 1
368#define ERRFUNC 2
369
370/*
371** Look for a C function named 'sym' in a dynamically loaded library
372** 'path'.
373** First, check whether the library is already loaded; if not, try
374** to load it.
375** Then, if 'sym' is '*', return true (as library has been loaded).
376** Otherwise, look for symbol 'sym' in the library and push a
377** C function with that symbol.
378** Return 0 and 'true' or a function in the stack; in case of
379** errors, return an error code and an error message in the stack.
380*/
381static int lookforfunc (lua_State *L, const char *path, const char *sym) {
382 void *reg = checkclib(L, path); /* check loaded C libraries */
383 if (reg == NULL) { /* must load library? */
384 reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */
385 if (reg == NULL) return ERRLIB; /* unable to load library */
386 addtoclib(L, path, reg);
387 }
388 if (*sym == '*') { /* loading only library (no function)? */
389 lua_pushboolean(L, 1); /* return 'true' */
390 return 0; /* no errors */
391 }
392 else {
393 lua_CFunction f = lsys_sym(L, reg, sym);
394 if (f == NULL)
395 return ERRFUNC; /* unable to find function */
396 lua_pushcfunction(L, f); /* else create new function */
397 return 0; /* no errors */
398 }
399}
400
401
402static int ll_loadlib (lua_State *L) {
403 const char *path = luaL_checkstring(L, 1);
404 const char *init = luaL_checkstring(L, 2);
405 int stat = lookforfunc(L, path, init);
406 if (l_likely(stat == 0)) /* no errors? */
407 return 1; /* return the loaded function */
408 else { /* error; error message is on stack top */
409 luaL_pushfail(L);
410 lua_insert(L, -2);
411 lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
412 return 3; /* return fail, error message, and where */
413 }
414}
415
416
417
418/*
419** {======================================================
420** 'require' function
421** =======================================================
422*/
423
424
425static int readable (const char *filename) {
426 FILE *f = fopen(filename, "r"); /* try to open file */
427 if (f == NULL) return 0; /* open failed */
428 fclose(f);
429 return 1;
430}
431
432
433/*
434** Get the next name in '*path' = 'name1;name2;name3;...', changing
435** the ending ';' to '\0' to create a zero-terminated string. Return
436** NULL when list ends.
437*/
438static const char *getnextfilename (char **path, char *end) {
439 char *sep;
440 char *name = *path;
441 if (name == end)
442 return NULL; /* no more names */
443 else if (*name == '\0') { /* from previous iteration? */
444 *name = *LUA_PATH_SEP; /* restore separator */
445 name++; /* skip it */
446 }
447 sep = strchr(name, *LUA_PATH_SEP); /* find next separator */
448 if (sep == NULL) /* separator not found? */
449 sep = end; /* name goes until the end */
450 *sep = '\0'; /* finish file name */
451 *path = sep; /* will start next search from here */
452 return name;
453}
454
455
456/*
457** Given a path such as ";blabla.so;blublu.so", pushes the string
458**
459** no file 'blabla.so'
460** no file 'blublu.so'
461*/
462static void pusherrornotfound (lua_State *L, const char *path) {
463 luaL_Buffer b;
464 luaL_buffinit(L, &b);
465 luaL_addstring(&b, "no file '");
466 luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '");
467 luaL_addstring(&b, "'");
468 luaL_pushresult(&b);
469}
470
471
472static const char *searchpath (lua_State *L, const char *name,
473 const char *path,
474 const char *sep,
475 const char *dirsep) {
476 luaL_Buffer buff;
477 char *pathname; /* path with name inserted */
478 char *endpathname; /* its end */
479 const char *filename;
480 /* separator is non-empty and appears in 'name'? */
481 if (*sep != '\0' && strchr(name, *sep) != NULL)
482 name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
483 luaL_buffinit(L, &buff);
484 /* add path to the buffer, replacing marks ('?') with the file name */
485 luaL_addgsub(&buff, path, LUA_PATH_MARK, name);
486 luaL_addchar(&buff, '\0');
487 pathname = luaL_buffaddr(&buff); /* writable list of file names */
488 endpathname = pathname + luaL_bufflen(&buff) - 1;
489 while ((filename = getnextfilename(&pathname, endpathname)) != NULL) {
490 if (readable(filename)) /* does file exist and is readable? */
491 return lua_pushstring(L, filename); /* save and return name */
492 }
493 luaL_pushresult(&buff); /* push path to create error message */
494 pusherrornotfound(L, lua_tostring(L, -1)); /* create error message */
495 return NULL; /* not found */
496}
497
498
499static int ll_searchpath (lua_State *L) {
500 const char *f = searchpath(L, luaL_checkstring(L, 1),
501 luaL_checkstring(L, 2),
502 luaL_optstring(L, 3, "."),
503 luaL_optstring(L, 4, LUA_DIRSEP));
504 if (f != NULL) return 1;
505 else { /* error message is on top of the stack */
506 luaL_pushfail(L);
507 lua_insert(L, -2);
508 return 2; /* return fail + error message */
509 }
510}
511
512
513static const char *findfile (lua_State *L, const char *name,
514 const char *pname,
515 const char *dirsep) {
516 const char *path;
517 lua_getfield(L, lua_upvalueindex(1), pname);
518 path = lua_tostring(L, -1);
519 if (l_unlikely(path == NULL))
520 luaL_error(L, "'package.%s' must be a string", pname);
521 return searchpath(L, name, path, ".", dirsep);
522}
523
524
525static int checkload (lua_State *L, int stat, const char *filename) {
526 if (l_likely(stat)) { /* module loaded successfully? */
527 lua_pushstring(L, filename); /* will be 2nd argument to module */
528 return 2; /* return open function and file name */
529 }
530 else
531 return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s",
532 lua_tostring(L, 1), filename, lua_tostring(L, -1));
533}
534
535
536static int searcher_Lua (lua_State *L) {
537 const char *filename;
538 const char *name = luaL_checkstring(L, 1);
539 filename = findfile(L, name, "path", LUA_LSUBSEP);
540 if (filename == NULL) return 1; /* module not found in this path */
541 return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
542}
543
544
545/*
546** Try to find a load function for module 'modname' at file 'filename'.
547** First, change '.' to '_' in 'modname'; then, if 'modname' has
548** the form X-Y (that is, it has an "ignore mark"), build a function
549** name "luaopen_X" and look for it. (For compatibility, if that
550** fails, it also tries "luaopen_Y".) If there is no ignore mark,
551** look for a function named "luaopen_modname".
552*/
553static int loadfunc (lua_State *L, const char *filename, const char *modname) {
554 const char *openfunc;
555 const char *mark;
556 modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
557 mark = strchr(modname, *LUA_IGMARK);
558 if (mark) {
559 int stat;
560 openfunc = lua_pushlstring(L, modname, mark - modname);
561 openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
562 stat = lookforfunc(L, filename, openfunc);
563 if (stat != ERRFUNC) return stat;
564 modname = mark + 1; /* else go ahead and try old-style name */
565 }
566 openfunc = lua_pushfstring(L, LUA_POF"%s", modname);
567 return lookforfunc(L, filename, openfunc);
568}
569
570
571static int searcher_C (lua_State *L) {
572 const char *name = luaL_checkstring(L, 1);
573 const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP);
574 if (filename == NULL) return 1; /* module not found in this path */
575 return checkload(L, (loadfunc(L, filename, name) == 0), filename);
576}
577
578
579static int searcher_Croot (lua_State *L) {
580 const char *filename;
581 const char *name = luaL_checkstring(L, 1);
582 const char *p = strchr(name, '.');
583 int stat;
584 if (p == NULL) return 0; /* is root */
585 lua_pushlstring(L, name, p - name);
586 filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP);
587 if (filename == NULL) return 1; /* root not found */
588 if ((stat = loadfunc(L, filename, name)) != 0) {
589 if (stat != ERRFUNC)
590 return checkload(L, 0, filename); /* real error */
591 else { /* open function not found */
592 lua_pushfstring(L, "no module '%s' in file '%s'", name, filename);
593 return 1;
594 }
595 }
596 lua_pushstring(L, filename); /* will be 2nd argument to module */
597 return 2;
598}
599
600
601static int searcher_preload (lua_State *L) {
602 const char *name = luaL_checkstring(L, 1);
603 lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
604 if (lua_getfield(L, -1, name) == LUA_TNIL) { /* not found? */
605 lua_pushfstring(L, "no field package.preload['%s']", name);
606 return 1;
607 }
608 else {
609 lua_pushliteral(L, ":preload:");
610 return 2;
611 }
612}
613
614
615static void findloader (lua_State *L, const char *name) {
616 int i;
617 luaL_Buffer msg; /* to build error message */
618 /* push 'package.searchers' to index 3 in the stack */
619 if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers")
620 != LUA_TTABLE))
621 luaL_error(L, "'package.searchers' must be a table");
622 luaL_buffinit(L, &msg);
623 /* iterate over available searchers to find a loader */
624 for (i = 1; ; i++) {
625 luaL_addstring(&msg, "\n\t"); /* error-message prefix */
626 if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) { /* no more searchers? */
627 lua_pop(L, 1); /* remove nil */
628 luaL_buffsub(&msg, 2); /* remove prefix */
629 luaL_pushresult(&msg); /* create error message */
630 luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
631 }
632 lua_pushstring(L, name);
633 lua_call(L, 1, 2); /* call it */
634 if (lua_isfunction(L, -2)) /* did it find a loader? */
635 return; /* module loader found */
636 else if (lua_isstring(L, -2)) { /* searcher returned error message? */
637 lua_pop(L, 1); /* remove extra return */
638 luaL_addvalue(&msg); /* concatenate error message */
639 }
640 else { /* no error message */
641 lua_pop(L, 2); /* remove both returns */
642 luaL_buffsub(&msg, 2); /* remove prefix */
643 }
644 }
645}
646
647
648static int ll_require (lua_State *L) {
649 const char *name = luaL_checkstring(L, 1);
650 lua_settop(L, 1); /* LOADED table will be at index 2 */
651 lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
652 lua_getfield(L, 2, name); /* LOADED[name] */
653 if (lua_toboolean(L, -1)) /* is it there? */
654 return 1; /* package is already loaded */
655 /* else must load package */
656 lua_pop(L, 1); /* remove 'getfield' result */
657 findloader(L, name);
658 lua_rotate(L, -2, 1); /* function <-> loader data */
659 lua_pushvalue(L, 1); /* name is 1st argument to module loader */
660 lua_pushvalue(L, -3); /* loader data is 2nd argument */
661 /* stack: ...; loader data; loader function; mod. name; loader data */
662 lua_call(L, 2, 1); /* run loader to load module */
663 /* stack: ...; loader data; result from loader */
664 if (!lua_isnil(L, -1)) /* non-nil return? */
665 lua_setfield(L, 2, name); /* LOADED[name] = returned value */
666 else
667 lua_pop(L, 1); /* pop nil */
668 if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */
669 lua_pushboolean(L, 1); /* use true as result */
670 lua_copy(L, -1, -2); /* replace loader result */
671 lua_setfield(L, 2, name); /* LOADED[name] = true */
672 }
673 lua_rotate(L, -2, 1); /* loader data <-> module result */
674 return 2; /* return module result and loader data */
675}
676
677/* }====================================================== */
678
679
680
681
682static const luaL_Reg pk_funcs[] = {
683 {"loadlib", ll_loadlib},
684 {"searchpath", ll_searchpath},
685 /* placeholders */
686 {"preload", NULL},
687 {"cpath", NULL},
688 {"path", NULL},
689 {"searchers", NULL},
690 {"loaded", NULL},
691 {NULL, NULL}
692};
693
694
695static const luaL_Reg ll_funcs[] = {
696 {"require", ll_require},
697 {NULL, NULL}
698};
699
700
701static void createsearcherstable (lua_State *L) {
702 static const lua_CFunction searchers[] = {
703 searcher_preload,
704 searcher_Lua,
705 searcher_C,
706 searcher_Croot,
707 NULL
708 };
709 int i;
710 /* create 'searchers' table */
711 lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);
712 /* fill it with predefined searchers */
713 for (i=0; searchers[i] != NULL; i++) {
714 lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */
715 lua_pushcclosure(L, searchers[i], 1);
716 lua_rawseti(L, -2, i+1);
717 }
718 lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
719}
720
721
722/*
723** create table CLIBS to keep track of loaded C libraries,
724** setting a finalizer to close all libraries when closing state.
725*/
726static void createclibstable (lua_State *L) {
727 luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* create CLIBS table */
728 lua_createtable(L, 0, 1); /* create metatable for CLIBS */
729 lua_pushcfunction(L, gctm);
730 lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */
731 lua_setmetatable(L, -2);
732}
733
734
735LUAMOD_API int luaopen_package (lua_State *L) {
736 createclibstable(L);
737 luaL_newlib(L, pk_funcs); /* create 'package' table */
738 createsearcherstable(L);
739 /* set paths */
740 setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT);
741 setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
742 /* store config information */
743 lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
744 LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
745 lua_setfield(L, -2, "config");
746 /* set field 'loaded' */
747 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
748 lua_setfield(L, -2, "loaded");
749 /* set field 'preload' */
750 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
751 lua_setfield(L, -2, "preload");
752 lua_pushglobaltable(L);
753 lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */
754 luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */
755 lua_pop(L, 1); /* pop global table */
756 return 1; /* return 'package' table */
757}
758
diff --git a/vendor/lua-5.4.8/src/lobject.c b/vendor/lua-5.4.8/src/lobject.c
new file mode 100644
index 0000000..9cfa522
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lobject.c
@@ -0,0 +1,602 @@
1/*
2** $Id: lobject.c $
3** Some generic functions over Lua objects
4** See Copyright Notice in lua.h
5*/
6
7#define lobject_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <locale.h>
14#include <math.h>
15#include <stdarg.h>
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19
20#include "lua.h"
21
22#include "lctype.h"
23#include "ldebug.h"
24#include "ldo.h"
25#include "lmem.h"
26#include "lobject.h"
27#include "lstate.h"
28#include "lstring.h"
29#include "lvm.h"
30
31
32/*
33** Computes ceil(log2(x))
34*/
35int luaO_ceillog2 (unsigned int x) {
36 static const lu_byte log_2[256] = { /* log_2[i] = ceil(log2(i - 1)) */
37 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
38 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
39 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
40 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
41 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
42 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
43 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
44 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
45 };
46 int l = 0;
47 x--;
48 while (x >= 256) { l += 8; x >>= 8; }
49 return l + log_2[x];
50}
51
52
53static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
54 lua_Integer v2) {
55 switch (op) {
56 case LUA_OPADD: return intop(+, v1, v2);
57 case LUA_OPSUB:return intop(-, v1, v2);
58 case LUA_OPMUL:return intop(*, v1, v2);
59 case LUA_OPMOD: return luaV_mod(L, v1, v2);
60 case LUA_OPIDIV: return luaV_idiv(L, v1, v2);
61 case LUA_OPBAND: return intop(&, v1, v2);
62 case LUA_OPBOR: return intop(|, v1, v2);
63 case LUA_OPBXOR: return intop(^, v1, v2);
64 case LUA_OPSHL: return luaV_shiftl(v1, v2);
65 case LUA_OPSHR: return luaV_shiftr(v1, v2);
66 case LUA_OPUNM: return intop(-, 0, v1);
67 case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
68 default: lua_assert(0); return 0;
69 }
70}
71
72
73static lua_Number numarith (lua_State *L, int op, lua_Number v1,
74 lua_Number v2) {
75 switch (op) {
76 case LUA_OPADD: return luai_numadd(L, v1, v2);
77 case LUA_OPSUB: return luai_numsub(L, v1, v2);
78 case LUA_OPMUL: return luai_nummul(L, v1, v2);
79 case LUA_OPDIV: return luai_numdiv(L, v1, v2);
80 case LUA_OPPOW: return luai_numpow(L, v1, v2);
81 case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
82 case LUA_OPUNM: return luai_numunm(L, v1);
83 case LUA_OPMOD: return luaV_modf(L, v1, v2);
84 default: lua_assert(0); return 0;
85 }
86}
87
88
89int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2,
90 TValue *res) {
91 switch (op) {
92 case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
93 case LUA_OPSHL: case LUA_OPSHR:
94 case LUA_OPBNOT: { /* operate only on integers */
95 lua_Integer i1; lua_Integer i2;
96 if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) {
97 setivalue(res, intarith(L, op, i1, i2));
98 return 1;
99 }
100 else return 0; /* fail */
101 }
102 case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */
103 lua_Number n1; lua_Number n2;
104 if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
105 setfltvalue(res, numarith(L, op, n1, n2));
106 return 1;
107 }
108 else return 0; /* fail */
109 }
110 default: { /* other operations */
111 lua_Number n1; lua_Number n2;
112 if (ttisinteger(p1) && ttisinteger(p2)) {
113 setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
114 return 1;
115 }
116 else if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
117 setfltvalue(res, numarith(L, op, n1, n2));
118 return 1;
119 }
120 else return 0; /* fail */
121 }
122 }
123}
124
125
126void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
127 StkId res) {
128 if (!luaO_rawarith(L, op, p1, p2, s2v(res))) {
129 /* could not perform raw operation; try metamethod */
130 luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));
131 }
132}
133
134
135int luaO_hexavalue (int c) {
136 if (lisdigit(c)) return c - '0';
137 else return (ltolower(c) - 'a') + 10;
138}
139
140
141static int isneg (const char **s) {
142 if (**s == '-') { (*s)++; return 1; }
143 else if (**s == '+') (*s)++;
144 return 0;
145}
146
147
148
149/*
150** {==================================================================
151** Lua's implementation for 'lua_strx2number'
152** ===================================================================
153*/
154
155#if !defined(lua_strx2number)
156
157/* maximum number of significant digits to read (to avoid overflows
158 even with single floats) */
159#define MAXSIGDIG 30
160
161/*
162** convert a hexadecimal numeric string to a number, following
163** C99 specification for 'strtod'
164*/
165static lua_Number lua_strx2number (const char *s, char **endptr) {
166 int dot = lua_getlocaledecpoint();
167 lua_Number r = l_mathop(0.0); /* result (accumulator) */
168 int sigdig = 0; /* number of significant digits */
169 int nosigdig = 0; /* number of non-significant digits */
170 int e = 0; /* exponent correction */
171 int neg; /* 1 if number is negative */
172 int hasdot = 0; /* true after seen a dot */
173 *endptr = cast_charp(s); /* nothing is valid yet */
174 while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
175 neg = isneg(&s); /* check sign */
176 if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
177 return l_mathop(0.0); /* invalid format (no '0x') */
178 for (s += 2; ; s++) { /* skip '0x' and read numeral */
179 if (*s == dot) {
180 if (hasdot) break; /* second dot? stop loop */
181 else hasdot = 1;
182 }
183 else if (lisxdigit(cast_uchar(*s))) {
184 if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */
185 nosigdig++;
186 else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */
187 r = (r * l_mathop(16.0)) + luaO_hexavalue(*s);
188 else e++; /* too many digits; ignore, but still count for exponent */
189 if (hasdot) e--; /* decimal digit? correct exponent */
190 }
191 else break; /* neither a dot nor a digit */
192 }
193 if (nosigdig + sigdig == 0) /* no digits? */
194 return l_mathop(0.0); /* invalid format */
195 *endptr = cast_charp(s); /* valid up to here */
196 e *= 4; /* each digit multiplies/divides value by 2^4 */
197 if (*s == 'p' || *s == 'P') { /* exponent part? */
198 int exp1 = 0; /* exponent value */
199 int neg1; /* exponent sign */
200 s++; /* skip 'p' */
201 neg1 = isneg(&s); /* sign */
202 if (!lisdigit(cast_uchar(*s)))
203 return l_mathop(0.0); /* invalid; must have at least one digit */
204 while (lisdigit(cast_uchar(*s))) /* read exponent */
205 exp1 = exp1 * 10 + *(s++) - '0';
206 if (neg1) exp1 = -exp1;
207 e += exp1;
208 *endptr = cast_charp(s); /* valid up to here */
209 }
210 if (neg) r = -r;
211 return l_mathop(ldexp)(r, e);
212}
213
214#endif
215/* }====================================================== */
216
217
218/* maximum length of a numeral to be converted to a number */
219#if !defined (L_MAXLENNUM)
220#define L_MAXLENNUM 200
221#endif
222
223/*
224** Convert string 's' to a Lua number (put in 'result'). Return NULL on
225** fail or the address of the ending '\0' on success. ('mode' == 'x')
226** means a hexadecimal numeral.
227*/
228static const char *l_str2dloc (const char *s, lua_Number *result, int mode) {
229 char *endptr;
230 *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */
231 : lua_str2number(s, &endptr);
232 if (endptr == s) return NULL; /* nothing recognized? */
233 while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */
234 return (*endptr == '\0') ? endptr : NULL; /* OK iff no trailing chars */
235}
236
237
238/*
239** Convert string 's' to a Lua number (put in 'result') handling the
240** current locale.
241** This function accepts both the current locale or a dot as the radix
242** mark. If the conversion fails, it may mean number has a dot but
243** locale accepts something else. In that case, the code copies 's'
244** to a buffer (because 's' is read-only), changes the dot to the
245** current locale radix mark, and tries to convert again.
246** The variable 'mode' checks for special characters in the string:
247** - 'n' means 'inf' or 'nan' (which should be rejected)
248** - 'x' means a hexadecimal numeral
249** - '.' just optimizes the search for the common case (no special chars)
250*/
251static const char *l_str2d (const char *s, lua_Number *result) {
252 const char *endptr;
253 const char *pmode = strpbrk(s, ".xXnN"); /* look for special chars */
254 int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
255 if (mode == 'n') /* reject 'inf' and 'nan' */
256 return NULL;
257 endptr = l_str2dloc(s, result, mode); /* try to convert */
258 if (endptr == NULL) { /* failed? may be a different locale */
259 char buff[L_MAXLENNUM + 1];
260 const char *pdot = strchr(s, '.');
261 if (pdot == NULL || strlen(s) > L_MAXLENNUM)
262 return NULL; /* string too long or no dot; fail */
263 strcpy(buff, s); /* copy string to buffer */
264 buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */
265 endptr = l_str2dloc(buff, result, mode); /* try again */
266 if (endptr != NULL)
267 endptr = s + (endptr - buff); /* make relative to 's' */
268 }
269 return endptr;
270}
271
272
273#define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10)
274#define MAXLASTD cast_int(LUA_MAXINTEGER % 10)
275
276static const char *l_str2int (const char *s, lua_Integer *result) {
277 lua_Unsigned a = 0;
278 int empty = 1;
279 int neg;
280 while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
281 neg = isneg(&s);
282 if (s[0] == '0' &&
283 (s[1] == 'x' || s[1] == 'X')) { /* hex? */
284 s += 2; /* skip '0x' */
285 for (; lisxdigit(cast_uchar(*s)); s++) {
286 a = a * 16 + luaO_hexavalue(*s);
287 empty = 0;
288 }
289 }
290 else { /* decimal */
291 for (; lisdigit(cast_uchar(*s)); s++) {
292 int d = *s - '0';
293 if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */
294 return NULL; /* do not accept it (as integer) */
295 a = a * 10 + d;
296 empty = 0;
297 }
298 }
299 while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */
300 if (empty || *s != '\0') return NULL; /* something wrong in the numeral */
301 else {
302 *result = l_castU2S((neg) ? 0u - a : a);
303 return s;
304 }
305}
306
307
308size_t luaO_str2num (const char *s, TValue *o) {
309 lua_Integer i; lua_Number n;
310 const char *e;
311 if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */
312 setivalue(o, i);
313 }
314 else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */
315 setfltvalue(o, n);
316 }
317 else
318 return 0; /* conversion failed */
319 return (e - s) + 1; /* success; return string size */
320}
321
322
323int luaO_utf8esc (char *buff, unsigned long x) {
324 int n = 1; /* number of bytes put in buffer (backwards) */
325 lua_assert(x <= 0x7FFFFFFFu);
326 if (x < 0x80) /* ascii? */
327 buff[UTF8BUFFSZ - 1] = cast_char(x);
328 else { /* need continuation bytes */
329 unsigned int mfb = 0x3f; /* maximum that fits in first byte */
330 do { /* add continuation bytes */
331 buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f));
332 x >>= 6; /* remove added bits */
333 mfb >>= 1; /* now there is one less bit available in first byte */
334 } while (x > mfb); /* still needs continuation byte? */
335 buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x); /* add first byte */
336 }
337 return n;
338}
339
340
341/*
342** Maximum length of the conversion of a number to a string. Must be
343** enough to accommodate both LUA_INTEGER_FMT and LUA_NUMBER_FMT.
344** (For a long long int, this is 19 digits plus a sign and a final '\0',
345** adding to 21. For a long double, it can go to a sign, 33 digits,
346** the dot, an exponent letter, an exponent sign, 5 exponent digits,
347** and a final '\0', adding to 43.)
348*/
349#define MAXNUMBER2STR 44
350
351
352/*
353** Convert a number object to a string, adding it to a buffer
354*/
355static int tostringbuff (TValue *obj, char *buff) {
356 int len;
357 lua_assert(ttisnumber(obj));
358 if (ttisinteger(obj))
359 len = lua_integer2str(buff, MAXNUMBER2STR, ivalue(obj));
360 else {
361 len = lua_number2str(buff, MAXNUMBER2STR, fltvalue(obj));
362 if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */
363 buff[len++] = lua_getlocaledecpoint();
364 buff[len++] = '0'; /* adds '.0' to result */
365 }
366 }
367 return len;
368}
369
370
371/*
372** Convert a number object to a Lua string, replacing the value at 'obj'
373*/
374void luaO_tostring (lua_State *L, TValue *obj) {
375 char buff[MAXNUMBER2STR];
376 int len = tostringbuff(obj, buff);
377 setsvalue(L, obj, luaS_newlstr(L, buff, len));
378}
379
380
381
382
383/*
384** {==================================================================
385** 'luaO_pushvfstring'
386** ===================================================================
387*/
388
389/*
390** Size for buffer space used by 'luaO_pushvfstring'. It should be
391** (LUA_IDSIZE + MAXNUMBER2STR) + a minimal space for basic messages,
392** so that 'luaG_addinfo' can work directly on the buffer.
393*/
394#define BUFVFS (LUA_IDSIZE + MAXNUMBER2STR + 95)
395
396/* buffer used by 'luaO_pushvfstring' */
397typedef struct BuffFS {
398 lua_State *L;
399 int pushed; /* true if there is a part of the result on the stack */
400 int blen; /* length of partial string in 'space' */
401 char space[BUFVFS]; /* holds last part of the result */
402} BuffFS;
403
404
405/*
406** Push given string to the stack, as part of the result, and
407** join it to previous partial result if there is one.
408** It may call 'luaV_concat' while using one slot from EXTRA_STACK.
409** This call cannot invoke metamethods, as both operands must be
410** strings. It can, however, raise an error if the result is too
411** long. In that case, 'luaV_concat' frees the extra slot before
412** raising the error.
413*/
414static void pushstr (BuffFS *buff, const char *str, size_t lstr) {
415 lua_State *L = buff->L;
416 setsvalue2s(L, L->top.p, luaS_newlstr(L, str, lstr));
417 L->top.p++; /* may use one slot from EXTRA_STACK */
418 if (!buff->pushed) /* no previous string on the stack? */
419 buff->pushed = 1; /* now there is one */
420 else /* join previous string with new one */
421 luaV_concat(L, 2);
422}
423
424
425/*
426** empty the buffer space into the stack
427*/
428static void clearbuff (BuffFS *buff) {
429 pushstr(buff, buff->space, buff->blen); /* push buffer contents */
430 buff->blen = 0; /* space now is empty */
431}
432
433
434/*
435** Get a space of size 'sz' in the buffer. If buffer has not enough
436** space, empty it. 'sz' must fit in an empty buffer.
437*/
438static char *getbuff (BuffFS *buff, int sz) {
439 lua_assert(buff->blen <= BUFVFS); lua_assert(sz <= BUFVFS);
440 if (sz > BUFVFS - buff->blen) /* not enough space? */
441 clearbuff(buff);
442 return buff->space + buff->blen;
443}
444
445
446#define addsize(b,sz) ((b)->blen += (sz))
447
448
449/*
450** Add 'str' to the buffer. If string is larger than the buffer space,
451** push the string directly to the stack.
452*/
453static void addstr2buff (BuffFS *buff, const char *str, size_t slen) {
454 if (slen <= BUFVFS) { /* does string fit into buffer? */
455 char *bf = getbuff(buff, cast_int(slen));
456 memcpy(bf, str, slen); /* add string to buffer */
457 addsize(buff, cast_int(slen));
458 }
459 else { /* string larger than buffer */
460 clearbuff(buff); /* string comes after buffer's content */
461 pushstr(buff, str, slen); /* push string */
462 }
463}
464
465
466/*
467** Add a numeral to the buffer.
468*/
469static void addnum2buff (BuffFS *buff, TValue *num) {
470 char *numbuff = getbuff(buff, MAXNUMBER2STR);
471 int len = tostringbuff(num, numbuff); /* format number into 'numbuff' */
472 addsize(buff, len);
473}
474
475
476/*
477** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%'
478 conventional formats, plus Lua-specific '%I' and '%U'
479*/
480const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
481 BuffFS buff; /* holds last part of the result */
482 const char *e; /* points to next '%' */
483 buff.pushed = buff.blen = 0;
484 buff.L = L;
485 while ((e = strchr(fmt, '%')) != NULL) {
486 addstr2buff(&buff, fmt, e - fmt); /* add 'fmt' up to '%' */
487 switch (*(e + 1)) { /* conversion specifier */
488 case 's': { /* zero-terminated string */
489 const char *s = va_arg(argp, char *);
490 if (s == NULL) s = "(null)";
491 addstr2buff(&buff, s, strlen(s));
492 break;
493 }
494 case 'c': { /* an 'int' as a character */
495 char c = cast_uchar(va_arg(argp, int));
496 addstr2buff(&buff, &c, sizeof(char));
497 break;
498 }
499 case 'd': { /* an 'int' */
500 TValue num;
501 setivalue(&num, va_arg(argp, int));
502 addnum2buff(&buff, &num);
503 break;
504 }
505 case 'I': { /* a 'lua_Integer' */
506 TValue num;
507 setivalue(&num, cast(lua_Integer, va_arg(argp, l_uacInt)));
508 addnum2buff(&buff, &num);
509 break;
510 }
511 case 'f': { /* a 'lua_Number' */
512 TValue num;
513 setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber)));
514 addnum2buff(&buff, &num);
515 break;
516 }
517 case 'p': { /* a pointer */
518 const int sz = 3 * sizeof(void*) + 8; /* enough space for '%p' */
519 char *bf = getbuff(&buff, sz);
520 void *p = va_arg(argp, void *);
521 int len = lua_pointer2str(bf, sz, p);
522 addsize(&buff, len);
523 break;
524 }
525 case 'U': { /* a 'long' as a UTF-8 sequence */
526 char bf[UTF8BUFFSZ];
527 int len = luaO_utf8esc(bf, va_arg(argp, long));
528 addstr2buff(&buff, bf + UTF8BUFFSZ - len, len);
529 break;
530 }
531 case '%': {
532 addstr2buff(&buff, "%", 1);
533 break;
534 }
535 default: {
536 luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
537 *(e + 1));
538 }
539 }
540 fmt = e + 2; /* skip '%' and the specifier */
541 }
542 addstr2buff(&buff, fmt, strlen(fmt)); /* rest of 'fmt' */
543 clearbuff(&buff); /* empty buffer into the stack */
544 lua_assert(buff.pushed == 1);
545 return getstr(tsvalue(s2v(L->top.p - 1)));
546}
547
548
549const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
550 const char *msg;
551 va_list argp;
552 va_start(argp, fmt);
553 msg = luaO_pushvfstring(L, fmt, argp);
554 va_end(argp);
555 return msg;
556}
557
558/* }================================================================== */
559
560
561#define RETS "..."
562#define PRE "[string \""
563#define POS "\"]"
564
565#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
566
567void luaO_chunkid (char *out, const char *source, size_t srclen) {
568 size_t bufflen = LUA_IDSIZE; /* free space in buffer */
569 if (*source == '=') { /* 'literal' source */
570 if (srclen <= bufflen) /* small enough? */
571 memcpy(out, source + 1, srclen * sizeof(char));
572 else { /* truncate it */
573 addstr(out, source + 1, bufflen - 1);
574 *out = '\0';
575 }
576 }
577 else if (*source == '@') { /* file name */
578 if (srclen <= bufflen) /* small enough? */
579 memcpy(out, source + 1, srclen * sizeof(char));
580 else { /* add '...' before rest of name */
581 addstr(out, RETS, LL(RETS));
582 bufflen -= LL(RETS);
583 memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char));
584 }
585 }
586 else { /* string; format as [string "source"] */
587 const char *nl = strchr(source, '\n'); /* find first new line (if any) */
588 addstr(out, PRE, LL(PRE)); /* add prefix */
589 bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */
590 if (srclen < bufflen && nl == NULL) { /* small one-line source? */
591 addstr(out, source, srclen); /* keep it */
592 }
593 else {
594 if (nl != NULL) srclen = nl - source; /* stop at first newline */
595 if (srclen > bufflen) srclen = bufflen;
596 addstr(out, source, srclen);
597 addstr(out, RETS, LL(RETS));
598 }
599 memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
600 }
601}
602
diff --git a/vendor/lua-5.4.8/src/lobject.h b/vendor/lua-5.4.8/src/lobject.h
new file mode 100644
index 0000000..980e42f
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lobject.h
@@ -0,0 +1,813 @@
1/*
2** $Id: lobject.h $
3** Type definitions for Lua objects
4** See Copyright Notice in lua.h
5*/
6
7
8#ifndef lobject_h
9#define lobject_h
10
11
12#include <stdarg.h>
13
14
15#include "llimits.h"
16#include "lua.h"
17
18
19/*
20** Extra types for collectable non-values
21*/
22#define LUA_TUPVAL LUA_NUMTYPES /* upvalues */
23#define LUA_TPROTO (LUA_NUMTYPES+1) /* function prototypes */
24#define LUA_TDEADKEY (LUA_NUMTYPES+2) /* removed keys in tables */
25
26
27
28/*
29** number of all possible types (including LUA_TNONE but excluding DEADKEY)
30*/
31#define LUA_TOTALTYPES (LUA_TPROTO + 2)
32
33
34/*
35** tags for Tagged Values have the following use of bits:
36** bits 0-3: actual tag (a LUA_T* constant)
37** bits 4-5: variant bits
38** bit 6: whether value is collectable
39*/
40
41/* add variant bits to a type */
42#define makevariant(t,v) ((t) | ((v) << 4))
43
44
45
46/*
47** Union of all Lua values
48*/
49typedef union Value {
50 struct GCObject *gc; /* collectable objects */
51 void *p; /* light userdata */
52 lua_CFunction f; /* light C functions */
53 lua_Integer i; /* integer numbers */
54 lua_Number n; /* float numbers */
55 /* not used, but may avoid warnings for uninitialized value */
56 lu_byte ub;
57} Value;
58
59
60/*
61** Tagged Values. This is the basic representation of values in Lua:
62** an actual value plus a tag with its type.
63*/
64
65#define TValuefields Value value_; lu_byte tt_
66
67typedef struct TValue {
68 TValuefields;
69} TValue;
70
71
72#define val_(o) ((o)->value_)
73#define valraw(o) (val_(o))
74
75
76/* raw type tag of a TValue */
77#define rawtt(o) ((o)->tt_)
78
79/* tag with no variants (bits 0-3) */
80#define novariant(t) ((t) & 0x0F)
81
82/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */
83#define withvariant(t) ((t) & 0x3F)
84#define ttypetag(o) withvariant(rawtt(o))
85
86/* type of a TValue */
87#define ttype(o) (novariant(rawtt(o)))
88
89
90/* Macros to test type */
91#define checktag(o,t) (rawtt(o) == (t))
92#define checktype(o,t) (ttype(o) == (t))
93
94
95/* Macros for internal tests */
96
97/* collectable object has the same tag as the original value */
98#define righttt(obj) (ttypetag(obj) == gcvalue(obj)->tt)
99
100/*
101** Any value being manipulated by the program either is non
102** collectable, or the collectable object has the right tag
103** and it is not dead. The option 'L == NULL' allows other
104** macros using this one to be used where L is not available.
105*/
106#define checkliveness(L,obj) \
107 ((void)L, lua_longassert(!iscollectable(obj) || \
108 (righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj))))))
109
110
111/* Macros to set values */
112
113/* set a value's tag */
114#define settt_(o,t) ((o)->tt_=(t))
115
116
117/* main macro to copy values (from 'obj2' to 'obj1') */
118#define setobj(L,obj1,obj2) \
119 { TValue *io1=(obj1); const TValue *io2=(obj2); \
120 io1->value_ = io2->value_; settt_(io1, io2->tt_); \
121 checkliveness(L,io1); lua_assert(!isnonstrictnil(io1)); }
122
123/*
124** Different types of assignments, according to source and destination.
125** (They are mostly equal now, but may be different in the future.)
126*/
127
128/* from stack to stack */
129#define setobjs2s(L,o1,o2) setobj(L,s2v(o1),s2v(o2))
130/* to stack (not from same stack) */
131#define setobj2s(L,o1,o2) setobj(L,s2v(o1),o2)
132/* from table to same table */
133#define setobjt2t setobj
134/* to new object */
135#define setobj2n setobj
136/* to table */
137#define setobj2t setobj
138
139
140/*
141** Entries in a Lua stack. Field 'tbclist' forms a list of all
142** to-be-closed variables active in this stack. Dummy entries are
143** used when the distance between two tbc variables does not fit
144** in an unsigned short. They are represented by delta==0, and
145** their real delta is always the maximum value that fits in
146** that field.
147*/
148typedef union StackValue {
149 TValue val;
150 struct {
151 TValuefields;
152 unsigned short delta;
153 } tbclist;
154} StackValue;
155
156
157/* index to stack elements */
158typedef StackValue *StkId;
159
160
161/*
162** When reallocating the stack, change all pointers to the stack into
163** proper offsets.
164*/
165typedef union {
166 StkId p; /* actual pointer */
167 ptrdiff_t offset; /* used while the stack is being reallocated */
168} StkIdRel;
169
170
171/* convert a 'StackValue' to a 'TValue' */
172#define s2v(o) (&(o)->val)
173
174
175
176/*
177** {==================================================================
178** Nil
179** ===================================================================
180*/
181
182/* Standard nil */
183#define LUA_VNIL makevariant(LUA_TNIL, 0)
184
185/* Empty slot (which might be different from a slot containing nil) */
186#define LUA_VEMPTY makevariant(LUA_TNIL, 1)
187
188/* Value returned for a key not found in a table (absent key) */
189#define LUA_VABSTKEY makevariant(LUA_TNIL, 2)
190
191
192/* macro to test for (any kind of) nil */
193#define ttisnil(v) checktype((v), LUA_TNIL)
194
195
196/* macro to test for a standard nil */
197#define ttisstrictnil(o) checktag((o), LUA_VNIL)
198
199
200#define setnilvalue(obj) settt_(obj, LUA_VNIL)
201
202
203#define isabstkey(v) checktag((v), LUA_VABSTKEY)
204
205
206/*
207** macro to detect non-standard nils (used only in assertions)
208*/
209#define isnonstrictnil(v) (ttisnil(v) && !ttisstrictnil(v))
210
211
212/*
213** By default, entries with any kind of nil are considered empty.
214** (In any definition, values associated with absent keys must also
215** be accepted as empty.)
216*/
217#define isempty(v) ttisnil(v)
218
219
220/* macro defining a value corresponding to an absent key */
221#define ABSTKEYCONSTANT {NULL}, LUA_VABSTKEY
222
223
224/* mark an entry as empty */
225#define setempty(v) settt_(v, LUA_VEMPTY)
226
227
228
229/* }================================================================== */
230
231
232/*
233** {==================================================================
234** Booleans
235** ===================================================================
236*/
237
238
239#define LUA_VFALSE makevariant(LUA_TBOOLEAN, 0)
240#define LUA_VTRUE makevariant(LUA_TBOOLEAN, 1)
241
242#define ttisboolean(o) checktype((o), LUA_TBOOLEAN)
243#define ttisfalse(o) checktag((o), LUA_VFALSE)
244#define ttistrue(o) checktag((o), LUA_VTRUE)
245
246
247#define l_isfalse(o) (ttisfalse(o) || ttisnil(o))
248
249
250#define setbfvalue(obj) settt_(obj, LUA_VFALSE)
251#define setbtvalue(obj) settt_(obj, LUA_VTRUE)
252
253/* }================================================================== */
254
255
256/*
257** {==================================================================
258** Threads
259** ===================================================================
260*/
261
262#define LUA_VTHREAD makevariant(LUA_TTHREAD, 0)
263
264#define ttisthread(o) checktag((o), ctb(LUA_VTHREAD))
265
266#define thvalue(o) check_exp(ttisthread(o), gco2th(val_(o).gc))
267
268#define setthvalue(L,obj,x) \
269 { TValue *io = (obj); lua_State *x_ = (x); \
270 val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTHREAD)); \
271 checkliveness(L,io); }
272
273#define setthvalue2s(L,o,t) setthvalue(L,s2v(o),t)
274
275/* }================================================================== */
276
277
278/*
279** {==================================================================
280** Collectable Objects
281** ===================================================================
282*/
283
284/*
285** Common Header for all collectable objects (in macro form, to be
286** included in other objects)
287*/
288#define CommonHeader struct GCObject *next; lu_byte tt; lu_byte marked
289
290
291/* Common type for all collectable objects */
292typedef struct GCObject {
293 CommonHeader;
294} GCObject;
295
296
297/* Bit mark for collectable types */
298#define BIT_ISCOLLECTABLE (1 << 6)
299
300#define iscollectable(o) (rawtt(o) & BIT_ISCOLLECTABLE)
301
302/* mark a tag as collectable */
303#define ctb(t) ((t) | BIT_ISCOLLECTABLE)
304
305#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc)
306
307#define gcvalueraw(v) ((v).gc)
308
309#define setgcovalue(L,obj,x) \
310 { TValue *io = (obj); GCObject *i_g=(x); \
311 val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); }
312
313/* }================================================================== */
314
315
316/*
317** {==================================================================
318** Numbers
319** ===================================================================
320*/
321
322/* Variant tags for numbers */
323#define LUA_VNUMINT makevariant(LUA_TNUMBER, 0) /* integer numbers */
324#define LUA_VNUMFLT makevariant(LUA_TNUMBER, 1) /* float numbers */
325
326#define ttisnumber(o) checktype((o), LUA_TNUMBER)
327#define ttisfloat(o) checktag((o), LUA_VNUMFLT)
328#define ttisinteger(o) checktag((o), LUA_VNUMINT)
329
330#define nvalue(o) check_exp(ttisnumber(o), \
331 (ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o)))
332#define fltvalue(o) check_exp(ttisfloat(o), val_(o).n)
333#define ivalue(o) check_exp(ttisinteger(o), val_(o).i)
334
335#define fltvalueraw(v) ((v).n)
336#define ivalueraw(v) ((v).i)
337
338#define setfltvalue(obj,x) \
339 { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_VNUMFLT); }
340
341#define chgfltvalue(obj,x) \
342 { TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); }
343
344#define setivalue(obj,x) \
345 { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_VNUMINT); }
346
347#define chgivalue(obj,x) \
348 { TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); }
349
350/* }================================================================== */
351
352
353/*
354** {==================================================================
355** Strings
356** ===================================================================
357*/
358
359/* Variant tags for strings */
360#define LUA_VSHRSTR makevariant(LUA_TSTRING, 0) /* short strings */
361#define LUA_VLNGSTR makevariant(LUA_TSTRING, 1) /* long strings */
362
363#define ttisstring(o) checktype((o), LUA_TSTRING)
364#define ttisshrstring(o) checktag((o), ctb(LUA_VSHRSTR))
365#define ttislngstring(o) checktag((o), ctb(LUA_VLNGSTR))
366
367#define tsvalueraw(v) (gco2ts((v).gc))
368
369#define tsvalue(o) check_exp(ttisstring(o), gco2ts(val_(o).gc))
370
371#define setsvalue(L,obj,x) \
372 { TValue *io = (obj); TString *x_ = (x); \
373 val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \
374 checkliveness(L,io); }
375
376/* set a string to the stack */
377#define setsvalue2s(L,o,s) setsvalue(L,s2v(o),s)
378
379/* set a string to a new object */
380#define setsvalue2n setsvalue
381
382
383/*
384** Header for a string value.
385*/
386typedef struct TString {
387 CommonHeader;
388 lu_byte extra; /* reserved words for short strings; "has hash" for longs */
389 lu_byte shrlen; /* length for short strings, 0xFF for long strings */
390 unsigned int hash;
391 union {
392 size_t lnglen; /* length for long strings */
393 struct TString *hnext; /* linked list for hash table */
394 } u;
395 char contents[1];
396} TString;
397
398
399
400/*
401** Get the actual string (array of bytes) from a 'TString'. (Generic
402** version and specialized versions for long and short strings.)
403*/
404#define getstr(ts) ((ts)->contents)
405#define getlngstr(ts) check_exp((ts)->shrlen == 0xFF, (ts)->contents)
406#define getshrstr(ts) check_exp((ts)->shrlen != 0xFF, (ts)->contents)
407
408
409/* get string length from 'TString *s' */
410#define tsslen(s) \
411 ((s)->shrlen != 0xFF ? (s)->shrlen : (s)->u.lnglen)
412
413/* }================================================================== */
414
415
416/*
417** {==================================================================
418** Userdata
419** ===================================================================
420*/
421
422
423/*
424** Light userdata should be a variant of userdata, but for compatibility
425** reasons they are also different types.
426*/
427#define LUA_VLIGHTUSERDATA makevariant(LUA_TLIGHTUSERDATA, 0)
428
429#define LUA_VUSERDATA makevariant(LUA_TUSERDATA, 0)
430
431#define ttislightuserdata(o) checktag((o), LUA_VLIGHTUSERDATA)
432#define ttisfulluserdata(o) checktag((o), ctb(LUA_VUSERDATA))
433
434#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p)
435#define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc))
436
437#define pvalueraw(v) ((v).p)
438
439#define setpvalue(obj,x) \
440 { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_VLIGHTUSERDATA); }
441
442#define setuvalue(L,obj,x) \
443 { TValue *io = (obj); Udata *x_ = (x); \
444 val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VUSERDATA)); \
445 checkliveness(L,io); }
446
447
448/* Ensures that addresses after this type are always fully aligned. */
449typedef union UValue {
450 TValue uv;
451 LUAI_MAXALIGN; /* ensures maximum alignment for udata bytes */
452} UValue;
453
454
455/*
456** Header for userdata with user values;
457** memory area follows the end of this structure.
458*/
459typedef struct Udata {
460 CommonHeader;
461 unsigned short nuvalue; /* number of user values */
462 size_t len; /* number of bytes */
463 struct Table *metatable;
464 GCObject *gclist;
465 UValue uv[1]; /* user values */
466} Udata;
467
468
469/*
470** Header for userdata with no user values. These userdata do not need
471** to be gray during GC, and therefore do not need a 'gclist' field.
472** To simplify, the code always use 'Udata' for both kinds of userdata,
473** making sure it never accesses 'gclist' on userdata with no user values.
474** This structure here is used only to compute the correct size for
475** this representation. (The 'bindata' field in its end ensures correct
476** alignment for binary data following this header.)
477*/
478typedef struct Udata0 {
479 CommonHeader;
480 unsigned short nuvalue; /* number of user values */
481 size_t len; /* number of bytes */
482 struct Table *metatable;
483 union {LUAI_MAXALIGN;} bindata;
484} Udata0;
485
486
487/* compute the offset of the memory area of a userdata */
488#define udatamemoffset(nuv) \
489 ((nuv) == 0 ? offsetof(Udata0, bindata) \
490 : offsetof(Udata, uv) + (sizeof(UValue) * (nuv)))
491
492/* get the address of the memory block inside 'Udata' */
493#define getudatamem(u) (cast_charp(u) + udatamemoffset((u)->nuvalue))
494
495/* compute the size of a userdata */
496#define sizeudata(nuv,nb) (udatamemoffset(nuv) + (nb))
497
498/* }================================================================== */
499
500
501/*
502** {==================================================================
503** Prototypes
504** ===================================================================
505*/
506
507#define LUA_VPROTO makevariant(LUA_TPROTO, 0)
508
509
510/*
511** Description of an upvalue for function prototypes
512*/
513typedef struct Upvaldesc {
514 TString *name; /* upvalue name (for debug information) */
515 lu_byte instack; /* whether it is in stack (register) */
516 lu_byte idx; /* index of upvalue (in stack or in outer function's list) */
517 lu_byte kind; /* kind of corresponding variable */
518} Upvaldesc;
519
520
521/*
522** Description of a local variable for function prototypes
523** (used for debug information)
524*/
525typedef struct LocVar {
526 TString *varname;
527 int startpc; /* first point where variable is active */
528 int endpc; /* first point where variable is dead */
529} LocVar;
530
531
532/*
533** Associates the absolute line source for a given instruction ('pc').
534** The array 'lineinfo' gives, for each instruction, the difference in
535** lines from the previous instruction. When that difference does not
536** fit into a byte, Lua saves the absolute line for that instruction.
537** (Lua also saves the absolute line periodically, to speed up the
538** computation of a line number: we can use binary search in the
539** absolute-line array, but we must traverse the 'lineinfo' array
540** linearly to compute a line.)
541*/
542typedef struct AbsLineInfo {
543 int pc;
544 int line;
545} AbsLineInfo;
546
547/*
548** Function Prototypes
549*/
550typedef struct Proto {
551 CommonHeader;
552 lu_byte numparams; /* number of fixed (named) parameters */
553 lu_byte is_vararg;
554 lu_byte maxstacksize; /* number of registers needed by this function */
555 int sizeupvalues; /* size of 'upvalues' */
556 int sizek; /* size of 'k' */
557 int sizecode;
558 int sizelineinfo;
559 int sizep; /* size of 'p' */
560 int sizelocvars;
561 int sizeabslineinfo; /* size of 'abslineinfo' */
562 int linedefined; /* debug information */
563 int lastlinedefined; /* debug information */
564 TValue *k; /* constants used by the function */
565 Instruction *code; /* opcodes */
566 struct Proto **p; /* functions defined inside the function */
567 Upvaldesc *upvalues; /* upvalue information */
568 ls_byte *lineinfo; /* information about source lines (debug information) */
569 AbsLineInfo *abslineinfo; /* idem */
570 LocVar *locvars; /* information about local variables (debug information) */
571 TString *source; /* used for debug information */
572 GCObject *gclist;
573} Proto;
574
575/* }================================================================== */
576
577
578/*
579** {==================================================================
580** Functions
581** ===================================================================
582*/
583
584#define LUA_VUPVAL makevariant(LUA_TUPVAL, 0)
585
586
587/* Variant tags for functions */
588#define LUA_VLCL makevariant(LUA_TFUNCTION, 0) /* Lua closure */
589#define LUA_VLCF makevariant(LUA_TFUNCTION, 1) /* light C function */
590#define LUA_VCCL makevariant(LUA_TFUNCTION, 2) /* C closure */
591
592#define ttisfunction(o) checktype(o, LUA_TFUNCTION)
593#define ttisLclosure(o) checktag((o), ctb(LUA_VLCL))
594#define ttislcf(o) checktag((o), LUA_VLCF)
595#define ttisCclosure(o) checktag((o), ctb(LUA_VCCL))
596#define ttisclosure(o) (ttisLclosure(o) || ttisCclosure(o))
597
598
599#define isLfunction(o) ttisLclosure(o)
600
601#define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc))
602#define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc))
603#define fvalue(o) check_exp(ttislcf(o), val_(o).f)
604#define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc))
605
606#define fvalueraw(v) ((v).f)
607
608#define setclLvalue(L,obj,x) \
609 { TValue *io = (obj); LClosure *x_ = (x); \
610 val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VLCL)); \
611 checkliveness(L,io); }
612
613#define setclLvalue2s(L,o,cl) setclLvalue(L,s2v(o),cl)
614
615#define setfvalue(obj,x) \
616 { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_VLCF); }
617
618#define setclCvalue(L,obj,x) \
619 { TValue *io = (obj); CClosure *x_ = (x); \
620 val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VCCL)); \
621 checkliveness(L,io); }
622
623
624/*
625** Upvalues for Lua closures
626*/
627typedef struct UpVal {
628 CommonHeader;
629 union {
630 TValue *p; /* points to stack or to its own value */
631 ptrdiff_t offset; /* used while the stack is being reallocated */
632 } v;
633 union {
634 struct { /* (when open) */
635 struct UpVal *next; /* linked list */
636 struct UpVal **previous;
637 } open;
638 TValue value; /* the value (when closed) */
639 } u;
640} UpVal;
641
642
643
644#define ClosureHeader \
645 CommonHeader; lu_byte nupvalues; GCObject *gclist
646
647typedef struct CClosure {
648 ClosureHeader;
649 lua_CFunction f;
650 TValue upvalue[1]; /* list of upvalues */
651} CClosure;
652
653
654typedef struct LClosure {
655 ClosureHeader;
656 struct Proto *p;
657 UpVal *upvals[1]; /* list of upvalues */
658} LClosure;
659
660
661typedef union Closure {
662 CClosure c;
663 LClosure l;
664} Closure;
665
666
667#define getproto(o) (clLvalue(o)->p)
668
669/* }================================================================== */
670
671
672/*
673** {==================================================================
674** Tables
675** ===================================================================
676*/
677
678#define LUA_VTABLE makevariant(LUA_TTABLE, 0)
679
680#define ttistable(o) checktag((o), ctb(LUA_VTABLE))
681
682#define hvalue(o) check_exp(ttistable(o), gco2t(val_(o).gc))
683
684#define sethvalue(L,obj,x) \
685 { TValue *io = (obj); Table *x_ = (x); \
686 val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTABLE)); \
687 checkliveness(L,io); }
688
689#define sethvalue2s(L,o,h) sethvalue(L,s2v(o),h)
690
691
692/*
693** Nodes for Hash tables: A pack of two TValue's (key-value pairs)
694** plus a 'next' field to link colliding entries. The distribution
695** of the key's fields ('key_tt' and 'key_val') not forming a proper
696** 'TValue' allows for a smaller size for 'Node' both in 4-byte
697** and 8-byte alignments.
698*/
699typedef union Node {
700 struct NodeKey {
701 TValuefields; /* fields for value */
702 lu_byte key_tt; /* key type */
703 int next; /* for chaining */
704 Value key_val; /* key value */
705 } u;
706 TValue i_val; /* direct access to node's value as a proper 'TValue' */
707} Node;
708
709
710/* copy a value into a key */
711#define setnodekey(L,node,obj) \
712 { Node *n_=(node); const TValue *io_=(obj); \
713 n_->u.key_val = io_->value_; n_->u.key_tt = io_->tt_; \
714 checkliveness(L,io_); }
715
716
717/* copy a value from a key */
718#define getnodekey(L,obj,node) \
719 { TValue *io_=(obj); const Node *n_=(node); \
720 io_->value_ = n_->u.key_val; io_->tt_ = n_->u.key_tt; \
721 checkliveness(L,io_); }
722
723
724/*
725** About 'alimit': if 'isrealasize(t)' is true, then 'alimit' is the
726** real size of 'array'. Otherwise, the real size of 'array' is the
727** smallest power of two not smaller than 'alimit' (or zero iff 'alimit'
728** is zero); 'alimit' is then used as a hint for #t.
729*/
730
731#define BITRAS (1 << 7)
732#define isrealasize(t) (!((t)->flags & BITRAS))
733#define setrealasize(t) ((t)->flags &= cast_byte(~BITRAS))
734#define setnorealasize(t) ((t)->flags |= BITRAS)
735
736
737typedef struct Table {
738 CommonHeader;
739 lu_byte flags; /* 1<<p means tagmethod(p) is not present */
740 lu_byte lsizenode; /* log2 of size of 'node' array */
741 unsigned int alimit; /* "limit" of 'array' array */
742 TValue *array; /* array part */
743 Node *node;
744 Node *lastfree; /* any free position is before this position */
745 struct Table *metatable;
746 GCObject *gclist;
747} Table;
748
749
750/*
751** Macros to manipulate keys inserted in nodes
752*/
753#define keytt(node) ((node)->u.key_tt)
754#define keyval(node) ((node)->u.key_val)
755
756#define keyisnil(node) (keytt(node) == LUA_TNIL)
757#define keyisinteger(node) (keytt(node) == LUA_VNUMINT)
758#define keyival(node) (keyval(node).i)
759#define keyisshrstr(node) (keytt(node) == ctb(LUA_VSHRSTR))
760#define keystrval(node) (gco2ts(keyval(node).gc))
761
762#define setnilkey(node) (keytt(node) = LUA_TNIL)
763
764#define keyiscollectable(n) (keytt(n) & BIT_ISCOLLECTABLE)
765
766#define gckey(n) (keyval(n).gc)
767#define gckeyN(n) (keyiscollectable(n) ? gckey(n) : NULL)
768
769
770/*
771** Dead keys in tables have the tag DEADKEY but keep their original
772** gcvalue. This distinguishes them from regular keys but allows them to
773** be found when searched in a special way. ('next' needs that to find
774** keys removed from a table during a traversal.)
775*/
776#define setdeadkey(node) (keytt(node) = LUA_TDEADKEY)
777#define keyisdead(node) (keytt(node) == LUA_TDEADKEY)
778
779/* }================================================================== */
780
781
782
783/*
784** 'module' operation for hashing (size is always a power of 2)
785*/
786#define lmod(s,size) \
787 (check_exp((size&(size-1))==0, (cast_int((s) & ((size)-1)))))
788
789
790#define twoto(x) (1<<(x))
791#define sizenode(t) (twoto((t)->lsizenode))
792
793
794/* size of buffer for 'luaO_utf8esc' function */
795#define UTF8BUFFSZ 8
796
797LUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x);
798LUAI_FUNC int luaO_ceillog2 (unsigned int x);
799LUAI_FUNC int luaO_rawarith (lua_State *L, int op, const TValue *p1,
800 const TValue *p2, TValue *res);
801LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1,
802 const TValue *p2, StkId res);
803LUAI_FUNC size_t luaO_str2num (const char *s, TValue *o);
804LUAI_FUNC int luaO_hexavalue (int c);
805LUAI_FUNC void luaO_tostring (lua_State *L, TValue *obj);
806LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
807 va_list argp);
808LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);
809LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t srclen);
810
811
812#endif
813
diff --git a/vendor/lua-5.4.8/src/lopcodes.c b/vendor/lua-5.4.8/src/lopcodes.c
new file mode 100644
index 0000000..c67aa22
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lopcodes.c
@@ -0,0 +1,104 @@
1/*
2** $Id: lopcodes.c $
3** Opcodes for Lua virtual machine
4** See Copyright Notice in lua.h
5*/
6
7#define lopcodes_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include "lopcodes.h"
14
15
16/* ORDER OP */
17
18LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {
19/* MM OT IT T A mode opcode */
20 opmode(0, 0, 0, 0, 1, iABC) /* OP_MOVE */
21 ,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADI */
22 ,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADF */
23 ,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADK */
24 ,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADKX */
25 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADFALSE */
26 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LFALSESKIP */
27 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADTRUE */
28 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADNIL */
29 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETUPVAL */
30 ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETUPVAL */
31 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABUP */
32 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABLE */
33 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETI */
34 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETFIELD */
35 ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABUP */
36 ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABLE */
37 ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETI */
38 ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETFIELD */
39 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_NEWTABLE */
40 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SELF */
41 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDI */
42 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDK */
43 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUBK */
44 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MULK */
45 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MODK */
46 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_POWK */
47 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIVK */
48 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIVK */
49 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BANDK */
50 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BORK */
51 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXORK */
52 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHRI */
53 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHLI */
54 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADD */
55 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUB */
56 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MUL */
57 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MOD */
58 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_POW */
59 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIV */
60 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIV */
61 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BAND */
62 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BOR */
63 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXOR */
64 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHL */
65 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHR */
66 ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBIN */
67 ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINI*/
68 ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINK*/
69 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_UNM */
70 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BNOT */
71 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_NOT */
72 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LEN */
73 ,opmode(0, 0, 0, 0, 1, iABC) /* OP_CONCAT */
74 ,opmode(0, 0, 0, 0, 0, iABC) /* OP_CLOSE */
75 ,opmode(0, 0, 0, 0, 0, iABC) /* OP_TBC */
76 ,opmode(0, 0, 0, 0, 0, isJ) /* OP_JMP */
77 ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQ */
78 ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LT */
79 ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LE */
80 ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQK */
81 ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQI */
82 ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LTI */
83 ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LEI */
84 ,opmode(0, 0, 0, 1, 0, iABC) /* OP_GTI */
85 ,opmode(0, 0, 0, 1, 0, iABC) /* OP_GEI */
86 ,opmode(0, 0, 0, 1, 0, iABC) /* OP_TEST */
87 ,opmode(0, 0, 0, 1, 1, iABC) /* OP_TESTSET */
88 ,opmode(0, 1, 1, 0, 1, iABC) /* OP_CALL */
89 ,opmode(0, 1, 1, 0, 1, iABC) /* OP_TAILCALL */
90 ,opmode(0, 0, 1, 0, 0, iABC) /* OP_RETURN */
91 ,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN0 */
92 ,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN1 */
93 ,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORLOOP */
94 ,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORPREP */
95 ,opmode(0, 0, 0, 0, 0, iABx) /* OP_TFORPREP */
96 ,opmode(0, 0, 0, 0, 0, iABC) /* OP_TFORCALL */
97 ,opmode(0, 0, 0, 0, 1, iABx) /* OP_TFORLOOP */
98 ,opmode(0, 0, 1, 0, 0, iABC) /* OP_SETLIST */
99 ,opmode(0, 0, 0, 0, 1, iABx) /* OP_CLOSURE */
100 ,opmode(0, 1, 0, 0, 1, iABC) /* OP_VARARG */
101 ,opmode(0, 0, 1, 0, 1, iABC) /* OP_VARARGPREP */
102 ,opmode(0, 0, 0, 0, 0, iAx) /* OP_EXTRAARG */
103};
104
diff --git a/vendor/lua-5.4.8/src/lopcodes.h b/vendor/lua-5.4.8/src/lopcodes.h
new file mode 100644
index 0000000..46911ca
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lopcodes.h
@@ -0,0 +1,405 @@
1/*
2** $Id: lopcodes.h $
3** Opcodes for Lua virtual machine
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lopcodes_h
8#define lopcodes_h
9
10#include "llimits.h"
11
12
13/*===========================================================================
14 We assume that instructions are unsigned 32-bit integers.
15 All instructions have an opcode in the first 7 bits.
16 Instructions can have the following formats:
17
18 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
19 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
20iABC C(8) | B(8) |k| A(8) | Op(7) |
21iABx Bx(17) | A(8) | Op(7) |
22iAsBx sBx (signed)(17) | A(8) | Op(7) |
23iAx Ax(25) | Op(7) |
24isJ sJ (signed)(25) | Op(7) |
25
26 A signed argument is represented in excess K: the represented value is
27 the written unsigned value minus K, where K is half the maximum for the
28 corresponding unsigned argument.
29===========================================================================*/
30
31
32enum OpMode {iABC, iABx, iAsBx, iAx, isJ}; /* basic instruction formats */
33
34
35/*
36** size and position of opcode arguments.
37*/
38#define SIZE_C 8
39#define SIZE_B 8
40#define SIZE_Bx (SIZE_C + SIZE_B + 1)
41#define SIZE_A 8
42#define SIZE_Ax (SIZE_Bx + SIZE_A)
43#define SIZE_sJ (SIZE_Bx + SIZE_A)
44
45#define SIZE_OP 7
46
47#define POS_OP 0
48
49#define POS_A (POS_OP + SIZE_OP)
50#define POS_k (POS_A + SIZE_A)
51#define POS_B (POS_k + 1)
52#define POS_C (POS_B + SIZE_B)
53
54#define POS_Bx POS_k
55
56#define POS_Ax POS_A
57
58#define POS_sJ POS_A
59
60
61/*
62** limits for opcode arguments.
63** we use (signed) 'int' to manipulate most arguments,
64** so they must fit in ints.
65*/
66
67/* Check whether type 'int' has at least 'b' bits ('b' < 32) */
68#define L_INTHASBITS(b) ((UINT_MAX >> ((b) - 1)) >= 1)
69
70
71#if L_INTHASBITS(SIZE_Bx)
72#define MAXARG_Bx ((1<<SIZE_Bx)-1)
73#else
74#define MAXARG_Bx MAX_INT
75#endif
76
77#define OFFSET_sBx (MAXARG_Bx>>1) /* 'sBx' is signed */
78
79
80#if L_INTHASBITS(SIZE_Ax)
81#define MAXARG_Ax ((1<<SIZE_Ax)-1)
82#else
83#define MAXARG_Ax MAX_INT
84#endif
85
86#if L_INTHASBITS(SIZE_sJ)
87#define MAXARG_sJ ((1 << SIZE_sJ) - 1)
88#else
89#define MAXARG_sJ MAX_INT
90#endif
91
92#define OFFSET_sJ (MAXARG_sJ >> 1)
93
94
95#define MAXARG_A ((1<<SIZE_A)-1)
96#define MAXARG_B ((1<<SIZE_B)-1)
97#define MAXARG_C ((1<<SIZE_C)-1)
98#define OFFSET_sC (MAXARG_C >> 1)
99
100#define int2sC(i) ((i) + OFFSET_sC)
101#define sC2int(i) ((i) - OFFSET_sC)
102
103
104/* creates a mask with 'n' 1 bits at position 'p' */
105#define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p))
106
107/* creates a mask with 'n' 0 bits at position 'p' */
108#define MASK0(n,p) (~MASK1(n,p))
109
110/*
111** the following macros help to manipulate instructions
112*/
113
114#define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0)))
115#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \
116 ((cast(Instruction, o)<<POS_OP)&MASK1(SIZE_OP,POS_OP))))
117
118#define checkopm(i,m) (getOpMode(GET_OPCODE(i)) == m)
119
120
121#define getarg(i,pos,size) (cast_int(((i)>>(pos)) & MASK1(size,0)))
122#define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \
123 ((cast(Instruction, v)<<pos)&MASK1(size,pos))))
124
125#define GETARG_A(i) getarg(i, POS_A, SIZE_A)
126#define SETARG_A(i,v) setarg(i, v, POS_A, SIZE_A)
127
128#define GETARG_B(i) check_exp(checkopm(i, iABC), getarg(i, POS_B, SIZE_B))
129#define GETARG_sB(i) sC2int(GETARG_B(i))
130#define SETARG_B(i,v) setarg(i, v, POS_B, SIZE_B)
131
132#define GETARG_C(i) check_exp(checkopm(i, iABC), getarg(i, POS_C, SIZE_C))
133#define GETARG_sC(i) sC2int(GETARG_C(i))
134#define SETARG_C(i,v) setarg(i, v, POS_C, SIZE_C)
135
136#define TESTARG_k(i) check_exp(checkopm(i, iABC), (cast_int(((i) & (1u << POS_k)))))
137#define GETARG_k(i) check_exp(checkopm(i, iABC), getarg(i, POS_k, 1))
138#define SETARG_k(i,v) setarg(i, v, POS_k, 1)
139
140#define GETARG_Bx(i) check_exp(checkopm(i, iABx), getarg(i, POS_Bx, SIZE_Bx))
141#define SETARG_Bx(i,v) setarg(i, v, POS_Bx, SIZE_Bx)
142
143#define GETARG_Ax(i) check_exp(checkopm(i, iAx), getarg(i, POS_Ax, SIZE_Ax))
144#define SETARG_Ax(i,v) setarg(i, v, POS_Ax, SIZE_Ax)
145
146#define GETARG_sBx(i) \
147 check_exp(checkopm(i, iAsBx), getarg(i, POS_Bx, SIZE_Bx) - OFFSET_sBx)
148#define SETARG_sBx(i,b) SETARG_Bx((i),cast_uint((b)+OFFSET_sBx))
149
150#define GETARG_sJ(i) \
151 check_exp(checkopm(i, isJ), getarg(i, POS_sJ, SIZE_sJ) - OFFSET_sJ)
152#define SETARG_sJ(i,j) \
153 setarg(i, cast_uint((j)+OFFSET_sJ), POS_sJ, SIZE_sJ)
154
155
156#define CREATE_ABCk(o,a,b,c,k) ((cast(Instruction, o)<<POS_OP) \
157 | (cast(Instruction, a)<<POS_A) \
158 | (cast(Instruction, b)<<POS_B) \
159 | (cast(Instruction, c)<<POS_C) \
160 | (cast(Instruction, k)<<POS_k))
161
162#define CREATE_ABx(o,a,bc) ((cast(Instruction, o)<<POS_OP) \
163 | (cast(Instruction, a)<<POS_A) \
164 | (cast(Instruction, bc)<<POS_Bx))
165
166#define CREATE_Ax(o,a) ((cast(Instruction, o)<<POS_OP) \
167 | (cast(Instruction, a)<<POS_Ax))
168
169#define CREATE_sJ(o,j,k) ((cast(Instruction, o) << POS_OP) \
170 | (cast(Instruction, j) << POS_sJ) \
171 | (cast(Instruction, k) << POS_k))
172
173
174#if !defined(MAXINDEXRK) /* (for debugging only) */
175#define MAXINDEXRK MAXARG_B
176#endif
177
178
179/*
180** invalid register that fits in 8 bits
181*/
182#define NO_REG MAXARG_A
183
184
185/*
186** R[x] - register
187** K[x] - constant (in constant table)
188** RK(x) == if k(i) then K[x] else R[x]
189*/
190
191
192/*
193** Grep "ORDER OP" if you change these enums. Opcodes marked with a (*)
194** has extra descriptions in the notes after the enumeration.
195*/
196
197typedef enum {
198/*----------------------------------------------------------------------
199 name args description
200------------------------------------------------------------------------*/
201OP_MOVE,/* A B R[A] := R[B] */
202OP_LOADI,/* A sBx R[A] := sBx */
203OP_LOADF,/* A sBx R[A] := (lua_Number)sBx */
204OP_LOADK,/* A Bx R[A] := K[Bx] */
205OP_LOADKX,/* A R[A] := K[extra arg] */
206OP_LOADFALSE,/* A R[A] := false */
207OP_LFALSESKIP,/*A R[A] := false; pc++ (*) */
208OP_LOADTRUE,/* A R[A] := true */
209OP_LOADNIL,/* A B R[A], R[A+1], ..., R[A+B] := nil */
210OP_GETUPVAL,/* A B R[A] := UpValue[B] */
211OP_SETUPVAL,/* A B UpValue[B] := R[A] */
212
213OP_GETTABUP,/* A B C R[A] := UpValue[B][K[C]:shortstring] */
214OP_GETTABLE,/* A B C R[A] := R[B][R[C]] */
215OP_GETI,/* A B C R[A] := R[B][C] */
216OP_GETFIELD,/* A B C R[A] := R[B][K[C]:shortstring] */
217
218OP_SETTABUP,/* A B C UpValue[A][K[B]:shortstring] := RK(C) */
219OP_SETTABLE,/* A B C R[A][R[B]] := RK(C) */
220OP_SETI,/* A B C R[A][B] := RK(C) */
221OP_SETFIELD,/* A B C R[A][K[B]:shortstring] := RK(C) */
222
223OP_NEWTABLE,/* A B C k R[A] := {} */
224
225OP_SELF,/* A B C R[A+1] := R[B]; R[A] := R[B][RK(C):string] */
226
227OP_ADDI,/* A B sC R[A] := R[B] + sC */
228
229OP_ADDK,/* A B C R[A] := R[B] + K[C]:number */
230OP_SUBK,/* A B C R[A] := R[B] - K[C]:number */
231OP_MULK,/* A B C R[A] := R[B] * K[C]:number */
232OP_MODK,/* A B C R[A] := R[B] % K[C]:number */
233OP_POWK,/* A B C R[A] := R[B] ^ K[C]:number */
234OP_DIVK,/* A B C R[A] := R[B] / K[C]:number */
235OP_IDIVK,/* A B C R[A] := R[B] // K[C]:number */
236
237OP_BANDK,/* A B C R[A] := R[B] & K[C]:integer */
238OP_BORK,/* A B C R[A] := R[B] | K[C]:integer */
239OP_BXORK,/* A B C R[A] := R[B] ~ K[C]:integer */
240
241OP_SHRI,/* A B sC R[A] := R[B] >> sC */
242OP_SHLI,/* A B sC R[A] := sC << R[B] */
243
244OP_ADD,/* A B C R[A] := R[B] + R[C] */
245OP_SUB,/* A B C R[A] := R[B] - R[C] */
246OP_MUL,/* A B C R[A] := R[B] * R[C] */
247OP_MOD,/* A B C R[A] := R[B] % R[C] */
248OP_POW,/* A B C R[A] := R[B] ^ R[C] */
249OP_DIV,/* A B C R[A] := R[B] / R[C] */
250OP_IDIV,/* A B C R[A] := R[B] // R[C] */
251
252OP_BAND,/* A B C R[A] := R[B] & R[C] */
253OP_BOR,/* A B C R[A] := R[B] | R[C] */
254OP_BXOR,/* A B C R[A] := R[B] ~ R[C] */
255OP_SHL,/* A B C R[A] := R[B] << R[C] */
256OP_SHR,/* A B C R[A] := R[B] >> R[C] */
257
258OP_MMBIN,/* A B C call C metamethod over R[A] and R[B] (*) */
259OP_MMBINI,/* A sB C k call C metamethod over R[A] and sB */
260OP_MMBINK,/* A B C k call C metamethod over R[A] and K[B] */
261
262OP_UNM,/* A B R[A] := -R[B] */
263OP_BNOT,/* A B R[A] := ~R[B] */
264OP_NOT,/* A B R[A] := not R[B] */
265OP_LEN,/* A B R[A] := #R[B] (length operator) */
266
267OP_CONCAT,/* A B R[A] := R[A].. ... ..R[A + B - 1] */
268
269OP_CLOSE,/* A close all upvalues >= R[A] */
270OP_TBC,/* A mark variable A "to be closed" */
271OP_JMP,/* sJ pc += sJ */
272OP_EQ,/* A B k if ((R[A] == R[B]) ~= k) then pc++ */
273OP_LT,/* A B k if ((R[A] < R[B]) ~= k) then pc++ */
274OP_LE,/* A B k if ((R[A] <= R[B]) ~= k) then pc++ */
275
276OP_EQK,/* A B k if ((R[A] == K[B]) ~= k) then pc++ */
277OP_EQI,/* A sB k if ((R[A] == sB) ~= k) then pc++ */
278OP_LTI,/* A sB k if ((R[A] < sB) ~= k) then pc++ */
279OP_LEI,/* A sB k if ((R[A] <= sB) ~= k) then pc++ */
280OP_GTI,/* A sB k if ((R[A] > sB) ~= k) then pc++ */
281OP_GEI,/* A sB k if ((R[A] >= sB) ~= k) then pc++ */
282
283OP_TEST,/* A k if (not R[A] == k) then pc++ */
284OP_TESTSET,/* A B k if (not R[B] == k) then pc++ else R[A] := R[B] (*) */
285
286OP_CALL,/* A B C R[A], ... ,R[A+C-2] := R[A](R[A+1], ... ,R[A+B-1]) */
287OP_TAILCALL,/* A B C k return R[A](R[A+1], ... ,R[A+B-1]) */
288
289OP_RETURN,/* A B C k return R[A], ... ,R[A+B-2] (see note) */
290OP_RETURN0,/* return */
291OP_RETURN1,/* A return R[A] */
292
293OP_FORLOOP,/* A Bx update counters; if loop continues then pc-=Bx; */
294OP_FORPREP,/* A Bx <check values and prepare counters>;
295 if not to run then pc+=Bx+1; */
296
297OP_TFORPREP,/* A Bx create upvalue for R[A + 3]; pc+=Bx */
298OP_TFORCALL,/* A C R[A+4], ... ,R[A+3+C] := R[A](R[A+1], R[A+2]); */
299OP_TFORLOOP,/* A Bx if R[A+2] ~= nil then { R[A]=R[A+2]; pc -= Bx } */
300
301OP_SETLIST,/* A B C k R[A][C+i] := R[A+i], 1 <= i <= B */
302
303OP_CLOSURE,/* A Bx R[A] := closure(KPROTO[Bx]) */
304
305OP_VARARG,/* A C R[A], R[A+1], ..., R[A+C-2] = vararg */
306
307OP_VARARGPREP,/*A (adjust vararg parameters) */
308
309OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
310} OpCode;
311
312
313#define NUM_OPCODES ((int)(OP_EXTRAARG) + 1)
314
315
316
317/*===========================================================================
318 Notes:
319
320 (*) Opcode OP_LFALSESKIP is used to convert a condition to a boolean
321 value, in a code equivalent to (not cond ? false : true). (It
322 produces false and skips the next instruction producing true.)
323
324 (*) Opcodes OP_MMBIN and variants follow each arithmetic and
325 bitwise opcode. If the operation succeeds, it skips this next
326 opcode. Otherwise, this opcode calls the corresponding metamethod.
327
328 (*) Opcode OP_TESTSET is used in short-circuit expressions that need
329 both to jump and to produce a value, such as (a = b or c).
330
331 (*) In OP_CALL, if (B == 0) then B = top - A. If (C == 0), then
332 'top' is set to last_result+1, so next open instruction (OP_CALL,
333 OP_RETURN*, OP_SETLIST) may use 'top'.
334
335 (*) In OP_VARARG, if (C == 0) then use actual number of varargs and
336 set top (like in OP_CALL with C == 0).
337
338 (*) In OP_RETURN, if (B == 0) then return up to 'top'.
339
340 (*) In OP_LOADKX and OP_NEWTABLE, the next instruction is always
341 OP_EXTRAARG.
342
343 (*) In OP_SETLIST, if (B == 0) then real B = 'top'; if k, then
344 real C = EXTRAARG _ C (the bits of EXTRAARG concatenated with the
345 bits of C).
346
347 (*) In OP_NEWTABLE, B is log2 of the hash size (which is always a
348 power of 2) plus 1, or zero for size zero. If not k, the array size
349 is C. Otherwise, the array size is EXTRAARG _ C.
350
351 (*) For comparisons, k specifies what condition the test should accept
352 (true or false).
353
354 (*) In OP_MMBINI/OP_MMBINK, k means the arguments were flipped
355 (the constant is the first operand).
356
357 (*) All 'skips' (pc++) assume that next instruction is a jump.
358
359 (*) In instructions OP_RETURN/OP_TAILCALL, 'k' specifies that the
360 function builds upvalues, which may need to be closed. C > 0 means
361 the function is vararg, so that its 'func' must be corrected before
362 returning; in this case, (C - 1) is its number of fixed parameters.
363
364 (*) In comparisons with an immediate operand, C signals whether the
365 original operand was a float. (It must be corrected in case of
366 metamethods.)
367
368===========================================================================*/
369
370
371/*
372** masks for instruction properties. The format is:
373** bits 0-2: op mode
374** bit 3: instruction set register A
375** bit 4: operator is a test (next instruction must be a jump)
376** bit 5: instruction uses 'L->top' set by previous instruction (when B == 0)
377** bit 6: instruction sets 'L->top' for next instruction (when C == 0)
378** bit 7: instruction is an MM instruction (call a metamethod)
379*/
380
381LUAI_DDEC(const lu_byte luaP_opmodes[NUM_OPCODES];)
382
383#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 7))
384#define testAMode(m) (luaP_opmodes[m] & (1 << 3))
385#define testTMode(m) (luaP_opmodes[m] & (1 << 4))
386#define testITMode(m) (luaP_opmodes[m] & (1 << 5))
387#define testOTMode(m) (luaP_opmodes[m] & (1 << 6))
388#define testMMMode(m) (luaP_opmodes[m] & (1 << 7))
389
390/* "out top" (set top for next instruction) */
391#define isOT(i) \
392 ((testOTMode(GET_OPCODE(i)) && GETARG_C(i) == 0) || \
393 GET_OPCODE(i) == OP_TAILCALL)
394
395/* "in top" (uses top from previous instruction) */
396#define isIT(i) (testITMode(GET_OPCODE(i)) && GETARG_B(i) == 0)
397
398#define opmode(mm,ot,it,t,a,m) \
399 (((mm) << 7) | ((ot) << 6) | ((it) << 5) | ((t) << 4) | ((a) << 3) | (m))
400
401
402/* number of list items to accumulate before a SETLIST instruction */
403#define LFIELDS_PER_FLUSH 50
404
405#endif
diff --git a/vendor/lua-5.4.8/src/lopnames.h b/vendor/lua-5.4.8/src/lopnames.h
new file mode 100644
index 0000000..965cec9
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lopnames.h
@@ -0,0 +1,103 @@
1/*
2** $Id: lopnames.h $
3** Opcode names
4** See Copyright Notice in lua.h
5*/
6
7#if !defined(lopnames_h)
8#define lopnames_h
9
10#include <stddef.h>
11
12
13/* ORDER OP */
14
15static const char *const opnames[] = {
16 "MOVE",
17 "LOADI",
18 "LOADF",
19 "LOADK",
20 "LOADKX",
21 "LOADFALSE",
22 "LFALSESKIP",
23 "LOADTRUE",
24 "LOADNIL",
25 "GETUPVAL",
26 "SETUPVAL",
27 "GETTABUP",
28 "GETTABLE",
29 "GETI",
30 "GETFIELD",
31 "SETTABUP",
32 "SETTABLE",
33 "SETI",
34 "SETFIELD",
35 "NEWTABLE",
36 "SELF",
37 "ADDI",
38 "ADDK",
39 "SUBK",
40 "MULK",
41 "MODK",
42 "POWK",
43 "DIVK",
44 "IDIVK",
45 "BANDK",
46 "BORK",
47 "BXORK",
48 "SHRI",
49 "SHLI",
50 "ADD",
51 "SUB",
52 "MUL",
53 "MOD",
54 "POW",
55 "DIV",
56 "IDIV",
57 "BAND",
58 "BOR",
59 "BXOR",
60 "SHL",
61 "SHR",
62 "MMBIN",
63 "MMBINI",
64 "MMBINK",
65 "UNM",
66 "BNOT",
67 "NOT",
68 "LEN",
69 "CONCAT",
70 "CLOSE",
71 "TBC",
72 "JMP",
73 "EQ",
74 "LT",
75 "LE",
76 "EQK",
77 "EQI",
78 "LTI",
79 "LEI",
80 "GTI",
81 "GEI",
82 "TEST",
83 "TESTSET",
84 "CALL",
85 "TAILCALL",
86 "RETURN",
87 "RETURN0",
88 "RETURN1",
89 "FORLOOP",
90 "FORPREP",
91 "TFORPREP",
92 "TFORCALL",
93 "TFORLOOP",
94 "SETLIST",
95 "CLOSURE",
96 "VARARG",
97 "VARARGPREP",
98 "EXTRAARG",
99 NULL
100};
101
102#endif
103
diff --git a/vendor/lua-5.4.8/src/loslib.c b/vendor/lua-5.4.8/src/loslib.c
new file mode 100644
index 0000000..ba80d72
--- /dev/null
+++ b/vendor/lua-5.4.8/src/loslib.c
@@ -0,0 +1,430 @@
1/*
2** $Id: loslib.c $
3** Standard Operating System library
4** See Copyright Notice in lua.h
5*/
6
7#define loslib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <errno.h>
14#include <locale.h>
15#include <stdlib.h>
16#include <string.h>
17#include <time.h>
18
19#include "lua.h"
20
21#include "lauxlib.h"
22#include "lualib.h"
23
24
25/*
26** {==================================================================
27** List of valid conversion specifiers for the 'strftime' function;
28** options are grouped by length; group of length 2 start with '||'.
29** ===================================================================
30*/
31#if !defined(LUA_STRFTIMEOPTIONS) /* { */
32
33#if defined(LUA_USE_WINDOWS)
34#define LUA_STRFTIMEOPTIONS "aAbBcdHIjmMpSUwWxXyYzZ%" \
35 "||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y" /* two-char options */
36#elif defined(LUA_USE_C89) /* ANSI C 89 (only 1-char options) */
37#define LUA_STRFTIMEOPTIONS "aAbBcdHIjmMpSUwWxXyYZ%"
38#else /* C99 specification */
39#define LUA_STRFTIMEOPTIONS "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \
40 "||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */
41#endif
42
43#endif /* } */
44/* }================================================================== */
45
46
47/*
48** {==================================================================
49** Configuration for time-related stuff
50** ===================================================================
51*/
52
53/*
54** type to represent time_t in Lua
55*/
56#if !defined(LUA_NUMTIME) /* { */
57
58#define l_timet lua_Integer
59#define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t))
60#define l_gettime(L,arg) luaL_checkinteger(L, arg)
61
62#else /* }{ */
63
64#define l_timet lua_Number
65#define l_pushtime(L,t) lua_pushnumber(L,(lua_Number)(t))
66#define l_gettime(L,arg) luaL_checknumber(L, arg)
67
68#endif /* } */
69
70
71#if !defined(l_gmtime) /* { */
72/*
73** By default, Lua uses gmtime/localtime, except when POSIX is available,
74** where it uses gmtime_r/localtime_r
75*/
76
77#if defined(LUA_USE_POSIX) /* { */
78
79#define l_gmtime(t,r) gmtime_r(t,r)
80#define l_localtime(t,r) localtime_r(t,r)
81
82#else /* }{ */
83
84/* ISO C definitions */
85#define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t))
86#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t))
87
88#endif /* } */
89
90#endif /* } */
91
92/* }================================================================== */
93
94
95/*
96** {==================================================================
97** Configuration for 'tmpnam':
98** By default, Lua uses tmpnam except when POSIX is available, where
99** it uses mkstemp.
100** ===================================================================
101*/
102#if !defined(lua_tmpnam) /* { */
103
104#if defined(LUA_USE_POSIX) /* { */
105
106#include <unistd.h>
107
108#define LUA_TMPNAMBUFSIZE 32
109
110#if !defined(LUA_TMPNAMTEMPLATE)
111#define LUA_TMPNAMTEMPLATE "/tmp/lua_XXXXXX"
112#endif
113
114#define lua_tmpnam(b,e) { \
115 strcpy(b, LUA_TMPNAMTEMPLATE); \
116 e = mkstemp(b); \
117 if (e != -1) close(e); \
118 e = (e == -1); }
119
120#else /* }{ */
121
122/* ISO C definitions */
123#define LUA_TMPNAMBUFSIZE L_tmpnam
124#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); }
125
126#endif /* } */
127
128#endif /* } */
129/* }================================================================== */
130
131
132#if !defined(l_system)
133#if defined(LUA_USE_IOS)
134/* Despite claiming to be ISO C, iOS does not implement 'system'. */
135#define l_system(cmd) ((cmd) == NULL ? 0 : -1)
136#else
137#define l_system(cmd) system(cmd) /* default definition */
138#endif
139#endif
140
141
142static int os_execute (lua_State *L) {
143 const char *cmd = luaL_optstring(L, 1, NULL);
144 int stat;
145 errno = 0;
146 stat = l_system(cmd);
147 if (cmd != NULL)
148 return luaL_execresult(L, stat);
149 else {
150 lua_pushboolean(L, stat); /* true if there is a shell */
151 return 1;
152 }
153}
154
155
156static int os_remove (lua_State *L) {
157 const char *filename = luaL_checkstring(L, 1);
158 errno = 0;
159 return luaL_fileresult(L, remove(filename) == 0, filename);
160}
161
162
163static int os_rename (lua_State *L) {
164 const char *fromname = luaL_checkstring(L, 1);
165 const char *toname = luaL_checkstring(L, 2);
166 errno = 0;
167 return luaL_fileresult(L, rename(fromname, toname) == 0, NULL);
168}
169
170
171static int os_tmpname (lua_State *L) {
172 char buff[LUA_TMPNAMBUFSIZE];
173 int err;
174 lua_tmpnam(buff, err);
175 if (l_unlikely(err))
176 return luaL_error(L, "unable to generate a unique filename");
177 lua_pushstring(L, buff);
178 return 1;
179}
180
181
182static int os_getenv (lua_State *L) {
183 lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */
184 return 1;
185}
186
187
188static int os_clock (lua_State *L) {
189 lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
190 return 1;
191}
192
193
194/*
195** {======================================================
196** Time/Date operations
197** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
198** wday=%w+1, yday=%j, isdst=? }
199** =======================================================
200*/
201
202/*
203** About the overflow check: an overflow cannot occur when time
204** is represented by a lua_Integer, because either lua_Integer is
205** large enough to represent all int fields or it is not large enough
206** to represent a time that cause a field to overflow. However, if
207** times are represented as doubles and lua_Integer is int, then the
208** time 0x1.e1853b0d184f6p+55 would cause an overflow when adding 1900
209** to compute the year.
210*/
211static void setfield (lua_State *L, const char *key, int value, int delta) {
212 #if (defined(LUA_NUMTIME) && LUA_MAXINTEGER <= INT_MAX)
213 if (l_unlikely(value > LUA_MAXINTEGER - delta))
214 luaL_error(L, "field '%s' is out-of-bound", key);
215 #endif
216 lua_pushinteger(L, (lua_Integer)value + delta);
217 lua_setfield(L, -2, key);
218}
219
220
221static void setboolfield (lua_State *L, const char *key, int value) {
222 if (value < 0) /* undefined? */
223 return; /* does not set field */
224 lua_pushboolean(L, value);
225 lua_setfield(L, -2, key);
226}
227
228
229/*
230** Set all fields from structure 'tm' in the table on top of the stack
231*/
232static void setallfields (lua_State *L, struct tm *stm) {
233 setfield(L, "year", stm->tm_year, 1900);
234 setfield(L, "month", stm->tm_mon, 1);
235 setfield(L, "day", stm->tm_mday, 0);
236 setfield(L, "hour", stm->tm_hour, 0);
237 setfield(L, "min", stm->tm_min, 0);
238 setfield(L, "sec", stm->tm_sec, 0);
239 setfield(L, "yday", stm->tm_yday, 1);
240 setfield(L, "wday", stm->tm_wday, 1);
241 setboolfield(L, "isdst", stm->tm_isdst);
242}
243
244
245static int getboolfield (lua_State *L, const char *key) {
246 int res;
247 res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
248 lua_pop(L, 1);
249 return res;
250}
251
252
253static int getfield (lua_State *L, const char *key, int d, int delta) {
254 int isnum;
255 int t = lua_getfield(L, -1, key); /* get field and its type */
256 lua_Integer res = lua_tointegerx(L, -1, &isnum);
257 if (!isnum) { /* field is not an integer? */
258 if (l_unlikely(t != LUA_TNIL)) /* some other value? */
259 return luaL_error(L, "field '%s' is not an integer", key);
260 else if (l_unlikely(d < 0)) /* absent field; no default? */
261 return luaL_error(L, "field '%s' missing in date table", key);
262 res = d;
263 }
264 else {
265 if (!(res >= 0 ? res - delta <= INT_MAX : INT_MIN + delta <= res))
266 return luaL_error(L, "field '%s' is out-of-bound", key);
267 res -= delta;
268 }
269 lua_pop(L, 1);
270 return (int)res;
271}
272
273
274static const char *checkoption (lua_State *L, const char *conv,
275 ptrdiff_t convlen, char *buff) {
276 const char *option = LUA_STRFTIMEOPTIONS;
277 int oplen = 1; /* length of options being checked */
278 for (; *option != '\0' && oplen <= convlen; option += oplen) {
279 if (*option == '|') /* next block? */
280 oplen++; /* will check options with next length (+1) */
281 else if (memcmp(conv, option, oplen) == 0) { /* match? */
282 memcpy(buff, conv, oplen); /* copy valid option to buffer */
283 buff[oplen] = '\0';
284 return conv + oplen; /* return next item */
285 }
286 }
287 luaL_argerror(L, 1,
288 lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv));
289 return conv; /* to avoid warnings */
290}
291
292
293static time_t l_checktime (lua_State *L, int arg) {
294 l_timet t = l_gettime(L, arg);
295 luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds");
296 return (time_t)t;
297}
298
299
300/* maximum size for an individual 'strftime' item */
301#define SIZETIMEFMT 250
302
303
304static int os_date (lua_State *L) {
305 size_t slen;
306 const char *s = luaL_optlstring(L, 1, "%c", &slen);
307 time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
308 const char *se = s + slen; /* 's' end */
309 struct tm tmr, *stm;
310 if (*s == '!') { /* UTC? */
311 stm = l_gmtime(&t, &tmr);
312 s++; /* skip '!' */
313 }
314 else
315 stm = l_localtime(&t, &tmr);
316 if (stm == NULL) /* invalid date? */
317 return luaL_error(L,
318 "date result cannot be represented in this installation");
319 if (strcmp(s, "*t") == 0) {
320 lua_createtable(L, 0, 9); /* 9 = number of fields */
321 setallfields(L, stm);
322 }
323 else {
324 char cc[4]; /* buffer for individual conversion specifiers */
325 luaL_Buffer b;
326 cc[0] = '%';
327 luaL_buffinit(L, &b);
328 while (s < se) {
329 if (*s != '%') /* not a conversion specifier? */
330 luaL_addchar(&b, *s++);
331 else {
332 size_t reslen;
333 char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT);
334 s++; /* skip '%' */
335 s = checkoption(L, s, se - s, cc + 1); /* copy specifier to 'cc' */
336 reslen = strftime(buff, SIZETIMEFMT, cc, stm);
337 luaL_addsize(&b, reslen);
338 }
339 }
340 luaL_pushresult(&b);
341 }
342 return 1;
343}
344
345
346static int os_time (lua_State *L) {
347 time_t t;
348 if (lua_isnoneornil(L, 1)) /* called without args? */
349 t = time(NULL); /* get current time */
350 else {
351 struct tm ts;
352 luaL_checktype(L, 1, LUA_TTABLE);
353 lua_settop(L, 1); /* make sure table is at the top */
354 ts.tm_year = getfield(L, "year", -1, 1900);
355 ts.tm_mon = getfield(L, "month", -1, 1);
356 ts.tm_mday = getfield(L, "day", -1, 0);
357 ts.tm_hour = getfield(L, "hour", 12, 0);
358 ts.tm_min = getfield(L, "min", 0, 0);
359 ts.tm_sec = getfield(L, "sec", 0, 0);
360 ts.tm_isdst = getboolfield(L, "isdst");
361 t = mktime(&ts);
362 setallfields(L, &ts); /* update fields with normalized values */
363 }
364 if (t != (time_t)(l_timet)t || t == (time_t)(-1))
365 return luaL_error(L,
366 "time result cannot be represented in this installation");
367 l_pushtime(L, t);
368 return 1;
369}
370
371
372static int os_difftime (lua_State *L) {
373 time_t t1 = l_checktime(L, 1);
374 time_t t2 = l_checktime(L, 2);
375 lua_pushnumber(L, (lua_Number)difftime(t1, t2));
376 return 1;
377}
378
379/* }====================================================== */
380
381
382static int os_setlocale (lua_State *L) {
383 static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
384 LC_NUMERIC, LC_TIME};
385 static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
386 "numeric", "time", NULL};
387 const char *l = luaL_optstring(L, 1, NULL);
388 int op = luaL_checkoption(L, 2, "all", catnames);
389 lua_pushstring(L, setlocale(cat[op], l));
390 return 1;
391}
392
393
394static int os_exit (lua_State *L) {
395 int status;
396 if (lua_isboolean(L, 1))
397 status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
398 else
399 status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
400 if (lua_toboolean(L, 2))
401 lua_close(L);
402 if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */
403 return 0;
404}
405
406
407static const luaL_Reg syslib[] = {
408 {"clock", os_clock},
409 {"date", os_date},
410 {"difftime", os_difftime},
411 {"execute", os_execute},
412 {"exit", os_exit},
413 {"getenv", os_getenv},
414 {"remove", os_remove},
415 {"rename", os_rename},
416 {"setlocale", os_setlocale},
417 {"time", os_time},
418 {"tmpname", os_tmpname},
419 {NULL, NULL}
420};
421
422/* }====================================================== */
423
424
425
426LUAMOD_API int luaopen_os (lua_State *L) {
427 luaL_newlib(L, syslib);
428 return 1;
429}
430
diff --git a/vendor/lua-5.4.8/src/lparser.c b/vendor/lua-5.4.8/src/lparser.c
new file mode 100644
index 0000000..1ac8299
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lparser.c
@@ -0,0 +1,1966 @@
1/*
2** $Id: lparser.c $
3** Lua Parser
4** See Copyright Notice in lua.h
5*/
6
7#define lparser_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <limits.h>
14#include <string.h>
15
16#include "lua.h"
17
18#include "lcode.h"
19#include "ldebug.h"
20#include "ldo.h"
21#include "lfunc.h"
22#include "llex.h"
23#include "lmem.h"
24#include "lobject.h"
25#include "lopcodes.h"
26#include "lparser.h"
27#include "lstate.h"
28#include "lstring.h"
29#include "ltable.h"
30
31
32
33/* maximum number of local variables per function (must be smaller
34 than 250, due to the bytecode format) */
35#define MAXVARS 200
36
37
38#define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
39
40
41/* because all strings are unified by the scanner, the parser
42 can use pointer equality for string equality */
43#define eqstr(a,b) ((a) == (b))
44
45
46/*
47** nodes for block list (list of active blocks)
48*/
49typedef struct BlockCnt {
50 struct BlockCnt *previous; /* chain */
51 int firstlabel; /* index of first label in this block */
52 int firstgoto; /* index of first pending goto in this block */
53 lu_byte nactvar; /* # active locals outside the block */
54 lu_byte upval; /* true if some variable in the block is an upvalue */
55 lu_byte isloop; /* true if 'block' is a loop */
56 lu_byte insidetbc; /* true if inside the scope of a to-be-closed var. */
57} BlockCnt;
58
59
60
61/*
62** prototypes for recursive non-terminal functions
63*/
64static void statement (LexState *ls);
65static void expr (LexState *ls, expdesc *v);
66
67
68static l_noret error_expected (LexState *ls, int token) {
69 luaX_syntaxerror(ls,
70 luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
71}
72
73
74static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
75 lua_State *L = fs->ls->L;
76 const char *msg;
77 int line = fs->f->linedefined;
78 const char *where = (line == 0)
79 ? "main function"
80 : luaO_pushfstring(L, "function at line %d", line);
81 msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
82 what, limit, where);
83 luaX_syntaxerror(fs->ls, msg);
84}
85
86
87static void checklimit (FuncState *fs, int v, int l, const char *what) {
88 if (v > l) errorlimit(fs, l, what);
89}
90
91
92/*
93** Test whether next token is 'c'; if so, skip it.
94*/
95static int testnext (LexState *ls, int c) {
96 if (ls->t.token == c) {
97 luaX_next(ls);
98 return 1;
99 }
100 else return 0;
101}
102
103
104/*
105** Check that next token is 'c'.
106*/
107static void check (LexState *ls, int c) {
108 if (ls->t.token != c)
109 error_expected(ls, c);
110}
111
112
113/*
114** Check that next token is 'c' and skip it.
115*/
116static void checknext (LexState *ls, int c) {
117 check(ls, c);
118 luaX_next(ls);
119}
120
121
122#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
123
124
125/*
126** Check that next token is 'what' and skip it. In case of error,
127** raise an error that the expected 'what' should match a 'who'
128** in line 'where' (if that is not the current line).
129*/
130static void check_match (LexState *ls, int what, int who, int where) {
131 if (l_unlikely(!testnext(ls, what))) {
132 if (where == ls->linenumber) /* all in the same line? */
133 error_expected(ls, what); /* do not need a complex message */
134 else {
135 luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
136 "%s expected (to close %s at line %d)",
137 luaX_token2str(ls, what), luaX_token2str(ls, who), where));
138 }
139 }
140}
141
142
143static TString *str_checkname (LexState *ls) {
144 TString *ts;
145 check(ls, TK_NAME);
146 ts = ls->t.seminfo.ts;
147 luaX_next(ls);
148 return ts;
149}
150
151
152static void init_exp (expdesc *e, expkind k, int i) {
153 e->f = e->t = NO_JUMP;
154 e->k = k;
155 e->u.info = i;
156}
157
158
159static void codestring (expdesc *e, TString *s) {
160 e->f = e->t = NO_JUMP;
161 e->k = VKSTR;
162 e->u.strval = s;
163}
164
165
166static void codename (LexState *ls, expdesc *e) {
167 codestring(e, str_checkname(ls));
168}
169
170
171/*
172** Register a new local variable in the active 'Proto' (for debug
173** information).
174*/
175static int registerlocalvar (LexState *ls, FuncState *fs, TString *varname) {
176 Proto *f = fs->f;
177 int oldsize = f->sizelocvars;
178 luaM_growvector(ls->L, f->locvars, fs->ndebugvars, f->sizelocvars,
179 LocVar, SHRT_MAX, "local variables");
180 while (oldsize < f->sizelocvars)
181 f->locvars[oldsize++].varname = NULL;
182 f->locvars[fs->ndebugvars].varname = varname;
183 f->locvars[fs->ndebugvars].startpc = fs->pc;
184 luaC_objbarrier(ls->L, f, varname);
185 return fs->ndebugvars++;
186}
187
188
189/*
190** Create a new local variable with the given 'name'. Return its index
191** in the function.
192*/
193static int new_localvar (LexState *ls, TString *name) {
194 lua_State *L = ls->L;
195 FuncState *fs = ls->fs;
196 Dyndata *dyd = ls->dyd;
197 Vardesc *var;
198 checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
199 MAXVARS, "local variables");
200 luaM_growvector(L, dyd->actvar.arr, dyd->actvar.n + 1,
201 dyd->actvar.size, Vardesc, SHRT_MAX, "local variables");
202 var = &dyd->actvar.arr[dyd->actvar.n++];
203 var->vd.kind = VDKREG; /* default */
204 var->vd.name = name;
205 return dyd->actvar.n - 1 - fs->firstlocal;
206}
207
208#define new_localvarliteral(ls,v) \
209 new_localvar(ls, \
210 luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1));
211
212
213
214/*
215** Return the "variable description" (Vardesc) of a given variable.
216** (Unless noted otherwise, all variables are referred to by their
217** compiler indices.)
218*/
219static Vardesc *getlocalvardesc (FuncState *fs, int vidx) {
220 return &fs->ls->dyd->actvar.arr[fs->firstlocal + vidx];
221}
222
223
224/*
225** Convert 'nvar', a compiler index level, to its corresponding
226** register. For that, search for the highest variable below that level
227** that is in a register and uses its register index ('ridx') plus one.
228*/
229static int reglevel (FuncState *fs, int nvar) {
230 while (nvar-- > 0) {
231 Vardesc *vd = getlocalvardesc(fs, nvar); /* get previous variable */
232 if (vd->vd.kind != RDKCTC) /* is in a register? */
233 return vd->vd.ridx + 1;
234 }
235 return 0; /* no variables in registers */
236}
237
238
239/*
240** Return the number of variables in the register stack for the given
241** function.
242*/
243int luaY_nvarstack (FuncState *fs) {
244 return reglevel(fs, fs->nactvar);
245}
246
247
248/*
249** Get the debug-information entry for current variable 'vidx'.
250*/
251static LocVar *localdebuginfo (FuncState *fs, int vidx) {
252 Vardesc *vd = getlocalvardesc(fs, vidx);
253 if (vd->vd.kind == RDKCTC)
254 return NULL; /* no debug info. for constants */
255 else {
256 int idx = vd->vd.pidx;
257 lua_assert(idx < fs->ndebugvars);
258 return &fs->f->locvars[idx];
259 }
260}
261
262
263/*
264** Create an expression representing variable 'vidx'
265*/
266static void init_var (FuncState *fs, expdesc *e, int vidx) {
267 e->f = e->t = NO_JUMP;
268 e->k = VLOCAL;
269 e->u.var.vidx = vidx;
270 e->u.var.ridx = getlocalvardesc(fs, vidx)->vd.ridx;
271}
272
273
274/*
275** Raises an error if variable described by 'e' is read only
276*/
277static void check_readonly (LexState *ls, expdesc *e) {
278 FuncState *fs = ls->fs;
279 TString *varname = NULL; /* to be set if variable is const */
280 switch (e->k) {
281 case VCONST: {
282 varname = ls->dyd->actvar.arr[e->u.info].vd.name;
283 break;
284 }
285 case VLOCAL: {
286 Vardesc *vardesc = getlocalvardesc(fs, e->u.var.vidx);
287 if (vardesc->vd.kind != VDKREG) /* not a regular variable? */
288 varname = vardesc->vd.name;
289 break;
290 }
291 case VUPVAL: {
292 Upvaldesc *up = &fs->f->upvalues[e->u.info];
293 if (up->kind != VDKREG)
294 varname = up->name;
295 break;
296 }
297 default:
298 return; /* other cases cannot be read-only */
299 }
300 if (varname) {
301 const char *msg = luaO_pushfstring(ls->L,
302 "attempt to assign to const variable '%s'", getstr(varname));
303 luaK_semerror(ls, msg); /* error */
304 }
305}
306
307
308/*
309** Start the scope for the last 'nvars' created variables.
310*/
311static void adjustlocalvars (LexState *ls, int nvars) {
312 FuncState *fs = ls->fs;
313 int reglevel = luaY_nvarstack(fs);
314 int i;
315 for (i = 0; i < nvars; i++) {
316 int vidx = fs->nactvar++;
317 Vardesc *var = getlocalvardesc(fs, vidx);
318 var->vd.ridx = reglevel++;
319 var->vd.pidx = registerlocalvar(ls, fs, var->vd.name);
320 }
321}
322
323
324/*
325** Close the scope for all variables up to level 'tolevel'.
326** (debug info.)
327*/
328static void removevars (FuncState *fs, int tolevel) {
329 fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
330 while (fs->nactvar > tolevel) {
331 LocVar *var = localdebuginfo(fs, --fs->nactvar);
332 if (var) /* does it have debug information? */
333 var->endpc = fs->pc;
334 }
335}
336
337
338/*
339** Search the upvalues of the function 'fs' for one
340** with the given 'name'.
341*/
342static int searchupvalue (FuncState *fs, TString *name) {
343 int i;
344 Upvaldesc *up = fs->f->upvalues;
345 for (i = 0; i < fs->nups; i++) {
346 if (eqstr(up[i].name, name)) return i;
347 }
348 return -1; /* not found */
349}
350
351
352static Upvaldesc *allocupvalue (FuncState *fs) {
353 Proto *f = fs->f;
354 int oldsize = f->sizeupvalues;
355 checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
356 luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
357 Upvaldesc, MAXUPVAL, "upvalues");
358 while (oldsize < f->sizeupvalues)
359 f->upvalues[oldsize++].name = NULL;
360 return &f->upvalues[fs->nups++];
361}
362
363
364static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
365 Upvaldesc *up = allocupvalue(fs);
366 FuncState *prev = fs->prev;
367 if (v->k == VLOCAL) {
368 up->instack = 1;
369 up->idx = v->u.var.ridx;
370 up->kind = getlocalvardesc(prev, v->u.var.vidx)->vd.kind;
371 lua_assert(eqstr(name, getlocalvardesc(prev, v->u.var.vidx)->vd.name));
372 }
373 else {
374 up->instack = 0;
375 up->idx = cast_byte(v->u.info);
376 up->kind = prev->f->upvalues[v->u.info].kind;
377 lua_assert(eqstr(name, prev->f->upvalues[v->u.info].name));
378 }
379 up->name = name;
380 luaC_objbarrier(fs->ls->L, fs->f, name);
381 return fs->nups - 1;
382}
383
384
385/*
386** Look for an active local variable with the name 'n' in the
387** function 'fs'. If found, initialize 'var' with it and return
388** its expression kind; otherwise return -1.
389*/
390static int searchvar (FuncState *fs, TString *n, expdesc *var) {
391 int i;
392 for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
393 Vardesc *vd = getlocalvardesc(fs, i);
394 if (eqstr(n, vd->vd.name)) { /* found? */
395 if (vd->vd.kind == RDKCTC) /* compile-time constant? */
396 init_exp(var, VCONST, fs->firstlocal + i);
397 else /* real variable */
398 init_var(fs, var, i);
399 return var->k;
400 }
401 }
402 return -1; /* not found */
403}
404
405
406/*
407** Mark block where variable at given level was defined
408** (to emit close instructions later).
409*/
410static void markupval (FuncState *fs, int level) {
411 BlockCnt *bl = fs->bl;
412 while (bl->nactvar > level)
413 bl = bl->previous;
414 bl->upval = 1;
415 fs->needclose = 1;
416}
417
418
419/*
420** Mark that current block has a to-be-closed variable.
421*/
422static void marktobeclosed (FuncState *fs) {
423 BlockCnt *bl = fs->bl;
424 bl->upval = 1;
425 bl->insidetbc = 1;
426 fs->needclose = 1;
427}
428
429
430/*
431** Find a variable with the given name 'n'. If it is an upvalue, add
432** this upvalue into all intermediate functions. If it is a global, set
433** 'var' as 'void' as a flag.
434*/
435static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
436 if (fs == NULL) /* no more levels? */
437 init_exp(var, VVOID, 0); /* default is global */
438 else {
439 int v = searchvar(fs, n, var); /* look up locals at current level */
440 if (v >= 0) { /* found? */
441 if (v == VLOCAL && !base)
442 markupval(fs, var->u.var.vidx); /* local will be used as an upval */
443 }
444 else { /* not found as local at current level; try upvalues */
445 int idx = searchupvalue(fs, n); /* try existing upvalues */
446 if (idx < 0) { /* not found? */
447 singlevaraux(fs->prev, n, var, 0); /* try upper levels */
448 if (var->k == VLOCAL || var->k == VUPVAL) /* local or upvalue? */
449 idx = newupvalue(fs, n, var); /* will be a new upvalue */
450 else /* it is a global or a constant */
451 return; /* don't need to do anything at this level */
452 }
453 init_exp(var, VUPVAL, idx); /* new or old upvalue */
454 }
455 }
456}
457
458
459/*
460** Find a variable with the given name 'n', handling global variables
461** too.
462*/
463static void singlevar (LexState *ls, expdesc *var) {
464 TString *varname = str_checkname(ls);
465 FuncState *fs = ls->fs;
466 singlevaraux(fs, varname, var, 1);
467 if (var->k == VVOID) { /* global name? */
468 expdesc key;
469 singlevaraux(fs, ls->envn, var, 1); /* get environment variable */
470 lua_assert(var->k != VVOID); /* this one must exist */
471 luaK_exp2anyregup(fs, var); /* but could be a constant */
472 codestring(&key, varname); /* key is variable name */
473 luaK_indexed(fs, var, &key); /* env[varname] */
474 }
475}
476
477
478/*
479** Adjust the number of results from an expression list 'e' with 'nexps'
480** expressions to 'nvars' values.
481*/
482static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
483 FuncState *fs = ls->fs;
484 int needed = nvars - nexps; /* extra values needed */
485 if (hasmultret(e->k)) { /* last expression has multiple returns? */
486 int extra = needed + 1; /* discount last expression itself */
487 if (extra < 0)
488 extra = 0;
489 luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
490 }
491 else {
492 if (e->k != VVOID) /* at least one expression? */
493 luaK_exp2nextreg(fs, e); /* close last expression */
494 if (needed > 0) /* missing values? */
495 luaK_nil(fs, fs->freereg, needed); /* complete with nils */
496 }
497 if (needed > 0)
498 luaK_reserveregs(fs, needed); /* registers for extra values */
499 else /* adding 'needed' is actually a subtraction */
500 fs->freereg += needed; /* remove extra values */
501}
502
503
504#define enterlevel(ls) luaE_incCstack(ls->L)
505
506
507#define leavelevel(ls) ((ls)->L->nCcalls--)
508
509
510/*
511** Generates an error that a goto jumps into the scope of some
512** local variable.
513*/
514static l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) {
515 const char *varname = getstr(getlocalvardesc(ls->fs, gt->nactvar)->vd.name);
516 const char *msg = "<goto %s> at line %d jumps into the scope of local '%s'";
517 msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line, varname);
518 luaK_semerror(ls, msg); /* raise the error */
519}
520
521
522/*
523** Solves the goto at index 'g' to given 'label' and removes it
524** from the list of pending gotos.
525** If it jumps into the scope of some variable, raises an error.
526*/
527static void solvegoto (LexState *ls, int g, Labeldesc *label) {
528 int i;
529 Labellist *gl = &ls->dyd->gt; /* list of gotos */
530 Labeldesc *gt = &gl->arr[g]; /* goto to be resolved */
531 lua_assert(eqstr(gt->name, label->name));
532 if (l_unlikely(gt->nactvar < label->nactvar)) /* enter some scope? */
533 jumpscopeerror(ls, gt);
534 luaK_patchlist(ls->fs, gt->pc, label->pc);
535 for (i = g; i < gl->n - 1; i++) /* remove goto from pending list */
536 gl->arr[i] = gl->arr[i + 1];
537 gl->n--;
538}
539
540
541/*
542** Search for an active label with the given name.
543*/
544static Labeldesc *findlabel (LexState *ls, TString *name) {
545 int i;
546 Dyndata *dyd = ls->dyd;
547 /* check labels in current function for a match */
548 for (i = ls->fs->firstlabel; i < dyd->label.n; i++) {
549 Labeldesc *lb = &dyd->label.arr[i];
550 if (eqstr(lb->name, name)) /* correct label? */
551 return lb;
552 }
553 return NULL; /* label not found */
554}
555
556
557/*
558** Adds a new label/goto in the corresponding list.
559*/
560static int newlabelentry (LexState *ls, Labellist *l, TString *name,
561 int line, int pc) {
562 int n = l->n;
563 luaM_growvector(ls->L, l->arr, n, l->size,
564 Labeldesc, SHRT_MAX, "labels/gotos");
565 l->arr[n].name = name;
566 l->arr[n].line = line;
567 l->arr[n].nactvar = ls->fs->nactvar;
568 l->arr[n].close = 0;
569 l->arr[n].pc = pc;
570 l->n = n + 1;
571 return n;
572}
573
574
575static int newgotoentry (LexState *ls, TString *name, int line, int pc) {
576 return newlabelentry(ls, &ls->dyd->gt, name, line, pc);
577}
578
579
580/*
581** Solves forward jumps. Check whether new label 'lb' matches any
582** pending gotos in current block and solves them. Return true
583** if any of the gotos need to close upvalues.
584*/
585static int solvegotos (LexState *ls, Labeldesc *lb) {
586 Labellist *gl = &ls->dyd->gt;
587 int i = ls->fs->bl->firstgoto;
588 int needsclose = 0;
589 while (i < gl->n) {
590 if (eqstr(gl->arr[i].name, lb->name)) {
591 needsclose |= gl->arr[i].close;
592 solvegoto(ls, i, lb); /* will remove 'i' from the list */
593 }
594 else
595 i++;
596 }
597 return needsclose;
598}
599
600
601/*
602** Create a new label with the given 'name' at the given 'line'.
603** 'last' tells whether label is the last non-op statement in its
604** block. Solves all pending gotos to this new label and adds
605** a close instruction if necessary.
606** Returns true iff it added a close instruction.
607*/
608static int createlabel (LexState *ls, TString *name, int line,
609 int last) {
610 FuncState *fs = ls->fs;
611 Labellist *ll = &ls->dyd->label;
612 int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs));
613 if (last) { /* label is last no-op statement in the block? */
614 /* assume that locals are already out of scope */
615 ll->arr[l].nactvar = fs->bl->nactvar;
616 }
617 if (solvegotos(ls, &ll->arr[l])) { /* need close? */
618 luaK_codeABC(fs, OP_CLOSE, luaY_nvarstack(fs), 0, 0);
619 return 1;
620 }
621 return 0;
622}
623
624
625/*
626** Adjust pending gotos to outer level of a block.
627*/
628static void movegotosout (FuncState *fs, BlockCnt *bl) {
629 int i;
630 Labellist *gl = &fs->ls->dyd->gt;
631 /* correct pending gotos to current block */
632 for (i = bl->firstgoto; i < gl->n; i++) { /* for each pending goto */
633 Labeldesc *gt = &gl->arr[i];
634 /* leaving a variable scope? */
635 if (reglevel(fs, gt->nactvar) > reglevel(fs, bl->nactvar))
636 gt->close |= bl->upval; /* jump may need a close */
637 gt->nactvar = bl->nactvar; /* update goto level */
638 }
639}
640
641
642static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
643 bl->isloop = isloop;
644 bl->nactvar = fs->nactvar;
645 bl->firstlabel = fs->ls->dyd->label.n;
646 bl->firstgoto = fs->ls->dyd->gt.n;
647 bl->upval = 0;
648 bl->insidetbc = (fs->bl != NULL && fs->bl->insidetbc);
649 bl->previous = fs->bl;
650 fs->bl = bl;
651 lua_assert(fs->freereg == luaY_nvarstack(fs));
652}
653
654
655/*
656** generates an error for an undefined 'goto'.
657*/
658static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
659 const char *msg;
660 if (eqstr(gt->name, luaS_newliteral(ls->L, "break"))) {
661 msg = "break outside loop at line %d";
662 msg = luaO_pushfstring(ls->L, msg, gt->line);
663 }
664 else {
665 msg = "no visible label '%s' for <goto> at line %d";
666 msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
667 }
668 luaK_semerror(ls, msg);
669}
670
671
672static void leaveblock (FuncState *fs) {
673 BlockCnt *bl = fs->bl;
674 LexState *ls = fs->ls;
675 int hasclose = 0;
676 int stklevel = reglevel(fs, bl->nactvar); /* level outside the block */
677 removevars(fs, bl->nactvar); /* remove block locals */
678 lua_assert(bl->nactvar == fs->nactvar); /* back to level on entry */
679 if (bl->isloop) /* has to fix pending breaks? */
680 hasclose = createlabel(ls, luaS_newliteral(ls->L, "break"), 0, 0);
681 if (!hasclose && bl->previous && bl->upval) /* still need a 'close'? */
682 luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0);
683 fs->freereg = stklevel; /* free registers */
684 ls->dyd->label.n = bl->firstlabel; /* remove local labels */
685 fs->bl = bl->previous; /* current block now is previous one */
686 if (bl->previous) /* was it a nested block? */
687 movegotosout(fs, bl); /* update pending gotos to enclosing block */
688 else {
689 if (bl->firstgoto < ls->dyd->gt.n) /* still pending gotos? */
690 undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
691 }
692}
693
694
695/*
696** adds a new prototype into list of prototypes
697*/
698static Proto *addprototype (LexState *ls) {
699 Proto *clp;
700 lua_State *L = ls->L;
701 FuncState *fs = ls->fs;
702 Proto *f = fs->f; /* prototype of current function */
703 if (fs->np >= f->sizep) {
704 int oldsize = f->sizep;
705 luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
706 while (oldsize < f->sizep)
707 f->p[oldsize++] = NULL;
708 }
709 f->p[fs->np++] = clp = luaF_newproto(L);
710 luaC_objbarrier(L, f, clp);
711 return clp;
712}
713
714
715/*
716** codes instruction to create new closure in parent function.
717** The OP_CLOSURE instruction uses the last available register,
718** so that, if it invokes the GC, the GC knows which registers
719** are in use at that time.
720
721*/
722static void codeclosure (LexState *ls, expdesc *v) {
723 FuncState *fs = ls->fs->prev;
724 init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
725 luaK_exp2nextreg(fs, v); /* fix it at the last register */
726}
727
728
729static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
730 Proto *f = fs->f;
731 fs->prev = ls->fs; /* linked list of funcstates */
732 fs->ls = ls;
733 ls->fs = fs;
734 fs->pc = 0;
735 fs->previousline = f->linedefined;
736 fs->iwthabs = 0;
737 fs->lasttarget = 0;
738 fs->freereg = 0;
739 fs->nk = 0;
740 fs->nabslineinfo = 0;
741 fs->np = 0;
742 fs->nups = 0;
743 fs->ndebugvars = 0;
744 fs->nactvar = 0;
745 fs->needclose = 0;
746 fs->firstlocal = ls->dyd->actvar.n;
747 fs->firstlabel = ls->dyd->label.n;
748 fs->bl = NULL;
749 f->source = ls->source;
750 luaC_objbarrier(ls->L, f, f->source);
751 f->maxstacksize = 2; /* registers 0/1 are always valid */
752 enterblock(fs, bl, 0);
753}
754
755
756static void close_func (LexState *ls) {
757 lua_State *L = ls->L;
758 FuncState *fs = ls->fs;
759 Proto *f = fs->f;
760 luaK_ret(fs, luaY_nvarstack(fs), 0); /* final return */
761 leaveblock(fs);
762 lua_assert(fs->bl == NULL);
763 luaK_finish(fs);
764 luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction);
765 luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte);
766 luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo,
767 fs->nabslineinfo, AbsLineInfo);
768 luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue);
769 luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *);
770 luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar);
771 luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
772 ls->fs = fs->prev;
773 luaC_checkGC(L);
774}
775
776
777
778/*============================================================*/
779/* GRAMMAR RULES */
780/*============================================================*/
781
782
783/*
784** check whether current token is in the follow set of a block.
785** 'until' closes syntactical blocks, but do not close scope,
786** so it is handled in separate.
787*/
788static int block_follow (LexState *ls, int withuntil) {
789 switch (ls->t.token) {
790 case TK_ELSE: case TK_ELSEIF:
791 case TK_END: case TK_EOS:
792 return 1;
793 case TK_UNTIL: return withuntil;
794 default: return 0;
795 }
796}
797
798
799static void statlist (LexState *ls) {
800 /* statlist -> { stat [';'] } */
801 while (!block_follow(ls, 1)) {
802 if (ls->t.token == TK_RETURN) {
803 statement(ls);
804 return; /* 'return' must be last statement */
805 }
806 statement(ls);
807 }
808}
809
810
811static void fieldsel (LexState *ls, expdesc *v) {
812 /* fieldsel -> ['.' | ':'] NAME */
813 FuncState *fs = ls->fs;
814 expdesc key;
815 luaK_exp2anyregup(fs, v);
816 luaX_next(ls); /* skip the dot or colon */
817 codename(ls, &key);
818 luaK_indexed(fs, v, &key);
819}
820
821
822static void yindex (LexState *ls, expdesc *v) {
823 /* index -> '[' expr ']' */
824 luaX_next(ls); /* skip the '[' */
825 expr(ls, v);
826 luaK_exp2val(ls->fs, v);
827 checknext(ls, ']');
828}
829
830
831/*
832** {======================================================================
833** Rules for Constructors
834** =======================================================================
835*/
836
837
838typedef struct ConsControl {
839 expdesc v; /* last list item read */
840 expdesc *t; /* table descriptor */
841 int nh; /* total number of 'record' elements */
842 int na; /* number of array elements already stored */
843 int tostore; /* number of array elements pending to be stored */
844} ConsControl;
845
846
847static void recfield (LexState *ls, ConsControl *cc) {
848 /* recfield -> (NAME | '['exp']') = exp */
849 FuncState *fs = ls->fs;
850 int reg = ls->fs->freereg;
851 expdesc tab, key, val;
852 if (ls->t.token == TK_NAME)
853 codename(ls, &key);
854 else /* ls->t.token == '[' */
855 yindex(ls, &key);
856 checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
857 cc->nh++;
858 checknext(ls, '=');
859 tab = *cc->t;
860 luaK_indexed(fs, &tab, &key);
861 expr(ls, &val);
862 luaK_storevar(fs, &tab, &val);
863 fs->freereg = reg; /* free registers */
864}
865
866
867static void closelistfield (FuncState *fs, ConsControl *cc) {
868 if (cc->v.k == VVOID) return; /* there is no list item */
869 luaK_exp2nextreg(fs, &cc->v);
870 cc->v.k = VVOID;
871 if (cc->tostore == LFIELDS_PER_FLUSH) {
872 luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
873 cc->na += cc->tostore;
874 cc->tostore = 0; /* no more items pending */
875 }
876}
877
878
879static void lastlistfield (FuncState *fs, ConsControl *cc) {
880 if (cc->tostore == 0) return;
881 if (hasmultret(cc->v.k)) {
882 luaK_setmultret(fs, &cc->v);
883 luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
884 cc->na--; /* do not count last expression (unknown number of elements) */
885 }
886 else {
887 if (cc->v.k != VVOID)
888 luaK_exp2nextreg(fs, &cc->v);
889 luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
890 }
891 cc->na += cc->tostore;
892}
893
894
895static void listfield (LexState *ls, ConsControl *cc) {
896 /* listfield -> exp */
897 expr(ls, &cc->v);
898 cc->tostore++;
899}
900
901
902static void field (LexState *ls, ConsControl *cc) {
903 /* field -> listfield | recfield */
904 switch(ls->t.token) {
905 case TK_NAME: { /* may be 'listfield' or 'recfield' */
906 if (luaX_lookahead(ls) != '=') /* expression? */
907 listfield(ls, cc);
908 else
909 recfield(ls, cc);
910 break;
911 }
912 case '[': {
913 recfield(ls, cc);
914 break;
915 }
916 default: {
917 listfield(ls, cc);
918 break;
919 }
920 }
921}
922
923
924static void constructor (LexState *ls, expdesc *t) {
925 /* constructor -> '{' [ field { sep field } [sep] ] '}'
926 sep -> ',' | ';' */
927 FuncState *fs = ls->fs;
928 int line = ls->linenumber;
929 int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
930 ConsControl cc;
931 luaK_code(fs, 0); /* space for extra arg. */
932 cc.na = cc.nh = cc.tostore = 0;
933 cc.t = t;
934 init_exp(t, VNONRELOC, fs->freereg); /* table will be at stack top */
935 luaK_reserveregs(fs, 1);
936 init_exp(&cc.v, VVOID, 0); /* no value (yet) */
937 checknext(ls, '{');
938 do {
939 lua_assert(cc.v.k == VVOID || cc.tostore > 0);
940 if (ls->t.token == '}') break;
941 closelistfield(fs, &cc);
942 field(ls, &cc);
943 } while (testnext(ls, ',') || testnext(ls, ';'));
944 check_match(ls, '}', '{', line);
945 lastlistfield(fs, &cc);
946 luaK_settablesize(fs, pc, t->u.info, cc.na, cc.nh);
947}
948
949/* }====================================================================== */
950
951
952static void setvararg (FuncState *fs, int nparams) {
953 fs->f->is_vararg = 1;
954 luaK_codeABC(fs, OP_VARARGPREP, nparams, 0, 0);
955}
956
957
958static void parlist (LexState *ls) {
959 /* parlist -> [ {NAME ','} (NAME | '...') ] */
960 FuncState *fs = ls->fs;
961 Proto *f = fs->f;
962 int nparams = 0;
963 int isvararg = 0;
964 if (ls->t.token != ')') { /* is 'parlist' not empty? */
965 do {
966 switch (ls->t.token) {
967 case TK_NAME: {
968 new_localvar(ls, str_checkname(ls));
969 nparams++;
970 break;
971 }
972 case TK_DOTS: {
973 luaX_next(ls);
974 isvararg = 1;
975 break;
976 }
977 default: luaX_syntaxerror(ls, "<name> or '...' expected");
978 }
979 } while (!isvararg && testnext(ls, ','));
980 }
981 adjustlocalvars(ls, nparams);
982 f->numparams = cast_byte(fs->nactvar);
983 if (isvararg)
984 setvararg(fs, f->numparams); /* declared vararg */
985 luaK_reserveregs(fs, fs->nactvar); /* reserve registers for parameters */
986}
987
988
989static void body (LexState *ls, expdesc *e, int ismethod, int line) {
990 /* body -> '(' parlist ')' block END */
991 FuncState new_fs;
992 BlockCnt bl;
993 new_fs.f = addprototype(ls);
994 new_fs.f->linedefined = line;
995 open_func(ls, &new_fs, &bl);
996 checknext(ls, '(');
997 if (ismethod) {
998 new_localvarliteral(ls, "self"); /* create 'self' parameter */
999 adjustlocalvars(ls, 1);
1000 }
1001 parlist(ls);
1002 checknext(ls, ')');
1003 statlist(ls);
1004 new_fs.f->lastlinedefined = ls->linenumber;
1005 check_match(ls, TK_END, TK_FUNCTION, line);
1006 codeclosure(ls, e);
1007 close_func(ls);
1008}
1009
1010
1011static int explist (LexState *ls, expdesc *v) {
1012 /* explist -> expr { ',' expr } */
1013 int n = 1; /* at least one expression */
1014 expr(ls, v);
1015 while (testnext(ls, ',')) {
1016 luaK_exp2nextreg(ls->fs, v);
1017 expr(ls, v);
1018 n++;
1019 }
1020 return n;
1021}
1022
1023
1024static void funcargs (LexState *ls, expdesc *f) {
1025 FuncState *fs = ls->fs;
1026 expdesc args;
1027 int base, nparams;
1028 int line = ls->linenumber;
1029 switch (ls->t.token) {
1030 case '(': { /* funcargs -> '(' [ explist ] ')' */
1031 luaX_next(ls);
1032 if (ls->t.token == ')') /* arg list is empty? */
1033 args.k = VVOID;
1034 else {
1035 explist(ls, &args);
1036 if (hasmultret(args.k))
1037 luaK_setmultret(fs, &args);
1038 }
1039 check_match(ls, ')', '(', line);
1040 break;
1041 }
1042 case '{': { /* funcargs -> constructor */
1043 constructor(ls, &args);
1044 break;
1045 }
1046 case TK_STRING: { /* funcargs -> STRING */
1047 codestring(&args, ls->t.seminfo.ts);
1048 luaX_next(ls); /* must use 'seminfo' before 'next' */
1049 break;
1050 }
1051 default: {
1052 luaX_syntaxerror(ls, "function arguments expected");
1053 }
1054 }
1055 lua_assert(f->k == VNONRELOC);
1056 base = f->u.info; /* base register for call */
1057 if (hasmultret(args.k))
1058 nparams = LUA_MULTRET; /* open call */
1059 else {
1060 if (args.k != VVOID)
1061 luaK_exp2nextreg(fs, &args); /* close last argument */
1062 nparams = fs->freereg - (base+1);
1063 }
1064 init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
1065 luaK_fixline(fs, line);
1066 fs->freereg = base+1; /* call removes function and arguments and leaves
1067 one result (unless changed later) */
1068}
1069
1070
1071
1072
1073/*
1074** {======================================================================
1075** Expression parsing
1076** =======================================================================
1077*/
1078
1079
1080static void primaryexp (LexState *ls, expdesc *v) {
1081 /* primaryexp -> NAME | '(' expr ')' */
1082 switch (ls->t.token) {
1083 case '(': {
1084 int line = ls->linenumber;
1085 luaX_next(ls);
1086 expr(ls, v);
1087 check_match(ls, ')', '(', line);
1088 luaK_dischargevars(ls->fs, v);
1089 return;
1090 }
1091 case TK_NAME: {
1092 singlevar(ls, v);
1093 return;
1094 }
1095 default: {
1096 luaX_syntaxerror(ls, "unexpected symbol");
1097 }
1098 }
1099}
1100
1101
1102static void suffixedexp (LexState *ls, expdesc *v) {
1103 /* suffixedexp ->
1104 primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
1105 FuncState *fs = ls->fs;
1106 primaryexp(ls, v);
1107 for (;;) {
1108 switch (ls->t.token) {
1109 case '.': { /* fieldsel */
1110 fieldsel(ls, v);
1111 break;
1112 }
1113 case '[': { /* '[' exp ']' */
1114 expdesc key;
1115 luaK_exp2anyregup(fs, v);
1116 yindex(ls, &key);
1117 luaK_indexed(fs, v, &key);
1118 break;
1119 }
1120 case ':': { /* ':' NAME funcargs */
1121 expdesc key;
1122 luaX_next(ls);
1123 codename(ls, &key);
1124 luaK_self(fs, v, &key);
1125 funcargs(ls, v);
1126 break;
1127 }
1128 case '(': case TK_STRING: case '{': { /* funcargs */
1129 luaK_exp2nextreg(fs, v);
1130 funcargs(ls, v);
1131 break;
1132 }
1133 default: return;
1134 }
1135 }
1136}
1137
1138
1139static void simpleexp (LexState *ls, expdesc *v) {
1140 /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
1141 constructor | FUNCTION body | suffixedexp */
1142 switch (ls->t.token) {
1143 case TK_FLT: {
1144 init_exp(v, VKFLT, 0);
1145 v->u.nval = ls->t.seminfo.r;
1146 break;
1147 }
1148 case TK_INT: {
1149 init_exp(v, VKINT, 0);
1150 v->u.ival = ls->t.seminfo.i;
1151 break;
1152 }
1153 case TK_STRING: {
1154 codestring(v, ls->t.seminfo.ts);
1155 break;
1156 }
1157 case TK_NIL: {
1158 init_exp(v, VNIL, 0);
1159 break;
1160 }
1161 case TK_TRUE: {
1162 init_exp(v, VTRUE, 0);
1163 break;
1164 }
1165 case TK_FALSE: {
1166 init_exp(v, VFALSE, 0);
1167 break;
1168 }
1169 case TK_DOTS: { /* vararg */
1170 FuncState *fs = ls->fs;
1171 check_condition(ls, fs->f->is_vararg,
1172 "cannot use '...' outside a vararg function");
1173 init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 0, 1));
1174 break;
1175 }
1176 case '{': { /* constructor */
1177 constructor(ls, v);
1178 return;
1179 }
1180 case TK_FUNCTION: {
1181 luaX_next(ls);
1182 body(ls, v, 0, ls->linenumber);
1183 return;
1184 }
1185 default: {
1186 suffixedexp(ls, v);
1187 return;
1188 }
1189 }
1190 luaX_next(ls);
1191}
1192
1193
1194static UnOpr getunopr (int op) {
1195 switch (op) {
1196 case TK_NOT: return OPR_NOT;
1197 case '-': return OPR_MINUS;
1198 case '~': return OPR_BNOT;
1199 case '#': return OPR_LEN;
1200 default: return OPR_NOUNOPR;
1201 }
1202}
1203
1204
1205static BinOpr getbinopr (int op) {
1206 switch (op) {
1207 case '+': return OPR_ADD;
1208 case '-': return OPR_SUB;
1209 case '*': return OPR_MUL;
1210 case '%': return OPR_MOD;
1211 case '^': return OPR_POW;
1212 case '/': return OPR_DIV;
1213 case TK_IDIV: return OPR_IDIV;
1214 case '&': return OPR_BAND;
1215 case '|': return OPR_BOR;
1216 case '~': return OPR_BXOR;
1217 case TK_SHL: return OPR_SHL;
1218 case TK_SHR: return OPR_SHR;
1219 case TK_CONCAT: return OPR_CONCAT;
1220 case TK_NE: return OPR_NE;
1221 case TK_EQ: return OPR_EQ;
1222 case '<': return OPR_LT;
1223 case TK_LE: return OPR_LE;
1224 case '>': return OPR_GT;
1225 case TK_GE: return OPR_GE;
1226 case TK_AND: return OPR_AND;
1227 case TK_OR: return OPR_OR;
1228 default: return OPR_NOBINOPR;
1229 }
1230}
1231
1232
1233/*
1234** Priority table for binary operators.
1235*/
1236static const struct {
1237 lu_byte left; /* left priority for each binary operator */
1238 lu_byte right; /* right priority */
1239} priority[] = { /* ORDER OPR */
1240 {10, 10}, {10, 10}, /* '+' '-' */
1241 {11, 11}, {11, 11}, /* '*' '%' */
1242 {14, 13}, /* '^' (right associative) */
1243 {11, 11}, {11, 11}, /* '/' '//' */
1244 {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
1245 {7, 7}, {7, 7}, /* '<<' '>>' */
1246 {9, 8}, /* '..' (right associative) */
1247 {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
1248 {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
1249 {2, 2}, {1, 1} /* and, or */
1250};
1251
1252#define UNARY_PRIORITY 12 /* priority for unary operators */
1253
1254
1255/*
1256** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1257** where 'binop' is any binary operator with a priority higher than 'limit'
1258*/
1259static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
1260 BinOpr op;
1261 UnOpr uop;
1262 enterlevel(ls);
1263 uop = getunopr(ls->t.token);
1264 if (uop != OPR_NOUNOPR) { /* prefix (unary) operator? */
1265 int line = ls->linenumber;
1266 luaX_next(ls); /* skip operator */
1267 subexpr(ls, v, UNARY_PRIORITY);
1268 luaK_prefix(ls->fs, uop, v, line);
1269 }
1270 else simpleexp(ls, v);
1271 /* expand while operators have priorities higher than 'limit' */
1272 op = getbinopr(ls->t.token);
1273 while (op != OPR_NOBINOPR && priority[op].left > limit) {
1274 expdesc v2;
1275 BinOpr nextop;
1276 int line = ls->linenumber;
1277 luaX_next(ls); /* skip operator */
1278 luaK_infix(ls->fs, op, v);
1279 /* read sub-expression with higher priority */
1280 nextop = subexpr(ls, &v2, priority[op].right);
1281 luaK_posfix(ls->fs, op, v, &v2, line);
1282 op = nextop;
1283 }
1284 leavelevel(ls);
1285 return op; /* return first untreated operator */
1286}
1287
1288
1289static void expr (LexState *ls, expdesc *v) {
1290 subexpr(ls, v, 0);
1291}
1292
1293/* }==================================================================== */
1294
1295
1296
1297/*
1298** {======================================================================
1299** Rules for Statements
1300** =======================================================================
1301*/
1302
1303
1304static void block (LexState *ls) {
1305 /* block -> statlist */
1306 FuncState *fs = ls->fs;
1307 BlockCnt bl;
1308 enterblock(fs, &bl, 0);
1309 statlist(ls);
1310 leaveblock(fs);
1311}
1312
1313
1314/*
1315** structure to chain all variables in the left-hand side of an
1316** assignment
1317*/
1318struct LHS_assign {
1319 struct LHS_assign *prev;
1320 expdesc v; /* variable (global, local, upvalue, or indexed) */
1321};
1322
1323
1324/*
1325** check whether, in an assignment to an upvalue/local variable, the
1326** upvalue/local variable is begin used in a previous assignment to a
1327** table. If so, save original upvalue/local value in a safe place and
1328** use this safe copy in the previous assignment.
1329*/
1330static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
1331 FuncState *fs = ls->fs;
1332 int extra = fs->freereg; /* eventual position to save local variable */
1333 int conflict = 0;
1334 for (; lh; lh = lh->prev) { /* check all previous assignments */
1335 if (vkisindexed(lh->v.k)) { /* assignment to table field? */
1336 if (lh->v.k == VINDEXUP) { /* is table an upvalue? */
1337 if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) {
1338 conflict = 1; /* table is the upvalue being assigned now */
1339 lh->v.k = VINDEXSTR;
1340 lh->v.u.ind.t = extra; /* assignment will use safe copy */
1341 }
1342 }
1343 else { /* table is a register */
1344 if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.ridx) {
1345 conflict = 1; /* table is the local being assigned now */
1346 lh->v.u.ind.t = extra; /* assignment will use safe copy */
1347 }
1348 /* is index the local being assigned? */
1349 if (lh->v.k == VINDEXED && v->k == VLOCAL &&
1350 lh->v.u.ind.idx == v->u.var.ridx) {
1351 conflict = 1;
1352 lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
1353 }
1354 }
1355 }
1356 }
1357 if (conflict) {
1358 /* copy upvalue/local value to a temporary (in position 'extra') */
1359 if (v->k == VLOCAL)
1360 luaK_codeABC(fs, OP_MOVE, extra, v->u.var.ridx, 0);
1361 else
1362 luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0);
1363 luaK_reserveregs(fs, 1);
1364 }
1365}
1366
1367/*
1368** Parse and compile a multiple assignment. The first "variable"
1369** (a 'suffixedexp') was already read by the caller.
1370**
1371** assignment -> suffixedexp restassign
1372** restassign -> ',' suffixedexp restassign | '=' explist
1373*/
1374static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) {
1375 expdesc e;
1376 check_condition(ls, vkisvar(lh->v.k), "syntax error");
1377 check_readonly(ls, &lh->v);
1378 if (testnext(ls, ',')) { /* restassign -> ',' suffixedexp restassign */
1379 struct LHS_assign nv;
1380 nv.prev = lh;
1381 suffixedexp(ls, &nv.v);
1382 if (!vkisindexed(nv.v.k))
1383 check_conflict(ls, lh, &nv.v);
1384 enterlevel(ls); /* control recursion depth */
1385 restassign(ls, &nv, nvars+1);
1386 leavelevel(ls);
1387 }
1388 else { /* restassign -> '=' explist */
1389 int nexps;
1390 checknext(ls, '=');
1391 nexps = explist(ls, &e);
1392 if (nexps != nvars)
1393 adjust_assign(ls, nvars, nexps, &e);
1394 else {
1395 luaK_setoneret(ls->fs, &e); /* close last expression */
1396 luaK_storevar(ls->fs, &lh->v, &e);
1397 return; /* avoid default */
1398 }
1399 }
1400 init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
1401 luaK_storevar(ls->fs, &lh->v, &e);
1402}
1403
1404
1405static int cond (LexState *ls) {
1406 /* cond -> exp */
1407 expdesc v;
1408 expr(ls, &v); /* read condition */
1409 if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */
1410 luaK_goiftrue(ls->fs, &v);
1411 return v.f;
1412}
1413
1414
1415static void gotostat (LexState *ls) {
1416 FuncState *fs = ls->fs;
1417 int line = ls->linenumber;
1418 TString *name = str_checkname(ls); /* label's name */
1419 Labeldesc *lb = findlabel(ls, name);
1420 if (lb == NULL) /* no label? */
1421 /* forward jump; will be resolved when the label is declared */
1422 newgotoentry(ls, name, line, luaK_jump(fs));
1423 else { /* found a label */
1424 /* backward jump; will be resolved here */
1425 int lblevel = reglevel(fs, lb->nactvar); /* label level */
1426 if (luaY_nvarstack(fs) > lblevel) /* leaving the scope of a variable? */
1427 luaK_codeABC(fs, OP_CLOSE, lblevel, 0, 0);
1428 /* create jump and link it to the label */
1429 luaK_patchlist(fs, luaK_jump(fs), lb->pc);
1430 }
1431}
1432
1433
1434/*
1435** Break statement. Semantically equivalent to "goto break".
1436*/
1437static void breakstat (LexState *ls) {
1438 int line = ls->linenumber;
1439 luaX_next(ls); /* skip break */
1440 newgotoentry(ls, luaS_newliteral(ls->L, "break"), line, luaK_jump(ls->fs));
1441}
1442
1443
1444/*
1445** Check whether there is already a label with the given 'name'.
1446*/
1447static void checkrepeated (LexState *ls, TString *name) {
1448 Labeldesc *lb = findlabel(ls, name);
1449 if (l_unlikely(lb != NULL)) { /* already defined? */
1450 const char *msg = "label '%s' already defined on line %d";
1451 msg = luaO_pushfstring(ls->L, msg, getstr(name), lb->line);
1452 luaK_semerror(ls, msg); /* error */
1453 }
1454}
1455
1456
1457static void labelstat (LexState *ls, TString *name, int line) {
1458 /* label -> '::' NAME '::' */
1459 checknext(ls, TK_DBCOLON); /* skip double colon */
1460 while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
1461 statement(ls); /* skip other no-op statements */
1462 checkrepeated(ls, name); /* check for repeated labels */
1463 createlabel(ls, name, line, block_follow(ls, 0));
1464}
1465
1466
1467static void whilestat (LexState *ls, int line) {
1468 /* whilestat -> WHILE cond DO block END */
1469 FuncState *fs = ls->fs;
1470 int whileinit;
1471 int condexit;
1472 BlockCnt bl;
1473 luaX_next(ls); /* skip WHILE */
1474 whileinit = luaK_getlabel(fs);
1475 condexit = cond(ls);
1476 enterblock(fs, &bl, 1);
1477 checknext(ls, TK_DO);
1478 block(ls);
1479 luaK_jumpto(fs, whileinit);
1480 check_match(ls, TK_END, TK_WHILE, line);
1481 leaveblock(fs);
1482 luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
1483}
1484
1485
1486static void repeatstat (LexState *ls, int line) {
1487 /* repeatstat -> REPEAT block UNTIL cond */
1488 int condexit;
1489 FuncState *fs = ls->fs;
1490 int repeat_init = luaK_getlabel(fs);
1491 BlockCnt bl1, bl2;
1492 enterblock(fs, &bl1, 1); /* loop block */
1493 enterblock(fs, &bl2, 0); /* scope block */
1494 luaX_next(ls); /* skip REPEAT */
1495 statlist(ls);
1496 check_match(ls, TK_UNTIL, TK_REPEAT, line);
1497 condexit = cond(ls); /* read condition (inside scope block) */
1498 leaveblock(fs); /* finish scope */
1499 if (bl2.upval) { /* upvalues? */
1500 int exit = luaK_jump(fs); /* normal exit must jump over fix */
1501 luaK_patchtohere(fs, condexit); /* repetition must close upvalues */
1502 luaK_codeABC(fs, OP_CLOSE, reglevel(fs, bl2.nactvar), 0, 0);
1503 condexit = luaK_jump(fs); /* repeat after closing upvalues */
1504 luaK_patchtohere(fs, exit); /* normal exit comes to here */
1505 }
1506 luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
1507 leaveblock(fs); /* finish loop */
1508}
1509
1510
1511/*
1512** Read an expression and generate code to put its results in next
1513** stack slot.
1514**
1515*/
1516static void exp1 (LexState *ls) {
1517 expdesc e;
1518 expr(ls, &e);
1519 luaK_exp2nextreg(ls->fs, &e);
1520 lua_assert(e.k == VNONRELOC);
1521}
1522
1523
1524/*
1525** Fix for instruction at position 'pc' to jump to 'dest'.
1526** (Jump addresses are relative in Lua). 'back' true means
1527** a back jump.
1528*/
1529static void fixforjump (FuncState *fs, int pc, int dest, int back) {
1530 Instruction *jmp = &fs->f->code[pc];
1531 int offset = dest - (pc + 1);
1532 if (back)
1533 offset = -offset;
1534 if (l_unlikely(offset > MAXARG_Bx))
1535 luaX_syntaxerror(fs->ls, "control structure too long");
1536 SETARG_Bx(*jmp, offset);
1537}
1538
1539
1540/*
1541** Generate code for a 'for' loop.
1542*/
1543static void forbody (LexState *ls, int base, int line, int nvars, int isgen) {
1544 /* forbody -> DO block */
1545 static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP};
1546 static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP};
1547 BlockCnt bl;
1548 FuncState *fs = ls->fs;
1549 int prep, endfor;
1550 checknext(ls, TK_DO);
1551 prep = luaK_codeABx(fs, forprep[isgen], base, 0);
1552 enterblock(fs, &bl, 0); /* scope for declared variables */
1553 adjustlocalvars(ls, nvars);
1554 luaK_reserveregs(fs, nvars);
1555 block(ls);
1556 leaveblock(fs); /* end of scope for declared variables */
1557 fixforjump(fs, prep, luaK_getlabel(fs), 0);
1558 if (isgen) { /* generic for? */
1559 luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
1560 luaK_fixline(fs, line);
1561 }
1562 endfor = luaK_codeABx(fs, forloop[isgen], base, 0);
1563 fixforjump(fs, endfor, prep + 1, 1);
1564 luaK_fixline(fs, line);
1565}
1566
1567
1568static void fornum (LexState *ls, TString *varname, int line) {
1569 /* fornum -> NAME = exp,exp[,exp] forbody */
1570 FuncState *fs = ls->fs;
1571 int base = fs->freereg;
1572 new_localvarliteral(ls, "(for state)");
1573 new_localvarliteral(ls, "(for state)");
1574 new_localvarliteral(ls, "(for state)");
1575 new_localvar(ls, varname);
1576 checknext(ls, '=');
1577 exp1(ls); /* initial value */
1578 checknext(ls, ',');
1579 exp1(ls); /* limit */
1580 if (testnext(ls, ','))
1581 exp1(ls); /* optional step */
1582 else { /* default step = 1 */
1583 luaK_int(fs, fs->freereg, 1);
1584 luaK_reserveregs(fs, 1);
1585 }
1586 adjustlocalvars(ls, 3); /* control variables */
1587 forbody(ls, base, line, 1, 0);
1588}
1589
1590
1591static void forlist (LexState *ls, TString *indexname) {
1592 /* forlist -> NAME {,NAME} IN explist forbody */
1593 FuncState *fs = ls->fs;
1594 expdesc e;
1595 int nvars = 5; /* gen, state, control, toclose, 'indexname' */
1596 int line;
1597 int base = fs->freereg;
1598 /* create control variables */
1599 new_localvarliteral(ls, "(for state)");
1600 new_localvarliteral(ls, "(for state)");
1601 new_localvarliteral(ls, "(for state)");
1602 new_localvarliteral(ls, "(for state)");
1603 /* create declared variables */
1604 new_localvar(ls, indexname);
1605 while (testnext(ls, ',')) {
1606 new_localvar(ls, str_checkname(ls));
1607 nvars++;
1608 }
1609 checknext(ls, TK_IN);
1610 line = ls->linenumber;
1611 adjust_assign(ls, 4, explist(ls, &e), &e);
1612 adjustlocalvars(ls, 4); /* control variables */
1613 marktobeclosed(fs); /* last control var. must be closed */
1614 luaK_checkstack(fs, 3); /* extra space to call generator */
1615 forbody(ls, base, line, nvars - 4, 1);
1616}
1617
1618
1619static void forstat (LexState *ls, int line) {
1620 /* forstat -> FOR (fornum | forlist) END */
1621 FuncState *fs = ls->fs;
1622 TString *varname;
1623 BlockCnt bl;
1624 enterblock(fs, &bl, 1); /* scope for loop and control variables */
1625 luaX_next(ls); /* skip 'for' */
1626 varname = str_checkname(ls); /* first variable name */
1627 switch (ls->t.token) {
1628 case '=': fornum(ls, varname, line); break;
1629 case ',': case TK_IN: forlist(ls, varname); break;
1630 default: luaX_syntaxerror(ls, "'=' or 'in' expected");
1631 }
1632 check_match(ls, TK_END, TK_FOR, line);
1633 leaveblock(fs); /* loop scope ('break' jumps to this point) */
1634}
1635
1636
1637static void test_then_block (LexState *ls, int *escapelist) {
1638 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1639 BlockCnt bl;
1640 FuncState *fs = ls->fs;
1641 expdesc v;
1642 int jf; /* instruction to skip 'then' code (if condition is false) */
1643 luaX_next(ls); /* skip IF or ELSEIF */
1644 expr(ls, &v); /* read condition */
1645 checknext(ls, TK_THEN);
1646 if (ls->t.token == TK_BREAK) { /* 'if x then break' ? */
1647 int line = ls->linenumber;
1648 luaK_goiffalse(ls->fs, &v); /* will jump if condition is true */
1649 luaX_next(ls); /* skip 'break' */
1650 enterblock(fs, &bl, 0); /* must enter block before 'goto' */
1651 newgotoentry(ls, luaS_newliteral(ls->L, "break"), line, v.t);
1652 while (testnext(ls, ';')) {} /* skip semicolons */
1653 if (block_follow(ls, 0)) { /* jump is the entire block? */
1654 leaveblock(fs);
1655 return; /* and that is it */
1656 }
1657 else /* must skip over 'then' part if condition is false */
1658 jf = luaK_jump(fs);
1659 }
1660 else { /* regular case (not a break) */
1661 luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */
1662 enterblock(fs, &bl, 0);
1663 jf = v.f;
1664 }
1665 statlist(ls); /* 'then' part */
1666 leaveblock(fs);
1667 if (ls->t.token == TK_ELSE ||
1668 ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
1669 luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
1670 luaK_patchtohere(fs, jf);
1671}
1672
1673
1674static void ifstat (LexState *ls, int line) {
1675 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1676 FuncState *fs = ls->fs;
1677 int escapelist = NO_JUMP; /* exit list for finished parts */
1678 test_then_block(ls, &escapelist); /* IF cond THEN block */
1679 while (ls->t.token == TK_ELSEIF)
1680 test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
1681 if (testnext(ls, TK_ELSE))
1682 block(ls); /* 'else' part */
1683 check_match(ls, TK_END, TK_IF, line);
1684 luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
1685}
1686
1687
1688static void localfunc (LexState *ls) {
1689 expdesc b;
1690 FuncState *fs = ls->fs;
1691 int fvar = fs->nactvar; /* function's variable index */
1692 new_localvar(ls, str_checkname(ls)); /* new local variable */
1693 adjustlocalvars(ls, 1); /* enter its scope */
1694 body(ls, &b, 0, ls->linenumber); /* function created in next register */
1695 /* debug information will only see the variable after this point! */
1696 localdebuginfo(fs, fvar)->startpc = fs->pc;
1697}
1698
1699
1700static int getlocalattribute (LexState *ls) {
1701 /* ATTRIB -> ['<' Name '>'] */
1702 if (testnext(ls, '<')) {
1703 const char *attr = getstr(str_checkname(ls));
1704 checknext(ls, '>');
1705 if (strcmp(attr, "const") == 0)
1706 return RDKCONST; /* read-only variable */
1707 else if (strcmp(attr, "close") == 0)
1708 return RDKTOCLOSE; /* to-be-closed variable */
1709 else
1710 luaK_semerror(ls,
1711 luaO_pushfstring(ls->L, "unknown attribute '%s'", attr));
1712 }
1713 return VDKREG; /* regular variable */
1714}
1715
1716
1717static void checktoclose (FuncState *fs, int level) {
1718 if (level != -1) { /* is there a to-be-closed variable? */
1719 marktobeclosed(fs);
1720 luaK_codeABC(fs, OP_TBC, reglevel(fs, level), 0, 0);
1721 }
1722}
1723
1724
1725static void localstat (LexState *ls) {
1726 /* stat -> LOCAL NAME ATTRIB { ',' NAME ATTRIB } ['=' explist] */
1727 FuncState *fs = ls->fs;
1728 int toclose = -1; /* index of to-be-closed variable (if any) */
1729 Vardesc *var; /* last variable */
1730 int vidx, kind; /* index and kind of last variable */
1731 int nvars = 0;
1732 int nexps;
1733 expdesc e;
1734 do {
1735 vidx = new_localvar(ls, str_checkname(ls));
1736 kind = getlocalattribute(ls);
1737 getlocalvardesc(fs, vidx)->vd.kind = kind;
1738 if (kind == RDKTOCLOSE) { /* to-be-closed? */
1739 if (toclose != -1) /* one already present? */
1740 luaK_semerror(ls, "multiple to-be-closed variables in local list");
1741 toclose = fs->nactvar + nvars;
1742 }
1743 nvars++;
1744 } while (testnext(ls, ','));
1745 if (testnext(ls, '='))
1746 nexps = explist(ls, &e);
1747 else {
1748 e.k = VVOID;
1749 nexps = 0;
1750 }
1751 var = getlocalvardesc(fs, vidx); /* get last variable */
1752 if (nvars == nexps && /* no adjustments? */
1753 var->vd.kind == RDKCONST && /* last variable is const? */
1754 luaK_exp2const(fs, &e, &var->k)) { /* compile-time constant? */
1755 var->vd.kind = RDKCTC; /* variable is a compile-time constant */
1756 adjustlocalvars(ls, nvars - 1); /* exclude last variable */
1757 fs->nactvar++; /* but count it */
1758 }
1759 else {
1760 adjust_assign(ls, nvars, nexps, &e);
1761 adjustlocalvars(ls, nvars);
1762 }
1763 checktoclose(fs, toclose);
1764}
1765
1766
1767static int funcname (LexState *ls, expdesc *v) {
1768 /* funcname -> NAME {fieldsel} [':' NAME] */
1769 int ismethod = 0;
1770 singlevar(ls, v);
1771 while (ls->t.token == '.')
1772 fieldsel(ls, v);
1773 if (ls->t.token == ':') {
1774 ismethod = 1;
1775 fieldsel(ls, v);
1776 }
1777 return ismethod;
1778}
1779
1780
1781static void funcstat (LexState *ls, int line) {
1782 /* funcstat -> FUNCTION funcname body */
1783 int ismethod;
1784 expdesc v, b;
1785 luaX_next(ls); /* skip FUNCTION */
1786 ismethod = funcname(ls, &v);
1787 body(ls, &b, ismethod, line);
1788 check_readonly(ls, &v);
1789 luaK_storevar(ls->fs, &v, &b);
1790 luaK_fixline(ls->fs, line); /* definition "happens" in the first line */
1791}
1792
1793
1794static void exprstat (LexState *ls) {
1795 /* stat -> func | assignment */
1796 FuncState *fs = ls->fs;
1797 struct LHS_assign v;
1798 suffixedexp(ls, &v.v);
1799 if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
1800 v.prev = NULL;
1801 restassign(ls, &v, 1);
1802 }
1803 else { /* stat -> func */
1804 Instruction *inst;
1805 check_condition(ls, v.v.k == VCALL, "syntax error");
1806 inst = &getinstruction(fs, &v.v);
1807 SETARG_C(*inst, 1); /* call statement uses no results */
1808 }
1809}
1810
1811
1812static void retstat (LexState *ls) {
1813 /* stat -> RETURN [explist] [';'] */
1814 FuncState *fs = ls->fs;
1815 expdesc e;
1816 int nret; /* number of values being returned */
1817 int first = luaY_nvarstack(fs); /* first slot to be returned */
1818 if (block_follow(ls, 1) || ls->t.token == ';')
1819 nret = 0; /* return no values */
1820 else {
1821 nret = explist(ls, &e); /* optional return values */
1822 if (hasmultret(e.k)) {
1823 luaK_setmultret(fs, &e);
1824 if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc) { /* tail call? */
1825 SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);
1826 lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs));
1827 }
1828 nret = LUA_MULTRET; /* return all values */
1829 }
1830 else {
1831 if (nret == 1) /* only one single value? */
1832 first = luaK_exp2anyreg(fs, &e); /* can use original slot */
1833 else { /* values must go to the top of the stack */
1834 luaK_exp2nextreg(fs, &e);
1835 lua_assert(nret == fs->freereg - first);
1836 }
1837 }
1838 }
1839 luaK_ret(fs, first, nret);
1840 testnext(ls, ';'); /* skip optional semicolon */
1841}
1842
1843
1844static void statement (LexState *ls) {
1845 int line = ls->linenumber; /* may be needed for error messages */
1846 enterlevel(ls);
1847 switch (ls->t.token) {
1848 case ';': { /* stat -> ';' (empty statement) */
1849 luaX_next(ls); /* skip ';' */
1850 break;
1851 }
1852 case TK_IF: { /* stat -> ifstat */
1853 ifstat(ls, line);
1854 break;
1855 }
1856 case TK_WHILE: { /* stat -> whilestat */
1857 whilestat(ls, line);
1858 break;
1859 }
1860 case TK_DO: { /* stat -> DO block END */
1861 luaX_next(ls); /* skip DO */
1862 block(ls);
1863 check_match(ls, TK_END, TK_DO, line);
1864 break;
1865 }
1866 case TK_FOR: { /* stat -> forstat */
1867 forstat(ls, line);
1868 break;
1869 }
1870 case TK_REPEAT: { /* stat -> repeatstat */
1871 repeatstat(ls, line);
1872 break;
1873 }
1874 case TK_FUNCTION: { /* stat -> funcstat */
1875 funcstat(ls, line);
1876 break;
1877 }
1878 case TK_LOCAL: { /* stat -> localstat */
1879 luaX_next(ls); /* skip LOCAL */
1880 if (testnext(ls, TK_FUNCTION)) /* local function? */
1881 localfunc(ls);
1882 else
1883 localstat(ls);
1884 break;
1885 }
1886 case TK_DBCOLON: { /* stat -> label */
1887 luaX_next(ls); /* skip double colon */
1888 labelstat(ls, str_checkname(ls), line);
1889 break;
1890 }
1891 case TK_RETURN: { /* stat -> retstat */
1892 luaX_next(ls); /* skip RETURN */
1893 retstat(ls);
1894 break;
1895 }
1896 case TK_BREAK: { /* stat -> breakstat */
1897 breakstat(ls);
1898 break;
1899 }
1900 case TK_GOTO: { /* stat -> 'goto' NAME */
1901 luaX_next(ls); /* skip 'goto' */
1902 gotostat(ls);
1903 break;
1904 }
1905 default: { /* stat -> func | assignment */
1906 exprstat(ls);
1907 break;
1908 }
1909 }
1910 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1911 ls->fs->freereg >= luaY_nvarstack(ls->fs));
1912 ls->fs->freereg = luaY_nvarstack(ls->fs); /* free registers */
1913 leavelevel(ls);
1914}
1915
1916/* }====================================================================== */
1917
1918
1919/*
1920** compiles the main function, which is a regular vararg function with an
1921** upvalue named LUA_ENV
1922*/
1923static void mainfunc (LexState *ls, FuncState *fs) {
1924 BlockCnt bl;
1925 Upvaldesc *env;
1926 open_func(ls, fs, &bl);
1927 setvararg(fs, 0); /* main function is always declared vararg */
1928 env = allocupvalue(fs); /* ...set environment upvalue */
1929 env->instack = 1;
1930 env->idx = 0;
1931 env->kind = VDKREG;
1932 env->name = ls->envn;
1933 luaC_objbarrier(ls->L, fs->f, env->name);
1934 luaX_next(ls); /* read first token */
1935 statlist(ls); /* parse main body */
1936 check(ls, TK_EOS);
1937 close_func(ls);
1938}
1939
1940
1941LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1942 Dyndata *dyd, const char *name, int firstchar) {
1943 LexState lexstate;
1944 FuncState funcstate;
1945 LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */
1946 setclLvalue2s(L, L->top.p, cl); /* anchor it (to avoid being collected) */
1947 luaD_inctop(L);
1948 lexstate.h = luaH_new(L); /* create table for scanner */
1949 sethvalue2s(L, L->top.p, lexstate.h); /* anchor it */
1950 luaD_inctop(L);
1951 funcstate.f = cl->p = luaF_newproto(L);
1952 luaC_objbarrier(L, cl, cl->p);
1953 funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
1954 luaC_objbarrier(L, funcstate.f, funcstate.f->source);
1955 lexstate.buff = buff;
1956 lexstate.dyd = dyd;
1957 dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
1958 luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
1959 mainfunc(&lexstate, &funcstate);
1960 lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
1961 /* all scopes should be correctly finished */
1962 lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
1963 L->top.p--; /* remove scanner's table */
1964 return cl; /* closure is on the stack, too */
1965}
1966
diff --git a/vendor/lua-5.4.8/src/lparser.h b/vendor/lua-5.4.8/src/lparser.h
new file mode 100644
index 0000000..5e4500f
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lparser.h
@@ -0,0 +1,171 @@
1/*
2** $Id: lparser.h $
3** Lua Parser
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lparser_h
8#define lparser_h
9
10#include "llimits.h"
11#include "lobject.h"
12#include "lzio.h"
13
14
15/*
16** Expression and variable descriptor.
17** Code generation for variables and expressions can be delayed to allow
18** optimizations; An 'expdesc' structure describes a potentially-delayed
19** variable/expression. It has a description of its "main" value plus a
20** list of conditional jumps that can also produce its value (generated
21** by short-circuit operators 'and'/'or').
22*/
23
24/* kinds of variables/expressions */
25typedef enum {
26 VVOID, /* when 'expdesc' describes the last expression of a list,
27 this kind means an empty list (so, no expression) */
28 VNIL, /* constant nil */
29 VTRUE, /* constant true */
30 VFALSE, /* constant false */
31 VK, /* constant in 'k'; info = index of constant in 'k' */
32 VKFLT, /* floating constant; nval = numerical float value */
33 VKINT, /* integer constant; ival = numerical integer value */
34 VKSTR, /* string constant; strval = TString address;
35 (string is fixed by the lexer) */
36 VNONRELOC, /* expression has its value in a fixed register;
37 info = result register */
38 VLOCAL, /* local variable; var.ridx = register index;
39 var.vidx = relative index in 'actvar.arr' */
40 VUPVAL, /* upvalue variable; info = index of upvalue in 'upvalues' */
41 VCONST, /* compile-time <const> variable;
42 info = absolute index in 'actvar.arr' */
43 VINDEXED, /* indexed variable;
44 ind.t = table register;
45 ind.idx = key's R index */
46 VINDEXUP, /* indexed upvalue;
47 ind.t = table upvalue;
48 ind.idx = key's K index */
49 VINDEXI, /* indexed variable with constant integer;
50 ind.t = table register;
51 ind.idx = key's value */
52 VINDEXSTR, /* indexed variable with literal string;
53 ind.t = table register;
54 ind.idx = key's K index */
55 VJMP, /* expression is a test/comparison;
56 info = pc of corresponding jump instruction */
57 VRELOC, /* expression can put result in any register;
58 info = instruction pc */
59 VCALL, /* expression is a function call; info = instruction pc */
60 VVARARG /* vararg expression; info = instruction pc */
61} expkind;
62
63
64#define vkisvar(k) (VLOCAL <= (k) && (k) <= VINDEXSTR)
65#define vkisindexed(k) (VINDEXED <= (k) && (k) <= VINDEXSTR)
66
67
68typedef struct expdesc {
69 expkind k;
70 union {
71 lua_Integer ival; /* for VKINT */
72 lua_Number nval; /* for VKFLT */
73 TString *strval; /* for VKSTR */
74 int info; /* for generic use */
75 struct { /* for indexed variables */
76 short idx; /* index (R or "long" K) */
77 lu_byte t; /* table (register or upvalue) */
78 } ind;
79 struct { /* for local variables */
80 lu_byte ridx; /* register holding the variable */
81 unsigned short vidx; /* compiler index (in 'actvar.arr') */
82 } var;
83 } u;
84 int t; /* patch list of 'exit when true' */
85 int f; /* patch list of 'exit when false' */
86} expdesc;
87
88
89/* kinds of variables */
90#define VDKREG 0 /* regular */
91#define RDKCONST 1 /* constant */
92#define RDKTOCLOSE 2 /* to-be-closed */
93#define RDKCTC 3 /* compile-time constant */
94
95/* description of an active local variable */
96typedef union Vardesc {
97 struct {
98 TValuefields; /* constant value (if it is a compile-time constant) */
99 lu_byte kind;
100 lu_byte ridx; /* register holding the variable */
101 short pidx; /* index of the variable in the Proto's 'locvars' array */
102 TString *name; /* variable name */
103 } vd;
104 TValue k; /* constant value (if any) */
105} Vardesc;
106
107
108
109/* description of pending goto statements and label statements */
110typedef struct Labeldesc {
111 TString *name; /* label identifier */
112 int pc; /* position in code */
113 int line; /* line where it appeared */
114 lu_byte nactvar; /* number of active variables in that position */
115 lu_byte close; /* goto that escapes upvalues */
116} Labeldesc;
117
118
119/* list of labels or gotos */
120typedef struct Labellist {
121 Labeldesc *arr; /* array */
122 int n; /* number of entries in use */
123 int size; /* array size */
124} Labellist;
125
126
127/* dynamic structures used by the parser */
128typedef struct Dyndata {
129 struct { /* list of all active local variables */
130 Vardesc *arr;
131 int n;
132 int size;
133 } actvar;
134 Labellist gt; /* list of pending gotos */
135 Labellist label; /* list of active labels */
136} Dyndata;
137
138
139/* control of blocks */
140struct BlockCnt; /* defined in lparser.c */
141
142
143/* state needed to generate code for a given function */
144typedef struct FuncState {
145 Proto *f; /* current function header */
146 struct FuncState *prev; /* enclosing function */
147 struct LexState *ls; /* lexical state */
148 struct BlockCnt *bl; /* chain of current blocks */
149 int pc; /* next position to code (equivalent to 'ncode') */
150 int lasttarget; /* 'label' of last 'jump label' */
151 int previousline; /* last line that was saved in 'lineinfo' */
152 int nk; /* number of elements in 'k' */
153 int np; /* number of elements in 'p' */
154 int nabslineinfo; /* number of elements in 'abslineinfo' */
155 int firstlocal; /* index of first local var (in Dyndata array) */
156 int firstlabel; /* index of first label (in 'dyd->label->arr') */
157 short ndebugvars; /* number of elements in 'f->locvars' */
158 lu_byte nactvar; /* number of active local variables */
159 lu_byte nups; /* number of upvalues */
160 lu_byte freereg; /* first free register */
161 lu_byte iwthabs; /* instructions issued since last absolute line info */
162 lu_byte needclose; /* function needs to close upvalues when returning */
163} FuncState;
164
165
166LUAI_FUNC int luaY_nvarstack (FuncState *fs);
167LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
168 Dyndata *dyd, const char *name, int firstchar);
169
170
171#endif
diff --git a/vendor/lua-5.4.8/src/lprefix.h b/vendor/lua-5.4.8/src/lprefix.h
new file mode 100644
index 0000000..484f2ad
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lprefix.h
@@ -0,0 +1,45 @@
1/*
2** $Id: lprefix.h $
3** Definitions for Lua code that must come before any other header file
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lprefix_h
8#define lprefix_h
9
10
11/*
12** Allows POSIX/XSI stuff
13*/
14#if !defined(LUA_USE_C89) /* { */
15
16#if !defined(_XOPEN_SOURCE)
17#define _XOPEN_SOURCE 600
18#elif _XOPEN_SOURCE == 0
19#undef _XOPEN_SOURCE /* use -D_XOPEN_SOURCE=0 to undefine it */
20#endif
21
22/*
23** Allows manipulation of large files in gcc and some other compilers
24*/
25#if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS)
26#define _LARGEFILE_SOURCE 1
27#define _FILE_OFFSET_BITS 64
28#endif
29
30#endif /* } */
31
32
33/*
34** Windows stuff
35*/
36#if defined(_WIN32) /* { */
37
38#if !defined(_CRT_SECURE_NO_WARNINGS)
39#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */
40#endif
41
42#endif /* } */
43
44#endif
45
diff --git a/vendor/lua-5.4.8/src/lstate.c b/vendor/lua-5.4.8/src/lstate.c
new file mode 100644
index 0000000..f3f2ccf
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lstate.c
@@ -0,0 +1,448 @@
1/*
2** $Id: lstate.c $
3** Global State
4** See Copyright Notice in lua.h
5*/
6
7#define lstate_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <stddef.h>
14#include <string.h>
15
16#include "lua.h"
17
18#include "lapi.h"
19#include "ldebug.h"
20#include "ldo.h"
21#include "lfunc.h"
22#include "lgc.h"
23#include "llex.h"
24#include "lmem.h"
25#include "lstate.h"
26#include "lstring.h"
27#include "ltable.h"
28#include "ltm.h"
29
30
31
32/*
33** thread state + extra space
34*/
35typedef struct LX {
36 lu_byte extra_[LUA_EXTRASPACE];
37 lua_State l;
38} LX;
39
40
41/*
42** Main thread combines a thread state and the global state
43*/
44typedef struct LG {
45 LX l;
46 global_State g;
47} LG;
48
49
50
51#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l)))
52
53
54/*
55** A macro to create a "random" seed when a state is created;
56** the seed is used to randomize string hashes.
57*/
58#if !defined(luai_makeseed)
59
60#include <time.h>
61
62/*
63** Compute an initial seed with some level of randomness.
64** Rely on Address Space Layout Randomization (if present) and
65** current time.
66*/
67#define addbuff(b,p,e) \
68 { size_t t = cast_sizet(e); \
69 memcpy(b + p, &t, sizeof(t)); p += sizeof(t); }
70
71static unsigned int luai_makeseed (lua_State *L) {
72 char buff[3 * sizeof(size_t)];
73 unsigned int h = cast_uint(time(NULL));
74 int p = 0;
75 addbuff(buff, p, L); /* heap variable */
76 addbuff(buff, p, &h); /* local variable */
77 addbuff(buff, p, &lua_newstate); /* public function */
78 lua_assert(p == sizeof(buff));
79 return luaS_hash(buff, p, h);
80}
81
82#endif
83
84
85/*
86** set GCdebt to a new value keeping the value (totalbytes + GCdebt)
87** invariant (and avoiding underflows in 'totalbytes')
88*/
89void luaE_setdebt (global_State *g, l_mem debt) {
90 l_mem tb = gettotalbytes(g);
91 lua_assert(tb > 0);
92 if (debt < tb - MAX_LMEM)
93 debt = tb - MAX_LMEM; /* will make 'totalbytes == MAX_LMEM' */
94 g->totalbytes = tb - debt;
95 g->GCdebt = debt;
96}
97
98
99LUA_API int lua_setcstacklimit (lua_State *L, unsigned int limit) {
100 UNUSED(L); UNUSED(limit);
101 return LUAI_MAXCCALLS; /* warning?? */
102}
103
104
105CallInfo *luaE_extendCI (lua_State *L) {
106 CallInfo *ci;
107 lua_assert(L->ci->next == NULL);
108 ci = luaM_new(L, CallInfo);
109 lua_assert(L->ci->next == NULL);
110 L->ci->next = ci;
111 ci->previous = L->ci;
112 ci->next = NULL;
113 ci->u.l.trap = 0;
114 L->nci++;
115 return ci;
116}
117
118
119/*
120** free all CallInfo structures not in use by a thread
121*/
122static void freeCI (lua_State *L) {
123 CallInfo *ci = L->ci;
124 CallInfo *next = ci->next;
125 ci->next = NULL;
126 while ((ci = next) != NULL) {
127 next = ci->next;
128 luaM_free(L, ci);
129 L->nci--;
130 }
131}
132
133
134/*
135** free half of the CallInfo structures not in use by a thread,
136** keeping the first one.
137*/
138void luaE_shrinkCI (lua_State *L) {
139 CallInfo *ci = L->ci->next; /* first free CallInfo */
140 CallInfo *next;
141 if (ci == NULL)
142 return; /* no extra elements */
143 while ((next = ci->next) != NULL) { /* two extra elements? */
144 CallInfo *next2 = next->next; /* next's next */
145 ci->next = next2; /* remove next from the list */
146 L->nci--;
147 luaM_free(L, next); /* free next */
148 if (next2 == NULL)
149 break; /* no more elements */
150 else {
151 next2->previous = ci;
152 ci = next2; /* continue */
153 }
154 }
155}
156
157
158/*
159** Called when 'getCcalls(L)' larger or equal to LUAI_MAXCCALLS.
160** If equal, raises an overflow error. If value is larger than
161** LUAI_MAXCCALLS (which means it is handling an overflow) but
162** not much larger, does not report an error (to allow overflow
163** handling to work).
164*/
165void luaE_checkcstack (lua_State *L) {
166 if (getCcalls(L) == LUAI_MAXCCALLS)
167 luaG_runerror(L, "C stack overflow");
168 else if (getCcalls(L) >= (LUAI_MAXCCALLS / 10 * 11))
169 luaD_errerr(L); /* error while handling stack error */
170}
171
172
173LUAI_FUNC void luaE_incCstack (lua_State *L) {
174 L->nCcalls++;
175 if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS))
176 luaE_checkcstack(L);
177}
178
179
180static void stack_init (lua_State *L1, lua_State *L) {
181 int i; CallInfo *ci;
182 /* initialize stack array */
183 L1->stack.p = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, StackValue);
184 L1->tbclist.p = L1->stack.p;
185 for (i = 0; i < BASIC_STACK_SIZE + EXTRA_STACK; i++)
186 setnilvalue(s2v(L1->stack.p + i)); /* erase new stack */
187 L1->top.p = L1->stack.p;
188 L1->stack_last.p = L1->stack.p + BASIC_STACK_SIZE;
189 /* initialize first ci */
190 ci = &L1->base_ci;
191 ci->next = ci->previous = NULL;
192 ci->callstatus = CIST_C;
193 ci->func.p = L1->top.p;
194 ci->u.c.k = NULL;
195 ci->nresults = 0;
196 setnilvalue(s2v(L1->top.p)); /* 'function' entry for this 'ci' */
197 L1->top.p++;
198 ci->top.p = L1->top.p + LUA_MINSTACK;
199 L1->ci = ci;
200}
201
202
203static void freestack (lua_State *L) {
204 if (L->stack.p == NULL)
205 return; /* stack not completely built yet */
206 L->ci = &L->base_ci; /* free the entire 'ci' list */
207 freeCI(L);
208 lua_assert(L->nci == 0);
209 luaM_freearray(L, L->stack.p, stacksize(L) + EXTRA_STACK); /* free stack */
210}
211
212
213/*
214** Create registry table and its predefined values
215*/
216static void init_registry (lua_State *L, global_State *g) {
217 /* create registry */
218 Table *registry = luaH_new(L);
219 sethvalue(L, &g->l_registry, registry);
220 luaH_resize(L, registry, LUA_RIDX_LAST, 0);
221 /* registry[LUA_RIDX_MAINTHREAD] = L */
222 setthvalue(L, &registry->array[LUA_RIDX_MAINTHREAD - 1], L);
223 /* registry[LUA_RIDX_GLOBALS] = new table (table of globals) */
224 sethvalue(L, &registry->array[LUA_RIDX_GLOBALS - 1], luaH_new(L));
225}
226
227
228/*
229** open parts of the state that may cause memory-allocation errors.
230*/
231static void f_luaopen (lua_State *L, void *ud) {
232 global_State *g = G(L);
233 UNUSED(ud);
234 stack_init(L, L); /* init stack */
235 init_registry(L, g);
236 luaS_init(L);
237 luaT_init(L);
238 luaX_init(L);
239 g->gcstp = 0; /* allow gc */
240 setnilvalue(&g->nilvalue); /* now state is complete */
241 luai_userstateopen(L);
242}
243
244
245/*
246** preinitialize a thread with consistent values without allocating
247** any memory (to avoid errors)
248*/
249static void preinit_thread (lua_State *L, global_State *g) {
250 G(L) = g;
251 L->stack.p = NULL;
252 L->ci = NULL;
253 L->nci = 0;
254 L->twups = L; /* thread has no upvalues */
255 L->nCcalls = 0;
256 L->errorJmp = NULL;
257 L->hook = NULL;
258 L->hookmask = 0;
259 L->basehookcount = 0;
260 L->allowhook = 1;
261 resethookcount(L);
262 L->openupval = NULL;
263 L->status = LUA_OK;
264 L->errfunc = 0;
265 L->oldpc = 0;
266}
267
268
269static void close_state (lua_State *L) {
270 global_State *g = G(L);
271 if (!completestate(g)) /* closing a partially built state? */
272 luaC_freeallobjects(L); /* just collect its objects */
273 else { /* closing a fully built state */
274 L->ci = &L->base_ci; /* unwind CallInfo list */
275 L->errfunc = 0; /* stack unwind can "throw away" the error function */
276 luaD_closeprotected(L, 1, LUA_OK); /* close all upvalues */
277 L->top.p = L->stack.p + 1; /* empty the stack to run finalizers */
278 luaC_freeallobjects(L); /* collect all objects */
279 luai_userstateclose(L);
280 }
281 luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);
282 freestack(L);
283 lua_assert(gettotalbytes(g) == sizeof(LG));
284 (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */
285}
286
287
288LUA_API lua_State *lua_newthread (lua_State *L) {
289 global_State *g = G(L);
290 GCObject *o;
291 lua_State *L1;
292 lua_lock(L);
293 luaC_checkGC(L);
294 /* create new thread */
295 o = luaC_newobjdt(L, LUA_TTHREAD, sizeof(LX), offsetof(LX, l));
296 L1 = gco2th(o);
297 /* anchor it on L stack */
298 setthvalue2s(L, L->top.p, L1);
299 api_incr_top(L);
300 preinit_thread(L1, g);
301 L1->hookmask = L->hookmask;
302 L1->basehookcount = L->basehookcount;
303 L1->hook = L->hook;
304 resethookcount(L1);
305 /* initialize L1 extra space */
306 memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread),
307 LUA_EXTRASPACE);
308 luai_userstatethread(L, L1);
309 stack_init(L1, L); /* init stack */
310 lua_unlock(L);
311 return L1;
312}
313
314
315void luaE_freethread (lua_State *L, lua_State *L1) {
316 LX *l = fromstate(L1);
317 luaF_closeupval(L1, L1->stack.p); /* close all upvalues */
318 lua_assert(L1->openupval == NULL);
319 luai_userstatefree(L, L1);
320 freestack(L1);
321 luaM_free(L, l);
322}
323
324
325int luaE_resetthread (lua_State *L, int status) {
326 CallInfo *ci = L->ci = &L->base_ci; /* unwind CallInfo list */
327 setnilvalue(s2v(L->stack.p)); /* 'function' entry for basic 'ci' */
328 ci->func.p = L->stack.p;
329 ci->callstatus = CIST_C;
330 if (status == LUA_YIELD)
331 status = LUA_OK;
332 L->status = LUA_OK; /* so it can run __close metamethods */
333 L->errfunc = 0; /* stack unwind can "throw away" the error function */
334 status = luaD_closeprotected(L, 1, status);
335 if (status != LUA_OK) /* errors? */
336 luaD_seterrorobj(L, status, L->stack.p + 1);
337 else
338 L->top.p = L->stack.p + 1;
339 ci->top.p = L->top.p + LUA_MINSTACK;
340 luaD_reallocstack(L, cast_int(ci->top.p - L->stack.p), 0);
341 return status;
342}
343
344
345LUA_API int lua_closethread (lua_State *L, lua_State *from) {
346 int status;
347 lua_lock(L);
348 L->nCcalls = (from) ? getCcalls(from) : 0;
349 status = luaE_resetthread(L, L->status);
350 lua_unlock(L);
351 return status;
352}
353
354
355/*
356** Deprecated! Use 'lua_closethread' instead.
357*/
358LUA_API int lua_resetthread (lua_State *L) {
359 return lua_closethread(L, NULL);
360}
361
362
363LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
364 int i;
365 lua_State *L;
366 global_State *g;
367 LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG)));
368 if (l == NULL) return NULL;
369 L = &l->l.l;
370 g = &l->g;
371 L->tt = LUA_VTHREAD;
372 g->currentwhite = bitmask(WHITE0BIT);
373 L->marked = luaC_white(g);
374 preinit_thread(L, g);
375 g->allgc = obj2gco(L); /* by now, only object is the main thread */
376 L->next = NULL;
377 incnny(L); /* main thread is always non yieldable */
378 g->frealloc = f;
379 g->ud = ud;
380 g->warnf = NULL;
381 g->ud_warn = NULL;
382 g->mainthread = L;
383 g->seed = luai_makeseed(L);
384 g->gcstp = GCSTPGC; /* no GC while building state */
385 g->strt.size = g->strt.nuse = 0;
386 g->strt.hash = NULL;
387 setnilvalue(&g->l_registry);
388 g->panic = NULL;
389 g->gcstate = GCSpause;
390 g->gckind = KGC_INC;
391 g->gcstopem = 0;
392 g->gcemergency = 0;
393 g->finobj = g->tobefnz = g->fixedgc = NULL;
394 g->firstold1 = g->survival = g->old1 = g->reallyold = NULL;
395 g->finobjsur = g->finobjold1 = g->finobjrold = NULL;
396 g->sweepgc = NULL;
397 g->gray = g->grayagain = NULL;
398 g->weak = g->ephemeron = g->allweak = NULL;
399 g->twups = NULL;
400 g->totalbytes = sizeof(LG);
401 g->GCdebt = 0;
402 g->lastatomic = 0;
403 setivalue(&g->nilvalue, 0); /* to signal that state is not yet built */
404 setgcparam(g->gcpause, LUAI_GCPAUSE);
405 setgcparam(g->gcstepmul, LUAI_GCMUL);
406 g->gcstepsize = LUAI_GCSTEPSIZE;
407 setgcparam(g->genmajormul, LUAI_GENMAJORMUL);
408 g->genminormul = LUAI_GENMINORMUL;
409 for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL;
410 if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {
411 /* memory allocation error: free partial state */
412 close_state(L);
413 L = NULL;
414 }
415 return L;
416}
417
418
419LUA_API void lua_close (lua_State *L) {
420 lua_lock(L);
421 L = G(L)->mainthread; /* only the main thread can be closed */
422 close_state(L);
423}
424
425
426void luaE_warning (lua_State *L, const char *msg, int tocont) {
427 lua_WarnFunction wf = G(L)->warnf;
428 if (wf != NULL)
429 wf(G(L)->ud_warn, msg, tocont);
430}
431
432
433/*
434** Generate a warning from an error message
435*/
436void luaE_warnerror (lua_State *L, const char *where) {
437 TValue *errobj = s2v(L->top.p - 1); /* error object */
438 const char *msg = (ttisstring(errobj))
439 ? getstr(tsvalue(errobj))
440 : "error object is not a string";
441 /* produce warning "error in %s (%s)" (where, msg) */
442 luaE_warning(L, "error in ", 1);
443 luaE_warning(L, where, 1);
444 luaE_warning(L, " (", 1);
445 luaE_warning(L, msg, 1);
446 luaE_warning(L, ")", 0);
447}
448
diff --git a/vendor/lua-5.4.8/src/lstate.h b/vendor/lua-5.4.8/src/lstate.h
new file mode 100644
index 0000000..007704c
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lstate.h
@@ -0,0 +1,408 @@
1/*
2** $Id: lstate.h $
3** Global State
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lstate_h
8#define lstate_h
9
10#include "lua.h"
11
12
13/* Some header files included here need this definition */
14typedef struct CallInfo CallInfo;
15
16
17#include "lobject.h"
18#include "ltm.h"
19#include "lzio.h"
20
21
22/*
23** Some notes about garbage-collected objects: All objects in Lua must
24** be kept somehow accessible until being freed, so all objects always
25** belong to one (and only one) of these lists, using field 'next' of
26** the 'CommonHeader' for the link:
27**
28** 'allgc': all objects not marked for finalization;
29** 'finobj': all objects marked for finalization;
30** 'tobefnz': all objects ready to be finalized;
31** 'fixedgc': all objects that are not to be collected (currently
32** only small strings, such as reserved words).
33**
34** For the generational collector, some of these lists have marks for
35** generations. Each mark points to the first element in the list for
36** that particular generation; that generation goes until the next mark.
37**
38** 'allgc' -> 'survival': new objects;
39** 'survival' -> 'old': objects that survived one collection;
40** 'old1' -> 'reallyold': objects that became old in last collection;
41** 'reallyold' -> NULL: objects old for more than one cycle.
42**
43** 'finobj' -> 'finobjsur': new objects marked for finalization;
44** 'finobjsur' -> 'finobjold1': survived """";
45** 'finobjold1' -> 'finobjrold': just old """";
46** 'finobjrold' -> NULL: really old """".
47**
48** All lists can contain elements older than their main ages, due
49** to 'luaC_checkfinalizer' and 'udata2finalize', which move
50** objects between the normal lists and the "marked for finalization"
51** lists. Moreover, barriers can age young objects in young lists as
52** OLD0, which then become OLD1. However, a list never contains
53** elements younger than their main ages.
54**
55** The generational collector also uses a pointer 'firstold1', which
56** points to the first OLD1 object in the list. It is used to optimize
57** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc'
58** and 'reallyold', but often the list has no OLD1 objects or they are
59** after 'old1'.) Note the difference between it and 'old1':
60** 'firstold1': no OLD1 objects before this point; there can be all
61** ages after it.
62** 'old1': no objects younger than OLD1 after this point.
63*/
64
65/*
66** Moreover, there is another set of lists that control gray objects.
67** These lists are linked by fields 'gclist'. (All objects that
68** can become gray have such a field. The field is not the same
69** in all objects, but it always has this name.) Any gray object
70** must belong to one of these lists, and all objects in these lists
71** must be gray (with two exceptions explained below):
72**
73** 'gray': regular gray objects, still waiting to be visited.
74** 'grayagain': objects that must be revisited at the atomic phase.
75** That includes
76** - black objects got in a write barrier;
77** - all kinds of weak tables during propagation phase;
78** - all threads.
79** 'weak': tables with weak values to be cleared;
80** 'ephemeron': ephemeron tables with white->white entries;
81** 'allweak': tables with weak keys and/or weak values to be cleared.
82**
83** The exceptions to that "gray rule" are:
84** - TOUCHED2 objects in generational mode stay in a gray list (because
85** they must be visited again at the end of the cycle), but they are
86** marked black because assignments to them must activate barriers (to
87** move them back to TOUCHED1).
88** - Open upvales are kept gray to avoid barriers, but they stay out
89** of gray lists. (They don't even have a 'gclist' field.)
90*/
91
92
93
94/*
95** About 'nCcalls': This count has two parts: the lower 16 bits counts
96** the number of recursive invocations in the C stack; the higher
97** 16 bits counts the number of non-yieldable calls in the stack.
98** (They are together so that we can change and save both with one
99** instruction.)
100*/
101
102
103/* true if this thread does not have non-yieldable calls in the stack */
104#define yieldable(L) (((L)->nCcalls & 0xffff0000) == 0)
105
106/* real number of C calls */
107#define getCcalls(L) ((L)->nCcalls & 0xffff)
108
109
110/* Increment the number of non-yieldable calls */
111#define incnny(L) ((L)->nCcalls += 0x10000)
112
113/* Decrement the number of non-yieldable calls */
114#define decnny(L) ((L)->nCcalls -= 0x10000)
115
116/* Non-yieldable call increment */
117#define nyci (0x10000 | 1)
118
119
120
121
122struct lua_longjmp; /* defined in ldo.c */
123
124
125/*
126** Atomic type (relative to signals) to better ensure that 'lua_sethook'
127** is thread safe
128*/
129#if !defined(l_signalT)
130#include <signal.h>
131#define l_signalT sig_atomic_t
132#endif
133
134
135/*
136** Extra stack space to handle TM calls and some other extras. This
137** space is not included in 'stack_last'. It is used only to avoid stack
138** checks, either because the element will be promptly popped or because
139** there will be a stack check soon after the push. Function frames
140** never use this extra space, so it does not need to be kept clean.
141*/
142#define EXTRA_STACK 5
143
144
145#define BASIC_STACK_SIZE (2*LUA_MINSTACK)
146
147#define stacksize(th) cast_int((th)->stack_last.p - (th)->stack.p)
148
149
150/* kinds of Garbage Collection */
151#define KGC_INC 0 /* incremental gc */
152#define KGC_GEN 1 /* generational gc */
153
154
155typedef struct stringtable {
156 TString **hash;
157 int nuse; /* number of elements */
158 int size;
159} stringtable;
160
161
162/*
163** Information about a call.
164** About union 'u':
165** - field 'l' is used only for Lua functions;
166** - field 'c' is used only for C functions.
167** About union 'u2':
168** - field 'funcidx' is used only by C functions while doing a
169** protected call;
170** - field 'nyield' is used only while a function is "doing" an
171** yield (from the yield until the next resume);
172** - field 'nres' is used only while closing tbc variables when
173** returning from a function;
174** - field 'transferinfo' is used only during call/returnhooks,
175** before the function starts or after it ends.
176*/
177struct CallInfo {
178 StkIdRel func; /* function index in the stack */
179 StkIdRel top; /* top for this function */
180 struct CallInfo *previous, *next; /* dynamic call link */
181 union {
182 struct { /* only for Lua functions */
183 const Instruction *savedpc;
184 volatile l_signalT trap; /* function is tracing lines/counts */
185 int nextraargs; /* # of extra arguments in vararg functions */
186 } l;
187 struct { /* only for C functions */
188 lua_KFunction k; /* continuation in case of yields */
189 ptrdiff_t old_errfunc;
190 lua_KContext ctx; /* context info. in case of yields */
191 } c;
192 } u;
193 union {
194 int funcidx; /* called-function index */
195 int nyield; /* number of values yielded */
196 int nres; /* number of values returned */
197 struct { /* info about transferred values (for call/return hooks) */
198 unsigned short ftransfer; /* offset of first value transferred */
199 unsigned short ntransfer; /* number of values transferred */
200 } transferinfo;
201 } u2;
202 short nresults; /* expected number of results from this function */
203 unsigned short callstatus;
204};
205
206
207/*
208** Bits in CallInfo status
209*/
210#define CIST_OAH (1<<0) /* original value of 'allowhook' */
211#define CIST_C (1<<1) /* call is running a C function */
212#define CIST_FRESH (1<<2) /* call is on a fresh "luaV_execute" frame */
213#define CIST_HOOKED (1<<3) /* call is running a debug hook */
214#define CIST_YPCALL (1<<4) /* doing a yieldable protected call */
215#define CIST_TAIL (1<<5) /* call was tail called */
216#define CIST_HOOKYIELD (1<<6) /* last hook called yielded */
217#define CIST_FIN (1<<7) /* function "called" a finalizer */
218#define CIST_TRAN (1<<8) /* 'ci' has transfer information */
219#define CIST_CLSRET (1<<9) /* function is closing tbc variables */
220/* Bits 10-12 are used for CIST_RECST (see below) */
221#define CIST_RECST 10
222#if defined(LUA_COMPAT_LT_LE)
223#define CIST_LEQ (1<<13) /* using __lt for __le */
224#endif
225
226
227/*
228** Field CIST_RECST stores the "recover status", used to keep the error
229** status while closing to-be-closed variables in coroutines, so that
230** Lua can correctly resume after an yield from a __close method called
231** because of an error. (Three bits are enough for error status.)
232*/
233#define getcistrecst(ci) (((ci)->callstatus >> CIST_RECST) & 7)
234#define setcistrecst(ci,st) \
235 check_exp(((st) & 7) == (st), /* status must fit in three bits */ \
236 ((ci)->callstatus = ((ci)->callstatus & ~(7 << CIST_RECST)) \
237 | ((st) << CIST_RECST)))
238
239
240/* active function is a Lua function */
241#define isLua(ci) (!((ci)->callstatus & CIST_C))
242
243/* call is running Lua code (not a hook) */
244#define isLuacode(ci) (!((ci)->callstatus & (CIST_C | CIST_HOOKED)))
245
246/* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */
247#define setoah(st,v) ((st) = ((st) & ~CIST_OAH) | (v))
248#define getoah(st) ((st) & CIST_OAH)
249
250
251/*
252** 'global state', shared by all threads of this state
253*/
254typedef struct global_State {
255 lua_Alloc frealloc; /* function to reallocate memory */
256 void *ud; /* auxiliary data to 'frealloc' */
257 l_mem totalbytes; /* number of bytes currently allocated - GCdebt */
258 l_mem GCdebt; /* bytes allocated not yet compensated by the collector */
259 lu_mem GCestimate; /* an estimate of the non-garbage memory in use */
260 lu_mem lastatomic; /* see function 'genstep' in file 'lgc.c' */
261 stringtable strt; /* hash table for strings */
262 TValue l_registry;
263 TValue nilvalue; /* a nil value */
264 unsigned int seed; /* randomized seed for hashes */
265 lu_byte currentwhite;
266 lu_byte gcstate; /* state of garbage collector */
267 lu_byte gckind; /* kind of GC running */
268 lu_byte gcstopem; /* stops emergency collections */
269 lu_byte genminormul; /* control for minor generational collections */
270 lu_byte genmajormul; /* control for major generational collections */
271 lu_byte gcstp; /* control whether GC is running */
272 lu_byte gcemergency; /* true if this is an emergency collection */
273 lu_byte gcpause; /* size of pause between successive GCs */
274 lu_byte gcstepmul; /* GC "speed" */
275 lu_byte gcstepsize; /* (log2 of) GC granularity */
276 GCObject *allgc; /* list of all collectable objects */
277 GCObject **sweepgc; /* current position of sweep in list */
278 GCObject *finobj; /* list of collectable objects with finalizers */
279 GCObject *gray; /* list of gray objects */
280 GCObject *grayagain; /* list of objects to be traversed atomically */
281 GCObject *weak; /* list of tables with weak values */
282 GCObject *ephemeron; /* list of ephemeron tables (weak keys) */
283 GCObject *allweak; /* list of all-weak tables */
284 GCObject *tobefnz; /* list of userdata to be GC */
285 GCObject *fixedgc; /* list of objects not to be collected */
286 /* fields for generational collector */
287 GCObject *survival; /* start of objects that survived one GC cycle */
288 GCObject *old1; /* start of old1 objects */
289 GCObject *reallyold; /* objects more than one cycle old ("really old") */
290 GCObject *firstold1; /* first OLD1 object in the list (if any) */
291 GCObject *finobjsur; /* list of survival objects with finalizers */
292 GCObject *finobjold1; /* list of old1 objects with finalizers */
293 GCObject *finobjrold; /* list of really old objects with finalizers */
294 struct lua_State *twups; /* list of threads with open upvalues */
295 lua_CFunction panic; /* to be called in unprotected errors */
296 struct lua_State *mainthread;
297 TString *memerrmsg; /* message for memory-allocation errors */
298 TString *tmname[TM_N]; /* array with tag-method names */
299 struct Table *mt[LUA_NUMTYPES]; /* metatables for basic types */
300 TString *strcache[STRCACHE_N][STRCACHE_M]; /* cache for strings in API */
301 lua_WarnFunction warnf; /* warning function */
302 void *ud_warn; /* auxiliary data to 'warnf' */
303} global_State;
304
305
306/*
307** 'per thread' state
308*/
309struct lua_State {
310 CommonHeader;
311 lu_byte status;
312 lu_byte allowhook;
313 unsigned short nci; /* number of items in 'ci' list */
314 StkIdRel top; /* first free slot in the stack */
315 global_State *l_G;
316 CallInfo *ci; /* call info for current function */
317 StkIdRel stack_last; /* end of stack (last element + 1) */
318 StkIdRel stack; /* stack base */
319 UpVal *openupval; /* list of open upvalues in this stack */
320 StkIdRel tbclist; /* list of to-be-closed variables */
321 GCObject *gclist;
322 struct lua_State *twups; /* list of threads with open upvalues */
323 struct lua_longjmp *errorJmp; /* current error recover point */
324 CallInfo base_ci; /* CallInfo for first level (C calling Lua) */
325 volatile lua_Hook hook;
326 ptrdiff_t errfunc; /* current error handling function (stack index) */
327 l_uint32 nCcalls; /* number of nested (non-yieldable | C) calls */
328 int oldpc; /* last pc traced */
329 int basehookcount;
330 int hookcount;
331 volatile l_signalT hookmask;
332};
333
334
335#define G(L) (L->l_G)
336
337/*
338** 'g->nilvalue' being a nil value flags that the state was completely
339** build.
340*/
341#define completestate(g) ttisnil(&g->nilvalue)
342
343
344/*
345** Union of all collectable objects (only for conversions)
346** ISO C99, 6.5.2.3 p.5:
347** "if a union contains several structures that share a common initial
348** sequence [...], and if the union object currently contains one
349** of these structures, it is permitted to inspect the common initial
350** part of any of them anywhere that a declaration of the complete type
351** of the union is visible."
352*/
353union GCUnion {
354 GCObject gc; /* common header */
355 struct TString ts;
356 struct Udata u;
357 union Closure cl;
358 struct Table h;
359 struct Proto p;
360 struct lua_State th; /* thread */
361 struct UpVal upv;
362};
363
364
365/*
366** ISO C99, 6.7.2.1 p.14:
367** "A pointer to a union object, suitably converted, points to each of
368** its members [...], and vice versa."
369*/
370#define cast_u(o) cast(union GCUnion *, (o))
371
372/* macros to convert a GCObject into a specific value */
373#define gco2ts(o) \
374 check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
375#define gco2u(o) check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))
376#define gco2lcl(o) check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))
377#define gco2ccl(o) check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))
378#define gco2cl(o) \
379 check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
380#define gco2t(o) check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))
381#define gco2p(o) check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))
382#define gco2th(o) check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))
383#define gco2upv(o) check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))
384
385
386/*
387** macro to convert a Lua object into a GCObject
388** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.)
389*/
390#define obj2gco(v) check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc))
391
392
393/* actual number of total bytes allocated */
394#define gettotalbytes(g) cast(lu_mem, (g)->totalbytes + (g)->GCdebt)
395
396LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
397LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
398LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
399LUAI_FUNC void luaE_shrinkCI (lua_State *L);
400LUAI_FUNC void luaE_checkcstack (lua_State *L);
401LUAI_FUNC void luaE_incCstack (lua_State *L);
402LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);
403LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);
404LUAI_FUNC int luaE_resetthread (lua_State *L, int status);
405
406
407#endif
408
diff --git a/vendor/lua-5.4.8/src/lstring.c b/vendor/lua-5.4.8/src/lstring.c
new file mode 100644
index 0000000..9775735
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lstring.c
@@ -0,0 +1,274 @@
1/*
2** $Id: lstring.c $
3** String table (keeps all strings handled by Lua)
4** See Copyright Notice in lua.h
5*/
6
7#define lstring_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <string.h>
14
15#include "lua.h"
16
17#include "ldebug.h"
18#include "ldo.h"
19#include "lmem.h"
20#include "lobject.h"
21#include "lstate.h"
22#include "lstring.h"
23
24
25/*
26** Maximum size for string table.
27*/
28#define MAXSTRTB cast_int(luaM_limitN(MAX_INT, TString*))
29
30
31/*
32** equality for long strings
33*/
34int luaS_eqlngstr (TString *a, TString *b) {
35 size_t len = a->u.lnglen;
36 lua_assert(a->tt == LUA_VLNGSTR && b->tt == LUA_VLNGSTR);
37 return (a == b) || /* same instance or... */
38 ((len == b->u.lnglen) && /* equal length and ... */
39 (memcmp(getlngstr(a), getlngstr(b), len) == 0)); /* equal contents */
40}
41
42
43unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) {
44 unsigned int h = seed ^ cast_uint(l);
45 for (; l > 0; l--)
46 h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1]));
47 return h;
48}
49
50
51unsigned int luaS_hashlongstr (TString *ts) {
52 lua_assert(ts->tt == LUA_VLNGSTR);
53 if (ts->extra == 0) { /* no hash? */
54 size_t len = ts->u.lnglen;
55 ts->hash = luaS_hash(getlngstr(ts), len, ts->hash);
56 ts->extra = 1; /* now it has its hash */
57 }
58 return ts->hash;
59}
60
61
62static void tablerehash (TString **vect, int osize, int nsize) {
63 int i;
64 for (i = osize; i < nsize; i++) /* clear new elements */
65 vect[i] = NULL;
66 for (i = 0; i < osize; i++) { /* rehash old part of the array */
67 TString *p = vect[i];
68 vect[i] = NULL;
69 while (p) { /* for each string in the list */
70 TString *hnext = p->u.hnext; /* save next */
71 unsigned int h = lmod(p->hash, nsize); /* new position */
72 p->u.hnext = vect[h]; /* chain it into array */
73 vect[h] = p;
74 p = hnext;
75 }
76 }
77}
78
79
80/*
81** Resize the string table. If allocation fails, keep the current size.
82** (This can degrade performance, but any non-zero size should work
83** correctly.)
84*/
85void luaS_resize (lua_State *L, int nsize) {
86 stringtable *tb = &G(L)->strt;
87 int osize = tb->size;
88 TString **newvect;
89 if (nsize < osize) /* shrinking table? */
90 tablerehash(tb->hash, osize, nsize); /* depopulate shrinking part */
91 newvect = luaM_reallocvector(L, tb->hash, osize, nsize, TString*);
92 if (l_unlikely(newvect == NULL)) { /* reallocation failed? */
93 if (nsize < osize) /* was it shrinking table? */
94 tablerehash(tb->hash, nsize, osize); /* restore to original size */
95 /* leave table as it was */
96 }
97 else { /* allocation succeeded */
98 tb->hash = newvect;
99 tb->size = nsize;
100 if (nsize > osize)
101 tablerehash(newvect, osize, nsize); /* rehash for new size */
102 }
103}
104
105
106/*
107** Clear API string cache. (Entries cannot be empty, so fill them with
108** a non-collectable string.)
109*/
110void luaS_clearcache (global_State *g) {
111 int i, j;
112 for (i = 0; i < STRCACHE_N; i++)
113 for (j = 0; j < STRCACHE_M; j++) {
114 if (iswhite(g->strcache[i][j])) /* will entry be collected? */
115 g->strcache[i][j] = g->memerrmsg; /* replace it with something fixed */
116 }
117}
118
119
120/*
121** Initialize the string table and the string cache
122*/
123void luaS_init (lua_State *L) {
124 global_State *g = G(L);
125 int i, j;
126 stringtable *tb = &G(L)->strt;
127 tb->hash = luaM_newvector(L, MINSTRTABSIZE, TString*);
128 tablerehash(tb->hash, 0, MINSTRTABSIZE); /* clear array */
129 tb->size = MINSTRTABSIZE;
130 /* pre-create memory-error message */
131 g->memerrmsg = luaS_newliteral(L, MEMERRMSG);
132 luaC_fix(L, obj2gco(g->memerrmsg)); /* it should never be collected */
133 for (i = 0; i < STRCACHE_N; i++) /* fill cache with valid strings */
134 for (j = 0; j < STRCACHE_M; j++)
135 g->strcache[i][j] = g->memerrmsg;
136}
137
138
139
140/*
141** creates a new string object
142*/
143static TString *createstrobj (lua_State *L, size_t l, int tag, unsigned int h) {
144 TString *ts;
145 GCObject *o;
146 size_t totalsize; /* total size of TString object */
147 totalsize = sizelstring(l);
148 o = luaC_newobj(L, tag, totalsize);
149 ts = gco2ts(o);
150 ts->hash = h;
151 ts->extra = 0;
152 getstr(ts)[l] = '\0'; /* ending 0 */
153 return ts;
154}
155
156
157TString *luaS_createlngstrobj (lua_State *L, size_t l) {
158 TString *ts = createstrobj(L, l, LUA_VLNGSTR, G(L)->seed);
159 ts->u.lnglen = l;
160 ts->shrlen = 0xFF; /* signals that it is a long string */
161 return ts;
162}
163
164
165void luaS_remove (lua_State *L, TString *ts) {
166 stringtable *tb = &G(L)->strt;
167 TString **p = &tb->hash[lmod(ts->hash, tb->size)];
168 while (*p != ts) /* find previous element */
169 p = &(*p)->u.hnext;
170 *p = (*p)->u.hnext; /* remove element from its list */
171 tb->nuse--;
172}
173
174
175static void growstrtab (lua_State *L, stringtable *tb) {
176 if (l_unlikely(tb->nuse == MAX_INT)) { /* too many strings? */
177 luaC_fullgc(L, 1); /* try to free some... */
178 if (tb->nuse == MAX_INT) /* still too many? */
179 luaM_error(L); /* cannot even create a message... */
180 }
181 if (tb->size <= MAXSTRTB / 2) /* can grow string table? */
182 luaS_resize(L, tb->size * 2);
183}
184
185
186/*
187** Checks whether short string exists and reuses it or creates a new one.
188*/
189static TString *internshrstr (lua_State *L, const char *str, size_t l) {
190 TString *ts;
191 global_State *g = G(L);
192 stringtable *tb = &g->strt;
193 unsigned int h = luaS_hash(str, l, g->seed);
194 TString **list = &tb->hash[lmod(h, tb->size)];
195 lua_assert(str != NULL); /* otherwise 'memcmp'/'memcpy' are undefined */
196 for (ts = *list; ts != NULL; ts = ts->u.hnext) {
197 if (l == ts->shrlen && (memcmp(str, getshrstr(ts), l * sizeof(char)) == 0)) {
198 /* found! */
199 if (isdead(g, ts)) /* dead (but not collected yet)? */
200 changewhite(ts); /* resurrect it */
201 return ts;
202 }
203 }
204 /* else must create a new string */
205 if (tb->nuse >= tb->size) { /* need to grow string table? */
206 growstrtab(L, tb);
207 list = &tb->hash[lmod(h, tb->size)]; /* rehash with new size */
208 }
209 ts = createstrobj(L, l, LUA_VSHRSTR, h);
210 ts->shrlen = cast_byte(l);
211 memcpy(getshrstr(ts), str, l * sizeof(char));
212 ts->u.hnext = *list;
213 *list = ts;
214 tb->nuse++;
215 return ts;
216}
217
218
219/*
220** new string (with explicit length)
221*/
222TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
223 if (l <= LUAI_MAXSHORTLEN) /* short string? */
224 return internshrstr(L, str, l);
225 else {
226 TString *ts;
227 if (l_unlikely(l * sizeof(char) >= (MAX_SIZE - sizeof(TString))))
228 luaM_toobig(L);
229 ts = luaS_createlngstrobj(L, l);
230 memcpy(getlngstr(ts), str, l * sizeof(char));
231 return ts;
232 }
233}
234
235
236/*
237** Create or reuse a zero-terminated string, first checking in the
238** cache (using the string address as a key). The cache can contain
239** only zero-terminated strings, so it is safe to use 'strcmp' to
240** check hits.
241*/
242TString *luaS_new (lua_State *L, const char *str) {
243 unsigned int i = point2uint(str) % STRCACHE_N; /* hash */
244 int j;
245 TString **p = G(L)->strcache[i];
246 for (j = 0; j < STRCACHE_M; j++) {
247 if (strcmp(str, getstr(p[j])) == 0) /* hit? */
248 return p[j]; /* that is it */
249 }
250 /* normal route */
251 for (j = STRCACHE_M - 1; j > 0; j--)
252 p[j] = p[j - 1]; /* move out last element */
253 /* new element is first in the list */
254 p[0] = luaS_newlstr(L, str, strlen(str));
255 return p[0];
256}
257
258
259Udata *luaS_newudata (lua_State *L, size_t s, int nuvalue) {
260 Udata *u;
261 int i;
262 GCObject *o;
263 if (l_unlikely(s > MAX_SIZE - udatamemoffset(nuvalue)))
264 luaM_toobig(L);
265 o = luaC_newobj(L, LUA_VUSERDATA, sizeudata(nuvalue, s));
266 u = gco2u(o);
267 u->len = s;
268 u->nuvalue = nuvalue;
269 u->metatable = NULL;
270 for (i = 0; i < nuvalue; i++)
271 setnilvalue(&u->uv[i].uv);
272 return u;
273}
274
diff --git a/vendor/lua-5.4.8/src/lstring.h b/vendor/lua-5.4.8/src/lstring.h
new file mode 100644
index 0000000..450c239
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lstring.h
@@ -0,0 +1,57 @@
1/*
2** $Id: lstring.h $
3** String table (keep all strings handled by Lua)
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lstring_h
8#define lstring_h
9
10#include "lgc.h"
11#include "lobject.h"
12#include "lstate.h"
13
14
15/*
16** Memory-allocation error message must be preallocated (it cannot
17** be created after memory is exhausted)
18*/
19#define MEMERRMSG "not enough memory"
20
21
22/*
23** Size of a TString: Size of the header plus space for the string
24** itself (including final '\0').
25*/
26#define sizelstring(l) (offsetof(TString, contents) + ((l) + 1) * sizeof(char))
27
28#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
29 (sizeof(s)/sizeof(char))-1))
30
31
32/*
33** test whether a string is a reserved word
34*/
35#define isreserved(s) ((s)->tt == LUA_VSHRSTR && (s)->extra > 0)
36
37
38/*
39** equality for short strings, which are always internalized
40*/
41#define eqshrstr(a,b) check_exp((a)->tt == LUA_VSHRSTR, (a) == (b))
42
43
44LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed);
45LUAI_FUNC unsigned int luaS_hashlongstr (TString *ts);
46LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b);
47LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
48LUAI_FUNC void luaS_clearcache (global_State *g);
49LUAI_FUNC void luaS_init (lua_State *L);
50LUAI_FUNC void luaS_remove (lua_State *L, TString *ts);
51LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, int nuvalue);
52LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
53LUAI_FUNC TString *luaS_new (lua_State *L, const char *str);
54LUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l);
55
56
57#endif
diff --git a/vendor/lua-5.4.8/src/lstrlib.c b/vendor/lua-5.4.8/src/lstrlib.c
new file mode 100644
index 0000000..0316716
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lstrlib.c
@@ -0,0 +1,1874 @@
1/*
2** $Id: lstrlib.c $
3** Standard library for string operations and pattern-matching
4** See Copyright Notice in lua.h
5*/
6
7#define lstrlib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <ctype.h>
14#include <float.h>
15#include <limits.h>
16#include <locale.h>
17#include <math.h>
18#include <stddef.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22
23#include "lua.h"
24
25#include "lauxlib.h"
26#include "lualib.h"
27
28
29/*
30** maximum number of captures that a pattern can do during
31** pattern-matching. This limit is arbitrary, but must fit in
32** an unsigned char.
33*/
34#if !defined(LUA_MAXCAPTURES)
35#define LUA_MAXCAPTURES 32
36#endif
37
38
39/* macro to 'unsign' a character */
40#define uchar(c) ((unsigned char)(c))
41
42
43/*
44** Some sizes are better limited to fit in 'int', but must also fit in
45** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.)
46*/
47#define MAX_SIZET ((size_t)(~(size_t)0))
48
49#define MAXSIZE \
50 (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX))
51
52
53
54
55static int str_len (lua_State *L) {
56 size_t l;
57 luaL_checklstring(L, 1, &l);
58 lua_pushinteger(L, (lua_Integer)l);
59 return 1;
60}
61
62
63/*
64** translate a relative initial string position
65** (negative means back from end): clip result to [1, inf).
66** The length of any string in Lua must fit in a lua_Integer,
67** so there are no overflows in the casts.
68** The inverted comparison avoids a possible overflow
69** computing '-pos'.
70*/
71static size_t posrelatI (lua_Integer pos, size_t len) {
72 if (pos > 0)
73 return (size_t)pos;
74 else if (pos == 0)
75 return 1;
76 else if (pos < -(lua_Integer)len) /* inverted comparison */
77 return 1; /* clip to 1 */
78 else return len + (size_t)pos + 1;
79}
80
81
82/*
83** Gets an optional ending string position from argument 'arg',
84** with default value 'def'.
85** Negative means back from end: clip result to [0, len]
86*/
87static size_t getendpos (lua_State *L, int arg, lua_Integer def,
88 size_t len) {
89 lua_Integer pos = luaL_optinteger(L, arg, def);
90 if (pos > (lua_Integer)len)
91 return len;
92 else if (pos >= 0)
93 return (size_t)pos;
94 else if (pos < -(lua_Integer)len)
95 return 0;
96 else return len + (size_t)pos + 1;
97}
98
99
100static int str_sub (lua_State *L) {
101 size_t l;
102 const char *s = luaL_checklstring(L, 1, &l);
103 size_t start = posrelatI(luaL_checkinteger(L, 2), l);
104 size_t end = getendpos(L, 3, -1, l);
105 if (start <= end)
106 lua_pushlstring(L, s + start - 1, (end - start) + 1);
107 else lua_pushliteral(L, "");
108 return 1;
109}
110
111
112static int str_reverse (lua_State *L) {
113 size_t l, i;
114 luaL_Buffer b;
115 const char *s = luaL_checklstring(L, 1, &l);
116 char *p = luaL_buffinitsize(L, &b, l);
117 for (i = 0; i < l; i++)
118 p[i] = s[l - i - 1];
119 luaL_pushresultsize(&b, l);
120 return 1;
121}
122
123
124static int str_lower (lua_State *L) {
125 size_t l;
126 size_t i;
127 luaL_Buffer b;
128 const char *s = luaL_checklstring(L, 1, &l);
129 char *p = luaL_buffinitsize(L, &b, l);
130 for (i=0; i<l; i++)
131 p[i] = tolower(uchar(s[i]));
132 luaL_pushresultsize(&b, l);
133 return 1;
134}
135
136
137static int str_upper (lua_State *L) {
138 size_t l;
139 size_t i;
140 luaL_Buffer b;
141 const char *s = luaL_checklstring(L, 1, &l);
142 char *p = luaL_buffinitsize(L, &b, l);
143 for (i=0; i<l; i++)
144 p[i] = toupper(uchar(s[i]));
145 luaL_pushresultsize(&b, l);
146 return 1;
147}
148
149
150static int str_rep (lua_State *L) {
151 size_t l, lsep;
152 const char *s = luaL_checklstring(L, 1, &l);
153 lua_Integer n = luaL_checkinteger(L, 2);
154 const char *sep = luaL_optlstring(L, 3, "", &lsep);
155 if (n <= 0)
156 lua_pushliteral(L, "");
157 else if (l_unlikely(l + lsep < l || l + lsep > MAXSIZE / n))
158 return luaL_error(L, "resulting string too large");
159 else {
160 size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep;
161 luaL_Buffer b;
162 char *p = luaL_buffinitsize(L, &b, totallen);
163 while (n-- > 1) { /* first n-1 copies (followed by separator) */
164 memcpy(p, s, l * sizeof(char)); p += l;
165 if (lsep > 0) { /* empty 'memcpy' is not that cheap */
166 memcpy(p, sep, lsep * sizeof(char));
167 p += lsep;
168 }
169 }
170 memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
171 luaL_pushresultsize(&b, totallen);
172 }
173 return 1;
174}
175
176
177static int str_byte (lua_State *L) {
178 size_t l;
179 const char *s = luaL_checklstring(L, 1, &l);
180 lua_Integer pi = luaL_optinteger(L, 2, 1);
181 size_t posi = posrelatI(pi, l);
182 size_t pose = getendpos(L, 3, pi, l);
183 int n, i;
184 if (posi > pose) return 0; /* empty interval; return no values */
185 if (l_unlikely(pose - posi >= (size_t)INT_MAX)) /* arithmetic overflow? */
186 return luaL_error(L, "string slice too long");
187 n = (int)(pose - posi) + 1;
188 luaL_checkstack(L, n, "string slice too long");
189 for (i=0; i<n; i++)
190 lua_pushinteger(L, uchar(s[posi+i-1]));
191 return n;
192}
193
194
195static int str_char (lua_State *L) {
196 int n = lua_gettop(L); /* number of arguments */
197 int i;
198 luaL_Buffer b;
199 char *p = luaL_buffinitsize(L, &b, n);
200 for (i=1; i<=n; i++) {
201 lua_Unsigned c = (lua_Unsigned)luaL_checkinteger(L, i);
202 luaL_argcheck(L, c <= (lua_Unsigned)UCHAR_MAX, i, "value out of range");
203 p[i - 1] = uchar(c);
204 }
205 luaL_pushresultsize(&b, n);
206 return 1;
207}
208
209
210/*
211** Buffer to store the result of 'string.dump'. It must be initialized
212** after the call to 'lua_dump', to ensure that the function is on the
213** top of the stack when 'lua_dump' is called. ('luaL_buffinit' might
214** push stuff.)
215*/
216struct str_Writer {
217 int init; /* true iff buffer has been initialized */
218 luaL_Buffer B;
219};
220
221
222static int writer (lua_State *L, const void *b, size_t size, void *ud) {
223 struct str_Writer *state = (struct str_Writer *)ud;
224 if (!state->init) {
225 state->init = 1;
226 luaL_buffinit(L, &state->B);
227 }
228 luaL_addlstring(&state->B, (const char *)b, size);
229 return 0;
230}
231
232
233static int str_dump (lua_State *L) {
234 struct str_Writer state;
235 int strip = lua_toboolean(L, 2);
236 luaL_checktype(L, 1, LUA_TFUNCTION);
237 lua_settop(L, 1); /* ensure function is on the top of the stack */
238 state.init = 0;
239 if (l_unlikely(lua_dump(L, writer, &state, strip) != 0))
240 return luaL_error(L, "unable to dump given function");
241 luaL_pushresult(&state.B);
242 return 1;
243}
244
245
246
247/*
248** {======================================================
249** METAMETHODS
250** =======================================================
251*/
252
253#if defined(LUA_NOCVTS2N) /* { */
254
255/* no coercion from strings to numbers */
256
257static const luaL_Reg stringmetamethods[] = {
258 {"__index", NULL}, /* placeholder */
259 {NULL, NULL}
260};
261
262#else /* }{ */
263
264static int tonum (lua_State *L, int arg) {
265 if (lua_type(L, arg) == LUA_TNUMBER) { /* already a number? */
266 lua_pushvalue(L, arg);
267 return 1;
268 }
269 else { /* check whether it is a numerical string */
270 size_t len;
271 const char *s = lua_tolstring(L, arg, &len);
272 return (s != NULL && lua_stringtonumber(L, s) == len + 1);
273 }
274}
275
276
277static void trymt (lua_State *L, const char *mtname) {
278 lua_settop(L, 2); /* back to the original arguments */
279 if (l_unlikely(lua_type(L, 2) == LUA_TSTRING ||
280 !luaL_getmetafield(L, 2, mtname)))
281 luaL_error(L, "attempt to %s a '%s' with a '%s'", mtname + 2,
282 luaL_typename(L, -2), luaL_typename(L, -1));
283 lua_insert(L, -3); /* put metamethod before arguments */
284 lua_call(L, 2, 1); /* call metamethod */
285}
286
287
288static int arith (lua_State *L, int op, const char *mtname) {
289 if (tonum(L, 1) && tonum(L, 2))
290 lua_arith(L, op); /* result will be on the top */
291 else
292 trymt(L, mtname);
293 return 1;
294}
295
296
297static int arith_add (lua_State *L) {
298 return arith(L, LUA_OPADD, "__add");
299}
300
301static int arith_sub (lua_State *L) {
302 return arith(L, LUA_OPSUB, "__sub");
303}
304
305static int arith_mul (lua_State *L) {
306 return arith(L, LUA_OPMUL, "__mul");
307}
308
309static int arith_mod (lua_State *L) {
310 return arith(L, LUA_OPMOD, "__mod");
311}
312
313static int arith_pow (lua_State *L) {
314 return arith(L, LUA_OPPOW, "__pow");
315}
316
317static int arith_div (lua_State *L) {
318 return arith(L, LUA_OPDIV, "__div");
319}
320
321static int arith_idiv (lua_State *L) {
322 return arith(L, LUA_OPIDIV, "__idiv");
323}
324
325static int arith_unm (lua_State *L) {
326 return arith(L, LUA_OPUNM, "__unm");
327}
328
329
330static const luaL_Reg stringmetamethods[] = {
331 {"__add", arith_add},
332 {"__sub", arith_sub},
333 {"__mul", arith_mul},
334 {"__mod", arith_mod},
335 {"__pow", arith_pow},
336 {"__div", arith_div},
337 {"__idiv", arith_idiv},
338 {"__unm", arith_unm},
339 {"__index", NULL}, /* placeholder */
340 {NULL, NULL}
341};
342
343#endif /* } */
344
345/* }====================================================== */
346
347/*
348** {======================================================
349** PATTERN MATCHING
350** =======================================================
351*/
352
353
354#define CAP_UNFINISHED (-1)
355#define CAP_POSITION (-2)
356
357
358typedef struct MatchState {
359 const char *src_init; /* init of source string */
360 const char *src_end; /* end ('\0') of source string */
361 const char *p_end; /* end ('\0') of pattern */
362 lua_State *L;
363 int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
364 unsigned char level; /* total number of captures (finished or unfinished) */
365 struct {
366 const char *init;
367 ptrdiff_t len;
368 } capture[LUA_MAXCAPTURES];
369} MatchState;
370
371
372/* recursive function */
373static const char *match (MatchState *ms, const char *s, const char *p);
374
375
376/* maximum recursion depth for 'match' */
377#if !defined(MAXCCALLS)
378#define MAXCCALLS 200
379#endif
380
381
382#define L_ESC '%'
383#define SPECIALS "^$*+?.([%-"
384
385
386static int check_capture (MatchState *ms, int l) {
387 l -= '1';
388 if (l_unlikely(l < 0 || l >= ms->level ||
389 ms->capture[l].len == CAP_UNFINISHED))
390 return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
391 return l;
392}
393
394
395static int capture_to_close (MatchState *ms) {
396 int level = ms->level;
397 for (level--; level>=0; level--)
398 if (ms->capture[level].len == CAP_UNFINISHED) return level;
399 return luaL_error(ms->L, "invalid pattern capture");
400}
401
402
403static const char *classend (MatchState *ms, const char *p) {
404 switch (*p++) {
405 case L_ESC: {
406 if (l_unlikely(p == ms->p_end))
407 luaL_error(ms->L, "malformed pattern (ends with '%%')");
408 return p+1;
409 }
410 case '[': {
411 if (*p == '^') p++;
412 do { /* look for a ']' */
413 if (l_unlikely(p == ms->p_end))
414 luaL_error(ms->L, "malformed pattern (missing ']')");
415 if (*(p++) == L_ESC && p < ms->p_end)
416 p++; /* skip escapes (e.g. '%]') */
417 } while (*p != ']');
418 return p+1;
419 }
420 default: {
421 return p;
422 }
423 }
424}
425
426
427static int match_class (int c, int cl) {
428 int res;
429 switch (tolower(cl)) {
430 case 'a' : res = isalpha(c); break;
431 case 'c' : res = iscntrl(c); break;
432 case 'd' : res = isdigit(c); break;
433 case 'g' : res = isgraph(c); break;
434 case 'l' : res = islower(c); break;
435 case 'p' : res = ispunct(c); break;
436 case 's' : res = isspace(c); break;
437 case 'u' : res = isupper(c); break;
438 case 'w' : res = isalnum(c); break;
439 case 'x' : res = isxdigit(c); break;
440 case 'z' : res = (c == 0); break; /* deprecated option */
441 default: return (cl == c);
442 }
443 return (islower(cl) ? res : !res);
444}
445
446
447static int matchbracketclass (int c, const char *p, const char *ec) {
448 int sig = 1;
449 if (*(p+1) == '^') {
450 sig = 0;
451 p++; /* skip the '^' */
452 }
453 while (++p < ec) {
454 if (*p == L_ESC) {
455 p++;
456 if (match_class(c, uchar(*p)))
457 return sig;
458 }
459 else if ((*(p+1) == '-') && (p+2 < ec)) {
460 p+=2;
461 if (uchar(*(p-2)) <= c && c <= uchar(*p))
462 return sig;
463 }
464 else if (uchar(*p) == c) return sig;
465 }
466 return !sig;
467}
468
469
470static int singlematch (MatchState *ms, const char *s, const char *p,
471 const char *ep) {
472 if (s >= ms->src_end)
473 return 0;
474 else {
475 int c = uchar(*s);
476 switch (*p) {
477 case '.': return 1; /* matches any char */
478 case L_ESC: return match_class(c, uchar(*(p+1)));
479 case '[': return matchbracketclass(c, p, ep-1);
480 default: return (uchar(*p) == c);
481 }
482 }
483}
484
485
486static const char *matchbalance (MatchState *ms, const char *s,
487 const char *p) {
488 if (l_unlikely(p >= ms->p_end - 1))
489 luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
490 if (*s != *p) return NULL;
491 else {
492 int b = *p;
493 int e = *(p+1);
494 int cont = 1;
495 while (++s < ms->src_end) {
496 if (*s == e) {
497 if (--cont == 0) return s+1;
498 }
499 else if (*s == b) cont++;
500 }
501 }
502 return NULL; /* string ends out of balance */
503}
504
505
506static const char *max_expand (MatchState *ms, const char *s,
507 const char *p, const char *ep) {
508 ptrdiff_t i = 0; /* counts maximum expand for item */
509 while (singlematch(ms, s + i, p, ep))
510 i++;
511 /* keeps trying to match with the maximum repetitions */
512 while (i>=0) {
513 const char *res = match(ms, (s+i), ep+1);
514 if (res) return res;
515 i--; /* else didn't match; reduce 1 repetition to try again */
516 }
517 return NULL;
518}
519
520
521static const char *min_expand (MatchState *ms, const char *s,
522 const char *p, const char *ep) {
523 for (;;) {
524 const char *res = match(ms, s, ep+1);
525 if (res != NULL)
526 return res;
527 else if (singlematch(ms, s, p, ep))
528 s++; /* try with one more repetition */
529 else return NULL;
530 }
531}
532
533
534static const char *start_capture (MatchState *ms, const char *s,
535 const char *p, int what) {
536 const char *res;
537 int level = ms->level;
538 if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
539 ms->capture[level].init = s;
540 ms->capture[level].len = what;
541 ms->level = level+1;
542 if ((res=match(ms, s, p)) == NULL) /* match failed? */
543 ms->level--; /* undo capture */
544 return res;
545}
546
547
548static const char *end_capture (MatchState *ms, const char *s,
549 const char *p) {
550 int l = capture_to_close(ms);
551 const char *res;
552 ms->capture[l].len = s - ms->capture[l].init; /* close capture */
553 if ((res = match(ms, s, p)) == NULL) /* match failed? */
554 ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
555 return res;
556}
557
558
559static const char *match_capture (MatchState *ms, const char *s, int l) {
560 size_t len;
561 l = check_capture(ms, l);
562 len = ms->capture[l].len;
563 if ((size_t)(ms->src_end-s) >= len &&
564 memcmp(ms->capture[l].init, s, len) == 0)
565 return s+len;
566 else return NULL;
567}
568
569
570static const char *match (MatchState *ms, const char *s, const char *p) {
571 if (l_unlikely(ms->matchdepth-- == 0))
572 luaL_error(ms->L, "pattern too complex");
573 init: /* using goto to optimize tail recursion */
574 if (p != ms->p_end) { /* end of pattern? */
575 switch (*p) {
576 case '(': { /* start capture */
577 if (*(p + 1) == ')') /* position capture? */
578 s = start_capture(ms, s, p + 2, CAP_POSITION);
579 else
580 s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
581 break;
582 }
583 case ')': { /* end capture */
584 s = end_capture(ms, s, p + 1);
585 break;
586 }
587 case '$': {
588 if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */
589 goto dflt; /* no; go to default */
590 s = (s == ms->src_end) ? s : NULL; /* check end of string */
591 break;
592 }
593 case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
594 switch (*(p + 1)) {
595 case 'b': { /* balanced string? */
596 s = matchbalance(ms, s, p + 2);
597 if (s != NULL) {
598 p += 4; goto init; /* return match(ms, s, p + 4); */
599 } /* else fail (s == NULL) */
600 break;
601 }
602 case 'f': { /* frontier? */
603 const char *ep; char previous;
604 p += 2;
605 if (l_unlikely(*p != '['))
606 luaL_error(ms->L, "missing '[' after '%%f' in pattern");
607 ep = classend(ms, p); /* points to what is next */
608 previous = (s == ms->src_init) ? '\0' : *(s - 1);
609 if (!matchbracketclass(uchar(previous), p, ep - 1) &&
610 matchbracketclass(uchar(*s), p, ep - 1)) {
611 p = ep; goto init; /* return match(ms, s, ep); */
612 }
613 s = NULL; /* match failed */
614 break;
615 }
616 case '0': case '1': case '2': case '3':
617 case '4': case '5': case '6': case '7':
618 case '8': case '9': { /* capture results (%0-%9)? */
619 s = match_capture(ms, s, uchar(*(p + 1)));
620 if (s != NULL) {
621 p += 2; goto init; /* return match(ms, s, p + 2) */
622 }
623 break;
624 }
625 default: goto dflt;
626 }
627 break;
628 }
629 default: dflt: { /* pattern class plus optional suffix */
630 const char *ep = classend(ms, p); /* points to optional suffix */
631 /* does not match at least once? */
632 if (!singlematch(ms, s, p, ep)) {
633 if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
634 p = ep + 1; goto init; /* return match(ms, s, ep + 1); */
635 }
636 else /* '+' or no suffix */
637 s = NULL; /* fail */
638 }
639 else { /* matched once */
640 switch (*ep) { /* handle optional suffix */
641 case '?': { /* optional */
642 const char *res;
643 if ((res = match(ms, s + 1, ep + 1)) != NULL)
644 s = res;
645 else {
646 p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */
647 }
648 break;
649 }
650 case '+': /* 1 or more repetitions */
651 s++; /* 1 match already done */
652 /* FALLTHROUGH */
653 case '*': /* 0 or more repetitions */
654 s = max_expand(ms, s, p, ep);
655 break;
656 case '-': /* 0 or more repetitions (minimum) */
657 s = min_expand(ms, s, p, ep);
658 break;
659 default: /* no suffix */
660 s++; p = ep; goto init; /* return match(ms, s + 1, ep); */
661 }
662 }
663 break;
664 }
665 }
666 }
667 ms->matchdepth++;
668 return s;
669}
670
671
672
673static const char *lmemfind (const char *s1, size_t l1,
674 const char *s2, size_t l2) {
675 if (l2 == 0) return s1; /* empty strings are everywhere */
676 else if (l2 > l1) return NULL; /* avoids a negative 'l1' */
677 else {
678 const char *init; /* to search for a '*s2' inside 's1' */
679 l2--; /* 1st char will be checked by 'memchr' */
680 l1 = l1-l2; /* 's2' cannot be found after that */
681 while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
682 init++; /* 1st char is already checked */
683 if (memcmp(init, s2+1, l2) == 0)
684 return init-1;
685 else { /* correct 'l1' and 's1' to try again */
686 l1 -= init-s1;
687 s1 = init;
688 }
689 }
690 return NULL; /* not found */
691 }
692}
693
694
695/*
696** get information about the i-th capture. If there are no captures
697** and 'i==0', return information about the whole match, which
698** is the range 's'..'e'. If the capture is a string, return
699** its length and put its address in '*cap'. If it is an integer
700** (a position), push it on the stack and return CAP_POSITION.
701*/
702static size_t get_onecapture (MatchState *ms, int i, const char *s,
703 const char *e, const char **cap) {
704 if (i >= ms->level) {
705 if (l_unlikely(i != 0))
706 luaL_error(ms->L, "invalid capture index %%%d", i + 1);
707 *cap = s;
708 return e - s;
709 }
710 else {
711 ptrdiff_t capl = ms->capture[i].len;
712 *cap = ms->capture[i].init;
713 if (l_unlikely(capl == CAP_UNFINISHED))
714 luaL_error(ms->L, "unfinished capture");
715 else if (capl == CAP_POSITION)
716 lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1);
717 return capl;
718 }
719}
720
721
722/*
723** Push the i-th capture on the stack.
724*/
725static void push_onecapture (MatchState *ms, int i, const char *s,
726 const char *e) {
727 const char *cap;
728 ptrdiff_t l = get_onecapture(ms, i, s, e, &cap);
729 if (l != CAP_POSITION)
730 lua_pushlstring(ms->L, cap, l);
731 /* else position was already pushed */
732}
733
734
735static int push_captures (MatchState *ms, const char *s, const char *e) {
736 int i;
737 int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
738 luaL_checkstack(ms->L, nlevels, "too many captures");
739 for (i = 0; i < nlevels; i++)
740 push_onecapture(ms, i, s, e);
741 return nlevels; /* number of strings pushed */
742}
743
744
745/* check whether pattern has no special characters */
746static int nospecials (const char *p, size_t l) {
747 size_t upto = 0;
748 do {
749 if (strpbrk(p + upto, SPECIALS))
750 return 0; /* pattern has a special character */
751 upto += strlen(p + upto) + 1; /* may have more after \0 */
752 } while (upto <= l);
753 return 1; /* no special chars found */
754}
755
756
757static void prepstate (MatchState *ms, lua_State *L,
758 const char *s, size_t ls, const char *p, size_t lp) {
759 ms->L = L;
760 ms->matchdepth = MAXCCALLS;
761 ms->src_init = s;
762 ms->src_end = s + ls;
763 ms->p_end = p + lp;
764}
765
766
767static void reprepstate (MatchState *ms) {
768 ms->level = 0;
769 lua_assert(ms->matchdepth == MAXCCALLS);
770}
771
772
773static int str_find_aux (lua_State *L, int find) {
774 size_t ls, lp;
775 const char *s = luaL_checklstring(L, 1, &ls);
776 const char *p = luaL_checklstring(L, 2, &lp);
777 size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
778 if (init > ls) { /* start after string's end? */
779 luaL_pushfail(L); /* cannot find anything */
780 return 1;
781 }
782 /* explicit request or no special characters? */
783 if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
784 /* do a plain search */
785 const char *s2 = lmemfind(s + init, ls - init, p, lp);
786 if (s2) {
787 lua_pushinteger(L, (s2 - s) + 1);
788 lua_pushinteger(L, (s2 - s) + lp);
789 return 2;
790 }
791 }
792 else {
793 MatchState ms;
794 const char *s1 = s + init;
795 int anchor = (*p == '^');
796 if (anchor) {
797 p++; lp--; /* skip anchor character */
798 }
799 prepstate(&ms, L, s, ls, p, lp);
800 do {
801 const char *res;
802 reprepstate(&ms);
803 if ((res=match(&ms, s1, p)) != NULL) {
804 if (find) {
805 lua_pushinteger(L, (s1 - s) + 1); /* start */
806 lua_pushinteger(L, res - s); /* end */
807 return push_captures(&ms, NULL, 0) + 2;
808 }
809 else
810 return push_captures(&ms, s1, res);
811 }
812 } while (s1++ < ms.src_end && !anchor);
813 }
814 luaL_pushfail(L); /* not found */
815 return 1;
816}
817
818
819static int str_find (lua_State *L) {
820 return str_find_aux(L, 1);
821}
822
823
824static int str_match (lua_State *L) {
825 return str_find_aux(L, 0);
826}
827
828
829/* state for 'gmatch' */
830typedef struct GMatchState {
831 const char *src; /* current position */
832 const char *p; /* pattern */
833 const char *lastmatch; /* end of last match */
834 MatchState ms; /* match state */
835} GMatchState;
836
837
838static int gmatch_aux (lua_State *L) {
839 GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
840 const char *src;
841 gm->ms.L = L;
842 for (src = gm->src; src <= gm->ms.src_end; src++) {
843 const char *e;
844 reprepstate(&gm->ms);
845 if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {
846 gm->src = gm->lastmatch = e;
847 return push_captures(&gm->ms, src, e);
848 }
849 }
850 return 0; /* not found */
851}
852
853
854static int gmatch (lua_State *L) {
855 size_t ls, lp;
856 const char *s = luaL_checklstring(L, 1, &ls);
857 const char *p = luaL_checklstring(L, 2, &lp);
858 size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
859 GMatchState *gm;
860 lua_settop(L, 2); /* keep strings on closure to avoid being collected */
861 gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);
862 if (init > ls) /* start after string's end? */
863 init = ls + 1; /* avoid overflows in 's + init' */
864 prepstate(&gm->ms, L, s, ls, p, lp);
865 gm->src = s + init; gm->p = p; gm->lastmatch = NULL;
866 lua_pushcclosure(L, gmatch_aux, 3);
867 return 1;
868}
869
870
871static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
872 const char *e) {
873 size_t l;
874 lua_State *L = ms->L;
875 const char *news = lua_tolstring(L, 3, &l);
876 const char *p;
877 while ((p = (char *)memchr(news, L_ESC, l)) != NULL) {
878 luaL_addlstring(b, news, p - news);
879 p++; /* skip ESC */
880 if (*p == L_ESC) /* '%%' */
881 luaL_addchar(b, *p);
882 else if (*p == '0') /* '%0' */
883 luaL_addlstring(b, s, e - s);
884 else if (isdigit(uchar(*p))) { /* '%n' */
885 const char *cap;
886 ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap);
887 if (resl == CAP_POSITION)
888 luaL_addvalue(b); /* add position to accumulated result */
889 else
890 luaL_addlstring(b, cap, resl);
891 }
892 else
893 luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
894 l -= p + 1 - news;
895 news = p + 1;
896 }
897 luaL_addlstring(b, news, l);
898}
899
900
901/*
902** Add the replacement value to the string buffer 'b'.
903** Return true if the original string was changed. (Function calls and
904** table indexing resulting in nil or false do not change the subject.)
905*/
906static int add_value (MatchState *ms, luaL_Buffer *b, const char *s,
907 const char *e, int tr) {
908 lua_State *L = ms->L;
909 switch (tr) {
910 case LUA_TFUNCTION: { /* call the function */
911 int n;
912 lua_pushvalue(L, 3); /* push the function */
913 n = push_captures(ms, s, e); /* all captures as arguments */
914 lua_call(L, n, 1); /* call it */
915 break;
916 }
917 case LUA_TTABLE: { /* index the table */
918 push_onecapture(ms, 0, s, e); /* first capture is the index */
919 lua_gettable(L, 3);
920 break;
921 }
922 default: { /* LUA_TNUMBER or LUA_TSTRING */
923 add_s(ms, b, s, e); /* add value to the buffer */
924 return 1; /* something changed */
925 }
926 }
927 if (!lua_toboolean(L, -1)) { /* nil or false? */
928 lua_pop(L, 1); /* remove value */
929 luaL_addlstring(b, s, e - s); /* keep original text */
930 return 0; /* no changes */
931 }
932 else if (l_unlikely(!lua_isstring(L, -1)))
933 return luaL_error(L, "invalid replacement value (a %s)",
934 luaL_typename(L, -1));
935 else {
936 luaL_addvalue(b); /* add result to accumulator */
937 return 1; /* something changed */
938 }
939}
940
941
942static int str_gsub (lua_State *L) {
943 size_t srcl, lp;
944 const char *src = luaL_checklstring(L, 1, &srcl); /* subject */
945 const char *p = luaL_checklstring(L, 2, &lp); /* pattern */
946 const char *lastmatch = NULL; /* end of last match */
947 int tr = lua_type(L, 3); /* replacement type */
948 lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1); /* max replacements */
949 int anchor = (*p == '^');
950 lua_Integer n = 0; /* replacement count */
951 int changed = 0; /* change flag */
952 MatchState ms;
953 luaL_Buffer b;
954 luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
955 tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
956 "string/function/table");
957 luaL_buffinit(L, &b);
958 if (anchor) {
959 p++; lp--; /* skip anchor character */
960 }
961 prepstate(&ms, L, src, srcl, p, lp);
962 while (n < max_s) {
963 const char *e;
964 reprepstate(&ms); /* (re)prepare state for new match */
965 if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */
966 n++;
967 changed = add_value(&ms, &b, src, e, tr) | changed;
968 src = lastmatch = e;
969 }
970 else if (src < ms.src_end) /* otherwise, skip one character */
971 luaL_addchar(&b, *src++);
972 else break; /* end of subject */
973 if (anchor) break;
974 }
975 if (!changed) /* no changes? */
976 lua_pushvalue(L, 1); /* return original string */
977 else { /* something changed */
978 luaL_addlstring(&b, src, ms.src_end-src);
979 luaL_pushresult(&b); /* create and return new string */
980 }
981 lua_pushinteger(L, n); /* number of substitutions */
982 return 2;
983}
984
985/* }====================================================== */
986
987
988
989/*
990** {======================================================
991** STRING FORMAT
992** =======================================================
993*/
994
995#if !defined(lua_number2strx) /* { */
996
997/*
998** Hexadecimal floating-point formatter
999*/
1000
1001#define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char))
1002
1003
1004/*
1005** Number of bits that goes into the first digit. It can be any value
1006** between 1 and 4; the following definition tries to align the number
1007** to nibble boundaries by making what is left after that first digit a
1008** multiple of 4.
1009*/
1010#define L_NBFD ((l_floatatt(MANT_DIG) - 1)%4 + 1)
1011
1012
1013/*
1014** Add integer part of 'x' to buffer and return new 'x'
1015*/
1016static lua_Number adddigit (char *buff, int n, lua_Number x) {
1017 lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */
1018 int d = (int)dd;
1019 buff[n] = (d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */
1020 return x - dd; /* return what is left */
1021}
1022
1023
1024static int num2straux (char *buff, int sz, lua_Number x) {
1025 /* if 'inf' or 'NaN', format it like '%g' */
1026 if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL)
1027 return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x);
1028 else if (x == 0) { /* can be -0... */
1029 /* create "0" or "-0" followed by exponent */
1030 return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x);
1031 }
1032 else {
1033 int e;
1034 lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */
1035 int n = 0; /* character count */
1036 if (m < 0) { /* is number negative? */
1037 buff[n++] = '-'; /* add sign */
1038 m = -m; /* make it positive */
1039 }
1040 buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */
1041 m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */
1042 e -= L_NBFD; /* this digit goes before the radix point */
1043 if (m > 0) { /* more digits? */
1044 buff[n++] = lua_getlocaledecpoint(); /* add radix point */
1045 do { /* add as many digits as needed */
1046 m = adddigit(buff, n++, m * 16);
1047 } while (m > 0);
1048 }
1049 n += l_sprintf(buff + n, sz - n, "p%+d", e); /* add exponent */
1050 lua_assert(n < sz);
1051 return n;
1052 }
1053}
1054
1055
1056static int lua_number2strx (lua_State *L, char *buff, int sz,
1057 const char *fmt, lua_Number x) {
1058 int n = num2straux(buff, sz, x);
1059 if (fmt[SIZELENMOD] == 'A') {
1060 int i;
1061 for (i = 0; i < n; i++)
1062 buff[i] = toupper(uchar(buff[i]));
1063 }
1064 else if (l_unlikely(fmt[SIZELENMOD] != 'a'))
1065 return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented");
1066 return n;
1067}
1068
1069#endif /* } */
1070
1071
1072/*
1073** Maximum size for items formatted with '%f'. This size is produced
1074** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.',
1075** and '\0') + number of decimal digits to represent maxfloat (which
1076** is maximum exponent + 1). (99+3+1, adding some extra, 110)
1077*/
1078#define MAX_ITEMF (110 + l_floatatt(MAX_10_EXP))
1079
1080
1081/*
1082** All formats except '%f' do not need that large limit. The other
1083** float formats use exponents, so that they fit in the 99 limit for
1084** significant digits; 's' for large strings and 'q' add items directly
1085** to the buffer; all integer formats also fit in the 99 limit. The
1086** worst case are floats: they may need 99 significant digits, plus
1087** '0x', '-', '.', 'e+XXXX', and '\0'. Adding some extra, 120.
1088*/
1089#define MAX_ITEM 120
1090
1091
1092/* valid flags in a format specification */
1093#if !defined(L_FMTFLAGSF)
1094
1095/* valid flags for a, A, e, E, f, F, g, and G conversions */
1096#define L_FMTFLAGSF "-+#0 "
1097
1098/* valid flags for o, x, and X conversions */
1099#define L_FMTFLAGSX "-#0"
1100
1101/* valid flags for d and i conversions */
1102#define L_FMTFLAGSI "-+0 "
1103
1104/* valid flags for u conversions */
1105#define L_FMTFLAGSU "-0"
1106
1107/* valid flags for c, p, and s conversions */
1108#define L_FMTFLAGSC "-"
1109
1110#endif
1111
1112
1113/*
1114** Maximum size of each format specification (such as "%-099.99d"):
1115** Initial '%', flags (up to 5), width (2), period, precision (2),
1116** length modifier (8), conversion specifier, and final '\0', plus some
1117** extra.
1118*/
1119#define MAX_FORMAT 32
1120
1121
1122static void addquoted (luaL_Buffer *b, const char *s, size_t len) {
1123 luaL_addchar(b, '"');
1124 while (len--) {
1125 if (*s == '"' || *s == '\\' || *s == '\n') {
1126 luaL_addchar(b, '\\');
1127 luaL_addchar(b, *s);
1128 }
1129 else if (iscntrl(uchar(*s))) {
1130 char buff[10];
1131 if (!isdigit(uchar(*(s+1))))
1132 l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s));
1133 else
1134 l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s));
1135 luaL_addstring(b, buff);
1136 }
1137 else
1138 luaL_addchar(b, *s);
1139 s++;
1140 }
1141 luaL_addchar(b, '"');
1142}
1143
1144
1145/*
1146** Serialize a floating-point number in such a way that it can be
1147** scanned back by Lua. Use hexadecimal format for "common" numbers
1148** (to preserve precision); inf, -inf, and NaN are handled separately.
1149** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.)
1150*/
1151static int quotefloat (lua_State *L, char *buff, lua_Number n) {
1152 const char *s; /* for the fixed representations */
1153 if (n == (lua_Number)HUGE_VAL) /* inf? */
1154 s = "1e9999";
1155 else if (n == -(lua_Number)HUGE_VAL) /* -inf? */
1156 s = "-1e9999";
1157 else if (n != n) /* NaN? */
1158 s = "(0/0)";
1159 else { /* format number as hexadecimal */
1160 int nb = lua_number2strx(L, buff, MAX_ITEM,
1161 "%" LUA_NUMBER_FRMLEN "a", n);
1162 /* ensures that 'buff' string uses a dot as the radix character */
1163 if (memchr(buff, '.', nb) == NULL) { /* no dot? */
1164 char point = lua_getlocaledecpoint(); /* try locale point */
1165 char *ppoint = (char *)memchr(buff, point, nb);
1166 if (ppoint) *ppoint = '.'; /* change it to a dot */
1167 }
1168 return nb;
1169 }
1170 /* for the fixed representations */
1171 return l_sprintf(buff, MAX_ITEM, "%s", s);
1172}
1173
1174
1175static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
1176 switch (lua_type(L, arg)) {
1177 case LUA_TSTRING: {
1178 size_t len;
1179 const char *s = lua_tolstring(L, arg, &len);
1180 addquoted(b, s, len);
1181 break;
1182 }
1183 case LUA_TNUMBER: {
1184 char *buff = luaL_prepbuffsize(b, MAX_ITEM);
1185 int nb;
1186 if (!lua_isinteger(L, arg)) /* float? */
1187 nb = quotefloat(L, buff, lua_tonumber(L, arg));
1188 else { /* integers */
1189 lua_Integer n = lua_tointeger(L, arg);
1190 const char *format = (n == LUA_MININTEGER) /* corner case? */
1191 ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hex */
1192 : LUA_INTEGER_FMT; /* else use default format */
1193 nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);
1194 }
1195 luaL_addsize(b, nb);
1196 break;
1197 }
1198 case LUA_TNIL: case LUA_TBOOLEAN: {
1199 luaL_tolstring(L, arg, NULL);
1200 luaL_addvalue(b);
1201 break;
1202 }
1203 default: {
1204 luaL_argerror(L, arg, "value has no literal form");
1205 }
1206 }
1207}
1208
1209
1210static const char *get2digits (const char *s) {
1211 if (isdigit(uchar(*s))) {
1212 s++;
1213 if (isdigit(uchar(*s))) s++; /* (2 digits at most) */
1214 }
1215 return s;
1216}
1217
1218
1219/*
1220** Check whether a conversion specification is valid. When called,
1221** first character in 'form' must be '%' and last character must
1222** be a valid conversion specifier. 'flags' are the accepted flags;
1223** 'precision' signals whether to accept a precision.
1224*/
1225static void checkformat (lua_State *L, const char *form, const char *flags,
1226 int precision) {
1227 const char *spec = form + 1; /* skip '%' */
1228 spec += strspn(spec, flags); /* skip flags */
1229 if (*spec != '0') { /* a width cannot start with '0' */
1230 spec = get2digits(spec); /* skip width */
1231 if (*spec == '.' && precision) {
1232 spec++;
1233 spec = get2digits(spec); /* skip precision */
1234 }
1235 }
1236 if (!isalpha(uchar(*spec))) /* did not go to the end? */
1237 luaL_error(L, "invalid conversion specification: '%s'", form);
1238}
1239
1240
1241/*
1242** Get a conversion specification and copy it to 'form'.
1243** Return the address of its last character.
1244*/
1245static const char *getformat (lua_State *L, const char *strfrmt,
1246 char *form) {
1247 /* spans flags, width, and precision ('0' is included as a flag) */
1248 size_t len = strspn(strfrmt, L_FMTFLAGSF "123456789.");
1249 len++; /* adds following character (should be the specifier) */
1250 /* still needs space for '%', '\0', plus a length modifier */
1251 if (len >= MAX_FORMAT - 10)
1252 luaL_error(L, "invalid format (too long)");
1253 *(form++) = '%';
1254 memcpy(form, strfrmt, len * sizeof(char));
1255 *(form + len) = '\0';
1256 return strfrmt + len - 1;
1257}
1258
1259
1260/*
1261** add length modifier into formats
1262*/
1263static void addlenmod (char *form, const char *lenmod) {
1264 size_t l = strlen(form);
1265 size_t lm = strlen(lenmod);
1266 char spec = form[l - 1];
1267 strcpy(form + l - 1, lenmod);
1268 form[l + lm - 1] = spec;
1269 form[l + lm] = '\0';
1270}
1271
1272
1273static int str_format (lua_State *L) {
1274 int top = lua_gettop(L);
1275 int arg = 1;
1276 size_t sfl;
1277 const char *strfrmt = luaL_checklstring(L, arg, &sfl);
1278 const char *strfrmt_end = strfrmt+sfl;
1279 const char *flags;
1280 luaL_Buffer b;
1281 luaL_buffinit(L, &b);
1282 while (strfrmt < strfrmt_end) {
1283 if (*strfrmt != L_ESC)
1284 luaL_addchar(&b, *strfrmt++);
1285 else if (*++strfrmt == L_ESC)
1286 luaL_addchar(&b, *strfrmt++); /* %% */
1287 else { /* format item */
1288 char form[MAX_FORMAT]; /* to store the format ('%...') */
1289 int maxitem = MAX_ITEM; /* maximum length for the result */
1290 char *buff = luaL_prepbuffsize(&b, maxitem); /* to put result */
1291 int nb = 0; /* number of bytes in result */
1292 if (++arg > top)
1293 return luaL_argerror(L, arg, "no value");
1294 strfrmt = getformat(L, strfrmt, form);
1295 switch (*strfrmt++) {
1296 case 'c': {
1297 checkformat(L, form, L_FMTFLAGSC, 0);
1298 nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg));
1299 break;
1300 }
1301 case 'd': case 'i':
1302 flags = L_FMTFLAGSI;
1303 goto intcase;
1304 case 'u':
1305 flags = L_FMTFLAGSU;
1306 goto intcase;
1307 case 'o': case 'x': case 'X':
1308 flags = L_FMTFLAGSX;
1309 intcase: {
1310 lua_Integer n = luaL_checkinteger(L, arg);
1311 checkformat(L, form, flags, 1);
1312 addlenmod(form, LUA_INTEGER_FRMLEN);
1313 nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n);
1314 break;
1315 }
1316 case 'a': case 'A':
1317 checkformat(L, form, L_FMTFLAGSF, 1);
1318 addlenmod(form, LUA_NUMBER_FRMLEN);
1319 nb = lua_number2strx(L, buff, maxitem, form,
1320 luaL_checknumber(L, arg));
1321 break;
1322 case 'f':
1323 maxitem = MAX_ITEMF; /* extra space for '%f' */
1324 buff = luaL_prepbuffsize(&b, maxitem);
1325 /* FALLTHROUGH */
1326 case 'e': case 'E': case 'g': case 'G': {
1327 lua_Number n = luaL_checknumber(L, arg);
1328 checkformat(L, form, L_FMTFLAGSF, 1);
1329 addlenmod(form, LUA_NUMBER_FRMLEN);
1330 nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n);
1331 break;
1332 }
1333 case 'p': {
1334 const void *p = lua_topointer(L, arg);
1335 checkformat(L, form, L_FMTFLAGSC, 0);
1336 if (p == NULL) { /* avoid calling 'printf' with argument NULL */
1337 p = "(null)"; /* result */
1338 form[strlen(form) - 1] = 's'; /* format it as a string */
1339 }
1340 nb = l_sprintf(buff, maxitem, form, p);
1341 break;
1342 }
1343 case 'q': {
1344 if (form[2] != '\0') /* modifiers? */
1345 return luaL_error(L, "specifier '%%q' cannot have modifiers");
1346 addliteral(L, &b, arg);
1347 break;
1348 }
1349 case 's': {
1350 size_t l;
1351 const char *s = luaL_tolstring(L, arg, &l);
1352 if (form[2] == '\0') /* no modifiers? */
1353 luaL_addvalue(&b); /* keep entire string */
1354 else {
1355 luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
1356 checkformat(L, form, L_FMTFLAGSC, 1);
1357 if (strchr(form, '.') == NULL && l >= 100) {
1358 /* no precision and string is too long to be formatted */
1359 luaL_addvalue(&b); /* keep entire string */
1360 }
1361 else { /* format the string into 'buff' */
1362 nb = l_sprintf(buff, maxitem, form, s);
1363 lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
1364 }
1365 }
1366 break;
1367 }
1368 default: { /* also treat cases 'pnLlh' */
1369 return luaL_error(L, "invalid conversion '%s' to 'format'", form);
1370 }
1371 }
1372 lua_assert(nb < maxitem);
1373 luaL_addsize(&b, nb);
1374 }
1375 }
1376 luaL_pushresult(&b);
1377 return 1;
1378}
1379
1380/* }====================================================== */
1381
1382
1383/*
1384** {======================================================
1385** PACK/UNPACK
1386** =======================================================
1387*/
1388
1389
1390/* value used for padding */
1391#if !defined(LUAL_PACKPADBYTE)
1392#define LUAL_PACKPADBYTE 0x00
1393#endif
1394
1395/* maximum size for the binary representation of an integer */
1396#define MAXINTSIZE 16
1397
1398/* number of bits in a character */
1399#define NB CHAR_BIT
1400
1401/* mask for one character (NB 1's) */
1402#define MC ((1 << NB) - 1)
1403
1404/* size of a lua_Integer */
1405#define SZINT ((int)sizeof(lua_Integer))
1406
1407
1408/* dummy union to get native endianness */
1409static const union {
1410 int dummy;
1411 char little; /* true iff machine is little endian */
1412} nativeendian = {1};
1413
1414
1415/*
1416** information to pack/unpack stuff
1417*/
1418typedef struct Header {
1419 lua_State *L;
1420 int islittle;
1421 int maxalign;
1422} Header;
1423
1424
1425/*
1426** options for pack/unpack
1427*/
1428typedef enum KOption {
1429 Kint, /* signed integers */
1430 Kuint, /* unsigned integers */
1431 Kfloat, /* single-precision floating-point numbers */
1432 Knumber, /* Lua "native" floating-point numbers */
1433 Kdouble, /* double-precision floating-point numbers */
1434 Kchar, /* fixed-length strings */
1435 Kstring, /* strings with prefixed length */
1436 Kzstr, /* zero-terminated strings */
1437 Kpadding, /* padding */
1438 Kpaddalign, /* padding for alignment */
1439 Knop /* no-op (configuration or spaces) */
1440} KOption;
1441
1442
1443/*
1444** Read an integer numeral from string 'fmt' or return 'df' if
1445** there is no numeral
1446*/
1447static int digit (int c) { return '0' <= c && c <= '9'; }
1448
1449static int getnum (const char **fmt, int df) {
1450 if (!digit(**fmt)) /* no number? */
1451 return df; /* return default value */
1452 else {
1453 int a = 0;
1454 do {
1455 a = a*10 + (*((*fmt)++) - '0');
1456 } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10);
1457 return a;
1458 }
1459}
1460
1461
1462/*
1463** Read an integer numeral and raises an error if it is larger
1464** than the maximum size for integers.
1465*/
1466static int getnumlimit (Header *h, const char **fmt, int df) {
1467 int sz = getnum(fmt, df);
1468 if (l_unlikely(sz > MAXINTSIZE || sz <= 0))
1469 return luaL_error(h->L, "integral size (%d) out of limits [1,%d]",
1470 sz, MAXINTSIZE);
1471 return sz;
1472}
1473
1474
1475/*
1476** Initialize Header
1477*/
1478static void initheader (lua_State *L, Header *h) {
1479 h->L = L;
1480 h->islittle = nativeendian.little;
1481 h->maxalign = 1;
1482}
1483
1484
1485/*
1486** Read and classify next option. 'size' is filled with option's size.
1487*/
1488static KOption getoption (Header *h, const char **fmt, int *size) {
1489 /* dummy structure to get native alignment requirements */
1490 struct cD { char c; union { LUAI_MAXALIGN; } u; };
1491 int opt = *((*fmt)++);
1492 *size = 0; /* default */
1493 switch (opt) {
1494 case 'b': *size = sizeof(char); return Kint;
1495 case 'B': *size = sizeof(char); return Kuint;
1496 case 'h': *size = sizeof(short); return Kint;
1497 case 'H': *size = sizeof(short); return Kuint;
1498 case 'l': *size = sizeof(long); return Kint;
1499 case 'L': *size = sizeof(long); return Kuint;
1500 case 'j': *size = sizeof(lua_Integer); return Kint;
1501 case 'J': *size = sizeof(lua_Integer); return Kuint;
1502 case 'T': *size = sizeof(size_t); return Kuint;
1503 case 'f': *size = sizeof(float); return Kfloat;
1504 case 'n': *size = sizeof(lua_Number); return Knumber;
1505 case 'd': *size = sizeof(double); return Kdouble;
1506 case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
1507 case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
1508 case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
1509 case 'c':
1510 *size = getnum(fmt, -1);
1511 if (l_unlikely(*size == -1))
1512 luaL_error(h->L, "missing size for format option 'c'");
1513 return Kchar;
1514 case 'z': return Kzstr;
1515 case 'x': *size = 1; return Kpadding;
1516 case 'X': return Kpaddalign;
1517 case ' ': break;
1518 case '<': h->islittle = 1; break;
1519 case '>': h->islittle = 0; break;
1520 case '=': h->islittle = nativeendian.little; break;
1521 case '!': {
1522 const int maxalign = offsetof(struct cD, u);
1523 h->maxalign = getnumlimit(h, fmt, maxalign);
1524 break;
1525 }
1526 default: luaL_error(h->L, "invalid format option '%c'", opt);
1527 }
1528 return Knop;
1529}
1530
1531
1532/*
1533** Read, classify, and fill other details about the next option.
1534** 'psize' is filled with option's size, 'notoalign' with its
1535** alignment requirements.
1536** Local variable 'size' gets the size to be aligned. (Kpadal option
1537** always gets its full alignment, other options are limited by
1538** the maximum alignment ('maxalign'). Kchar option needs no alignment
1539** despite its size.
1540*/
1541static KOption getdetails (Header *h, size_t totalsize,
1542 const char **fmt, int *psize, int *ntoalign) {
1543 KOption opt = getoption(h, fmt, psize);
1544 int align = *psize; /* usually, alignment follows size */
1545 if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
1546 if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
1547 luaL_argerror(h->L, 1, "invalid next option for option 'X'");
1548 }
1549 if (align <= 1 || opt == Kchar) /* need no alignment? */
1550 *ntoalign = 0;
1551 else {
1552 if (align > h->maxalign) /* enforce maximum alignment */
1553 align = h->maxalign;
1554 if (l_unlikely((align & (align - 1)) != 0)) /* not a power of 2? */
1555 luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
1556 *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
1557 }
1558 return opt;
1559}
1560
1561
1562/*
1563** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
1564** The final 'if' handles the case when 'size' is larger than
1565** the size of a Lua integer, correcting the extra sign-extension
1566** bytes if necessary (by default they would be zeros).
1567*/
1568static void packint (luaL_Buffer *b, lua_Unsigned n,
1569 int islittle, int size, int neg) {
1570 char *buff = luaL_prepbuffsize(b, size);
1571 int i;
1572 buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */
1573 for (i = 1; i < size; i++) {
1574 n >>= NB;
1575 buff[islittle ? i : size - 1 - i] = (char)(n & MC);
1576 }
1577 if (neg && size > SZINT) { /* negative number need sign extension? */
1578 for (i = SZINT; i < size; i++) /* correct extra bytes */
1579 buff[islittle ? i : size - 1 - i] = (char)MC;
1580 }
1581 luaL_addsize(b, size); /* add result to buffer */
1582}
1583
1584
1585/*
1586** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
1587** given 'islittle' is different from native endianness.
1588*/
1589static void copywithendian (char *dest, const char *src,
1590 int size, int islittle) {
1591 if (islittle == nativeendian.little)
1592 memcpy(dest, src, size);
1593 else {
1594 dest += size - 1;
1595 while (size-- != 0)
1596 *(dest--) = *(src++);
1597 }
1598}
1599
1600
1601static int str_pack (lua_State *L) {
1602 luaL_Buffer b;
1603 Header h;
1604 const char *fmt = luaL_checkstring(L, 1); /* format string */
1605 int arg = 1; /* current argument to pack */
1606 size_t totalsize = 0; /* accumulate total size of result */
1607 initheader(L, &h);
1608 lua_pushnil(L); /* mark to separate arguments from string buffer */
1609 luaL_buffinit(L, &b);
1610 while (*fmt != '\0') {
1611 int size, ntoalign;
1612 KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1613 totalsize += ntoalign + size;
1614 while (ntoalign-- > 0)
1615 luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */
1616 arg++;
1617 switch (opt) {
1618 case Kint: { /* signed integers */
1619 lua_Integer n = luaL_checkinteger(L, arg);
1620 if (size < SZINT) { /* need overflow check? */
1621 lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
1622 luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
1623 }
1624 packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0));
1625 break;
1626 }
1627 case Kuint: { /* unsigned integers */
1628 lua_Integer n = luaL_checkinteger(L, arg);
1629 if (size < SZINT) /* need overflow check? */
1630 luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
1631 arg, "unsigned overflow");
1632 packint(&b, (lua_Unsigned)n, h.islittle, size, 0);
1633 break;
1634 }
1635 case Kfloat: { /* C float */
1636 float f = (float)luaL_checknumber(L, arg); /* get argument */
1637 char *buff = luaL_prepbuffsize(&b, sizeof(f));
1638 /* move 'f' to final result, correcting endianness if needed */
1639 copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1640 luaL_addsize(&b, size);
1641 break;
1642 }
1643 case Knumber: { /* Lua float */
1644 lua_Number f = luaL_checknumber(L, arg); /* get argument */
1645 char *buff = luaL_prepbuffsize(&b, sizeof(f));
1646 /* move 'f' to final result, correcting endianness if needed */
1647 copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1648 luaL_addsize(&b, size);
1649 break;
1650 }
1651 case Kdouble: { /* C double */
1652 double f = (double)luaL_checknumber(L, arg); /* get argument */
1653 char *buff = luaL_prepbuffsize(&b, sizeof(f));
1654 /* move 'f' to final result, correcting endianness if needed */
1655 copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1656 luaL_addsize(&b, size);
1657 break;
1658 }
1659 case Kchar: { /* fixed-size string */
1660 size_t len;
1661 const char *s = luaL_checklstring(L, arg, &len);
1662 luaL_argcheck(L, len <= (size_t)size, arg,
1663 "string longer than given size");
1664 luaL_addlstring(&b, s, len); /* add string */
1665 while (len++ < (size_t)size) /* pad extra space */
1666 luaL_addchar(&b, LUAL_PACKPADBYTE);
1667 break;
1668 }
1669 case Kstring: { /* strings with length count */
1670 size_t len;
1671 const char *s = luaL_checklstring(L, arg, &len);
1672 luaL_argcheck(L, size >= (int)sizeof(size_t) ||
1673 len < ((size_t)1 << (size * NB)),
1674 arg, "string length does not fit in given size");
1675 packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */
1676 luaL_addlstring(&b, s, len);
1677 totalsize += len;
1678 break;
1679 }
1680 case Kzstr: { /* zero-terminated string */
1681 size_t len;
1682 const char *s = luaL_checklstring(L, arg, &len);
1683 luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
1684 luaL_addlstring(&b, s, len);
1685 luaL_addchar(&b, '\0'); /* add zero at the end */
1686 totalsize += len + 1;
1687 break;
1688 }
1689 case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */
1690 case Kpaddalign: case Knop:
1691 arg--; /* undo increment */
1692 break;
1693 }
1694 }
1695 luaL_pushresult(&b);
1696 return 1;
1697}
1698
1699
1700static int str_packsize (lua_State *L) {
1701 Header h;
1702 const char *fmt = luaL_checkstring(L, 1); /* format string */
1703 size_t totalsize = 0; /* accumulate total size of result */
1704 initheader(L, &h);
1705 while (*fmt != '\0') {
1706 int size, ntoalign;
1707 KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1708 luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
1709 "variable-length format");
1710 size += ntoalign; /* total space used by option */
1711 luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,
1712 "format result too large");
1713 totalsize += size;
1714 }
1715 lua_pushinteger(L, (lua_Integer)totalsize);
1716 return 1;
1717}
1718
1719
1720/*
1721** Unpack an integer with 'size' bytes and 'islittle' endianness.
1722** If size is smaller than the size of a Lua integer and integer
1723** is signed, must do sign extension (propagating the sign to the
1724** higher bits); if size is larger than the size of a Lua integer,
1725** it must check the unread bytes to see whether they do not cause an
1726** overflow.
1727*/
1728static lua_Integer unpackint (lua_State *L, const char *str,
1729 int islittle, int size, int issigned) {
1730 lua_Unsigned res = 0;
1731 int i;
1732 int limit = (size <= SZINT) ? size : SZINT;
1733 for (i = limit - 1; i >= 0; i--) {
1734 res <<= NB;
1735 res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
1736 }
1737 if (size < SZINT) { /* real size smaller than lua_Integer? */
1738 if (issigned) { /* needs sign extension? */
1739 lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
1740 res = ((res ^ mask) - mask); /* do sign extension */
1741 }
1742 }
1743 else if (size > SZINT) { /* must check unread bytes */
1744 int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
1745 for (i = limit; i < size; i++) {
1746 if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask))
1747 luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
1748 }
1749 }
1750 return (lua_Integer)res;
1751}
1752
1753
1754static int str_unpack (lua_State *L) {
1755 Header h;
1756 const char *fmt = luaL_checkstring(L, 1);
1757 size_t ld;
1758 const char *data = luaL_checklstring(L, 2, &ld);
1759 size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
1760 int n = 0; /* number of results */
1761 luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
1762 initheader(L, &h);
1763 while (*fmt != '\0') {
1764 int size, ntoalign;
1765 KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
1766 luaL_argcheck(L, (size_t)ntoalign + size <= ld - pos, 2,
1767 "data string too short");
1768 pos += ntoalign; /* skip alignment */
1769 /* stack space for item + next position */
1770 luaL_checkstack(L, 2, "too many results");
1771 n++;
1772 switch (opt) {
1773 case Kint:
1774 case Kuint: {
1775 lua_Integer res = unpackint(L, data + pos, h.islittle, size,
1776 (opt == Kint));
1777 lua_pushinteger(L, res);
1778 break;
1779 }
1780 case Kfloat: {
1781 float f;
1782 copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1783 lua_pushnumber(L, (lua_Number)f);
1784 break;
1785 }
1786 case Knumber: {
1787 lua_Number f;
1788 copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1789 lua_pushnumber(L, f);
1790 break;
1791 }
1792 case Kdouble: {
1793 double f;
1794 copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1795 lua_pushnumber(L, (lua_Number)f);
1796 break;
1797 }
1798 case Kchar: {
1799 lua_pushlstring(L, data + pos, size);
1800 break;
1801 }
1802 case Kstring: {
1803 size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0);
1804 luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
1805 lua_pushlstring(L, data + pos + size, len);
1806 pos += len; /* skip string */
1807 break;
1808 }
1809 case Kzstr: {
1810 size_t len = strlen(data + pos);
1811 luaL_argcheck(L, pos + len < ld, 2,
1812 "unfinished string for format 'z'");
1813 lua_pushlstring(L, data + pos, len);
1814 pos += len + 1; /* skip string plus final '\0' */
1815 break;
1816 }
1817 case Kpaddalign: case Kpadding: case Knop:
1818 n--; /* undo increment */
1819 break;
1820 }
1821 pos += size;
1822 }
1823 lua_pushinteger(L, pos + 1); /* next position */
1824 return n + 1;
1825}
1826
1827/* }====================================================== */
1828
1829
1830static const luaL_Reg strlib[] = {
1831 {"byte", str_byte},
1832 {"char", str_char},
1833 {"dump", str_dump},
1834 {"find", str_find},
1835 {"format", str_format},
1836 {"gmatch", gmatch},
1837 {"gsub", str_gsub},
1838 {"len", str_len},
1839 {"lower", str_lower},
1840 {"match", str_match},
1841 {"rep", str_rep},
1842 {"reverse", str_reverse},
1843 {"sub", str_sub},
1844 {"upper", str_upper},
1845 {"pack", str_pack},
1846 {"packsize", str_packsize},
1847 {"unpack", str_unpack},
1848 {NULL, NULL}
1849};
1850
1851
1852static void createmetatable (lua_State *L) {
1853 /* table to be metatable for strings */
1854 luaL_newlibtable(L, stringmetamethods);
1855 luaL_setfuncs(L, stringmetamethods, 0);
1856 lua_pushliteral(L, ""); /* dummy string */
1857 lua_pushvalue(L, -2); /* copy table */
1858 lua_setmetatable(L, -2); /* set table as metatable for strings */
1859 lua_pop(L, 1); /* pop dummy string */
1860 lua_pushvalue(L, -2); /* get string library */
1861 lua_setfield(L, -2, "__index"); /* metatable.__index = string */
1862 lua_pop(L, 1); /* pop metatable */
1863}
1864
1865
1866/*
1867** Open string library
1868*/
1869LUAMOD_API int luaopen_string (lua_State *L) {
1870 luaL_newlib(L, strlib);
1871 createmetatable(L);
1872 return 1;
1873}
1874
diff --git a/vendor/lua-5.4.8/src/ltable.c b/vendor/lua-5.4.8/src/ltable.c
new file mode 100644
index 0000000..3353c04
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ltable.c
@@ -0,0 +1,995 @@
1/*
2** $Id: ltable.c $
3** Lua tables (hash)
4** See Copyright Notice in lua.h
5*/
6
7#define ltable_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13/*
14** Implementation of tables (aka arrays, objects, or hash tables).
15** Tables keep its elements in two parts: an array part and a hash part.
16** Non-negative integer keys are all candidates to be kept in the array
17** part. The actual size of the array is the largest 'n' such that
18** more than half the slots between 1 and n are in use.
19** Hash uses a mix of chained scatter table with Brent's variation.
20** A main invariant of these tables is that, if an element is not
21** in its main position (i.e. the 'original' position that its hash gives
22** to it), then the colliding element is in its own main position.
23** Hence even when the load factor reaches 100%, performance remains good.
24*/
25
26#include <math.h>
27#include <limits.h>
28
29#include "lua.h"
30
31#include "ldebug.h"
32#include "ldo.h"
33#include "lgc.h"
34#include "lmem.h"
35#include "lobject.h"
36#include "lstate.h"
37#include "lstring.h"
38#include "ltable.h"
39#include "lvm.h"
40
41
42/*
43** MAXABITS is the largest integer such that MAXASIZE fits in an
44** unsigned int.
45*/
46#define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1)
47
48
49/*
50** MAXASIZE is the maximum size of the array part. It is the minimum
51** between 2^MAXABITS and the maximum size that, measured in bytes,
52** fits in a 'size_t'.
53*/
54#define MAXASIZE luaM_limitN(1u << MAXABITS, TValue)
55
56/*
57** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a
58** signed int.
59*/
60#define MAXHBITS (MAXABITS - 1)
61
62
63/*
64** MAXHSIZE is the maximum size of the hash part. It is the minimum
65** between 2^MAXHBITS and the maximum size such that, measured in bytes,
66** it fits in a 'size_t'.
67*/
68#define MAXHSIZE luaM_limitN(1u << MAXHBITS, Node)
69
70
71/*
72** When the original hash value is good, hashing by a power of 2
73** avoids the cost of '%'.
74*/
75#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
76
77/*
78** for other types, it is better to avoid modulo by power of 2, as
79** they can have many 2 factors.
80*/
81#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
82
83
84#define hashstr(t,str) hashpow2(t, (str)->hash)
85#define hashboolean(t,p) hashpow2(t, p)
86
87
88#define hashpointer(t,p) hashmod(t, point2uint(p))
89
90
91#define dummynode (&dummynode_)
92
93static const Node dummynode_ = {
94 {{NULL}, LUA_VEMPTY, /* value's value and type */
95 LUA_VNIL, 0, {NULL}} /* key type, next, and key value */
96};
97
98
99static const TValue absentkey = {ABSTKEYCONSTANT};
100
101
102/*
103** Hash for integers. To allow a good hash, use the remainder operator
104** ('%'). If integer fits as a non-negative int, compute an int
105** remainder, which is faster. Otherwise, use an unsigned-integer
106** remainder, which uses all bits and ensures a non-negative result.
107*/
108static Node *hashint (const Table *t, lua_Integer i) {
109 lua_Unsigned ui = l_castS2U(i);
110 if (ui <= cast_uint(INT_MAX))
111 return hashmod(t, cast_int(ui));
112 else
113 return hashmod(t, ui);
114}
115
116
117/*
118** Hash for floating-point numbers.
119** The main computation should be just
120** n = frexp(n, &i); return (n * INT_MAX) + i
121** but there are some numerical subtleties.
122** In a two-complement representation, INT_MAX does not has an exact
123** representation as a float, but INT_MIN does; because the absolute
124** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the
125** absolute value of the product 'frexp * -INT_MIN' is smaller or equal
126** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when
127** adding 'i'; the use of '~u' (instead of '-u') avoids problems with
128** INT_MIN.
129*/
130#if !defined(l_hashfloat)
131static int l_hashfloat (lua_Number n) {
132 int i;
133 lua_Integer ni;
134 n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
135 if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */
136 lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
137 return 0;
138 }
139 else { /* normal case */
140 unsigned int u = cast_uint(i) + cast_uint(ni);
141 return cast_int(u <= cast_uint(INT_MAX) ? u : ~u);
142 }
143}
144#endif
145
146
147/*
148** returns the 'main' position of an element in a table (that is,
149** the index of its hash value).
150*/
151static Node *mainpositionTV (const Table *t, const TValue *key) {
152 switch (ttypetag(key)) {
153 case LUA_VNUMINT: {
154 lua_Integer i = ivalue(key);
155 return hashint(t, i);
156 }
157 case LUA_VNUMFLT: {
158 lua_Number n = fltvalue(key);
159 return hashmod(t, l_hashfloat(n));
160 }
161 case LUA_VSHRSTR: {
162 TString *ts = tsvalue(key);
163 return hashstr(t, ts);
164 }
165 case LUA_VLNGSTR: {
166 TString *ts = tsvalue(key);
167 return hashpow2(t, luaS_hashlongstr(ts));
168 }
169 case LUA_VFALSE:
170 return hashboolean(t, 0);
171 case LUA_VTRUE:
172 return hashboolean(t, 1);
173 case LUA_VLIGHTUSERDATA: {
174 void *p = pvalue(key);
175 return hashpointer(t, p);
176 }
177 case LUA_VLCF: {
178 lua_CFunction f = fvalue(key);
179 return hashpointer(t, f);
180 }
181 default: {
182 GCObject *o = gcvalue(key);
183 return hashpointer(t, o);
184 }
185 }
186}
187
188
189l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {
190 TValue key;
191 getnodekey(cast(lua_State *, NULL), &key, nd);
192 return mainpositionTV(t, &key);
193}
194
195
196/*
197** Check whether key 'k1' is equal to the key in node 'n2'. This
198** equality is raw, so there are no metamethods. Floats with integer
199** values have been normalized, so integers cannot be equal to
200** floats. It is assumed that 'eqshrstr' is simply pointer equality, so
201** that short strings are handled in the default case.
202** A true 'deadok' means to accept dead keys as equal to their original
203** values. All dead keys are compared in the default case, by pointer
204** identity. (Only collectable objects can produce dead keys.) Note that
205** dead long strings are also compared by identity.
206** Once a key is dead, its corresponding value may be collected, and
207** then another value can be created with the same address. If this
208** other value is given to 'next', 'equalkey' will signal a false
209** positive. In a regular traversal, this situation should never happen,
210** as all keys given to 'next' came from the table itself, and therefore
211** could not have been collected. Outside a regular traversal, we
212** have garbage in, garbage out. What is relevant is that this false
213** positive does not break anything. (In particular, 'next' will return
214** some other valid item on the table or nil.)
215*/
216static int equalkey (const TValue *k1, const Node *n2, int deadok) {
217 if ((rawtt(k1) != keytt(n2)) && /* not the same variants? */
218 !(deadok && keyisdead(n2) && iscollectable(k1)))
219 return 0; /* cannot be same key */
220 switch (keytt(n2)) {
221 case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
222 return 1;
223 case LUA_VNUMINT:
224 return (ivalue(k1) == keyival(n2));
225 case LUA_VNUMFLT:
226 return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
227 case LUA_VLIGHTUSERDATA:
228 return pvalue(k1) == pvalueraw(keyval(n2));
229 case LUA_VLCF:
230 return fvalue(k1) == fvalueraw(keyval(n2));
231 case ctb(LUA_VLNGSTR):
232 return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
233 default:
234 return gcvalue(k1) == gcvalueraw(keyval(n2));
235 }
236}
237
238
239/*
240** True if value of 'alimit' is equal to the real size of the array
241** part of table 't'. (Otherwise, the array part must be larger than
242** 'alimit'.)
243*/
244#define limitequalsasize(t) (isrealasize(t) || ispow2((t)->alimit))
245
246
247/*
248** Returns the real size of the 'array' array
249*/
250LUAI_FUNC unsigned int luaH_realasize (const Table *t) {
251 if (limitequalsasize(t))
252 return t->alimit; /* this is the size */
253 else {
254 unsigned int size = t->alimit;
255 /* compute the smallest power of 2 not smaller than 'size' */
256 size |= (size >> 1);
257 size |= (size >> 2);
258 size |= (size >> 4);
259 size |= (size >> 8);
260#if (UINT_MAX >> 14) > 3 /* unsigned int has more than 16 bits */
261 size |= (size >> 16);
262#if (UINT_MAX >> 30) > 3
263 size |= (size >> 32); /* unsigned int has more than 32 bits */
264#endif
265#endif
266 size++;
267 lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size);
268 return size;
269 }
270}
271
272
273/*
274** Check whether real size of the array is a power of 2.
275** (If it is not, 'alimit' cannot be changed to any other value
276** without changing the real size.)
277*/
278static int ispow2realasize (const Table *t) {
279 return (!isrealasize(t) || ispow2(t->alimit));
280}
281
282
283static unsigned int setlimittosize (Table *t) {
284 t->alimit = luaH_realasize(t);
285 setrealasize(t);
286 return t->alimit;
287}
288
289
290#define limitasasize(t) check_exp(isrealasize(t), t->alimit)
291
292
293
294/*
295** "Generic" get version. (Not that generic: not valid for integers,
296** which may be in array part, nor for floats with integral values.)
297** See explanation about 'deadok' in function 'equalkey'.
298*/
299static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
300 Node *n = mainpositionTV(t, key);
301 for (;;) { /* check whether 'key' is somewhere in the chain */
302 if (equalkey(key, n, deadok))
303 return gval(n); /* that's it */
304 else {
305 int nx = gnext(n);
306 if (nx == 0)
307 return &absentkey; /* not found */
308 n += nx;
309 }
310 }
311}
312
313
314/*
315** returns the index for 'k' if 'k' is an appropriate key to live in
316** the array part of a table, 0 otherwise.
317*/
318static unsigned int arrayindex (lua_Integer k) {
319 if (l_castS2U(k) - 1u < MAXASIZE) /* 'k' in [1, MAXASIZE]? */
320 return cast_uint(k); /* 'key' is an appropriate array index */
321 else
322 return 0;
323}
324
325
326/*
327** returns the index of a 'key' for table traversals. First goes all
328** elements in the array part, then elements in the hash part. The
329** beginning of a traversal is signaled by 0.
330*/
331static unsigned int findindex (lua_State *L, Table *t, TValue *key,
332 unsigned int asize) {
333 unsigned int i;
334 if (ttisnil(key)) return 0; /* first iteration */
335 i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;
336 if (i - 1u < asize) /* is 'key' inside array part? */
337 return i; /* yes; that's the index */
338 else {
339 const TValue *n = getgeneric(t, key, 1);
340 if (l_unlikely(isabstkey(n)))
341 luaG_runerror(L, "invalid key to 'next'"); /* key not found */
342 i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */
343 /* hash elements are numbered after array ones */
344 return (i + 1) + asize;
345 }
346}
347
348
349int luaH_next (lua_State *L, Table *t, StkId key) {
350 unsigned int asize = luaH_realasize(t);
351 unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */
352 for (; i < asize; i++) { /* try first array part */
353 if (!isempty(&t->array[i])) { /* a non-empty entry? */
354 setivalue(s2v(key), i + 1);
355 setobj2s(L, key + 1, &t->array[i]);
356 return 1;
357 }
358 }
359 for (i -= asize; cast_int(i) < sizenode(t); i++) { /* hash part */
360 if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */
361 Node *n = gnode(t, i);
362 getnodekey(L, s2v(key), n);
363 setobj2s(L, key + 1, gval(n));
364 return 1;
365 }
366 }
367 return 0; /* no more elements */
368}
369
370
371static void freehash (lua_State *L, Table *t) {
372 if (!isdummy(t))
373 luaM_freearray(L, t->node, cast_sizet(sizenode(t)));
374}
375
376
377/*
378** {=============================================================
379** Rehash
380** ==============================================================
381*/
382
383/*
384** Compute the optimal size for the array part of table 't'. 'nums' is a
385** "count array" where 'nums[i]' is the number of integers in the table
386** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
387** integer keys in the table and leaves with the number of keys that
388** will go to the array part; return the optimal size. (The condition
389** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
390*/
391static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
392 int i;
393 unsigned int twotoi; /* 2^i (candidate for optimal size) */
394 unsigned int a = 0; /* number of elements smaller than 2^i */
395 unsigned int na = 0; /* number of elements to go to array part */
396 unsigned int optimal = 0; /* optimal size for array part */
397 /* loop while keys can fill more than half of total size */
398 for (i = 0, twotoi = 1;
399 twotoi > 0 && *pna > twotoi / 2;
400 i++, twotoi *= 2) {
401 a += nums[i];
402 if (a > twotoi/2) { /* more than half elements present? */
403 optimal = twotoi; /* optimal size (till now) */
404 na = a; /* all elements up to 'optimal' will go to array part */
405 }
406 }
407 lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
408 *pna = na;
409 return optimal;
410}
411
412
413static int countint (lua_Integer key, unsigned int *nums) {
414 unsigned int k = arrayindex(key);
415 if (k != 0) { /* is 'key' an appropriate array index? */
416 nums[luaO_ceillog2(k)]++; /* count as such */
417 return 1;
418 }
419 else
420 return 0;
421}
422
423
424/*
425** Count keys in array part of table 't': Fill 'nums[i]' with
426** number of keys that will go into corresponding slice and return
427** total number of non-nil keys.
428*/
429static unsigned int numusearray (const Table *t, unsigned int *nums) {
430 int lg;
431 unsigned int ttlg; /* 2^lg */
432 unsigned int ause = 0; /* summation of 'nums' */
433 unsigned int i = 1; /* count to traverse all array keys */
434 unsigned int asize = limitasasize(t); /* real array size */
435 /* traverse each slice */
436 for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
437 unsigned int lc = 0; /* counter */
438 unsigned int lim = ttlg;
439 if (lim > asize) {
440 lim = asize; /* adjust upper limit */
441 if (i > lim)
442 break; /* no more elements to count */
443 }
444 /* count elements in range (2^(lg - 1), 2^lg] */
445 for (; i <= lim; i++) {
446 if (!isempty(&t->array[i-1]))
447 lc++;
448 }
449 nums[lg] += lc;
450 ause += lc;
451 }
452 return ause;
453}
454
455
456static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
457 int totaluse = 0; /* total number of elements */
458 int ause = 0; /* elements added to 'nums' (can go to array part) */
459 int i = sizenode(t);
460 while (i--) {
461 Node *n = &t->node[i];
462 if (!isempty(gval(n))) {
463 if (keyisinteger(n))
464 ause += countint(keyival(n), nums);
465 totaluse++;
466 }
467 }
468 *pna += ause;
469 return totaluse;
470}
471
472
473/*
474** Creates an array for the hash part of a table with the given
475** size, or reuses the dummy node if size is zero.
476** The computation for size overflow is in two steps: the first
477** comparison ensures that the shift in the second one does not
478** overflow.
479*/
480static void setnodevector (lua_State *L, Table *t, unsigned int size) {
481 if (size == 0) { /* no elements to hash part? */
482 t->node = cast(Node *, dummynode); /* use common 'dummynode' */
483 t->lsizenode = 0;
484 t->lastfree = NULL; /* signal that it is using dummy node */
485 }
486 else {
487 int i;
488 int lsize = luaO_ceillog2(size);
489 if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
490 luaG_runerror(L, "table overflow");
491 size = twoto(lsize);
492 t->node = luaM_newvector(L, size, Node);
493 for (i = 0; i < cast_int(size); i++) {
494 Node *n = gnode(t, i);
495 gnext(n) = 0;
496 setnilkey(n);
497 setempty(gval(n));
498 }
499 t->lsizenode = cast_byte(lsize);
500 t->lastfree = gnode(t, size); /* all positions are free */
501 }
502}
503
504
505/*
506** (Re)insert all elements from the hash part of 'ot' into table 't'.
507*/
508static void reinsert (lua_State *L, Table *ot, Table *t) {
509 int j;
510 int size = sizenode(ot);
511 for (j = 0; j < size; j++) {
512 Node *old = gnode(ot, j);
513 if (!isempty(gval(old))) {
514 /* doesn't need barrier/invalidate cache, as entry was
515 already present in the table */
516 TValue k;
517 getnodekey(L, &k, old);
518 luaH_set(L, t, &k, gval(old));
519 }
520 }
521}
522
523
524/*
525** Exchange the hash part of 't1' and 't2'.
526*/
527static void exchangehashpart (Table *t1, Table *t2) {
528 lu_byte lsizenode = t1->lsizenode;
529 Node *node = t1->node;
530 Node *lastfree = t1->lastfree;
531 t1->lsizenode = t2->lsizenode;
532 t1->node = t2->node;
533 t1->lastfree = t2->lastfree;
534 t2->lsizenode = lsizenode;
535 t2->node = node;
536 t2->lastfree = lastfree;
537}
538
539
540/*
541** Resize table 't' for the new given sizes. Both allocations (for
542** the hash part and for the array part) can fail, which creates some
543** subtleties. If the first allocation, for the hash part, fails, an
544** error is raised and that is it. Otherwise, it copies the elements from
545** the shrinking part of the array (if it is shrinking) into the new
546** hash. Then it reallocates the array part. If that fails, the table
547** is in its original state; the function frees the new hash part and then
548** raises the allocation error. Otherwise, it sets the new hash part
549** into the table, initializes the new part of the array (if any) with
550** nils and reinserts the elements of the old hash back into the new
551** parts of the table.
552*/
553void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
554 unsigned int nhsize) {
555 unsigned int i;
556 Table newt; /* to keep the new hash part */
557 unsigned int oldasize = setlimittosize(t);
558 TValue *newarray;
559 /* create new hash part with appropriate size into 'newt' */
560 setnodevector(L, &newt, nhsize);
561 if (newasize < oldasize) { /* will array shrink? */
562 t->alimit = newasize; /* pretend array has new size... */
563 exchangehashpart(t, &newt); /* and new hash */
564 /* re-insert into the new hash the elements from vanishing slice */
565 for (i = newasize; i < oldasize; i++) {
566 if (!isempty(&t->array[i]))
567 luaH_setint(L, t, i + 1, &t->array[i]);
568 }
569 t->alimit = oldasize; /* restore current size... */
570 exchangehashpart(t, &newt); /* and hash (in case of errors) */
571 }
572 /* allocate new array */
573 newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);
574 if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
575 freehash(L, &newt); /* release new hash part */
576 luaM_error(L); /* raise error (with array unchanged) */
577 }
578 /* allocation ok; initialize new part of the array */
579 exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
580 t->array = newarray; /* set new array part */
581 t->alimit = newasize;
582 for (i = oldasize; i < newasize; i++) /* clear new slice of the array */
583 setempty(&t->array[i]);
584 /* re-insert elements from old hash part into new parts */
585 reinsert(L, &newt, t); /* 'newt' now has the old hash */
586 freehash(L, &newt); /* free old hash part */
587}
588
589
590void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
591 int nsize = allocsizenode(t);
592 luaH_resize(L, t, nasize, nsize);
593}
594
595/*
596** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
597*/
598static void rehash (lua_State *L, Table *t, const TValue *ek) {
599 unsigned int asize; /* optimal size for array part */
600 unsigned int na; /* number of keys in the array part */
601 unsigned int nums[MAXABITS + 1];
602 int i;
603 int totaluse;
604 for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
605 setlimittosize(t);
606 na = numusearray(t, nums); /* count keys in array part */
607 totaluse = na; /* all those keys are integer keys */
608 totaluse += numusehash(t, nums, &na); /* count keys in hash part */
609 /* count extra key */
610 if (ttisinteger(ek))
611 na += countint(ivalue(ek), nums);
612 totaluse++;
613 /* compute new size for array part */
614 asize = computesizes(nums, &na);
615 /* resize the table to new computed sizes */
616 luaH_resize(L, t, asize, totaluse - na);
617}
618
619
620
621/*
622** }=============================================================
623*/
624
625
626Table *luaH_new (lua_State *L) {
627 GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
628 Table *t = gco2t(o);
629 t->metatable = NULL;
630 t->flags = cast_byte(maskflags); /* table has no metamethod fields */
631 t->array = NULL;
632 t->alimit = 0;
633 setnodevector(L, t, 0);
634 return t;
635}
636
637
638void luaH_free (lua_State *L, Table *t) {
639 freehash(L, t);
640 luaM_freearray(L, t->array, luaH_realasize(t));
641 luaM_free(L, t);
642}
643
644
645static Node *getfreepos (Table *t) {
646 if (!isdummy(t)) {
647 while (t->lastfree > t->node) {
648 t->lastfree--;
649 if (keyisnil(t->lastfree))
650 return t->lastfree;
651 }
652 }
653 return NULL; /* could not find a free place */
654}
655
656
657
658/*
659** inserts a new key into a hash table; first, check whether key's main
660** position is free. If not, check whether colliding node is in its main
661** position or not: if it is not, move colliding node to an empty place and
662** put new key in its main position; otherwise (colliding node is in its main
663** position), new key goes to an empty position.
664*/
665static void luaH_newkey (lua_State *L, Table *t, const TValue *key,
666 TValue *value) {
667 Node *mp;
668 TValue aux;
669 if (l_unlikely(ttisnil(key)))
670 luaG_runerror(L, "table index is nil");
671 else if (ttisfloat(key)) {
672 lua_Number f = fltvalue(key);
673 lua_Integer k;
674 if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */
675 setivalue(&aux, k);
676 key = &aux; /* insert it as an integer */
677 }
678 else if (l_unlikely(luai_numisnan(f)))
679 luaG_runerror(L, "table index is NaN");
680 }
681 if (ttisnil(value))
682 return; /* do not insert nil values */
683 mp = mainpositionTV(t, key);
684 if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
685 Node *othern;
686 Node *f = getfreepos(t); /* get a free place */
687 if (f == NULL) { /* cannot find a free place? */
688 rehash(L, t, key); /* grow table */
689 /* whatever called 'newkey' takes care of TM cache */
690 luaH_set(L, t, key, value); /* insert key into grown table */
691 return;
692 }
693 lua_assert(!isdummy(t));
694 othern = mainpositionfromnode(t, mp);
695 if (othern != mp) { /* is colliding node out of its main position? */
696 /* yes; move colliding node into free position */
697 while (othern + gnext(othern) != mp) /* find previous */
698 othern += gnext(othern);
699 gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
700 *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
701 if (gnext(mp) != 0) {
702 gnext(f) += cast_int(mp - f); /* correct 'next' */
703 gnext(mp) = 0; /* now 'mp' is free */
704 }
705 setempty(gval(mp));
706 }
707 else { /* colliding node is in its own main position */
708 /* new node will go into free position */
709 if (gnext(mp) != 0)
710 gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
711 else lua_assert(gnext(f) == 0);
712 gnext(mp) = cast_int(f - mp);
713 mp = f;
714 }
715 }
716 setnodekey(L, mp, key);
717 luaC_barrierback(L, obj2gco(t), key);
718 lua_assert(isempty(gval(mp)));
719 setobj2t(L, gval(mp), value);
720}
721
722
723/*
724** Search function for integers. If integer is inside 'alimit', get it
725** directly from the array part. Otherwise, if 'alimit' is not
726** the real size of the array, the key still can be in the array part.
727** In this case, do the "Xmilia trick" to check whether 'key-1' is
728** smaller than the real size.
729** The trick works as follow: let 'p' be an integer such that
730** '2^(p+1) >= alimit > 2^p', or '2^(p+1) > alimit-1 >= 2^p'.
731** That is, 2^(p+1) is the real size of the array, and 'p' is the highest
732** bit on in 'alimit-1'. What we have to check becomes 'key-1 < 2^(p+1)'.
733** We compute '(key-1) & ~(alimit-1)', which we call 'res'; it will
734** have the 'p' bit cleared. If the key is outside the array, that is,
735** 'key-1 >= 2^(p+1)', then 'res' will have some bit on higher than 'p',
736** therefore it will be larger or equal to 'alimit', and the check
737** will fail. If 'key-1 < 2^(p+1)', then 'res' has no bit on higher than
738** 'p', and as the bit 'p' itself was cleared, 'res' will be smaller
739** than 2^p, therefore smaller than 'alimit', and the check succeeds.
740** As special cases, when 'alimit' is 0 the condition is trivially false,
741** and when 'alimit' is 1 the condition simplifies to 'key-1 < alimit'.
742** If key is 0 or negative, 'res' will have its higher bit on, so that
743** if cannot be smaller than alimit.
744*/
745const TValue *luaH_getint (Table *t, lua_Integer key) {
746 lua_Unsigned alimit = t->alimit;
747 if (l_castS2U(key) - 1u < alimit) /* 'key' in [1, t->alimit]? */
748 return &t->array[key - 1];
749 else if (!isrealasize(t) && /* key still may be in the array part? */
750 (((l_castS2U(key) - 1u) & ~(alimit - 1u)) < alimit)) {
751 t->alimit = cast_uint(key); /* probably '#t' is here now */
752 return &t->array[key - 1];
753 }
754 else { /* key is not in the array part; check the hash */
755 Node *n = hashint(t, key);
756 for (;;) { /* check whether 'key' is somewhere in the chain */
757 if (keyisinteger(n) && keyival(n) == key)
758 return gval(n); /* that's it */
759 else {
760 int nx = gnext(n);
761 if (nx == 0) break;
762 n += nx;
763 }
764 }
765 return &absentkey;
766 }
767}
768
769
770/*
771** search function for short strings
772*/
773const TValue *luaH_getshortstr (Table *t, TString *key) {
774 Node *n = hashstr(t, key);
775 lua_assert(key->tt == LUA_VSHRSTR);
776 for (;;) { /* check whether 'key' is somewhere in the chain */
777 if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
778 return gval(n); /* that's it */
779 else {
780 int nx = gnext(n);
781 if (nx == 0)
782 return &absentkey; /* not found */
783 n += nx;
784 }
785 }
786}
787
788
789const TValue *luaH_getstr (Table *t, TString *key) {
790 if (key->tt == LUA_VSHRSTR)
791 return luaH_getshortstr(t, key);
792 else { /* for long strings, use generic case */
793 TValue ko;
794 setsvalue(cast(lua_State *, NULL), &ko, key);
795 return getgeneric(t, &ko, 0);
796 }
797}
798
799
800/*
801** main search function
802*/
803const TValue *luaH_get (Table *t, const TValue *key) {
804 switch (ttypetag(key)) {
805 case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key));
806 case LUA_VNUMINT: return luaH_getint(t, ivalue(key));
807 case LUA_VNIL: return &absentkey;
808 case LUA_VNUMFLT: {
809 lua_Integer k;
810 if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
811 return luaH_getint(t, k); /* use specialized version */
812 /* else... */
813 } /* FALLTHROUGH */
814 default:
815 return getgeneric(t, key, 0);
816 }
817}
818
819
820/*
821** Finish a raw "set table" operation, where 'slot' is where the value
822** should have been (the result of a previous "get table").
823** Beware: when using this function you probably need to check a GC
824** barrier and invalidate the TM cache.
825*/
826void luaH_finishset (lua_State *L, Table *t, const TValue *key,
827 const TValue *slot, TValue *value) {
828 if (isabstkey(slot))
829 luaH_newkey(L, t, key, value);
830 else
831 setobj2t(L, cast(TValue *, slot), value);
832}
833
834
835/*
836** beware: when using this function you probably need to check a GC
837** barrier and invalidate the TM cache.
838*/
839void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
840 const TValue *slot = luaH_get(t, key);
841 luaH_finishset(L, t, key, slot, value);
842}
843
844
845void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
846 const TValue *p = luaH_getint(t, key);
847 if (isabstkey(p)) {
848 TValue k;
849 setivalue(&k, key);
850 luaH_newkey(L, t, &k, value);
851 }
852 else
853 setobj2t(L, cast(TValue *, p), value);
854}
855
856
857/*
858** Try to find a boundary in the hash part of table 't'. From the
859** caller, we know that 'j' is zero or present and that 'j + 1' is
860** present. We want to find a larger key that is absent from the
861** table, so that we can do a binary search between the two keys to
862** find a boundary. We keep doubling 'j' until we get an absent index.
863** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
864** absent, we are ready for the binary search. ('j', being max integer,
865** is larger or equal to 'i', but it cannot be equal because it is
866** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
867** boundary. ('j + 1' cannot be a present integer key because it is
868** not a valid integer in Lua.)
869*/
870static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
871 lua_Unsigned i;
872 if (j == 0) j++; /* the caller ensures 'j + 1' is present */
873 do {
874 i = j; /* 'i' is a present index */
875 if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
876 j *= 2;
877 else {
878 j = LUA_MAXINTEGER;
879 if (isempty(luaH_getint(t, j))) /* t[j] not present? */
880 break; /* 'j' now is an absent index */
881 else /* weird case */
882 return j; /* well, max integer is a boundary... */
883 }
884 } while (!isempty(luaH_getint(t, j))); /* repeat until an absent t[j] */
885 /* i < j && t[i] present && t[j] absent */
886 while (j - i > 1u) { /* do a binary search between them */
887 lua_Unsigned m = (i + j) / 2;
888 if (isempty(luaH_getint(t, m))) j = m;
889 else i = m;
890 }
891 return i;
892}
893
894
895static unsigned int binsearch (const TValue *array, unsigned int i,
896 unsigned int j) {
897 while (j - i > 1u) { /* binary search */
898 unsigned int m = (i + j) / 2;
899 if (isempty(&array[m - 1])) j = m;
900 else i = m;
901 }
902 return i;
903}
904
905
906/*
907** Try to find a boundary in table 't'. (A 'boundary' is an integer index
908** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
909** and 'maxinteger' if t[maxinteger] is present.)
910** (In the next explanation, we use Lua indices, that is, with base 1.
911** The code itself uses base 0 when indexing the array part of the table.)
912** The code starts with 'limit = t->alimit', a position in the array
913** part that may be a boundary.
914**
915** (1) If 't[limit]' is empty, there must be a boundary before it.
916** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
917** is present. If so, it is a boundary. Otherwise, do a binary search
918** between 0 and limit to find a boundary. In both cases, try to
919** use this boundary as the new 'alimit', as a hint for the next call.
920**
921** (2) If 't[limit]' is not empty and the array has more elements
922** after 'limit', try to find a boundary there. Again, try first
923** the special case (which should be quite frequent) where 'limit+1'
924** is empty, so that 'limit' is a boundary. Otherwise, check the
925** last element of the array part. If it is empty, there must be a
926** boundary between the old limit (present) and the last element
927** (absent), which is found with a binary search. (This boundary always
928** can be a new limit.)
929**
930** (3) The last case is when there are no elements in the array part
931** (limit == 0) or its last element (the new limit) is present.
932** In this case, must check the hash part. If there is no hash part
933** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call
934** 'hash_search' to find a boundary in the hash part of the table.
935** (In those cases, the boundary is not inside the array part, and
936** therefore cannot be used as a new limit.)
937*/
938lua_Unsigned luaH_getn (Table *t) {
939 unsigned int limit = t->alimit;
940 if (limit > 0 && isempty(&t->array[limit - 1])) { /* (1)? */
941 /* there must be a boundary before 'limit' */
942 if (limit >= 2 && !isempty(&t->array[limit - 2])) {
943 /* 'limit - 1' is a boundary; can it be a new limit? */
944 if (ispow2realasize(t) && !ispow2(limit - 1)) {
945 t->alimit = limit - 1;
946 setnorealasize(t); /* now 'alimit' is not the real size */
947 }
948 return limit - 1;
949 }
950 else { /* must search for a boundary in [0, limit] */
951 unsigned int boundary = binsearch(t->array, 0, limit);
952 /* can this boundary represent the real size of the array? */
953 if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {
954 t->alimit = boundary; /* use it as the new limit */
955 setnorealasize(t);
956 }
957 return boundary;
958 }
959 }
960 /* 'limit' is zero or present in table */
961 if (!limitequalsasize(t)) { /* (2)? */
962 /* 'limit' > 0 and array has more elements after 'limit' */
963 if (isempty(&t->array[limit])) /* 'limit + 1' is empty? */
964 return limit; /* this is the boundary */
965 /* else, try last element in the array */
966 limit = luaH_realasize(t);
967 if (isempty(&t->array[limit - 1])) { /* empty? */
968 /* there must be a boundary in the array after old limit,
969 and it must be a valid new limit */
970 unsigned int boundary = binsearch(t->array, t->alimit, limit);
971 t->alimit = boundary;
972 return boundary;
973 }
974 /* else, new limit is present in the table; check the hash part */
975 }
976 /* (3) 'limit' is the last element and either is zero or present in table */
977 lua_assert(limit == luaH_realasize(t) &&
978 (limit == 0 || !isempty(&t->array[limit - 1])));
979 if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1))))
980 return limit; /* 'limit + 1' is absent */
981 else /* 'limit + 1' is also present */
982 return hash_search(t, limit);
983}
984
985
986
987#if defined(LUA_DEBUG)
988
989/* export these functions for the test library */
990
991Node *luaH_mainposition (const Table *t, const TValue *key) {
992 return mainpositionTV(t, key);
993}
994
995#endif
diff --git a/vendor/lua-5.4.8/src/ltable.h b/vendor/lua-5.4.8/src/ltable.h
new file mode 100644
index 0000000..8e68903
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ltable.h
@@ -0,0 +1,63 @@
1/*
2** $Id: ltable.h $
3** Lua tables (hash)
4** See Copyright Notice in lua.h
5*/
6
7#ifndef ltable_h
8#define ltable_h
9
10#include "lobject.h"
11
12
13#define gnode(t,i) (&(t)->node[i])
14#define gval(n) (&(n)->i_val)
15#define gnext(n) ((n)->u.next)
16
17
18/*
19** Clear all bits of fast-access metamethods, which means that the table
20** may have any of these metamethods. (First access that fails after the
21** clearing will set the bit again.)
22*/
23#define invalidateTMcache(t) ((t)->flags &= ~maskflags)
24
25
26/* true when 't' is using 'dummynode' as its hash part */
27#define isdummy(t) ((t)->lastfree == NULL)
28
29
30/* allocated size for hash nodes */
31#define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t))
32
33
34/* returns the Node, given the value of a table entry */
35#define nodefromval(v) cast(Node *, (v))
36
37
38LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key);
39LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key,
40 TValue *value);
41LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key);
42LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
43LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
44LUAI_FUNC void luaH_set (lua_State *L, Table *t, const TValue *key,
45 TValue *value);
46LUAI_FUNC void luaH_finishset (lua_State *L, Table *t, const TValue *key,
47 const TValue *slot, TValue *value);
48LUAI_FUNC Table *luaH_new (lua_State *L);
49LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
50 unsigned int nhsize);
51LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize);
52LUAI_FUNC void luaH_free (lua_State *L, Table *t);
53LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);
54LUAI_FUNC lua_Unsigned luaH_getn (Table *t);
55LUAI_FUNC unsigned int luaH_realasize (const Table *t);
56
57
58#if defined(LUA_DEBUG)
59LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key);
60#endif
61
62
63#endif
diff --git a/vendor/lua-5.4.8/src/ltablib.c b/vendor/lua-5.4.8/src/ltablib.c
new file mode 100644
index 0000000..e6bc4d0
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ltablib.c
@@ -0,0 +1,430 @@
1/*
2** $Id: ltablib.c $
3** Library for Table Manipulation
4** See Copyright Notice in lua.h
5*/
6
7#define ltablib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <limits.h>
14#include <stddef.h>
15#include <string.h>
16
17#include "lua.h"
18
19#include "lauxlib.h"
20#include "lualib.h"
21
22
23/*
24** Operations that an object must define to mimic a table
25** (some functions only need some of them)
26*/
27#define TAB_R 1 /* read */
28#define TAB_W 2 /* write */
29#define TAB_L 4 /* length */
30#define TAB_RW (TAB_R | TAB_W) /* read/write */
31
32
33#define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n))
34
35
36static int checkfield (lua_State *L, const char *key, int n) {
37 lua_pushstring(L, key);
38 return (lua_rawget(L, -n) != LUA_TNIL);
39}
40
41
42/*
43** Check that 'arg' either is a table or can behave like one (that is,
44** has a metatable with the required metamethods)
45*/
46static void checktab (lua_State *L, int arg, int what) {
47 if (lua_type(L, arg) != LUA_TTABLE) { /* is it not a table? */
48 int n = 1; /* number of elements to pop */
49 if (lua_getmetatable(L, arg) && /* must have metatable */
50 (!(what & TAB_R) || checkfield(L, "__index", ++n)) &&
51 (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) &&
52 (!(what & TAB_L) || checkfield(L, "__len", ++n))) {
53 lua_pop(L, n); /* pop metatable and tested metamethods */
54 }
55 else
56 luaL_checktype(L, arg, LUA_TTABLE); /* force an error */
57 }
58}
59
60
61static int tinsert (lua_State *L) {
62 lua_Integer pos; /* where to insert new element */
63 lua_Integer e = aux_getn(L, 1, TAB_RW);
64 e = luaL_intop(+, e, 1); /* first empty element */
65 switch (lua_gettop(L)) {
66 case 2: { /* called with only 2 arguments */
67 pos = e; /* insert new element at the end */
68 break;
69 }
70 case 3: {
71 lua_Integer i;
72 pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */
73 /* check whether 'pos' is in [1, e] */
74 luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2,
75 "position out of bounds");
76 for (i = e; i > pos; i--) { /* move up elements */
77 lua_geti(L, 1, i - 1);
78 lua_seti(L, 1, i); /* t[i] = t[i - 1] */
79 }
80 break;
81 }
82 default: {
83 return luaL_error(L, "wrong number of arguments to 'insert'");
84 }
85 }
86 lua_seti(L, 1, pos); /* t[pos] = v */
87 return 0;
88}
89
90
91static int tremove (lua_State *L) {
92 lua_Integer size = aux_getn(L, 1, TAB_RW);
93 lua_Integer pos = luaL_optinteger(L, 2, size);
94 if (pos != size) /* validate 'pos' if given */
95 /* check whether 'pos' is in [1, size + 1] */
96 luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 2,
97 "position out of bounds");
98 lua_geti(L, 1, pos); /* result = t[pos] */
99 for ( ; pos < size; pos++) {
100 lua_geti(L, 1, pos + 1);
101 lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */
102 }
103 lua_pushnil(L);
104 lua_seti(L, 1, pos); /* remove entry t[pos] */
105 return 1;
106}
107
108
109/*
110** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever
111** possible, copy in increasing order, which is better for rehashing.
112** "possible" means destination after original range, or smaller
113** than origin, or copying to another table.
114*/
115static int tmove (lua_State *L) {
116 lua_Integer f = luaL_checkinteger(L, 2);
117 lua_Integer e = luaL_checkinteger(L, 3);
118 lua_Integer t = luaL_checkinteger(L, 4);
119 int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */
120 checktab(L, 1, TAB_R);
121 checktab(L, tt, TAB_W);
122 if (e >= f) { /* otherwise, nothing to move */
123 lua_Integer n, i;
124 luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3,
125 "too many elements to move");
126 n = e - f + 1; /* number of elements to move */
127 luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4,
128 "destination wrap around");
129 if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) {
130 for (i = 0; i < n; i++) {
131 lua_geti(L, 1, f + i);
132 lua_seti(L, tt, t + i);
133 }
134 }
135 else {
136 for (i = n - 1; i >= 0; i--) {
137 lua_geti(L, 1, f + i);
138 lua_seti(L, tt, t + i);
139 }
140 }
141 }
142 lua_pushvalue(L, tt); /* return destination table */
143 return 1;
144}
145
146
147static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {
148 lua_geti(L, 1, i);
149 if (l_unlikely(!lua_isstring(L, -1)))
150 luaL_error(L, "invalid value (%s) at index %I in table for 'concat'",
151 luaL_typename(L, -1), (LUAI_UACINT)i);
152 luaL_addvalue(b);
153}
154
155
156static int tconcat (lua_State *L) {
157 luaL_Buffer b;
158 lua_Integer last = aux_getn(L, 1, TAB_R);
159 size_t lsep;
160 const char *sep = luaL_optlstring(L, 2, "", &lsep);
161 lua_Integer i = luaL_optinteger(L, 3, 1);
162 last = luaL_optinteger(L, 4, last);
163 luaL_buffinit(L, &b);
164 for (; i < last; i++) {
165 addfield(L, &b, i);
166 luaL_addlstring(&b, sep, lsep);
167 }
168 if (i == last) /* add last value (if interval was not empty) */
169 addfield(L, &b, i);
170 luaL_pushresult(&b);
171 return 1;
172}
173
174
175/*
176** {======================================================
177** Pack/unpack
178** =======================================================
179*/
180
181static int tpack (lua_State *L) {
182 int i;
183 int n = lua_gettop(L); /* number of elements to pack */
184 lua_createtable(L, n, 1); /* create result table */
185 lua_insert(L, 1); /* put it at index 1 */
186 for (i = n; i >= 1; i--) /* assign elements */
187 lua_seti(L, 1, i);
188 lua_pushinteger(L, n);
189 lua_setfield(L, 1, "n"); /* t.n = number of elements */
190 return 1; /* return table */
191}
192
193
194static int tunpack (lua_State *L) {
195 lua_Unsigned n;
196 lua_Integer i = luaL_optinteger(L, 2, 1);
197 lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
198 if (i > e) return 0; /* empty range */
199 n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */
200 if (l_unlikely(n >= (unsigned int)INT_MAX ||
201 !lua_checkstack(L, (int)(++n))))
202 return luaL_error(L, "too many results to unpack");
203 for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */
204 lua_geti(L, 1, i);
205 }
206 lua_geti(L, 1, e); /* push last element */
207 return (int)n;
208}
209
210/* }====================================================== */
211
212
213
214/*
215** {======================================================
216** Quicksort
217** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
218** Addison-Wesley, 1993.)
219** =======================================================
220*/
221
222
223/* type for array indices */
224typedef unsigned int IdxT;
225
226
227/*
228** Produce a "random" 'unsigned int' to randomize pivot choice. This
229** macro is used only when 'sort' detects a big imbalance in the result
230** of a partition. (If you don't want/need this "randomness", ~0 is a
231** good choice.)
232*/
233#if !defined(l_randomizePivot) /* { */
234
235#include <time.h>
236
237/* size of 'e' measured in number of 'unsigned int's */
238#define sof(e) (sizeof(e) / sizeof(unsigned int))
239
240/*
241** Use 'time' and 'clock' as sources of "randomness". Because we don't
242** know the types 'clock_t' and 'time_t', we cannot cast them to
243** anything without risking overflows. A safe way to use their values
244** is to copy them to an array of a known type and use the array values.
245*/
246static unsigned int l_randomizePivot (void) {
247 clock_t c = clock();
248 time_t t = time(NULL);
249 unsigned int buff[sof(c) + sof(t)];
250 unsigned int i, rnd = 0;
251 memcpy(buff, &c, sof(c) * sizeof(unsigned int));
252 memcpy(buff + sof(c), &t, sof(t) * sizeof(unsigned int));
253 for (i = 0; i < sof(buff); i++)
254 rnd += buff[i];
255 return rnd;
256}
257
258#endif /* } */
259
260
261/* arrays larger than 'RANLIMIT' may use randomized pivots */
262#define RANLIMIT 100u
263
264
265static void set2 (lua_State *L, IdxT i, IdxT j) {
266 lua_seti(L, 1, i);
267 lua_seti(L, 1, j);
268}
269
270
271/*
272** Return true iff value at stack index 'a' is less than the value at
273** index 'b' (according to the order of the sort).
274*/
275static int sort_comp (lua_State *L, int a, int b) {
276 if (lua_isnil(L, 2)) /* no function? */
277 return lua_compare(L, a, b, LUA_OPLT); /* a < b */
278 else { /* function */
279 int res;
280 lua_pushvalue(L, 2); /* push function */
281 lua_pushvalue(L, a-1); /* -1 to compensate function */
282 lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */
283 lua_call(L, 2, 1); /* call function */
284 res = lua_toboolean(L, -1); /* get result */
285 lua_pop(L, 1); /* pop result */
286 return res;
287 }
288}
289
290
291/*
292** Does the partition: Pivot P is at the top of the stack.
293** precondition: a[lo] <= P == a[up-1] <= a[up],
294** so it only needs to do the partition from lo + 1 to up - 2.
295** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up]
296** returns 'i'.
297*/
298static IdxT partition (lua_State *L, IdxT lo, IdxT up) {
299 IdxT i = lo; /* will be incremented before first use */
300 IdxT j = up - 1; /* will be decremented before first use */
301 /* loop invariant: a[lo .. i] <= P <= a[j .. up] */
302 for (;;) {
303 /* next loop: repeat ++i while a[i] < P */
304 while ((void)lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) {
305 if (l_unlikely(i == up - 1)) /* a[i] < P but a[up - 1] == P ?? */
306 luaL_error(L, "invalid order function for sorting");
307 lua_pop(L, 1); /* remove a[i] */
308 }
309 /* after the loop, a[i] >= P and a[lo .. i - 1] < P */
310 /* next loop: repeat --j while P < a[j] */
311 while ((void)lua_geti(L, 1, --j), sort_comp(L, -3, -1)) {
312 if (l_unlikely(j < i)) /* j < i but a[j] > P ?? */
313 luaL_error(L, "invalid order function for sorting");
314 lua_pop(L, 1); /* remove a[j] */
315 }
316 /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */
317 if (j < i) { /* no elements out of place? */
318 /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */
319 lua_pop(L, 1); /* pop a[j] */
320 /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */
321 set2(L, up - 1, i);
322 return i;
323 }
324 /* otherwise, swap a[i] - a[j] to restore invariant and repeat */
325 set2(L, i, j);
326 }
327}
328
329
330/*
331** Choose an element in the middle (2nd-3th quarters) of [lo,up]
332** "randomized" by 'rnd'
333*/
334static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) {
335 IdxT r4 = (up - lo) / 4; /* range/4 */
336 IdxT p = rnd % (r4 * 2) + (lo + r4);
337 lua_assert(lo + r4 <= p && p <= up - r4);
338 return p;
339}
340
341
342/*
343** Quicksort algorithm (recursive function)
344*/
345static void auxsort (lua_State *L, IdxT lo, IdxT up,
346 unsigned int rnd) {
347 while (lo < up) { /* loop for tail recursion */
348 IdxT p; /* Pivot index */
349 IdxT n; /* to be used later */
350 /* sort elements 'lo', 'p', and 'up' */
351 lua_geti(L, 1, lo);
352 lua_geti(L, 1, up);
353 if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */
354 set2(L, lo, up); /* swap a[lo] - a[up] */
355 else
356 lua_pop(L, 2); /* remove both values */
357 if (up - lo == 1) /* only 2 elements? */
358 return; /* already sorted */
359 if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */
360 p = (lo + up)/2; /* middle element is a good pivot */
361 else /* for larger intervals, it is worth a random pivot */
362 p = choosePivot(lo, up, rnd);
363 lua_geti(L, 1, p);
364 lua_geti(L, 1, lo);
365 if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */
366 set2(L, p, lo); /* swap a[p] - a[lo] */
367 else {
368 lua_pop(L, 1); /* remove a[lo] */
369 lua_geti(L, 1, up);
370 if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */
371 set2(L, p, up); /* swap a[up] - a[p] */
372 else
373 lua_pop(L, 2);
374 }
375 if (up - lo == 2) /* only 3 elements? */
376 return; /* already sorted */
377 lua_geti(L, 1, p); /* get middle element (Pivot) */
378 lua_pushvalue(L, -1); /* push Pivot */
379 lua_geti(L, 1, up - 1); /* push a[up - 1] */
380 set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */
381 p = partition(L, lo, up);
382 /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */
383 if (p - lo < up - p) { /* lower interval is smaller? */
384 auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */
385 n = p - lo; /* size of smaller interval */
386 lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */
387 }
388 else {
389 auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */
390 n = up - p; /* size of smaller interval */
391 up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */
392 }
393 if ((up - lo) / 128 > n) /* partition too imbalanced? */
394 rnd = l_randomizePivot(); /* try a new randomization */
395 } /* tail call auxsort(L, lo, up, rnd) */
396}
397
398
399static int sort (lua_State *L) {
400 lua_Integer n = aux_getn(L, 1, TAB_RW);
401 if (n > 1) { /* non-trivial interval? */
402 luaL_argcheck(L, n < INT_MAX, 1, "array too big");
403 if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */
404 luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */
405 lua_settop(L, 2); /* make sure there are two arguments */
406 auxsort(L, 1, (IdxT)n, 0);
407 }
408 return 0;
409}
410
411/* }====================================================== */
412
413
414static const luaL_Reg tab_funcs[] = {
415 {"concat", tconcat},
416 {"insert", tinsert},
417 {"pack", tpack},
418 {"unpack", tunpack},
419 {"remove", tremove},
420 {"move", tmove},
421 {"sort", sort},
422 {NULL, NULL}
423};
424
425
426LUAMOD_API int luaopen_table (lua_State *L) {
427 luaL_newlib(L, tab_funcs);
428 return 1;
429}
430
diff --git a/vendor/lua-5.4.8/src/ltm.c b/vendor/lua-5.4.8/src/ltm.c
new file mode 100644
index 0000000..07a0608
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ltm.c
@@ -0,0 +1,271 @@
1/*
2** $Id: ltm.c $
3** Tag methods
4** See Copyright Notice in lua.h
5*/
6
7#define ltm_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <string.h>
14
15#include "lua.h"
16
17#include "ldebug.h"
18#include "ldo.h"
19#include "lgc.h"
20#include "lobject.h"
21#include "lstate.h"
22#include "lstring.h"
23#include "ltable.h"
24#include "ltm.h"
25#include "lvm.h"
26
27
28static const char udatatypename[] = "userdata";
29
30LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTYPES] = {
31 "no value",
32 "nil", "boolean", udatatypename, "number",
33 "string", "table", "function", udatatypename, "thread",
34 "upvalue", "proto" /* these last cases are used for tests only */
35};
36
37
38void luaT_init (lua_State *L) {
39 static const char *const luaT_eventname[] = { /* ORDER TM */
40 "__index", "__newindex",
41 "__gc", "__mode", "__len", "__eq",
42 "__add", "__sub", "__mul", "__mod", "__pow",
43 "__div", "__idiv",
44 "__band", "__bor", "__bxor", "__shl", "__shr",
45 "__unm", "__bnot", "__lt", "__le",
46 "__concat", "__call", "__close"
47 };
48 int i;
49 for (i=0; i<TM_N; i++) {
50 G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);
51 luaC_fix(L, obj2gco(G(L)->tmname[i])); /* never collect these names */
52 }
53}
54
55
56/*
57** function to be used with macro "fasttm": optimized for absence of
58** tag methods
59*/
60const TValue *luaT_gettm (Table *events, TMS event, TString *ename) {
61 const TValue *tm = luaH_getshortstr(events, ename);
62 lua_assert(event <= TM_EQ);
63 if (notm(tm)) { /* no tag method? */
64 events->flags |= cast_byte(1u<<event); /* cache this fact */
65 return NULL;
66 }
67 else return tm;
68}
69
70
71const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {
72 Table *mt;
73 switch (ttype(o)) {
74 case LUA_TTABLE:
75 mt = hvalue(o)->metatable;
76 break;
77 case LUA_TUSERDATA:
78 mt = uvalue(o)->metatable;
79 break;
80 default:
81 mt = G(L)->mt[ttype(o)];
82 }
83 return (mt ? luaH_getshortstr(mt, G(L)->tmname[event]) : &G(L)->nilvalue);
84}
85
86
87/*
88** Return the name of the type of an object. For tables and userdata
89** with metatable, use their '__name' metafield, if present.
90*/
91const char *luaT_objtypename (lua_State *L, const TValue *o) {
92 Table *mt;
93 if ((ttistable(o) && (mt = hvalue(o)->metatable) != NULL) ||
94 (ttisfulluserdata(o) && (mt = uvalue(o)->metatable) != NULL)) {
95 const TValue *name = luaH_getshortstr(mt, luaS_new(L, "__name"));
96 if (ttisstring(name)) /* is '__name' a string? */
97 return getstr(tsvalue(name)); /* use it as type name */
98 }
99 return ttypename(ttype(o)); /* else use standard type name */
100}
101
102
103void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,
104 const TValue *p2, const TValue *p3) {
105 StkId func = L->top.p;
106 setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */
107 setobj2s(L, func + 1, p1); /* 1st argument */
108 setobj2s(L, func + 2, p2); /* 2nd argument */
109 setobj2s(L, func + 3, p3); /* 3rd argument */
110 L->top.p = func + 4;
111 /* metamethod may yield only when called from Lua code */
112 if (isLuacode(L->ci))
113 luaD_call(L, func, 0);
114 else
115 luaD_callnoyield(L, func, 0);
116}
117
118
119void luaT_callTMres (lua_State *L, const TValue *f, const TValue *p1,
120 const TValue *p2, StkId res) {
121 ptrdiff_t result = savestack(L, res);
122 StkId func = L->top.p;
123 setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */
124 setobj2s(L, func + 1, p1); /* 1st argument */
125 setobj2s(L, func + 2, p2); /* 2nd argument */
126 L->top.p += 3;
127 /* metamethod may yield only when called from Lua code */
128 if (isLuacode(L->ci))
129 luaD_call(L, func, 1);
130 else
131 luaD_callnoyield(L, func, 1);
132 res = restorestack(L, result);
133 setobjs2s(L, res, --L->top.p); /* move result to its place */
134}
135
136
137static int callbinTM (lua_State *L, const TValue *p1, const TValue *p2,
138 StkId res, TMS event) {
139 const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */
140 if (notm(tm))
141 tm = luaT_gettmbyobj(L, p2, event); /* try second operand */
142 if (notm(tm)) return 0;
143 luaT_callTMres(L, tm, p1, p2, res);
144 return 1;
145}
146
147
148void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
149 StkId res, TMS event) {
150 if (l_unlikely(!callbinTM(L, p1, p2, res, event))) {
151 switch (event) {
152 case TM_BAND: case TM_BOR: case TM_BXOR:
153 case TM_SHL: case TM_SHR: case TM_BNOT: {
154 if (ttisnumber(p1) && ttisnumber(p2))
155 luaG_tointerror(L, p1, p2);
156 else
157 luaG_opinterror(L, p1, p2, "perform bitwise operation on");
158 }
159 /* calls never return, but to avoid warnings: *//* FALLTHROUGH */
160 default:
161 luaG_opinterror(L, p1, p2, "perform arithmetic on");
162 }
163 }
164}
165
166
167void luaT_tryconcatTM (lua_State *L) {
168 StkId top = L->top.p;
169 if (l_unlikely(!callbinTM(L, s2v(top - 2), s2v(top - 1), top - 2,
170 TM_CONCAT)))
171 luaG_concaterror(L, s2v(top - 2), s2v(top - 1));
172}
173
174
175void luaT_trybinassocTM (lua_State *L, const TValue *p1, const TValue *p2,
176 int flip, StkId res, TMS event) {
177 if (flip)
178 luaT_trybinTM(L, p2, p1, res, event);
179 else
180 luaT_trybinTM(L, p1, p2, res, event);
181}
182
183
184void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2,
185 int flip, StkId res, TMS event) {
186 TValue aux;
187 setivalue(&aux, i2);
188 luaT_trybinassocTM(L, p1, &aux, flip, res, event);
189}
190
191
192/*
193** Calls an order tag method.
194** For lessequal, LUA_COMPAT_LT_LE keeps compatibility with old
195** behavior: if there is no '__le', try '__lt', based on l <= r iff
196** !(r < l) (assuming a total order). If the metamethod yields during
197** this substitution, the continuation has to know about it (to negate
198** the result of r<l); bit CIST_LEQ in the call status keeps that
199** information.
200*/
201int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2,
202 TMS event) {
203 if (callbinTM(L, p1, p2, L->top.p, event)) /* try original event */
204 return !l_isfalse(s2v(L->top.p));
205#if defined(LUA_COMPAT_LT_LE)
206 else if (event == TM_LE) {
207 /* try '!(p2 < p1)' for '(p1 <= p2)' */
208 L->ci->callstatus |= CIST_LEQ; /* mark it is doing 'lt' for 'le' */
209 if (callbinTM(L, p2, p1, L->top.p, TM_LT)) {
210 L->ci->callstatus ^= CIST_LEQ; /* clear mark */
211 return l_isfalse(s2v(L->top.p));
212 }
213 /* else error will remove this 'ci'; no need to clear mark */
214 }
215#endif
216 luaG_ordererror(L, p1, p2); /* no metamethod found */
217 return 0; /* to avoid warnings */
218}
219
220
221int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2,
222 int flip, int isfloat, TMS event) {
223 TValue aux; const TValue *p2;
224 if (isfloat) {
225 setfltvalue(&aux, cast_num(v2));
226 }
227 else
228 setivalue(&aux, v2);
229 if (flip) { /* arguments were exchanged? */
230 p2 = p1; p1 = &aux; /* correct them */
231 }
232 else
233 p2 = &aux;
234 return luaT_callorderTM(L, p1, p2, event);
235}
236
237
238void luaT_adjustvarargs (lua_State *L, int nfixparams, CallInfo *ci,
239 const Proto *p) {
240 int i;
241 int actual = cast_int(L->top.p - ci->func.p) - 1; /* number of arguments */
242 int nextra = actual - nfixparams; /* number of extra arguments */
243 ci->u.l.nextraargs = nextra;
244 luaD_checkstack(L, p->maxstacksize + 1);
245 /* copy function to the top of the stack */
246 setobjs2s(L, L->top.p++, ci->func.p);
247 /* move fixed parameters to the top of the stack */
248 for (i = 1; i <= nfixparams; i++) {
249 setobjs2s(L, L->top.p++, ci->func.p + i);
250 setnilvalue(s2v(ci->func.p + i)); /* erase original parameter (for GC) */
251 }
252 ci->func.p += actual + 1;
253 ci->top.p += actual + 1;
254 lua_assert(L->top.p <= ci->top.p && ci->top.p <= L->stack_last.p);
255}
256
257
258void luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted) {
259 int i;
260 int nextra = ci->u.l.nextraargs;
261 if (wanted < 0) {
262 wanted = nextra; /* get all extra arguments available */
263 checkstackGCp(L, nextra, where); /* ensure stack space */
264 L->top.p = where + nextra; /* next instruction will need top */
265 }
266 for (i = 0; i < wanted && i < nextra; i++)
267 setobjs2s(L, where + i, ci->func.p - nextra + i);
268 for (; i < wanted; i++) /* complete required results with nil */
269 setnilvalue(s2v(where + i));
270}
271
diff --git a/vendor/lua-5.4.8/src/ltm.h b/vendor/lua-5.4.8/src/ltm.h
new file mode 100644
index 0000000..73b833c
--- /dev/null
+++ b/vendor/lua-5.4.8/src/ltm.h
@@ -0,0 +1,103 @@
1/*
2** $Id: ltm.h $
3** Tag methods
4** See Copyright Notice in lua.h
5*/
6
7#ifndef ltm_h
8#define ltm_h
9
10
11#include "lobject.h"
12
13
14/*
15* WARNING: if you change the order of this enumeration,
16* grep "ORDER TM" and "ORDER OP"
17*/
18typedef enum {
19 TM_INDEX,
20 TM_NEWINDEX,
21 TM_GC,
22 TM_MODE,
23 TM_LEN,
24 TM_EQ, /* last tag method with fast access */
25 TM_ADD,
26 TM_SUB,
27 TM_MUL,
28 TM_MOD,
29 TM_POW,
30 TM_DIV,
31 TM_IDIV,
32 TM_BAND,
33 TM_BOR,
34 TM_BXOR,
35 TM_SHL,
36 TM_SHR,
37 TM_UNM,
38 TM_BNOT,
39 TM_LT,
40 TM_LE,
41 TM_CONCAT,
42 TM_CALL,
43 TM_CLOSE,
44 TM_N /* number of elements in the enum */
45} TMS;
46
47
48/*
49** Mask with 1 in all fast-access methods. A 1 in any of these bits
50** in the flag of a (meta)table means the metatable does not have the
51** corresponding metamethod field. (Bit 7 of the flag is used for
52** 'isrealasize'.)
53*/
54#define maskflags (~(~0u << (TM_EQ + 1)))
55
56
57/*
58** Test whether there is no tagmethod.
59** (Because tagmethods use raw accesses, the result may be an "empty" nil.)
60*/
61#define notm(tm) ttisnil(tm)
62
63
64#define gfasttm(g,et,e) ((et) == NULL ? NULL : \
65 ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e]))
66
67#define fasttm(l,et,e) gfasttm(G(l), et, e)
68
69#define ttypename(x) luaT_typenames_[(x) + 1]
70
71LUAI_DDEC(const char *const luaT_typenames_[LUA_TOTALTYPES];)
72
73
74LUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o);
75
76LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);
77LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o,
78 TMS event);
79LUAI_FUNC void luaT_init (lua_State *L);
80
81LUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,
82 const TValue *p2, const TValue *p3);
83LUAI_FUNC void luaT_callTMres (lua_State *L, const TValue *f,
84 const TValue *p1, const TValue *p2, StkId p3);
85LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
86 StkId res, TMS event);
87LUAI_FUNC void luaT_tryconcatTM (lua_State *L);
88LUAI_FUNC void luaT_trybinassocTM (lua_State *L, const TValue *p1,
89 const TValue *p2, int inv, StkId res, TMS event);
90LUAI_FUNC void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2,
91 int inv, StkId res, TMS event);
92LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1,
93 const TValue *p2, TMS event);
94LUAI_FUNC int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2,
95 int inv, int isfloat, TMS event);
96
97LUAI_FUNC void luaT_adjustvarargs (lua_State *L, int nfixparams,
98 struct CallInfo *ci, const Proto *p);
99LUAI_FUNC void luaT_getvarargs (lua_State *L, struct CallInfo *ci,
100 StkId where, int wanted);
101
102
103#endif
diff --git a/vendor/lua-5.4.8/src/lua b/vendor/lua-5.4.8/src/lua
new file mode 100755
index 0000000..b948446
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lua
Binary files differ
diff --git a/vendor/lua-5.4.8/src/lua.c b/vendor/lua-5.4.8/src/lua.c
new file mode 100644
index 0000000..4a90e55
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lua.c
@@ -0,0 +1,687 @@
1/*
2** $Id: lua.c $
3** Lua stand-alone interpreter
4** See Copyright Notice in lua.h
5*/
6
7#define lua_c
8
9#include "lprefix.h"
10
11
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15
16#include <signal.h>
17
18#include "lua.h"
19
20#include "lauxlib.h"
21#include "lualib.h"
22
23
24#if !defined(LUA_PROGNAME)
25#define LUA_PROGNAME "lua"
26#endif
27
28#if !defined(LUA_INIT_VAR)
29#define LUA_INIT_VAR "LUA_INIT"
30#endif
31
32#define LUA_INITVARVERSION LUA_INIT_VAR LUA_VERSUFFIX
33
34
35static lua_State *globalL = NULL;
36
37static const char *progname = LUA_PROGNAME;
38
39
40#if defined(LUA_USE_POSIX) /* { */
41
42/*
43** Use 'sigaction' when available.
44*/
45static void setsignal (int sig, void (*handler)(int)) {
46 struct sigaction sa;
47 sa.sa_handler = handler;
48 sa.sa_flags = 0;
49 sigemptyset(&sa.sa_mask); /* do not mask any signal */
50 sigaction(sig, &sa, NULL);
51}
52
53#else /* }{ */
54
55#define setsignal signal
56
57#endif /* } */
58
59
60/*
61** Hook set by signal function to stop the interpreter.
62*/
63static void lstop (lua_State *L, lua_Debug *ar) {
64 (void)ar; /* unused arg. */
65 lua_sethook(L, NULL, 0, 0); /* reset hook */
66 luaL_error(L, "interrupted!");
67}
68
69
70/*
71** Function to be called at a C signal. Because a C signal cannot
72** just change a Lua state (as there is no proper synchronization),
73** this function only sets a hook that, when called, will stop the
74** interpreter.
75*/
76static void laction (int i) {
77 int flag = LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT;
78 setsignal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
79 lua_sethook(globalL, lstop, flag, 1);
80}
81
82
83static void print_usage (const char *badoption) {
84 lua_writestringerror("%s: ", progname);
85 if (badoption[1] == 'e' || badoption[1] == 'l')
86 lua_writestringerror("'%s' needs argument\n", badoption);
87 else
88 lua_writestringerror("unrecognized option '%s'\n", badoption);
89 lua_writestringerror(
90 "usage: %s [options] [script [args]]\n"
91 "Available options are:\n"
92 " -e stat execute string 'stat'\n"
93 " -i enter interactive mode after executing 'script'\n"
94 " -l mod require library 'mod' into global 'mod'\n"
95 " -l g=mod require library 'mod' into global 'g'\n"
96 " -v show version information\n"
97 " -E ignore environment variables\n"
98 " -W turn warnings on\n"
99 " -- stop handling options\n"
100 " - stop handling options and execute stdin\n"
101 ,
102 progname);
103}
104
105
106/*
107** Prints an error message, adding the program name in front of it
108** (if present)
109*/
110static void l_message (const char *pname, const char *msg) {
111 if (pname) lua_writestringerror("%s: ", pname);
112 lua_writestringerror("%s\n", msg);
113}
114
115
116/*
117** Check whether 'status' is not OK and, if so, prints the error
118** message on the top of the stack.
119*/
120static int report (lua_State *L, int status) {
121 if (status != LUA_OK) {
122 const char *msg = lua_tostring(L, -1);
123 if (msg == NULL)
124 msg = "(error message not a string)";
125 l_message(progname, msg);
126 lua_pop(L, 1); /* remove message */
127 }
128 return status;
129}
130
131
132/*
133** Message handler used to run all chunks
134*/
135static int msghandler (lua_State *L) {
136 const char *msg = lua_tostring(L, 1);
137 if (msg == NULL) { /* is error object not a string? */
138 if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */
139 lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */
140 return 1; /* that is the message */
141 else
142 msg = lua_pushfstring(L, "(error object is a %s value)",
143 luaL_typename(L, 1));
144 }
145 luaL_traceback(L, L, msg, 1); /* append a standard traceback */
146 return 1; /* return the traceback */
147}
148
149
150/*
151** Interface to 'lua_pcall', which sets appropriate message function
152** and C-signal handler. Used to run all chunks.
153*/
154static int docall (lua_State *L, int narg, int nres) {
155 int status;
156 int base = lua_gettop(L) - narg; /* function index */
157 lua_pushcfunction(L, msghandler); /* push message handler */
158 lua_insert(L, base); /* put it under function and args */
159 globalL = L; /* to be available to 'laction' */
160 setsignal(SIGINT, laction); /* set C-signal handler */
161 status = lua_pcall(L, narg, nres, base);
162 setsignal(SIGINT, SIG_DFL); /* reset C-signal handler */
163 lua_remove(L, base); /* remove message handler from the stack */
164 return status;
165}
166
167
168static void print_version (void) {
169 lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
170 lua_writeline();
171}
172
173
174/*
175** Create the 'arg' table, which stores all arguments from the
176** command line ('argv'). It should be aligned so that, at index 0,
177** it has 'argv[script]', which is the script name. The arguments
178** to the script (everything after 'script') go to positive indices;
179** other arguments (before the script name) go to negative indices.
180** If there is no script name, assume interpreter's name as base.
181** (If there is no interpreter's name either, 'script' is -1, so
182** table sizes are zero.)
183*/
184static void createargtable (lua_State *L, char **argv, int argc, int script) {
185 int i, narg;
186 narg = argc - (script + 1); /* number of positive indices */
187 lua_createtable(L, narg, script + 1);
188 for (i = 0; i < argc; i++) {
189 lua_pushstring(L, argv[i]);
190 lua_rawseti(L, -2, i - script);
191 }
192 lua_setglobal(L, "arg");
193}
194
195
196static int dochunk (lua_State *L, int status) {
197 if (status == LUA_OK) status = docall(L, 0, 0);
198 return report(L, status);
199}
200
201
202static int dofile (lua_State *L, const char *name) {
203 return dochunk(L, luaL_loadfile(L, name));
204}
205
206
207static int dostring (lua_State *L, const char *s, const char *name) {
208 return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name));
209}
210
211
212/*
213** Receives 'globname[=modname]' and runs 'globname = require(modname)'.
214** If there is no explicit modname and globname contains a '-', cut
215** the suffix after '-' (the "version") to make the global name.
216*/
217static int dolibrary (lua_State *L, char *globname) {
218 int status;
219 char *suffix = NULL;
220 char *modname = strchr(globname, '=');
221 if (modname == NULL) { /* no explicit name? */
222 modname = globname; /* module name is equal to global name */
223 suffix = strchr(modname, *LUA_IGMARK); /* look for a suffix mark */
224 }
225 else {
226 *modname = '\0'; /* global name ends here */
227 modname++; /* module name starts after the '=' */
228 }
229 lua_getglobal(L, "require");
230 lua_pushstring(L, modname);
231 status = docall(L, 1, 1); /* call 'require(modname)' */
232 if (status == LUA_OK) {
233 if (suffix != NULL) /* is there a suffix mark? */
234 *suffix = '\0'; /* remove suffix from global name */
235 lua_setglobal(L, globname); /* globname = require(modname) */
236 }
237 return report(L, status);
238}
239
240
241/*
242** Push on the stack the contents of table 'arg' from 1 to #arg
243*/
244static int pushargs (lua_State *L) {
245 int i, n;
246 if (lua_getglobal(L, "arg") != LUA_TTABLE)
247 luaL_error(L, "'arg' is not a table");
248 n = (int)luaL_len(L, -1);
249 luaL_checkstack(L, n + 3, "too many arguments to script");
250 for (i = 1; i <= n; i++)
251 lua_rawgeti(L, -i, i);
252 lua_remove(L, -i); /* remove table from the stack */
253 return n;
254}
255
256
257static int handle_script (lua_State *L, char **argv) {
258 int status;
259 const char *fname = argv[0];
260 if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0)
261 fname = NULL; /* stdin */
262 status = luaL_loadfile(L, fname);
263 if (status == LUA_OK) {
264 int n = pushargs(L); /* push arguments to script */
265 status = docall(L, n, LUA_MULTRET);
266 }
267 return report(L, status);
268}
269
270
271/* bits of various argument indicators in 'args' */
272#define has_error 1 /* bad option */
273#define has_i 2 /* -i */
274#define has_v 4 /* -v */
275#define has_e 8 /* -e */
276#define has_E 16 /* -E */
277
278
279/*
280** Traverses all arguments from 'argv', returning a mask with those
281** needed before running any Lua code or an error code if it finds any
282** invalid argument. In case of error, 'first' is the index of the bad
283** argument. Otherwise, 'first' is -1 if there is no program name,
284** 0 if there is no script name, or the index of the script name.
285*/
286static int collectargs (char **argv, int *first) {
287 int args = 0;
288 int i;
289 if (argv[0] != NULL) { /* is there a program name? */
290 if (argv[0][0]) /* not empty? */
291 progname = argv[0]; /* save it */
292 }
293 else { /* no program name */
294 *first = -1;
295 return 0;
296 }
297 for (i = 1; argv[i] != NULL; i++) { /* handle arguments */
298 *first = i;
299 if (argv[i][0] != '-') /* not an option? */
300 return args; /* stop handling options */
301 switch (argv[i][1]) { /* else check option */
302 case '-': /* '--' */
303 if (argv[i][2] != '\0') /* extra characters after '--'? */
304 return has_error; /* invalid option */
305 *first = i + 1;
306 return args;
307 case '\0': /* '-' */
308 return args; /* script "name" is '-' */
309 case 'E':
310 if (argv[i][2] != '\0') /* extra characters? */
311 return has_error; /* invalid option */
312 args |= has_E;
313 break;
314 case 'W':
315 if (argv[i][2] != '\0') /* extra characters? */
316 return has_error; /* invalid option */
317 break;
318 case 'i':
319 args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */
320 case 'v':
321 if (argv[i][2] != '\0') /* extra characters? */
322 return has_error; /* invalid option */
323 args |= has_v;
324 break;
325 case 'e':
326 args |= has_e; /* FALLTHROUGH */
327 case 'l': /* both options need an argument */
328 if (argv[i][2] == '\0') { /* no concatenated argument? */
329 i++; /* try next 'argv' */
330 if (argv[i] == NULL || argv[i][0] == '-')
331 return has_error; /* no next argument or it is another option */
332 }
333 break;
334 default: /* invalid option */
335 return has_error;
336 }
337 }
338 *first = 0; /* no script name */
339 return args;
340}
341
342
343/*
344** Processes options 'e' and 'l', which involve running Lua code, and
345** 'W', which also affects the state.
346** Returns 0 if some code raises an error.
347*/
348static int runargs (lua_State *L, char **argv, int n) {
349 int i;
350 for (i = 1; i < n; i++) {
351 int option = argv[i][1];
352 lua_assert(argv[i][0] == '-'); /* already checked */
353 switch (option) {
354 case 'e': case 'l': {
355 int status;
356 char *extra = argv[i] + 2; /* both options need an argument */
357 if (*extra == '\0') extra = argv[++i];
358 lua_assert(extra != NULL);
359 status = (option == 'e')
360 ? dostring(L, extra, "=(command line)")
361 : dolibrary(L, extra);
362 if (status != LUA_OK) return 0;
363 break;
364 }
365 case 'W':
366 lua_warning(L, "@on", 0); /* warnings on */
367 break;
368 }
369 }
370 return 1;
371}
372
373
374static int handle_luainit (lua_State *L) {
375 const char *name = "=" LUA_INITVARVERSION;
376 const char *init = getenv(name + 1);
377 if (init == NULL) {
378 name = "=" LUA_INIT_VAR;
379 init = getenv(name + 1); /* try alternative name */
380 }
381 if (init == NULL) return LUA_OK;
382 else if (init[0] == '@')
383 return dofile(L, init+1);
384 else
385 return dostring(L, init, name);
386}
387
388
389/*
390** {==================================================================
391** Read-Eval-Print Loop (REPL)
392** ===================================================================
393*/
394
395#if !defined(LUA_PROMPT)
396#define LUA_PROMPT "> "
397#define LUA_PROMPT2 ">> "
398#endif
399
400#if !defined(LUA_MAXINPUT)
401#define LUA_MAXINPUT 512
402#endif
403
404
405/*
406** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
407** is, whether we're running lua interactively).
408*/
409#if !defined(lua_stdin_is_tty) /* { */
410
411#if defined(LUA_USE_POSIX) /* { */
412
413#include <unistd.h>
414#define lua_stdin_is_tty() isatty(0)
415
416#elif defined(LUA_USE_WINDOWS) /* }{ */
417
418#include <io.h>
419#include <windows.h>
420
421#define lua_stdin_is_tty() _isatty(_fileno(stdin))
422
423#else /* }{ */
424
425/* ISO C definition */
426#define lua_stdin_is_tty() 1 /* assume stdin is a tty */
427
428#endif /* } */
429
430#endif /* } */
431
432
433/*
434** lua_readline defines how to show a prompt and then read a line from
435** the standard input.
436** lua_saveline defines how to "save" a read line in a "history".
437** lua_freeline defines how to free a line read by lua_readline.
438*/
439#if !defined(lua_readline) /* { */
440
441#if defined(LUA_USE_READLINE) /* { */
442
443#include <readline/readline.h>
444#include <readline/history.h>
445#define lua_initreadline(L) ((void)L, rl_readline_name="lua")
446#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
447#define lua_saveline(L,line) ((void)L, add_history(line))
448#define lua_freeline(L,b) ((void)L, free(b))
449
450#else /* }{ */
451
452#define lua_initreadline(L) ((void)L)
453#define lua_readline(L,b,p) \
454 ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
455 fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */
456#define lua_saveline(L,line) { (void)L; (void)line; }
457#define lua_freeline(L,b) { (void)L; (void)b; }
458
459#endif /* } */
460
461#endif /* } */
462
463
464/*
465** Return the string to be used as a prompt by the interpreter. Leave
466** the string (or nil, if using the default value) on the stack, to keep
467** it anchored.
468*/
469static const char *get_prompt (lua_State *L, int firstline) {
470 if (lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2") == LUA_TNIL)
471 return (firstline ? LUA_PROMPT : LUA_PROMPT2); /* use the default */
472 else { /* apply 'tostring' over the value */
473 const char *p = luaL_tolstring(L, -1, NULL);
474 lua_remove(L, -2); /* remove original value */
475 return p;
476 }
477}
478
479/* mark in error messages for incomplete statements */
480#define EOFMARK "<eof>"
481#define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
482
483
484/*
485** Check whether 'status' signals a syntax error and the error
486** message at the top of the stack ends with the above mark for
487** incomplete statements.
488*/
489static int incomplete (lua_State *L, int status) {
490 if (status == LUA_ERRSYNTAX) {
491 size_t lmsg;
492 const char *msg = lua_tolstring(L, -1, &lmsg);
493 if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0)
494 return 1;
495 }
496 return 0; /* else... */
497}
498
499
500/*
501** Prompt the user, read a line, and push it into the Lua stack.
502*/
503static int pushline (lua_State *L, int firstline) {
504 char buffer[LUA_MAXINPUT];
505 char *b = buffer;
506 size_t l;
507 const char *prmt = get_prompt(L, firstline);
508 int readstatus = lua_readline(L, b, prmt);
509 lua_pop(L, 1); /* remove prompt */
510 if (readstatus == 0)
511 return 0; /* no input */
512 l = strlen(b);
513 if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
514 b[--l] = '\0'; /* remove it */
515 if (firstline && b[0] == '=') /* for compatibility with 5.2, ... */
516 lua_pushfstring(L, "return %s", b + 1); /* change '=' to 'return' */
517 else
518 lua_pushlstring(L, b, l);
519 lua_freeline(L, b);
520 return 1;
521}
522
523
524/*
525** Try to compile line on the stack as 'return <line>;'; on return, stack
526** has either compiled chunk or original line (if compilation failed).
527*/
528static int addreturn (lua_State *L) {
529 const char *line = lua_tostring(L, -1); /* original line */
530 const char *retline = lua_pushfstring(L, "return %s;", line);
531 int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin");
532 if (status == LUA_OK) {
533 lua_remove(L, -2); /* remove modified line */
534 if (line[0] != '\0') /* non empty? */
535 lua_saveline(L, line); /* keep history */
536 }
537 else
538 lua_pop(L, 2); /* pop result from 'luaL_loadbuffer' and modified line */
539 return status;
540}
541
542
543/*
544** Read multiple lines until a complete Lua statement
545*/
546static int multiline (lua_State *L) {
547 for (;;) { /* repeat until gets a complete statement */
548 size_t len;
549 const char *line = lua_tolstring(L, 1, &len); /* get what it has */
550 int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */
551 if (!incomplete(L, status) || !pushline(L, 0)) {
552 lua_saveline(L, line); /* keep history */
553 return status; /* should not or cannot try to add continuation line */
554 }
555 lua_remove(L, -2); /* remove error message (from incomplete line) */
556 lua_pushliteral(L, "\n"); /* add newline... */
557 lua_insert(L, -2); /* ...between the two lines */
558 lua_concat(L, 3); /* join them */
559 }
560}
561
562
563/*
564** Read a line and try to load (compile) it first as an expression (by
565** adding "return " in front of it) and second as a statement. Return
566** the final status of load/call with the resulting function (if any)
567** in the top of the stack.
568*/
569static int loadline (lua_State *L) {
570 int status;
571 lua_settop(L, 0);
572 if (!pushline(L, 1))
573 return -1; /* no input */
574 if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */
575 status = multiline(L); /* try as command, maybe with continuation lines */
576 lua_remove(L, 1); /* remove line from the stack */
577 lua_assert(lua_gettop(L) == 1);
578 return status;
579}
580
581
582/*
583** Prints (calling the Lua 'print' function) any values on the stack
584*/
585static void l_print (lua_State *L) {
586 int n = lua_gettop(L);
587 if (n > 0) { /* any result to be printed? */
588 luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
589 lua_getglobal(L, "print");
590 lua_insert(L, 1);
591 if (lua_pcall(L, n, 0, 0) != LUA_OK)
592 l_message(progname, lua_pushfstring(L, "error calling 'print' (%s)",
593 lua_tostring(L, -1)));
594 }
595}
596
597
598/*
599** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and
600** print any results.
601*/
602static void doREPL (lua_State *L) {
603 int status;
604 const char *oldprogname = progname;
605 progname = NULL; /* no 'progname' on errors in interactive mode */
606 lua_initreadline(L);
607 while ((status = loadline(L)) != -1) {
608 if (status == LUA_OK)
609 status = docall(L, 0, LUA_MULTRET);
610 if (status == LUA_OK) l_print(L);
611 else report(L, status);
612 }
613 lua_settop(L, 0); /* clear stack */
614 lua_writeline();
615 progname = oldprogname;
616}
617
618/* }================================================================== */
619
620
621/*
622** Main body of stand-alone interpreter (to be called in protected mode).
623** Reads the options and handles them all.
624*/
625static int pmain (lua_State *L) {
626 int argc = (int)lua_tointeger(L, 1);
627 char **argv = (char **)lua_touserdata(L, 2);
628 int script;
629 int args = collectargs(argv, &script);
630 int optlim = (script > 0) ? script : argc; /* first argv not an option */
631 luaL_checkversion(L); /* check that interpreter has correct version */
632 if (args == has_error) { /* bad arg? */
633 print_usage(argv[script]); /* 'script' has index of bad arg. */
634 return 0;
635 }
636 if (args & has_v) /* option '-v'? */
637 print_version();
638 if (args & has_E) { /* option '-E'? */
639 lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */
640 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
641 }
642 luaL_openlibs(L); /* open standard libraries */
643 createargtable(L, argv, argc, script); /* create table 'arg' */
644 lua_gc(L, LUA_GCRESTART); /* start GC... */
645 lua_gc(L, LUA_GCGEN, 0, 0); /* ...in generational mode */
646 if (!(args & has_E)) { /* no option '-E'? */
647 if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */
648 return 0; /* error running LUA_INIT */
649 }
650 if (!runargs(L, argv, optlim)) /* execute arguments -e and -l */
651 return 0; /* something failed */
652 if (script > 0) { /* execute main script (if there is one) */
653 if (handle_script(L, argv + script) != LUA_OK)
654 return 0; /* interrupt in case of error */
655 }
656 if (args & has_i) /* -i option? */
657 doREPL(L); /* do read-eval-print loop */
658 else if (script < 1 && !(args & (has_e | has_v))) { /* no active option? */
659 if (lua_stdin_is_tty()) { /* running in interactive mode? */
660 print_version();
661 doREPL(L); /* do read-eval-print loop */
662 }
663 else dofile(L, NULL); /* executes stdin as a file */
664 }
665 lua_pushboolean(L, 1); /* signal no errors */
666 return 1;
667}
668
669
670int main (int argc, char **argv) {
671 int status, result;
672 lua_State *L = luaL_newstate(); /* create state */
673 if (L == NULL) {
674 l_message(argv[0], "cannot create state: not enough memory");
675 return EXIT_FAILURE;
676 }
677 lua_gc(L, LUA_GCSTOP); /* stop GC while building state */
678 lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */
679 lua_pushinteger(L, argc); /* 1st argument */
680 lua_pushlightuserdata(L, argv); /* 2nd argument */
681 status = lua_pcall(L, 2, 1, 0); /* do the call */
682 result = lua_toboolean(L, -1); /* get result */
683 report(L, status);
684 lua_close(L);
685 return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
686}
687
diff --git a/vendor/lua-5.4.8/src/lua.h b/vendor/lua-5.4.8/src/lua.h
new file mode 100644
index 0000000..f3ea590
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lua.h
@@ -0,0 +1,523 @@
1/*
2** $Id: lua.h $
3** Lua - A Scripting Language
4** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
5** See Copyright Notice at the end of this file
6*/
7
8
9#ifndef lua_h
10#define lua_h
11
12#include <stdarg.h>
13#include <stddef.h>
14
15
16#include "luaconf.h"
17
18
19#define LUA_VERSION_MAJOR "5"
20#define LUA_VERSION_MINOR "4"
21#define LUA_VERSION_RELEASE "8"
22
23#define LUA_VERSION_NUM 504
24#define LUA_VERSION_RELEASE_NUM (LUA_VERSION_NUM * 100 + 8)
25
26#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
27#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
28#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2025 Lua.org, PUC-Rio"
29#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
30
31
32/* mark for precompiled code ('<esc>Lua') */
33#define LUA_SIGNATURE "\x1bLua"
34
35/* option for multiple returns in 'lua_pcall' and 'lua_call' */
36#define LUA_MULTRET (-1)
37
38
39/*
40** Pseudo-indices
41** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty
42** space after that to help overflow detection)
43*/
44#define LUA_REGISTRYINDEX (-LUAI_MAXSTACK - 1000)
45#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i))
46
47
48/* thread status */
49#define LUA_OK 0
50#define LUA_YIELD 1
51#define LUA_ERRRUN 2
52#define LUA_ERRSYNTAX 3
53#define LUA_ERRMEM 4
54#define LUA_ERRERR 5
55
56
57typedef struct lua_State lua_State;
58
59
60/*
61** basic types
62*/
63#define LUA_TNONE (-1)
64
65#define LUA_TNIL 0
66#define LUA_TBOOLEAN 1
67#define LUA_TLIGHTUSERDATA 2
68#define LUA_TNUMBER 3
69#define LUA_TSTRING 4
70#define LUA_TTABLE 5
71#define LUA_TFUNCTION 6
72#define LUA_TUSERDATA 7
73#define LUA_TTHREAD 8
74
75#define LUA_NUMTYPES 9
76
77
78
79/* minimum Lua stack available to a C function */
80#define LUA_MINSTACK 20
81
82
83/* predefined values in the registry */
84#define LUA_RIDX_MAINTHREAD 1
85#define LUA_RIDX_GLOBALS 2
86#define LUA_RIDX_LAST LUA_RIDX_GLOBALS
87
88
89/* type of numbers in Lua */
90typedef LUA_NUMBER lua_Number;
91
92
93/* type for integer functions */
94typedef LUA_INTEGER lua_Integer;
95
96/* unsigned integer type */
97typedef LUA_UNSIGNED lua_Unsigned;
98
99/* type for continuation-function contexts */
100typedef LUA_KCONTEXT lua_KContext;
101
102
103/*
104** Type for C functions registered with Lua
105*/
106typedef int (*lua_CFunction) (lua_State *L);
107
108/*
109** Type for continuation functions
110*/
111typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);
112
113
114/*
115** Type for functions that read/write blocks when loading/dumping Lua chunks
116*/
117typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
118
119typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud);
120
121
122/*
123** Type for memory-allocation functions
124*/
125typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
126
127
128/*
129** Type for warning functions
130*/
131typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);
132
133
134/*
135** Type used by the debug API to collect debug information
136*/
137typedef struct lua_Debug lua_Debug;
138
139
140/*
141** Functions to be called by the debugger in specific events
142*/
143typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
144
145
146/*
147** generic extra include file
148*/
149#if defined(LUA_USER_H)
150#include LUA_USER_H
151#endif
152
153
154/*
155** RCS ident string
156*/
157extern const char lua_ident[];
158
159
160/*
161** state manipulation
162*/
163LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud);
164LUA_API void (lua_close) (lua_State *L);
165LUA_API lua_State *(lua_newthread) (lua_State *L);
166LUA_API int (lua_closethread) (lua_State *L, lua_State *from);
167LUA_API int (lua_resetthread) (lua_State *L); /* Deprecated! */
168
169LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf);
170
171
172LUA_API lua_Number (lua_version) (lua_State *L);
173
174
175/*
176** basic stack manipulation
177*/
178LUA_API int (lua_absindex) (lua_State *L, int idx);
179LUA_API int (lua_gettop) (lua_State *L);
180LUA_API void (lua_settop) (lua_State *L, int idx);
181LUA_API void (lua_pushvalue) (lua_State *L, int idx);
182LUA_API void (lua_rotate) (lua_State *L, int idx, int n);
183LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx);
184LUA_API int (lua_checkstack) (lua_State *L, int n);
185
186LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n);
187
188
189/*
190** access functions (stack -> C)
191*/
192
193LUA_API int (lua_isnumber) (lua_State *L, int idx);
194LUA_API int (lua_isstring) (lua_State *L, int idx);
195LUA_API int (lua_iscfunction) (lua_State *L, int idx);
196LUA_API int (lua_isinteger) (lua_State *L, int idx);
197LUA_API int (lua_isuserdata) (lua_State *L, int idx);
198LUA_API int (lua_type) (lua_State *L, int idx);
199LUA_API const char *(lua_typename) (lua_State *L, int tp);
200
201LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum);
202LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum);
203LUA_API int (lua_toboolean) (lua_State *L, int idx);
204LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len);
205LUA_API lua_Unsigned (lua_rawlen) (lua_State *L, int idx);
206LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx);
207LUA_API void *(lua_touserdata) (lua_State *L, int idx);
208LUA_API lua_State *(lua_tothread) (lua_State *L, int idx);
209LUA_API const void *(lua_topointer) (lua_State *L, int idx);
210
211
212/*
213** Comparison and arithmetic functions
214*/
215
216#define LUA_OPADD 0 /* ORDER TM, ORDER OP */
217#define LUA_OPSUB 1
218#define LUA_OPMUL 2
219#define LUA_OPMOD 3
220#define LUA_OPPOW 4
221#define LUA_OPDIV 5
222#define LUA_OPIDIV 6
223#define LUA_OPBAND 7
224#define LUA_OPBOR 8
225#define LUA_OPBXOR 9
226#define LUA_OPSHL 10
227#define LUA_OPSHR 11
228#define LUA_OPUNM 12
229#define LUA_OPBNOT 13
230
231LUA_API void (lua_arith) (lua_State *L, int op);
232
233#define LUA_OPEQ 0
234#define LUA_OPLT 1
235#define LUA_OPLE 2
236
237LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2);
238LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op);
239
240
241/*
242** push functions (C -> stack)
243*/
244LUA_API void (lua_pushnil) (lua_State *L);
245LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n);
246LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n);
247LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len);
248LUA_API const char *(lua_pushstring) (lua_State *L, const char *s);
249LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt,
250 va_list argp);
251LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...);
252LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n);
253LUA_API void (lua_pushboolean) (lua_State *L, int b);
254LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p);
255LUA_API int (lua_pushthread) (lua_State *L);
256
257
258/*
259** get functions (Lua -> stack)
260*/
261LUA_API int (lua_getglobal) (lua_State *L, const char *name);
262LUA_API int (lua_gettable) (lua_State *L, int idx);
263LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k);
264LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n);
265LUA_API int (lua_rawget) (lua_State *L, int idx);
266LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n);
267LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p);
268
269LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec);
270LUA_API void *(lua_newuserdatauv) (lua_State *L, size_t sz, int nuvalue);
271LUA_API int (lua_getmetatable) (lua_State *L, int objindex);
272LUA_API int (lua_getiuservalue) (lua_State *L, int idx, int n);
273
274
275/*
276** set functions (stack -> Lua)
277*/
278LUA_API void (lua_setglobal) (lua_State *L, const char *name);
279LUA_API void (lua_settable) (lua_State *L, int idx);
280LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k);
281LUA_API void (lua_seti) (lua_State *L, int idx, lua_Integer n);
282LUA_API void (lua_rawset) (lua_State *L, int idx);
283LUA_API void (lua_rawseti) (lua_State *L, int idx, lua_Integer n);
284LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p);
285LUA_API int (lua_setmetatable) (lua_State *L, int objindex);
286LUA_API int (lua_setiuservalue) (lua_State *L, int idx, int n);
287
288
289/*
290** 'load' and 'call' functions (load and run Lua code)
291*/
292LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults,
293 lua_KContext ctx, lua_KFunction k);
294#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL)
295
296LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
297 lua_KContext ctx, lua_KFunction k);
298#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL)
299
300LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt,
301 const char *chunkname, const char *mode);
302
303LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip);
304
305
306/*
307** coroutine functions
308*/
309LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx,
310 lua_KFunction k);
311LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg,
312 int *nres);
313LUA_API int (lua_status) (lua_State *L);
314LUA_API int (lua_isyieldable) (lua_State *L);
315
316#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL)
317
318
319/*
320** Warning-related functions
321*/
322LUA_API void (lua_setwarnf) (lua_State *L, lua_WarnFunction f, void *ud);
323LUA_API void (lua_warning) (lua_State *L, const char *msg, int tocont);
324
325
326/*
327** garbage-collection function and options
328*/
329
330#define LUA_GCSTOP 0
331#define LUA_GCRESTART 1
332#define LUA_GCCOLLECT 2
333#define LUA_GCCOUNT 3
334#define LUA_GCCOUNTB 4
335#define LUA_GCSTEP 5
336#define LUA_GCSETPAUSE 6
337#define LUA_GCSETSTEPMUL 7
338#define LUA_GCISRUNNING 9
339#define LUA_GCGEN 10
340#define LUA_GCINC 11
341
342LUA_API int (lua_gc) (lua_State *L, int what, ...);
343
344
345/*
346** miscellaneous functions
347*/
348
349LUA_API int (lua_error) (lua_State *L);
350
351LUA_API int (lua_next) (lua_State *L, int idx);
352
353LUA_API void (lua_concat) (lua_State *L, int n);
354LUA_API void (lua_len) (lua_State *L, int idx);
355
356LUA_API size_t (lua_stringtonumber) (lua_State *L, const char *s);
357
358LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);
359LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);
360
361LUA_API void (lua_toclose) (lua_State *L, int idx);
362LUA_API void (lua_closeslot) (lua_State *L, int idx);
363
364
365/*
366** {==============================================================
367** some useful macros
368** ===============================================================
369*/
370
371#define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE))
372
373#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL)
374#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL)
375
376#define lua_pop(L,n) lua_settop(L, -(n)-1)
377
378#define lua_newtable(L) lua_createtable(L, 0, 0)
379
380#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))
381
382#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0)
383
384#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION)
385#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE)
386#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA)
387#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL)
388#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN)
389#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD)
390#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE)
391#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0)
392
393#define lua_pushliteral(L, s) lua_pushstring(L, "" s)
394
395#define lua_pushglobaltable(L) \
396 ((void)lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS))
397
398#define lua_tostring(L,i) lua_tolstring(L, (i), NULL)
399
400
401#define lua_insert(L,idx) lua_rotate(L, (idx), 1)
402
403#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1))
404
405#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1))
406
407/* }============================================================== */
408
409
410/*
411** {==============================================================
412** compatibility macros
413** ===============================================================
414*/
415#if defined(LUA_COMPAT_APIINTCASTS)
416
417#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n))
418#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is))
419#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL)
420
421#endif
422
423#define lua_newuserdata(L,s) lua_newuserdatauv(L,s,1)
424#define lua_getuservalue(L,idx) lua_getiuservalue(L,idx,1)
425#define lua_setuservalue(L,idx) lua_setiuservalue(L,idx,1)
426
427#define LUA_NUMTAGS LUA_NUMTYPES
428
429/* }============================================================== */
430
431/*
432** {======================================================================
433** Debug API
434** =======================================================================
435*/
436
437
438/*
439** Event codes
440*/
441#define LUA_HOOKCALL 0
442#define LUA_HOOKRET 1
443#define LUA_HOOKLINE 2
444#define LUA_HOOKCOUNT 3
445#define LUA_HOOKTAILCALL 4
446
447
448/*
449** Event masks
450*/
451#define LUA_MASKCALL (1 << LUA_HOOKCALL)
452#define LUA_MASKRET (1 << LUA_HOOKRET)
453#define LUA_MASKLINE (1 << LUA_HOOKLINE)
454#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT)
455
456
457LUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar);
458LUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar);
459LUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n);
460LUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n);
461LUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n);
462LUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n);
463
464LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n);
465LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1,
466 int fidx2, int n2);
467
468LUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count);
469LUA_API lua_Hook (lua_gethook) (lua_State *L);
470LUA_API int (lua_gethookmask) (lua_State *L);
471LUA_API int (lua_gethookcount) (lua_State *L);
472
473LUA_API int (lua_setcstacklimit) (lua_State *L, unsigned int limit);
474
475struct lua_Debug {
476 int event;
477 const char *name; /* (n) */
478 const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */
479 const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */
480 const char *source; /* (S) */
481 size_t srclen; /* (S) */
482 int currentline; /* (l) */
483 int linedefined; /* (S) */
484 int lastlinedefined; /* (S) */
485 unsigned char nups; /* (u) number of upvalues */
486 unsigned char nparams;/* (u) number of parameters */
487 char isvararg; /* (u) */
488 char istailcall; /* (t) */
489 unsigned short ftransfer; /* (r) index of first value transferred */
490 unsigned short ntransfer; /* (r) number of transferred values */
491 char short_src[LUA_IDSIZE]; /* (S) */
492 /* private part */
493 struct CallInfo *i_ci; /* active function */
494};
495
496/* }====================================================================== */
497
498
499/******************************************************************************
500* Copyright (C) 1994-2025 Lua.org, PUC-Rio.
501*
502* Permission is hereby granted, free of charge, to any person obtaining
503* a copy of this software and associated documentation files (the
504* "Software"), to deal in the Software without restriction, including
505* without limitation the rights to use, copy, modify, merge, publish,
506* distribute, sublicense, and/or sell copies of the Software, and to
507* permit persons to whom the Software is furnished to do so, subject to
508* the following conditions:
509*
510* The above copyright notice and this permission notice shall be
511* included in all copies or substantial portions of the Software.
512*
513* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
514* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
515* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
516* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
517* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
518* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
519* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
520******************************************************************************/
521
522
523#endif
diff --git a/vendor/lua-5.4.8/src/lua.hpp b/vendor/lua-5.4.8/src/lua.hpp
new file mode 100644
index 0000000..ec417f5
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lua.hpp
@@ -0,0 +1,9 @@
1// lua.hpp
2// Lua header files for C++
3// <<extern "C">> not supplied automatically because Lua also compiles as C++
4
5extern "C" {
6#include "lua.h"
7#include "lualib.h"
8#include "lauxlib.h"
9}
diff --git a/vendor/lua-5.4.8/src/luac b/vendor/lua-5.4.8/src/luac
new file mode 100755
index 0000000..bed1c2f
--- /dev/null
+++ b/vendor/lua-5.4.8/src/luac
Binary files differ
diff --git a/vendor/lua-5.4.8/src/luac.c b/vendor/lua-5.4.8/src/luac.c
new file mode 100644
index 0000000..5f4a141
--- /dev/null
+++ b/vendor/lua-5.4.8/src/luac.c
@@ -0,0 +1,723 @@
1/*
2** $Id: luac.c $
3** Lua compiler (saves bytecodes to files; also lists bytecodes)
4** See Copyright Notice in lua.h
5*/
6
7#define luac_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12#include <ctype.h>
13#include <errno.h>
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17
18#include "lua.h"
19#include "lauxlib.h"
20
21#include "ldebug.h"
22#include "lobject.h"
23#include "lopcodes.h"
24#include "lopnames.h"
25#include "lstate.h"
26#include "lundump.h"
27
28static void PrintFunction(const Proto* f, int full);
29#define luaU_print PrintFunction
30
31#define PROGNAME "luac" /* default program name */
32#define OUTPUT PROGNAME ".out" /* default output file */
33
34static int listing=0; /* list bytecodes? */
35static int dumping=1; /* dump bytecodes? */
36static int stripping=0; /* strip debug information? */
37static char Output[]={ OUTPUT }; /* default output file name */
38static const char* output=Output; /* actual output file name */
39static const char* progname=PROGNAME; /* actual program name */
40static TString **tmname;
41
42static void fatal(const char* message)
43{
44 fprintf(stderr,"%s: %s\n",progname,message);
45 exit(EXIT_FAILURE);
46}
47
48static void cannot(const char* what)
49{
50 fprintf(stderr,"%s: cannot %s %s: %s\n",progname,what,output,strerror(errno));
51 exit(EXIT_FAILURE);
52}
53
54static void usage(const char* message)
55{
56 if (*message=='-')
57 fprintf(stderr,"%s: unrecognized option '%s'\n",progname,message);
58 else
59 fprintf(stderr,"%s: %s\n",progname,message);
60 fprintf(stderr,
61 "usage: %s [options] [filenames]\n"
62 "Available options are:\n"
63 " -l list (use -l -l for full listing)\n"
64 " -o name output to file 'name' (default is \"%s\")\n"
65 " -p parse only\n"
66 " -s strip debug information\n"
67 " -v show version information\n"
68 " -- stop handling options\n"
69 " - stop handling options and process stdin\n"
70 ,progname,Output);
71 exit(EXIT_FAILURE);
72}
73
74#define IS(s) (strcmp(argv[i],s)==0)
75
76static int doargs(int argc, char* argv[])
77{
78 int i;
79 int version=0;
80 if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0];
81 for (i=1; i<argc; i++)
82 {
83 if (*argv[i]!='-') /* end of options; keep it */
84 break;
85 else if (IS("--")) /* end of options; skip it */
86 {
87 ++i;
88 if (version) ++version;
89 break;
90 }
91 else if (IS("-")) /* end of options; use stdin */
92 break;
93 else if (IS("-l")) /* list */
94 ++listing;
95 else if (IS("-o")) /* output file */
96 {
97 output=argv[++i];
98 if (output==NULL || *output==0 || (*output=='-' && output[1]!=0))
99 usage("'-o' needs argument");
100 if (IS("-")) output=NULL;
101 }
102 else if (IS("-p")) /* parse only */
103 dumping=0;
104 else if (IS("-s")) /* strip debug information */
105 stripping=1;
106 else if (IS("-v")) /* show version */
107 ++version;
108 else /* unknown option */
109 usage(argv[i]);
110 }
111 if (i==argc && (listing || !dumping))
112 {
113 dumping=0;
114 argv[--i]=Output;
115 }
116 if (version)
117 {
118 printf("%s\n",LUA_COPYRIGHT);
119 if (version==argc-1) exit(EXIT_SUCCESS);
120 }
121 return i;
122}
123
124#define FUNCTION "(function()end)();\n"
125
126static const char* reader(lua_State* L, void* ud, size_t* size)
127{
128 UNUSED(L);
129 if ((*(int*)ud)--)
130 {
131 *size=sizeof(FUNCTION)-1;
132 return FUNCTION;
133 }
134 else
135 {
136 *size=0;
137 return NULL;
138 }
139}
140
141#define toproto(L,i) getproto(s2v(L->top.p+(i)))
142
143static const Proto* combine(lua_State* L, int n)
144{
145 if (n==1)
146 return toproto(L,-1);
147 else
148 {
149 Proto* f;
150 int i=n;
151 if (lua_load(L,reader,&i,"=(" PROGNAME ")",NULL)!=LUA_OK) fatal(lua_tostring(L,-1));
152 f=toproto(L,-1);
153 for (i=0; i<n; i++)
154 {
155 f->p[i]=toproto(L,i-n-1);
156 if (f->p[i]->sizeupvalues>0) f->p[i]->upvalues[0].instack=0;
157 }
158 return f;
159 }
160}
161
162static int writer(lua_State* L, const void* p, size_t size, void* u)
163{
164 UNUSED(L);
165 return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0);
166}
167
168static int pmain(lua_State* L)
169{
170 int argc=(int)lua_tointeger(L,1);
171 char** argv=(char**)lua_touserdata(L,2);
172 const Proto* f;
173 int i;
174 tmname=G(L)->tmname;
175 if (!lua_checkstack(L,argc)) fatal("too many input files");
176 for (i=0; i<argc; i++)
177 {
178 const char* filename=IS("-") ? NULL : argv[i];
179 if (luaL_loadfile(L,filename)!=LUA_OK) fatal(lua_tostring(L,-1));
180 }
181 f=combine(L,argc);
182 if (listing) luaU_print(f,listing>1);
183 if (dumping)
184 {
185 FILE* D= (output==NULL) ? stdout : fopen(output,"wb");
186 if (D==NULL) cannot("open");
187 lua_lock(L);
188 luaU_dump(L,f,writer,D,stripping);
189 lua_unlock(L);
190 if (ferror(D)) cannot("write");
191 if (fclose(D)) cannot("close");
192 }
193 return 0;
194}
195
196int main(int argc, char* argv[])
197{
198 lua_State* L;
199 int i=doargs(argc,argv);
200 argc-=i; argv+=i;
201 if (argc<=0) usage("no input files given");
202 L=luaL_newstate();
203 if (L==NULL) fatal("cannot create state: not enough memory");
204 lua_pushcfunction(L,&pmain);
205 lua_pushinteger(L,argc);
206 lua_pushlightuserdata(L,argv);
207 if (lua_pcall(L,2,0,0)!=LUA_OK) fatal(lua_tostring(L,-1));
208 lua_close(L);
209 return EXIT_SUCCESS;
210}
211
212/*
213** print bytecodes
214*/
215
216#define UPVALNAME(x) ((f->upvalues[x].name) ? getstr(f->upvalues[x].name) : "-")
217#define VOID(p) ((const void*)(p))
218#define eventname(i) (getstr(tmname[i]))
219
220static void PrintString(const TString* ts)
221{
222 const char* s=getstr(ts);
223 size_t i,n=tsslen(ts);
224 printf("\"");
225 for (i=0; i<n; i++)
226 {
227 int c=(int)(unsigned char)s[i];
228 switch (c)
229 {
230 case '"':
231 printf("\\\"");
232 break;
233 case '\\':
234 printf("\\\\");
235 break;
236 case '\a':
237 printf("\\a");
238 break;
239 case '\b':
240 printf("\\b");
241 break;
242 case '\f':
243 printf("\\f");
244 break;
245 case '\n':
246 printf("\\n");
247 break;
248 case '\r':
249 printf("\\r");
250 break;
251 case '\t':
252 printf("\\t");
253 break;
254 case '\v':
255 printf("\\v");
256 break;
257 default:
258 if (isprint(c)) printf("%c",c); else printf("\\%03d",c);
259 break;
260 }
261 }
262 printf("\"");
263}
264
265static void PrintType(const Proto* f, int i)
266{
267 const TValue* o=&f->k[i];
268 switch (ttypetag(o))
269 {
270 case LUA_VNIL:
271 printf("N");
272 break;
273 case LUA_VFALSE:
274 case LUA_VTRUE:
275 printf("B");
276 break;
277 case LUA_VNUMFLT:
278 printf("F");
279 break;
280 case LUA_VNUMINT:
281 printf("I");
282 break;
283 case LUA_VSHRSTR:
284 case LUA_VLNGSTR:
285 printf("S");
286 break;
287 default: /* cannot happen */
288 printf("?%d",ttypetag(o));
289 break;
290 }
291 printf("\t");
292}
293
294static void PrintConstant(const Proto* f, int i)
295{
296 const TValue* o=&f->k[i];
297 switch (ttypetag(o))
298 {
299 case LUA_VNIL:
300 printf("nil");
301 break;
302 case LUA_VFALSE:
303 printf("false");
304 break;
305 case LUA_VTRUE:
306 printf("true");
307 break;
308 case LUA_VNUMFLT:
309 {
310 char buff[100];
311 sprintf(buff,LUA_NUMBER_FMT,fltvalue(o));
312 printf("%s",buff);
313 if (buff[strspn(buff,"-0123456789")]=='\0') printf(".0");
314 break;
315 }
316 case LUA_VNUMINT:
317 printf(LUA_INTEGER_FMT,ivalue(o));
318 break;
319 case LUA_VSHRSTR:
320 case LUA_VLNGSTR:
321 PrintString(tsvalue(o));
322 break;
323 default: /* cannot happen */
324 printf("?%d",ttypetag(o));
325 break;
326 }
327}
328
329#define COMMENT "\t; "
330#define EXTRAARG GETARG_Ax(code[pc+1])
331#define EXTRAARGC (EXTRAARG*(MAXARG_C+1))
332#define ISK (isk ? "k" : "")
333
334static void PrintCode(const Proto* f)
335{
336 const Instruction* code=f->code;
337 int pc,n=f->sizecode;
338 for (pc=0; pc<n; pc++)
339 {
340 Instruction i=code[pc];
341 OpCode o=GET_OPCODE(i);
342 int a=GETARG_A(i);
343 int b=GETARG_B(i);
344 int c=GETARG_C(i);
345 int ax=GETARG_Ax(i);
346 int bx=GETARG_Bx(i);
347 int sb=GETARG_sB(i);
348 int sc=GETARG_sC(i);
349 int sbx=GETARG_sBx(i);
350 int isk=GETARG_k(i);
351 int line=luaG_getfuncline(f,pc);
352 printf("\t%d\t",pc+1);
353 if (line>0) printf("[%d]\t",line); else printf("[-]\t");
354 printf("%-9s\t",opnames[o]);
355 switch (o)
356 {
357 case OP_MOVE:
358 printf("%d %d",a,b);
359 break;
360 case OP_LOADI:
361 printf("%d %d",a,sbx);
362 break;
363 case OP_LOADF:
364 printf("%d %d",a,sbx);
365 break;
366 case OP_LOADK:
367 printf("%d %d",a,bx);
368 printf(COMMENT); PrintConstant(f,bx);
369 break;
370 case OP_LOADKX:
371 printf("%d",a);
372 printf(COMMENT); PrintConstant(f,EXTRAARG);
373 break;
374 case OP_LOADFALSE:
375 printf("%d",a);
376 break;
377 case OP_LFALSESKIP:
378 printf("%d",a);
379 break;
380 case OP_LOADTRUE:
381 printf("%d",a);
382 break;
383 case OP_LOADNIL:
384 printf("%d %d",a,b);
385 printf(COMMENT "%d out",b+1);
386 break;
387 case OP_GETUPVAL:
388 printf("%d %d",a,b);
389 printf(COMMENT "%s",UPVALNAME(b));
390 break;
391 case OP_SETUPVAL:
392 printf("%d %d",a,b);
393 printf(COMMENT "%s",UPVALNAME(b));
394 break;
395 case OP_GETTABUP:
396 printf("%d %d %d",a,b,c);
397 printf(COMMENT "%s",UPVALNAME(b));
398 printf(" "); PrintConstant(f,c);
399 break;
400 case OP_GETTABLE:
401 printf("%d %d %d",a,b,c);
402 break;
403 case OP_GETI:
404 printf("%d %d %d",a,b,c);
405 break;
406 case OP_GETFIELD:
407 printf("%d %d %d",a,b,c);
408 printf(COMMENT); PrintConstant(f,c);
409 break;
410 case OP_SETTABUP:
411 printf("%d %d %d%s",a,b,c,ISK);
412 printf(COMMENT "%s",UPVALNAME(a));
413 printf(" "); PrintConstant(f,b);
414 if (isk) { printf(" "); PrintConstant(f,c); }
415 break;
416 case OP_SETTABLE:
417 printf("%d %d %d%s",a,b,c,ISK);
418 if (isk) { printf(COMMENT); PrintConstant(f,c); }
419 break;
420 case OP_SETI:
421 printf("%d %d %d%s",a,b,c,ISK);
422 if (isk) { printf(COMMENT); PrintConstant(f,c); }
423 break;
424 case OP_SETFIELD:
425 printf("%d %d %d%s",a,b,c,ISK);
426 printf(COMMENT); PrintConstant(f,b);
427 if (isk) { printf(" "); PrintConstant(f,c); }
428 break;
429 case OP_NEWTABLE:
430 printf("%d %d %d",a,b,c);
431 printf(COMMENT "%d",c+EXTRAARGC);
432 break;
433 case OP_SELF:
434 printf("%d %d %d%s",a,b,c,ISK);
435 if (isk) { printf(COMMENT); PrintConstant(f,c); }
436 break;
437 case OP_ADDI:
438 printf("%d %d %d",a,b,sc);
439 break;
440 case OP_ADDK:
441 printf("%d %d %d",a,b,c);
442 printf(COMMENT); PrintConstant(f,c);
443 break;
444 case OP_SUBK:
445 printf("%d %d %d",a,b,c);
446 printf(COMMENT); PrintConstant(f,c);
447 break;
448 case OP_MULK:
449 printf("%d %d %d",a,b,c);
450 printf(COMMENT); PrintConstant(f,c);
451 break;
452 case OP_MODK:
453 printf("%d %d %d",a,b,c);
454 printf(COMMENT); PrintConstant(f,c);
455 break;
456 case OP_POWK:
457 printf("%d %d %d",a,b,c);
458 printf(COMMENT); PrintConstant(f,c);
459 break;
460 case OP_DIVK:
461 printf("%d %d %d",a,b,c);
462 printf(COMMENT); PrintConstant(f,c);
463 break;
464 case OP_IDIVK:
465 printf("%d %d %d",a,b,c);
466 printf(COMMENT); PrintConstant(f,c);
467 break;
468 case OP_BANDK:
469 printf("%d %d %d",a,b,c);
470 printf(COMMENT); PrintConstant(f,c);
471 break;
472 case OP_BORK:
473 printf("%d %d %d",a,b,c);
474 printf(COMMENT); PrintConstant(f,c);
475 break;
476 case OP_BXORK:
477 printf("%d %d %d",a,b,c);
478 printf(COMMENT); PrintConstant(f,c);
479 break;
480 case OP_SHRI:
481 printf("%d %d %d",a,b,sc);
482 break;
483 case OP_SHLI:
484 printf("%d %d %d",a,b,sc);
485 break;
486 case OP_ADD:
487 printf("%d %d %d",a,b,c);
488 break;
489 case OP_SUB:
490 printf("%d %d %d",a,b,c);
491 break;
492 case OP_MUL:
493 printf("%d %d %d",a,b,c);
494 break;
495 case OP_MOD:
496 printf("%d %d %d",a,b,c);
497 break;
498 case OP_POW:
499 printf("%d %d %d",a,b,c);
500 break;
501 case OP_DIV:
502 printf("%d %d %d",a,b,c);
503 break;
504 case OP_IDIV:
505 printf("%d %d %d",a,b,c);
506 break;
507 case OP_BAND:
508 printf("%d %d %d",a,b,c);
509 break;
510 case OP_BOR:
511 printf("%d %d %d",a,b,c);
512 break;
513 case OP_BXOR:
514 printf("%d %d %d",a,b,c);
515 break;
516 case OP_SHL:
517 printf("%d %d %d",a,b,c);
518 break;
519 case OP_SHR:
520 printf("%d %d %d",a,b,c);
521 break;
522 case OP_MMBIN:
523 printf("%d %d %d",a,b,c);
524 printf(COMMENT "%s",eventname(c));
525 break;
526 case OP_MMBINI:
527 printf("%d %d %d %d",a,sb,c,isk);
528 printf(COMMENT "%s",eventname(c));
529 if (isk) printf(" flip");
530 break;
531 case OP_MMBINK:
532 printf("%d %d %d %d",a,b,c,isk);
533 printf(COMMENT "%s ",eventname(c)); PrintConstant(f,b);
534 if (isk) printf(" flip");
535 break;
536 case OP_UNM:
537 printf("%d %d",a,b);
538 break;
539 case OP_BNOT:
540 printf("%d %d",a,b);
541 break;
542 case OP_NOT:
543 printf("%d %d",a,b);
544 break;
545 case OP_LEN:
546 printf("%d %d",a,b);
547 break;
548 case OP_CONCAT:
549 printf("%d %d",a,b);
550 break;
551 case OP_CLOSE:
552 printf("%d",a);
553 break;
554 case OP_TBC:
555 printf("%d",a);
556 break;
557 case OP_JMP:
558 printf("%d",GETARG_sJ(i));
559 printf(COMMENT "to %d",GETARG_sJ(i)+pc+2);
560 break;
561 case OP_EQ:
562 printf("%d %d %d",a,b,isk);
563 break;
564 case OP_LT:
565 printf("%d %d %d",a,b,isk);
566 break;
567 case OP_LE:
568 printf("%d %d %d",a,b,isk);
569 break;
570 case OP_EQK:
571 printf("%d %d %d",a,b,isk);
572 printf(COMMENT); PrintConstant(f,b);
573 break;
574 case OP_EQI:
575 printf("%d %d %d",a,sb,isk);
576 break;
577 case OP_LTI:
578 printf("%d %d %d",a,sb,isk);
579 break;
580 case OP_LEI:
581 printf("%d %d %d",a,sb,isk);
582 break;
583 case OP_GTI:
584 printf("%d %d %d",a,sb,isk);
585 break;
586 case OP_GEI:
587 printf("%d %d %d",a,sb,isk);
588 break;
589 case OP_TEST:
590 printf("%d %d",a,isk);
591 break;
592 case OP_TESTSET:
593 printf("%d %d %d",a,b,isk);
594 break;
595 case OP_CALL:
596 printf("%d %d %d",a,b,c);
597 printf(COMMENT);
598 if (b==0) printf("all in "); else printf("%d in ",b-1);
599 if (c==0) printf("all out"); else printf("%d out",c-1);
600 break;
601 case OP_TAILCALL:
602 printf("%d %d %d%s",a,b,c,ISK);
603 printf(COMMENT "%d in",b-1);
604 break;
605 case OP_RETURN:
606 printf("%d %d %d%s",a,b,c,ISK);
607 printf(COMMENT);
608 if (b==0) printf("all out"); else printf("%d out",b-1);
609 break;
610 case OP_RETURN0:
611 break;
612 case OP_RETURN1:
613 printf("%d",a);
614 break;
615 case OP_FORLOOP:
616 printf("%d %d",a,bx);
617 printf(COMMENT "to %d",pc-bx+2);
618 break;
619 case OP_FORPREP:
620 printf("%d %d",a,bx);
621 printf(COMMENT "exit to %d",pc+bx+3);
622 break;
623 case OP_TFORPREP:
624 printf("%d %d",a,bx);
625 printf(COMMENT "to %d",pc+bx+2);
626 break;
627 case OP_TFORCALL:
628 printf("%d %d",a,c);
629 break;
630 case OP_TFORLOOP:
631 printf("%d %d",a,bx);
632 printf(COMMENT "to %d",pc-bx+2);
633 break;
634 case OP_SETLIST:
635 printf("%d %d %d",a,b,c);
636 if (isk) printf(COMMENT "%d",c+EXTRAARGC);
637 break;
638 case OP_CLOSURE:
639 printf("%d %d",a,bx);
640 printf(COMMENT "%p",VOID(f->p[bx]));
641 break;
642 case OP_VARARG:
643 printf("%d %d",a,c);
644 printf(COMMENT);
645 if (c==0) printf("all out"); else printf("%d out",c-1);
646 break;
647 case OP_VARARGPREP:
648 printf("%d",a);
649 break;
650 case OP_EXTRAARG:
651 printf("%d",ax);
652 break;
653#if 0
654 default:
655 printf("%d %d %d",a,b,c);
656 printf(COMMENT "not handled");
657 break;
658#endif
659 }
660 printf("\n");
661 }
662}
663
664
665#define SS(x) ((x==1)?"":"s")
666#define S(x) (int)(x),SS(x)
667
668static void PrintHeader(const Proto* f)
669{
670 const char* s=f->source ? getstr(f->source) : "=?";
671 if (*s=='@' || *s=='=')
672 s++;
673 else if (*s==LUA_SIGNATURE[0])
674 s="(bstring)";
675 else
676 s="(string)";
677 printf("\n%s <%s:%d,%d> (%d instruction%s at %p)\n",
678 (f->linedefined==0)?"main":"function",s,
679 f->linedefined,f->lastlinedefined,
680 S(f->sizecode),VOID(f));
681 printf("%d%s param%s, %d slot%s, %d upvalue%s, ",
682 (int)(f->numparams),f->is_vararg?"+":"",SS(f->numparams),
683 S(f->maxstacksize),S(f->sizeupvalues));
684 printf("%d local%s, %d constant%s, %d function%s\n",
685 S(f->sizelocvars),S(f->sizek),S(f->sizep));
686}
687
688static void PrintDebug(const Proto* f)
689{
690 int i,n;
691 n=f->sizek;
692 printf("constants (%d) for %p:\n",n,VOID(f));
693 for (i=0; i<n; i++)
694 {
695 printf("\t%d\t",i);
696 PrintType(f,i);
697 PrintConstant(f,i);
698 printf("\n");
699 }
700 n=f->sizelocvars;
701 printf("locals (%d) for %p:\n",n,VOID(f));
702 for (i=0; i<n; i++)
703 {
704 printf("\t%d\t%s\t%d\t%d\n",
705 i,getstr(f->locvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1);
706 }
707 n=f->sizeupvalues;
708 printf("upvalues (%d) for %p:\n",n,VOID(f));
709 for (i=0; i<n; i++)
710 {
711 printf("\t%d\t%s\t%d\t%d\n",
712 i,UPVALNAME(i),f->upvalues[i].instack,f->upvalues[i].idx);
713 }
714}
715
716static void PrintFunction(const Proto* f, int full)
717{
718 int i,n=f->sizep;
719 PrintHeader(f);
720 PrintCode(f);
721 if (full) PrintDebug(f);
722 for (i=0; i<n; i++) PrintFunction(f->p[i],full);
723}
diff --git a/vendor/lua-5.4.8/src/luaconf.h b/vendor/lua-5.4.8/src/luaconf.h
new file mode 100644
index 0000000..33bb580
--- /dev/null
+++ b/vendor/lua-5.4.8/src/luaconf.h
@@ -0,0 +1,802 @@
1/*
2** $Id: luaconf.h $
3** Configuration file for Lua
4** See Copyright Notice in lua.h
5*/
6
7
8#ifndef luaconf_h
9#define luaconf_h
10
11#include <limits.h>
12#include <stddef.h>
13
14
15/*
16** ===================================================================
17** General Configuration File for Lua
18**
19** Some definitions here can be changed externally, through the compiler
20** (e.g., with '-D' options): They are commented out or protected
21** by '#if !defined' guards. However, several other definitions
22** should be changed directly here, either because they affect the
23** Lua ABI (by making the changes here, you ensure that all software
24** connected to Lua, such as C libraries, will be compiled with the same
25** configuration); or because they are seldom changed.
26**
27** Search for "@@" to find all configurable definitions.
28** ===================================================================
29*/
30
31
32/*
33** {====================================================================
34** System Configuration: macros to adapt (if needed) Lua to some
35** particular platform, for instance restricting it to C89.
36** =====================================================================
37*/
38
39/*
40@@ LUA_USE_C89 controls the use of non-ISO-C89 features.
41** Define it if you want Lua to avoid the use of a few C99 features
42** or Windows-specific features on Windows.
43*/
44/* #define LUA_USE_C89 */
45
46
47/*
48** By default, Lua on Windows use (some) specific Windows features
49*/
50#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE)
51#define LUA_USE_WINDOWS /* enable goodies for regular Windows */
52#endif
53
54
55#if defined(LUA_USE_WINDOWS)
56#define LUA_DL_DLL /* enable support for DLL */
57#define LUA_USE_C89 /* broadly, Windows is C89 */
58#endif
59
60
61#if defined(LUA_USE_LINUX)
62#define LUA_USE_POSIX
63#define LUA_USE_DLOPEN /* needs an extra library: -ldl */
64#endif
65
66
67#if defined(LUA_USE_MACOSX)
68#define LUA_USE_POSIX
69#define LUA_USE_DLOPEN /* MacOS does not need -ldl */
70#endif
71
72
73#if defined(LUA_USE_IOS)
74#define LUA_USE_POSIX
75#define LUA_USE_DLOPEN
76#endif
77
78
79/*
80@@ LUAI_IS32INT is true iff 'int' has (at least) 32 bits.
81*/
82#define LUAI_IS32INT ((UINT_MAX >> 30) >= 3)
83
84/* }================================================================== */
85
86
87
88/*
89** {==================================================================
90** Configuration for Number types. These options should not be
91** set externally, because any other code connected to Lua must
92** use the same configuration.
93** ===================================================================
94*/
95
96/*
97@@ LUA_INT_TYPE defines the type for Lua integers.
98@@ LUA_FLOAT_TYPE defines the type for Lua floats.
99** Lua should work fine with any mix of these options supported
100** by your C compiler. The usual configurations are 64-bit integers
101** and 'double' (the default), 32-bit integers and 'float' (for
102** restricted platforms), and 'long'/'double' (for C compilers not
103** compliant with C99, which may not have support for 'long long').
104*/
105
106/* predefined options for LUA_INT_TYPE */
107#define LUA_INT_INT 1
108#define LUA_INT_LONG 2
109#define LUA_INT_LONGLONG 3
110
111/* predefined options for LUA_FLOAT_TYPE */
112#define LUA_FLOAT_FLOAT 1
113#define LUA_FLOAT_DOUBLE 2
114#define LUA_FLOAT_LONGDOUBLE 3
115
116
117/* Default configuration ('long long' and 'double', for 64-bit Lua) */
118#define LUA_INT_DEFAULT LUA_INT_LONGLONG
119#define LUA_FLOAT_DEFAULT LUA_FLOAT_DOUBLE
120
121
122/*
123@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats.
124*/
125#define LUA_32BITS 0
126
127
128/*
129@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for
130** C89 ('long' and 'double'); Windows always has '__int64', so it does
131** not need to use this case.
132*/
133#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS)
134#define LUA_C89_NUMBERS 1
135#else
136#define LUA_C89_NUMBERS 0
137#endif
138
139
140#if LUA_32BITS /* { */
141/*
142** 32-bit integers and 'float'
143*/
144#if LUAI_IS32INT /* use 'int' if big enough */
145#define LUA_INT_TYPE LUA_INT_INT
146#else /* otherwise use 'long' */
147#define LUA_INT_TYPE LUA_INT_LONG
148#endif
149#define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT
150
151#elif LUA_C89_NUMBERS /* }{ */
152/*
153** largest types available for C89 ('long' and 'double')
154*/
155#define LUA_INT_TYPE LUA_INT_LONG
156#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE
157
158#else /* }{ */
159/* use defaults */
160
161#define LUA_INT_TYPE LUA_INT_DEFAULT
162#define LUA_FLOAT_TYPE LUA_FLOAT_DEFAULT
163
164#endif /* } */
165
166
167/* }================================================================== */
168
169
170
171/*
172** {==================================================================
173** Configuration for Paths.
174** ===================================================================
175*/
176
177/*
178** LUA_PATH_SEP is the character that separates templates in a path.
179** LUA_PATH_MARK is the string that marks the substitution points in a
180** template.
181** LUA_EXEC_DIR in a Windows path is replaced by the executable's
182** directory.
183*/
184#define LUA_PATH_SEP ";"
185#define LUA_PATH_MARK "?"
186#define LUA_EXEC_DIR "!"
187
188
189/*
190@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for
191** Lua libraries.
192@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for
193** C libraries.
194** CHANGE them if your machine has a non-conventional directory
195** hierarchy or if you want to install your libraries in
196** non-conventional directories.
197*/
198
199#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
200#if defined(_WIN32) /* { */
201/*
202** In Windows, any exclamation mark ('!') in the path is replaced by the
203** path of the directory of the executable file of the current process.
204*/
205#define LUA_LDIR "!\\lua\\"
206#define LUA_CDIR "!\\"
207#define LUA_SHRDIR "!\\..\\share\\lua\\" LUA_VDIR "\\"
208
209#if !defined(LUA_PATH_DEFAULT)
210#define LUA_PATH_DEFAULT \
211 LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \
212 LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \
213 LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \
214 ".\\?.lua;" ".\\?\\init.lua"
215#endif
216
217#if !defined(LUA_CPATH_DEFAULT)
218#define LUA_CPATH_DEFAULT \
219 LUA_CDIR"?.dll;" \
220 LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \
221 LUA_CDIR"loadall.dll;" ".\\?.dll"
222#endif
223
224#else /* }{ */
225
226#define LUA_ROOT "/usr/local/"
227#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR "/"
228#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR "/"
229
230#if !defined(LUA_PATH_DEFAULT)
231#define LUA_PATH_DEFAULT \
232 LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \
233 LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \
234 "./?.lua;" "./?/init.lua"
235#endif
236
237#if !defined(LUA_CPATH_DEFAULT)
238#define LUA_CPATH_DEFAULT \
239 LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so"
240#endif
241
242#endif /* } */
243
244
245/*
246@@ LUA_DIRSEP is the directory separator (for submodules).
247** CHANGE it if your machine does not use "/" as the directory separator
248** and is not Windows. (On Windows Lua automatically uses "\".)
249*/
250#if !defined(LUA_DIRSEP)
251
252#if defined(_WIN32)
253#define LUA_DIRSEP "\\"
254#else
255#define LUA_DIRSEP "/"
256#endif
257
258#endif
259
260
261/*
262** LUA_IGMARK is a mark to ignore all after it when building the
263** module name (e.g., used to build the luaopen_ function name).
264** Typically, the suffix after the mark is the module version,
265** as in "mod-v1.2.so".
266*/
267#define LUA_IGMARK "-"
268
269/* }================================================================== */
270
271
272/*
273** {==================================================================
274** Marks for exported symbols in the C code
275** ===================================================================
276*/
277
278/*
279@@ LUA_API is a mark for all core API functions.
280@@ LUALIB_API is a mark for all auxiliary library functions.
281@@ LUAMOD_API is a mark for all standard library opening functions.
282** CHANGE them if you need to define those functions in some special way.
283** For instance, if you want to create one Windows DLL with the core and
284** the libraries, you may want to use the following definition (define
285** LUA_BUILD_AS_DLL to get it).
286*/
287#if defined(LUA_BUILD_AS_DLL) /* { */
288
289#if defined(LUA_CORE) || defined(LUA_LIB) /* { */
290#define LUA_API __declspec(dllexport)
291#else /* }{ */
292#define LUA_API __declspec(dllimport)
293#endif /* } */
294
295#else /* }{ */
296
297#define LUA_API extern
298
299#endif /* } */
300
301
302/*
303** More often than not the libs go together with the core.
304*/
305#define LUALIB_API LUA_API
306#define LUAMOD_API LUA_API
307
308
309/*
310@@ LUAI_FUNC is a mark for all extern functions that are not to be
311** exported to outside modules.
312@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables,
313** none of which to be exported to outside modules (LUAI_DDEF for
314** definitions and LUAI_DDEC for declarations).
315** CHANGE them if you need to mark them in some special way. Elf/gcc
316** (versions 3.2 and later) mark them as "hidden" to optimize access
317** when Lua is compiled as a shared library. Not all elf targets support
318** this attribute. Unfortunately, gcc does not offer a way to check
319** whether the target offers that support, and those without support
320** give a warning about it. To avoid these warnings, change to the
321** default definition.
322*/
323#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
324 defined(__ELF__) /* { */
325#define LUAI_FUNC __attribute__((visibility("internal"))) extern
326#else /* }{ */
327#define LUAI_FUNC extern
328#endif /* } */
329
330#define LUAI_DDEC(dec) LUAI_FUNC dec
331#define LUAI_DDEF /* empty */
332
333/* }================================================================== */
334
335
336/*
337** {==================================================================
338** Compatibility with previous versions
339** ===================================================================
340*/
341
342/*
343@@ LUA_COMPAT_5_3 controls other macros for compatibility with Lua 5.3.
344** You can define it to get all options, or change specific options
345** to fit your specific needs.
346*/
347#if defined(LUA_COMPAT_5_3) /* { */
348
349/*
350@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated
351** functions in the mathematical library.
352** (These functions were already officially removed in 5.3;
353** nevertheless they are still available here.)
354*/
355#define LUA_COMPAT_MATHLIB
356
357/*
358@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for
359** manipulating other integer types (lua_pushunsigned, lua_tounsigned,
360** luaL_checkint, luaL_checklong, etc.)
361** (These macros were also officially removed in 5.3, but they are still
362** available here.)
363*/
364#define LUA_COMPAT_APIINTCASTS
365
366
367/*
368@@ LUA_COMPAT_LT_LE controls the emulation of the '__le' metamethod
369** using '__lt'.
370*/
371#define LUA_COMPAT_LT_LE
372
373
374/*
375@@ The following macros supply trivial compatibility for some
376** changes in the API. The macros themselves document how to
377** change your code to avoid using them.
378** (Once more, these macros were officially removed in 5.3, but they are
379** still available here.)
380*/
381#define lua_strlen(L,i) lua_rawlen(L, (i))
382
383#define lua_objlen(L,i) lua_rawlen(L, (i))
384
385#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ)
386#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT)
387
388#endif /* } */
389
390/* }================================================================== */
391
392
393
394/*
395** {==================================================================
396** Configuration for Numbers (low-level part).
397** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_*
398** satisfy your needs.
399** ===================================================================
400*/
401
402/*
403@@ LUAI_UACNUMBER is the result of a 'default argument promotion'
404@@ over a floating number.
405@@ l_floatatt(x) corrects float attribute 'x' to the proper float type
406** by prefixing it with one of FLT/DBL/LDBL.
407@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats.
408@@ LUA_NUMBER_FMT is the format for writing floats.
409@@ lua_number2str converts a float to a string.
410@@ l_mathop allows the addition of an 'l' or 'f' to all math operations.
411@@ l_floor takes the floor of a float.
412@@ lua_str2number converts a decimal numeral to a number.
413*/
414
415
416/* The following definitions are good for most cases here */
417
418#define l_floor(x) (l_mathop(floor)(x))
419
420#define lua_number2str(s,sz,n) \
421 l_sprintf((s), sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)(n))
422
423/*
424@@ lua_numbertointeger converts a float number with an integral value
425** to an integer, or returns 0 if float is not within the range of
426** a lua_Integer. (The range comparisons are tricky because of
427** rounding. The tests here assume a two-complement representation,
428** where MININTEGER always has an exact representation as a float;
429** MAXINTEGER may not have one, and therefore its conversion to float
430** may have an ill-defined value.)
431*/
432#define lua_numbertointeger(n,p) \
433 ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \
434 (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \
435 (*(p) = (LUA_INTEGER)(n), 1))
436
437
438/* now the variable definitions */
439
440#if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */
441
442#define LUA_NUMBER float
443
444#define l_floatatt(n) (FLT_##n)
445
446#define LUAI_UACNUMBER double
447
448#define LUA_NUMBER_FRMLEN ""
449#define LUA_NUMBER_FMT "%.7g"
450
451#define l_mathop(op) op##f
452
453#define lua_str2number(s,p) strtof((s), (p))
454
455
456#elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE /* }{ long double */
457
458#define LUA_NUMBER long double
459
460#define l_floatatt(n) (LDBL_##n)
461
462#define LUAI_UACNUMBER long double
463
464#define LUA_NUMBER_FRMLEN "L"
465#define LUA_NUMBER_FMT "%.19Lg"
466
467#define l_mathop(op) op##l
468
469#define lua_str2number(s,p) strtold((s), (p))
470
471#elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE /* }{ double */
472
473#define LUA_NUMBER double
474
475#define l_floatatt(n) (DBL_##n)
476
477#define LUAI_UACNUMBER double
478
479#define LUA_NUMBER_FRMLEN ""
480#define LUA_NUMBER_FMT "%.14g"
481
482#define l_mathop(op) op
483
484#define lua_str2number(s,p) strtod((s), (p))
485
486#else /* }{ */
487
488#error "numeric float type not defined"
489
490#endif /* } */
491
492
493
494/*
495@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER.
496@@ LUAI_UACINT is the result of a 'default argument promotion'
497@@ over a LUA_INTEGER.
498@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers.
499@@ LUA_INTEGER_FMT is the format for writing integers.
500@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER.
501@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER.
502@@ LUA_MAXUNSIGNED is the maximum value for a LUA_UNSIGNED.
503@@ lua_integer2str converts an integer to a string.
504*/
505
506
507/* The following definitions are good for most cases here */
508
509#define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d"
510
511#define LUAI_UACINT LUA_INTEGER
512
513#define lua_integer2str(s,sz,n) \
514 l_sprintf((s), sz, LUA_INTEGER_FMT, (LUAI_UACINT)(n))
515
516/*
517** use LUAI_UACINT here to avoid problems with promotions (which
518** can turn a comparison between unsigneds into a signed comparison)
519*/
520#define LUA_UNSIGNED unsigned LUAI_UACINT
521
522
523/* now the variable definitions */
524
525#if LUA_INT_TYPE == LUA_INT_INT /* { int */
526
527#define LUA_INTEGER int
528#define LUA_INTEGER_FRMLEN ""
529
530#define LUA_MAXINTEGER INT_MAX
531#define LUA_MININTEGER INT_MIN
532
533#define LUA_MAXUNSIGNED UINT_MAX
534
535#elif LUA_INT_TYPE == LUA_INT_LONG /* }{ long */
536
537#define LUA_INTEGER long
538#define LUA_INTEGER_FRMLEN "l"
539
540#define LUA_MAXINTEGER LONG_MAX
541#define LUA_MININTEGER LONG_MIN
542
543#define LUA_MAXUNSIGNED ULONG_MAX
544
545#elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */
546
547/* use presence of macro LLONG_MAX as proxy for C99 compliance */
548#if defined(LLONG_MAX) /* { */
549/* use ISO C99 stuff */
550
551#define LUA_INTEGER long long
552#define LUA_INTEGER_FRMLEN "ll"
553
554#define LUA_MAXINTEGER LLONG_MAX
555#define LUA_MININTEGER LLONG_MIN
556
557#define LUA_MAXUNSIGNED ULLONG_MAX
558
559#elif defined(LUA_USE_WINDOWS) /* }{ */
560/* in Windows, can use specific Windows types */
561
562#define LUA_INTEGER __int64
563#define LUA_INTEGER_FRMLEN "I64"
564
565#define LUA_MAXINTEGER _I64_MAX
566#define LUA_MININTEGER _I64_MIN
567
568#define LUA_MAXUNSIGNED _UI64_MAX
569
570#else /* }{ */
571
572#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \
573 or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)"
574
575#endif /* } */
576
577#else /* }{ */
578
579#error "numeric integer type not defined"
580
581#endif /* } */
582
583/* }================================================================== */
584
585
586/*
587** {==================================================================
588** Dependencies with C99 and other C details
589** ===================================================================
590*/
591
592/*
593@@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89.
594** (All uses in Lua have only one format item.)
595*/
596#if !defined(LUA_USE_C89)
597#define l_sprintf(s,sz,f,i) snprintf(s,sz,f,i)
598#else
599#define l_sprintf(s,sz,f,i) ((void)(sz), sprintf(s,f,i))
600#endif
601
602
603/*
604@@ lua_strx2number converts a hexadecimal numeral to a number.
605** In C99, 'strtod' does that conversion. Otherwise, you can
606** leave 'lua_strx2number' undefined and Lua will provide its own
607** implementation.
608*/
609#if !defined(LUA_USE_C89)
610#define lua_strx2number(s,p) lua_str2number(s,p)
611#endif
612
613
614/*
615@@ lua_pointer2str converts a pointer to a readable string in a
616** non-specified way.
617*/
618#define lua_pointer2str(buff,sz,p) l_sprintf(buff,sz,"%p",p)
619
620
621/*
622@@ lua_number2strx converts a float to a hexadecimal numeral.
623** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that.
624** Otherwise, you can leave 'lua_number2strx' undefined and Lua will
625** provide its own implementation.
626*/
627#if !defined(LUA_USE_C89)
628#define lua_number2strx(L,b,sz,f,n) \
629 ((void)L, l_sprintf(b,sz,f,(LUAI_UACNUMBER)(n)))
630#endif
631
632
633/*
634** 'strtof' and 'opf' variants for math functions are not valid in
635** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the
636** availability of these variants. ('math.h' is already included in
637** all files that use these macros.)
638*/
639#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF))
640#undef l_mathop /* variants not available */
641#undef lua_str2number
642#define l_mathop(op) (lua_Number)op /* no variant */
643#define lua_str2number(s,p) ((lua_Number)strtod((s), (p)))
644#endif
645
646
647/*
648@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation
649** functions. It must be a numerical type; Lua will use 'intptr_t' if
650** available, otherwise it will use 'ptrdiff_t' (the nearest thing to
651** 'intptr_t' in C89)
652*/
653#define LUA_KCONTEXT ptrdiff_t
654
655#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \
656 __STDC_VERSION__ >= 199901L
657#include <stdint.h>
658#if defined(INTPTR_MAX) /* even in C99 this type is optional */
659#undef LUA_KCONTEXT
660#define LUA_KCONTEXT intptr_t
661#endif
662#endif
663
664
665/*
666@@ lua_getlocaledecpoint gets the locale "radix character" (decimal point).
667** Change that if you do not want to use C locales. (Code using this
668** macro must include the header 'locale.h'.)
669*/
670#if !defined(lua_getlocaledecpoint)
671#define lua_getlocaledecpoint() (localeconv()->decimal_point[0])
672#endif
673
674
675/*
676** macros to improve jump prediction, used mostly for error handling
677** and debug facilities. (Some macros in the Lua API use these macros.
678** Define LUA_NOBUILTIN if you do not want '__builtin_expect' in your
679** code.)
680*/
681#if !defined(luai_likely)
682
683#if defined(__GNUC__) && !defined(LUA_NOBUILTIN)
684#define luai_likely(x) (__builtin_expect(((x) != 0), 1))
685#define luai_unlikely(x) (__builtin_expect(((x) != 0), 0))
686#else
687#define luai_likely(x) (x)
688#define luai_unlikely(x) (x)
689#endif
690
691#endif
692
693
694#if defined(LUA_CORE) || defined(LUA_LIB)
695/* shorter names for Lua's own use */
696#define l_likely(x) luai_likely(x)
697#define l_unlikely(x) luai_unlikely(x)
698#endif
699
700
701
702/* }================================================================== */
703
704
705/*
706** {==================================================================
707** Language Variations
708** =====================================================================
709*/
710
711/*
712@@ LUA_NOCVTN2S/LUA_NOCVTS2N control how Lua performs some
713** coercions. Define LUA_NOCVTN2S to turn off automatic coercion from
714** numbers to strings. Define LUA_NOCVTS2N to turn off automatic
715** coercion from strings to numbers.
716*/
717/* #define LUA_NOCVTN2S */
718/* #define LUA_NOCVTS2N */
719
720
721/*
722@@ LUA_USE_APICHECK turns on several consistency checks on the C API.
723** Define it as a help when debugging C code.
724*/
725#if defined(LUA_USE_APICHECK)
726#include <assert.h>
727#define luai_apicheck(l,e) assert(e)
728#endif
729
730/* }================================================================== */
731
732
733/*
734** {==================================================================
735** Macros that affect the API and must be stable (that is, must be the
736** same when you compile Lua and when you compile code that links to
737** Lua).
738** =====================================================================
739*/
740
741/*
742@@ LUAI_MAXSTACK limits the size of the Lua stack.
743** CHANGE it if you need a different limit. This limit is arbitrary;
744** its only purpose is to stop Lua from consuming unlimited stack
745** space (and to reserve some numbers for pseudo-indices).
746** (It must fit into max(size_t)/32 and max(int)/2.)
747*/
748#if LUAI_IS32INT
749#define LUAI_MAXSTACK 1000000
750#else
751#define LUAI_MAXSTACK 15000
752#endif
753
754
755/*
756@@ LUA_EXTRASPACE defines the size of a raw memory area associated with
757** a Lua state with very fast access.
758** CHANGE it if you need a different size.
759*/
760#define LUA_EXTRASPACE (sizeof(void *))
761
762
763/*
764@@ LUA_IDSIZE gives the maximum size for the description of the source
765** of a function in debug information.
766** CHANGE it if you want a different size.
767*/
768#define LUA_IDSIZE 60
769
770
771/*
772@@ LUAL_BUFFERSIZE is the initial buffer size used by the lauxlib
773** buffer system.
774*/
775#define LUAL_BUFFERSIZE ((int)(16 * sizeof(void*) * sizeof(lua_Number)))
776
777
778/*
779@@ LUAI_MAXALIGN defines fields that, when used in a union, ensure
780** maximum alignment for the other items in that union.
781*/
782#define LUAI_MAXALIGN lua_Number n; double u; void *s; lua_Integer i; long l
783
784/* }================================================================== */
785
786
787
788
789
790/* =================================================================== */
791
792/*
793** Local configuration. You can use this space to add your redefinitions
794** without modifying the main part of the file.
795*/
796
797
798
799
800
801#endif
802
diff --git a/vendor/lua-5.4.8/src/lualib.h b/vendor/lua-5.4.8/src/lualib.h
new file mode 100644
index 0000000..2625529
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lualib.h
@@ -0,0 +1,52 @@
1/*
2** $Id: lualib.h $
3** Lua standard libraries
4** See Copyright Notice in lua.h
5*/
6
7
8#ifndef lualib_h
9#define lualib_h
10
11#include "lua.h"
12
13
14/* version suffix for environment variable names */
15#define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
16
17
18LUAMOD_API int (luaopen_base) (lua_State *L);
19
20#define LUA_COLIBNAME "coroutine"
21LUAMOD_API int (luaopen_coroutine) (lua_State *L);
22
23#define LUA_TABLIBNAME "table"
24LUAMOD_API int (luaopen_table) (lua_State *L);
25
26#define LUA_IOLIBNAME "io"
27LUAMOD_API int (luaopen_io) (lua_State *L);
28
29#define LUA_OSLIBNAME "os"
30LUAMOD_API int (luaopen_os) (lua_State *L);
31
32#define LUA_STRLIBNAME "string"
33LUAMOD_API int (luaopen_string) (lua_State *L);
34
35#define LUA_UTF8LIBNAME "utf8"
36LUAMOD_API int (luaopen_utf8) (lua_State *L);
37
38#define LUA_MATHLIBNAME "math"
39LUAMOD_API int (luaopen_math) (lua_State *L);
40
41#define LUA_DBLIBNAME "debug"
42LUAMOD_API int (luaopen_debug) (lua_State *L);
43
44#define LUA_LOADLIBNAME "package"
45LUAMOD_API int (luaopen_package) (lua_State *L);
46
47
48/* open all previous libraries */
49LUALIB_API void (luaL_openlibs) (lua_State *L);
50
51
52#endif
diff --git a/vendor/lua-5.4.8/src/lundump.c b/vendor/lua-5.4.8/src/lundump.c
new file mode 100644
index 0000000..e8d92a8
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lundump.c
@@ -0,0 +1,335 @@
1/*
2** $Id: lundump.c $
3** load precompiled Lua chunks
4** See Copyright Notice in lua.h
5*/
6
7#define lundump_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <limits.h>
14#include <string.h>
15
16#include "lua.h"
17
18#include "ldebug.h"
19#include "ldo.h"
20#include "lfunc.h"
21#include "lmem.h"
22#include "lobject.h"
23#include "lstring.h"
24#include "lundump.h"
25#include "lzio.h"
26
27
28#if !defined(luai_verifycode)
29#define luai_verifycode(L,f) /* empty */
30#endif
31
32
33typedef struct {
34 lua_State *L;
35 ZIO *Z;
36 const char *name;
37} LoadState;
38
39
40static l_noret error (LoadState *S, const char *why) {
41 luaO_pushfstring(S->L, "%s: bad binary format (%s)", S->name, why);
42 luaD_throw(S->L, LUA_ERRSYNTAX);
43}
44
45
46/*
47** All high-level loads go through loadVector; you can change it to
48** adapt to the endianness of the input
49*/
50#define loadVector(S,b,n) loadBlock(S,b,(n)*sizeof((b)[0]))
51
52static void loadBlock (LoadState *S, void *b, size_t size) {
53 if (luaZ_read(S->Z, b, size) != 0)
54 error(S, "truncated chunk");
55}
56
57
58#define loadVar(S,x) loadVector(S,&x,1)
59
60
61static lu_byte loadByte (LoadState *S) {
62 int b = zgetc(S->Z);
63 if (b == EOZ)
64 error(S, "truncated chunk");
65 return cast_byte(b);
66}
67
68
69static size_t loadUnsigned (LoadState *S, size_t limit) {
70 size_t x = 0;
71 int b;
72 limit >>= 7;
73 do {
74 b = loadByte(S);
75 if (x >= limit)
76 error(S, "integer overflow");
77 x = (x << 7) | (b & 0x7f);
78 } while ((b & 0x80) == 0);
79 return x;
80}
81
82
83static size_t loadSize (LoadState *S) {
84 return loadUnsigned(S, MAX_SIZET);
85}
86
87
88static int loadInt (LoadState *S) {
89 return cast_int(loadUnsigned(S, INT_MAX));
90}
91
92
93static lua_Number loadNumber (LoadState *S) {
94 lua_Number x;
95 loadVar(S, x);
96 return x;
97}
98
99
100static lua_Integer loadInteger (LoadState *S) {
101 lua_Integer x;
102 loadVar(S, x);
103 return x;
104}
105
106
107/*
108** Load a nullable string into prototype 'p'.
109*/
110static TString *loadStringN (LoadState *S, Proto *p) {
111 lua_State *L = S->L;
112 TString *ts;
113 size_t size = loadSize(S);
114 if (size == 0) /* no string? */
115 return NULL;
116 else if (--size <= LUAI_MAXSHORTLEN) { /* short string? */
117 char buff[LUAI_MAXSHORTLEN];
118 loadVector(S, buff, size); /* load string into buffer */
119 ts = luaS_newlstr(L, buff, size); /* create string */
120 }
121 else { /* long string */
122 ts = luaS_createlngstrobj(L, size); /* create string */
123 setsvalue2s(L, L->top.p, ts); /* anchor it ('loadVector' can GC) */
124 luaD_inctop(L);
125 loadVector(S, getlngstr(ts), size); /* load directly in final place */
126 L->top.p--; /* pop string */
127 }
128 luaC_objbarrier(L, p, ts);
129 return ts;
130}
131
132
133/*
134** Load a non-nullable string into prototype 'p'.
135*/
136static TString *loadString (LoadState *S, Proto *p) {
137 TString *st = loadStringN(S, p);
138 if (st == NULL)
139 error(S, "bad format for constant string");
140 return st;
141}
142
143
144static void loadCode (LoadState *S, Proto *f) {
145 int n = loadInt(S);
146 f->code = luaM_newvectorchecked(S->L, n, Instruction);
147 f->sizecode = n;
148 loadVector(S, f->code, n);
149}
150
151
152static void loadFunction(LoadState *S, Proto *f, TString *psource);
153
154
155static void loadConstants (LoadState *S, Proto *f) {
156 int i;
157 int n = loadInt(S);
158 f->k = luaM_newvectorchecked(S->L, n, TValue);
159 f->sizek = n;
160 for (i = 0; i < n; i++)
161 setnilvalue(&f->k[i]);
162 for (i = 0; i < n; i++) {
163 TValue *o = &f->k[i];
164 int t = loadByte(S);
165 switch (t) {
166 case LUA_VNIL:
167 setnilvalue(o);
168 break;
169 case LUA_VFALSE:
170 setbfvalue(o);
171 break;
172 case LUA_VTRUE:
173 setbtvalue(o);
174 break;
175 case LUA_VNUMFLT:
176 setfltvalue(o, loadNumber(S));
177 break;
178 case LUA_VNUMINT:
179 setivalue(o, loadInteger(S));
180 break;
181 case LUA_VSHRSTR:
182 case LUA_VLNGSTR:
183 setsvalue2n(S->L, o, loadString(S, f));
184 break;
185 default: lua_assert(0);
186 }
187 }
188}
189
190
191static void loadProtos (LoadState *S, Proto *f) {
192 int i;
193 int n = loadInt(S);
194 f->p = luaM_newvectorchecked(S->L, n, Proto *);
195 f->sizep = n;
196 for (i = 0; i < n; i++)
197 f->p[i] = NULL;
198 for (i = 0; i < n; i++) {
199 f->p[i] = luaF_newproto(S->L);
200 luaC_objbarrier(S->L, f, f->p[i]);
201 loadFunction(S, f->p[i], f->source);
202 }
203}
204
205
206/*
207** Load the upvalues for a function. The names must be filled first,
208** because the filling of the other fields can raise read errors and
209** the creation of the error message can call an emergency collection;
210** in that case all prototypes must be consistent for the GC.
211*/
212static void loadUpvalues (LoadState *S, Proto *f) {
213 int i, n;
214 n = loadInt(S);
215 f->upvalues = luaM_newvectorchecked(S->L, n, Upvaldesc);
216 f->sizeupvalues = n;
217 for (i = 0; i < n; i++) /* make array valid for GC */
218 f->upvalues[i].name = NULL;
219 for (i = 0; i < n; i++) { /* following calls can raise errors */
220 f->upvalues[i].instack = loadByte(S);
221 f->upvalues[i].idx = loadByte(S);
222 f->upvalues[i].kind = loadByte(S);
223 }
224}
225
226
227static void loadDebug (LoadState *S, Proto *f) {
228 int i, n;
229 n = loadInt(S);
230 f->lineinfo = luaM_newvectorchecked(S->L, n, ls_byte);
231 f->sizelineinfo = n;
232 loadVector(S, f->lineinfo, n);
233 n = loadInt(S);
234 f->abslineinfo = luaM_newvectorchecked(S->L, n, AbsLineInfo);
235 f->sizeabslineinfo = n;
236 for (i = 0; i < n; i++) {
237 f->abslineinfo[i].pc = loadInt(S);
238 f->abslineinfo[i].line = loadInt(S);
239 }
240 n = loadInt(S);
241 f->locvars = luaM_newvectorchecked(S->L, n, LocVar);
242 f->sizelocvars = n;
243 for (i = 0; i < n; i++)
244 f->locvars[i].varname = NULL;
245 for (i = 0; i < n; i++) {
246 f->locvars[i].varname = loadStringN(S, f);
247 f->locvars[i].startpc = loadInt(S);
248 f->locvars[i].endpc = loadInt(S);
249 }
250 n = loadInt(S);
251 if (n != 0) /* does it have debug information? */
252 n = f->sizeupvalues; /* must be this many */
253 for (i = 0; i < n; i++)
254 f->upvalues[i].name = loadStringN(S, f);
255}
256
257
258static void loadFunction (LoadState *S, Proto *f, TString *psource) {
259 f->source = loadStringN(S, f);
260 if (f->source == NULL) /* no source in dump? */
261 f->source = psource; /* reuse parent's source */
262 f->linedefined = loadInt(S);
263 f->lastlinedefined = loadInt(S);
264 f->numparams = loadByte(S);
265 f->is_vararg = loadByte(S);
266 f->maxstacksize = loadByte(S);
267 loadCode(S, f);
268 loadConstants(S, f);
269 loadUpvalues(S, f);
270 loadProtos(S, f);
271 loadDebug(S, f);
272}
273
274
275static void checkliteral (LoadState *S, const char *s, const char *msg) {
276 char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */
277 size_t len = strlen(s);
278 loadVector(S, buff, len);
279 if (memcmp(s, buff, len) != 0)
280 error(S, msg);
281}
282
283
284static void fchecksize (LoadState *S, size_t size, const char *tname) {
285 if (loadByte(S) != size)
286 error(S, luaO_pushfstring(S->L, "%s size mismatch", tname));
287}
288
289
290#define checksize(S,t) fchecksize(S,sizeof(t),#t)
291
292static void checkHeader (LoadState *S) {
293 /* skip 1st char (already read and checked) */
294 checkliteral(S, &LUA_SIGNATURE[1], "not a binary chunk");
295 if (loadByte(S) != LUAC_VERSION)
296 error(S, "version mismatch");
297 if (loadByte(S) != LUAC_FORMAT)
298 error(S, "format mismatch");
299 checkliteral(S, LUAC_DATA, "corrupted chunk");
300 checksize(S, Instruction);
301 checksize(S, lua_Integer);
302 checksize(S, lua_Number);
303 if (loadInteger(S) != LUAC_INT)
304 error(S, "integer format mismatch");
305 if (loadNumber(S) != LUAC_NUM)
306 error(S, "float format mismatch");
307}
308
309
310/*
311** Load precompiled chunk.
312*/
313LClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) {
314 LoadState S;
315 LClosure *cl;
316 if (*name == '@' || *name == '=')
317 S.name = name + 1;
318 else if (*name == LUA_SIGNATURE[0])
319 S.name = "binary string";
320 else
321 S.name = name;
322 S.L = L;
323 S.Z = Z;
324 checkHeader(&S);
325 cl = luaF_newLclosure(L, loadByte(&S));
326 setclLvalue2s(L, L->top.p, cl);
327 luaD_inctop(L);
328 cl->p = luaF_newproto(L);
329 luaC_objbarrier(L, cl, cl->p);
330 loadFunction(&S, cl->p, NULL);
331 lua_assert(cl->nupvalues == cl->p->sizeupvalues);
332 luai_verifycode(L, cl->p);
333 return cl;
334}
335
diff --git a/vendor/lua-5.4.8/src/lundump.h b/vendor/lua-5.4.8/src/lundump.h
new file mode 100644
index 0000000..a97676c
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lundump.h
@@ -0,0 +1,35 @@
1/*
2** $Id: lundump.h $
3** load precompiled Lua chunks
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lundump_h
8#define lundump_h
9
10#include "llimits.h"
11#include "lobject.h"
12#include "lzio.h"
13
14
15/* data to catch conversion errors */
16#define LUAC_DATA "\x19\x93\r\n\x1a\n"
17
18#define LUAC_INT 0x5678
19#define LUAC_NUM cast_num(370.5)
20
21/*
22** Encode major-minor version in one byte, one nibble for each
23*/
24#define LUAC_VERSION (((LUA_VERSION_NUM / 100) * 16) + LUA_VERSION_NUM % 100)
25
26#define LUAC_FORMAT 0 /* this is the official format */
27
28/* load one chunk; from lundump.c */
29LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, const char* name);
30
31/* dump one chunk; from ldump.c */
32LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w,
33 void* data, int strip);
34
35#endif
diff --git a/vendor/lua-5.4.8/src/lutf8lib.c b/vendor/lua-5.4.8/src/lutf8lib.c
new file mode 100644
index 0000000..3a5b9bc
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lutf8lib.c
@@ -0,0 +1,291 @@
1/*
2** $Id: lutf8lib.c $
3** Standard library for UTF-8 manipulation
4** See Copyright Notice in lua.h
5*/
6
7#define lutf8lib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <assert.h>
14#include <limits.h>
15#include <stdlib.h>
16#include <string.h>
17
18#include "lua.h"
19
20#include "lauxlib.h"
21#include "lualib.h"
22
23
24#define MAXUNICODE 0x10FFFFu
25
26#define MAXUTF 0x7FFFFFFFu
27
28
29#define MSGInvalid "invalid UTF-8 code"
30
31/*
32** Integer type for decoded UTF-8 values; MAXUTF needs 31 bits.
33*/
34#if (UINT_MAX >> 30) >= 1
35typedef unsigned int utfint;
36#else
37typedef unsigned long utfint;
38#endif
39
40
41#define iscont(c) (((c) & 0xC0) == 0x80)
42#define iscontp(p) iscont(*(p))
43
44
45/* from strlib */
46/* translate a relative string position: negative means back from end */
47static lua_Integer u_posrelat (lua_Integer pos, size_t len) {
48 if (pos >= 0) return pos;
49 else if (0u - (size_t)pos > len) return 0;
50 else return (lua_Integer)len + pos + 1;
51}
52
53
54/*
55** Decode one UTF-8 sequence, returning NULL if byte sequence is
56** invalid. The array 'limits' stores the minimum value for each
57** sequence length, to check for overlong representations. Its first
58** entry forces an error for non-ascii bytes with no continuation
59** bytes (count == 0).
60*/
61static const char *utf8_decode (const char *s, utfint *val, int strict) {
62 static const utfint limits[] =
63 {~(utfint)0, 0x80, 0x800, 0x10000u, 0x200000u, 0x4000000u};
64 unsigned int c = (unsigned char)s[0];
65 utfint res = 0; /* final result */
66 if (c < 0x80) /* ascii? */
67 res = c;
68 else {
69 int count = 0; /* to count number of continuation bytes */
70 for (; c & 0x40; c <<= 1) { /* while it needs continuation bytes... */
71 unsigned int cc = (unsigned char)s[++count]; /* read next byte */
72 if (!iscont(cc)) /* not a continuation byte? */
73 return NULL; /* invalid byte sequence */
74 res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */
75 }
76 res |= ((utfint)(c & 0x7F) << (count * 5)); /* add first byte */
77 if (count > 5 || res > MAXUTF || res < limits[count])
78 return NULL; /* invalid byte sequence */
79 s += count; /* skip continuation bytes read */
80 }
81 if (strict) {
82 /* check for invalid code points; too large or surrogates */
83 if (res > MAXUNICODE || (0xD800u <= res && res <= 0xDFFFu))
84 return NULL;
85 }
86 if (val) *val = res;
87 return s + 1; /* +1 to include first byte */
88}
89
90
91/*
92** utf8len(s [, i [, j [, lax]]]) --> number of characters that
93** start in the range [i,j], or nil + current position if 's' is not
94** well formed in that interval
95*/
96static int utflen (lua_State *L) {
97 lua_Integer n = 0; /* counter for the number of characters */
98 size_t len; /* string length in bytes */
99 const char *s = luaL_checklstring(L, 1, &len);
100 lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
101 lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len);
102 int lax = lua_toboolean(L, 4);
103 luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,
104 "initial position out of bounds");
105 luaL_argcheck(L, --posj < (lua_Integer)len, 3,
106 "final position out of bounds");
107 while (posi <= posj) {
108 const char *s1 = utf8_decode(s + posi, NULL, !lax);
109 if (s1 == NULL) { /* conversion error? */
110 luaL_pushfail(L); /* return fail ... */
111 lua_pushinteger(L, posi + 1); /* ... and current position */
112 return 2;
113 }
114 posi = s1 - s;
115 n++;
116 }
117 lua_pushinteger(L, n);
118 return 1;
119}
120
121
122/*
123** codepoint(s, [i, [j [, lax]]]) -> returns codepoints for all
124** characters that start in the range [i,j]
125*/
126static int codepoint (lua_State *L) {
127 size_t len;
128 const char *s = luaL_checklstring(L, 1, &len);
129 lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
130 lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len);
131 int lax = lua_toboolean(L, 4);
132 int n;
133 const char *se;
134 luaL_argcheck(L, posi >= 1, 2, "out of bounds");
135 luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of bounds");
136 if (posi > pose) return 0; /* empty interval; return no values */
137 if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */
138 return luaL_error(L, "string slice too long");
139 n = (int)(pose - posi) + 1; /* upper bound for number of returns */
140 luaL_checkstack(L, n, "string slice too long");
141 n = 0; /* count the number of returns */
142 se = s + pose; /* string end */
143 for (s += posi - 1; s < se;) {
144 utfint code;
145 s = utf8_decode(s, &code, !lax);
146 if (s == NULL)
147 return luaL_error(L, MSGInvalid);
148 lua_pushinteger(L, code);
149 n++;
150 }
151 return n;
152}
153
154
155static void pushutfchar (lua_State *L, int arg) {
156 lua_Unsigned code = (lua_Unsigned)luaL_checkinteger(L, arg);
157 luaL_argcheck(L, code <= MAXUTF, arg, "value out of range");
158 lua_pushfstring(L, "%U", (long)code);
159}
160
161
162/*
163** utfchar(n1, n2, ...) -> char(n1)..char(n2)...
164*/
165static int utfchar (lua_State *L) {
166 int n = lua_gettop(L); /* number of arguments */
167 if (n == 1) /* optimize common case of single char */
168 pushutfchar(L, 1);
169 else {
170 int i;
171 luaL_Buffer b;
172 luaL_buffinit(L, &b);
173 for (i = 1; i <= n; i++) {
174 pushutfchar(L, i);
175 luaL_addvalue(&b);
176 }
177 luaL_pushresult(&b);
178 }
179 return 1;
180}
181
182
183/*
184** offset(s, n, [i]) -> index where n-th character counting from
185** position 'i' starts; 0 means character at 'i'.
186*/
187static int byteoffset (lua_State *L) {
188 size_t len;
189 const char *s = luaL_checklstring(L, 1, &len);
190 lua_Integer n = luaL_checkinteger(L, 2);
191 lua_Integer posi = (n >= 0) ? 1 : len + 1;
192 posi = u_posrelat(luaL_optinteger(L, 3, posi), len);
193 luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3,
194 "position out of bounds");
195 if (n == 0) {
196 /* find beginning of current byte sequence */
197 while (posi > 0 && iscontp(s + posi)) posi--;
198 }
199 else {
200 if (iscontp(s + posi))
201 return luaL_error(L, "initial position is a continuation byte");
202 if (n < 0) {
203 while (n < 0 && posi > 0) { /* move back */
204 do { /* find beginning of previous character */
205 posi--;
206 } while (posi > 0 && iscontp(s + posi));
207 n++;
208 }
209 }
210 else {
211 n--; /* do not move for 1st character */
212 while (n > 0 && posi < (lua_Integer)len) {
213 do { /* find beginning of next character */
214 posi++;
215 } while (iscontp(s + posi)); /* (cannot pass final '\0') */
216 n--;
217 }
218 }
219 }
220 if (n == 0) /* did it find given character? */
221 lua_pushinteger(L, posi + 1);
222 else /* no such character */
223 luaL_pushfail(L);
224 return 1;
225}
226
227
228static int iter_aux (lua_State *L, int strict) {
229 size_t len;
230 const char *s = luaL_checklstring(L, 1, &len);
231 lua_Unsigned n = (lua_Unsigned)lua_tointeger(L, 2);
232 if (n < len) {
233 while (iscontp(s + n)) n++; /* go to next character */
234 }
235 if (n >= len) /* (also handles original 'n' being negative) */
236 return 0; /* no more codepoints */
237 else {
238 utfint code;
239 const char *next = utf8_decode(s + n, &code, strict);
240 if (next == NULL || iscontp(next))
241 return luaL_error(L, MSGInvalid);
242 lua_pushinteger(L, n + 1);
243 lua_pushinteger(L, code);
244 return 2;
245 }
246}
247
248
249static int iter_auxstrict (lua_State *L) {
250 return iter_aux(L, 1);
251}
252
253static int iter_auxlax (lua_State *L) {
254 return iter_aux(L, 0);
255}
256
257
258static int iter_codes (lua_State *L) {
259 int lax = lua_toboolean(L, 2);
260 const char *s = luaL_checkstring(L, 1);
261 luaL_argcheck(L, !iscontp(s), 1, MSGInvalid);
262 lua_pushcfunction(L, lax ? iter_auxlax : iter_auxstrict);
263 lua_pushvalue(L, 1);
264 lua_pushinteger(L, 0);
265 return 3;
266}
267
268
269/* pattern to match a single UTF-8 character */
270#define UTF8PATT "[\0-\x7F\xC2-\xFD][\x80-\xBF]*"
271
272
273static const luaL_Reg funcs[] = {
274 {"offset", byteoffset},
275 {"codepoint", codepoint},
276 {"char", utfchar},
277 {"len", utflen},
278 {"codes", iter_codes},
279 /* placeholders */
280 {"charpattern", NULL},
281 {NULL, NULL}
282};
283
284
285LUAMOD_API int luaopen_utf8 (lua_State *L) {
286 luaL_newlib(L, funcs);
287 lua_pushlstring(L, UTF8PATT, sizeof(UTF8PATT)/sizeof(char) - 1);
288 lua_setfield(L, -2, "charpattern");
289 return 1;
290}
291
diff --git a/vendor/lua-5.4.8/src/lvm.c b/vendor/lua-5.4.8/src/lvm.c
new file mode 100644
index 0000000..7023a04
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lvm.c
@@ -0,0 +1,1902 @@
1/*
2** $Id: lvm.c $
3** Lua virtual machine
4** See Copyright Notice in lua.h
5*/
6
7#define lvm_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12#include <float.h>
13#include <limits.h>
14#include <math.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18
19#include "lua.h"
20
21#include "ldebug.h"
22#include "ldo.h"
23#include "lfunc.h"
24#include "lgc.h"
25#include "lobject.h"
26#include "lopcodes.h"
27#include "lstate.h"
28#include "lstring.h"
29#include "ltable.h"
30#include "ltm.h"
31#include "lvm.h"
32
33
34/*
35** By default, use jump tables in the main interpreter loop on gcc
36** and compatible compilers.
37*/
38#if !defined(LUA_USE_JUMPTABLE)
39#if defined(__GNUC__)
40#define LUA_USE_JUMPTABLE 1
41#else
42#define LUA_USE_JUMPTABLE 0
43#endif
44#endif
45
46
47
48/* limit for table tag-method chains (to avoid infinite loops) */
49#define MAXTAGLOOP 2000
50
51
52/*
53** 'l_intfitsf' checks whether a given integer is in the range that
54** can be converted to a float without rounding. Used in comparisons.
55*/
56
57/* number of bits in the mantissa of a float */
58#define NBM (l_floatatt(MANT_DIG))
59
60/*
61** Check whether some integers may not fit in a float, testing whether
62** (maxinteger >> NBM) > 0. (That implies (1 << NBM) <= maxinteger.)
63** (The shifts are done in parts, to avoid shifting by more than the size
64** of an integer. In a worst case, NBM == 113 for long double and
65** sizeof(long) == 32.)
66*/
67#if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \
68 >> (NBM - (3 * (NBM / 4)))) > 0
69
70/* limit for integers that fit in a float */
71#define MAXINTFITSF ((lua_Unsigned)1 << NBM)
72
73/* check whether 'i' is in the interval [-MAXINTFITSF, MAXINTFITSF] */
74#define l_intfitsf(i) ((MAXINTFITSF + l_castS2U(i)) <= (2 * MAXINTFITSF))
75
76#else /* all integers fit in a float precisely */
77
78#define l_intfitsf(i) 1
79
80#endif
81
82
83/*
84** Try to convert a value from string to a number value.
85** If the value is not a string or is a string not representing
86** a valid numeral (or if coercions from strings to numbers
87** are disabled via macro 'cvt2num'), do not modify 'result'
88** and return 0.
89*/
90static int l_strton (const TValue *obj, TValue *result) {
91 lua_assert(obj != result);
92 if (!cvt2num(obj)) /* is object not a string? */
93 return 0;
94 else {
95 TString *st = tsvalue(obj);
96 return (luaO_str2num(getstr(st), result) == tsslen(st) + 1);
97 }
98}
99
100
101/*
102** Try to convert a value to a float. The float case is already handled
103** by the macro 'tonumber'.
104*/
105int luaV_tonumber_ (const TValue *obj, lua_Number *n) {
106 TValue v;
107 if (ttisinteger(obj)) {
108 *n = cast_num(ivalue(obj));
109 return 1;
110 }
111 else if (l_strton(obj, &v)) { /* string coercible to number? */
112 *n = nvalue(&v); /* convert result of 'luaO_str2num' to a float */
113 return 1;
114 }
115 else
116 return 0; /* conversion failed */
117}
118
119
120/*
121** try to convert a float to an integer, rounding according to 'mode'.
122*/
123int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode) {
124 lua_Number f = l_floor(n);
125 if (n != f) { /* not an integral value? */
126 if (mode == F2Ieq) return 0; /* fails if mode demands integral value */
127 else if (mode == F2Iceil) /* needs ceil? */
128 f += 1; /* convert floor to ceil (remember: n != f) */
129 }
130 return lua_numbertointeger(f, p);
131}
132
133
134/*
135** try to convert a value to an integer, rounding according to 'mode',
136** without string coercion.
137** ("Fast track" handled by macro 'tointegerns'.)
138*/
139int luaV_tointegerns (const TValue *obj, lua_Integer *p, F2Imod mode) {
140 if (ttisfloat(obj))
141 return luaV_flttointeger(fltvalue(obj), p, mode);
142 else if (ttisinteger(obj)) {
143 *p = ivalue(obj);
144 return 1;
145 }
146 else
147 return 0;
148}
149
150
151/*
152** try to convert a value to an integer.
153*/
154int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode) {
155 TValue v;
156 if (l_strton(obj, &v)) /* does 'obj' point to a numerical string? */
157 obj = &v; /* change it to point to its corresponding number */
158 return luaV_tointegerns(obj, p, mode);
159}
160
161
162/*
163** Try to convert a 'for' limit to an integer, preserving the semantics
164** of the loop. Return true if the loop must not run; otherwise, '*p'
165** gets the integer limit.
166** (The following explanation assumes a positive step; it is valid for
167** negative steps mutatis mutandis.)
168** If the limit is an integer or can be converted to an integer,
169** rounding down, that is the limit.
170** Otherwise, check whether the limit can be converted to a float. If
171** the float is too large, clip it to LUA_MAXINTEGER. If the float
172** is too negative, the loop should not run, because any initial
173** integer value is greater than such limit; so, the function returns
174** true to signal that. (For this latter case, no integer limit would be
175** correct; even a limit of LUA_MININTEGER would run the loop once for
176** an initial value equal to LUA_MININTEGER.)
177*/
178static int forlimit (lua_State *L, lua_Integer init, const TValue *lim,
179 lua_Integer *p, lua_Integer step) {
180 if (!luaV_tointeger(lim, p, (step < 0 ? F2Iceil : F2Ifloor))) {
181 /* not coercible to in integer */
182 lua_Number flim; /* try to convert to float */
183 if (!tonumber(lim, &flim)) /* cannot convert to float? */
184 luaG_forerror(L, lim, "limit");
185 /* else 'flim' is a float out of integer bounds */
186 if (luai_numlt(0, flim)) { /* if it is positive, it is too large */
187 if (step < 0) return 1; /* initial value must be less than it */
188 *p = LUA_MAXINTEGER; /* truncate */
189 }
190 else { /* it is less than min integer */
191 if (step > 0) return 1; /* initial value must be greater than it */
192 *p = LUA_MININTEGER; /* truncate */
193 }
194 }
195 return (step > 0 ? init > *p : init < *p); /* not to run? */
196}
197
198
199/*
200** Prepare a numerical for loop (opcode OP_FORPREP).
201** Return true to skip the loop. Otherwise,
202** after preparation, stack will be as follows:
203** ra : internal index (safe copy of the control variable)
204** ra + 1 : loop counter (integer loops) or limit (float loops)
205** ra + 2 : step
206** ra + 3 : control variable
207*/
208static int forprep (lua_State *L, StkId ra) {
209 TValue *pinit = s2v(ra);
210 TValue *plimit = s2v(ra + 1);
211 TValue *pstep = s2v(ra + 2);
212 if (ttisinteger(pinit) && ttisinteger(pstep)) { /* integer loop? */
213 lua_Integer init = ivalue(pinit);
214 lua_Integer step = ivalue(pstep);
215 lua_Integer limit;
216 if (step == 0)
217 luaG_runerror(L, "'for' step is zero");
218 setivalue(s2v(ra + 3), init); /* control variable */
219 if (forlimit(L, init, plimit, &limit, step))
220 return 1; /* skip the loop */
221 else { /* prepare loop counter */
222 lua_Unsigned count;
223 if (step > 0) { /* ascending loop? */
224 count = l_castS2U(limit) - l_castS2U(init);
225 if (step != 1) /* avoid division in the too common case */
226 count /= l_castS2U(step);
227 }
228 else { /* step < 0; descending loop */
229 count = l_castS2U(init) - l_castS2U(limit);
230 /* 'step+1' avoids negating 'mininteger' */
231 count /= l_castS2U(-(step + 1)) + 1u;
232 }
233 /* store the counter in place of the limit (which won't be
234 needed anymore) */
235 setivalue(plimit, l_castU2S(count));
236 }
237 }
238 else { /* try making all values floats */
239 lua_Number init; lua_Number limit; lua_Number step;
240 if (l_unlikely(!tonumber(plimit, &limit)))
241 luaG_forerror(L, plimit, "limit");
242 if (l_unlikely(!tonumber(pstep, &step)))
243 luaG_forerror(L, pstep, "step");
244 if (l_unlikely(!tonumber(pinit, &init)))
245 luaG_forerror(L, pinit, "initial value");
246 if (step == 0)
247 luaG_runerror(L, "'for' step is zero");
248 if (luai_numlt(0, step) ? luai_numlt(limit, init)
249 : luai_numlt(init, limit))
250 return 1; /* skip the loop */
251 else {
252 /* make sure internal values are all floats */
253 setfltvalue(plimit, limit);
254 setfltvalue(pstep, step);
255 setfltvalue(s2v(ra), init); /* internal index */
256 setfltvalue(s2v(ra + 3), init); /* control variable */
257 }
258 }
259 return 0;
260}
261
262
263/*
264** Execute a step of a float numerical for loop, returning
265** true iff the loop must continue. (The integer case is
266** written online with opcode OP_FORLOOP, for performance.)
267*/
268static int floatforloop (StkId ra) {
269 lua_Number step = fltvalue(s2v(ra + 2));
270 lua_Number limit = fltvalue(s2v(ra + 1));
271 lua_Number idx = fltvalue(s2v(ra)); /* internal index */
272 idx = luai_numadd(L, idx, step); /* increment index */
273 if (luai_numlt(0, step) ? luai_numle(idx, limit)
274 : luai_numle(limit, idx)) {
275 chgfltvalue(s2v(ra), idx); /* update internal index */
276 setfltvalue(s2v(ra + 3), idx); /* and control variable */
277 return 1; /* jump back */
278 }
279 else
280 return 0; /* finish the loop */
281}
282
283
284/*
285** Finish the table access 'val = t[key]'.
286** if 'slot' is NULL, 't' is not a table; otherwise, 'slot' points to
287** t[k] entry (which must be empty).
288*/
289void luaV_finishget (lua_State *L, const TValue *t, TValue *key, StkId val,
290 const TValue *slot) {
291 int loop; /* counter to avoid infinite loops */
292 const TValue *tm; /* metamethod */
293 for (loop = 0; loop < MAXTAGLOOP; loop++) {
294 if (slot == NULL) { /* 't' is not a table? */
295 lua_assert(!ttistable(t));
296 tm = luaT_gettmbyobj(L, t, TM_INDEX);
297 if (l_unlikely(notm(tm)))
298 luaG_typeerror(L, t, "index"); /* no metamethod */
299 /* else will try the metamethod */
300 }
301 else { /* 't' is a table */
302 lua_assert(isempty(slot));
303 tm = fasttm(L, hvalue(t)->metatable, TM_INDEX); /* table's metamethod */
304 if (tm == NULL) { /* no metamethod? */
305 setnilvalue(s2v(val)); /* result is nil */
306 return;
307 }
308 /* else will try the metamethod */
309 }
310 if (ttisfunction(tm)) { /* is metamethod a function? */
311 luaT_callTMres(L, tm, t, key, val); /* call it */
312 return;
313 }
314 t = tm; /* else try to access 'tm[key]' */
315 if (luaV_fastget(L, t, key, slot, luaH_get)) { /* fast track? */
316 setobj2s(L, val, slot); /* done */
317 return;
318 }
319 /* else repeat (tail call 'luaV_finishget') */
320 }
321 luaG_runerror(L, "'__index' chain too long; possible loop");
322}
323
324
325/*
326** Finish a table assignment 't[key] = val'.
327** If 'slot' is NULL, 't' is not a table. Otherwise, 'slot' points
328** to the entry 't[key]', or to a value with an absent key if there
329** is no such entry. (The value at 'slot' must be empty, otherwise
330** 'luaV_fastget' would have done the job.)
331*/
332void luaV_finishset (lua_State *L, const TValue *t, TValue *key,
333 TValue *val, const TValue *slot) {
334 int loop; /* counter to avoid infinite loops */
335 for (loop = 0; loop < MAXTAGLOOP; loop++) {
336 const TValue *tm; /* '__newindex' metamethod */
337 if (slot != NULL) { /* is 't' a table? */
338 Table *h = hvalue(t); /* save 't' table */
339 lua_assert(isempty(slot)); /* slot must be empty */
340 tm = fasttm(L, h->metatable, TM_NEWINDEX); /* get metamethod */
341 if (tm == NULL) { /* no metamethod? */
342 sethvalue2s(L, L->top.p, h); /* anchor 't' */
343 L->top.p++; /* assume EXTRA_STACK */
344 luaH_finishset(L, h, key, slot, val); /* set new value */
345 L->top.p--;
346 invalidateTMcache(h);
347 luaC_barrierback(L, obj2gco(h), val);
348 return;
349 }
350 /* else will try the metamethod */
351 }
352 else { /* not a table; check metamethod */
353 tm = luaT_gettmbyobj(L, t, TM_NEWINDEX);
354 if (l_unlikely(notm(tm)))
355 luaG_typeerror(L, t, "index");
356 }
357 /* try the metamethod */
358 if (ttisfunction(tm)) {
359 luaT_callTM(L, tm, t, key, val);
360 return;
361 }
362 t = tm; /* else repeat assignment over 'tm' */
363 if (luaV_fastget(L, t, key, slot, luaH_get)) {
364 luaV_finishfastset(L, t, slot, val);
365 return; /* done */
366 }
367 /* else 'return luaV_finishset(L, t, key, val, slot)' (loop) */
368 }
369 luaG_runerror(L, "'__newindex' chain too long; possible loop");
370}
371
372
373/*
374** Compare two strings 'ts1' x 'ts2', returning an integer less-equal-
375** -greater than zero if 'ts1' is less-equal-greater than 'ts2'.
376** The code is a little tricky because it allows '\0' in the strings
377** and it uses 'strcoll' (to respect locales) for each segment
378** of the strings. Note that segments can compare equal but still
379** have different lengths.
380*/
381static int l_strcmp (const TString *ts1, const TString *ts2) {
382 const char *s1 = getstr(ts1);
383 size_t rl1 = tsslen(ts1); /* real length */
384 const char *s2 = getstr(ts2);
385 size_t rl2 = tsslen(ts2);
386 for (;;) { /* for each segment */
387 int temp = strcoll(s1, s2);
388 if (temp != 0) /* not equal? */
389 return temp; /* done */
390 else { /* strings are equal up to a '\0' */
391 size_t zl1 = strlen(s1); /* index of first '\0' in 's1' */
392 size_t zl2 = strlen(s2); /* index of first '\0' in 's2' */
393 if (zl2 == rl2) /* 's2' is finished? */
394 return (zl1 == rl1) ? 0 : 1; /* check 's1' */
395 else if (zl1 == rl1) /* 's1' is finished? */
396 return -1; /* 's1' is less than 's2' ('s2' is not finished) */
397 /* both strings longer than 'zl'; go on comparing after the '\0' */
398 zl1++; zl2++;
399 s1 += zl1; rl1 -= zl1; s2 += zl2; rl2 -= zl2;
400 }
401 }
402}
403
404
405/*
406** Check whether integer 'i' is less than float 'f'. If 'i' has an
407** exact representation as a float ('l_intfitsf'), compare numbers as
408** floats. Otherwise, use the equivalence 'i < f <=> i < ceil(f)'.
409** If 'ceil(f)' is out of integer range, either 'f' is greater than
410** all integers or less than all integers.
411** (The test with 'l_intfitsf' is only for performance; the else
412** case is correct for all values, but it is slow due to the conversion
413** from float to int.)
414** When 'f' is NaN, comparisons must result in false.
415*/
416l_sinline int LTintfloat (lua_Integer i, lua_Number f) {
417 if (l_intfitsf(i))
418 return luai_numlt(cast_num(i), f); /* compare them as floats */
419 else { /* i < f <=> i < ceil(f) */
420 lua_Integer fi;
421 if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */
422 return i < fi; /* compare them as integers */
423 else /* 'f' is either greater or less than all integers */
424 return f > 0; /* greater? */
425 }
426}
427
428
429/*
430** Check whether integer 'i' is less than or equal to float 'f'.
431** See comments on previous function.
432*/
433l_sinline int LEintfloat (lua_Integer i, lua_Number f) {
434 if (l_intfitsf(i))
435 return luai_numle(cast_num(i), f); /* compare them as floats */
436 else { /* i <= f <=> i <= floor(f) */
437 lua_Integer fi;
438 if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */
439 return i <= fi; /* compare them as integers */
440 else /* 'f' is either greater or less than all integers */
441 return f > 0; /* greater? */
442 }
443}
444
445
446/*
447** Check whether float 'f' is less than integer 'i'.
448** See comments on previous function.
449*/
450l_sinline int LTfloatint (lua_Number f, lua_Integer i) {
451 if (l_intfitsf(i))
452 return luai_numlt(f, cast_num(i)); /* compare them as floats */
453 else { /* f < i <=> floor(f) < i */
454 lua_Integer fi;
455 if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */
456 return fi < i; /* compare them as integers */
457 else /* 'f' is either greater or less than all integers */
458 return f < 0; /* less? */
459 }
460}
461
462
463/*
464** Check whether float 'f' is less than or equal to integer 'i'.
465** See comments on previous function.
466*/
467l_sinline int LEfloatint (lua_Number f, lua_Integer i) {
468 if (l_intfitsf(i))
469 return luai_numle(f, cast_num(i)); /* compare them as floats */
470 else { /* f <= i <=> ceil(f) <= i */
471 lua_Integer fi;
472 if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */
473 return fi <= i; /* compare them as integers */
474 else /* 'f' is either greater or less than all integers */
475 return f < 0; /* less? */
476 }
477}
478
479
480/*
481** Return 'l < r', for numbers.
482*/
483l_sinline int LTnum (const TValue *l, const TValue *r) {
484 lua_assert(ttisnumber(l) && ttisnumber(r));
485 if (ttisinteger(l)) {
486 lua_Integer li = ivalue(l);
487 if (ttisinteger(r))
488 return li < ivalue(r); /* both are integers */
489 else /* 'l' is int and 'r' is float */
490 return LTintfloat(li, fltvalue(r)); /* l < r ? */
491 }
492 else {
493 lua_Number lf = fltvalue(l); /* 'l' must be float */
494 if (ttisfloat(r))
495 return luai_numlt(lf, fltvalue(r)); /* both are float */
496 else /* 'l' is float and 'r' is int */
497 return LTfloatint(lf, ivalue(r));
498 }
499}
500
501
502/*
503** Return 'l <= r', for numbers.
504*/
505l_sinline int LEnum (const TValue *l, const TValue *r) {
506 lua_assert(ttisnumber(l) && ttisnumber(r));
507 if (ttisinteger(l)) {
508 lua_Integer li = ivalue(l);
509 if (ttisinteger(r))
510 return li <= ivalue(r); /* both are integers */
511 else /* 'l' is int and 'r' is float */
512 return LEintfloat(li, fltvalue(r)); /* l <= r ? */
513 }
514 else {
515 lua_Number lf = fltvalue(l); /* 'l' must be float */
516 if (ttisfloat(r))
517 return luai_numle(lf, fltvalue(r)); /* both are float */
518 else /* 'l' is float and 'r' is int */
519 return LEfloatint(lf, ivalue(r));
520 }
521}
522
523
524/*
525** return 'l < r' for non-numbers.
526*/
527static int lessthanothers (lua_State *L, const TValue *l, const TValue *r) {
528 lua_assert(!ttisnumber(l) || !ttisnumber(r));
529 if (ttisstring(l) && ttisstring(r)) /* both are strings? */
530 return l_strcmp(tsvalue(l), tsvalue(r)) < 0;
531 else
532 return luaT_callorderTM(L, l, r, TM_LT);
533}
534
535
536/*
537** Main operation less than; return 'l < r'.
538*/
539int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
540 if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */
541 return LTnum(l, r);
542 else return lessthanothers(L, l, r);
543}
544
545
546/*
547** return 'l <= r' for non-numbers.
548*/
549static int lessequalothers (lua_State *L, const TValue *l, const TValue *r) {
550 lua_assert(!ttisnumber(l) || !ttisnumber(r));
551 if (ttisstring(l) && ttisstring(r)) /* both are strings? */
552 return l_strcmp(tsvalue(l), tsvalue(r)) <= 0;
553 else
554 return luaT_callorderTM(L, l, r, TM_LE);
555}
556
557
558/*
559** Main operation less than or equal to; return 'l <= r'.
560*/
561int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {
562 if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */
563 return LEnum(l, r);
564 else return lessequalothers(L, l, r);
565}
566
567
568/*
569** Main operation for equality of Lua values; return 't1 == t2'.
570** L == NULL means raw equality (no metamethods)
571*/
572int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) {
573 const TValue *tm;
574 if (ttypetag(t1) != ttypetag(t2)) { /* not the same variant? */
575 if (ttype(t1) != ttype(t2) || ttype(t1) != LUA_TNUMBER)
576 return 0; /* only numbers can be equal with different variants */
577 else { /* two numbers with different variants */
578 /* One of them is an integer. If the other does not have an
579 integer value, they cannot be equal; otherwise, compare their
580 integer values. */
581 lua_Integer i1, i2;
582 return (luaV_tointegerns(t1, &i1, F2Ieq) &&
583 luaV_tointegerns(t2, &i2, F2Ieq) &&
584 i1 == i2);
585 }
586 }
587 /* values have same type and same variant */
588 switch (ttypetag(t1)) {
589 case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE: return 1;
590 case LUA_VNUMINT: return (ivalue(t1) == ivalue(t2));
591 case LUA_VNUMFLT: return luai_numeq(fltvalue(t1), fltvalue(t2));
592 case LUA_VLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
593 case LUA_VLCF: return fvalue(t1) == fvalue(t2);
594 case LUA_VSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2));
595 case LUA_VLNGSTR: return luaS_eqlngstr(tsvalue(t1), tsvalue(t2));
596 case LUA_VUSERDATA: {
597 if (uvalue(t1) == uvalue(t2)) return 1;
598 else if (L == NULL) return 0;
599 tm = fasttm(L, uvalue(t1)->metatable, TM_EQ);
600 if (tm == NULL)
601 tm = fasttm(L, uvalue(t2)->metatable, TM_EQ);
602 break; /* will try TM */
603 }
604 case LUA_VTABLE: {
605 if (hvalue(t1) == hvalue(t2)) return 1;
606 else if (L == NULL) return 0;
607 tm = fasttm(L, hvalue(t1)->metatable, TM_EQ);
608 if (tm == NULL)
609 tm = fasttm(L, hvalue(t2)->metatable, TM_EQ);
610 break; /* will try TM */
611 }
612 default:
613 return gcvalue(t1) == gcvalue(t2);
614 }
615 if (tm == NULL) /* no TM? */
616 return 0; /* objects are different */
617 else {
618 luaT_callTMres(L, tm, t1, t2, L->top.p); /* call TM */
619 return !l_isfalse(s2v(L->top.p));
620 }
621}
622
623
624/* macro used by 'luaV_concat' to ensure that element at 'o' is a string */
625#define tostring(L,o) \
626 (ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1)))
627
628#define isemptystr(o) (ttisshrstring(o) && tsvalue(o)->shrlen == 0)
629
630/* copy strings in stack from top - n up to top - 1 to buffer */
631static void copy2buff (StkId top, int n, char *buff) {
632 size_t tl = 0; /* size already copied */
633 do {
634 TString *st = tsvalue(s2v(top - n));
635 size_t l = tsslen(st); /* length of string being copied */
636 memcpy(buff + tl, getstr(st), l * sizeof(char));
637 tl += l;
638 } while (--n > 0);
639}
640
641
642/*
643** Main operation for concatenation: concat 'total' values in the stack,
644** from 'L->top.p - total' up to 'L->top.p - 1'.
645*/
646void luaV_concat (lua_State *L, int total) {
647 if (total == 1)
648 return; /* "all" values already concatenated */
649 do {
650 StkId top = L->top.p;
651 int n = 2; /* number of elements handled in this pass (at least 2) */
652 if (!(ttisstring(s2v(top - 2)) || cvt2str(s2v(top - 2))) ||
653 !tostring(L, s2v(top - 1)))
654 luaT_tryconcatTM(L); /* may invalidate 'top' */
655 else if (isemptystr(s2v(top - 1))) /* second operand is empty? */
656 cast_void(tostring(L, s2v(top - 2))); /* result is first operand */
657 else if (isemptystr(s2v(top - 2))) { /* first operand is empty string? */
658 setobjs2s(L, top - 2, top - 1); /* result is second op. */
659 }
660 else {
661 /* at least two non-empty string values; get as many as possible */
662 size_t tl = tsslen(tsvalue(s2v(top - 1)));
663 TString *ts;
664 /* collect total length and number of strings */
665 for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) {
666 size_t l = tsslen(tsvalue(s2v(top - n - 1)));
667 if (l_unlikely(l >= MAX_SIZE - sizeof(TString) - tl)) {
668 L->top.p = top - total; /* pop strings to avoid wasting stack */
669 luaG_runerror(L, "string length overflow");
670 }
671 tl += l;
672 }
673 if (tl <= LUAI_MAXSHORTLEN) { /* is result a short string? */
674 char buff[LUAI_MAXSHORTLEN];
675 copy2buff(top, n, buff); /* copy strings to buffer */
676 ts = luaS_newlstr(L, buff, tl);
677 }
678 else { /* long string; copy strings directly to final result */
679 ts = luaS_createlngstrobj(L, tl);
680 copy2buff(top, n, getlngstr(ts));
681 }
682 setsvalue2s(L, top - n, ts); /* create result */
683 }
684 total -= n - 1; /* got 'n' strings to create one new */
685 L->top.p -= n - 1; /* popped 'n' strings and pushed one */
686 } while (total > 1); /* repeat until only 1 result left */
687}
688
689
690/*
691** Main operation 'ra = #rb'.
692*/
693void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
694 const TValue *tm;
695 switch (ttypetag(rb)) {
696 case LUA_VTABLE: {
697 Table *h = hvalue(rb);
698 tm = fasttm(L, h->metatable, TM_LEN);
699 if (tm) break; /* metamethod? break switch to call it */
700 setivalue(s2v(ra), luaH_getn(h)); /* else primitive len */
701 return;
702 }
703 case LUA_VSHRSTR: {
704 setivalue(s2v(ra), tsvalue(rb)->shrlen);
705 return;
706 }
707 case LUA_VLNGSTR: {
708 setivalue(s2v(ra), tsvalue(rb)->u.lnglen);
709 return;
710 }
711 default: { /* try metamethod */
712 tm = luaT_gettmbyobj(L, rb, TM_LEN);
713 if (l_unlikely(notm(tm))) /* no metamethod? */
714 luaG_typeerror(L, rb, "get length of");
715 break;
716 }
717 }
718 luaT_callTMres(L, tm, rb, rb, ra);
719}
720
721
722/*
723** Integer division; return 'm // n', that is, floor(m/n).
724** C division truncates its result (rounds towards zero).
725** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer,
726** otherwise 'floor(q) == trunc(q) - 1'.
727*/
728lua_Integer luaV_idiv (lua_State *L, lua_Integer m, lua_Integer n) {
729 if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */
730 if (n == 0)
731 luaG_runerror(L, "attempt to divide by zero");
732 return intop(-, 0, m); /* n==-1; avoid overflow with 0x80000...//-1 */
733 }
734 else {
735 lua_Integer q = m / n; /* perform C division */
736 if ((m ^ n) < 0 && m % n != 0) /* 'm/n' would be negative non-integer? */
737 q -= 1; /* correct result for different rounding */
738 return q;
739 }
740}
741
742
743/*
744** Integer modulus; return 'm % n'. (Assume that C '%' with
745** negative operands follows C99 behavior. See previous comment
746** about luaV_idiv.)
747*/
748lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) {
749 if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */
750 if (n == 0)
751 luaG_runerror(L, "attempt to perform 'n%%0'");
752 return 0; /* m % -1 == 0; avoid overflow with 0x80000...%-1 */
753 }
754 else {
755 lua_Integer r = m % n;
756 if (r != 0 && (r ^ n) < 0) /* 'm/n' would be non-integer negative? */
757 r += n; /* correct result for different rounding */
758 return r;
759 }
760}
761
762
763/*
764** Float modulus
765*/
766lua_Number luaV_modf (lua_State *L, lua_Number m, lua_Number n) {
767 lua_Number r;
768 luai_nummod(L, m, n, r);
769 return r;
770}
771
772
773/* number of bits in an integer */
774#define NBITS cast_int(sizeof(lua_Integer) * CHAR_BIT)
775
776
777/*
778** Shift left operation. (Shift right just negates 'y'.)
779*/
780lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) {
781 if (y < 0) { /* shift right? */
782 if (y <= -NBITS) return 0;
783 else return intop(>>, x, -y);
784 }
785 else { /* shift left */
786 if (y >= NBITS) return 0;
787 else return intop(<<, x, y);
788 }
789}
790
791
792/*
793** create a new Lua closure, push it in the stack, and initialize
794** its upvalues.
795*/
796static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
797 StkId ra) {
798 int nup = p->sizeupvalues;
799 Upvaldesc *uv = p->upvalues;
800 int i;
801 LClosure *ncl = luaF_newLclosure(L, nup);
802 ncl->p = p;
803 setclLvalue2s(L, ra, ncl); /* anchor new closure in stack */
804 for (i = 0; i < nup; i++) { /* fill in its upvalues */
805 if (uv[i].instack) /* upvalue refers to local variable? */
806 ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx);
807 else /* get upvalue from enclosing function */
808 ncl->upvals[i] = encup[uv[i].idx];
809 luaC_objbarrier(L, ncl, ncl->upvals[i]);
810 }
811}
812
813
814/*
815** finish execution of an opcode interrupted by a yield
816*/
817void luaV_finishOp (lua_State *L) {
818 CallInfo *ci = L->ci;
819 StkId base = ci->func.p + 1;
820 Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */
821 OpCode op = GET_OPCODE(inst);
822 switch (op) { /* finish its execution */
823 case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {
824 setobjs2s(L, base + GETARG_A(*(ci->u.l.savedpc - 2)), --L->top.p);
825 break;
826 }
827 case OP_UNM: case OP_BNOT: case OP_LEN:
828 case OP_GETTABUP: case OP_GETTABLE: case OP_GETI:
829 case OP_GETFIELD: case OP_SELF: {
830 setobjs2s(L, base + GETARG_A(inst), --L->top.p);
831 break;
832 }
833 case OP_LT: case OP_LE:
834 case OP_LTI: case OP_LEI:
835 case OP_GTI: case OP_GEI:
836 case OP_EQ: { /* note that 'OP_EQI'/'OP_EQK' cannot yield */
837 int res = !l_isfalse(s2v(L->top.p - 1));
838 L->top.p--;
839#if defined(LUA_COMPAT_LT_LE)
840 if (ci->callstatus & CIST_LEQ) { /* "<=" using "<" instead? */
841 ci->callstatus ^= CIST_LEQ; /* clear mark */
842 res = !res; /* negate result */
843 }
844#endif
845 lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP);
846 if (res != GETARG_k(inst)) /* condition failed? */
847 ci->u.l.savedpc++; /* skip jump instruction */
848 break;
849 }
850 case OP_CONCAT: {
851 StkId top = L->top.p - 1; /* top when 'luaT_tryconcatTM' was called */
852 int a = GETARG_A(inst); /* first element to concatenate */
853 int total = cast_int(top - 1 - (base + a)); /* yet to concatenate */
854 setobjs2s(L, top - 2, top); /* put TM result in proper position */
855 L->top.p = top - 1; /* top is one after last element (at top-2) */
856 luaV_concat(L, total); /* concat them (may yield again) */
857 break;
858 }
859 case OP_CLOSE: { /* yielded closing variables */
860 ci->u.l.savedpc--; /* repeat instruction to close other vars. */
861 break;
862 }
863 case OP_RETURN: { /* yielded closing variables */
864 StkId ra = base + GETARG_A(inst);
865 /* adjust top to signal correct number of returns, in case the
866 return is "up to top" ('isIT') */
867 L->top.p = ra + ci->u2.nres;
868 /* repeat instruction to close other vars. and complete the return */
869 ci->u.l.savedpc--;
870 break;
871 }
872 default: {
873 /* only these other opcodes can yield */
874 lua_assert(op == OP_TFORCALL || op == OP_CALL ||
875 op == OP_TAILCALL || op == OP_SETTABUP || op == OP_SETTABLE ||
876 op == OP_SETI || op == OP_SETFIELD);
877 break;
878 }
879 }
880}
881
882
883
884
885/*
886** {==================================================================
887** Macros for arithmetic/bitwise/comparison opcodes in 'luaV_execute'
888** ===================================================================
889*/
890
891#define l_addi(L,a,b) intop(+, a, b)
892#define l_subi(L,a,b) intop(-, a, b)
893#define l_muli(L,a,b) intop(*, a, b)
894#define l_band(a,b) intop(&, a, b)
895#define l_bor(a,b) intop(|, a, b)
896#define l_bxor(a,b) intop(^, a, b)
897
898#define l_lti(a,b) (a < b)
899#define l_lei(a,b) (a <= b)
900#define l_gti(a,b) (a > b)
901#define l_gei(a,b) (a >= b)
902
903
904/*
905** Arithmetic operations with immediate operands. 'iop' is the integer
906** operation, 'fop' is the float operation.
907*/
908#define op_arithI(L,iop,fop) { \
909 StkId ra = RA(i); \
910 TValue *v1 = vRB(i); \
911 int imm = GETARG_sC(i); \
912 if (ttisinteger(v1)) { \
913 lua_Integer iv1 = ivalue(v1); \
914 pc++; setivalue(s2v(ra), iop(L, iv1, imm)); \
915 } \
916 else if (ttisfloat(v1)) { \
917 lua_Number nb = fltvalue(v1); \
918 lua_Number fimm = cast_num(imm); \
919 pc++; setfltvalue(s2v(ra), fop(L, nb, fimm)); \
920 }}
921
922
923/*
924** Auxiliary function for arithmetic operations over floats and others
925** with two register operands.
926*/
927#define op_arithf_aux(L,v1,v2,fop) { \
928 lua_Number n1; lua_Number n2; \
929 if (tonumberns(v1, n1) && tonumberns(v2, n2)) { \
930 pc++; setfltvalue(s2v(ra), fop(L, n1, n2)); \
931 }}
932
933
934/*
935** Arithmetic operations over floats and others with register operands.
936*/
937#define op_arithf(L,fop) { \
938 StkId ra = RA(i); \
939 TValue *v1 = vRB(i); \
940 TValue *v2 = vRC(i); \
941 op_arithf_aux(L, v1, v2, fop); }
942
943
944/*
945** Arithmetic operations with K operands for floats.
946*/
947#define op_arithfK(L,fop) { \
948 StkId ra = RA(i); \
949 TValue *v1 = vRB(i); \
950 TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \
951 op_arithf_aux(L, v1, v2, fop); }
952
953
954/*
955** Arithmetic operations over integers and floats.
956*/
957#define op_arith_aux(L,v1,v2,iop,fop) { \
958 StkId ra = RA(i); \
959 if (ttisinteger(v1) && ttisinteger(v2)) { \
960 lua_Integer i1 = ivalue(v1); lua_Integer i2 = ivalue(v2); \
961 pc++; setivalue(s2v(ra), iop(L, i1, i2)); \
962 } \
963 else op_arithf_aux(L, v1, v2, fop); }
964
965
966/*
967** Arithmetic operations with register operands.
968*/
969#define op_arith(L,iop,fop) { \
970 TValue *v1 = vRB(i); \
971 TValue *v2 = vRC(i); \
972 op_arith_aux(L, v1, v2, iop, fop); }
973
974
975/*
976** Arithmetic operations with K operands.
977*/
978#define op_arithK(L,iop,fop) { \
979 TValue *v1 = vRB(i); \
980 TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \
981 op_arith_aux(L, v1, v2, iop, fop); }
982
983
984/*
985** Bitwise operations with constant operand.
986*/
987#define op_bitwiseK(L,op) { \
988 StkId ra = RA(i); \
989 TValue *v1 = vRB(i); \
990 TValue *v2 = KC(i); \
991 lua_Integer i1; \
992 lua_Integer i2 = ivalue(v2); \
993 if (tointegerns(v1, &i1)) { \
994 pc++; setivalue(s2v(ra), op(i1, i2)); \
995 }}
996
997
998/*
999** Bitwise operations with register operands.
1000*/
1001#define op_bitwise(L,op) { \
1002 StkId ra = RA(i); \
1003 TValue *v1 = vRB(i); \
1004 TValue *v2 = vRC(i); \
1005 lua_Integer i1; lua_Integer i2; \
1006 if (tointegerns(v1, &i1) && tointegerns(v2, &i2)) { \
1007 pc++; setivalue(s2v(ra), op(i1, i2)); \
1008 }}
1009
1010
1011/*
1012** Order operations with register operands. 'opn' actually works
1013** for all numbers, but the fast track improves performance for
1014** integers.
1015*/
1016#define op_order(L,opi,opn,other) { \
1017 StkId ra = RA(i); \
1018 int cond; \
1019 TValue *rb = vRB(i); \
1020 if (ttisinteger(s2v(ra)) && ttisinteger(rb)) { \
1021 lua_Integer ia = ivalue(s2v(ra)); \
1022 lua_Integer ib = ivalue(rb); \
1023 cond = opi(ia, ib); \
1024 } \
1025 else if (ttisnumber(s2v(ra)) && ttisnumber(rb)) \
1026 cond = opn(s2v(ra), rb); \
1027 else \
1028 Protect(cond = other(L, s2v(ra), rb)); \
1029 docondjump(); }
1030
1031
1032/*
1033** Order operations with immediate operand. (Immediate operand is
1034** always small enough to have an exact representation as a float.)
1035*/
1036#define op_orderI(L,opi,opf,inv,tm) { \
1037 StkId ra = RA(i); \
1038 int cond; \
1039 int im = GETARG_sB(i); \
1040 if (ttisinteger(s2v(ra))) \
1041 cond = opi(ivalue(s2v(ra)), im); \
1042 else if (ttisfloat(s2v(ra))) { \
1043 lua_Number fa = fltvalue(s2v(ra)); \
1044 lua_Number fim = cast_num(im); \
1045 cond = opf(fa, fim); \
1046 } \
1047 else { \
1048 int isf = GETARG_C(i); \
1049 Protect(cond = luaT_callorderiTM(L, s2v(ra), im, inv, isf, tm)); \
1050 } \
1051 docondjump(); }
1052
1053/* }================================================================== */
1054
1055
1056/*
1057** {==================================================================
1058** Function 'luaV_execute': main interpreter loop
1059** ===================================================================
1060*/
1061
1062/*
1063** some macros for common tasks in 'luaV_execute'
1064*/
1065
1066
1067#define RA(i) (base+GETARG_A(i))
1068#define RB(i) (base+GETARG_B(i))
1069#define vRB(i) s2v(RB(i))
1070#define KB(i) (k+GETARG_B(i))
1071#define RC(i) (base+GETARG_C(i))
1072#define vRC(i) s2v(RC(i))
1073#define KC(i) (k+GETARG_C(i))
1074#define RKC(i) ((TESTARG_k(i)) ? k + GETARG_C(i) : s2v(base + GETARG_C(i)))
1075
1076
1077
1078#define updatetrap(ci) (trap = ci->u.l.trap)
1079
1080#define updatebase(ci) (base = ci->func.p + 1)
1081
1082
1083#define updatestack(ci) \
1084 { if (l_unlikely(trap)) { updatebase(ci); ra = RA(i); } }
1085
1086
1087/*
1088** Execute a jump instruction. The 'updatetrap' allows signals to stop
1089** tight loops. (Without it, the local copy of 'trap' could never change.)
1090*/
1091#define dojump(ci,i,e) { pc += GETARG_sJ(i) + e; updatetrap(ci); }
1092
1093
1094/* for test instructions, execute the jump instruction that follows it */
1095#define donextjump(ci) { Instruction ni = *pc; dojump(ci, ni, 1); }
1096
1097/*
1098** do a conditional jump: skip next instruction if 'cond' is not what
1099** was expected (parameter 'k'), else do next instruction, which must
1100** be a jump.
1101*/
1102#define docondjump() if (cond != GETARG_k(i)) pc++; else donextjump(ci);
1103
1104
1105/*
1106** Correct global 'pc'.
1107*/
1108#define savepc(L) (ci->u.l.savedpc = pc)
1109
1110
1111/*
1112** Whenever code can raise errors, the global 'pc' and the global
1113** 'top' must be correct to report occasional errors.
1114*/
1115#define savestate(L,ci) (savepc(L), L->top.p = ci->top.p)
1116
1117
1118/*
1119** Protect code that, in general, can raise errors, reallocate the
1120** stack, and change the hooks.
1121*/
1122#define Protect(exp) (savestate(L,ci), (exp), updatetrap(ci))
1123
1124/* special version that does not change the top */
1125#define ProtectNT(exp) (savepc(L), (exp), updatetrap(ci))
1126
1127/*
1128** Protect code that can only raise errors. (That is, it cannot change
1129** the stack or hooks.)
1130*/
1131#define halfProtect(exp) (savestate(L,ci), (exp))
1132
1133/* 'c' is the limit of live values in the stack */
1134#define checkGC(L,c) \
1135 { luaC_condGC(L, (savepc(L), L->top.p = (c)), \
1136 updatetrap(ci)); \
1137 luai_threadyield(L); }
1138
1139
1140/* fetch an instruction and prepare its execution */
1141#define vmfetch() { \
1142 if (l_unlikely(trap)) { /* stack reallocation or hooks? */ \
1143 trap = luaG_traceexec(L, pc); /* handle hooks */ \
1144 updatebase(ci); /* correct stack */ \
1145 } \
1146 i = *(pc++); \
1147}
1148
1149#define vmdispatch(o) switch(o)
1150#define vmcase(l) case l:
1151#define vmbreak break
1152
1153
1154void luaV_execute (lua_State *L, CallInfo *ci) {
1155 LClosure *cl;
1156 TValue *k;
1157 StkId base;
1158 const Instruction *pc;
1159 int trap;
1160#if LUA_USE_JUMPTABLE
1161#include "ljumptab.h"
1162#endif
1163 startfunc:
1164 trap = L->hookmask;
1165 returning: /* trap already set */
1166 cl = ci_func(ci);
1167 k = cl->p->k;
1168 pc = ci->u.l.savedpc;
1169 if (l_unlikely(trap))
1170 trap = luaG_tracecall(L);
1171 base = ci->func.p + 1;
1172 /* main loop of interpreter */
1173 for (;;) {
1174 Instruction i; /* instruction being executed */
1175 vmfetch();
1176 #if 0
1177 /* low-level line tracing for debugging Lua */
1178 printf("line: %d\n", luaG_getfuncline(cl->p, pcRel(pc, cl->p)));
1179 #endif
1180 lua_assert(base == ci->func.p + 1);
1181 lua_assert(base <= L->top.p && L->top.p <= L->stack_last.p);
1182 /* invalidate top for instructions not expecting it */
1183 lua_assert(isIT(i) || (cast_void(L->top.p = base), 1));
1184 vmdispatch (GET_OPCODE(i)) {
1185 vmcase(OP_MOVE) {
1186 StkId ra = RA(i);
1187 setobjs2s(L, ra, RB(i));
1188 vmbreak;
1189 }
1190 vmcase(OP_LOADI) {
1191 StkId ra = RA(i);
1192 lua_Integer b = GETARG_sBx(i);
1193 setivalue(s2v(ra), b);
1194 vmbreak;
1195 }
1196 vmcase(OP_LOADF) {
1197 StkId ra = RA(i);
1198 int b = GETARG_sBx(i);
1199 setfltvalue(s2v(ra), cast_num(b));
1200 vmbreak;
1201 }
1202 vmcase(OP_LOADK) {
1203 StkId ra = RA(i);
1204 TValue *rb = k + GETARG_Bx(i);
1205 setobj2s(L, ra, rb);
1206 vmbreak;
1207 }
1208 vmcase(OP_LOADKX) {
1209 StkId ra = RA(i);
1210 TValue *rb;
1211 rb = k + GETARG_Ax(*pc); pc++;
1212 setobj2s(L, ra, rb);
1213 vmbreak;
1214 }
1215 vmcase(OP_LOADFALSE) {
1216 StkId ra = RA(i);
1217 setbfvalue(s2v(ra));
1218 vmbreak;
1219 }
1220 vmcase(OP_LFALSESKIP) {
1221 StkId ra = RA(i);
1222 setbfvalue(s2v(ra));
1223 pc++; /* skip next instruction */
1224 vmbreak;
1225 }
1226 vmcase(OP_LOADTRUE) {
1227 StkId ra = RA(i);
1228 setbtvalue(s2v(ra));
1229 vmbreak;
1230 }
1231 vmcase(OP_LOADNIL) {
1232 StkId ra = RA(i);
1233 int b = GETARG_B(i);
1234 do {
1235 setnilvalue(s2v(ra++));
1236 } while (b--);
1237 vmbreak;
1238 }
1239 vmcase(OP_GETUPVAL) {
1240 StkId ra = RA(i);
1241 int b = GETARG_B(i);
1242 setobj2s(L, ra, cl->upvals[b]->v.p);
1243 vmbreak;
1244 }
1245 vmcase(OP_SETUPVAL) {
1246 StkId ra = RA(i);
1247 UpVal *uv = cl->upvals[GETARG_B(i)];
1248 setobj(L, uv->v.p, s2v(ra));
1249 luaC_barrier(L, uv, s2v(ra));
1250 vmbreak;
1251 }
1252 vmcase(OP_GETTABUP) {
1253 StkId ra = RA(i);
1254 const TValue *slot;
1255 TValue *upval = cl->upvals[GETARG_B(i)]->v.p;
1256 TValue *rc = KC(i);
1257 TString *key = tsvalue(rc); /* key must be a short string */
1258 if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) {
1259 setobj2s(L, ra, slot);
1260 }
1261 else
1262 Protect(luaV_finishget(L, upval, rc, ra, slot));
1263 vmbreak;
1264 }
1265 vmcase(OP_GETTABLE) {
1266 StkId ra = RA(i);
1267 const TValue *slot;
1268 TValue *rb = vRB(i);
1269 TValue *rc = vRC(i);
1270 lua_Unsigned n;
1271 if (ttisinteger(rc) /* fast track for integers? */
1272 ? (cast_void(n = ivalue(rc)), luaV_fastgeti(L, rb, n, slot))
1273 : luaV_fastget(L, rb, rc, slot, luaH_get)) {
1274 setobj2s(L, ra, slot);
1275 }
1276 else
1277 Protect(luaV_finishget(L, rb, rc, ra, slot));
1278 vmbreak;
1279 }
1280 vmcase(OP_GETI) {
1281 StkId ra = RA(i);
1282 const TValue *slot;
1283 TValue *rb = vRB(i);
1284 int c = GETARG_C(i);
1285 if (luaV_fastgeti(L, rb, c, slot)) {
1286 setobj2s(L, ra, slot);
1287 }
1288 else {
1289 TValue key;
1290 setivalue(&key, c);
1291 Protect(luaV_finishget(L, rb, &key, ra, slot));
1292 }
1293 vmbreak;
1294 }
1295 vmcase(OP_GETFIELD) {
1296 StkId ra = RA(i);
1297 const TValue *slot;
1298 TValue *rb = vRB(i);
1299 TValue *rc = KC(i);
1300 TString *key = tsvalue(rc); /* key must be a short string */
1301 if (luaV_fastget(L, rb, key, slot, luaH_getshortstr)) {
1302 setobj2s(L, ra, slot);
1303 }
1304 else
1305 Protect(luaV_finishget(L, rb, rc, ra, slot));
1306 vmbreak;
1307 }
1308 vmcase(OP_SETTABUP) {
1309 const TValue *slot;
1310 TValue *upval = cl->upvals[GETARG_A(i)]->v.p;
1311 TValue *rb = KB(i);
1312 TValue *rc = RKC(i);
1313 TString *key = tsvalue(rb); /* key must be a short string */
1314 if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) {
1315 luaV_finishfastset(L, upval, slot, rc);
1316 }
1317 else
1318 Protect(luaV_finishset(L, upval, rb, rc, slot));
1319 vmbreak;
1320 }
1321 vmcase(OP_SETTABLE) {
1322 StkId ra = RA(i);
1323 const TValue *slot;
1324 TValue *rb = vRB(i); /* key (table is in 'ra') */
1325 TValue *rc = RKC(i); /* value */
1326 lua_Unsigned n;
1327 if (ttisinteger(rb) /* fast track for integers? */
1328 ? (cast_void(n = ivalue(rb)), luaV_fastgeti(L, s2v(ra), n, slot))
1329 : luaV_fastget(L, s2v(ra), rb, slot, luaH_get)) {
1330 luaV_finishfastset(L, s2v(ra), slot, rc);
1331 }
1332 else
1333 Protect(luaV_finishset(L, s2v(ra), rb, rc, slot));
1334 vmbreak;
1335 }
1336 vmcase(OP_SETI) {
1337 StkId ra = RA(i);
1338 const TValue *slot;
1339 int c = GETARG_B(i);
1340 TValue *rc = RKC(i);
1341 if (luaV_fastgeti(L, s2v(ra), c, slot)) {
1342 luaV_finishfastset(L, s2v(ra), slot, rc);
1343 }
1344 else {
1345 TValue key;
1346 setivalue(&key, c);
1347 Protect(luaV_finishset(L, s2v(ra), &key, rc, slot));
1348 }
1349 vmbreak;
1350 }
1351 vmcase(OP_SETFIELD) {
1352 StkId ra = RA(i);
1353 const TValue *slot;
1354 TValue *rb = KB(i);
1355 TValue *rc = RKC(i);
1356 TString *key = tsvalue(rb); /* key must be a short string */
1357 if (luaV_fastget(L, s2v(ra), key, slot, luaH_getshortstr)) {
1358 luaV_finishfastset(L, s2v(ra), slot, rc);
1359 }
1360 else
1361 Protect(luaV_finishset(L, s2v(ra), rb, rc, slot));
1362 vmbreak;
1363 }
1364 vmcase(OP_NEWTABLE) {
1365 StkId ra = RA(i);
1366 int b = GETARG_B(i); /* log2(hash size) + 1 */
1367 int c = GETARG_C(i); /* array size */
1368 Table *t;
1369 if (b > 0)
1370 b = 1 << (b - 1); /* size is 2^(b - 1) */
1371 lua_assert((!TESTARG_k(i)) == (GETARG_Ax(*pc) == 0));
1372 if (TESTARG_k(i)) /* non-zero extra argument? */
1373 c += GETARG_Ax(*pc) * (MAXARG_C + 1); /* add it to size */
1374 pc++; /* skip extra argument */
1375 L->top.p = ra + 1; /* correct top in case of emergency GC */
1376 t = luaH_new(L); /* memory allocation */
1377 sethvalue2s(L, ra, t);
1378 if (b != 0 || c != 0)
1379 luaH_resize(L, t, c, b); /* idem */
1380 checkGC(L, ra + 1);
1381 vmbreak;
1382 }
1383 vmcase(OP_SELF) {
1384 StkId ra = RA(i);
1385 const TValue *slot;
1386 TValue *rb = vRB(i);
1387 TValue *rc = RKC(i);
1388 TString *key = tsvalue(rc); /* key must be a string */
1389 setobj2s(L, ra + 1, rb);
1390 if (luaV_fastget(L, rb, key, slot, luaH_getstr)) {
1391 setobj2s(L, ra, slot);
1392 }
1393 else
1394 Protect(luaV_finishget(L, rb, rc, ra, slot));
1395 vmbreak;
1396 }
1397 vmcase(OP_ADDI) {
1398 op_arithI(L, l_addi, luai_numadd);
1399 vmbreak;
1400 }
1401 vmcase(OP_ADDK) {
1402 op_arithK(L, l_addi, luai_numadd);
1403 vmbreak;
1404 }
1405 vmcase(OP_SUBK) {
1406 op_arithK(L, l_subi, luai_numsub);
1407 vmbreak;
1408 }
1409 vmcase(OP_MULK) {
1410 op_arithK(L, l_muli, luai_nummul);
1411 vmbreak;
1412 }
1413 vmcase(OP_MODK) {
1414 savestate(L, ci); /* in case of division by 0 */
1415 op_arithK(L, luaV_mod, luaV_modf);
1416 vmbreak;
1417 }
1418 vmcase(OP_POWK) {
1419 op_arithfK(L, luai_numpow);
1420 vmbreak;
1421 }
1422 vmcase(OP_DIVK) {
1423 op_arithfK(L, luai_numdiv);
1424 vmbreak;
1425 }
1426 vmcase(OP_IDIVK) {
1427 savestate(L, ci); /* in case of division by 0 */
1428 op_arithK(L, luaV_idiv, luai_numidiv);
1429 vmbreak;
1430 }
1431 vmcase(OP_BANDK) {
1432 op_bitwiseK(L, l_band);
1433 vmbreak;
1434 }
1435 vmcase(OP_BORK) {
1436 op_bitwiseK(L, l_bor);
1437 vmbreak;
1438 }
1439 vmcase(OP_BXORK) {
1440 op_bitwiseK(L, l_bxor);
1441 vmbreak;
1442 }
1443 vmcase(OP_SHRI) {
1444 StkId ra = RA(i);
1445 TValue *rb = vRB(i);
1446 int ic = GETARG_sC(i);
1447 lua_Integer ib;
1448 if (tointegerns(rb, &ib)) {
1449 pc++; setivalue(s2v(ra), luaV_shiftl(ib, -ic));
1450 }
1451 vmbreak;
1452 }
1453 vmcase(OP_SHLI) {
1454 StkId ra = RA(i);
1455 TValue *rb = vRB(i);
1456 int ic = GETARG_sC(i);
1457 lua_Integer ib;
1458 if (tointegerns(rb, &ib)) {
1459 pc++; setivalue(s2v(ra), luaV_shiftl(ic, ib));
1460 }
1461 vmbreak;
1462 }
1463 vmcase(OP_ADD) {
1464 op_arith(L, l_addi, luai_numadd);
1465 vmbreak;
1466 }
1467 vmcase(OP_SUB) {
1468 op_arith(L, l_subi, luai_numsub);
1469 vmbreak;
1470 }
1471 vmcase(OP_MUL) {
1472 op_arith(L, l_muli, luai_nummul);
1473 vmbreak;
1474 }
1475 vmcase(OP_MOD) {
1476 savestate(L, ci); /* in case of division by 0 */
1477 op_arith(L, luaV_mod, luaV_modf);
1478 vmbreak;
1479 }
1480 vmcase(OP_POW) {
1481 op_arithf(L, luai_numpow);
1482 vmbreak;
1483 }
1484 vmcase(OP_DIV) { /* float division (always with floats) */
1485 op_arithf(L, luai_numdiv);
1486 vmbreak;
1487 }
1488 vmcase(OP_IDIV) { /* floor division */
1489 savestate(L, ci); /* in case of division by 0 */
1490 op_arith(L, luaV_idiv, luai_numidiv);
1491 vmbreak;
1492 }
1493 vmcase(OP_BAND) {
1494 op_bitwise(L, l_band);
1495 vmbreak;
1496 }
1497 vmcase(OP_BOR) {
1498 op_bitwise(L, l_bor);
1499 vmbreak;
1500 }
1501 vmcase(OP_BXOR) {
1502 op_bitwise(L, l_bxor);
1503 vmbreak;
1504 }
1505 vmcase(OP_SHR) {
1506 op_bitwise(L, luaV_shiftr);
1507 vmbreak;
1508 }
1509 vmcase(OP_SHL) {
1510 op_bitwise(L, luaV_shiftl);
1511 vmbreak;
1512 }
1513 vmcase(OP_MMBIN) {
1514 StkId ra = RA(i);
1515 Instruction pi = *(pc - 2); /* original arith. expression */
1516 TValue *rb = vRB(i);
1517 TMS tm = (TMS)GETARG_C(i);
1518 StkId result = RA(pi);
1519 lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR);
1520 Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm));
1521 vmbreak;
1522 }
1523 vmcase(OP_MMBINI) {
1524 StkId ra = RA(i);
1525 Instruction pi = *(pc - 2); /* original arith. expression */
1526 int imm = GETARG_sB(i);
1527 TMS tm = (TMS)GETARG_C(i);
1528 int flip = GETARG_k(i);
1529 StkId result = RA(pi);
1530 Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm));
1531 vmbreak;
1532 }
1533 vmcase(OP_MMBINK) {
1534 StkId ra = RA(i);
1535 Instruction pi = *(pc - 2); /* original arith. expression */
1536 TValue *imm = KB(i);
1537 TMS tm = (TMS)GETARG_C(i);
1538 int flip = GETARG_k(i);
1539 StkId result = RA(pi);
1540 Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm));
1541 vmbreak;
1542 }
1543 vmcase(OP_UNM) {
1544 StkId ra = RA(i);
1545 TValue *rb = vRB(i);
1546 lua_Number nb;
1547 if (ttisinteger(rb)) {
1548 lua_Integer ib = ivalue(rb);
1549 setivalue(s2v(ra), intop(-, 0, ib));
1550 }
1551 else if (tonumberns(rb, nb)) {
1552 setfltvalue(s2v(ra), luai_numunm(L, nb));
1553 }
1554 else
1555 Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));
1556 vmbreak;
1557 }
1558 vmcase(OP_BNOT) {
1559 StkId ra = RA(i);
1560 TValue *rb = vRB(i);
1561 lua_Integer ib;
1562 if (tointegerns(rb, &ib)) {
1563 setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib));
1564 }
1565 else
1566 Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));
1567 vmbreak;
1568 }
1569 vmcase(OP_NOT) {
1570 StkId ra = RA(i);
1571 TValue *rb = vRB(i);
1572 if (l_isfalse(rb))
1573 setbtvalue(s2v(ra));
1574 else
1575 setbfvalue(s2v(ra));
1576 vmbreak;
1577 }
1578 vmcase(OP_LEN) {
1579 StkId ra = RA(i);
1580 Protect(luaV_objlen(L, ra, vRB(i)));
1581 vmbreak;
1582 }
1583 vmcase(OP_CONCAT) {
1584 StkId ra = RA(i);
1585 int n = GETARG_B(i); /* number of elements to concatenate */
1586 L->top.p = ra + n; /* mark the end of concat operands */
1587 ProtectNT(luaV_concat(L, n));
1588 checkGC(L, L->top.p); /* 'luaV_concat' ensures correct top */
1589 vmbreak;
1590 }
1591 vmcase(OP_CLOSE) {
1592 StkId ra = RA(i);
1593 Protect(luaF_close(L, ra, LUA_OK, 1));
1594 vmbreak;
1595 }
1596 vmcase(OP_TBC) {
1597 StkId ra = RA(i);
1598 /* create new to-be-closed upvalue */
1599 halfProtect(luaF_newtbcupval(L, ra));
1600 vmbreak;
1601 }
1602 vmcase(OP_JMP) {
1603 dojump(ci, i, 0);
1604 vmbreak;
1605 }
1606 vmcase(OP_EQ) {
1607 StkId ra = RA(i);
1608 int cond;
1609 TValue *rb = vRB(i);
1610 Protect(cond = luaV_equalobj(L, s2v(ra), rb));
1611 docondjump();
1612 vmbreak;
1613 }
1614 vmcase(OP_LT) {
1615 op_order(L, l_lti, LTnum, lessthanothers);
1616 vmbreak;
1617 }
1618 vmcase(OP_LE) {
1619 op_order(L, l_lei, LEnum, lessequalothers);
1620 vmbreak;
1621 }
1622 vmcase(OP_EQK) {
1623 StkId ra = RA(i);
1624 TValue *rb = KB(i);
1625 /* basic types do not use '__eq'; we can use raw equality */
1626 int cond = luaV_rawequalobj(s2v(ra), rb);
1627 docondjump();
1628 vmbreak;
1629 }
1630 vmcase(OP_EQI) {
1631 StkId ra = RA(i);
1632 int cond;
1633 int im = GETARG_sB(i);
1634 if (ttisinteger(s2v(ra)))
1635 cond = (ivalue(s2v(ra)) == im);
1636 else if (ttisfloat(s2v(ra)))
1637 cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im));
1638 else
1639 cond = 0; /* other types cannot be equal to a number */
1640 docondjump();
1641 vmbreak;
1642 }
1643 vmcase(OP_LTI) {
1644 op_orderI(L, l_lti, luai_numlt, 0, TM_LT);
1645 vmbreak;
1646 }
1647 vmcase(OP_LEI) {
1648 op_orderI(L, l_lei, luai_numle, 0, TM_LE);
1649 vmbreak;
1650 }
1651 vmcase(OP_GTI) {
1652 op_orderI(L, l_gti, luai_numgt, 1, TM_LT);
1653 vmbreak;
1654 }
1655 vmcase(OP_GEI) {
1656 op_orderI(L, l_gei, luai_numge, 1, TM_LE);
1657 vmbreak;
1658 }
1659 vmcase(OP_TEST) {
1660 StkId ra = RA(i);
1661 int cond = !l_isfalse(s2v(ra));
1662 docondjump();
1663 vmbreak;
1664 }
1665 vmcase(OP_TESTSET) {
1666 StkId ra = RA(i);
1667 TValue *rb = vRB(i);
1668 if (l_isfalse(rb) == GETARG_k(i))
1669 pc++;
1670 else {
1671 setobj2s(L, ra, rb);
1672 donextjump(ci);
1673 }
1674 vmbreak;
1675 }
1676 vmcase(OP_CALL) {
1677 StkId ra = RA(i);
1678 CallInfo *newci;
1679 int b = GETARG_B(i);
1680 int nresults = GETARG_C(i) - 1;
1681 if (b != 0) /* fixed number of arguments? */
1682 L->top.p = ra + b; /* top signals number of arguments */
1683 /* else previous instruction set top */
1684 savepc(L); /* in case of errors */
1685 if ((newci = luaD_precall(L, ra, nresults)) == NULL)
1686 updatetrap(ci); /* C call; nothing else to be done */
1687 else { /* Lua call: run function in this same C frame */
1688 ci = newci;
1689 goto startfunc;
1690 }
1691 vmbreak;
1692 }
1693 vmcase(OP_TAILCALL) {
1694 StkId ra = RA(i);
1695 int b = GETARG_B(i); /* number of arguments + 1 (function) */
1696 int n; /* number of results when calling a C function */
1697 int nparams1 = GETARG_C(i);
1698 /* delta is virtual 'func' - real 'func' (vararg functions) */
1699 int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0;
1700 if (b != 0)
1701 L->top.p = ra + b;
1702 else /* previous instruction set top */
1703 b = cast_int(L->top.p - ra);
1704 savepc(ci); /* several calls here can raise errors */
1705 if (TESTARG_k(i)) {
1706 luaF_closeupval(L, base); /* close upvalues from current call */
1707 lua_assert(L->tbclist.p < base); /* no pending tbc variables */
1708 lua_assert(base == ci->func.p + 1);
1709 }
1710 if ((n = luaD_pretailcall(L, ci, ra, b, delta)) < 0) /* Lua function? */
1711 goto startfunc; /* execute the callee */
1712 else { /* C function? */
1713 ci->func.p -= delta; /* restore 'func' (if vararg) */
1714 luaD_poscall(L, ci, n); /* finish caller */
1715 updatetrap(ci); /* 'luaD_poscall' can change hooks */
1716 goto ret; /* caller returns after the tail call */
1717 }
1718 }
1719 vmcase(OP_RETURN) {
1720 StkId ra = RA(i);
1721 int n = GETARG_B(i) - 1; /* number of results */
1722 int nparams1 = GETARG_C(i);
1723 if (n < 0) /* not fixed? */
1724 n = cast_int(L->top.p - ra); /* get what is available */
1725 savepc(ci);
1726 if (TESTARG_k(i)) { /* may there be open upvalues? */
1727 ci->u2.nres = n; /* save number of returns */
1728 if (L->top.p < ci->top.p)
1729 L->top.p = ci->top.p;
1730 luaF_close(L, base, CLOSEKTOP, 1);
1731 updatetrap(ci);
1732 updatestack(ci);
1733 }
1734 if (nparams1) /* vararg function? */
1735 ci->func.p -= ci->u.l.nextraargs + nparams1;
1736 L->top.p = ra + n; /* set call for 'luaD_poscall' */
1737 luaD_poscall(L, ci, n);
1738 updatetrap(ci); /* 'luaD_poscall' can change hooks */
1739 goto ret;
1740 }
1741 vmcase(OP_RETURN0) {
1742 if (l_unlikely(L->hookmask)) {
1743 StkId ra = RA(i);
1744 L->top.p = ra;
1745 savepc(ci);
1746 luaD_poscall(L, ci, 0); /* no hurry... */
1747 trap = 1;
1748 }
1749 else { /* do the 'poscall' here */
1750 int nres;
1751 L->ci = ci->previous; /* back to caller */
1752 L->top.p = base - 1;
1753 for (nres = ci->nresults; l_unlikely(nres > 0); nres--)
1754 setnilvalue(s2v(L->top.p++)); /* all results are nil */
1755 }
1756 goto ret;
1757 }
1758 vmcase(OP_RETURN1) {
1759 if (l_unlikely(L->hookmask)) {
1760 StkId ra = RA(i);
1761 L->top.p = ra + 1;
1762 savepc(ci);
1763 luaD_poscall(L, ci, 1); /* no hurry... */
1764 trap = 1;
1765 }
1766 else { /* do the 'poscall' here */
1767 int nres = ci->nresults;
1768 L->ci = ci->previous; /* back to caller */
1769 if (nres == 0)
1770 L->top.p = base - 1; /* asked for no results */
1771 else {
1772 StkId ra = RA(i);
1773 setobjs2s(L, base - 1, ra); /* at least this result */
1774 L->top.p = base;
1775 for (; l_unlikely(nres > 1); nres--)
1776 setnilvalue(s2v(L->top.p++)); /* complete missing results */
1777 }
1778 }
1779 ret: /* return from a Lua function */
1780 if (ci->callstatus & CIST_FRESH)
1781 return; /* end this frame */
1782 else {
1783 ci = ci->previous;
1784 goto returning; /* continue running caller in this frame */
1785 }
1786 }
1787 vmcase(OP_FORLOOP) {
1788 StkId ra = RA(i);
1789 if (ttisinteger(s2v(ra + 2))) { /* integer loop? */
1790 lua_Unsigned count = l_castS2U(ivalue(s2v(ra + 1)));
1791 if (count > 0) { /* still more iterations? */
1792 lua_Integer step = ivalue(s2v(ra + 2));
1793 lua_Integer idx = ivalue(s2v(ra)); /* internal index */
1794 chgivalue(s2v(ra + 1), count - 1); /* update counter */
1795 idx = intop(+, idx, step); /* add step to index */
1796 chgivalue(s2v(ra), idx); /* update internal index */
1797 setivalue(s2v(ra + 3), idx); /* and control variable */
1798 pc -= GETARG_Bx(i); /* jump back */
1799 }
1800 }
1801 else if (floatforloop(ra)) /* float loop */
1802 pc -= GETARG_Bx(i); /* jump back */
1803 updatetrap(ci); /* allows a signal to break the loop */
1804 vmbreak;
1805 }
1806 vmcase(OP_FORPREP) {
1807 StkId ra = RA(i);
1808 savestate(L, ci); /* in case of errors */
1809 if (forprep(L, ra))
1810 pc += GETARG_Bx(i) + 1; /* skip the loop */
1811 vmbreak;
1812 }
1813 vmcase(OP_TFORPREP) {
1814 StkId ra = RA(i);
1815 /* create to-be-closed upvalue (if needed) */
1816 halfProtect(luaF_newtbcupval(L, ra + 3));
1817 pc += GETARG_Bx(i);
1818 i = *(pc++); /* go to next instruction */
1819 lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i));
1820 goto l_tforcall;
1821 }
1822 vmcase(OP_TFORCALL) {
1823 l_tforcall: {
1824 StkId ra = RA(i);
1825 /* 'ra' has the iterator function, 'ra + 1' has the state,
1826 'ra + 2' has the control variable, and 'ra + 3' has the
1827 to-be-closed variable. The call will use the stack after
1828 these values (starting at 'ra + 4')
1829 */
1830 /* push function, state, and control variable */
1831 memcpy(ra + 4, ra, 3 * sizeof(*ra));
1832 L->top.p = ra + 4 + 3;
1833 ProtectNT(luaD_call(L, ra + 4, GETARG_C(i))); /* do the call */
1834 updatestack(ci); /* stack may have changed */
1835 i = *(pc++); /* go to next instruction */
1836 lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i));
1837 goto l_tforloop;
1838 }}
1839 vmcase(OP_TFORLOOP) {
1840 l_tforloop: {
1841 StkId ra = RA(i);
1842 if (!ttisnil(s2v(ra + 4))) { /* continue loop? */
1843 setobjs2s(L, ra + 2, ra + 4); /* save control variable */
1844 pc -= GETARG_Bx(i); /* jump back */
1845 }
1846 vmbreak;
1847 }}
1848 vmcase(OP_SETLIST) {
1849 StkId ra = RA(i);
1850 int n = GETARG_B(i);
1851 unsigned int last = GETARG_C(i);
1852 Table *h = hvalue(s2v(ra));
1853 if (n == 0)
1854 n = cast_int(L->top.p - ra) - 1; /* get up to the top */
1855 else
1856 L->top.p = ci->top.p; /* correct top in case of emergency GC */
1857 last += n;
1858 if (TESTARG_k(i)) {
1859 last += GETARG_Ax(*pc) * (MAXARG_C + 1);
1860 pc++;
1861 }
1862 if (last > luaH_realasize(h)) /* needs more space? */
1863 luaH_resizearray(L, h, last); /* preallocate it at once */
1864 for (; n > 0; n--) {
1865 TValue *val = s2v(ra + n);
1866 setobj2t(L, &h->array[last - 1], val);
1867 last--;
1868 luaC_barrierback(L, obj2gco(h), val);
1869 }
1870 vmbreak;
1871 }
1872 vmcase(OP_CLOSURE) {
1873 StkId ra = RA(i);
1874 Proto *p = cl->p->p[GETARG_Bx(i)];
1875 halfProtect(pushclosure(L, p, cl->upvals, base, ra));
1876 checkGC(L, ra + 1);
1877 vmbreak;
1878 }
1879 vmcase(OP_VARARG) {
1880 StkId ra = RA(i);
1881 int n = GETARG_C(i) - 1; /* required results */
1882 Protect(luaT_getvarargs(L, ci, ra, n));
1883 vmbreak;
1884 }
1885 vmcase(OP_VARARGPREP) {
1886 ProtectNT(luaT_adjustvarargs(L, GETARG_A(i), ci, cl->p));
1887 if (l_unlikely(trap)) { /* previous "Protect" updated trap */
1888 luaD_hookcall(L, ci);
1889 L->oldpc = 1; /* next opcode will be seen as a "new" line */
1890 }
1891 updatebase(ci); /* function has new base after adjustment */
1892 vmbreak;
1893 }
1894 vmcase(OP_EXTRAARG) {
1895 lua_assert(0);
1896 vmbreak;
1897 }
1898 }
1899 }
1900}
1901
1902/* }================================================================== */
diff --git a/vendor/lua-5.4.8/src/lvm.h b/vendor/lua-5.4.8/src/lvm.h
new file mode 100644
index 0000000..dba1ad2
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lvm.h
@@ -0,0 +1,141 @@
1/*
2** $Id: lvm.h $
3** Lua virtual machine
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lvm_h
8#define lvm_h
9
10
11#include "ldo.h"
12#include "lobject.h"
13#include "ltm.h"
14
15
16#if !defined(LUA_NOCVTN2S)
17#define cvt2str(o) ttisnumber(o)
18#else
19#define cvt2str(o) 0 /* no conversion from numbers to strings */
20#endif
21
22
23#if !defined(LUA_NOCVTS2N)
24#define cvt2num(o) ttisstring(o)
25#else
26#define cvt2num(o) 0 /* no conversion from strings to numbers */
27#endif
28
29
30/*
31** You can define LUA_FLOORN2I if you want to convert floats to integers
32** by flooring them (instead of raising an error if they are not
33** integral values)
34*/
35#if !defined(LUA_FLOORN2I)
36#define LUA_FLOORN2I F2Ieq
37#endif
38
39
40/*
41** Rounding modes for float->integer coercion
42 */
43typedef enum {
44 F2Ieq, /* no rounding; accepts only integral values */
45 F2Ifloor, /* takes the floor of the number */
46 F2Iceil /* takes the ceil of the number */
47} F2Imod;
48
49
50/* convert an object to a float (including string coercion) */
51#define tonumber(o,n) \
52 (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n))
53
54
55/* convert an object to a float (without string coercion) */
56#define tonumberns(o,n) \
57 (ttisfloat(o) ? ((n) = fltvalue(o), 1) : \
58 (ttisinteger(o) ? ((n) = cast_num(ivalue(o)), 1) : 0))
59
60
61/* convert an object to an integer (including string coercion) */
62#define tointeger(o,i) \
63 (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \
64 : luaV_tointeger(o,i,LUA_FLOORN2I))
65
66
67/* convert an object to an integer (without string coercion) */
68#define tointegerns(o,i) \
69 (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \
70 : luaV_tointegerns(o,i,LUA_FLOORN2I))
71
72
73#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2))
74
75#define luaV_rawequalobj(t1,t2) luaV_equalobj(NULL,t1,t2)
76
77
78/*
79** fast track for 'gettable': if 't' is a table and 't[k]' is present,
80** return 1 with 'slot' pointing to 't[k]' (position of final result).
81** Otherwise, return 0 (meaning it will have to check metamethod)
82** with 'slot' pointing to an empty 't[k]' (if 't' is a table) or NULL
83** (otherwise). 'f' is the raw get function to use.
84*/
85#define luaV_fastget(L,t,k,slot,f) \
86 (!ttistable(t) \
87 ? (slot = NULL, 0) /* not a table; 'slot' is NULL and result is 0 */ \
88 : (slot = f(hvalue(t), k), /* else, do raw access */ \
89 !isempty(slot))) /* result not empty? */
90
91
92/*
93** Special case of 'luaV_fastget' for integers, inlining the fast case
94** of 'luaH_getint'.
95*/
96#define luaV_fastgeti(L,t,k,slot) \
97 (!ttistable(t) \
98 ? (slot = NULL, 0) /* not a table; 'slot' is NULL and result is 0 */ \
99 : (slot = (l_castS2U(k) - 1u < hvalue(t)->alimit) \
100 ? &hvalue(t)->array[k - 1] : luaH_getint(hvalue(t), k), \
101 !isempty(slot))) /* result not empty? */
102
103
104/*
105** Finish a fast set operation (when fast get succeeds). In that case,
106** 'slot' points to the place to put the value.
107*/
108#define luaV_finishfastset(L,t,slot,v) \
109 { setobj2t(L, cast(TValue *,slot), v); \
110 luaC_barrierback(L, gcvalue(t), v); }
111
112
113/*
114** Shift right is the same as shift left with a negative 'y'
115*/
116#define luaV_shiftr(x,y) luaV_shiftl(x,intop(-, 0, y))
117
118
119
120LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2);
121LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
122LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);
123LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n);
124LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode);
125LUAI_FUNC int luaV_tointegerns (const TValue *obj, lua_Integer *p,
126 F2Imod mode);
127LUAI_FUNC int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode);
128LUAI_FUNC void luaV_finishget (lua_State *L, const TValue *t, TValue *key,
129 StkId val, const TValue *slot);
130LUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key,
131 TValue *val, const TValue *slot);
132LUAI_FUNC void luaV_finishOp (lua_State *L);
133LUAI_FUNC void luaV_execute (lua_State *L, CallInfo *ci);
134LUAI_FUNC void luaV_concat (lua_State *L, int total);
135LUAI_FUNC lua_Integer luaV_idiv (lua_State *L, lua_Integer x, lua_Integer y);
136LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y);
137LUAI_FUNC lua_Number luaV_modf (lua_State *L, lua_Number x, lua_Number y);
138LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y);
139LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb);
140
141#endif
diff --git a/vendor/lua-5.4.8/src/lzio.c b/vendor/lua-5.4.8/src/lzio.c
new file mode 100644
index 0000000..cd0a02d
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lzio.c
@@ -0,0 +1,68 @@
1/*
2** $Id: lzio.c $
3** Buffered streams
4** See Copyright Notice in lua.h
5*/
6
7#define lzio_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <string.h>
14
15#include "lua.h"
16
17#include "llimits.h"
18#include "lmem.h"
19#include "lstate.h"
20#include "lzio.h"
21
22
23int luaZ_fill (ZIO *z) {
24 size_t size;
25 lua_State *L = z->L;
26 const char *buff;
27 lua_unlock(L);
28 buff = z->reader(L, z->data, &size);
29 lua_lock(L);
30 if (buff == NULL || size == 0)
31 return EOZ;
32 z->n = size - 1; /* discount char being returned */
33 z->p = buff;
34 return cast_uchar(*(z->p++));
35}
36
37
38void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
39 z->L = L;
40 z->reader = reader;
41 z->data = data;
42 z->n = 0;
43 z->p = NULL;
44}
45
46
47/* --------------------------------------------------------------- read --- */
48size_t luaZ_read (ZIO *z, void *b, size_t n) {
49 while (n) {
50 size_t m;
51 if (z->n == 0) { /* no bytes in buffer? */
52 if (luaZ_fill(z) == EOZ) /* try to read more */
53 return n; /* no more input; return number of missing bytes */
54 else {
55 z->n++; /* luaZ_fill consumed first byte; put it back */
56 z->p--;
57 }
58 }
59 m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
60 memcpy(b, z->p, m);
61 z->n -= m;
62 z->p += m;
63 b = (char *)b + m;
64 n -= m;
65 }
66 return 0;
67}
68
diff --git a/vendor/lua-5.4.8/src/lzio.h b/vendor/lua-5.4.8/src/lzio.h
new file mode 100644
index 0000000..38f397f
--- /dev/null
+++ b/vendor/lua-5.4.8/src/lzio.h
@@ -0,0 +1,66 @@
1/*
2** $Id: lzio.h $
3** Buffered streams
4** See Copyright Notice in lua.h
5*/
6
7
8#ifndef lzio_h
9#define lzio_h
10
11#include "lua.h"
12
13#include "lmem.h"
14
15
16#define EOZ (-1) /* end of stream */
17
18typedef struct Zio ZIO;
19
20#define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z))
21
22
23typedef struct Mbuffer {
24 char *buffer;
25 size_t n;
26 size_t buffsize;
27} Mbuffer;
28
29#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0)
30
31#define luaZ_buffer(buff) ((buff)->buffer)
32#define luaZ_sizebuffer(buff) ((buff)->buffsize)
33#define luaZ_bufflen(buff) ((buff)->n)
34
35#define luaZ_buffremove(buff,i) ((buff)->n -= (i))
36#define luaZ_resetbuffer(buff) ((buff)->n = 0)
37
38
39#define luaZ_resizebuffer(L, buff, size) \
40 ((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \
41 (buff)->buffsize, size), \
42 (buff)->buffsize = size)
43
44#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0)
45
46
47LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,
48 void *data);
49LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n); /* read next n bytes */
50
51
52
53/* --------- Private Part ------------------ */
54
55struct Zio {
56 size_t n; /* bytes still unread */
57 const char *p; /* current position in buffer */
58 lua_Reader reader; /* reader function */
59 void *data; /* additional data */
60 lua_State *L; /* Lua state (for reader) */
61};
62
63
64LUAI_FUNC int luaZ_fill (ZIO *z);
65
66#endif