Commit bbeb09b6 authored by Terry Ellison's avatar Terry Ellison Committed by Marcel Stör
Browse files

Squashed updates do get Lua51 and Lua53 working (#3075)

-  Lots of minor but nasty bugfixes to get all tests to run clean
-  core lua and test suite fixes to allow luac -F to run cleanly against test suite
-  next tranch to get LFS working
-  luac.cross -a options plus fixes from feedback
-  UART fixes and lua.c merge
-  commit of wip prior to rebaselining against current dev
-  more tweaks
parent 99aba344
...@@ -13,6 +13,13 @@ ...@@ -13,6 +13,13 @@
#include <stdbool.h> #include <stdbool.h>
#include "user_config.h" #include "user_config.h"
#ifdef __XTENSA__
# define LUA_USE_ESP
#else
# define LUA_USE_HOST
#endif
/* /*
** ================================================================== ** ==================================================================
** Search for "@@" to find all configurable definitions. ** Search for "@@" to find all configurable definitions.
...@@ -266,16 +273,6 @@ ...@@ -266,16 +273,6 @@
#endif #endif
/*
@@ LUA_PROMPT is the default prompt used by stand-alone Lua.
@@ LUA_PROMPT2 is the default continuation prompt used by stand-alone Lua.
** CHANGE them if you want different prompts. (You can also change the
** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.)
*/
#define LUA_PROMPT "> "
#define LUA_PROMPT2 ">> "
/* /*
@@ LUA_PROGNAME is the default name for the stand-alone Lua program. @@ LUA_PROGNAME is the default name for the stand-alone Lua program.
** CHANGE it if your stand-alone interpreter has a different name and ** CHANGE it if your stand-alone interpreter has a different name and
...@@ -300,25 +297,6 @@ ...@@ -300,25 +297,6 @@
** CHANGE them if you want to improve this functionality (e.g., by using ** CHANGE them if you want to improve this functionality (e.g., by using
** GNU readline and history facilities). ** GNU readline and history facilities).
*/ */
#if defined(LUA_USE_STDIO)
#if defined(LUA_CROSS_COMPILER) && defined(LUA_USE_READLINE)
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
#define lua_saveline(L,idx) \
if (lua_strlen(L,idx) > 0) /* non-empty line? */ \
add_history(lua_tostring(L, idx)); /* add it to history */
#define lua_freeline(L,b) ((void)L, free(b))
#else // #if defined(LUA_CROSS_COMPILER) && defined(LUA_USE_READLINE)
#define lua_readline(L,b,p) \
((void)L, fputs(p, c_stdout), fflush(c_stdout), /* show prompt */ \
fgets(b, LUA_MAXINPUT, c_stdin) != NULL) /* get line */
#define lua_saveline(L,idx) { (void)L; (void)idx; }
#define lua_freeline(L,b) { (void)L; (void)b; }
#endif // #if defined(LUA_USE_READLINE)
#else // #if defined(LUA_USE_STDIO)
#define lua_readline(L,b,p) (readline4lua(p, b, LUA_MAXINPUT)) #define lua_readline(L,b,p) (readline4lua(p, b, LUA_MAXINPUT))
#define lua_saveline(L,idx) { (void)L; (void)idx; } #define lua_saveline(L,idx) { (void)L; (void)idx; }
...@@ -326,48 +304,29 @@ ...@@ -326,48 +304,29 @@
extern int readline4lua(const char *prompt, char *buffer, int length); extern int readline4lua(const char *prompt, char *buffer, int length);
#endif // #if defined(LUA_USE_STDIO)
/* /*
@@ luai_writestring/luai_writeline define how 'print' prints its results. @@ lua_writestring/luai_writeline define how 'print' prints its results.
** They are only used in libraries and the stand-alone program. (The #if ** They are only used in libraries and the stand-alone program. (The #if
** avoids including 'stdio.h' everywhere.) ** avoids including 'stdio.h' everywhere.)
*/ */
#if !defined(LUA_USE_STDIO) #ifdef LUA_USE_ESP
#define luai_writestring(s, l) puts(s) #define lua_writestring(s,l) output_redirect((s),(l))
#define luai_writeline() puts("\n") #else
#endif // defined(LUA_USE_STDIO) #define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
#endif
#define luai_writeline() lua_writestring("\n",1)
/* /*
@@ luai_writestringerror defines how to print error messages. @@ lua_writestringerror defines how to print error messages.
** (A format string with one argument is enough for Lua...) ** (A format string with one argument is enough for Lua...)
*/ */
#if !defined(LUA_USE_STDIO) #ifdef LUA_USE_ESP
#define luai_writestringerror(s,p) dbg_printf((s), (p)) #define lua_writestringerror(s,p) dbg_printf((s), (p))
#endif // defined(LUA_USE_STDIO) #else
#define lua_writestringerror(s,p) fprintf(stderr, (s), (p))
#endif
/* }================================================================== */
/*
@@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles
@* as a percentage.
** CHANGE it if you want the GC to run faster or slower (higher values
** mean larger pauses which mean slower collection.) You can also change
** this value dynamically.
*/
#define LUAI_GCPAUSE 110 /* 110% (wait memory to grow 10% before next gc) */
/* #define LUAI_GCPAUSE 110 /* 110% (wait memory to grow 10% before next gc) */
@@ LUAI_GCMUL defines the default speed of garbage collection relative to
@* memory allocation as a percentage.
** CHANGE it if you want to change the granularity of the garbage
** collection. (Higher values mean coarser collections. 0 represents
** infinity, where each step performs a full collection.) You can also
** change this value dynamically.
*/
#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */ #define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */
...@@ -898,4 +857,6 @@ union luai_Cast { double l_d; long l_l; }; ...@@ -898,4 +857,6 @@ union luai_Cast { double l_d; long l_l; };
#error "Pipes not supported NodeMCU firmware" #error "Pipes not supported NodeMCU firmware"
#endif #endif
#define LUA_DEBUG_HOOK lua_debugbreak
#endif #endif
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
#define lundump_c #define lundump_c
#define LUA_CORE #define LUA_CORE
#define LUAC_CROSS_FILE
#include "lua.h" #include "lua.h"
#include <string.h> #include <string.h>
...@@ -164,16 +163,9 @@ static TString* LoadString(LoadState* S) ...@@ -164,16 +163,9 @@ static TString* LoadString(LoadState* S)
return NULL; return NULL;
else else
{ {
char* s; char* s = luaZ_openspace(S->L,S->b,size);
if (!luaZ_direct_mode(S->Z)) { LoadBlock(S,s,size);
s = luaZ_openspace(S->L,S->b,size); return luaS_newlstr(S->L,s,size-1); /* remove trailing zero */
LoadBlock(S,s,size);
return luaS_newlstr(S->L,s,size-1); /* remove trailing zero */
} else {
s = (char*)luaZ_get_crt_address(S->Z);
LoadBlock(S,NULL,size);
return luaS_newlstr(S->L,s,size-1);
}
} }
} }
...@@ -181,13 +173,8 @@ static void LoadCode(LoadState* S, Proto* f) ...@@ -181,13 +173,8 @@ static void LoadCode(LoadState* S, Proto* f)
{ {
int n=LoadInt(S); int n=LoadInt(S);
Align4(S); Align4(S);
if (!luaZ_direct_mode(S->Z)) { f->code=luaM_newvector(S->L,n,Instruction);
f->code=luaM_newvector(S->L,n,Instruction); LoadVector(S,f->code,n,sizeof(Instruction));
LoadVector(S,f->code,n,sizeof(Instruction));
} else {
f->code=(Instruction*)luaZ_get_crt_address(S->Z);
LoadVector(S,NULL,n,sizeof(Instruction));
}
f->sizecode=n; f->sizecode=n;
} }
...@@ -238,24 +225,14 @@ static void LoadDebug(LoadState* S, Proto* f) ...@@ -238,24 +225,14 @@ static void LoadDebug(LoadState* S, Proto* f)
#ifdef LUA_OPTIMIZE_DEBUG #ifdef LUA_OPTIMIZE_DEBUG
if(n) { if(n) {
if (!luaZ_direct_mode(S->Z)) { f->packedlineinfo=luaM_newvector(S->L,n,unsigned char);
f->packedlineinfo=luaM_newvector(S->L,n,unsigned char); LoadBlock(S,f->packedlineinfo,n);
LoadBlock(S,f->packedlineinfo,n);
} else {
f->packedlineinfo=(unsigned char*)luaZ_get_crt_address(S->Z);
LoadBlock(S,NULL,n);
}
} else { } else {
f->packedlineinfo=NULL; f->packedlineinfo=NULL;
} }
#else #else
if (!luaZ_direct_mode(S->Z)) { f->lineinfo=luaM_newvector(S->L,n,int);
f->lineinfo=luaM_newvector(S->L,n,int); LoadVector(S,f->lineinfo,n,sizeof(int));
LoadVector(S,f->lineinfo,n,sizeof(int));
} else {
f->lineinfo=(int*)luaZ_get_crt_address(S->Z);
LoadVector(S,NULL,n,sizeof(int));
}
f->sizelineinfo=n; f->sizelineinfo=n;
#endif #endif
n=LoadInt(S); n=LoadInt(S);
...@@ -280,7 +257,6 @@ static Proto* LoadFunction(LoadState* S, TString* p) ...@@ -280,7 +257,6 @@ static Proto* LoadFunction(LoadState* S, TString* p)
Proto* f; Proto* f;
if (++S->L->nCcalls > LUAI_MAXCCALLS) error(S,"code too deep"); if (++S->L->nCcalls > LUAI_MAXCCALLS) error(S,"code too deep");
f=luaF_newproto(S->L); f=luaF_newproto(S->L);
if (luaZ_direct_mode(S->Z)) l_setbit((f)->marked, READONLYBIT);
setptvalue2s(S->L,S->L->top,f); incr_top(S->L); setptvalue2s(S->L,S->L->top,f); incr_top(S->L);
f->source=LoadString(S); if (f->source==NULL) f->source=p; f->source=LoadString(S); if (f->source==NULL) f->source=p;
f->linedefined=LoadInt(S); f->linedefined=LoadInt(S);
......
...@@ -50,11 +50,4 @@ LUAI_FUNC void luaU_print (const Proto* f, int full); ...@@ -50,11 +50,4 @@ LUAI_FUNC void luaU_print (const Proto* f, int full);
/* size of header of binary files */ /* size of header of binary files */
#define LUAC_HEADERSIZE 12 #define LUAC_HEADERSIZE 12
/* error codes from cross-compiler */
/* target integer is too small to hold a value */
#define LUA_ERR_CC_INTOVERFLOW 101
/* target lua_Number is integral but a constant is non-integer */
#define LUA_ERR_CC_NOTINTEGER 102
#endif #endif
...@@ -7,7 +7,6 @@ ...@@ -7,7 +7,6 @@
#define lvm_c #define lvm_c
#define LUA_CORE #define LUA_CORE
#define LUAC_CROSS_FILE
#include "lua.h" #include "lua.h"
#include <stdio.h> #include <stdio.h>
...@@ -25,7 +24,6 @@ ...@@ -25,7 +24,6 @@
#include "ltable.h" #include "ltable.h"
#include "ltm.h" #include "ltm.h"
#include "lvm.h" #include "lvm.h"
#include "lrotable.h"
/* limit for table tag-method chains (to avoid loops) */ /* limit for table tag-method chains (to avoid loops) */
...@@ -134,26 +132,17 @@ void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { ...@@ -134,26 +132,17 @@ void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {
if (ttistable(t)) { /* `t' is a table? */ if (ttistable(t)) { /* `t' is a table? */
Table *h = hvalue(t); Table *h = hvalue(t);
const TValue *res = luaH_get(h, key); /* do a primitive get */ const TValue *res = luaH_get(h, key); /* do a primitive get */
if (!ttisnil(res) || /* result is no nil? */ if (!ttisnil(res) || /* result is no nil? */
(tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */ (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */
setobj2s(L, val, res); setobj2s(L, val, res);
return; return;
} }
/* else will try the tag method */ /* else will try the tag method */
} else if (ttisrotable(t)) { /* `t' is a table? */
void *h = rvalue(t);
const TValue *res = luaH_get_ro(h, key); /* do a primitive get */
if (!ttisnil(res) || /* result is no nil? */
(tm = fasttm(L, (Table*)luaR_getmeta(h), TM_INDEX)) == NULL) { /* or no TM? */
setobj2s(L, val, res);
return;
}
/* else will try the tag method */
} }
else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX))) else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX)))
luaG_typeerror(L, t, "index"); luaG_typeerror(L, t, "index");
if (ttisfunction(tm) || ttislightfunction(tm)) { if (ttisfunction(tm)) {
callTMres(L, val, tm, t, key); callTMres(L, val, tm, t, key);
return; return;
} }
...@@ -193,7 +182,7 @@ void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { ...@@ -193,7 +182,7 @@ void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))
luaG_typeerror(L, t, "index"); luaG_typeerror(L, t, "index");
if (ttisfunction(tm) || ttislightfunction(tm)) { if (ttisfunction(tm)) {
L->top--; L->top--;
unfixedstack(L); unfixedstack(L);
callTM(L, tm, t, key, val); callTM(L, tm, t, key, val);
...@@ -305,8 +294,6 @@ int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) { ...@@ -305,8 +294,6 @@ int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) {
case LUA_TNIL: return 1; case LUA_TNIL: return 1;
case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */ case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */
case LUA_TROTABLE:
return rvalue(t1) == rvalue(t2);
case LUA_TLIGHTUSERDATA: case LUA_TLIGHTUSERDATA:
case LUA_TLIGHTFUNCTION: case LUA_TLIGHTFUNCTION:
return pvalue(t1) == pvalue(t2); return pvalue(t1) == pvalue(t2);
...@@ -316,6 +303,8 @@ int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) { ...@@ -316,6 +303,8 @@ int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) {
TM_EQ); TM_EQ);
break; /* will try TM */ break; /* will try TM */
} }
case LUA_TROTABLE:
return hvalue(t1) == hvalue(t2);
case LUA_TTABLE: { case LUA_TTABLE: {
if (hvalue(t1) == hvalue(t2)) return 1; if (hvalue(t1) == hvalue(t2)) return 1;
tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ); tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
...@@ -440,7 +429,6 @@ static void Arith (lua_State *L, StkId ra, const TValue *rb, ...@@ -440,7 +429,6 @@ static void Arith (lua_State *L, StkId ra, const TValue *rb,
} }
void luaV_execute (lua_State *L, int nexeccalls) { void luaV_execute (lua_State *L, int nexeccalls) {
LClosure *cl; LClosure *cl;
StkId base; StkId base;
...@@ -582,10 +570,9 @@ void luaV_execute (lua_State *L, int nexeccalls) { ...@@ -582,10 +570,9 @@ void luaV_execute (lua_State *L, int nexeccalls) {
} }
case OP_LEN: { case OP_LEN: {
const TValue *rb = RB(i); const TValue *rb = RB(i);
switch (ttype(rb)) { switch (basettype(rb)) {
case LUA_TTABLE: case LUA_TTABLE: {
case LUA_TROTABLE: { setnvalue(ra, cast_num(luaH_getn(hvalue(rb))));
setnvalue(ra, ttistable(rb) ? cast_num(luaH_getn(hvalue(rb))) : cast_num(luaH_getn_ro(rvalue(rb))));
break; break;
} }
case LUA_TSTRING: { case LUA_TSTRING: {
......
...@@ -7,7 +7,6 @@ ...@@ -7,7 +7,6 @@
#define lzio_c #define lzio_c
#define LUA_CORE #define LUA_CORE
#define LUAC_CROSS_FILE
#include "lua.h" #include "lua.h"
#include <string.h> #include <string.h>
...@@ -49,7 +48,7 @@ void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { ...@@ -49,7 +48,7 @@ void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
z->L = L; z->L = L;
z->reader = reader; z->reader = reader;
z->data = data; z->data = data;
z->n = z->i = 0; z->n = 0;
z->p = NULL; z->p = NULL;
} }
...@@ -64,7 +63,6 @@ size_t luaZ_read (ZIO *z, void *b, size_t n) { ...@@ -64,7 +63,6 @@ size_t luaZ_read (ZIO *z, void *b, size_t n) {
if (b) if (b)
memcpy(b, z->p, m); memcpy(b, z->p, m);
z->n -= m; z->n -= m;
z->i += m;
z->p += m; z->p += m;
if (b) if (b)
b = (char *)b + m; b = (char *)b + m;
......
...@@ -43,9 +43,6 @@ typedef struct Mbuffer { ...@@ -43,9 +43,6 @@ typedef struct Mbuffer {
#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) #define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0)
#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) #define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0)
#define luaZ_get_base_address(zio) ((const char *)((zio)->reader(NULL, (zio)->data, NULL)))
#define luaZ_direct_mode(zio) (luaZ_get_base_address(zio) != NULL)
#define luaZ_get_crt_address(zio) (luaZ_get_base_address(zio) + (zio)->i)
LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n); LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n);
LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,
...@@ -59,7 +56,6 @@ LUAI_FUNC int luaZ_lookahead (ZIO *z); ...@@ -59,7 +56,6 @@ LUAI_FUNC int luaZ_lookahead (ZIO *z);
struct Zio { struct Zio {
size_t n; /* bytes still unread */ size_t n; /* bytes still unread */
size_t i; /* buffer offset */
const char *p; /* current position in buffer */ const char *p; /* current position in buffer */
lua_Reader reader; lua_Reader reader;
void* data; /* additional data */ void* data; /* additional data */
......
#############################################################
# Required variables for each makefile
# Discard this section from all parent makefiles
# Expected variables (with automatic defaults):
# CSRCS (all "C" files in the dir)
# SUBDIRS (all subdirs with a Makefile)
# GEN_LIBS - list of libs to be generated ()
# GEN_IMAGES - list of images to be generated ()
# COMPONENTS_xxx - a list of libs/objs in the form
# subdir/lib to be extracted and rolled up into
# a generated lib/image xxx.a ()
#
ifndef PDIR
SUBDIRS = host
GEN_LIBS = liblua.a
endif
STD_CFLAGS=-std=gnu11 -Wimplicit -Wall
#############################################################
# Configuration i.e. compile options etc.
# Target specific stuff (defines etc.) goes in here!
#
#DEFINES += -DDEVELOPMENT_TOOLS -DDEVELOPMENT_USE_GDB -DDEVELOPMENT_BREAK_ON_STARTUP_PIN=1
#EXTRA_CCFLAGS += -ggdb -O0
#############################################################
# Recursion Magic - Don't touch this!!
#
INCLUDES := $(INCLUDES) -I $(PDIR)include
INCLUDES += -I ./
INCLUDES += -I ../spiffs
INCLUDES += -I ../libc
INCLUDES += -I ../modules
INCLUDES += -I ../platform
INCLUDES += -I ../uzlib
PDIR := ../$(PDIR)
sinclude $(PDIR)Makefile
#
# This Makefile is called from the core Makefile hierarchy which is a hierarchical
# make which uses parent callbacks to implement inheritance. However if luac_cross
# build stands outside this, it uses the host toolchain to implement a separate
# host build of the luac.cross image.
#
.NOTPARALLEL:
CCFLAGS:= -I. -I.. -I../../include -I../../uzlib
LDFLAGS:= -L$(SDK_DIR)/lib -L$(SDK_DIR)/ld -lm -ldl -Wl,-Map=mapfile
CCFLAGS += -Wall
TARGET = host
VERBOSE ?=
V ?= $(VERBOSE)
ifeq ("$(V)","1")
export summary := @true
else
export summary := @echo
# disable echoing of commands, directory names
# MAKEFLAGS += --silent -w
endif # $(V)==1
DEBUG ?=
ifeq ("$(DEBUG)","1")
FLAVOR = debug
CCFLAGS += -O0 -ggdb
TARGET_LDFLAGS += -O0 -ggdb
DEFINES += -DLUA_DEBUG_BUILD -DDEVELOPMENT_TOOLS -DDEVELOPMENT_USE_GDB
else
FLAVOR = release
CCFLAGS += -O2
TARGET_LDFLAGS += -O2
endif # DEBUG
LUACSRC := luac.c liolib.c loslib.c
LUASRC := lapi.c lauxlib.c lbaselib.c lcode.c lcorolib.c lctype.c \
ldblib.c ldebug.c ldo.c ldump.c lfunc.c lgc.c \
linit.c llex.c lmathlib.c lmem.c loadlib.c lnodemcu.c \
lobject.c lopcodes.c lparser.c lstate.c lstring.c lstrlib.c \
ltable.c ltablib.c ltm.c lundump.c lutf8lib.c lvm.c \
lzio.c
UZSRC := uzlib_deflate.c crc32.c
TEST ?=
ifeq ("$(TEST)","1")
DEFINES += -DLUA_ENABLE_TEST
LUACSRC += ltests.c
endif # $(TEST)==1
#
# This relies on the files being unique on the vpath
#
SRC := $(LUACSRC) $(LUASRC) $(UZSRC)
vpath %.c .:..:../../libc:../../uzlib
ODIR := .output/$(TARGET)/$(FLAVOR)/obj
OBJS := $(SRC:%.c=$(ODIR)/%.o)
DEPS := $(SRC:%.c=$(ODIR)/%.d)
CFLAGS = $(CCFLAGS) $(DEFINES) $(EXTRA_CCFLAGS) $(STD_CFLAGS) $(INCLUDES)
DFLAGS = $(CCFLAGS) $(DDEFINES) $(EXTRA_CCFLAGS) $(STD_CFLAGS) $(INCLUDES)
CC := $(WRAPCC) gcc
ECHO := echo
BUILD_TYPE := $(shell $(CC) $(EXTRA_CCFLAGS) -E -dM - <../../include/user_config.h | grep LUA_NUMBER_INTEGRAL | wc -l)
ifeq ($(BUILD_TYPE),0)
IMAGE := ../../../luac.cross
else
IMAGE := ../../../luac.cross.int
endif
.PHONY: test clean all
all: $(DEPS) $(IMAGE)
$(IMAGE) : $(OBJS)
$(summary) HOSTLD $@
$(CC) $(OBJS) -o $@ $(LDFLAGS)
test :
@echo CC: $(CC)
@echo SRC: $(SRC)
@echo OBJS: $(OBJS)
@echo DEPS: $(DEPS)
@echo IMAGE: $(IMAGE)
clean :
$(RM) -r $(ODIR)
ifneq ($(MAKECMDGOALS),clean)
-include $(DEPS)
endif
$(ODIR)/%.o: %.c
@mkdir -p $(ODIR);
$(summary) HOSTCC $(CURDIR)/$<
$(CC) $(if $(findstring $<,$(DSRCS)),$(DFLAGS),$(CFLAGS)) $(COPTS_$(*F)) -o $@ -c $<
$(ODIR)/%.d: %.c
@mkdir -p $(ODIR);
$(summary) DEPEND: HOSTCC $(CURDIR)/$<
@set -e; rm -f $@; \
$(CC) -M $(CFLAGS) $< > $@.$$$$; \
sed 's,\($*\.o\)[ :]*,$(ODIR)/\1 $@ : ,g' < $@.$$$$ > $@; \
rm -f $@.$$$$
/*
** $Id: liolib.c,v 2.151.1.1 2017/04/19 17:29:57 roberto Exp $
** Standard I/O (and system) library
** See Copyright Notice in lua.h
*/
#define liolib_c
#define LUA_LIB
#include "lprefix.h"
#include <ctype.h>
#include <errno.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
/*
** Change this macro to accept other modes for 'fopen' besides
** the standard ones.
*/
#if !defined(l_checkmode)
/* accepted extensions to 'mode' in 'fopen' */
#if !defined(L_MODEEXT)
#define L_MODEEXT "b"
#endif
/* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */
static int l_checkmode (const char *mode) {
return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&
(*mode != '+' || (++mode, 1)) && /* skip if char is '+' */
(strspn(mode, L_MODEEXT) == strlen(mode))); /* check extensions */
}
#endif
/*
** {======================================================
** l_popen spawns a new process connected to the current
** one through the file streams.
** =======================================================
*/
#if !defined(l_popen) /* { */
#if defined(LUA_USE_POSIX) /* { */
#define l_popen(L,c,m) (fflush(NULL), popen(c,m))
#define l_pclose(L,file) (pclose(file))
#elif defined(LUA_USE_WINDOWS) /* }{ */
#define l_popen(L,c,m) (_popen(c,m))
#define l_pclose(L,file) (_pclose(file))
#else /* }{ */
/* ISO C definitions */
#define l_popen(L,c,m) \
((void)((void)c, m), \
luaL_error(L, "'popen' not supported"), \
(FILE*)0)
#define l_pclose(L,file) ((void)L, (void)file, -1)
#endif /* } */
#endif /* } */
/* }====================================================== */
#if !defined(l_getc) /* { */
#if defined(LUA_USE_POSIX)
#define l_getc(f) getc_unlocked(f)
#define l_lockfile(f) flockfile(f)
#define l_unlockfile(f) funlockfile(f)
#else
#define l_getc(f) getc(f)
#define l_lockfile(f) ((void)0)
#define l_unlockfile(f) ((void)0)
#endif
#endif /* } */
/*
** {======================================================
** l_fseek: configuration for longer offsets
** =======================================================
*/
#if !defined(l_fseek) /* { */
#if defined(LUA_USE_POSIX) /* { */
#include <sys/types.h>
#define l_fseek(f,o,w) fseeko(f,o,w)
#define l_ftell(f) ftello(f)
#define l_seeknum off_t
#elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
&& defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
/* Windows (but not DDK) and Visual C++ 2005 or higher */
#define l_fseek(f,o,w) _fseeki64(f,o,w)
#define l_ftell(f) _ftelli64(f)
#define l_seeknum __int64
#else /* }{ */
/* ISO C definitions */
#define l_fseek(f,o,w) fseek(f,o,w)
#define l_ftell(f) ftell(f)
#define l_seeknum long
#endif /* } */
#endif /* } */
/* }====================================================== */
#define IO_PREFIX "_IO_"
#define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
#define IO_INPUT (IO_PREFIX "input")
#define IO_OUTPUT (IO_PREFIX "output")
typedef luaL_Stream LStream;
#define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
#define isclosed(p) ((p)->closef == NULL)
static int io_type (lua_State *L) {
LStream *p;
luaL_checkany(L, 1);
p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
if (p == NULL)
lua_pushnil(L); /* not a file */
else if (isclosed(p))
lua_pushliteral(L, "closed file");
else
lua_pushliteral(L, "file");
return 1;
}
static int f_tostring (lua_State *L) {
LStream *p = tolstream(L);
if (isclosed(p))
lua_pushliteral(L, "file (closed)");
else
lua_pushfstring(L, "file (%p)", p->f);
return 1;
}
static FILE *tofile (lua_State *L) {
LStream *p = tolstream(L);
if (isclosed(p))
luaL_error(L, "attempt to use a closed file");
lua_assert(p->f);
return p->f;
}
/*
** When creating file handles, always creates a 'closed' file handle
** before opening the actual file; so, if there is a memory error, the
** handle is in a consistent state.
*/
static LStream *newprefile (lua_State *L) {
LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
p->closef = NULL; /* mark file handle as 'closed' */
luaL_setmetatable(L, LUA_FILEHANDLE);
return p;
}
/*
** Calls the 'close' function from a file handle. The 'volatile' avoids
** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
** 32 bits).
*/
static int aux_close (lua_State *L) {
LStream *p = tolstream(L);
volatile lua_CFunction cf = p->closef;
p->closef = NULL; /* mark stream as closed */
return (*cf)(L); /* close it */
}
static int f_close (lua_State *L) {
tofile(L); /* make sure argument is an open stream */
return aux_close(L);
}
static int io_close (lua_State *L) {
if (lua_isnone(L, 1)) /* no argument? */
lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
return f_close(L);
}
static int f_gc (lua_State *L) {
LStream *p = tolstream(L);
if (!isclosed(p) && p->f != NULL)
aux_close(L); /* ignore closed and incompletely open files */
return 0;
}
/*
** function to close regular files
*/
static int io_fclose (lua_State *L) {
LStream *p = tolstream(L);
int res = fclose(p->f);
return luaL_fileresult(L, (res == 0), NULL);
}
static LStream *newfile (lua_State *L) {
LStream *p = newprefile(L);
p->f = NULL;
p->closef = &io_fclose;
return p;
}
static void opencheck (lua_State *L, const char *fname, const char *mode) {
LStream *p = newfile(L);
p->f = fopen(fname, mode);
if (p->f == NULL)
luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
}
static int io_open (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r");
LStream *p = newfile(L);
const char *md = mode; /* to traverse/check mode */
luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
p->f = fopen(filename, mode);
return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
}
/*
** function to close 'popen' files
*/
static int io_pclose (lua_State *L) {
LStream *p = tolstream(L);
return luaL_execresult(L, l_pclose(L, p->f));
}
static int io_popen (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r");
LStream *p = newprefile(L);
p->f = l_popen(L, filename, mode);
p->closef = &io_pclose;
return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
}
static int io_tmpfile (lua_State *L) {
LStream *p = newfile(L);
p->f = tmpfile();
return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
}
static FILE *getiofile (lua_State *L, const char *findex) {
LStream *p;
lua_getfield(L, LUA_REGISTRYINDEX, findex);
p = (LStream *)lua_touserdata(L, -1);
if (isclosed(p))
luaL_error(L, "standard %s file is closed", findex + IOPREF_LEN);
return p->f;
}
static int g_iofile (lua_State *L, const char *f, const char *mode) {
if (!lua_isnoneornil(L, 1)) {
const char *filename = lua_tostring(L, 1);
if (filename)
opencheck(L, filename, mode);
else {
tofile(L); /* check that it's a valid file handle */
lua_pushvalue(L, 1);
}
lua_setfield(L, LUA_REGISTRYINDEX, f);
}
/* return current value */
lua_getfield(L, LUA_REGISTRYINDEX, f);
return 1;
}
static int io_input (lua_State *L) {
return g_iofile(L, IO_INPUT, "r");
}
static int io_output (lua_State *L) {
return g_iofile(L, IO_OUTPUT, "w");
}
static int io_readline (lua_State *L);
/*
** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
** in the limit for upvalues of a closure)
*/
#define MAXARGLINE 250
static void aux_lines (lua_State *L, int toclose) {
int n = lua_gettop(L) - 1; /* number of arguments to read */
luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
lua_pushinteger(L, n); /* number of arguments to read */
lua_pushboolean(L, toclose); /* close/not close file when finished */
lua_rotate(L, 2, 2); /* move 'n' and 'toclose' to their positions */
lua_pushcclosure(L, io_readline, 3 + n);
}
static int f_lines (lua_State *L) {
tofile(L); /* check that it's a valid file handle */
aux_lines(L, 0);
return 1;
}
static int io_lines (lua_State *L) {
int toclose;
if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
if (lua_isnil(L, 1)) { /* no file name? */
lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
lua_replace(L, 1); /* put it at index 1 */
tofile(L); /* check that it's a valid file handle */
toclose = 0; /* do not close it after iteration */
}
else { /* open a new file */
const char *filename = luaL_checkstring(L, 1);
opencheck(L, filename, "r");
lua_replace(L, 1); /* put file at index 1 */
toclose = 1; /* close it after iteration */
}
aux_lines(L, toclose);
return 1;
}
/*
** {======================================================
** READ
** =======================================================
*/
/* maximum length of a numeral */
#if !defined (L_MAXLENNUM)
#define L_MAXLENNUM 200
#endif
/* auxiliary structure used by 'read_number' */
typedef struct {
FILE *f; /* file being read */
int c; /* current character (look ahead) */
int n; /* number of elements in buffer 'buff' */
char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */
} RN;
/*
** Add current char to buffer (if not out of space) and read next one
*/
static int nextc (RN *rn) {
if (rn->n >= L_MAXLENNUM) { /* buffer overflow? */
rn->buff[0] = '\0'; /* invalidate result */
return 0; /* fail */
}
else {
rn->buff[rn->n++] = rn->c; /* save current char */
rn->c = l_getc(rn->f); /* read next one */
return 1;
}
}
/*
** Accept current char if it is in 'set' (of size 2)
*/
static int test2 (RN *rn, const char *set) {
if (rn->c == set[0] || rn->c == set[1])
return nextc(rn);
else return 0;
}
/*
** Read a sequence of (hex)digits
*/
static int readdigits (RN *rn, int hex) {
int count = 0;
while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
count++;
return count;
}
/*
** Read a number: first reads a valid prefix of a numeral into a buffer.
** Then it calls 'lua_stringtonumber' to check whether the format is
** correct and to convert it to a Lua number
*/
static int read_number (lua_State *L, FILE *f) {
RN rn;
int count = 0;
int hex = 0;
char decp[2];
rn.f = f; rn.n = 0;
decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
decp[1] = '.'; /* always accept a dot */
l_lockfile(rn.f);
do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
test2(&rn, "-+"); /* optional signal */
if (test2(&rn, "00")) {
if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
else count = 1; /* count initial '0' as a valid digit */
}
count += readdigits(&rn, hex); /* integral part */
if (test2(&rn, decp)) /* decimal point? */
count += readdigits(&rn, hex); /* fractional part */
if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
test2(&rn, "-+"); /* exponent signal */
readdigits(&rn, 0); /* exponent digits */
}
ungetc(rn.c, rn.f); /* unread look-ahead char */
l_unlockfile(rn.f);
rn.buff[rn.n] = '\0'; /* finish string */
if (lua_stringtonumber(L, rn.buff)) /* is this a valid number? */
return 1; /* ok */
else { /* invalid format */
lua_pushnil(L); /* "result" to be removed */
return 0; /* read fails */
}
}
static int test_eof (lua_State *L, FILE *f) {
int c = getc(f);
ungetc(c, f); /* no-op when c == EOF */
lua_pushliteral(L, "");
return (c != EOF);
}
static int read_line (lua_State *L, FILE *f, int chop) {
luaL_Buffer b;
int c = '\0';
luaL_buffinit(L, &b);
while (c != EOF && c != '\n') { /* repeat until end of line */
char *buff = luaL_prepbuffer(&b); /* preallocate buffer */
int i = 0;
l_lockfile(f); /* no memory errors can happen inside the lock */
while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
buff[i++] = c;
l_unlockfile(f);
luaL_addsize(&b, i);
}
if (!chop && c == '\n') /* want a newline and have one? */
luaL_addchar(&b, c); /* add ending newline to result */
luaL_pushresult(&b); /* close buffer */
/* return ok if read something (either a newline or something else) */
return (c == '\n' || lua_rawlen(L, -1) > 0);
}
static void read_all (lua_State *L, FILE *f) {
size_t nr;
luaL_Buffer b;
luaL_buffinit(L, &b);
do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
char *p = luaL_prepbuffer(&b);
nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
luaL_addsize(&b, nr);
} while (nr == LUAL_BUFFERSIZE);
luaL_pushresult(&b); /* close buffer */
}
static int read_chars (lua_State *L, FILE *f, size_t n) {
size_t nr; /* number of chars actually read */
char *p;
luaL_Buffer b;
luaL_buffinit(L, &b);
p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
luaL_addsize(&b, nr);
luaL_pushresult(&b); /* close buffer */
return (nr > 0); /* true iff read something */
}
static int g_read (lua_State *L, FILE *f, int first) {
int nargs = lua_gettop(L) - 1;
int success;
int n;
clearerr(f);
if (nargs == 0) { /* no arguments? */
success = read_line(L, f, 1);
n = first+1; /* to return 1 result */
}
else { /* ensure stack space for all results and for auxlib's buffer */
luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
success = 1;
for (n = first; nargs-- && success; n++) {
if (lua_type(L, n) == LUA_TNUMBER) {
size_t l = (size_t)luaL_checkinteger(L, n);
success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
}
else {
const char *p = luaL_checkstring(L, n);
if (*p == '*') p++; /* skip optional '*' (for compatibility) */
switch (*p) {
case 'n': /* number */
success = read_number(L, f);
break;
case 'l': /* line */
success = read_line(L, f, 1);
break;
case 'L': /* line with end-of-line */
success = read_line(L, f, 0);
break;
case 'a': /* file */
read_all(L, f); /* read entire file */
success = 1; /* always success */
break;
default:
return luaL_argerror(L, n, "invalid format");
}
}
}
}
if (ferror(f))
return luaL_fileresult(L, 0, NULL);
if (!success) {
lua_pop(L, 1); /* remove last result */
lua_pushnil(L); /* push nil instead */
}
return n - first;
}
static int io_read (lua_State *L) {
return g_read(L, getiofile(L, IO_INPUT), 1);
}
static int f_read (lua_State *L) {
return g_read(L, tofile(L), 2);
}
static int io_readline (lua_State *L) {
LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
int i;
int n = (int)lua_tointeger(L, lua_upvalueindex(2));
if (isclosed(p)) /* file is already closed? */
return luaL_error(L, "file is already closed");
lua_settop(L , 1);
luaL_checkstack(L, n, "too many arguments");
for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
lua_pushvalue(L, lua_upvalueindex(3 + i));
n = g_read(L, p->f, 2); /* 'n' is number of results */
lua_assert(n > 0); /* should return at least a nil */
if (lua_toboolean(L, -n)) /* read at least one value? */
return n; /* return them */
else { /* first result is nil: EOF or error */
if (n > 1) { /* is there error information? */
/* 2nd result is error message */
return luaL_error(L, "%s", lua_tostring(L, -n + 1));
}
if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
lua_settop(L, 0);
lua_pushvalue(L, lua_upvalueindex(1));
aux_close(L); /* close it */
}
return 0;
}
}
/* }====================================================== */
static int g_write (lua_State *L, FILE *f, int arg) {
int nargs = lua_gettop(L) - arg;
int status = 1;
for (; nargs--; arg++) {
if (lua_type(L, arg) == LUA_TNUMBER) {
/* optimization: could be done exactly as for strings */
int len = lua_isinteger(L, arg)
? fprintf(f, LUA_INTEGER_FMT,
(LUAI_UACINT)lua_tointeger(L, arg))
: fprintf(f, LUA_NUMBER_FMT,
(LUAI_UACNUMBER)lua_tonumber(L, arg));
status = status && (len > 0);
}
else {
size_t l;
const char *s = luaL_checklstring(L, arg, &l);
status = status && (fwrite(s, sizeof(char), l, f) == l);
}
}
if (status) return 1; /* file handle already on stack top */
else return luaL_fileresult(L, status, NULL);
}
static int io_write (lua_State *L) {
return g_write(L, getiofile(L, IO_OUTPUT), 1);
}
static int f_write (lua_State *L) {
FILE *f = tofile(L);
lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
return g_write(L, f, 2);
}
static int f_seek (lua_State *L) {
static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
static const char *const modenames[] = {"set", "cur", "end", NULL};
FILE *f = tofile(L);
int op = luaL_checkoption(L, 2, "cur", modenames);
lua_Integer p3 = luaL_optinteger(L, 3, 0);
l_seeknum offset = (l_seeknum)p3;
luaL_argcheck(L, (lua_Integer)offset == p3, 3,
"not an integer in proper range");
op = l_fseek(f, offset, mode[op]);
if (op)
return luaL_fileresult(L, 0, NULL); /* error */
else {
lua_pushinteger(L, (lua_Integer)l_ftell(f));
return 1;
}
}
static int f_setvbuf (lua_State *L) {
static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
static const char *const modenames[] = {"no", "full", "line", NULL};
FILE *f = tofile(L);
int op = luaL_checkoption(L, 2, NULL, modenames);
lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
int res = setvbuf(f, NULL, mode[op], (size_t)sz);
return luaL_fileresult(L, res == 0, NULL);
}
static int io_flush (lua_State *L) {
return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
}
static int f_flush (lua_State *L) {
return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
}
/*
** functions for 'io' library
*/
static const luaL_Reg iolib[] = {
{"close", io_close},
{"flush", io_flush},
{"input", io_input},
{"lines", io_lines},
{"open", io_open},
{"output", io_output},
{"popen", io_popen},
{"read", io_read},
{"tmpfile", io_tmpfile},
{"type", io_type},
{"write", io_write},
{NULL, NULL}
};
/*
** methods for file handles
*/
static const luaL_Reg flib[] = {
{"close", f_close},
{"flush", f_flush},
{"lines", f_lines},
{"read", f_read},
{"seek", f_seek},
{"setvbuf", f_setvbuf},
{"write", f_write},
{"__gc", f_gc},
{"__tostring", f_tostring},
{NULL, NULL}
};
static void createmeta (lua_State *L) {
luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
lua_pushvalue(L, -1); /* push metatable */
lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
lua_pop(L, 1); /* pop new metatable */
}
/*
** function to (not) close the standard files stdin, stdout, and stderr
*/
static int io_noclose (lua_State *L) {
LStream *p = tolstream(L);
p->closef = &io_noclose; /* keep file opened */
lua_pushnil(L);
lua_pushliteral(L, "cannot close standard file");
return 2;
}
static void createstdfile (lua_State *L, FILE *f, const char *k,
const char *fname) {
LStream *p = newprefile(L);
p->f = f;
p->closef = &io_noclose;
if (k != NULL) {
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
}
lua_setfield(L, -2, fname); /* add file to module */
}
LUAMOD_API int luaopen_io (lua_State *L) {
luaL_newlib(L, iolib); /* new module */
createmeta(L);
/* create (and set) default files */
createstdfile(L, stdin, IO_INPUT, "stdin");
createstdfile(L, stdout, IO_OUTPUT, "stdout");
createstdfile(L, stderr, NULL, "stderr");
return 1;
}
/*
** $Id: loslib.c,v 1.65.1.1 2017/04/19 17:29:57 roberto Exp $
** Standard Operating System library
** See Copyright Notice in lua.h
*/
#define loslib_c
#define LUA_LIB
#include "lprefix.h"
#include <errno.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
/*
** {==================================================================
** List of valid conversion specifiers for the 'strftime' function;
** options are grouped by length; group of length 2 start with '||'.
** ===================================================================
*/
#if !defined(LUA_STRFTIMEOPTIONS) /* { */
/* options for ANSI C 89 (only 1-char options) */
#define L_STRFTIMEC89 "aAbBcdHIjmMpSUwWxXyYZ%"
/* options for ISO C 99 and POSIX */
#define L_STRFTIMEC99 "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \
"||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */
/* options for Windows */
#define L_STRFTIMEWIN "aAbBcdHIjmMpSUwWxXyYzZ%" \
"||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y" /* two-char options */
#if defined(LUA_USE_WINDOWS)
#define LUA_STRFTIMEOPTIONS L_STRFTIMEWIN
#elif defined(LUA_USE_C89)
#define LUA_STRFTIMEOPTIONS L_STRFTIMEC89
#else /* C99 specification */
#define LUA_STRFTIMEOPTIONS L_STRFTIMEC99
#endif
#endif /* } */
/* }================================================================== */
/*
** {==================================================================
** Configuration for time-related stuff
** ===================================================================
*/
#if !defined(l_time_t) /* { */
/*
** type to represent time_t in Lua
*/
#define l_timet lua_Integer
#define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t))
static time_t l_checktime (lua_State *L, int arg) {
lua_Integer t = luaL_checkinteger(L, arg);
luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds");
return (time_t)t;
}
#endif /* } */
#if !defined(l_gmtime) /* { */
/*
** By default, Lua uses gmtime/localtime, except when POSIX is available,
** where it uses gmtime_r/localtime_r
*/
#if defined(LUA_USE_POSIX) /* { */
#define l_gmtime(t,r) gmtime_r(t,r)
#define l_localtime(t,r) localtime_r(t,r)
#else /* }{ */
/* ISO C definitions */
#define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t))
#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t))
#endif /* } */
#endif /* } */
/* }================================================================== */
/*
** {==================================================================
** Configuration for 'tmpnam':
** By default, Lua uses tmpnam except when POSIX is available, where
** it uses mkstemp.
** ===================================================================
*/
#if !defined(lua_tmpnam) /* { */
#if defined(__GNUC__) /* { */
#include <unistd.h>
#define LUA_TMPNAMBUFSIZE 32
#if !defined(LUA_TMPNAMTEMPLATE)
#define LUA_TMPNAMTEMPLATE "/tmp/lua_XXXXXX"
#endif
#define lua_tmpnam(b,e) { \
strcpy(b, LUA_TMPNAMTEMPLATE); \
e = mkstemp(b); \
if (e != -1) close(e); \
e = (e == -1); }
#else /* }{ */
/* ISO C definitions */
#define LUA_TMPNAMBUFSIZE L_tmpnam
#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); }
#endif /* } */
#endif /* } */
/* }================================================================== */
static int os_execute (lua_State *L) {
const char *cmd = luaL_optstring(L, 1, NULL);
int stat = system(cmd);
if (cmd != NULL)
return luaL_execresult(L, stat);
else {
lua_pushboolean(L, stat); /* true if there is a shell */
return 1;
}
}
static int os_remove (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
return luaL_fileresult(L, remove(filename) == 0, filename);
}
static int os_rename (lua_State *L) {
const char *fromname = luaL_checkstring(L, 1);
const char *toname = luaL_checkstring(L, 2);
return luaL_fileresult(L, rename(fromname, toname) == 0, NULL);
}
static int os_tmpname (lua_State *L) {
char buff[LUA_TMPNAMBUFSIZE];
int err;
lua_tmpnam(buff, err);
if (err)
return luaL_error(L, "unable to generate a unique filename");
lua_pushstring(L, buff);
return 1;
}
static int os_getenv (lua_State *L) {
lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */
return 1;
}
static int os_clock (lua_State *L) {
lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
return 1;
}
/*
** {======================================================
** Time/Date operations
** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
** wday=%w+1, yday=%j, isdst=? }
** =======================================================
*/
static void setfield (lua_State *L, const char *key, int value) {
lua_pushinteger(L, value);
lua_setfield(L, -2, key);
}
static void setboolfield (lua_State *L, const char *key, int value) {
if (value < 0) /* undefined? */
return; /* does not set field */
lua_pushboolean(L, value);
lua_setfield(L, -2, key);
}
/*
** Set all fields from structure 'tm' in the table on top of the stack
*/
static void setallfields (lua_State *L, struct tm *stm) {
setfield(L, "sec", stm->tm_sec);
setfield(L, "min", stm->tm_min);
setfield(L, "hour", stm->tm_hour);
setfield(L, "day", stm->tm_mday);
setfield(L, "month", stm->tm_mon + 1);
setfield(L, "year", stm->tm_year + 1900);
setfield(L, "wday", stm->tm_wday + 1);
setfield(L, "yday", stm->tm_yday + 1);
setboolfield(L, "isdst", stm->tm_isdst);
}
static int getboolfield (lua_State *L, const char *key) {
int res;
res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
lua_pop(L, 1);
return res;
}
/* maximum value for date fields (to avoid arithmetic overflows with 'int') */
#if !defined(L_MAXDATEFIELD)
#define L_MAXDATEFIELD (INT_MAX / 2)
#endif
static int getfield (lua_State *L, const char *key, int d, int delta) {
int isnum;
int t = lua_getfield(L, -1, key); /* get field and its type */
lua_Integer res = lua_tointegerx(L, -1, &isnum);
if (!isnum) { /* field is not an integer? */
if (t != LUA_TNIL) /* some other value? */
return luaL_error(L, "field '%s' is not an integer", key);
else if (d < 0) /* absent field; no default? */
return luaL_error(L, "field '%s' missing in date table", key);
res = d;
}
else {
if (!(-L_MAXDATEFIELD <= res && res <= L_MAXDATEFIELD))
return luaL_error(L, "field '%s' is out-of-bound", key);
res -= delta;
}
lua_pop(L, 1);
return (int)res;
}
static const char *checkoption (lua_State *L, const char *conv,
ptrdiff_t convlen, char *buff) {
const char *option = LUA_STRFTIMEOPTIONS;
int oplen = 1; /* length of options being checked */
for (; *option != '\0' && oplen <= convlen; option += oplen) {
if (*option == '|') /* next block? */
oplen++; /* will check options with next length (+1) */
else if (memcmp(conv, option, oplen) == 0) { /* match? */
memcpy(buff, conv, oplen); /* copy valid option to buffer */
buff[oplen] = '\0';
return conv + oplen; /* return next item */
}
}
luaL_argerror(L, 1,
lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv));
return conv; /* to avoid warnings */
}
/* maximum size for an individual 'strftime' item */
#define SIZETIMEFMT 250
static int os_date (lua_State *L) {
size_t slen;
const char *s = luaL_optlstring(L, 1, "%c", &slen);
time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
const char *se = s + slen; /* 's' end */
struct tm tmr, *stm;
if (*s == '!') { /* UTC? */
stm = l_gmtime(&t, &tmr);
s++; /* skip '!' */
}
else
stm = l_localtime(&t, &tmr);
if (stm == NULL) /* invalid date? */
return luaL_error(L,
"time result cannot be represented in this installation");
if (strcmp(s, "*t") == 0) {
lua_createtable(L, 0, 9); /* 9 = number of fields */
setallfields(L, stm);
}
else {
char cc[4]; /* buffer for individual conversion specifiers */
luaL_Buffer b;
cc[0] = '%';
luaL_buffinit(L, &b);
while (s < se) {
if (*s != '%') /* not a conversion specifier? */
luaL_addchar(&b, *s++);
else {
size_t reslen;
char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT);
s++; /* skip '%' */
s = checkoption(L, s, se - s, cc + 1); /* copy specifier to 'cc' */
reslen = strftime(buff, SIZETIMEFMT, cc, stm);
luaL_addsize(&b, reslen);
}
}
luaL_pushresult(&b);
}
return 1;
}
static int os_time (lua_State *L) {
time_t t;
if (lua_isnoneornil(L, 1)) /* called without args? */
t = time(NULL); /* get current time */
else {
struct tm ts;
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 1); /* make sure table is at the top */
ts.tm_sec = getfield(L, "sec", 0, 0);
ts.tm_min = getfield(L, "min", 0, 0);
ts.tm_hour = getfield(L, "hour", 12, 0);
ts.tm_mday = getfield(L, "day", -1, 0);
ts.tm_mon = getfield(L, "month", -1, 1);
ts.tm_year = getfield(L, "year", -1, 1900);
ts.tm_isdst = getboolfield(L, "isdst");
t = mktime(&ts);
setallfields(L, &ts); /* update fields with normalized values */
}
if (t != (time_t)(l_timet)t || t == (time_t)(-1))
return luaL_error(L,
"time result cannot be represented in this installation");
l_pushtime(L, t);
return 1;
}
static int os_difftime (lua_State *L) {
time_t t1 = l_checktime(L, 1);
time_t t2 = l_checktime(L, 2);
lua_pushnumber(L, (lua_Number)difftime(t1, t2));
return 1;
}
/* }====================================================== */
static int os_setlocale (lua_State *L) {
static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
LC_NUMERIC, LC_TIME};
static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
"numeric", "time", NULL};
const char *l = luaL_optstring(L, 1, NULL);
int op = luaL_checkoption(L, 2, "all", catnames);
lua_pushstring(L, setlocale(cat[op], l));
return 1;
}
static int os_exit (lua_State *L) {
int status;
if (lua_isboolean(L, 1))
status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
else
status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
if (lua_toboolean(L, 2))
lua_close(L);
if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */
return 0;
}
static const luaL_Reg syslib[] = {
{"clock", os_clock},
{"date", os_date},
{"difftime", os_difftime},
{"execute", os_execute},
{"exit", os_exit},
{"getenv", os_getenv},
{"remove", os_remove},
{"rename", os_rename},
{"setlocale", os_setlocale},
{"time", os_time},
{"tmpname", os_tmpname},
{NULL, NULL}
};
/* }====================================================== */
LUAMOD_API int luaopen_os (lua_State *L) {
luaL_newlib(L, syslib);
return 1;
}
/*
** $Id: ltests.c,v 2.211 2016/12/04 20:17:24 roberto Exp $
** Internal Module for Debugging of the Lua Implementation
** See Copyright Notice in lua.h
*/
#define ltests_c
#define LUA_CORE
#include "lprefix.h"
#include <limits.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lapi.h"
#include "lauxlib.h"
#include "lcode.h"
#include "lctype.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lmem.h"
#include "lopcodes.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "lualib.h"
/*
** The whole module only makes sense with LUA_DEBUG on
*/
#if defined(LUA_DEBUG)
void *l_Trick = 0;
int islocked = 0;
#define obj_at(L,k) (L->ci->func + (k))
static int runC (lua_State *L, lua_State *L1, const char *pc);
static void setnameval (lua_State *L, const char *name, int val) {
lua_pushstring(L, name);
lua_pushinteger(L, val);
lua_settable(L, -3);
}
static void pushobject (lua_State *L, const TValue *o) {
setobj2s(L, L->top, o);
api_incr_top(L);
}
static int tpanic (lua_State *L) {
fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n",
lua_tostring(L, -1));
return (exit(EXIT_FAILURE), 0); /* do not return to Lua */
}
/*
** {======================================================================
** Controlled version for realloc.
** =======================================================================
*/
#define MARK 0x55 /* 01010101 (a nice pattern) */
typedef union Header {
L_Umaxalign a; /* ensures maximum alignment for Header */
struct {
size_t size;
int type;
union Header *prev;
union Header *next;
} d;
} Header;
static Header headBlock;
static Header headBlock = {.d.next = &headBlock, .d.prev = &headBlock};
#if !defined(EXTERNMEMCHECK)
/* full memory check */
#define MARKSIZE 16 /* size of marks after each block */
#define fillmem(mem,size) memset(mem, -MARK, size)
#else
/* external memory check: don't do it twice */
#define MARKSIZE 0
#define fillmem(mem,size) /* empty */
#endif
Memcontrol l_memcontrol =
{0L, 0L, 0L, 0L, {0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L}};
static void freeblock (Memcontrol *mc, Header *block) {
if (block) {
size_t size = block->d.size;
int i;
block->d.next->d.prev = block->d.prev;
block->d.prev->d.next = block->d.next;
for (i = 0; i < MARKSIZE; i++) /* check marks after block */
lua_assert(*(cast(char *, block + 1) + size + i) == MARK);
mc->objcount[block->d.type]--;
fillmem(block, sizeof(Header) + size + MARKSIZE); /* erase block */
free(block); /* actually free block */
mc->numblocks--; /* update counts */
mc->total -= size;
}
}
extern void *LFSregion; //DEBUG
void *debug_realloc (void *ud, void *b, size_t oldsize, size_t size) {
Memcontrol *mc = cast(Memcontrol *, ud);
Header *block = cast(Header *, b);
int type;
if (mc->memlimit == 0) { /* first time? */
char *limit = getenv("MEMLIMIT"); /* initialize memory limit */
mc->memlimit = limit ? strtoul(limit, NULL, 10) : ULONG_MAX;
}
if (block == NULL) {
type = (oldsize < LUA_NUMTAGS) ? oldsize : 0;
oldsize = 0;
}
else {
block--; /* go to real header */
type = block->d.type;
lua_assert(oldsize == block->d.size);
}
if (size == 0) {
freeblock(mc, block);
return NULL;
}
else if (size > oldsize && mc->total+size-oldsize > mc->memlimit)
return NULL; /* fake a memory allocation error */
else {
Header *newblock;
int i;
size_t commonsize = (oldsize < size) ? oldsize : size;
size_t realsize = sizeof(Header) + size + MARKSIZE;
if (realsize < size) return NULL; /* arithmetic overflow! */
newblock = cast(Header *, malloc(realsize)); /* alloc a new block */
size_t op = (char *) newblock- (char *) LFSregion; //DEBUG
lua_assert(op>0x20000); //DEBUG
if (newblock == NULL) return NULL; /* really out of memory? */
if (block) {
memcpy(newblock + 1, block + 1, commonsize); /* copy old contents */
freeblock(mc, block); /* erase (and check) old copy */
}
/* initialize new part of the block with something weird */
fillmem(cast(char *, newblock + 1) + commonsize, size - commonsize);
/* initialize marks after block */
for (i = 0; i < MARKSIZE; i++)
*(cast(char *, newblock + 1) + size + i) = MARK;
newblock->d.size = size;
newblock->d.type = type;
newblock->d.next = headBlock.d.next;
newblock->d.prev = &headBlock;
newblock->d.next->d.prev = newblock;
headBlock.d.next = newblock;
mc->total += size;
if (mc->total > mc->maxmem)
mc->maxmem = mc->total;
mc->numblocks++;
mc->objcount[type]++;
return newblock + 1;
}
}
/* }====================================================================== */
/*
** {======================================================
** Functions to check memory consistency
** =======================================================
*/
static int testobjref1 (global_State *g, GCObject *f, GCObject *t) {
if (isdead(g,t)) return 0;
if (!issweepphase(g))
return !(isblack(f) && iswhite(t));
else return 1;
}
static void printobj (global_State *g, GCObject *o) {
printf("||%s(%p)-%c(%02X)||",
ttypename(novariant(o->tt)), (void *)o,
isdead(g,o)?'d':isblack(o)?'b':iswhite(o)?'w':'g', o->marked);
}
static int testobjref (global_State *g, GCObject *f, GCObject *t) {
int r1 = testobjref1(g, f, t);
if (!r1) {
printf("%d(%02X) - ", g->gcstate, g->currentwhite);
printobj(g, f);
printf(" -> ");
printobj(g, t);
printf("\n");
}
return r1;
}
#define checkobjref(g,f,t) \
{ if (t) lua_longassert(testobjref(g,f,obj2gco(t))); }
static void checkvalref (global_State *g, GCObject *f, const TValue *t) {
lua_assert(!iscollectable(t) ||
(righttt(t) && testobjref(g, f, gcvalue(t))));
}
static void checktable (global_State *g, Table *h) {
unsigned int i;
Node *n, *limit = gnode(h, sizenode(h));
GCObject *hgc = obj2gco(h);
checkobjref(g, hgc, h->metatable);
for (i = 0; i < h->sizearray; i++)
checkvalref(g, hgc, &h->array[i]);
for (n = gnode(h, 0); n < limit; n++) {
if (!ttisnil(gval(n))) {
lua_assert(!ttisnil(gkey(n)));
checkvalref(g, hgc, gkey(n));
checkvalref(g, hgc, gval(n));
}
}
}
/*
** All marks are conditional because a GC may happen while the
** prototype is still being created
*/
static void checkproto (global_State *g, Proto *f) {
int i;
GCObject *fgc = obj2gco(f);
checkobjref(g, fgc, f->source);
for (i=0; i<f->sizek; i++) {
if (ttisstring(f->k + i))
checkobjref(g, fgc, tsvalue(f->k + i));
}
for (i=0; i<f->sizeupvalues; i++)
checkobjref(g, fgc, f->upvalues[i].name);
for (i=0; i<f->sizep; i++)
checkobjref(g, fgc, f->p[i]);
for (i=0; i<f->sizelocvars; i++)
checkobjref(g, fgc, f->locvars[i].varname);
}
static void checkCclosure (global_State *g, CClosure *cl) {
GCObject *clgc = obj2gco(cl);
int i;
for (i = 0; i < cl->nupvalues; i++)
checkvalref(g, clgc, &cl->upvalue[i]);
}
static void checkLclosure (global_State *g, LClosure *cl) {
GCObject *clgc = obj2gco(cl);
int i;
checkobjref(g, clgc, cl->p);
for (i=0; i<cl->nupvalues; i++) {
UpVal *uv = cl->upvals[i];
if (uv) {
if (!upisopen(uv)) /* only closed upvalues matter to invariant */
checkvalref(g, clgc, uv->v);
lua_assert(uv->refcount > 0);
}
}
}
static int lua_checkpc (lua_State *L, CallInfo *ci) {
if (!isLua(ci)) return 1;
else {
/* if function yielded (inside a hook), real 'func' is in 'extra' field */
StkId f = (L->status != LUA_YIELD || ci != L->ci)
? ci->func
: restorestack(L, ci->extra);
Proto *p = clLvalue(f)->p;
return p->code <= ci->u.l.savedpc &&
ci->u.l.savedpc <= p->code + p->sizecode;
}
}
static void checkstack (global_State *g, lua_State *L1) {
StkId o;
CallInfo *ci;
UpVal *uv;
lua_assert(!isdead(g, L1));
for (uv = L1->openupval; uv != NULL; uv = uv->u.open.next)
lua_assert(upisopen(uv)); /* must be open */
for (ci = L1->ci; ci != NULL; ci = ci->previous) {
lua_assert(ci->top <= L1->stack_last);
lua_assert(lua_checkpc(L1, ci));
}
if (L1->stack) { /* complete thread? */
for (o = L1->stack; o < L1->stack_last + EXTRA_STACK; o++)
checkliveness(L1, o); /* entire stack must have valid values */
}
else lua_assert(L1->stacksize == 0);
}
static void checkobject (global_State *g, GCObject *o, int maybedead) {
if (isdead(g, o))
lua_assert(maybedead);
else {
lua_assert(g->gcstate != GCSpause || iswhite(o));
switch (o->tt) {
case LUA_TUSERDATA: {
TValue uservalue;
Table *mt = gco2u(o)->metatable;
checkobjref(g, o, mt);
getuservalue(g->mainthread, gco2u(o), &uservalue);
checkvalref(g, o, &uservalue);
break;
}
case LUA_TTABLE: {
checktable(g, gco2t(o));
break;
}
case LUA_TTHREAD: {
checkstack(g, gco2th(o));
break;
}
case LUA_TLCL: {
checkLclosure(g, gco2lcl(o));
break;
}
case LUA_TCCL: {
checkCclosure(g, gco2ccl(o));
break;
}
case LUA_TPROTO: {
checkproto(g, gco2p(o));
break;
}
case LUA_TSHRSTR:
case LUA_TLNGSTR: {
lua_assert(!isgray(o)); /* strings are never gray */
break;
}
default: lua_assert(0);
}
}
}
#define TESTGRAYBIT 7
static void checkgraylist (global_State *g, GCObject *o) {
((void)g); /* better to keep it available if we need to print an object */
while (o) {
lua_assert(isgray(o));
lua_assert(!testbit(o->marked, TESTGRAYBIT));
l_setbit(o->marked, TESTGRAYBIT);
switch (o->tt) {
case LUA_TTABLE: o = gco2t(o)->gclist; break;
case LUA_TLCL: o = gco2lcl(o)->gclist; break;
case LUA_TCCL: o = gco2ccl(o)->gclist; break;
case LUA_TTHREAD: o = gco2th(o)->gclist; break;
case LUA_TPROTO: o = gco2p(o)->gclist; break;
default: lua_assert(0); /* other objects cannot be gray */
}
}
}
/*
** mark all objects in gray lists with the TESTGRAYBIT, so that
** 'checkmemory' can check that all gray objects are in a gray list
*/
static void markgrays (global_State *g) {
if (!keepinvariant(g)) return;
checkgraylist(g, g->gray);
checkgraylist(g, g->grayagain);
checkgraylist(g, g->weak);
checkgraylist(g, g->ephemeron);
checkgraylist(g, g->allweak);
}
static void checkgray (global_State *g, GCObject *o) {
for (; o != NULL; o = o->next) {
if (isgray(o)) {
lua_assert(!keepinvariant(g) || testbit(o->marked, TESTGRAYBIT));
resetbit(o->marked, TESTGRAYBIT);
}
lua_assert(!testbit(o->marked, TESTGRAYBIT));
}
}
int lua_checkmemory (lua_State *L) {
global_State *g = G(L);
GCObject *o;
int maybedead;
if (keepinvariant(g)) {
lua_assert(!iswhite(g->mainthread));
lua_assert(!iswhite(gcvalue(&g->l_registry)));
}
lua_assert(!isdead(g, gcvalue(&g->l_registry)));
checkstack(g, g->mainthread);
resetbit(g->mainthread->marked, TESTGRAYBIT);
lua_assert(g->sweepgc == NULL || issweepphase(g));
markgrays(g);
/* check 'fixedgc' list */
for (o = g->fixedgc; o != NULL; o = o->next) {
lua_assert(o->tt == LUA_TSHRSTR && isgray(o));
}
/* check 'allgc' list */
checkgray(g, g->allgc);
maybedead = (GCSatomic < g->gcstate && g->gcstate <= GCSswpallgc);
for (o = g->allgc; o != NULL; o = o->next) {
checkobject(g, o, maybedead);
lua_assert(!tofinalize(o));
}
/* check 'finobj' list */
checkgray(g, g->finobj);
for (o = g->finobj; o != NULL; o = o->next) {
checkobject(g, o, 0);
lua_assert(tofinalize(o));
lua_assert(o->tt == LUA_TUSERDATA || o->tt == LUA_TTABLE);
}
/* check 'tobefnz' list */
checkgray(g, g->tobefnz);
for (o = g->tobefnz; o != NULL; o = o->next) {
checkobject(g, o, 0);
lua_assert(tofinalize(o));
lua_assert(o->tt == LUA_TUSERDATA || o->tt == LUA_TTABLE);
}
return 0;
}
/* }====================================================== */
/*
** {======================================================
** Disassembler
** =======================================================
*/
static char *buildop (Proto *p, int pc, char *buff) {
Instruction i = p->code[pc];
OpCode o = GET_OPCODE(i);
const char *name = luaP_opnames[o];
int line = luaG_getfuncline(NULL, p, pc);
sprintf(buff, "(%4d) %4d - ", line, pc);
switch (getOpMode(o)) {
case iABC:
sprintf(buff+strlen(buff), "%-12s%4d %4d %4d", name,
GETARG_A(i), GETARG_B(i), GETARG_C(i));
break;
case iABx:
sprintf(buff+strlen(buff), "%-12s%4d %4d", name, GETARG_A(i), GETARG_Bx(i));
break;
case iAsBx:
sprintf(buff+strlen(buff), "%-12s%4d %4d", name, GETARG_A(i), GETARG_sBx(i));
break;
case iAx:
sprintf(buff+strlen(buff), "%-12s%4d", name, GETARG_Ax(i));
break;
}
return buff;
}
#if 0
void luaI_printcode (Proto *pt, int size) {
int pc;
for (pc=0; pc<size; pc++) {
char buff[100];
printf("%s\n", buildop(pt, pc, buff));
}
printf("-------\n");
}
void luaI_printinst (Proto *pt, int pc) {
char buff[100];
printf("%s\n", buildop(pt, pc, buff));
}
#endif
static int listcode (lua_State *L) {
int pc;
Proto *p;
luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
1, "Lua function expected");
p = getproto(obj_at(L, 1));
lua_newtable(L);
setnameval(L, "maxstack", p->maxstacksize);
setnameval(L, "numparams", p->numparams);
for (pc=0; pc<p->sizecode; pc++) {
char buff[100];
lua_pushinteger(L, pc+1);
lua_pushstring(L, buildop(p, pc, buff));
lua_settable(L, -3);
}
return 1;
}
static int listk (lua_State *L) {
Proto *p;
int i;
luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
1, "Lua function expected");
p = getproto(obj_at(L, 1));
lua_createtable(L, p->sizek, 0);
for (i=0; i<p->sizek; i++) {
pushobject(L, p->k+i);
lua_rawseti(L, -2, i+1);
}
return 1;
}
static int listlocals (lua_State *L) {
Proto *p;
int pc = cast_int(luaL_checkinteger(L, 2)) - 1;
int i = 0;
const char *name;
luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
1, "Lua function expected");
p = getproto(obj_at(L, 1));
while ((name = luaF_getlocalname(p, ++i, pc)) != NULL)
lua_pushstring(L, name);
return i-1;
}
/* }====================================================== */
static void printstack (lua_State *L) {
int i;
int n = lua_gettop(L);
for (i = 1; i <= n; i++) {
printf("%3d: %s\n", i, luaL_tolstring(L, i, NULL));
lua_pop(L, 1);
}
printf("\n");
}
static int get_limits (lua_State *L) {
lua_createtable(L, 0, 5);
setnameval(L, "BITS_INT", LUAI_BITSINT);
setnameval(L, "MAXARG_Ax", MAXARG_Ax);
setnameval(L, "MAXARG_Bx", MAXARG_Bx);
setnameval(L, "MAXARG_sBx", MAXARG_sBx);
setnameval(L, "BITS_INT", LUAI_BITSINT);
setnameval(L, "LFPF", LFIELDS_PER_FLUSH);
setnameval(L, "NUM_OPCODES", NUM_OPCODES);
return 1;
}
static int mem_query (lua_State *L) {
if (lua_isnone(L, 1)) {
lua_pushinteger(L, l_memcontrol.total);
lua_pushinteger(L, l_memcontrol.numblocks);
lua_pushinteger(L, l_memcontrol.maxmem);
return 3;
}
else if (lua_isnumber(L, 1)) {
unsigned long limit = cast(unsigned long, luaL_checkinteger(L, 1));
if (limit == 0) limit = ULONG_MAX;
l_memcontrol.memlimit = limit;
return 0;
}
else {
const char *t = luaL_checkstring(L, 1);
int i;
for (i = LUA_NUMTAGS - 1; i >= 0; i--) {
if (strcmp(t, ttypename(i)) == 0) {
lua_pushinteger(L, l_memcontrol.objcount[i]);
return 1;
}
}
return luaL_error(L, "unkown type '%s'", t);
}
}
static int settrick (lua_State *L) {
if (ttisnil(obj_at(L, 1)))
l_Trick = NULL;
else
l_Trick = gcvalue(obj_at(L, 1));
return 0;
}
static int gc_color (lua_State *L) {
TValue *o;
luaL_checkany(L, 1);
o = obj_at(L, 1);
if (!iscollectable(o))
lua_pushstring(L, "no collectable");
else {
GCObject *obj = gcvalue(o);
lua_pushstring(L, isdead(G(L), obj) ? "dead" :
iswhite(obj) ? "white" :
isblack(obj) ? "black" : "grey");
}
return 1;
}
static int gc_state (lua_State *L) {
static const char *statenames[] = {"propagate", "atomic", "sweepallgc",
"sweepfinobj", "sweeptobefnz", "sweepend", "pause", ""};
static const int states[] = {GCSpropagate, GCSatomic, GCSswpallgc,
GCSswpfinobj, GCSswptobefnz, GCSswpend, GCSpause, -1};
int option = states[luaL_checkoption(L, 1, "", statenames)];
if (option == -1) {
lua_pushstring(L, statenames[G(L)->gcstate]);
return 1;
}
else {
global_State *g = G(L);
lua_lock(L);
if (option < g->gcstate) { /* must cross 'pause'? */
luaC_runtilstate(L, bitmask(GCSpause)); /* run until pause */
}
luaC_runtilstate(L, bitmask(option));
lua_assert(G(L)->gcstate == option);
lua_unlock(L);
return 0;
}
}
static int hash_query (lua_State *L) {
if (lua_isnone(L, 2)) {
luaL_argcheck(L, lua_type(L, 1) == LUA_TSTRING, 1, "string expected");
lua_pushinteger(L, tsvalue(obj_at(L, 1))->hash);
}
else {
TValue *o = obj_at(L, 1);
Table *t;
luaL_checktype(L, 2, LUA_TTABLE);
t = hvalue(obj_at(L, 2));
lua_pushinteger(L, luaH_mainposition(t, o) - t->node);
}
return 1;
}
static int stacklevel (lua_State *L) {
unsigned long a = 0;
lua_pushinteger(L, (L->top - L->stack));
lua_pushinteger(L, (L->stack_last - L->stack));
lua_pushinteger(L, (unsigned long)&a);
return 3;
}
static int table_query (lua_State *L) {
const Table *t;
int i = cast_int(luaL_optinteger(L, 2, -1));
luaL_checktype(L, 1, LUA_TTABLE);
t = hvalue(obj_at(L, 1));
if(isrwtable(t)) {
if (i == -1) {
lua_pushinteger(L, t->sizearray);
lua_pushinteger(L, allocsizenode(t));
lua_pushinteger(L, isdummy(t) ? 0 : t->lastfree - t->node);
}
else if ((unsigned int)i < t->sizearray) {
lua_pushinteger(L, i);
pushobject(L, &t->array[i]);
lua_pushnil(L);
}
else if ((i -= t->sizearray) < sizenode(t)) {
if (!ttisnil(gval(gnode(t, i))) ||
ttisnil(gkey(gnode(t, i))) ||
ttisnumber(gkey(gnode(t, i)))) {
pushobject(L, gkey(gnode(t, i)));
}
else
lua_pushliteral(L, "<undef>");
pushobject(L, gval(gnode(t, i)));
if (gnext(&t->node[i]) != 0)
lua_pushinteger(L, gnext(&t->node[i]));
else
lua_pushnil(L);
}
} else { /* is ROTable */
ROTable *rt = cast(ROTable*, t);
if (i == -1) {
lua_pushinteger(L, 0);
lua_pushinteger(L, rt->lsizenode);
}
else {
lua_pushliteral(L, "<undef>");
lua_pushnil(L);
}
lua_pushvalue(L, -1);
}
return 3;
}
static int string_query (lua_State *L) {
stringtable *tb = &G(L)->strt;
int s = cast_int(luaL_optinteger(L, 1, 0)) - 1;
if (s == -1) {
lua_pushinteger(L ,tb->size);
lua_pushinteger(L ,tb->nuse);
return 2;
}
else if (s < tb->size) {
TString *ts;
int n = 0;
for (ts = tb->hash[s]; ts != NULL; ts = ts->u.hnext) {
setsvalue2s(L, L->top, ts);
api_incr_top(L);
n++;
}
return n;
}
else return 0;
}
static int tref (lua_State *L) {
int level = lua_gettop(L);
luaL_checkany(L, 1);
lua_pushvalue(L, 1);
lua_pushinteger(L, luaL_ref(L, LUA_REGISTRYINDEX));
lua_assert(lua_gettop(L) == level+1); /* +1 for result */
return 1;
}
static int getref (lua_State *L) {
int level = lua_gettop(L);
lua_rawgeti(L, LUA_REGISTRYINDEX, luaL_checkinteger(L, 1));
lua_assert(lua_gettop(L) == level+1);
return 1;
}
static int unref (lua_State *L) {
int level = lua_gettop(L);
luaL_unref(L, LUA_REGISTRYINDEX, cast_int(luaL_checkinteger(L, 1)));
lua_assert(lua_gettop(L) == level);
return 0;
}
static int upvalue (lua_State *L) {
int n = cast_int(luaL_checkinteger(L, 2));
luaL_checktype(L, 1, LUA_TFUNCTION);
if (lua_isnone(L, 3)) {
const char *name = lua_getupvalue(L, 1, n);
if (name == NULL) return 0;
lua_pushstring(L, name);
return 2;
}
else {
const char *name = lua_setupvalue(L, 1, n);
lua_pushstring(L, name);
return 1;
}
}
static int newuserdata (lua_State *L) {
size_t size = cast(size_t, luaL_checkinteger(L, 1));
char *p = cast(char *, lua_newuserdata(L, size));
while (size--) *p++ = '\0';
return 1;
}
static int pushuserdata (lua_State *L) {
lua_Integer u = luaL_checkinteger(L, 1);
lua_pushlightuserdata(L, cast(void *, cast(size_t, u)));
return 1;
}
static int udataval (lua_State *L) {
lua_pushinteger(L, cast(long, lua_touserdata(L, 1)));
return 1;
}
static int doonnewstack (lua_State *L) {
lua_State *L1 = lua_newthread(L);
size_t l;
const char *s = luaL_checklstring(L, 1, &l);
int status = luaL_loadbuffer(L1, s, l, s);
if (status == LUA_OK)
status = lua_pcall(L1, 0, 0, 0);
lua_pushinteger(L, status);
return 1;
}
static int s2d (lua_State *L) {
lua_pushnumber(L, *cast(const double *, luaL_checkstring(L, 1)));
return 1;
}
static int d2s (lua_State *L) {
double d = luaL_checknumber(L, 1);
lua_pushlstring(L, cast(char *, &d), sizeof(d));
return 1;
}
static int num2int (lua_State *L) {
lua_pushinteger(L, lua_tointeger(L, 1));
return 1;
}
static int newstate (lua_State *L) {
void *ud;
lua_Alloc f = lua_getallocf(L, &ud);
lua_State *L1 = lua_newstate(f, ud);
if (L1) {
lua_atpanic(L1, tpanic);
lua_pushlightuserdata(L, L1);
}
else
lua_pushnil(L);
return 1;
}
static lua_State *getstate (lua_State *L) {
lua_State *L1 = cast(lua_State *, lua_touserdata(L, 1));
luaL_argcheck(L, L1 != NULL, 1, "state expected");
return L1;
}
static int loadlib (lua_State *L) {
static const luaL_Reg libs[] = {
// {"_G", luaopen_base},
{"io", luaopen_io},
{"os", luaopen_os},
{"string", luaopen_string},
// The following are mapped into _G __index path from ROM
// {"coroutine", luaopen_coroutine},
// {"debug", luaopen_debug},
// {"math", luaopen_math},
// {"table", luaopen_table},
{NULL, NULL}
};
lua_State *L1 = getstate(L);
int i;
luaL_requiref(L1, "package", luaopen_package, 0);
lua_assert(lua_type(L1, -1) == LUA_TTABLE);
/* 'requiref' should not reload module already loaded... */
luaL_requiref(L1, "package", NULL, 1); /* seg. fault if it reloads */
/* ...but should return the same module */
lua_assert(lua_compare(L1, -1, -2, LUA_OPEQ));
luaL_requiref(L1, "_G", luaopen_base, 1);
luaL_getsubtable(L1, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
for (i = 0; libs[i].name; i++) {
lua_pushcfunction(L1, libs[i].func);
lua_setfield(L1, -2, libs[i].name);
}
return 0;
}
static int closestate (lua_State *L) {
lua_State *L1 = getstate(L);
lua_close(L1);
return 0;
}
static int doremote (lua_State *L) {
lua_State *L1 = getstate(L);
size_t lcode;
const char *code = luaL_checklstring(L, 2, &lcode);
int status;
lua_settop(L1, 0);
status = luaL_loadbuffer(L1, code, lcode, code);
if (status == LUA_OK)
status = lua_pcall(L1, 0, LUA_MULTRET, 0);
if (status != LUA_OK) {
lua_pushnil(L);
lua_pushstring(L, lua_tostring(L1, -1));
lua_pushinteger(L, status);
return 3;
}
else {
int i = 0;
while (!lua_isnone(L1, ++i))
lua_pushstring(L, lua_tostring(L1, i));
lua_pop(L1, i-1);
return i-1;
}
}
static int int2fb_aux (lua_State *L) {
int b = luaO_int2fb((unsigned int)luaL_checkinteger(L, 1));
lua_pushinteger(L, b);
lua_pushinteger(L, (unsigned int)luaO_fb2int(b));
return 2;
}
static int log2_aux (lua_State *L) {
unsigned int x = (unsigned int)luaL_checkinteger(L, 1);
lua_pushinteger(L, luaO_ceillog2(x));
return 1;
}
struct Aux { jmp_buf jb; const char *paniccode; lua_State *L; };
/*
** does a long-jump back to "main program".
*/
static int panicback (lua_State *L) {
struct Aux *b;
lua_checkstack(L, 1); /* open space for 'Aux' struct */
lua_getfield(L, LUA_REGISTRYINDEX, "_jmpbuf"); /* get 'Aux' struct */
b = (struct Aux *)lua_touserdata(L, -1);
lua_pop(L, 1); /* remove 'Aux' struct */
runC(b->L, L, b->paniccode); /* run optional panic code */
longjmp(b->jb, 1);
return 1; /* to avoid warnings */
}
static int checkpanic (lua_State *L) {
struct Aux b;
void *ud;
lua_State *L1;
const char *code = luaL_checkstring(L, 1);
lua_Alloc f = lua_getallocf(L, &ud);
b.paniccode = luaL_optstring(L, 2, "");
b.L = L;
L1 = lua_newstate(f, ud); /* create new state */
if (L1 == NULL) { /* error? */
lua_pushnil(L);
return 1;
}
lua_atpanic(L1, panicback); /* set its panic function */
lua_pushlightuserdata(L1, &b);
lua_setfield(L1, LUA_REGISTRYINDEX, "_jmpbuf"); /* store 'Aux' struct */
if (setjmp(b.jb) == 0) { /* set jump buffer */
runC(L, L1, code); /* run code unprotected */
lua_pushliteral(L, "no errors");
}
else { /* error handling */
/* move error message to original state */
lua_pushstring(L, lua_tostring(L1, -1));
}
lua_close(L1);
return 1;
}
/*
** {====================================================================
** function to test the API with C. It interprets a kind of assembler
** language with calls to the API, so the test can be driven by Lua code
** =====================================================================
*/
static void sethookaux (lua_State *L, int mask, int count, const char *code);
static const char *const delimits = " \t\n,;";
static void skip (const char **pc) {
for (;;) {
if (**pc != '\0' && strchr(delimits, **pc)) (*pc)++;
else if (**pc == '#') {
while (**pc != '\n' && **pc != '\0') (*pc)++;
}
else break;
}
}
static int getnum_aux (lua_State *L, lua_State *L1, const char **pc) {
int res = 0;
int sig = 1;
skip(pc);
if (**pc == '.') {
res = cast_int(lua_tointeger(L1, -1));
lua_pop(L1, 1);
(*pc)++;
return res;
}
else if (**pc == '*') {
res = lua_gettop(L1);
(*pc)++;
return res;
}
else if (**pc == '-') {
sig = -1;
(*pc)++;
}
if (!lisdigit(cast_uchar(**pc)))
luaL_error(L, "number expected (%s)", *pc);
while (lisdigit(cast_uchar(**pc))) res = res*10 + (*(*pc)++) - '0';
return sig*res;
}
static const char *getstring_aux (lua_State *L, char *buff, const char **pc) {
int i = 0;
skip(pc);
if (**pc == '"' || **pc == '\'') { /* quoted string? */
int quote = *(*pc)++;
while (**pc != quote) {
if (**pc == '\0') luaL_error(L, "unfinished string in C script");
buff[i++] = *(*pc)++;
}
(*pc)++;
}
else {
while (**pc != '\0' && !strchr(delimits, **pc))
buff[i++] = *(*pc)++;
}
buff[i] = '\0';
return buff;
}
static int getindex_aux (lua_State *L, lua_State *L1, const char **pc) {
skip(pc);
switch (*(*pc)++) {
case 'R': return LUA_REGISTRYINDEX;
case 'G': return luaL_error(L, "deprecated index 'G'");
case 'U': return lua_upvalueindex(getnum_aux(L, L1, pc));
default: (*pc)--; return getnum_aux(L, L1, pc);
}
}
static void pushcode (lua_State *L, int code) {
static const char *const codes[] = {"OK", "YIELD", "ERRRUN",
"ERRSYNTAX", "ERRMEM", "ERRGCMM", "ERRERR"};
lua_pushstring(L, codes[code]);
}
#define EQ(s1) (strcmp(s1, inst) == 0)
#define getnum (getnum_aux(L, L1, &pc))
#define getstring (getstring_aux(L, buff, &pc))
#define getindex (getindex_aux(L, L1, &pc))
static int testC (lua_State *L);
static int Cfunck (lua_State *L, int status, lua_KContext ctx);
/*
** arithmetic operation encoding for 'arith' instruction
** LUA_OPIDIV -> \
** LUA_OPSHL -> <
** LUA_OPSHR -> >
** LUA_OPUNM -> _
** LUA_OPBNOT -> !
*/
static const char ops[] = "+-*%^/\\&|~<>_!";
static int runC (lua_State *L, lua_State *L1, const char *pc) {
char buff[300];
int status = 0;
if (pc == NULL) return luaL_error(L, "attempt to runC null script");
for (;;) {
const char *inst = getstring;
if EQ("") return 0;
else if EQ("absindex") {
lua_pushnumber(L1, lua_absindex(L1, getindex));
}
else if EQ("append") {
int t = getindex;
int i = lua_rawlen(L1, t);
lua_rawseti(L1, t, i + 1);
}
else if EQ("arith") {
int op;
skip(&pc);
op = strchr(ops, *pc++) - ops;
lua_arith(L1, op);
}
else if EQ("call") {
int narg = getnum;
int nres = getnum;
lua_call(L1, narg, nres);
}
else if EQ("callk") {
int narg = getnum;
int nres = getnum;
int i = getindex;
lua_callk(L1, narg, nres, i, Cfunck);
}
else if EQ("checkstack") {
int sz = getnum;
const char *msg = getstring;
if (*msg == '\0')
msg = NULL; /* to test 'luaL_checkstack' with no message */
luaL_checkstack(L1, sz, msg);
}
else if EQ("compare") {
const char *opt = getstring; /* EQ, LT, or LE */
int op = (opt[0] == 'E') ? LUA_OPEQ
: (opt[1] == 'T') ? LUA_OPLT : LUA_OPLE;
int a = getindex;
int b = getindex;
lua_pushboolean(L1, lua_compare(L1, a, b, op));
}
else if EQ("concat") {
lua_concat(L1, getnum);
}
else if EQ("copy") {
int f = getindex;
lua_copy(L1, f, getindex);
}
else if EQ("func2num") {
lua_CFunction func = lua_tocfunction(L1, getindex);
lua_pushnumber(L1, cast(size_t, func));
}
else if EQ("getfield") {
int t = getindex;
lua_getfield(L1, t, getstring);
}
else if EQ("getglobal") {
lua_getglobal(L1, getstring);
}
else if EQ("getmetatable") {
if (lua_getmetatable(L1, getindex) == 0)
lua_pushnil(L1);
}
else if EQ("gettable") {
lua_gettable(L1, getindex);
}
else if EQ("gettop") {
lua_pushinteger(L1, lua_gettop(L1));
}
else if EQ("gsub") {
int a = getnum; int b = getnum; int c = getnum;
luaL_gsub(L1, lua_tostring(L1, a),
lua_tostring(L1, b),
lua_tostring(L1, c));
}
else if EQ("insert") {
lua_insert(L1, getnum);
}
else if EQ("iscfunction") {
lua_pushboolean(L1, lua_iscfunction(L1, getindex));
}
else if EQ("isfunction") {
lua_pushboolean(L1, lua_isfunction(L1, getindex));
}
else if EQ("isnil") {
lua_pushboolean(L1, lua_isnil(L1, getindex));
}
else if EQ("isnull") {
lua_pushboolean(L1, lua_isnone(L1, getindex));
}
else if EQ("isnumber") {
lua_pushboolean(L1, lua_isnumber(L1, getindex));
}
else if EQ("isstring") {
lua_pushboolean(L1, lua_isstring(L1, getindex));
}
else if EQ("istable") {
lua_pushboolean(L1, lua_istable(L1, getindex));
}
else if EQ("isudataval") {
lua_pushboolean(L1, lua_islightuserdata(L1, getindex));
}
else if EQ("isuserdata") {
lua_pushboolean(L1, lua_isuserdata(L1, getindex));
}
else if EQ("len") {
lua_len(L1, getindex);
}
else if EQ("Llen") {
lua_pushinteger(L1, luaL_len(L1, getindex));
}
else if EQ("loadfile") {
luaL_loadfile(L1, luaL_checkstring(L1, getnum));
}
else if EQ("loadstring") {
const char *s = luaL_checkstring(L1, getnum);
luaL_loadstring(L1, s);
}
else if EQ("newmetatable") {
lua_pushboolean(L1, luaL_newmetatable(L1, getstring));
}
else if EQ("newtable") {
lua_newtable(L1);
}
else if EQ("newthread") {
lua_newthread(L1);
}
else if EQ("newuserdata") {
lua_newuserdata(L1, getnum);
}
else if EQ("next") {
lua_next(L1, -2);
}
else if EQ("objsize") {
lua_pushinteger(L1, lua_rawlen(L1, getindex));
}
else if EQ("pcall") {
int narg = getnum;
int nres = getnum;
status = lua_pcall(L1, narg, nres, getnum);
}
else if EQ("pcallk") {
int narg = getnum;
int nres = getnum;
int i = getindex;
status = lua_pcallk(L1, narg, nres, 0, i, Cfunck);
}
else if EQ("pop") {
lua_pop(L1, getnum);
}
else if EQ("print") {
int n = getnum;
if (n != 0) {
printf("%s\n", luaL_tolstring(L1, n, NULL));
lua_pop(L1, 1);
}
else printstack(L1);
}
else if EQ("pushbool") {
lua_pushboolean(L1, getnum);
}
else if EQ("pushcclosure") {
lua_pushcclosure(L1, testC, getnum);
}
else if EQ("pushint") {
lua_pushinteger(L1, getnum);
}
else if EQ("pushnil") {
lua_pushnil(L1);
}
else if EQ("pushnum") {
lua_pushnumber(L1, (lua_Number)getnum);
}
else if EQ("pushstatus") {
pushcode(L1, status);
}
else if EQ("pushstring") {
lua_pushstring(L1, getstring);
}
else if EQ("pushupvalueindex") {
lua_pushinteger(L1, lua_upvalueindex(getnum));
}
else if EQ("pushvalue") {
lua_pushvalue(L1, getindex);
}
else if EQ("rawgeti") {
int t = getindex;
lua_rawgeti(L1, t, getnum);
}
else if EQ("rawgetp") {
int t = getindex;
lua_rawgetp(L1, t, cast(void *, cast(size_t, getnum)));
}
else if EQ("rawsetp") {
int t = getindex;
lua_rawsetp(L1, t, cast(void *, cast(size_t, getnum)));
}
else if EQ("remove") {
lua_remove(L1, getnum);
}
else if EQ("replace") {
lua_replace(L1, getindex);
}
else if EQ("resume") {
int i = getindex;
status = lua_resume(lua_tothread(L1, i), L, getnum);
}
else if EQ("return") {
int n = getnum;
if (L1 != L) {
int i;
for (i = 0; i < n; i++)
lua_pushstring(L, lua_tostring(L1, -(n - i)));
}
return n;
}
else if EQ("rotate") {
int i = getindex;
lua_rotate(L1, i, getnum);
}
else if EQ("setfield") {
int t = getindex;
lua_setfield(L1, t, getstring);
}
else if EQ("setglobal") {
lua_setglobal(L1, getstring);
}
else if EQ("sethook") {
int mask = getnum;
int count = getnum;
sethookaux(L1, mask, count, getstring);
}
else if EQ("setmetatable") {
lua_setmetatable(L1, getindex);
}
else if EQ("settable") {
lua_settable(L1, getindex);
}
else if EQ("settop") {
lua_settop(L1, getnum);
}
else if EQ("testudata") {
int i = getindex;
lua_pushboolean(L1, luaL_testudata(L1, i, getstring) != NULL);
}
else if EQ("error") {
lua_error(L1);
}
else if EQ("throw") {
#if defined(__cplusplus)
static struct X { int x; } x;
throw x;
#else
luaL_error(L1, "C++");
#endif
break;
}
else if EQ("tobool") {
lua_pushboolean(L1, lua_toboolean(L1, getindex));
}
else if EQ("tocfunction") {
lua_pushcfunction(L1, lua_tocfunction(L1, getindex));
}
else if EQ("tointeger") {
lua_pushinteger(L1, lua_tointeger(L1, getindex));
}
else if EQ("tonumber") {
lua_pushnumber(L1, lua_tonumber(L1, getindex));
}
else if EQ("topointer") {
lua_pushnumber(L1, cast(size_t, lua_topointer(L1, getindex)));
}
else if EQ("tostring") {
const char *s = lua_tostring(L1, getindex);
const char *s1 = lua_pushstring(L1, s);
lua_longassert((s == NULL && s1 == NULL) || strcmp(s, s1) == 0);
}
else if EQ("type") {
lua_pushstring(L1, luaL_typename(L1, getnum));
}
else if EQ("xmove") {
int f = getindex;
int t = getindex;
lua_State *fs = (f == 0) ? L1 : lua_tothread(L1, f);
lua_State *ts = (t == 0) ? L1 : lua_tothread(L1, t);
int n = getnum;
if (n == 0) n = lua_gettop(fs);
lua_xmove(fs, ts, n);
}
else if EQ("yield") {
return lua_yield(L1, getnum);
}
else if EQ("yieldk") {
int nres = getnum;
int i = getindex;
return lua_yieldk(L1, nres, i, Cfunck);
}
else luaL_error(L, "unknown instruction %s", buff);
}
return 0;
}
static int testC (lua_State *L) {
lua_State *L1;
const char *pc;
if (lua_isuserdata(L, 1)) {
L1 = getstate(L);
pc = luaL_checkstring(L, 2);
}
else if (lua_isthread(L, 1)) {
L1 = lua_tothread(L, 1);
pc = luaL_checkstring(L, 2);
}
else {
L1 = L;
pc = luaL_checkstring(L, 1);
}
return runC(L, L1, pc);
}
static int Cfunc (lua_State *L) {
return runC(L, L, lua_tostring(L, lua_upvalueindex(1)));
}
static int Cfunck (lua_State *L, int status, lua_KContext ctx) {
pushcode(L, status);
lua_setglobal(L, "status");
lua_pushinteger(L, ctx);
lua_setglobal(L, "ctx");
return runC(L, L, lua_tostring(L, ctx));
}
static int makeCfunc (lua_State *L) {
luaL_checkstring(L, 1);
lua_pushcclosure(L, Cfunc, lua_gettop(L));
return 1;
}
/* }====================================================== */
/*
** {======================================================
** tests for C hooks
** =======================================================
*/
/*
** C hook that runs the C script stored in registry.C_HOOK[L]
*/
static void Chook (lua_State *L, lua_Debug *ar) {
const char *scpt;
const char *const events [] = {"call", "ret", "line", "count", "tailcall"};
lua_getfield(L, LUA_REGISTRYINDEX, "C_HOOK");
lua_pushlightuserdata(L, L);
lua_gettable(L, -2); /* get C_HOOK[L] (script saved by sethookaux) */
scpt = lua_tostring(L, -1); /* not very religious (string will be popped) */
lua_pop(L, 2); /* remove C_HOOK and script */
lua_pushstring(L, events[ar->event]); /* may be used by script */
lua_pushinteger(L, ar->currentline); /* may be used by script */
runC(L, L, scpt); /* run script from C_HOOK[L] */
}
/*
** sets 'registry.C_HOOK[L] = scpt' and sets 'Chook' as a hook
*/
static void sethookaux (lua_State *L, int mask, int count, const char *scpt) {
if (*scpt == '\0') { /* no script? */
lua_sethook(L, NULL, 0, 0); /* turn off hooks */
return;
}
lua_getfield(L, LUA_REGISTRYINDEX, "C_HOOK"); /* get C_HOOK table */
if (!lua_istable(L, -1)) { /* no hook table? */
lua_pop(L, 1); /* remove previous value */
lua_newtable(L); /* create new C_HOOK table */
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, "C_HOOK"); /* register it */
}
lua_pushlightuserdata(L, L);
lua_pushstring(L, scpt);
lua_settable(L, -3); /* C_HOOK[L] = script */
lua_sethook(L, Chook, mask, count);
}
static int sethook (lua_State *L) {
if (lua_isnoneornil(L, 1))
lua_sethook(L, NULL, 0, 0); /* turn off hooks */
else {
const char *scpt = luaL_checkstring(L, 1);
const char *smask = luaL_checkstring(L, 2);
int count = cast_int(luaL_optinteger(L, 3, 0));
int mask = 0;
if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
if (strchr(smask, 'r')) mask |= LUA_MASKRET;
if (strchr(smask, 'l')) mask |= LUA_MASKLINE;
if (count > 0) mask |= LUA_MASKCOUNT;
sethookaux(L, mask, count, scpt);
}
return 0;
}
static int coresume (lua_State *L) {
int status;
lua_State *co = lua_tothread(L, 1);
luaL_argcheck(L, co, 1, "coroutine expected");
status = lua_resume(co, L, 0);
if (status != LUA_OK && status != LUA_YIELD) {
lua_pushboolean(L, 0);
lua_insert(L, -2);
return 2; /* return false + error message */
}
else {
lua_pushboolean(L, 1);
return 1;
}
}
/* }====================================================== */
static const struct luaL_Reg tests_funcs[] = {
{"checkmemory", lua_checkmemory},
{"closestate", closestate},
{"d2s", d2s},
{"doonnewstack", doonnewstack},
{"doremote", doremote},
{"gccolor", gc_color},
{"gcstate", gc_state},
{"getref", getref},
{"hash", hash_query},
{"int2fb", int2fb_aux},
{"log2", log2_aux},
{"limits", get_limits},
{"listcode", listcode},
{"listk", listk},
{"listlocals", listlocals},
{"loadlib", loadlib},
{"checkpanic", checkpanic},
{"newstate", newstate},
{"newuserdata", newuserdata},
{"num2int", num2int},
{"pushuserdata", pushuserdata},
{"querystr", string_query},
{"querytab", table_query},
{"ref", tref},
{"resume", coresume},
{"s2d", s2d},
{"sethook", sethook},
{"stacklevel", stacklevel},
{"testC", testC},
{"makeCfunc", makeCfunc},
{"totalmem", mem_query},
{"trick", settrick},
{"udataval", udataval},
{"unref", unref},
{"upvalue", upvalue},
{NULL, NULL}
};
static void checkfinalmem (void) {
lua_assert(l_memcontrol.numblocks == 0);
lua_assert(l_memcontrol.total == 0);
}
int luaB_opentests (lua_State *L) {
void *ud;
lua_atpanic(L, &tpanic);
atexit(checkfinalmem);
lua_assert(lua_getallocf(L, &ud) == debug_realloc);
lua_assert(ud == cast(void *, &l_memcontrol));
lua_setallocf(L, lua_getallocf(L, NULL), ud);
luaL_newlib(L, tests_funcs);
return 1;
}
#endif
/*
** $Id: ltests.h,v 2.50 2016/07/19 17:13:00 roberto Exp $
** Internal Header for Debugging of the Lua Implementation
** See Copyright Notice in lua.h
*/
#ifndef ltests_h
#define ltests_h
#include <stdlib.h>
#if 0 /* test Lua with compatibility code */
#undef LUA_COMPAT_MATHLIB
#undef LUA_COMPAT_IPAIRS
#undef LUA_COMPAT_BITLIB
#undef LUA_COMPAT_APIINTCASTS
#undef LUA_COMPAT_FLOATSTRING
#undef LUA_COMPAT_UNPACK
#undef LUA_COMPAT_LOADERS
#undef LUA_COMPAT_LOG10
#undef LUA_COMPAT_LOADSTRING
#undef LUA_COMPAT_MAXN
#undef LUA_COMPAT_MODULE
#endif
#define LUA_DEBUG
/* turn on assertions */
#undef NDEBUG
#include <assert.h>
#ifndef lua_assert
#define lua_assert(c) assert(c)
#endif
/* to avoid warnings, and to make sure value is really unused */
#define UNUSED(x) (x=0, (void)(x))
/* test for sizes in 'l_sprintf' (make sure whole buffer is available) */
#undef l_sprintf
#if !defined(LUA_USE_C89)
#define l_sprintf(s,sz,f,i) (memset(s,0xAB,sz), snprintf(s,sz,f,i))
#else
#define l_sprintf(s,sz,f,i) (memset(s,0xAB,sz), sprintf(s,f,i))
#endif
/* memory-allocator control variables */
typedef struct Memcontrol {
unsigned long numblocks;
unsigned long total;
unsigned long maxmem;
unsigned long memlimit;
unsigned long objcount[LUA_NUMTAGS];
} Memcontrol;
LUA_API Memcontrol l_memcontrol;
/*
** generic variable for debug tricks
*/
extern void *l_Trick;
/*
** Function to traverse and check all memory used by Lua
*/
int lua_checkmemory (lua_State *L);
/* test for lock/unlock */
struct L_EXTRA { int lock; int *plock; };
#undef LUA_EXTRASPACE
#define LUA_EXTRASPACE sizeof(struct L_EXTRA)
#define getlock(l) cast(struct L_EXTRA*, lua_getextraspace(l))
#define luai_userstateopen(l) \
(getlock(l)->lock = 0, getlock(l)->plock = &(getlock(l)->lock))
#define luai_userstateclose(l) \
lua_assert(getlock(l)->lock == 1 && getlock(l)->plock == &(getlock(l)->lock))
#define luai_userstatethread(l,l1) \
lua_assert(getlock(l1)->plock == getlock(l)->plock)
#define luai_userstatefree(l,l1) \
lua_assert(getlock(l)->plock == getlock(l1)->plock)
#define lua_lock(l) lua_assert((*getlock(l)->plock)++ == 0)
#define lua_unlock(l) lua_assert(--(*getlock(l)->plock) == 0)
LUA_API int luaB_opentests (lua_State *L);
LUA_API void *debug_realloc (void *ud, void *block,
size_t osize, size_t nsize);
#if defined(luac_c)
#define luaL_newstate() lua_newstate(debug_realloc, &l_memcontrol)
#define luaL_openlibs(L) \
{ (luaL_openlibs)(L); \
luaL_requiref(L, "T", luaB_opentests, 1); \
lua_pop(L, 1); }
#endif
/* change some sizes to give some bugs a chance */
#undef LUAL_BUFFERSIZE
#define LUAL_BUFFERSIZE 23
#define MINSTRTABSIZE 2
#define MAXINDEXRK 1
/* make stack-overflow tests run faster */
#undef LUAI_MAXSTACK
#define LUAI_MAXSTACK 50000
#undef LUAI_USER_ALIGNMENT_T
#define LUAI_USER_ALIGNMENT_T union { char b[sizeof(void*) * 8]; }
#define STRCACHE_N 16
#define STRCACHE_M 5
#endif
/*
** $Id: luac.c,v 1.76 2018/06/19 01:32:02 lhf Exp $
** Lua compiler (saves bytecodes to files; also lists bytecodes)
** See Copyright Notice in lua.h
*/
#define luac_c
#define LUA_CORE
#include "lprefix.h"
#include <alloca.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "ldebug.h"
#include "lnodemcu.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "lundump.h"
static void PrintFunction(const Proto* f, int full);
#define luaU_print PrintFunction
#define PROGNAME "luac.cross" /* default program name */
#define OUTPUT PROGNAME ".out" /* default output file */
static int listing=0; /* list bytecodes? */
static int dumping=1; /* dump bytecodes? */
static int stripping=0; /* strip debug information? */
static char Output[]={ OUTPUT }; /* default output file name */
static const char* output=Output; /* actual output file name */
static const char* progname=PROGNAME; /* actual program name */
static int flash = 0; /* output flash image */
static lu_int32 address = 0; /* output flash image at absolute location */
static lu_int32 maxSize = 0x40000; /* maximuum uncompressed image size */
static int lookup = 0; /* output lookup-style master combination header */
static const char *execute; /* executed a Lua file */
char *LFSimageName;
#define IROM0_SEG 0x40200000ul
#define IROM0_SEGMAX 0x00100000ul
#define IROM_OFFSET(a) (cast(lu_int32, (a)) - IROM0_SEG)
static void fatal(const char *message) {
fprintf(stderr, "%s: %s\n", progname, message);
exit(EXIT_FAILURE);
}
static void cannot(const char *what) {
fprintf(stderr, "%s: cannot %s %s: %s\n", progname, what, output, strerror(errno));
exit(EXIT_FAILURE);
}
static void usage(const char *message) {
if ( *message == '-')
fprintf(stderr, "%s: unrecognized option '%s'\n", progname, message);
else
fprintf(stderr, "%s: %s\n", progname, message);
fprintf(stderr,
"usage: %s [options] [filenames]\n"
"Available options are:\n"
" -l list (use -l -l for full listing)\n"
" -o name output to file 'name' (default is \"%s\")\n"
" -e name execute a lua source file\n"
" -f output a flash image file\n"
" -F name load a flash image file\n"
" -a addr generate an absolute, rather than "
"position independent flash image file\n"
" (use with -F LFSimage -o absLFSimage to "
"convert an image to absolute format)\n"
" -i generate lookup combination master (default with option -f)\n"
" -m size maximum LFS image in bytes\n"
" -p parse only\n"
" -s strip debug information\n"
" -v show version information\n"
" -- stop handling options\n"
" - stop handling options and process stdin\n", progname, Output);
exit(EXIT_FAILURE);
}
#define IS(s) (strcmp(argv[i],s)==0)
static int doargs(int argc, char *argv[]) {
int i;
int version = 0;
lu_int32 offset = 0;
if (argv[0] != NULL && *argv[0] != 0) progname = argv[0];
for (i = 1; i < argc; i++) {
if ( *argv[i] != '-') { /* end of options; keep it */
break;
} else if (IS("--")) { /* end of options; skip it */
++i;
if (version) ++version;
break;
} else if (IS("-")) { /* end of options; use stdin */
break;
} else if (IS("-e")) { /* execute a lua source file file */
execute = argv[++i];
if (execute == NULL || *execute == 0 || *execute == '-')
usage("\"-e\" needs a file argument");
} else if (IS("-F")) { /* execute a lua source file file */
LFSimageName = argv[++i];
if (LFSimageName == NULL || *LFSimageName == 0 || *LFSimageName == '-')
usage("\"-F\" needs an LFS image file argument");
} else if (IS("-f")) { /* Flash image file */
flash = lookup = 1;
} else if (IS("-a")) { /* Absolue flash image file */
flash = lookup = 1;
address = strtol(argv[++i], NULL, 0);
offset = IROM_OFFSET(address);
if (offset == 0 || offset > IROM0_SEGMAX)
usage("\"-a\" absolute address must be valid flash address");
} else if (IS("-i")) { /* lookup */
lookup = 1;
} else if (IS("-l")) { /* list */
++listing;
} else if (IS("-m")) { /* specify a maximum image size */
flash = lookup = 1;
maxSize = strtol(argv[++i], NULL, 0);
if (maxSize & 0xFFF)
usage("\"-e\" maximum size must be a multiple of 4,096");
} else if (IS("-o")) { /* output file */
output = argv[++i];
if (output == NULL || *output == 0 || ( *output == '-' && output[1] != 0))
usage("'-o' needs argument");
if (IS("-")) output = NULL;
} else if (IS("-p")) { /* parse only */
dumping = 0;
} else if (IS("-s")) { /* strip debug information */
stripping = 1;
} else if (IS("-v")) { /* show version */
++version;
} else { /* unknown option */
usage(argv[i]);
}
}
if (offset>0 && (output == NULL || LFSimageName == NULL ||
execute != NULL || i != argc))
usage("'-a' also requires '-o' and '-f' options without lua source files");
if (i == argc && (listing || !dumping)) {
dumping = 0;
argv[--i] = Output;
}
if (version) {
printf("%s\n", LUA_COPYRIGHT);
if (version == argc - 1) exit(EXIT_SUCCESS);
}
return i;
}
static const char *corename(lua_State *L, const TString *filename, int *len) {
const char *fn = getstr(filename) + 1;
const char *s = strrchr(fn, '/');
if (!s) s = strrchr(fn, '\\');
s = s ? s + 1 : fn;
while ( *s == '.') s++;
const char *e = strchr(s, '.');
if (len)
*len = e ? e - s : strlen(s);
return s;
}
/*
** If the luac command line includes multiple files or has the -f option
** then luac generates a main function to reference all sub-main prototypes.
** This is one of two types:
** Type 0 The standard luac combination main
** Type 1 A lookup wrapper that is used for LFS image dumps
*/
#define toproto(L, i) getproto(L->top + (i))
static const Proto *combine(lua_State *L, int n, int type) {
if (n == 1 && type == 0) {
return toproto(L, -1);
} else {
Proto *f;
int i, j;
/*
* Generate a minimal proto with 1 return, emtpy p, k & uv vectors
*/
if (luaL_loadbuffer(L, "\n", strlen("\n"), "=("PROGNAME ")") != LUA_OK)
fatal(lua_tostring(L, -1));
f = toproto(L, -1);
/*
* Allocate the vector for and bind the sub-protos
*/
luaM_reallocvector(L, f->p, f->sizep, n, Proto *);
f->sizep = n;
for (i = 0; i < n; i++) {
f->p[i] = toproto(L, i - n - 1);
if (f->p[i]->sizeupvalues > 0)
f->p[i]->upvalues[0].instack = 0;
}
f->numparams = 0;
f->maxstacksize = 1;
if (type == 1) {
/*
* For Type 1 main(), add a k vector of strings naming the corresponding
* protos with the Unixtime of the compile appended.
*/
luaM_reallocvector(L, f->k, f->sizek, n+1, TValue);
f->sizek = n + 1;
for (i = 0; i < n; i++) {
int len;
const char *name = corename(L, f->p[i]->source, &len);
TString* sname = luaS_newlstr(L, name, len);
for (j = 0; j < i; j++) {
if (tsvalue(f->k+j) == sname)
fatal(lua_pushfstring(L, "Cannot have duplicate files ('%s') in LFS", name));
}
setsvalue2n(L, f->k+i, sname);
}
setivalue(f->k+n, (lua_Integer) time(NULL));
}
return f;
}
}
static int writer(lua_State *L, const void *p, size_t size, void *u) {
UNUSED(L);
return (fwrite(p, size, 1, ((FILE **)u)[0]) != 1) && (size != 0);
}
static int msghandler (lua_State *L) {
const char *msg = lua_tostring(L, 1);
if (msg == NULL) /* is error object not a string? */
msg = lua_pushfstring(L, "(error object is a %s value)", luaL_typename(L, 1));
luaL_traceback(L, L, msg, 1); /* append a standard traceback */
return 1; /* return the traceback */
}
static int dofile (lua_State *L, const char *name) {
int status = luaL_loadfile(L, name);
if (status == LUA_OK) {
int base = lua_gettop(L);
lua_pushcfunction(L, msghandler); /* push message handler */
lua_insert(L, base); /* put it under function and args */
status = lua_pcall(L, 0, 0, base);
lua_remove(L, base); /* remove message handler from the stack */
}
if (status != LUA_OK) {
fprintf(stderr, "%s: %s\n", PROGNAME, lua_tostring(L, -1));
lua_pop(L, 1); /* remove message */
}
return status;
}
/*
** This function is an inintended consequence of constraints in ltable.c
** rotable_findentry(). The file list generates a ROTable in LFS and the
** rule for ROTables is that metavalue entries must be at the head of the
** ROTableentry list so argv file names with basenames starting with "__"
** must be head of the list. This is a botch. Sorry.
*/
static void reorderfiles(lua_State *L, int argc, char **list, char **argv) {
int i, j;
for (i = 0; i < argc; i++ ) {
TString *file = luaS_new(L,argv[i]);
if (strcmp("__", corename(L, file, NULL))) {
list[i] = argv[i]; /* add to the end of the new list */
} else {
for (j = 0; j < i; j++)
list[j+1] = list[j];
list[0] = argv[i]; /* add to the start of the new list */
}
}
}
static int pmain(lua_State *L) {
int argc = (int) lua_tointeger(L, 1);
char **argv = (char **) lua_touserdata(L, 2);
char **filelist = alloca(argc * sizeof(char *));
const Proto *f;
int i, status;
if (!lua_checkstack(L, argc + 1))
fatal("too many input files");
if (execute || address) {
luaL_openlibs(L); /* the nodemcu open will throw to signal an LFS reload */
status = dofile(L, execute);
if (status != LUA_OK)
return 0;
}
if (argc == 0)
return 0;
reorderfiles(L, argc, filelist, argv);
for (i = 0; i < argc; i++) {
const char *filename = IS("-") ? NULL : filelist[i];
if (luaL_loadfile(L, filename) != LUA_OK)
fatal(lua_tostring(L, -1));
//TODO: if strip = 2, replace proto->source by basename
}
f = combine(L, argc + (execute ? 1 : 0), lookup);
if (listing) luaU_print(f, listing > 1);
if (dumping) {
int result;
FILE *D = (output == NULL) ? stdout : fopen(output, "wb");
if (D == NULL) cannot("open");
lua_lock(L);
if (flash) {
UNUSED(address);
UNUSED(maxSize);
result = luaU_DumpAllProtos(L, f, writer, &D, stripping);
} else {
result = luaU_dump(L, f, writer, cast(void *, &D), stripping);
}
lua_unlock(L);
if (result == LUA_ERR_CC_INTOVERFLOW)
fatal("value too big or small for target integer type");
if (result == LUA_ERR_CC_NOTINTEGER)
fatal("target lua_Number is integral but fractional value found");
if (ferror(D)) cannot("write");
if (fclose(D)) cannot("close");
}
return 0;
}
int main(int argc, char *argv[]) {
lua_State *L;
int i = doargs(argc, argv);
int j, status;
argc -= i; argv += i;
if (argc <= 0 && execute == 0 && address == 0) usage("no input files given");
if (address)
luaN_setabsolute(address);
for (j = 0; j < 2 ; j++) {
L = luaL_newstate();
if (L == NULL) fatal("not enough memory for state");
lua_pushcfunction(L, &pmain);
lua_pushinteger(L, argc);
lua_pushlightuserdata(L, argv);
status = lua_pcall(L, 2, 0, 0);
if (status != LUA_OK) {
if (lua_isboolean(L,-1) && lua_toboolean(L,-1)) {
/*An LFS image has been loaded */
if (address) { /* write out as absolute image and exit */
lu_int32 size = cast(LFSHeader *, LFSregion)->flash_size;
FILE *af = fopen(output, "wb");
if (af == NULL) cannot("open");
if (fwrite(LFSregion, size, 1, af) != 1) cannot("write");
fclose(af);
exit(0);
}
/*otherwise simulate a restart */
lua_close(L);
continue; /* and loop around once more simulating restart */
}
char *err = strdup(lua_tostring(L, -1));
lua_close(L);
fatal(err);
}
lua_close(L);
break;
}
return EXIT_SUCCESS;
}
/*
** $Id: luac.c,v 1.76 2018/06/19 01:32:02 lhf Exp $
** print bytecodes
** See Copyright Notice in lua.h
*/
#include <ctype.h>
#include <stdio.h>
#define luac_c
#define LUA_CORE
#include "ldebug.h"
#include "lobject.h"
#include "lopcodes.h"
#define VOID(p) ((const void*)(p))
static void PrintString(const TString* ts)
{
const char* s=getstr(ts);
size_t i,n=tsslen(ts);
printf("%c",'"');
for (i=0; i<n; i++)
{
int c=(int)(unsigned char)s[i];
switch (c)
{
case '"': printf("\\\""); break;
case '\\': printf("\\\\"); break;
case '\a': printf("\\a"); break;
case '\b': printf("\\b"); break;
case '\f': printf("\\f"); break;
case '\n': printf("\\n"); break;
case '\r': printf("\\r"); break;
case '\t': printf("\\t"); break;
case '\v': printf("\\v"); break;
default: if (isprint(c))
printf("%c",c);
else
printf("\\%03d",c);
}
}
printf("%c",'"');
}
static void PrintConstant(const Proto* f, int i)
{
const TValue* o=&f->k[i];
switch (ttype(o))
{
case LUA_TNIL:
printf("nil");
break;
case LUA_TBOOLEAN:
printf(bvalue(o) ? "true" : "false");
break;
case LUA_TNUMFLT:
{
char buff[100];
sprintf(buff,LUA_NUMBER_FMT,fltvalue(o));
printf("%s",buff);
if (buff[strspn(buff,"-0123456789")]=='\0') printf(".0");
break;
}
case LUA_TNUMINT:
printf(LUA_INTEGER_FMT,ivalue(o));
break;
case LUA_TSHRSTR: case LUA_TLNGSTR:
PrintString(tsvalue(o));
break;
default: /* cannot happen */
printf("? type=%d",ttype(o));
break;
}
}
#define UPVALNAME(x) ((f->upvalues[x].name) ? getstr(f->upvalues[x].name) : "-")
#define MYK(x) (-1-(x))
static void PrintCode(const Proto* f)
{
const Instruction* code=f->code;
int pc,n=f->sizecode;
for (pc=0; pc<n; pc++)
{
Instruction i=code[pc];
OpCode o=GET_OPCODE(i);
int a=GETARG_A(i);
int b=GETARG_B(i);
int c=GETARG_C(i);
int ax=GETARG_Ax(i);
int bx=GETARG_Bx(i);
int sbx=GETARG_sBx(i);
int line=getfuncline(f,pc);
printf("\t%d\t",pc+1);
if (line>0) printf("[%d]\t",line); else printf("[-]\t");
printf("%-9s\t",luaP_opnames[o]);
switch (getOpMode(o))
{
case iABC:
printf("%d",a);
if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (MYK(INDEXK(b))) : b);
if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (MYK(INDEXK(c))) : c);
break;
case iABx:
printf("%d",a);
if (getBMode(o)==OpArgK) printf(" %d",MYK(bx));
if (getBMode(o)==OpArgU) printf(" %d",bx);
break;
case iAsBx:
printf("%d %d",a,sbx);
break;
case iAx:
printf("%d",MYK(ax));
break;
}
switch (o)
{
case OP_LOADK:
printf("\t; "); PrintConstant(f,bx);
break;
case OP_GETUPVAL:
case OP_SETUPVAL:
printf("\t; %s",UPVALNAME(b));
break;
case OP_GETTABUP:
printf("\t; %s",UPVALNAME(b));
if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); }
break;
case OP_SETTABUP:
printf("\t; %s",UPVALNAME(a));
if (ISK(b)) { printf(" "); PrintConstant(f,INDEXK(b)); }
if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); }
break;
case OP_GETTABLE:
case OP_SELF:
if (ISK(c)) { printf("\t; "); PrintConstant(f,INDEXK(c)); }
break;
case OP_SETTABLE:
case OP_ADD:
case OP_SUB:
case OP_MUL:
case OP_MOD:
case OP_POW:
case OP_DIV:
case OP_IDIV:
case OP_BAND:
case OP_BOR:
case OP_BXOR:
case OP_SHL:
case OP_SHR:
case OP_EQ:
case OP_LT:
case OP_LE:
if (ISK(b) || ISK(c))
{
printf("\t; ");
if (ISK(b)) PrintConstant(f,INDEXK(b)); else printf("-");
printf(" ");
if (ISK(c)) PrintConstant(f,INDEXK(c)); else printf("-");
}
break;
case OP_JMP:
case OP_FORLOOP:
case OP_FORPREP:
case OP_TFORLOOP:
printf("\t; to %d",sbx+pc+2);
break;
case OP_CLOSURE:
printf("\t; %p",VOID(f->p[bx]));
break;
case OP_SETLIST:
if (c==0) printf("\t; %d",(int)code[++pc]); else printf("\t; %d",c);
break;
case OP_EXTRAARG:
printf("\t; "); PrintConstant(f,ax);
break;
default:
break;
}
printf("\n");
}
}
#define SS(x) ((x==1)?"":"s")
#define S(x) (int)(x),SS(x)
static void PrintHeader(const Proto* f)
{
const char* s=f->source ? getstr(f->source) : "=?";
if (*s=='@' || *s=='=')
s++;
else if (*s==LUA_SIGNATURE[0])
s="(bstring)";
else
s="(string)";
printf("\n%s <%s:%d,%d> (%d instruction%s at %p)\n",
(f->linedefined==0)?"main":"function",s,
f->linedefined,f->lastlinedefined,
S(f->sizecode),VOID(f));
printf("%d%s param%s, %d slot%s, %d upvalue%s, ",
(int)(f->numparams),f->is_vararg?"+":"",SS(f->numparams),
S(f->maxstacksize),S(f->sizeupvalues));
printf("%d local%s, %d constant%s, %d function%s\n",
S(f->sizelocvars),S(f->sizek),S(f->sizep));
}
static void PrintDebug(const Proto* f)
{
int i,n;
n=f->sizek;
printf("constants (%d) for %p:\n",n,VOID(f));
for (i=0; i<n; i++)
{
printf("\t%d\t",i+1);
PrintConstant(f,i);
printf("\n");
}
n=f->sizelocvars;
printf("locals (%d) for %p:\n",n,VOID(f));
for (i=0; i<n; i++)
{
printf("\t%d\t%s\t%d\t%d\n",
i,getstr(f->locvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1);
}
n=f->sizeupvalues;
printf("upvalues (%d) for %p:\n",n,VOID(f));
for (i=0; i<n; i++)
{
printf("\t%d\t%s\t%d\t%d\n",
i,UPVALNAME(i),f->upvalues[i].instack,f->upvalues[i].idx);
}
}
static void PrintFunction(const Proto* f, int full)
{
int i,n=f->sizep;
PrintHeader(f);
PrintCode(f);
if (full) PrintDebug(f);
for (i=0; i<n; i++) PrintFunction(f->p[i],full);
}
#!../lua
-- $Id: all.lua,v 1.95 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice at the end of this file
local version = "Lua 5.3"
if _VERSION ~= version then
io.stderr:write("\nThis test suite is for ", version, ", not for ", _VERSION,
"\nExiting tests\n")
return
end
_G._ARG = arg -- save arg for other tests
-- next variables control the execution of some tests
-- true means no test (so an undefined variable does not skip a test)
-- defaults are for Linux; test everything.
-- Make true to avoid long or memory consuming tests
_soft = rawget(_G, "_soft") or false
-- Make true to avoid non-portable tests
_port = rawget(_G, "_port") or false
-- Make true to avoid messages about tests not performed
_nomsg = rawget(_G, "_nomsg") or false
local usertests = rawget(_G, "_U")
if usertests then
-- tests for sissies ;) Avoid problems
_soft = true
_port = true
_nomsg = true
end
-- tests should require debug when needed
debug = nil
if usertests then
T = nil -- no "internal" tests for user tests
else
T = rawget(_G, "T") -- avoid problems with 'strict' module
end
math.randomseed(0)
--[=[
example of a long [comment],
[[spanning several [lines]]]
]=]
print("current path:\n****" .. package.path .. "****\n")
local initclock = os.clock()
local lastclock = initclock
local walltime = os.time()
local collectgarbage = collectgarbage
do -- (
-- track messages for tests not performed
local msgs = {}
function Message (m)
if not _nomsg then
print(m)
msgs[#msgs+1] = string.sub(m, 3, -3)
end
end
assert(os.setlocale"C")
local T,print,format,write,assert,type,unpack,floor =
T,print,string.format,io.write,assert,type,table.unpack,math.floor
-- use K for 1000 and M for 1000000 (not 2^10 -- 2^20)
local function F (m)
local function round (m)
m = m + 0.04999
return format("%.1f", m) -- keep one decimal digit
end
if m < 1000 then return m
else
m = m / 1000
if m < 1000 then return round(m).."K"
else
return round(m/1000).."M"
end
end
end
local showmem
if not T then
local max = 0
showmem = function ()
local m = collectgarbage("count") * 1024
max = (m > max) and m or max
print(format(" ---- total memory: %s, max memory: %s ----\n",
F(m), F(max)))
end
else
showmem = function ()
T.checkmemory()
local total, numblocks, maxmem = T.totalmem()
local count = collectgarbage("count")
print(format(
"\n ---- total memory: %s (%.0fK), max use: %s, blocks: %d\n",
F(total), count, F(maxmem), numblocks))
print(format("\t(strings: %d, tables: %d, functions: %d, "..
"\n\tudata: %d, threads: %d)",
T.totalmem"string", T.totalmem"table", T.totalmem"function",
T.totalmem"userdata", T.totalmem"thread"))
end
end
--
-- redefine dofile to run files through dump/undump
--
local function report (n) print("\n***** FILE '"..n.."'*****") end
local olddofile = dofile
local dofile = function (n, strip)
showmem()
local c = os.clock()
print(string.format("time: %g (+%g)", c - initclock, c - lastclock))
lastclock = c
report(n)
local f = assert(loadfile(n))
local b = string.dump(f, strip)
f = assert(load(b))
return f()
end
dofile('main.lua')
do
local next, setmetatable, stderr = next, setmetatable, io.stderr
-- track collections
local mt = {}
-- each time a table is collected, remark it for finalization
-- on next cycle
mt.__gc = function (o)
stderr:write'.' -- mark progress
local n = setmetatable(o, mt) -- remark it
end
local n = setmetatable({}, mt) -- create object
end
report"gc.lua"
local f = assert(loadfile('gc.lua'))
f=nil -- NodeMCU removed f()
dofile('db.lua')
assert(dofile('calls.lua') == deep and deep)
olddofile('strings.lua')
olddofile('literals.lua')
dofile('tpack.lua')
assert(dofile('attrib.lua') == 27)
assert(dofile('locals.lua') == 5)
dofile('constructs.lua')
dofile('code.lua', true)
if not _G._soft then
report('big.lua')
local f = coroutine.wrap(assert(loadfile('big.lua')))
assert(f() == 'b')
assert(f() == 'a')
end
dofile('nextvar.lua')
dofile('pm.lua')
dofile('utf8.lua')
dofile('api.lua')
assert(dofile('events.lua') == 12)
dofile('vararg.lua')
dofile('closure.lua')
dofile('coroutine.lua')
dofile('goto.lua', true)
dofile('errors.lua')
dofile('math.lua')
dofile('sort.lua', true)
dofile('bitwise.lua')
assert(dofile('verybig.lua', true) == 10); collectgarbage()
dofile('files.lua')
if #msgs > 0 then
print("\ntests not performed:")
for i=1,#msgs do
print(msgs[i])
end
print()
end
-- no test module should define 'debug'
-- assert(debug == nil) -- NodeMCU. debug is always defined in ROM
local debug = require "debug"
print(string.format("%d-bit integers, %d-bit floats",
string.packsize("j") * 8, string.packsize("n") * 8))
debug.sethook(function (a) assert(type(a) == 'string') end, "cr")
-- to survive outside block
_G.showmem = showmem
end --)
local _G, showmem, print, format, clock, time, difftime, assert, open =
_G, showmem, print, string.format, os.clock, os.time, os.difftime,
assert, io.open
-- file with time of last performed test
local fname = T and "time-debug.txt" or "time.txt"
local lasttime
if not usertests then
-- open file with time of last performed test
local f = io.open(fname)
if f then
lasttime = assert(tonumber(f:read'a'))
f:close();
else -- no such file; assume it is recording time for first time
lasttime = nil
end
end
-- erase (almost) all globals
print('cleaning all!!!!')
for n in pairs(_G) do
if not ({___Glob = 1, tostring = 1})[n] then
_G[n] = nil
end
end
collectgarbage()
collectgarbage()
collectgarbage()
collectgarbage()
collectgarbage()
collectgarbage();showmem()
local clocktime = clock() - initclock
walltime = difftime(time(), walltime)
print(format("\n\ntotal time: %.2fs (wall time: %gs)\n", clocktime, walltime))
if not usertests then
lasttime = lasttime or clocktime -- if no last time, ignore difference
-- check whether current test time differs more than 5% from last time
local diff = (clocktime - lasttime) / lasttime
local tolerance = 0.05 -- 5%
if (diff >= tolerance or diff <= -tolerance) then
print(format("WARNING: time difference from previous test: %+.1f%%",
diff * 100))
end
assert(open(fname, "w")):write(clocktime):close()
end
print("final OK !!!")
--[[
*****************************************************************************
* Copyright (C) 1994-2016 Lua.org, PUC-Rio.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*****************************************************************************
]]
-- $Id: api.lua,v 1.147 2016/11/07 13:06:25 roberto Exp $
-- See Copyright Notice in file all.lua
if T==nil then
(Message or print)('\n >>> testC not active: skipping API tests <<<\n')
return
end
local debug = require "debug"
local pack = table.pack
function tcheck (t1, t2)
assert(t1.n == (t2.n or #t2) + 1)
for i = 2, t1.n do assert(t1[i] == t2[i - 1]) end
end
local function checkerr (msg, f, ...)
local stat, err = pcall(f, ...)
assert(not stat and string.find(err, msg))
end
print('testing C API')
a = T.testC("pushvalue R; return 1")
assert(a == debug.getregistry())
-- absindex
assert(T.testC("settop 10; absindex -1; return 1") == 10)
assert(T.testC("settop 5; absindex -5; return 1") == 1)
assert(T.testC("settop 10; absindex 1; return 1") == 1)
assert(T.testC("settop 10; absindex R; return 1") < -10)
-- testing alignment
a = T.d2s(12458954321123.0)
assert(a == string.pack("d", 12458954321123.0))
assert(T.s2d(a) == 12458954321123.0)
a,b,c = T.testC("pushnum 1; pushnum 2; pushnum 3; return 2")
assert(a == 2 and b == 3 and not c)
f = T.makeCfunc("pushnum 1; pushnum 2; pushnum 3; return 2")
a,b,c = f()
assert(a == 2 and b == 3 and not c)
-- test that all trues are equal
a,b,c = T.testC("pushbool 1; pushbool 2; pushbool 0; return 3")
assert(a == b and a == true and c == false)
a,b,c = T.testC"pushbool 0; pushbool 10; pushnil;\
tobool -3; tobool -3; tobool -3; return 3"
assert(a==false and b==true and c==false)
a,b,c = T.testC("gettop; return 2", 10, 20, 30, 40)
assert(a == 40 and b == 5 and not c)
t = pack(T.testC("settop 5; return *", 2, 3))
tcheck(t, {n=4,2,3})
t = pack(T.testC("settop 0; settop 15; return 10", 3, 1, 23))
assert(t.n == 10 and t[1] == nil and t[10] == nil)
t = pack(T.testC("remove -2; return *", 2, 3, 4))
tcheck(t, {n=2,2,4})
t = pack(T.testC("insert -1; return *", 2, 3))
tcheck(t, {n=2,2,3})
t = pack(T.testC("insert 3; return *", 2, 3, 4, 5))
tcheck(t, {n=4,2,5,3,4})
t = pack(T.testC("replace 2; return *", 2, 3, 4, 5))
tcheck(t, {n=3,5,3,4})
t = pack(T.testC("replace -2; return *", 2, 3, 4, 5))
tcheck(t, {n=3,2,3,5})
t = pack(T.testC("remove 3; return *", 2, 3, 4, 5))
tcheck(t, {n=3,2,4,5})
t = pack(T.testC("copy 3 4; return *", 2, 3, 4, 5))
tcheck(t, {n=4,2,3,3,5})
t = pack(T.testC("copy -3 -1; return *", 2, 3, 4, 5))
tcheck(t, {n=4,2,3,4,3})
do -- testing 'rotate'
local t = {10, 20, 30, 40, 50, 60}
for i = -6, 6 do
local s = string.format("rotate 2 %d; return 7", i)
local t1 = pack(T.testC(s, 10, 20, 30, 40, 50, 60))
tcheck(t1, t)
table.insert(t, 1, table.remove(t))
end
t = pack(T.testC("rotate -2 1; return *", 10, 20, 30, 40))
tcheck(t, {10, 20, 40, 30})
t = pack(T.testC("rotate -2 -1; return *", 10, 20, 30, 40))
tcheck(t, {10, 20, 40, 30})
-- some corner cases
t = pack(T.testC("rotate -1 0; return *", 10, 20, 30, 40))
tcheck(t, {10, 20, 30, 40})
t = pack(T.testC("rotate -1 1; return *", 10, 20, 30, 40))
tcheck(t, {10, 20, 30, 40})
t = pack(T.testC("rotate 5 -1; return *", 10, 20, 30, 40))
tcheck(t, {10, 20, 30, 40})
end
-- testing non-function message handlers
do
local f = T.makeCfunc[[
getglobal error
pushstring bola
pcall 1 1 1 # call 'error' with given handler
pushstatus
return 2 # return error message and status
]]
local msg, st = f({}) -- invalid handler
assert(st == "ERRERR" and string.find(msg, "error handling"))
local msg, st = f(nil) -- invalid handler
assert(st == "ERRERR" and string.find(msg, "error handling"))
local a = setmetatable({}, {__call = function (_, x) return x:upper() end})
local msg, st = f(a) -- callable handler
assert(st == "ERRRUN" and msg == "BOLA")
end
t = pack(T.testC("insert 3; pushvalue 3; remove 3; pushvalue 2; remove 2; \
insert 2; pushvalue 1; remove 1; insert 1; \
insert -2; pushvalue -2; remove -3; return *",
2, 3, 4, 5, 10, 40, 90))
tcheck(t, {n=7,2,3,4,5,10,40,90})
t = pack(T.testC("concat 5; return *", "alo", 2, 3, "joao", 12))
tcheck(t, {n=1,"alo23joao12"})
-- testing MULTRET
t = pack(T.testC("call 2,-1; return *",
function (a,b) return 1,2,3,4,a,b end, "alo", "joao"))
tcheck(t, {n=6,1,2,3,4,"alo", "joao"})
do -- test returning more results than fit in the caller stack
local a = {}
for i=1,1000 do a[i] = true end; a[999] = 10
local b = T.testC([[pcall 1 -1 0; pop 1; tostring -1; return 1]],
table.unpack, a)
assert(b == "10")
end
-- testing globals
_G.a = 14; _G.b = "a31"
local a = {T.testC[[
getglobal a;
getglobal b;
getglobal b;
setglobal a;
return *
]]}
assert(a[2] == 14 and a[3] == "a31" and a[4] == nil and _G.a == "a31")
-- testing arith
assert(T.testC("pushnum 10; pushnum 20; arith /; return 1") == 0.5)
assert(T.testC("pushnum 10; pushnum 20; arith -; return 1") == -10)
assert(T.testC("pushnum 10; pushnum -20; arith *; return 1") == -200)
assert(T.testC("pushnum 10; pushnum 3; arith ^; return 1") == 1000)
assert(T.testC("pushnum 10; pushstring 20; arith /; return 1") == 0.5)
assert(T.testC("pushstring 10; pushnum 20; arith -; return 1") == -10)
assert(T.testC("pushstring 10; pushstring -20; arith *; return 1") == -200)
assert(T.testC("pushstring 10; pushstring 3; arith ^; return 1") == 1000)
assert(T.testC("arith /; return 1", 2, 0) == 10.0/0)
a = T.testC("pushnum 10; pushint 3; arith \\; return 1")
assert(a == 3.0 and math.type(a) == "float")
a = T.testC("pushint 10; pushint 3; arith \\; return 1")
assert(a == 3 and math.type(a) == "integer")
a = assert(T.testC("pushint 10; pushint 3; arith +; return 1"))
assert(a == 13 and math.type(a) == "integer")
a = assert(T.testC("pushnum 10; pushint 3; arith +; return 1"))
assert(a == 13 and math.type(a) == "float")
a,b,c = T.testC([[pushnum 1;
pushstring 10; arith _;
pushstring 5; return 3]])
assert(a == 1 and b == -10 and c == "5")
mt = {__add = function (a,b) return setmetatable({a[1] + b[1]}, mt) end,
__mod = function (a,b) return setmetatable({a[1] % b[1]}, mt) end,
__unm = function (a) return setmetatable({a[1]* 2}, mt) end}
a,b,c = setmetatable({4}, mt),
setmetatable({8}, mt),
setmetatable({-3}, mt)
x,y,z = T.testC("arith +; return 2", 10, a, b)
assert(x == 10 and y[1] == 12 and z == nil)
assert(T.testC("arith %; return 1", a, c)[1] == 4%-3)
assert(T.testC("arith _; arith +; arith %; return 1", b, a, c)[1] ==
8 % (4 + (-3)*2))
-- errors in arithmetic
checkerr("divide by zero", T.testC, "arith \\", 10, 0)
checkerr("%%0", T.testC, "arith %", 10, 0)
-- testing lessthan and lessequal
assert(T.testC("compare LT 2 5, return 1", 3, 2, 2, 4, 2, 2))
assert(T.testC("compare LE 2 5, return 1", 3, 2, 2, 4, 2, 2))
assert(not T.testC("compare LT 3 4, return 1", 3, 2, 2, 4, 2, 2))
assert(T.testC("compare LE 3 4, return 1", 3, 2, 2, 4, 2, 2))
assert(T.testC("compare LT 5 2, return 1", 4, 2, 2, 3, 2, 2))
assert(not T.testC("compare LT 2 -3, return 1", "4", "2", "2", "3", "2", "2"))
assert(not T.testC("compare LT -3 2, return 1", "3", "2", "2", "4", "2", "2"))
-- non-valid indices produce false
assert(not T.testC("compare LT 1 4, return 1"))
assert(not T.testC("compare LE 9 1, return 1"))
assert(not T.testC("compare EQ 9 9, return 1"))
local b = {__lt = function (a,b) return a[1] < b[1] end}
local a1,a3,a4 = setmetatable({1}, b),
setmetatable({3}, b),
setmetatable({4}, b)
assert(T.testC("compare LT 2 5, return 1", a3, 2, 2, a4, 2, 2))
assert(T.testC("compare LE 2 5, return 1", a3, 2, 2, a4, 2, 2))
assert(T.testC("compare LT 5 -6, return 1", a4, 2, 2, a3, 2, 2))
a,b = T.testC("compare LT 5 -6, return 2", a1, 2, 2, a3, 2, 20)
assert(a == 20 and b == false)
a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a3, 2, 20)
assert(a == 20 and b == false)
a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a1, 2, 20)
assert(a == 20 and b == true)
-- testing length
local t = setmetatable({x = 20}, {__len = function (t) return t.x end})
a,b,c = T.testC([[
len 2;
Llen 2;
objsize 2;
return 3
]], t)
assert(a == 20 and b == 20 and c == 0)
t.x = "234"; t[1] = 20
a,b,c = T.testC([[
len 2;
Llen 2;
objsize 2;
return 3
]], t)
assert(a == "234" and b == 234 and c == 1)
t.x = print; t[1] = 20
a,c = T.testC([[
len 2;
objsize 2;
return 2
]], t)
assert(a == print and c == 1)
-- testing __concat
a = setmetatable({x="u"}, {__concat = function (a,b) return a.x..'.'..b.x end})
x,y = T.testC([[
pushnum 5
pushvalue 2;
pushvalue 2;
concat 2;
pushvalue -2;
return 2;
]], a, a)
assert(x == a..a and y == 5)
-- concat with 0 elements
assert(T.testC("concat 0; return 1") == "")
-- concat with 1 element
assert(T.testC("concat 1; return 1", "xuxu") == "xuxu")
-- testing lua_is
function B(x) return x and 1 or 0 end
function count (x, n)
n = n or 2
local prog = [[
isnumber %d;
isstring %d;
isfunction %d;
iscfunction %d;
istable %d;
isuserdata %d;
isnil %d;
isnull %d;
return 8
]]
prog = string.format(prog, n, n, n, n, n, n, n, n)
local a,b,c,d,e,f,g,h = T.testC(prog, x)
return B(a)+B(b)+B(c)+B(d)+B(e)+B(f)+B(g)+(100*B(h))
end
assert(count(3) == 2)
assert(count('alo') == 1)
assert(count('32') == 2)
assert(count({}) == 1)
assert(count(print) == 2)
assert(count(function () end) == 1)
assert(count(nil) == 1)
assert(count(io.stdin) == 1)
assert(count(nil, 15) == 100)
-- testing lua_to...
function to (s, x, n)
n = n or 2
return T.testC(string.format("%s %d; return 1", s, n), x)
end
local hfunc = string.gmatch("", "") -- a "heavy C function" (with upvalues)
assert(debug.getupvalue(hfunc, 1))
assert(to("tostring", {}) == nil)
assert(to("tostring", "alo") == "alo")
assert(to("tostring", 12) == "12")
assert(to("tostring", 12, 3) == nil)
assert(to("objsize", {}) == 0)
assert(to("objsize", {1,2,3}) == 3)
assert(to("objsize", "alo\0\0a") == 6)
assert(to("objsize", T.newuserdata(0)) == 0)
assert(to("objsize", T.newuserdata(101)) == 101)
assert(to("objsize", 124) == 0)
assert(to("objsize", true) == 0)
assert(to("tonumber", {}) == 0)
assert(to("tonumber", "12") == 12)
assert(to("tonumber", "s2") == 0)
assert(to("tonumber", 1, 20) == 0)
assert(to("topointer", 10) == 0)
assert(to("topointer", true) == 0)
assert(to("topointer", T.pushuserdata(20)) == 20)
assert(to("topointer", io.read) ~= 0) -- light C function
assert(to("topointer", hfunc) ~= 0) -- "heavy" C function
assert(to("topointer", function () end) ~= 0) -- Lua function
assert(to("topointer", io.stdin) ~= 0) -- full userdata
assert(to("func2num", 20) == 0)
assert(to("func2num", T.pushuserdata(10)) == 0)
assert(to("func2num", io.read) ~= 0) -- light C function
assert(to("func2num", hfunc) ~= 0) -- "heavy" C function (with upvalue)
a = to("tocfunction", math.deg)
assert(a(3) == math.deg(3) and a == math.deg)
print("testing panic function")
do
-- trivial error
assert(T.checkpanic("pushstring hi; error") == "hi")
-- using the stack inside panic
assert(T.checkpanic("pushstring hi; error;",
[[checkstack 5 XX
pushstring ' alo'
pushstring ' mundo'
concat 3]]) == "hi alo mundo")
-- "argerror" without frames
assert(T.checkpanic("loadstring 4") ==
"bad argument #4 (string expected, got no value)")
-- memory error
T.totalmem(T.totalmem()+10000) -- set low memory limit (+10k)
assert(T.checkpanic("newuserdata 20000") == "not enough memory")
T.totalmem(0) -- restore high limit
-- stack error
if not _soft then
local msg = T.checkpanic[[
pushstring "function f() f() end"
loadstring -1; call 0 0
getglobal f; call 0 0
]]
assert(string.find(msg, "stack overflow"))
end
end
-- testing deep C stack
if not _soft then
print("testing stack overflow")
collectgarbage("stop")
checkerr("XXXX", T.testC, "checkstack 1000023 XXXX") -- too deep
-- too deep (with no message)
checkerr("^stack overflow$", T.testC, "checkstack 1000023 ''")
local s = string.rep("pushnil;checkstack 1 XX;", 1000000)
checkerr("overflow", T.testC, s)
collectgarbage("restart")
print'+'
end
local lim = _soft and 500 or 12000
local prog = {"checkstack " .. (lim * 2 + 100) .. "msg", "newtable"}
for i = 1,lim do
prog[#prog + 1] = "pushnum " .. i
prog[#prog + 1] = "pushnum " .. i * 10
end
prog[#prog + 1] = "rawgeti R 2" -- get global table in registry
prog[#prog + 1] = "insert " .. -(2*lim + 2)
for i = 1,lim do
prog[#prog + 1] = "settable " .. -(2*(lim - i + 1) + 1)
end
prog[#prog + 1] = "return 2"
prog = table.concat(prog, ";")
local g, t = T.testC(prog)
assert(g == _G)
for i = 1,lim do assert(t[i] == i*10); t[i] = nil end
assert(next(t) == nil)
prog, g, t = nil
-- testing errors
a = T.testC([[
loadstring 2; pcall 0 1 0;
pushvalue 3; insert -2; pcall 1 1 0;
pcall 0 0 0;
return 1
]], "x=150", function (a) assert(a==nil); return 3 end)
assert(type(a) == 'string' and x == 150)
function check3(p, ...)
local arg = {...}
assert(#arg == 3)
assert(string.find(arg[3], p))
end
check3(":1:", T.testC("loadstring 2; return *", "x="))
check3("%.", T.testC("loadfile 2; return *", "."))
check3("xxxx", T.testC("loadfile 2; return *", "xxxx"))
-- test errors in non protected threads
function checkerrnopro (code, msg)
local th = coroutine.create(function () end) -- create new thread
local stt, err = pcall(T.testC, th, code) -- run code there
assert(not stt and string.find(err, msg))
end
if not _soft then
checkerrnopro("pushnum 3; call 0 0", "attempt to call")
print"testing stack overflow in unprotected thread"
function f () f() end
checkerrnopro("getglobal 'f'; call 0 0;", "stack overflow")
end
print"+"
-- testing table access
do -- getp/setp
local a = {}
T.testC("rawsetp 2 1", a, 20)
assert(a[T.pushuserdata(1)] == 20)
assert(T.testC("rawgetp 2 1; return 1", a) == 20)
end
a = {x=0, y=12}
x, y = T.testC("gettable 2; pushvalue 4; gettable 2; return 2",
a, 3, "y", 4, "x")
assert(x == 0 and y == 12)
T.testC("settable -5", a, 3, 4, "x", 15)
assert(a.x == 15)
a[a] = print
x = T.testC("gettable 2; return 1", a) -- table and key are the same object!
assert(x == print)
T.testC("settable 2", a, "x") -- table and key are the same object!
assert(a[a] == "x")
b = setmetatable({p = a}, {})
getmetatable(b).__index = function (t, i) return t.p[i] end
k, x = T.testC("gettable 3, return 2", 4, b, 20, 35, "x")
assert(x == 15 and k == 35)
k = T.testC("getfield 2 y, return 1", b)
assert(k == 12)
getmetatable(b).__index = function (t, i) return a[i] end
getmetatable(b).__newindex = function (t, i,v ) a[i] = v end
y = T.testC("insert 2; gettable -5; return 1", 2, 3, 4, "y", b)
assert(y == 12)
k = T.testC("settable -5, return 1", b, 3, 4, "x", 16)
assert(a.x == 16 and k == 4)
a[b] = 'xuxu'
y = T.testC("gettable 2, return 1", b)
assert(y == 'xuxu')
T.testC("settable 2", b, 19)
assert(a[b] == 19)
--
do -- testing getfield/setfield with long keys
local t = {_012345678901234567890123456789012345678901234567890123456789 = 32}
local a = T.testC([[
getfield 2 _012345678901234567890123456789012345678901234567890123456789
return 1
]], t)
assert(a == 32)
local a = T.testC([[
pushnum 33
setglobal _012345678901234567890123456789012345678901234567890123456789
]])
assert(_012345678901234567890123456789012345678901234567890123456789 == 33)
_012345678901234567890123456789012345678901234567890123456789 = nil
end
-- testing next
a = {}
t = pack(T.testC("next; return *", a, nil))
tcheck(t, {n=1,a})
a = {a=3}
t = pack(T.testC("next; return *", a, nil))
tcheck(t, {n=3,a,'a',3})
t = pack(T.testC("next; pop 1; next; return *", a, nil))
tcheck(t, {n=1,a})
-- testing upvalues
do
local A = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
t, b, c = A([[pushvalue U0; pushvalue U1; pushvalue U2; return 3]])
assert(b == 10 and c == 20 and type(t) == 'table')
a, b = A([[tostring U3; tonumber U4; return 2]])
assert(a == nil and b == 0)
A([[pushnum 100; pushnum 200; replace U2; replace U1]])
b, c = A([[pushvalue U1; pushvalue U2; return 2]])
assert(b == 100 and c == 200)
A([[replace U2; replace U1]], {x=1}, {x=2})
b, c = A([[pushvalue U1; pushvalue U2; return 2]])
assert(b.x == 1 and c.x == 2)
T.checkmemory()
end
-- testing absent upvalues from C-function pointers
assert(T.testC[[isnull U1; return 1]] == true)
assert(T.testC[[isnull U100; return 1]] == true)
assert(T.testC[[pushvalue U1; return 1]] == nil)
local f = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
assert(T.upvalue(f, 1) == 10 and
T.upvalue(f, 2) == 20 and
T.upvalue(f, 3) == nil)
T.upvalue(f, 2, "xuxu")
assert(T.upvalue(f, 2) == "xuxu")
-- large closures
do
local A = "checkstack 300 msg;" ..
string.rep("pushnum 10;", 255) ..
"pushcclosure 255; return 1"
A = T.testC(A)
for i=1,255 do
assert(A(("pushvalue U%d; return 1"):format(i)) == 10)
end
assert(A("isnull U256; return 1"))
assert(not A("isnil U256; return 1"))
end
-- testing get/setuservalue
-- bug in 5.1.2
checkerr("got number", debug.setuservalue, 3, {})
checkerr("got nil", debug.setuservalue, nil, {})
checkerr("got light userdata", debug.setuservalue, T.pushuserdata(1), {})
local b = T.newuserdata(0)
assert(debug.getuservalue(b) == nil)
for _, v in pairs{true, false, 4.56, print, {}, b, "XYZ"} do
assert(debug.setuservalue(b, v) == b)
assert(debug.getuservalue(b) == v)
end
assert(debug.getuservalue(4) == nil)
debug.setuservalue(b, function () return 10 end)
collectgarbage() -- function should not be collected
assert(debug.getuservalue(b)() == 10)
debug.setuservalue(b, 134)
collectgarbage() -- number should not be a problem for collector
assert(debug.getuservalue(b) == 134)
-- test barrier for uservalues
T.gcstate("atomic")
assert(T.gccolor(b) == "black")
debug.setuservalue(b, {x = 100})
T.gcstate("pause") -- complete collection
assert(debug.getuservalue(b).x == 100) -- uvalue should be there
-- long chain of userdata
for i = 1, 1000 do
local bb = T.newuserdata(0)
debug.setuservalue(bb, b)
b = bb
end
collectgarbage() -- nothing should not be collected
for i = 1, 1000 do
b = debug.getuservalue(b)
end
assert(debug.getuservalue(b).x == 100)
b = nil
-- testing locks (refs)
-- reuse of references
local i = T.ref{}
T.unref(i)
assert(T.ref{} == i)
Arr = {}
Lim = 100
for i=1,Lim do -- lock many objects
Arr[i] = T.ref({})
end
assert(T.ref(nil) == -1 and T.getref(-1) == nil)
T.unref(-1); T.unref(-1)
for i=1,Lim do -- unlock all them
T.unref(Arr[i])
end
function printlocks ()
local f = T.makeCfunc("gettable R; return 1")
local n = f("n")
print("n", n)
for i=0,n do
print(i, f(i))
end
end
for i=1,Lim do -- lock many objects
Arr[i] = T.ref({})
end
for i=1,Lim,2 do -- unlock half of them
T.unref(Arr[i])
end
assert(type(T.getref(Arr[2])) == 'table')
assert(T.getref(-1) == nil)
a = T.ref({})
collectgarbage()
assert(type(T.getref(a)) == 'table')
-- colect in cl the `val' of all collected userdata
tt = {}
cl = {n=0}
A = nil; B = nil
local F
F = function (x)
local udval = T.udataval(x)
table.insert(cl, udval)
local d = T.newuserdata(100) -- cria lixo
d = nil
assert(debug.getmetatable(x).__gc == F)
assert(load("table.insert({}, {})"))() -- cria mais lixo
collectgarbage() -- forca coleta de lixo durante coleta!
assert(debug.getmetatable(x).__gc == F) -- coleta anterior nao melou isso?
local dummy = {} -- cria lixo durante coleta
if A ~= nil then
assert(type(A) == "userdata")
assert(T.udataval(A) == B)
debug.getmetatable(A) -- just acess it
end
A = x -- ressucita userdata
B = udval
return 1,2,3
end
tt.__gc = F
-- test whether udate collection frees memory in the right time
do
collectgarbage();
collectgarbage();
local x = collectgarbage("count");
local a = T.newuserdata(5001)
assert(T.testC("objsize 2; return 1", a) == 5001)
assert(collectgarbage("count") >= x+4)
a = nil
collectgarbage();
assert(collectgarbage("count") <= x+1)
-- udata without finalizer
x = collectgarbage("count")
collectgarbage("stop")
for i=1,1000 do T.newuserdata(0) end
assert(collectgarbage("count") > x+10)
collectgarbage()
assert(collectgarbage("count") <= x+1)
-- udata with finalizer
collectgarbage()
x = collectgarbage("count")
collectgarbage("stop")
a = {__gc = function () end}
for i=1,1000 do debug.setmetatable(T.newuserdata(0), a) end
assert(collectgarbage("count") >= x+10)
collectgarbage() -- this collection only calls TM, without freeing memory
assert(collectgarbage("count") >= x+10)
collectgarbage() -- now frees memory
assert(collectgarbage("count") <= x+1)
collectgarbage("restart")
end
collectgarbage("stop")
-- create 3 userdatas with tag `tt'
a = T.newuserdata(0); debug.setmetatable(a, tt); na = T.udataval(a)
b = T.newuserdata(0); debug.setmetatable(b, tt); nb = T.udataval(b)
c = T.newuserdata(0); debug.setmetatable(c, tt); nc = T.udataval(c)
-- create userdata without meta table
x = T.newuserdata(4)
y = T.newuserdata(0)
checkerr("FILE%* expected, got userdata", io.input, a)
checkerr("FILE%* expected, got userdata", io.input, x)
assert(debug.getmetatable(x) == nil and debug.getmetatable(y) == nil)
d=T.ref(a);
e=T.ref(b);
f=T.ref(c);
t = {T.getref(d), T.getref(e), T.getref(f)}
assert(t[1] == a and t[2] == b and t[3] == c)
t=nil; a=nil; c=nil;
T.unref(e); T.unref(f)
collectgarbage()
-- check that unref objects have been collected
assert(#cl == 1 and cl[1] == nc)
x = T.getref(d)
assert(type(x) == 'userdata' and debug.getmetatable(x) == tt)
x =nil
tt.b = b -- create cycle
tt=nil -- frees tt for GC
A = nil
b = nil
T.unref(d);
n5 = T.newuserdata(0)
debug.setmetatable(n5, {__gc=F})
n5 = T.udataval(n5)
collectgarbage()
assert(#cl == 4)
-- check order of collection
assert(cl[2] == n5 and cl[3] == nb and cl[4] == na)
collectgarbage"restart"
a, na = {}, {}
for i=30,1,-1 do
a[i] = T.newuserdata(0)
debug.setmetatable(a[i], {__gc=F})
na[i] = T.udataval(a[i])
end
cl = {}
a = nil; collectgarbage()
assert(#cl == 30)
for i=1,30 do assert(cl[i] == na[i]) end
na = nil
for i=2,Lim,2 do -- unlock the other half
T.unref(Arr[i])
end
x = T.newuserdata(41); debug.setmetatable(x, {__gc=F})
assert(T.testC("objsize 2; return 1", x) == 41)
cl = {}
a = {[x] = 1}
x = T.udataval(x)
collectgarbage()
-- old `x' cannot be collected (`a' still uses it)
assert(#cl == 0)
for n in pairs(a) do a[n] = nil end
collectgarbage()
assert(#cl == 1 and cl[1] == x) -- old `x' must be collected
-- testing lua_equal
assert(T.testC("compare EQ 2 4; return 1", print, 1, print, 20))
assert(T.testC("compare EQ 3 2; return 1", 'alo', "alo"))
assert(T.testC("compare EQ 2 3; return 1", nil, nil))
assert(not T.testC("compare EQ 2 3; return 1", {}, {}))
assert(not T.testC("compare EQ 2 3; return 1"))
assert(not T.testC("compare EQ 2 3; return 1", 3))
-- testing lua_equal with fallbacks
do
local map = {}
local t = {__eq = function (a,b) return map[a] == map[b] end}
local function f(x)
local u = T.newuserdata(0)
debug.setmetatable(u, t)
map[u] = x
return u
end
assert(f(10) == f(10))
assert(f(10) ~= f(11))
assert(T.testC("compare EQ 2 3; return 1", f(10), f(10)))
assert(not T.testC("compare EQ 2 3; return 1", f(10), f(20)))
t.__eq = nil
assert(f(10) ~= f(10))
end
print'+'
-- testing changing hooks during hooks
_G.t = {}
T.sethook([[
# set a line hook after 3 count hooks
sethook 4 0 '
getglobal t;
pushvalue -3; append -2
pushvalue -2; append -2
']], "c", 3)
local a = 1 -- counting
a = 1 -- counting
a = 1 -- count hook (set line hook)
a = 1 -- line hook
a = 1 -- line hook
debug.sethook()
t = _G.t
assert(t[1] == "line")
line = t[2]
assert(t[3] == "line" and t[4] == line + 1)
assert(t[5] == "line" and t[6] == line + 2)
assert(t[7] == nil)
-------------------------------------------------------------------------
do -- testing errors during GC
local a = {}
for i=1,20 do
a[i] = T.newuserdata(i) -- creates several udata
end
for i=1,20,2 do -- mark half of them to raise errors during GC
debug.setmetatable(a[i], {__gc = function (x) error("error inside gc") end})
end
for i=2,20,2 do -- mark the other half to count and to create more garbage
debug.setmetatable(a[i], {__gc = function (x) load("A=A+1")() end})
end
_G.A = 0
a = 0
while 1 do
local stat, msg = pcall(collectgarbage)
if stat then
break -- stop when no more errors
else
a = a + 1
assert(string.find(msg, "__gc"))
end
end
assert(a == 10) -- number of errors
assert(A == 10) -- number of normal collections
end
-------------------------------------------------------------------------
-- test for userdata vals
do
local a = {}; local lim = 30
for i=0,lim do a[i] = T.pushuserdata(i) end
for i=0,lim do assert(T.udataval(a[i]) == i) end
for i=0,lim do assert(T.pushuserdata(i) == a[i]) end
for i=0,lim do a[a[i]] = i end
for i=0,lim do a[T.pushuserdata(i)] = i end
assert(type(tostring(a[1])) == "string")
end
-------------------------------------------------------------------------
-- testing multiple states
T.closestate(T.newstate());
L1 = T.newstate()
assert(L1)
assert(T.doremote(L1, "X='a'; return 'a'") == 'a')
assert(#pack(T.doremote(L1, "function f () return 'alo', 3 end; f()")) == 0)
a, b = T.doremote(L1, "return f()")
assert(a == 'alo' and b == '3')
T.doremote(L1, "_ERRORMESSAGE = nil")
-- error: `sin' is not defined
a, _, b = T.doremote(L1, "return sin(1)")
assert(a == nil and b == 2) -- 2 == run-time error
-- error: syntax error
a, b, c = T.doremote(L1, "return a+")
assert(a == nil and c == 3 and type(b) == "string") -- 3 == syntax error
T.loadlib(L1)
a, b, c = T.doremote(L1, [[
string = require'string'
a = require'_G'; assert(a == _G and require("_G") == a)
io = require'io'; assert(type(io.read) == "function")
assert(require("io") == io)
a = require'table'; assert(type(a.insert) == "function")
a = require'debug'; assert(type(a.getlocal) == "function")
a = require'math'; assert(type(a.sin) == "function")
return string.sub('okinama', 1, 2)
]])
assert(a == "ok")
T.closestate(L1);
L1 = T.newstate()
T.loadlib(L1)
T.doremote(L1, "a = {}")
T.testC(L1, [[getglobal "a"; pushstring "x"; pushint 1;
settable -3]])
assert(T.doremote(L1, "return a.x") == "1")
T.closestate(L1)
L1 = nil
print('+')
-------------------------------------------------------------------------
-- testing memory limits
-------------------------------------------------------------------------
checkerr("block too big", T.newuserdata, math.maxinteger)
collectgarbage()
T.totalmem(T.totalmem()+5000) -- set low memory limit (+5k)
checkerr("not enough memory", load"local a={}; for i=1,100000 do a[i]=i end")
T.totalmem(0) -- restore high limit
-- test memory errors; increase memory limit in small steps, so that
-- we get memory errors in different parts of a given task, up to there
-- is enough memory to complete the task without errors
function testamem (s, f)
collectgarbage(); collectgarbage()
local M = T.totalmem()
local oldM = M
local a,b = nil
while M < 200000 do
M = M+7 -- increase memory limit in small steps
T.totalmem(M)
a, b = pcall(f)
T.totalmem(0) -- restore high limit
if a and b then break end -- stop when no more errors
collectgarbage()
if not a and not -- `real' error?
(string.find(b, "memory") or string.find(b, "overflow")) then
error(b, 0) -- propagate it
end
end
if M > 200000 then print ("hit 20K limit") end
print("\nlimit for " .. s .. ": " .. M-oldM)
return b
end
-- testing memory errors when creating a new state
b = testamem("state creation", T.newstate)
T.closestate(b); -- close new state
-- testing threads
-- get main thread from registry (at index LUA_RIDX_MAINTHREAD == 1)
mt = T.testC("rawgeti R 1; return 1")
assert(type(mt) == "thread" and coroutine.running() == mt)
function expand (n,s)
if n==0 then return "" end
local e = string.rep("=", n)
return string.format("T.doonnewstack([%s[ %s;\n collectgarbage(); %s]%s])\n",
e, s, expand(n-1,s), e)
end
G=0; collectgarbage(); a =collectgarbage("count")
load(expand(20,"G=G+1"))()
assert(G==20); collectgarbage(); -- assert(gcinfo() <= a+1)
testamem("thread creation", function ()
return T.doonnewstack("x=1") == 0 -- try to create thread
end)
-- testing memory x compiler
testamem("loadstring", function ()
return load("x=1") -- try to do load a string
end)
local testprog = [[
local function foo () return end
local t = {"x"}
a = "aaa"
for i = 1, #t do a=a..t[i] end
return true
]]
-- testing memory x dofile
_G.a = nil
local t =os.tmpname()
local f = assert(io.open(t, "w"))
f:write(testprog)
f:close()
testamem("dofile", function ()
local a = loadfile(t)
return a and a()
end)
assert(os.remove(t))
assert(_G.a == "aaax")
-- other generic tests
testamem("string creation", function ()
local a, b = string.gsub("alo alo", "(a)", function (x) return x..'b' end)
return (a == 'ablo ablo')
end)
testamem("dump/undump", function ()
local a = load(testprog)
local b = a and string.dump(a)
a = b and load(b)
return a and a()
end)
local t = os.tmpname()
testamem("file creation", function ()
local f = assert(io.open(t, 'w'))
assert (not io.open"nomenaoexistente")
io.close(f);
return not loadfile'nomenaoexistente'
end)
assert(os.remove(t))
testamem("table creation", function ()
local a, lim = {}, 10
for i=1,lim do a[i] = i; a[i..'a'] = {} end
return (type(a[lim..'a']) == 'table' and a[lim] == lim)
end)
testamem("constructors", function ()
local a = {10, 20, 30, 40, 50; a=1, b=2, c=3, d=4, e=5}
return (type(a) == 'table' and a.e == 5)
end)
local a = 1
close = nil
testamem("closure creation", function ()
function close (b,c)
return function (x) return a+b+c+x end
end
return (close(2,3)(4) == 10)
end)
testamem("coroutines", function ()
local a = coroutine.wrap(function ()
coroutine.yield(string.rep("a", 10))
return {}
end)
assert(string.len(a()) == 10)
return a()
end)
do -- auxiliary buffer
local lim = 100
local a = {}; for i = 1, lim do a[i] = "01234567890123456789" end
testamem("auxiliary buffer", function ()
return (#table.concat(a, ",") == 20*lim + lim - 1)
end)
end
print'+'
-- testing some auxlib functions
local function gsub (a, b, c)
a, b = T.testC("gsub 2 3 4; gettop; return 2", a, b, c)
assert(b == 5)
return a
end
assert(gsub("alo.alo.uhuh.", ".", "//") == "alo//alo//uhuh//")
assert(gsub("alo.alo.uhuh.", "alo", "//") == "//.//.uhuh.")
assert(gsub("", "alo", "//") == "")
assert(gsub("...", ".", "/.") == "/././.")
assert(gsub("...", "...", "") == "")
-- testing luaL_newmetatable
local mt_xuxu, res, top = T.testC("newmetatable xuxu; gettop; return 3")
assert(type(mt_xuxu) == "table" and res and top == 3)
local d, res, top = T.testC("newmetatable xuxu; gettop; return 3")
assert(mt_xuxu == d and not res and top == 3)
d, res, top = T.testC("newmetatable xuxu1; gettop; return 3")
assert(mt_xuxu ~= d and res and top == 3)
x = T.newuserdata(0);
y = T.newuserdata(0);
T.testC("pushstring xuxu; gettable R; setmetatable 2", x)
assert(getmetatable(x) == mt_xuxu)
-- testing luaL_testudata
-- correct metatable
local res1, res2, top = T.testC([[testudata -1 xuxu
testudata 2 xuxu
gettop
return 3]], x)
assert(res1 and res2 and top == 4)
-- wrong metatable
res1, res2, top = T.testC([[testudata -1 xuxu1
testudata 2 xuxu1
gettop
return 3]], x)
assert(not res1 and not res2 and top == 4)
-- non-existent type
res1, res2, top = T.testC([[testudata -1 xuxu2
testudata 2 xuxu2
gettop
return 3]], x)
assert(not res1 and not res2 and top == 4)
-- userdata has no metatable
res1, res2, top = T.testC([[testudata -1 xuxu
testudata 2 xuxu
gettop
return 3]], y)
assert(not res1 and not res2 and top == 4)
-- erase metatables
do
local r = debug.getregistry()
assert(r.xuxu == mt_xuxu and r.xuxu1 == d)
r.xuxu = nil; r.xuxu1 = nil
end
print'OK'
-- $Id: attrib.lua,v 1.65 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice in file all.lua
print "testing require"
assert(require"string" == string)
assert(require"math" == math)
assert(require"table" == table)
assert(require"io" == io)
assert(require"os" == os)
assert(require"coroutine" == coroutine)
assert(type(package.path) == "string")
--[[NodeMCU doesn't support dynamic C loading
assert(type(package.cpath) == "string")
]]
assert(type(package.loaded) == "table")
assert(type(package.preload) == "table")
assert(type(package.config) == "string")
print("package config: "..string.gsub(package.config, "\n", "|"))
--[[TODO: NodeMCU doesn't support dynamic C loading
do
-- create a path with 'max' templates,
-- each with 1-10 repetitions of '?'
local max = _soft and 100 or 2000
local t = {}
for i = 1,max do t[i] = string.rep("?", i%10 + 1) end
t[#t + 1] = ";" -- empty template
local path = table.concat(t, ";")
-- use that path in a search
local s, err = package.searchpath("xuxu", path)
-- search fails; check that message has an occurence of
-- '??????????' with ? replaced by xuxu and at least 'max' lines
assert(not s and
string.find(err, string.rep("xuxu", 10)) and
#string.gsub(err, "[^\n]", "") >= max)
-- path with one very long template
local path = string.rep("?", max)
local s, err = package.searchpath("xuxu", path)
assert(not s and string.find(err, string.rep('xuxu', max)))
end
]]
do
local oldpath = package.path
package.path = {}
local s, err = pcall(require, "no-such-file")
assert(not s and string.find(err, "package.path"))
package.path = oldpath
end
print('+')
-- The next tests for 'require' assume some specific directories and
-- libraries.
--[=[TODO: NodeMCU doesn't support dynamic loading and rich FS. Might to use a subset here
if not _port then --[
local dirsep = string.match(package.config, "^([^\n]+)\n")
-- auxiliary directory with C modules and temporary files
local DIR = "libs" .. dirsep
-- prepend DIR to a name and correct directory separators
local function D (x)
x = string.gsub(x, "/", dirsep)
return DIR .. x
end
-- prepend DIR and pospend proper C lib. extension to a name
local function DC (x)
local ext = (dirsep == '\\') and ".dll" or ".so"
return D(x .. ext)
end
local function createfiles (files, preextras, posextras)
for n,c in pairs(files) do
io.output(D(n))
io.write(string.format(preextras, n))
io.write(c)
io.write(string.format(posextras, n))
io.close(io.output())
end
end
function removefiles (files)
for n in pairs(files) do
os.remove(D(n))
end
end
local files = {
["names.lua"] = "do return {...} end\n",
["err.lua"] = "B = 15; a = a + 1;",
["synerr.lua"] = "B =",
["A.lua"] = "",
["B.lua"] = "assert(...=='B');require 'A'",
["A.lc"] = "",
["A"] = "",
["L"] = "",
["XXxX"] = "",
["C.lua"] = "package.loaded[...] = 25; require'C'",
}
AA = nil
local extras = [[
NAME = '%s'
REQUIRED = ...
return AA]]
createfiles(files, "", extras)
-- testing explicit "dir" separator in 'searchpath'
assert(package.searchpath("C.lua", D"?", "", "") == D"C.lua")
assert(package.searchpath("C.lua", D"?", ".", ".") == D"C.lua")
assert(package.searchpath("--x-", D"?", "-", "X") == D"XXxX")
assert(package.searchpath("---xX", D"?", "---", "XX") == D"XXxX")
assert(package.searchpath(D"C.lua", "?", dirsep) == D"C.lua")
assert(package.searchpath(".\\C.lua", D"?", "\\") == D"./C.lua")
local oldpath = package.path
package.path = string.gsub("D/?.lua;D/?.lc;D/?;D/??x?;D/L", "D/", DIR)
local try = function (p, n, r)
NAME = nil
local rr = require(p)
assert(NAME == n)
assert(REQUIRED == p)
assert(rr == r)
end
a = require"names"
assert(a[1] == "names" and a[2] == D"names.lua")
_G.a = nil
local st, msg = pcall(require, "err")
assert(not st and string.find(msg, "arithmetic") and B == 15)
st, msg = pcall(require, "synerr")
assert(not st and string.find(msg, "error loading module"))
assert(package.searchpath("C", package.path) == D"C.lua")
assert(require"C" == 25)
assert(require"C" == 25)
AA = nil
try('B', 'B.lua', true)
assert(package.loaded.B)
assert(require"B" == true)
assert(package.loaded.A)
assert(require"C" == 25)
package.loaded.A = nil
try('B', nil, true) -- should not reload package
try('A', 'A.lua', true)
package.loaded.A = nil
os.remove(D'A.lua')
AA = {}
try('A', 'A.lc', AA) -- now must find second option
assert(package.searchpath("A", package.path) == D"A.lc")
assert(require("A") == AA)
AA = false
try('K', 'L', false) -- default option
try('K', 'L', false) -- default option (should reload it)
assert(rawget(_G, "_REQUIREDNAME") == nil)
AA = "x"
try("X", "XXxX", AA)
removefiles(files)
-- testing require of sub-packages
local _G = _G
package.path = string.gsub("D/?.lua;D/?/init.lua", "D/", DIR)
files = {
["P1/init.lua"] = "AA = 10",
["P1/xuxu.lua"] = "AA = 20",
}
createfiles(files, "_ENV = {}\n", "\nreturn _ENV\n")
AA = 0
local m = assert(require"P1")
assert(AA == 0 and m.AA == 10)
assert(require"P1" == m)
assert(require"P1" == m)
assert(package.searchpath("P1.xuxu", package.path) == D"P1/xuxu.lua")
m.xuxu = assert(require"P1.xuxu")
assert(AA == 0 and m.xuxu.AA == 20)
assert(require"P1.xuxu" == m.xuxu)
assert(require"P1.xuxu" == m.xuxu)
assert(require"P1" == m and m.AA == 10)
removefiles(files)
package.path = ""
assert(not pcall(require, "file_does_not_exist"))
package.path = "??\0?"
assert(not pcall(require, "file_does_not_exist1"))
package.path = oldpath
-- check 'require' error message
local fname = "file_does_not_exist2"
local m, err = pcall(require, fname)
for t in string.gmatch(package.path..";"..package.cpath, "[^;]+") do
t = string.gsub(t, "?", fname)
assert(string.find(err, t, 1, true))
end
do -- testing 'package.searchers' not being a table
local searchers = package.searchers
package.searchers = 3
local st, msg = pcall(require, 'a')
assert(not st and string.find(msg, "must be a table"))
package.searchers = searchers
end
local function import(...)
local f = {...}
return function (m)
for i=1, #f do m[f[i]] = _G[f[i]] end
end
end
-- cannot change environment of a C function
assert(not pcall(module, 'XUXU'))
-- testing require of C libraries
local p = "" -- On Mac OS X, redefine this to "_"
-- check whether loadlib works in this system
local st, err, when = package.loadlib(DC"lib1", "*")
if not st then
local f, err, when = package.loadlib("donotexist", p.."xuxu")
assert(not f and type(err) == "string" and when == "absent")
;(Message or print)('\n >>> cannot load dynamic library <<<\n')
print(err, when)
else
-- tests for loadlib
local f = assert(package.loadlib(DC"lib1", p.."onefunction"))
local a, b = f(15, 25)
assert(a == 25 and b == 15)
f = assert(package.loadlib(DC"lib1", p.."anotherfunc"))
assert(f(10, 20) == "10%20\n")
-- check error messages
local f, err, when = package.loadlib(DC"lib1", p.."xuxu")
assert(not f and type(err) == "string" and when == "init")
f, err, when = package.loadlib("donotexist", p.."xuxu")
assert(not f and type(err) == "string" and when == "open")
-- symbols from 'lib1' must be visible to other libraries
f = assert(package.loadlib(DC"lib11", p.."luaopen_lib11"))
assert(f() == "exported")
-- test C modules with prefixes in names
package.cpath = DC"?"
local lib2 = require"lib2-v2"
-- check correct access to global environment and correct
-- parameters
assert(_ENV.x == "lib2-v2" and _ENV.y == DC"lib2-v2")
assert(lib2.id("x") == "x")
-- test C submodules
local fs = require"lib1.sub"
assert(_ENV.x == "lib1.sub" and _ENV.y == DC"lib1")
assert(fs.id(45) == 45)
end
_ENV = _G
-- testing preload
do
local p = package
package = {}
p.preload.pl = function (...)
local _ENV = {...}
function xuxu (x) return x+20 end
return _ENV
end
local pl = require"pl"
assert(require"pl" == pl)
assert(pl.xuxu(10) == 30)
assert(pl[1] == "pl" and pl[2] == nil)
package = p
assert(type(package.path) == "string")
end
print('+')
end --]
--]=]
print("testing assignments, logical operators, and constructors")
local res, res2 = 27
a, b = 1, 2+3
assert(a==1 and b==5)
a={}
function f() return 10, 11, 12 end
a.x, b, a[1] = 1, 2, f()
assert(a.x==1 and b==2 and a[1]==10)
a[f()], b, a[f()+3] = f(), a, 'x'
assert(a[10] == 10 and b == a and a[13] == 'x')
do
local f = function (n) local x = {}; for i=1,n do x[i]=i end;
return table.unpack(x) end;
local a,b,c
a,b = 0, f(1)
assert(a == 0 and b == 1)
A,b = 0, f(1)
assert(A == 0 and b == 1)
a,b,c = 0,5,f(4)
assert(a==0 and b==5 and c==1)
a,b,c = 0,5,f(0)
assert(a==0 and b==5 and c==nil)
end
a, b, c, d = 1 and nil, 1 or nil, (1 and (nil or 1)), 6
assert(not a and b and c and d==6)
d = 20
a, b, c, d = f()
assert(a==10 and b==11 and c==12 and d==nil)
a,b = f(), 1, 2, 3, f()
assert(a==10 and b==1)
assert(a<b == false and a>b == true)
assert((10 and 2) == 2)
assert((10 or 2) == 10)
assert((10 or assert(nil)) == 10)
assert(not (nil and assert(nil)))
assert((nil or "alo") == "alo")
assert((nil and 10) == nil)
assert((false and 10) == false)
assert((true or 10) == true)
assert((false or 10) == 10)
assert(false ~= nil)
assert(nil ~= false)
assert(not nil == true)
assert(not not nil == false)
assert(not not 1 == true)
assert(not not a == true)
assert(not not (6 or nil) == true)
assert(not not (nil and 56) == false)
assert(not not (nil and true) == false)
assert(not 10 == false)
assert(not {} == false)
assert(not 0.5 == false)
assert(not "x" == false)
assert({} ~= {})
print('+')
a = {}
a[true] = 20
a[false] = 10
assert(a[1<2] == 20 and a[1>2] == 10)
function f(a) return a end
local a = {}
for i=3000,-3000,-1 do a[i + 0.0] = i; end
a[10e30] = "alo"; a[true] = 10; a[false] = 20
assert(a[10e30] == 'alo' and a[not 1] == 20 and a[10<20] == 10)
for i=3000,-3000,-1 do assert(a[i] == i); end
a[print] = assert
a[f] = print
a[a] = a
assert(a[a][a][a][a][print] == assert)
a[print](a[a[f]] == a[print])
assert(not pcall(function () local a = {}; a[nil] = 10 end))
assert(not pcall(function () local a = {[nil] = 10} end))
assert(a[nil] == nil)
a = nil
a = {10,9,8,7,6,5,4,3,2; [-3]='a', [f]=print, a='a', b='ab'}
a, a.x, a.y = a, a[-3]
assert(a[1]==10 and a[-3]==a.a and a[f]==print and a.x=='a' and not a.y)
a[1], f(a)[2], b, c = {['alo']=assert}, 10, a[1], a[f], 6, 10, 23, f(a), 2
a[1].alo(a[2]==10 and b==10 and c==print)
-- test of large float/integer indices
-- compute maximum integer where all bits fit in a float
local maxint = math.maxinteger
while maxint - 1.0 == maxint - 0.0 do -- trim (if needed) to fit in a float
maxint = maxint // 2
end
maxintF = maxint + 0.0 -- float version
assert(math.type(maxintF) == "float" and maxintF >= 2.0^14)
-- floats and integers must index the same places
a[maxintF] = 10; a[maxintF - 1.0] = 11;
a[-maxintF] = 12; a[-maxintF + 1.0] = 13;
assert(a[maxint] == 10 and a[maxint - 1] == 11 and
a[-maxint] == 12 and a[-maxint + 1] == 13)
a[maxint] = 20
a[-maxint] = 22
assert(a[maxintF] == 20 and a[maxintF - 1.0] == 11 and
a[-maxintF] == 22 and a[-maxintF + 1.0] == 13)
a = nil
-- test conflicts in multiple assignment
do
local a,i,j,b
a = {'a', 'b'}; i=1; j=2; b=a
i, a[i], a, j, a[j], a[i+j] = j, i, i, b, j, i
assert(i == 2 and b[1] == 1 and a == 1 and j == b and b[2] == 2 and
b[3] == 1)
end
-- repeat test with upvalues
do
local a,i,j,b
a = {'a', 'b'}; i=1; j=2; b=a
local function foo ()
i, a[i], a, j, a[j], a[i+j] = j, i, i, b, j, i
end
foo()
assert(i == 2 and b[1] == 1 and a == 1 and j == b and b[2] == 2 and
b[3] == 1)
local t = {}
(function (a) t[a], a = 10, 20 end)(1);
assert(t[1] == 10)
end
-- bug in 5.2 beta
local function foo ()
local a
return function ()
local b
a, b = 3, 14 -- local and upvalue have same index
return a, b
end
end
local a, b = foo()()
assert(a == 3 and b == 14)
print('OK')
return res
-- $Id: big.lua,v 1.32 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice in file all.lua
if _soft then
return 'a'
end
print "testing large tables"
local debug = require"debug"
-- NodeMCU: limit big size to IoT scales
local lim = 50000
local prog = { "local y = {0" }
for i = 1, lim do prog[#prog + 1] = i end
prog[#prog + 1] = "}\n"
prog[#prog + 1] = "X = y\n"
prog[#prog + 1] = ("assert(X[%d] == %d)"):format(lim - 1, lim - 2)
prog[#prog + 1] = "return 0"
prog = table.concat(prog, ";")
local env = {string = string, assert = assert}
local f = assert(load(prog, nil, nil, env))
f()
assert(env.X[lim] == lim - 1 and env.X[lim + 1] == lim)
for k in pairs(env) do env[k] = nil end
-- yields during accesses larger than K (in RK)
setmetatable(env, {
__index = function (t, n) coroutine.yield('g'); return _G[n] end,
__newindex = function (t, n, v) coroutine.yield('s'); _G[n] = v end,
})
X = nil
co = coroutine.wrap(f)
assert(co() == 's')
assert(co() == 'g')
assert(co() == 'g')
assert(co() == 0)
assert(X[lim] == lim - 1 and X[lim + 1] == lim)
-- errors in accesses larger than K (in RK)
getmetatable(env).__index = function () end
getmetatable(env).__newindex = function () end
local e, m = pcall(f)
assert(not e and m:find("global 'X'"))
-- errors in metamethods
getmetatable(env).__newindex = function () error("hi") end
local e, m = xpcall(f, debug.traceback)
assert(not e and m:find("'__newindex'"))
f, X = nil
coroutine.yield'b'
if 2^32 == 0 then -- (small integers) {
print "testing string length overflow"
local repstrings = 192 -- number of strings to be concatenated
local ssize = math.ceil(2.0^32 / repstrings) + 1 -- size of each string
assert(repstrings * ssize > 2.0^32) -- it should be larger than maximum size
local longs = string.rep("\0", ssize) -- create one long string
-- create function to concatentate 'repstrings' copies of its argument
local rep = assert(load(
"local a = ...; return " .. string.rep("a", repstrings, "..")))
local a, b = pcall(rep, longs) -- call that function
-- it should fail without creating string (result would be too large)
assert(not a and string.find(b, "overflow"))
end -- }
print'OK'
return 'a'
-- $Id: bitwise.lua,v 1.26 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice in file all.lua
print("testing bitwise operations")
local numbits = string.packsize('j') * 8
assert(~0 == -1)
assert((1 << (numbits - 1)) == math.mininteger)
-- basic tests for bitwise operators;
-- use variables to avoid constant folding
local a, b, c, d
a = 0xFFFFFFFFFFFFFFFF
assert(a == -1 and a & -1 == a and a & 35 == 35)
a = 0xF0F0F0F0F0F0F0F0
assert(a | -1 == -1)
assert(a ~ a == 0 and a ~ 0 == a and a ~ ~a == -1)
assert(a >> 4 == ~a)
a = 0xF0; b = 0xCC; c = 0xAA; d = 0xFD
assert(a | b ~ c & d == 0xF4)
a = 0xF0.0; b = 0xCC.0; c = "0xAA.0"; d = "0xFD.0"
assert(a | b ~ c & d == 0xF4)
a = 0xF0000000; b = 0xCC000000;
c = 0xAA000000; d = 0xFD000000
assert(a | b ~ c & d == 0xF4000000)
assert(~~a == a and ~a == -1 ~ a and -d == ~d + 1)
a = a << 32
b = b << 32
c = c << 32
d = d << 32
assert(a | b ~ c & d == 0xF4000000 << 32)
assert(~~a == a and ~a == -1 ~ a and -d == ~d + 1)
assert(-1 >> 1 == (1 << (numbits - 1)) - 1 and 1 << 31 == 0x80000000)
assert(-1 >> (numbits - 1) == 1)
assert(-1 >> numbits == 0 and
-1 >> -numbits == 0 and
-1 << numbits == 0 and
-1 << -numbits == 0)
assert((2^30 - 1) << 2^30 == 0)
assert((2^30 - 1) >> 2^30 == 0)
assert(1 >> -3 == 1 << 3 and 1000 >> 5 == 1000 << -5)
-- coercion from strings to integers
assert("0xffffffffffffffff" | 0 == -1)
assert("0xfffffffffffffffe" & "-1" == -2)
assert(" \t-0xfffffffffffffffe\n\t" & "-1" == 2)
assert(" \n -45 \t " >> " -2 " == -45 * 4)
-- out of range number
assert(not pcall(function () return "0xffffffffffffffff.0" | 0 end))
-- embedded zeros
assert(not pcall(function () return "0xffffffffffffffff\0" | 0 end))
print'+'
package.preload.bit32 = function () --{
-- no built-in 'bit32' library: implement it using bitwise operators
local bit = {}
function bit.bnot (a)
return ~a & 0xFFFFFFFF
end
--
-- in all vararg functions, avoid creating 'arg' table when there are
-- only 2 (or less) parameters, as 2 parameters is the common case
--
function bit.band (x, y, z, ...)
if not z then
return ((x or -1) & (y or -1)) & 0xFFFFFFFF
else
local arg = {...}
local res = x & y & z
for i = 1, #arg do res = res & arg[i] end
return res & 0xFFFFFFFF
end
end
function bit.bor (x, y, z, ...)
if not z then
return ((x or 0) | (y or 0)) & 0xFFFFFFFF
else
local arg = {...}
local res = x | y | z
for i = 1, #arg do res = res | arg[i] end
return res & 0xFFFFFFFF
end
end
function bit.bxor (x, y, z, ...)
if not z then
return ((x or 0) ~ (y or 0)) & 0xFFFFFFFF
else
local arg = {...}
local res = x ~ y ~ z
for i = 1, #arg do res = res ~ arg[i] end
return res & 0xFFFFFFFF
end
end
function bit.btest (...)
return bit.band(...) ~= 0
end
function bit.lshift (a, b)
return ((a & 0xFFFFFFFF) << b) & 0xFFFFFFFF
end
function bit.rshift (a, b)
return ((a & 0xFFFFFFFF) >> b) & 0xFFFFFFFF
end
function bit.arshift (a, b)
a = a & 0xFFFFFFFF
if b <= 0 or (a & 0x80000000) == 0 then
return (a >> b) & 0xFFFFFFFF
else
return ((a >> b) | ~(0xFFFFFFFF >> b)) & 0xFFFFFFFF
end
end
function bit.lrotate (a ,b)
b = b & 31
a = a & 0xFFFFFFFF
a = (a << b) | (a >> (32 - b))
return a & 0xFFFFFFFF
end
function bit.rrotate (a, b)
return bit.lrotate(a, -b)
end
local function checkfield (f, w)
w = w or 1
assert(f >= 0, "field cannot be negative")
assert(w > 0, "width must be positive")
assert(f + w <= 32, "trying to access non-existent bits")
return f, ~(-1 << w)
end
function bit.extract (a, f, w)
local f, mask = checkfield(f, w)
return (a >> f) & mask
end
function bit.replace (a, v, f, w)
local f, mask = checkfield(f, w)
v = v & mask
a = (a & ~(mask << f)) | (v << f)
return a & 0xFFFFFFFF
end
return bit
end --}
print("testing bitwise library")
local bit32 = require'bit32'
assert(bit32.band() == bit32.bnot(0))
assert(bit32.btest() == true)
assert(bit32.bor() == 0)
assert(bit32.bxor() == 0)
assert(bit32.band() == bit32.band(0xffffffff))
assert(bit32.band(1,2) == 0)
-- out-of-range numbers
assert(bit32.band(-1) == 0xffffffff)
assert(bit32.band((1 << 33) - 1) == 0xffffffff)
assert(bit32.band(-(1 << 33) - 1) == 0xffffffff)
assert(bit32.band((1 << 33) + 1) == 1)
assert(bit32.band(-(1 << 33) + 1) == 1)
assert(bit32.band(-(1 << 40)) == 0)
assert(bit32.band(1 << 40) == 0)
assert(bit32.band(-(1 << 40) - 2) == 0xfffffffe)
assert(bit32.band((1 << 40) - 4) == 0xfffffffc)
assert(bit32.lrotate(0, -1) == 0)
assert(bit32.lrotate(0, 7) == 0)
assert(bit32.lrotate(0x12345678, 0) == 0x12345678)
assert(bit32.lrotate(0x12345678, 32) == 0x12345678)
assert(bit32.lrotate(0x12345678, 4) == 0x23456781)
assert(bit32.rrotate(0x12345678, -4) == 0x23456781)
assert(bit32.lrotate(0x12345678, -8) == 0x78123456)
assert(bit32.rrotate(0x12345678, 8) == 0x78123456)
assert(bit32.lrotate(0xaaaaaaaa, 2) == 0xaaaaaaaa)
assert(bit32.lrotate(0xaaaaaaaa, -2) == 0xaaaaaaaa)
for i = -50, 50 do
assert(bit32.lrotate(0x89abcdef, i) == bit32.lrotate(0x89abcdef, i%32))
end
assert(bit32.lshift(0x12345678, 4) == 0x23456780)
assert(bit32.lshift(0x12345678, 8) == 0x34567800)
assert(bit32.lshift(0x12345678, -4) == 0x01234567)
assert(bit32.lshift(0x12345678, -8) == 0x00123456)
assert(bit32.lshift(0x12345678, 32) == 0)
assert(bit32.lshift(0x12345678, -32) == 0)
assert(bit32.rshift(0x12345678, 4) == 0x01234567)
assert(bit32.rshift(0x12345678, 8) == 0x00123456)
assert(bit32.rshift(0x12345678, 32) == 0)
assert(bit32.rshift(0x12345678, -32) == 0)
assert(bit32.arshift(0x12345678, 0) == 0x12345678)
assert(bit32.arshift(0x12345678, 1) == 0x12345678 // 2)
assert(bit32.arshift(0x12345678, -1) == 0x12345678 * 2)
assert(bit32.arshift(-1, 1) == 0xffffffff)
assert(bit32.arshift(-1, 24) == 0xffffffff)
assert(bit32.arshift(-1, 32) == 0xffffffff)
assert(bit32.arshift(-1, -1) == bit32.band(-1 * 2, 0xffffffff))
assert(0x12345678 << 4 == 0x123456780)
assert(0x12345678 << 8 == 0x1234567800)
assert(0x12345678 << -4 == 0x01234567)
assert(0x12345678 << -8 == 0x00123456)
assert(0x12345678 << 32 == 0x1234567800000000)
assert(0x12345678 << -32 == 0)
assert(0x12345678 >> 4 == 0x01234567)
assert(0x12345678 >> 8 == 0x00123456)
assert(0x12345678 >> 32 == 0)
assert(0x12345678 >> -32 == 0x1234567800000000)
print("+")
-- some special cases
local c = {0, 1, 2, 3, 10, 0x80000000, 0xaaaaaaaa, 0x55555555,
0xffffffff, 0x7fffffff}
for _, b in pairs(c) do
assert(bit32.band(b) == b)
assert(bit32.band(b, b) == b)
assert(bit32.band(b, b, b, b) == b)
assert(bit32.btest(b, b) == (b ~= 0))
assert(bit32.band(b, b, b) == b)
assert(bit32.band(b, b, b, ~b) == 0)
assert(bit32.btest(b, b, b) == (b ~= 0))
assert(bit32.band(b, bit32.bnot(b)) == 0)
assert(bit32.bor(b, bit32.bnot(b)) == bit32.bnot(0))
assert(bit32.bor(b) == b)
assert(bit32.bor(b, b) == b)
assert(bit32.bor(b, b, b) == b)
assert(bit32.bor(b, b, 0, ~b) == 0xffffffff)
assert(bit32.bxor(b) == b)
assert(bit32.bxor(b, b) == 0)
assert(bit32.bxor(b, b, b) == b)
assert(bit32.bxor(b, b, b, b) == 0)
assert(bit32.bxor(b, 0) == b)
assert(bit32.bnot(b) ~= b)
assert(bit32.bnot(bit32.bnot(b)) == b)
assert(bit32.bnot(b) == (1 << 32) - 1 - b)
assert(bit32.lrotate(b, 32) == b)
assert(bit32.rrotate(b, 32) == b)
assert(bit32.lshift(bit32.lshift(b, -4), 4) == bit32.band(b, bit32.bnot(0xf)))
assert(bit32.rshift(bit32.rshift(b, 4), -4) == bit32.band(b, bit32.bnot(0xf)))
end
-- for this test, use at most 24 bits (mantissa of a single float)
c = {0, 1, 2, 3, 10, 0x800000, 0xaaaaaa, 0x555555, 0xffffff, 0x7fffff}
for _, b in pairs(c) do
for i = -40, 40 do
local x = bit32.lshift(b, i)
local y = math.floor(math.fmod(b * 2.0^i, 2.0^32))
assert(math.fmod(x - y, 2.0^32) == 0)
end
end
assert(not pcall(bit32.band, {}))
assert(not pcall(bit32.bnot, "a"))
assert(not pcall(bit32.lshift, 45))
assert(not pcall(bit32.lshift, 45, print))
assert(not pcall(bit32.rshift, 45, print))
print("+")
-- testing extract/replace
assert(bit32.extract(0x12345678, 0, 4) == 8)
assert(bit32.extract(0x12345678, 4, 4) == 7)
assert(bit32.extract(0xa0001111, 28, 4) == 0xa)
assert(bit32.extract(0xa0001111, 31, 1) == 1)
assert(bit32.extract(0x50000111, 31, 1) == 0)
assert(bit32.extract(0xf2345679, 0, 32) == 0xf2345679)
assert(not pcall(bit32.extract, 0, -1))
assert(not pcall(bit32.extract, 0, 32))
assert(not pcall(bit32.extract, 0, 0, 33))
assert(not pcall(bit32.extract, 0, 31, 2))
assert(bit32.replace(0x12345678, 5, 28, 4) == 0x52345678)
assert(bit32.replace(0x12345678, 0x87654321, 0, 32) == 0x87654321)
assert(bit32.replace(0, 1, 2) == 2^2)
assert(bit32.replace(0, -1, 4) == 2^4)
assert(bit32.replace(-1, 0, 31) == (1 << 31) - 1)
assert(bit32.replace(-1, 0, 1, 2) == (1 << 32) - 7)
-- testing conversion of floats
assert(bit32.bor(3.0) == 3)
assert(bit32.bor(-4.0) == 0xfffffffc)
-- large floats and large-enough integers?
if 2.0^50 < 2.0^50 + 1.0 and 2.0^50 < (-1 >> 1) then
assert(bit32.bor(2.0^32 - 5.0) == 0xfffffffb)
assert(bit32.bor(-2.0^32 - 6.0) == 0xfffffffa)
assert(bit32.bor(2.0^48 - 5.0) == 0xfffffffb)
assert(bit32.bor(-2.0^48 - 6.0) == 0xfffffffa)
end
print'OK'
-- $Id: calls.lua,v 1.60 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice in file all.lua
print("testing functions and calls")
local debug = require "debug"
-- get the opportunity to test 'type' too ;)
assert(type(1<2) == 'boolean')
assert(type(true) == 'boolean' and type(false) == 'boolean')
assert(type(nil) == 'nil'
and type(-3) == 'number'
and type'x' == 'string'
and type{} == 'table'
and type(type) == 'function')
assert(type(assert) == type(print))
function f (x) return a:x (x) end
assert(type(f) == 'function')
assert(not pcall(type))
do -- test error in 'print' too...
-- NodeMCU setting tostring to nil does work with ROM searchlist use numeric override instead
_ENV.tostring = 1
local st, msg = pcall(print, 1)
assert(st == false and string.find(msg, "attempt to call a number value"))
_ENV.tostring = function () return {} end
local st, msg = pcall(print, 1)
assert(st == false and string.find(msg, "must return a string"))
_ENV.tostring = nil
end
-- testing local-function recursion
fact = false
do
local res = 1
local function fact (n)
if n==0 then return res
else return n*fact(n-1)
end
end
assert(fact(5) == 120)
end
assert(fact == false)
-- testing declarations
a = {i = 10}
self = 20
function a:x (x) return x+self.i end
function a.y (x) return x+self end
assert(a:x(1)+10 == a.y(1))
a.t = {i=-100}
a["t"].x = function (self, a,b) return self.i+a+b end
assert(a.t:x(2,3) == -95)
do
local a = {x=0}
function a:add (x) self.x, a.y = self.x+x, 20; return self end
assert(a:add(10):add(20):add(30).x == 60 and a.y == 20)
end
local a = {b={c={}}}
function a.b.c.f1 (x) return x+1 end
function a.b.c:f2 (x,y) self[x] = y end
assert(a.b.c.f1(4) == 5)
a.b.c:f2('k', 12); assert(a.b.c.k == 12)
print('+')
t = nil -- 'declare' t
function f(a,b,c) local d = 'a'; t={a,b,c,d} end
f( -- this line change must be valid
1,2)
assert(t[1] == 1 and t[2] == 2 and t[3] == nil and t[4] == 'a')
f(1,2, -- this one too
3,4)
assert(t[1] == 1 and t[2] == 2 and t[3] == 3 and t[4] == 'a')
function fat(x)
if x <= 1 then return 1
else return x*load("return fat(" .. x-1 .. ")", "")()
end
end
assert(load "load 'assert(fat(6)==720)' () ")()
a = load('return fat(5), 3')
a,b = a()
assert(a == 120 and b == 3)
print('+')
function err_on_n (n)
if n==0 then error(); exit(1);
else err_on_n (n-1); exit(1);
end
end
do
function dummy (n)
if n > 0 then
assert(not pcall(err_on_n, n))
dummy(n-1)
end
end
end
dummy(10)
function deep (n)
if n>0 then deep(n-1) end
end
deep(10)
deep(200)
-- testing tail call
function deep (n) if n>0 then return deep(n-1) else return 101 end end
assert(deep(30000) == 101)
a = {}
function a:deep (n) if n>0 then return self:deep(n-1) else return 101 end end
assert(a:deep(30000) == 101)
print('+')
a = nil
(function (x) a=x end)(23)
assert(a == 23 and (function (x) return x*2 end)(20) == 40)
-- testing closures
-- fixed-point operator
Z = function (le)
local function a (f)
return le(function (x) return f(f)(x) end)
end
return a(a)
end
-- non-recursive factorial
F = function (f)
return function (n)
if n == 0 then return 1
else return n*f(n-1) end
end
end
fat = Z(F)
assert(fat(0) == 1 and fat(4) == 24 and Z(F)(5)==5*Z(F)(4))
local function g (z)
local function f (a,b,c,d)
return function (x,y) return a+b+c+d+a+x+y+z end
end
return f(z,z+1,z+2,z+3)
end
f = g(10)
assert(f(9, 16) == 10+11+12+13+10+9+16+10)
Z, F, f = nil
print('+')
-- testing multiple returns
function unlpack (t, i)
i = i or 1
if (i <= #t) then
return t[i], unlpack(t, i+1)
end
end
function equaltab (t1, t2)
assert(#t1 == #t2)
for i = 1, #t1 do
assert(t1[i] == t2[i])
end
end
local pack = function (...) return (table.pack(...)) end
function f() return 1,2,30,4 end
function ret2 (a,b) return a,b end
local a,b,c,d = unlpack{1,2,3}
assert(a==1 and b==2 and c==3 and d==nil)
a = {1,2,3,4,false,10,'alo',false,assert}
equaltab(pack(unlpack(a)), a)
equaltab(pack(unlpack(a), -1), {1,-1})
a,b,c,d = ret2(f()), ret2(f())
assert(a==1 and b==1 and c==2 and d==nil)
a,b,c,d = unlpack(pack(ret2(f()), ret2(f())))
assert(a==1 and b==1 and c==2 and d==nil)
a,b,c,d = unlpack(pack(ret2(f()), (ret2(f()))))
assert(a==1 and b==1 and c==nil and d==nil)
a = ret2{ unlpack{1,2,3}, unlpack{3,2,1}, unlpack{"a", "b"}}
assert(a[1] == 1 and a[2] == 3 and a[3] == "a" and a[4] == "b")
-- testing calls with 'incorrect' arguments
rawget({}, "x", 1)
rawset({}, "x", 1, 2)
assert(math.sin(1,2) == math.sin(1))
table.sort({10,9,8,4,19,23,0,0}, function (a,b) return a<b end, "extra arg")
-- test for generic load
local x = "-- a comment\0\0\0\n x = 10 + \n23; \
local a = function () x = 'hi' end; \
return '\0'"
function read1 (x)
local i = 0
return function ()
collectgarbage()
i=i+1
return string.sub(x, i, i)
end
end
function cannotload (msg, a,b)
assert(not a and string.find(b, msg))
end
a = assert(load(read1(x), "modname", "t", _G))
assert(a() == "\0" and _G.x == 33)
assert(debug.getinfo(a).source == "modname")
-- cannot read text in binary mode
cannotload("attempt to load a text chunk", load(read1(x), "modname", "b", {}))
cannotload("attempt to load a text chunk", load(x, "modname", "b"))
a = assert(load(function () return nil end))
a() -- empty chunk
assert(not load(function () return true end))
-- small bug
local t = {nil, "return ", "3"}
f, msg = load(function () return table.remove(t, 1) end)
assert(f() == nil) -- should read the empty chunk
-- another small bug (in 5.2.1)
f = load(string.dump(function () return 1 end), nil, "b", {})
assert(type(f) == "function" and f() == 1)
x = string.dump(load("x = 1; return x"))
a = assert(load(read1(x), nil, "b"))
assert(a() == 1 and _G.x == 1)
cannotload("attempt to load a binary chunk", load(read1(x), nil, "t"))
cannotload("attempt to load a binary chunk", load(x, nil, "t"))
assert(not pcall(string.dump, print)) -- no dump of C functions
cannotload("unexpected symbol", load(read1("*a = 123")))
cannotload("unexpected symbol", load("*a = 123"))
cannotload("hhi", load(function () error("hhi") end))
-- any value is valid for _ENV
assert(load("return _ENV", nil, nil, 123)() == 123)
-- load when _ENV is not first upvalue
local x; XX = 123
local function h ()
local y=x -- use 'x', so that it becomes 1st upvalue
return XX -- global name
end
local d = string.dump(h)
x = load(d, "", "b")
assert(debug.getupvalue(x, 2) == '_ENV')
debug.setupvalue(x, 2, _G)
assert(x() == 123)
assert(assert(load("return XX + ...", nil, nil, {XX = 13}))(4) == 17)
-- test generic load with nested functions
x = [[
return function (x)
return function (y)
return function (z)
return x+y+z
end
end
end
]]
a = assert(load(read1(x)))
assert(a()(2)(3)(10) == 15)
-- test for dump/undump with upvalues
local a, b = 20, 30
x = load(string.dump(function (x)
if x == "set" then a = 10+b; b = b+1 else
return a
end
end), "", "b", nil)
assert(x() == nil)
assert(debug.setupvalue(x, 1, "hi") == "a")
assert(x() == "hi")
assert(debug.setupvalue(x, 2, 13) == "b")
assert(not debug.setupvalue(x, 3, 10)) -- only 2 upvalues
x("set")
assert(x() == 23)
x("set")
assert(x() == 24)
-- test for dump/undump with many upvalues
do
local nup = 200 -- maximum number of local variables
local prog = {"local a1"}
for i = 2, nup do prog[#prog + 1] = ", a" .. i end
prog[#prog + 1] = " = 1"
for i = 2, nup do prog[#prog + 1] = ", " .. i end
local sum = 1
prog[#prog + 1] = "; return function () return a1"
for i = 2, nup do prog[#prog + 1] = " + a" .. i; sum = sum + i end
prog[#prog + 1] = " end"
prog = table.concat(prog)
local f = assert(load(prog))()
assert(f() == sum)
f = load(string.dump(f)) -- main chunk now has many upvalues
local a = 10
local h = function () return a end
for i = 1, nup do
debug.upvaluejoin(f, i, h, 1)
end
assert(f() == 10 * nup)
end
-- test for long method names
do
local t = {x = 1}
function t:_012345678901234567890123456789012345678901234567890123456789 ()
return self.x
end
assert(t:_012345678901234567890123456789012345678901234567890123456789() == 1)
end
-- test for bug in parameter adjustment
assert((function () return nil end)(4) == nil)
assert((function () local a; return a end)(4) == nil)
assert((function (a) return a end)() == nil)
--[==[ NodeMCU code formats are different
print("testing binary chunks")
do
local header = string.pack("c4BBc6BBBBBj",
"\27Lua", -- signature
5*16 + 3, -- version 5.3
10, -- format
"\x19\x93\r\n\x1a\n", -- data
string.packsize("i"), -- sizeof(int)
string.packsize("T"), -- sizeof(size_t)
4, -- size of instruction
string.packsize("j"), -- sizeof(lua integer)
string.packsize("n"), -- sizeof(lua number)
0x5678 -- LUAC_INT
-- LUAC_NUM may not have a unique binary representation (padding...)
)
local c = string.dump(function () local a = 1; local b = 3; return a+b*3 end)
assert(string.sub(c, 1, #header) == header)
-- corrupted header
for i = 1, #header do
local s = string.sub(c, 1, i - 1) ..
string.char(string.byte(string.sub(c, i, i)) + 1) ..
string.sub(c, i + 1, -1)
assert(#s == #c)
assert(not load(s))
end
-- loading truncated binary chunks
for i = 1, #c - 1 do
local st, msg = load(string.sub(c, 1, i))
assert(not st and string.find(msg, "truncated"))
end
assert(assert(load(c))() == 10)
end
]==]
print('OK')
return deep
-- $Id: closure.lua,v 1.59 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice in file all.lua
print "testing closures"
local A,B = 0,{g=10}
function f(x)
local a = {}
for i=1,1000 do
local y = 0
do
a[i] = function () B.g = B.g+1; y = y+x; return y+A end
end
end
local dummy = function () return a[A] end
collectgarbage()
A = 1; assert(dummy() == a[1]); A = 0;
assert(a[1]() == x)
assert(a[3]() == x)
collectgarbage()
assert(B.g == 12)
return a
end
local a = f(10)
-- force a GC in this level
local x = {[1] = {}} -- to detect a GC
setmetatable(x, {__mode = 'kv'})
while x[1] do -- repeat until GC
local a = A..A..A..A -- create garbage
A = A+1
end
assert(a[1]() == 20+A)
assert(a[1]() == 30+A)
assert(a[2]() == 10+A)
collectgarbage()
assert(a[2]() == 20+A)
assert(a[2]() == 30+A)
assert(a[3]() == 20+A)
assert(a[8]() == 10+A)
assert(getmetatable(x).__mode == 'kv')
assert(B.g == 19)
-- testing equality
a = {}
for i = 1, 5 do a[i] = function (x) return x + a + _ENV end end
--[[This relies on Proto caching which is not implemented for NodeMCU
assert(a[3] == a[4] and a[4] == a[5])
]]
for i = 1, 5 do a[i] = function (x) return i + a + _ENV end end
assert(a[3] ~= a[4] and a[4] ~= a[5])
local function f()
return function (x) return math.sin(_ENV[x]) end
end
--[[This relies on Proto caching which is not implemented for NodeMCU
assert(f() == f())
]]
-- testing closures with 'for' control variable
a = {}
for i=1,10 do
a[i] = {set = function(x) i=x end, get = function () return i end}
if i == 3 then break end
end
assert(a[4] == nil)
a[1].set(10)
assert(a[2].get() == 2)
a[2].set('a')
assert(a[3].get() == 3)
assert(a[2].get() == 'a')
a = {}
local t = {"a", "b"}
for i = 1, #t do
local k = t[i]
a[i] = {set = function(x, y) i=x; k=y end,
get = function () return i, k end}
if i == 2 then break end
end
a[1].set(10, 20)
local r,s = a[2].get()
assert(r == 2 and s == 'b')
r,s = a[1].get()
assert(r == 10 and s == 20)
a[2].set('a', 'b')
r,s = a[2].get()
assert(r == "a" and s == "b")
-- testing closures with 'for' control variable x break
for i=1,3 do
f = function () return i end
break
end
assert(f() == 1)
for k = 1, #t do
local v = t[k]
f = function () return k, v end
break
end
assert(({f()})[1] == 1)
assert(({f()})[2] == "a")
-- testing closure x break x return x errors
local b
function f(x)
local first = 1
while 1 do
if x == 3 and not first then return end
local a = 'xuxu'
b = function (op, y)
if op == 'set' then
a = x+y
else
return a
end
end
if x == 1 then do break end
elseif x == 2 then return
else if x ~= 3 then error() end
end
first = nil
end
end
for i=1,3 do
f(i)
assert(b('get') == 'xuxu')
b('set', 10); assert(b('get') == 10+i)
b = nil
end
pcall(f, 4);
assert(b('get') == 'xuxu')
b('set', 10); assert(b('get') == 14)
local w
-- testing multi-level closure
function f(x)
return function (y)
return function (z) return w+x+y+z end
end
end
y = f(10)
w = 1.345
assert(y(20)(30) == 60+w)
-- testing closures x repeat-until
local a = {}
local i = 1
repeat
local x = i
a[i] = function () i = x+1; return x end
until i > 10 or a[i]() ~= x
assert(i == 11 and a[1]() == 1 and a[3]() == 3 and i == 4)
-- testing closures created in 'then' and 'else' parts of 'if's
a = {}
for i = 1, 10 do
if i % 3 == 0 then
local y = 0
a[i] = function (x) local t = y; y = x; return t end
elseif i % 3 == 1 then
goto L1
error'not here'
::L1::
local y = 1
a[i] = function (x) local t = y; y = x; return t end
elseif i % 3 == 2 then
local t
goto l4
::l4a:: a[i] = t; goto l4b
error("should never be here!")
::l4::
local y = 2
t = function (x) local t = y; y = x; return t end
goto l4a
error("should never be here!")
::l4b::
end
end
for i = 1, 10 do
assert(a[i](i * 10) == i % 3 and a[i]() == i * 10)
end
print'+'
-- test for correctly closing upvalues in tail calls of vararg functions
local function t ()
local function c(a,b) assert(a=="test" and b=="OK") end
local function v(f, ...) c("test", f() ~= 1 and "FAILED" or "OK") end
local x = 1
return v(function() return x end)
end
t()
-- test for debug manipulation of upvalues
local debug = require'debug'
do
local a , b, c = 3, 5, 7
foo1 = function () return a+b end;
foo2 = function () return b+a end;
do
local a = 10
foo3 = function () return a+b end;
end
end
assert(debug.upvalueid(foo1, 1))
assert(debug.upvalueid(foo1, 2))
assert(not pcall(debug.upvalueid, foo1, 3))
assert(debug.upvalueid(foo1, 1) == debug.upvalueid(foo2, 2))
assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo2, 1))
assert(debug.upvalueid(foo3, 1))
assert(debug.upvalueid(foo1, 1) ~= debug.upvalueid(foo3, 1))
assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo3, 2))
assert(debug.upvalueid(string.gmatch("x", "x"), 1) ~= nil)
assert(foo1() == 3 + 5 and foo2() == 5 + 3)
debug.upvaluejoin(foo1, 2, foo2, 2)
assert(foo1() == 3 + 3 and foo2() == 5 + 3)
assert(foo3() == 10 + 5)
debug.upvaluejoin(foo3, 2, foo2, 1)
assert(foo3() == 10 + 5)
debug.upvaluejoin(foo3, 2, foo2, 2)
assert(foo3() == 10 + 3)
assert(not pcall(debug.upvaluejoin, foo1, 3, foo2, 1))
assert(not pcall(debug.upvaluejoin, foo1, 1, foo2, 3))
assert(not pcall(debug.upvaluejoin, foo1, 0, foo2, 1))
assert(not pcall(debug.upvaluejoin, print, 1, foo2, 1))
assert(not pcall(debug.upvaluejoin, {}, 1, foo2, 1))
assert(not pcall(debug.upvaluejoin, foo1, 1, print, 1))
print'OK'
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment