diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 67d652c1..1af37ff5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,10 +6,11 @@ jobs: build: strategy: + fail-fast: false matrix: - lua_ver: ['5.1'] - numbers: ['float','integral'] - target: ['esp32','esp32c3'] + lua_ver: ['5.1', '5.3'] + numbers: ['default', 'alternate'] + target: ['esp32', 'esp32s2', 'esp32s3', 'esp32c3'] runs-on: ubuntu-latest @@ -28,19 +29,27 @@ jobs: - name: Install dependencies run: ./install.sh shell: bash - - name: Build firmware (Lua 5.1) - if: ${{ matrix.lua_ver == '5.1' && matrix.numbers == 'float' }} + - name: Build firmware (default configuration) + if: ${{ matrix.numbers == 'default' }} run: | cp sdkconfig.defaults sdkconfig make IDF_TARGET=${{ matrix.target }} shell: bash - name: Build firmware (Lua 5.1, integer-only) - if: ${{ matrix.lua_ver == '5.1' && matrix.numbers == 'integral' }} + if: ${{ matrix.lua_ver == '5.1' && matrix.numbers == 'alternate' }} run: | cp sdkconfig.defaults sdkconfig echo CONFIG_LUA_NUMBER_INTEGRAL=y >> sdkconfig make IDF_TARGET=${{ matrix.target }} shell: bash + - name: Build firmware (Lua 5.3, 64bit int/double) + if: ${{ matrix.lua_ver == '5.3' && matrix.numbers == 'alternate' }} + run: | + cp sdkconfig.defaults sdkconfig + echo CONFIG_LUA_NUMBER_INT64=y >> sdkconfig + echo CONFIG_LUA_NUMBER_DOUBLE=y >> sdkconfig + make IDF_TARGET=${{ matrix.target }} + shell: bash - name: Upload luac.cross uses: actions/upload-artifact@v2 if: ${{ success() }} diff --git a/components/base_nodemcu/CMakeLists.txt b/components/base_nodemcu/CMakeLists.txt index ae355564..38febb76 100644 --- a/components/base_nodemcu/CMakeLists.txt +++ b/components/base_nodemcu/CMakeLists.txt @@ -1,15 +1,7 @@ idf_component_register( - SRCS "ip_fmt.c" "lextra.c" "linit.c" "lnodeaux.c" "uart.c" "user_main.c" + SRCS "ip_fmt.c" "user_main.c" INCLUDE_DIRS "include" REQUIRES "lua" PRIV_REQUIRES "nvs_flash" LDFRAGMENTS "nodemcu.lf" ) - -target_compile_options(${COMPONENT_LIB} PRIVATE -DCONFIG_NODEMCU_CMODULE_UART) -target_link_libraries(${COMPONENT_LIB} - "-u UART_module_selected1" - "-u lua_rotables_part_map" - "-Wl,-defsym=lua_rotables_map=_lua_rotables_map_start" - "-Wl,-defsym=lua_libs_map=_lua_libs_map_start" -) diff --git a/components/base_nodemcu/include/module.h b/components/base_nodemcu/include/module.h index 21791afb..d188f06a 100644 --- a/components/base_nodemcu/include/module.h +++ b/components/base_nodemcu/include/module.h @@ -1,8 +1,7 @@ #ifndef __MODULE_H__ #define __MODULE_H__ -#include "sdkconfig.h" -#include "lrotable.h" +#include "lnodemcu.h" /* Registering a module within NodeMCU is really easy these days! * @@ -18,11 +17,11 @@ * * Then simply put a line like this at the bottom of your module file: * - * NODEMCU_MODULE(MYNAME, "myname", myname_map, luaopen_myname); + * NODEMCU_MODULE(MYNAME, "myname", myname, luaopen_myname); * * or perhaps * - * NODEMCU_MODULE(MYNAME, "myname", myname_map, NULL); + * NODEMCU_MODULE(MYNAME, "myname", myname, NULL); * * if you don't need an init function. * @@ -36,23 +35,6 @@ #define MODULE_PASTE_(x,y) x##y #define MODULE_EXPAND_PASTE_(x,y) MODULE_PASTE_(x,y) -#ifdef LUA_CROSS_COMPILER -#ifdef _MSC_VER -//on msvc it is necessary to go through more pre-processor hoops to get the -//section name built; string merging does not happen in the _declspecs. -//NOTE: linker magic is invoked via the magical '$' character. Caveat editor. -#define __TOKIFY(s) .rodata1$##s -#define __TOTOK(s) __TOKIFY(s) -#define __STRINGIFY(x) #x -#define __TOSTRING(x) __STRINGIFY(x) -#define __ROSECNAME(s) __TOSTRING(__TOTOK(s)) -#define LOCK_IN_SECTION(s) __declspec ( allocate( __ROSECNAME(s) ) ) -#else -#define LOCK_IN_SECTION(s) __attribute__((used,unused,section(".rodata1." #s))) -#endif -#else -#define LOCK_IN_SECTION(s) __attribute__((used,unused,section(".lua_" #s))) -#endif /* For the ROM table, we name the variable according to ( | denotes concat): * cfgname | _module_selected | CONFIG_NODEMCU_CMODULE_##cfgname * where the CONFIG_NODEMCU_CMODULE_XYZ macro is first expanded to yield either @@ -65,10 +47,10 @@ */ #define NODEMCU_MODULE(cfgname, luaname, map, initfunc) \ const LOCK_IN_SECTION(libs) \ - luaR_entry MODULE_PASTE_(lua_lib_,cfgname) = { luaname, LRO_FUNCVAL(initfunc) }; \ + ROTable_entry MODULE_PASTE_(lua_lib_,cfgname) = { luaname, LRO_FUNCVAL(initfunc) }; \ const LOCK_IN_SECTION(rotable) \ - luaR_entry MODULE_EXPAND_PASTE_(cfgname,MODULE_EXPAND_PASTE_(_module_selected,MODULE_PASTE_(CONFIG_NODEMCU_CMODULE_,cfgname))) \ - = {luaname, LRO_ROVAL(map ## _map)} + ROTable_entry MODULE_EXPAND_PASTE_(cfgname,MODULE_EXPAND_PASTE_(_module_selected,MODULE_PASTE_(CONFIG_NODEMCU_CMODULE_,cfgname))) \ + = {luaname, LRO_ROVAL(map)} #endif @@ -89,6 +71,6 @@ // NODEMCU_MODULE_STD() defines the entry points for an external module: #define NODEMCU_MODULE_STD() \ static const LOCK_IN_SECTION(libs) \ - luaR_entry lua_lib_module = {MODNAME, LRO_FUNCVAL(module_init)}; \ - const LOCK_IN_SECTION(rotable) \ - luaR_entry MODULE_EXPAND_PASTE_(EXTMODNAME, _entry) = {MODNAME, LRO_ROVAL(module_map)}; + ROTable_entry lua_lib_module = {MODNAME, LRO_FUNCVAL(module_init)}; \ + const const LOCK_IN_SECTION(rotable) \ + ROTable_entry MODULE_EXPAND_PASTE_(EXTMODNAME, _entry) = {MODNAME, LRO_ROVAL(module_map)}; diff --git a/components/base_nodemcu/linit.c b/components/base_nodemcu/linit.c deleted file mode 100644 index 1149467e..00000000 --- a/components/base_nodemcu/linit.c +++ /dev/null @@ -1,167 +0,0 @@ -/* -** $Id: linit.c,v 1.14.1.1 2007/12/27 13:02:25 roberto Exp $ -** Initialization of libraries for lua.c -** See Copyright Notice in lua.h -*/ - - -#define linit_c -#define LUA_LIB -#define LUAC_CROSS_FILE - -#include "lua.h" - -#include "lualib.h" -#include "lauxlib.h" -#include "luaconf.h" -#include "module.h" -#include "lstate.h" -#include "lrotable.h" -#include -#include - -LROT_EXTERN(strlib); -LROT_EXTERN(tab_funcs); -LROT_EXTERN(dblib); -LROT_EXTERN(co_funcs); -LROT_EXTERN(math); -#if defined(LUA_CROSS_COMPILER) -LROT_EXTERN(oslib); -//LROT_EXTERN(iolib); -#endif -/* - * The NodeMCU Lua initalisation has been adapted to use linker-based module - * registration. This uses a PSECT naming convention to allow the ROTable and - * initialisation function entries to be collected by the linker into two - * consoliated ROTables. This significantly simplifies adding new modules and - * configuring builds with a small subset of the total modules. - * - * This linker-based approach is not practical for cross compiler builds which - * must link on a range of platforms, and where we don't have control of PSECT - * placement. However unlike the target builds, the luac.cross builds only - * used a small and fixed list of libraries and so in this case the table can - * be defined in this source file, so in this case all library ROTables are - * defined here, avoiding the need for linker magic is avoided on host builds. - * - * Note that a separate ROTable is defined in lbaselib.c for the base functions - * and there is a metatable index cascade from _G to this base function table to - * the master rotables table. In the target build, the linker marshals the - * table, hence the LROT_BREAK() macros which don't 0 terminate the lists. - */ - -#ifdef _MSC_VER -//MSVC requires us to declare these sections before we refer to them -#pragma section(__ROSECNAME(A), read) -#pragma section(__ROSECNAME(zzzzzzzz), read) -#pragma section(__ROSECNAME(libs), read) -#pragma section(__ROSECNAME(rotable), read) -//These help us to find the beginning and ending of the RO data. NOTE: linker -//magic is used; the section names are lexically sorted, so 'a' and 'z' are -//important to keep the other sections lexically between these two dummy -//variables. Check your mapfile output if you need to fiddle with this stuff. -const LOCK_IN_SECTION(A) char _ro_start[1] = {0}; -const LOCK_IN_SECTION(zzzzzzzz) char _ro_end[1] = {0}; -#endif - -#if defined(LUA_CROSS_COMPILER) - -LROT_PUBLIC_BEGIN(LOCK_IN_SECTION(rotable) lua_rotables) - LROT_TABENTRY( string, strlib ) - LROT_TABENTRY( table, tab_funcs ) - LROT_TABENTRY( coroutine, co_funcs ) - LROT_TABENTRY( debug, dblib) - LROT_TABENTRY( math, math ) - LROT_TABENTRY( ROM, lua_rotables ) - LROT_TABENTRY( os, oslib ) - //LROT_TABENTRY( io, iolib ) -LROT_END(lua_rotables, NULL, 0) - -#else - -// Due to limitations in the IDF linker fragment generation, we have to -// play with link-time symbol generation/aliasing to set up the rotables -// properly. As part of that, we need to use a different name for the -// table here. - -LROT_PUBLIC_BEGIN(LOCK_IN_SECTION(rotable) lua_rotables_part) -#ifdef CONFIG_LUA_BUILTIN_STRING - LROT_TABENTRY( string, strlib ) -#endif -#ifdef CONFIG_LUA_BUILTIN_TABLE - LROT_TABENTRY( table, tab_funcs ) -#endif -#ifdef CONFIG_LUA_BUILTIN_COROUTINE - LROT_TABENTRY( coroutine, co_funcs ) -#endif -#ifdef CONFIG_LUA_BUILTIN_DEBUG - LROT_TABENTRY( debug, dblib) -#endif -#ifdef CONFIG_LUA_BUILTIN_MATH - LROT_TABENTRY( math, math ) -#endif - LROT_TABENTRY( ROM, lua_rotables_part ) -LROT_BREAK(lua_rotables_part) - -#endif - - -LROT_PUBLIC_BEGIN(LOCK_IN_SECTION(libs) lua_libs) - LROT_FUNCENTRY( _, luaopen_base ) - LROT_FUNCENTRY( package, luaopen_package ) -#ifdef CONFIG_LUA_BUILTIN_STRING - LROT_FUNCENTRY( string, luaopen_string ) -#endif -#ifdef CONFIG_LUA_BUILTIN_TABLE - LROT_FUNCENTRY( table, luaopen_table ) -#endif -#ifdef CONFIG_LUA_BUILTIN_DEBUG - LROT_FUNCENTRY( debug, luaopen_debug ) -#endif -#ifndef LUA_CROSS_COMPILER -LROT_BREAK(lua_libs) -#else - LROT_FUNCENTRY( io, luaopen_io ) -LROT_END( lua_libs, NULL, 0) -#endif - -#ifndef LUA_CROSS_COMPILER -extern void luaL_dbgbreak(void); -#endif - -/* Historically the linker script took care of zero terminating both the - * lua_libs and lua_rotable arrays, but the IDF currently does not - * support injecting LONG(0) entries. To compensate, we have explicit - * end markers here which the linker fragment then place appropriately - * to terminate aforementioned arrays. - */ -const luaR_entry LOCK_IN_SECTION(libs_end_marker) libs_end_marker= { 0, }; -const luaR_entry LOCK_IN_SECTION(rotable_end_marker) rotable_end_marker = { 0, }; - -void luaL_openlibs (lua_State *L) { - lua_pushrotable(L, LROT_TABLEREF(lua_libs)); - lua_pushnil(L); /* first key */ - /* loop round and open libraries */ -#ifndef LUA_CROSS_COMPILER -// luaL_dbgbreak(); // This is a test point for debugging library start ups -#endif - while (lua_next(L, -2) != 0) { - if (lua_islightfunction(L,-1) && - fvalue(L->top-1)) { // only process function entries - lua_pushvalue(L, -2); - lua_call(L, 1, 0); // call luaopen_XXX(libname) - } else { - lua_pop(L, 1); - } - } - lua_pop(L, 1); //cleanup stack -} - -#ifndef LUA_CROSS_COMPILER -# ifdef LUA_NUMBER_INTEGRAL -# define COMPARE <= -# else -# define COMPARE == -# endif -_Static_assert(_Alignof(luaR_entry) COMPARE 8, "Unexpected alignment of module registration - update the linker script snippets to match!"); -_Static_assert(sizeof(luaR_entry) COMPARE 24, "Unexpect size of array member - update the linker script snippets to match!"); -#endif diff --git a/components/base_nodemcu/nodemcu.lf b/components/base_nodemcu/nodemcu.lf index 1756aa32..9b399ada 100644 --- a/components/base_nodemcu/nodemcu.lf +++ b/components/base_nodemcu/nodemcu.lf @@ -1,41 +1,17 @@ -[sections:lua_libs] -entries: - .lua_libs - -[sections:lua_libs_end_marker] -entries: - .lua_libs_end_marker - -[sections:lua_rotable] -entries: - .lua_rotable - -[sections:lua_rotable_end_marker] -entries: - .lua_rotable_end_marker - [sections:lua_esp_event_cb_table] entries: .lua_esp_event_cb_table [scheme:nodemcu_arrays] entries: - lua_libs -> flash_rodata - lua_libs_end_marker -> flash_rodata - lua_rotable -> flash_rodata - lua_rotable_end_marker -> flash_rodata lua_esp_event_cb_table -> flash_rodata # Important: don't change the alignments below without also updating the -# _Static_assert over in linit.c and/or nodemcu_esp_event.h! +# _Static_assert over in nodemcu_esp_event.h! [mapping:nodemcu] archive: * entries: * (nodemcu_arrays); - lua_libs -> flash_rodata KEEP() ALIGN(8) SURROUND(lua_libs_map), - lua_libs_end_marker -> flash_rodata KEEP(), - lua_rotable -> flash_rodata ALIGN(8) SURROUND(lua_rotables_map), - lua_rotable_end_marker -> flash_rodata KEEP(), lua_esp_event_cb_table -> flash_rodata KEEP() ALIGN(4) SURROUND(esp_event_cb_table) diff --git a/components/base_nodemcu/user_main.c b/components/base_nodemcu/user_main.c index 96cc6058..565c3537 100644 --- a/components/base_nodemcu/user_main.c +++ b/components/base_nodemcu/user_main.c @@ -9,6 +9,7 @@ * 2014/1/1, v1.0 create this file. *******************************************************************************/ #include "lua.h" +#include "linput.h" #include "platform.h" #include #include @@ -19,7 +20,6 @@ #include "nvs_flash.h" #include "flash_api.h" -#include "driver/console.h" #include "task/task.h" #include "sections.h" #include "nodemcu_esp_event.h" @@ -93,24 +93,9 @@ static void handle_default_loop_event(task_param_t param, task_prio_t prio) // +================== New task interface ==================+ static void start_lua () { - char* lua_argv[] = { (char *)"lua", (char *)"-i", NULL }; NODE_DBG("Task task_lua started.\n"); - lua_main( 2, lua_argv ); -} - -static void handle_input(task_param_t flag, task_prio_t priority) { - (void)priority; - lua_handle_input (flag); -} - -static task_handle_t input_task; - -task_handle_t user_get_input_sig(void) { - return input_task; -} - -bool user_process_input(bool force) { - return task_post_low(input_task, force); + if (lua_main()) // If it returns true then LFS restart is needed + lua_main(); } void nodemcu_init(void) @@ -144,8 +129,6 @@ void __attribute__((noreturn)) app_main(void) { task_init(); - input_task = task_get_id (handle_input); - relayed_event_handled = xSemaphoreCreateBinary(); relayed_event_task = task_get_id(handle_default_loop_event); @@ -156,19 +139,7 @@ void __attribute__((noreturn)) app_main(void) relay_default_loop_events, NULL); - ConsoleSetup_t cfg; - cfg.bit_rate = CONFIG_NODEMCU_CONSOLE_BIT_RATE; - cfg.data_bits = CONSOLE_NUM_BITS_8; - cfg.parity = CONSOLE_PARITY_NONE; - cfg.stop_bits = CONSOLE_STOP_BITS_1; - cfg.auto_baud = -#ifdef CONFIG_NODEMCU_CONSOLE_BIT_RATE_AUTO - true; -#else - false; -#endif - - console_init (&cfg, input_task); + platform_uart_start(CONFIG_ESP_CONSOLE_UART_NUM); setvbuf(stdout, NULL, _IONBF, 0); nodemcu_init (); diff --git a/components/driver_can/CMakeLists.txt b/components/driver_can/CMakeLists.txt index 520c9f1c..44bde7b9 100644 --- a/components/driver_can/CMakeLists.txt +++ b/components/driver_can/CMakeLists.txt @@ -1,4 +1,4 @@ -if(NOT "${IDF_TARGET}" STREQUAL "esp32c3") +if(IDF_TARGET STREQUAL "esp32") idf_component_register( SRCS "CAN.c" diff --git a/components/driver_console/CMakeLists.txt b/components/driver_console/CMakeLists.txt deleted file mode 100644 index b412cdeb..00000000 --- a/components/driver_console/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -idf_component_register( - SRCS "console.c" - INCLUDE_DIRS "include" - REQUIRES "task" "esp32" -) diff --git a/components/driver_console/console.c b/components/driver_console/console.c deleted file mode 100644 index 1fc015bb..00000000 --- a/components/driver_console/console.c +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright 2016 Dius Computing Pty Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - Neither the name of the copyright holders nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - * @author Johny Mattsson - */ - -#include "driver/console.h" -#include "driver/uart.h" -#include "esp_intr_alloc.h" -#include "soc/soc.h" -#include "soc/uart_reg.h" -#include "freertos/FreeRTOS.h" -#include "freertos/queue.h" -#include "sys/reent.h" -#include - -#include "rom/libc_stubs.h" -#include "rom/uart.h" - -#define UART_INPUT_QUEUE_SZ 0x100 - -// These used to be available in soc/uart_register.h: -#define UART_GET_RXFIFO_RD_BYTE(i) GET_PERI_REG_BITS2(UART_FIFO_REG(i) , UART_RXFIFO_RD_BYTE_V, UART_RXFIFO_RD_BYTE_S) -#define UART_GET_RXFIFO_CNT(i) GET_PERI_REG_BITS2(UART_STATUS_REG(i) , UART_RXFIFO_CNT_V, UART_RXFIFO_CNT_S) -#define UART_SET_AUTOBAUD_EN(i,val) SET_PERI_REG_BITS(UART_AUTOBAUD_REG(i) ,UART_AUTOBAUD_EN_V,(val),UART_AUTOBAUD_EN_S) - - -typedef int (*_read_r_fn) (struct _reent *r, int fd, void *buf, int size); - -static _read_r_fn _read_r_app; -#if !defined(CONFIG_IDF_TARGET_ESP32C3) -static _read_r_fn _read_r_pro; -#endif - -static xQueueHandle uart0Q; -static task_handle_t input_task = 0; - -// --- Syscall support for reading from STDIN_FILENO --------------- - -static int console_read_r (struct _reent *r, int fd, void *buf, int size, _read_r_fn next) -{ - if (fd == STDIN_FILENO) - { - static _lock_t stdin_lock; - _lock_acquire_recursive (&stdin_lock); - char *c = (char *)buf; - int i = 0; - for (; i < size; ++i) - { - if (!console_getc (c++)) - break; - } - _lock_release_recursive (&stdin_lock); - return i; - } - else if (next) - return next (r, fd, buf, size); - else - return -1; -} - -#if !defined(CONFIG_IDF_TARGET_ESP32C3) -static int console_read_r_pro (struct _reent *r, int fd, void *buf, int size) -{ - return console_read_r (r, fd, buf, size, _read_r_pro); -} -#endif -static int console_read_r_app (struct _reent *r, int fd, void *buf, int size) -{ - return console_read_r (r, fd, buf, size, _read_r_app); -} - -// --- End syscall support ------------------------------------------- - -static void uart0_rx_intr_handler (void *arg) -{ - (void)arg; - bool received = false; - uint32_t status = READ_PERI_REG(UART_INT_ST_REG(CONSOLE_UART)); - while (status) - { - if (status & UART_FRM_ERR_INT_ENA) - { - // TODO: report somehow? - WRITE_PERI_REG(UART_INT_CLR_REG(CONSOLE_UART), UART_FRM_ERR_INT_ENA); - } - if ((status & UART_RXFIFO_TOUT_INT_ENA) || - (status & UART_RXFIFO_FULL_INT_ENA)) - { - uint32_t fifo_len = UART_GET_RXFIFO_CNT(CONSOLE_UART); - for (uint32_t i = 0; i < fifo_len; ++i) - { - received = true; - char c = UART_GET_RXFIFO_RD_BYTE(CONSOLE_UART); - if (uart0Q) - xQueueSendToBackFromISR (uart0Q, &c, NULL); - } - WRITE_PERI_REG(UART_INT_CLR_REG(CONSOLE_UART), - UART_RXFIFO_TOUT_INT_ENA | UART_RXFIFO_FULL_INT_ENA); - } - status = READ_PERI_REG(UART_INT_ST_REG(CONSOLE_UART)); - } - if (received && input_task) - task_post_isr_low (input_task, false); -} - - -void console_setup (const ConsoleSetup_t *cfg) -{ - esp_rom_uart_tx_wait_idle (CONSOLE_UART); - - uart_config_t uart_conf = { - .baud_rate = cfg->bit_rate, - .data_bits = - cfg->data_bits == CONSOLE_NUM_BITS_5 ? UART_DATA_5_BITS : - cfg->data_bits == CONSOLE_NUM_BITS_6 ? UART_DATA_6_BITS : - cfg->data_bits == CONSOLE_NUM_BITS_7 ? UART_DATA_7_BITS : - UART_DATA_8_BITS, - .stop_bits = - cfg->stop_bits == CONSOLE_STOP_BITS_1 ? UART_STOP_BITS_1 : - cfg->stop_bits == CONSOLE_STOP_BITS_2 ? UART_STOP_BITS_2 : - UART_STOP_BITS_1_5, - .parity = - cfg->parity == CONSOLE_PARITY_NONE ? UART_PARITY_DISABLE : - cfg->parity == CONSOLE_PARITY_EVEN ? UART_PARITY_EVEN : - UART_PARITY_ODD, - .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, - }; - uart_param_config(CONSOLE_UART, &uart_conf); - -#if !defined(CONFIG_IDF_TARGET_ESP32C3) - // TODO: Make this actually work - UART_SET_AUTOBAUD_EN(CONSOLE_UART, cfg->auto_baud); -#endif -} - - - -void console_init (const ConsoleSetup_t *cfg, task_handle_t tsk) -{ - input_task = tsk; - uart0Q = xQueueCreate (UART_INPUT_QUEUE_SZ, sizeof (char)); - - console_setup (cfg); - - uart_isr_register(CONSOLE_UART, uart0_rx_intr_handler, NULL, 0, NULL); - uart_set_rx_timeout(CONSOLE_UART, 2); - uart_set_rx_full_threshold(CONSOLE_UART, 10); - uart_enable_intr_mask(CONSOLE_UART, - UART_RXFIFO_TOUT_INT_ENA_M | - UART_RXFIFO_FULL_INT_ENA_M | - UART_FRM_ERR_INT_ENA_M); - - // Register our console_read_r_xxx functions to support stdin input -#if defined(CONFIG_IDF_TARGET_ESP32C3) - _read_r_app = syscall_table_ptr->_read_r; - syscall_table_ptr->_read_r = console_read_r_app; -#else - _read_r_app = syscall_table_ptr_app->_read_r; - _read_r_pro = syscall_table_ptr_pro->_read_r; - syscall_table_ptr_app->_read_r = console_read_r_app; - syscall_table_ptr_pro->_read_r = console_read_r_pro; -#endif -} - - -bool console_getc (char *c) -{ - return (uart0Q && (xQueueReceive (uart0Q, c, 0) == pdTRUE)); -} diff --git a/components/driver_console/include/driver/console.h b/components/driver_console/include/driver/console.h deleted file mode 100644 index 25fb747d..00000000 --- a/components/driver_console/include/driver/console.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2016 Dius Computing Pty Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - Neither the name of the copyright holders nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - * @author Johny Mattsson - */ - -#include "esp_rom_uart.h" -#include "task/task.h" -#include -#include - -#define CONSOLE_UART CONFIG_ESP_CONSOLE_UART_NUM - -typedef enum -{ - CONSOLE_NUM_BITS_5 = 0x0, - CONSOLE_NUM_BITS_6 = 0x1, - CONSOLE_NUM_BITS_7 = 0x2, - CONSOLE_NUM_BITS_8 = 0x3 -} ConsoleNumBits_t; - -typedef enum -{ - CONSOLE_PARITY_NONE = 0x2, - CONSOLE_PARITY_ODD = 0x1, - CONSOLE_PARITY_EVEN = 0x0 -} ConsoleParity_t; - -typedef enum -{ - CONSOLE_STOP_BITS_1 = 0x1, - CONSOLE_STOP_BITS_1_5 = 0x2, - CONSOLE_STOP_BITS_2 = 0x3 -} ConsoleStopBits_t; - -typedef struct -{ - uint32_t bit_rate; - ConsoleNumBits_t data_bits; - ConsoleParity_t parity; - ConsoleStopBits_t stop_bits; - bool auto_baud; -} ConsoleSetup_t; - -void console_init (const ConsoleSetup_t *cfg, task_handle_t tsk); -void console_setup (const ConsoleSetup_t *cfg); -bool console_getc (char *c); diff --git a/components/lua/CMakeLists.txt b/components/lua/CMakeLists.txt index 63ef1982..b98e8586 100644 --- a/components/lua/CMakeLists.txt +++ b/components/lua/CMakeLists.txt @@ -1,10 +1,117 @@ -idf_component_register( - SRCS "lapi.c" "lauxlib.c" "lbaselib.c" "lcode.c" "ldblib.c" "ldebug.c" - "ldo.c" "ldump.c" "legc.c" "lflash.c" "lfunc.c" "lgc.c" "llex.c" "lmathlib.c" - "lmem.c" "loadlib.c" "lobject.c" "lopcodes.c" "lparser.c" "lrotable.c" - "lstate.c" "lstring.c" "lstrlib.c" "ltable.c" "ltablib.c" "ltm.c" - "lua.c" "lundump.c" "lvm.c" "lzio.c" - INCLUDE_DIRS "." - REQUIRES "platform" "uzlib" "driver_console" - PRIV_REQUIRES "base_nodemcu" "embedded_lfs" +if(CONFIG_LUA_VERSION_51) + set(srcs + "lua-5.1/lapi.c" + "lua-5.1/lauxlib.c" + "lua-5.1/lbaselib.c" + "lua-5.1/lcode.c" + "lua-5.1/ldblib.c" + "lua-5.1/ldebug.c" + "lua-5.1/ldo.c" + "lua-5.1/ldump.c" + "lua-5.1/lflash.c" + "lua-5.1/lfunc.c" + "lua-5.1/lgc.c" + "lua-5.1/llex.c" + "lua-5.1/lmathlib.c" + "lua-5.1/lmem.c" + "lua-5.1/lnodemcu.c" + "lua-5.1/loadlib.c" + "lua-5.1/lobject.c" + "lua-5.1/lopcodes.c" + "lua-5.1/lparser.c" + "lua-5.1/lstate.c" + "lua-5.1/lstring.c" + "lua-5.1/lstrlib.c" + "lua-5.1/ltable.c" + "lua-5.1/ltablib.c" + "lua-5.1/ltm.c" + "lua-5.1/lua.c" + "lua-5.1/lundump.c" + "lua-5.1/lvm.c" + "lua-5.1/lzio.c" + ) + set(luadir "lua-5.1") +elseif(CONFIG_LUA_VERSION_53) + set(srcs + "lua-5.3/lapi.c" + "lua-5.3/lauxlib.c" + "lua-5.3/lbaselib.c" + "lua-5.3/lbitlib.c" + "lua-5.3/lcode.c" + "lua-5.3/lcorolib.c" + "lua-5.3/lctype.c" + "lua-5.3/ldblib.c" + "lua-5.3/ldebug.c" + "lua-5.3/ldo.c" + "lua-5.3/ldump.c" + "lua-5.3/lfunc.c" + "lua-5.3/lgc.c" + "lua-5.3/llex.c" + "lua-5.3/lmathlib.c" + "lua-5.3/lmem.c" + "lua-5.3/lnodemcu.c" + "lua-5.3/loadlib.c" + "lua-5.3/lobject.c" + "lua-5.3/lopcodes.c" + "lua-5.3/lparser.c" + "lua-5.3/lstate.c" + "lua-5.3/lstring.c" + "lua-5.3/lstrlib.c" + "lua-5.3/ltable.c" + "lua-5.3/ltablib.c" + "lua-5.3/ltm.c" + "lua-5.3/lua.c" + "lua-5.3/lundump.c" + "lua-5.3/lutf8lib.c" + "lua-5.3/lvm.c" + "lua-5.3/lzio.c" + ) + set(luadir "lua-5.3") +endif() + +set(common_srcs + "common/lextra.c" + "common/lfs.c" + "common/linput.c" + "common/linit.c" + "common/lnodeaux.c" + "common/lpanic.c" ) + +idf_component_register( + SRCS ${srcs} ${common_srcs} + INCLUDE_DIRS ${luadir} "common" + REQUIRES "platform" "nvs_flash" "uzlib" + PRIV_REQUIRES "base_nodemcu" "embedded_lfs" + LDFRAGMENTS "link_lua.lf" +) + +# +# Cross compiler targets +# + +# Not sure why we can't directly depend on ${SDKCONFIG_HEADER} in our +# externalproject_add(), but them's the brakes... + +set(luac_build_dir "${BUILD_DIR}/luac_cross") + +add_custom_command( + OUTPUT sdkconfig.h + COMMAND mkdir -p "${luac_build_dir}" && cp ${SDKCONFIG_HEADER} ${luac_build_dir}/sdkconfig.h + DEPENDS ${SDKCONFIG_HEADER} + VERBATIM +) +add_custom_target(sdkconfig_h DEPENDS sdkconfig.h) + +externalproject_add(luac_cross_build + PREFIX ${luac_build_dir} + SOURCE_DIR ${COMPONENT_DIR}/${luadir}/host + CONFIGURE_COMMAND "" + BUILD_COMMAND make -f ${COMPONENT_DIR}/${luadir}/host/idf.mk LUAC_BUILD_DIR=${luac_build_dir} LUA_PATH=${COMPONENT_DIR}/${luadir} PYTHON=${PYTHON} + INSTALL_COMMAND "" + BUILD_ALWAYS 1 + DEPENDS sdkconfig_h +) + +set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES + "${BUILD_DIR}/luac_cross/luac.cross;${BUILD_DIR}/luac_cross/${luadir}" ) diff --git a/components/lua/Kconfig b/components/lua/Kconfig index 1082417a..8cb8d9dd 100644 --- a/components/lua/Kconfig +++ b/components/lua/Kconfig @@ -1,12 +1,46 @@ menu "Lua configuration" + choice LUA_VERSION + prompt "Lua version" + default LUA_VERSION_51 + help + The version of Lua interpreter to use. + + config LUA_VERSION_51 + bool "Lua 5.1" + + config LUA_VERSION_53 + bool "Lua 5.3" + + endchoice + config LUA_NUMBER_INTEGRAL + depends on LUA_VERSION_51 bool "Integer-only build" default "n" help Build Lua without support for floating point numbers. Not generally recommended, but can save on code size. + config LUA_NUMBER_INT64 + depends on LUA_VERSION_53 + bool "Use 64bit integers" + default "n" + help + Build Lua with 64bit integers. This provides a greater value + range, but at the expense of extra memory usage and somewhat + reduced performance over the default 32bit integers. + + config LUA_NUMBER_DOUBLE + depends on LUA_VERSION_53 + bool "Use double precision floating point" + default "n" + help + Build Lua with double floating point precision. This provides + a greater value range, but at the expense of extra memory + usage and somewhat reduced performance over the default + single precision floating point. + menu "Core Lua modules" config LUA_BUILTIN_STRING @@ -33,6 +67,13 @@ menu "Lua configuration" help Includes the math module (recommended). + config LUA_BUILTIN_UTF8 + depends on !LUA_VERSION_51 + bool "UTF8 module" + default "y" + help + Includes the debug module (required by our Lua VM). + config LUA_BUILTIN_DEBUG bool "Debug module" default "n" @@ -78,4 +119,11 @@ menu "Lua configuration" endmenu + config LUA_REQUIRED_MODULES + bool + default y + select NODEMCU_CMODULE_PIPE + select NODEMCU_CMODULE_UART + select LUA_BUILTIN_DEBUG + endmenu diff --git a/components/base_nodemcu/lextra.c b/components/lua/common/lextra.c similarity index 100% rename from components/base_nodemcu/lextra.c rename to components/lua/common/lextra.c diff --git a/components/base_nodemcu/include/lextra.h b/components/lua/common/lextra.h similarity index 100% rename from components/base_nodemcu/include/lextra.h rename to components/lua/common/lextra.h diff --git a/components/lua/common/lfs.c b/components/lua/common/lfs.c new file mode 100644 index 00000000..847cb8bf --- /dev/null +++ b/components/lua/common/lfs.c @@ -0,0 +1,103 @@ +#include "lfs.h" + +#include "esp_partition.h" +#include "nvs_flash.h" +#include "platform.h" + +#if defined(CONFIG_NODEMCU_EMBEDDED_LFS_SIZE) +// Symbol provided by embedded_lfs component +extern const char lua_flash_store_reserved[0]; +#endif + + +bool lfs_get_location(lfs_location_info_t *out) +{ +#if defined(CONFIG_NODEMCU_EMBEDDED_LFS_SIZE) + out->size = CONFIG_NODEMCU_EMBEDDED_LFS_SIZE; + out->addr_mem = lua_flash_store_reserved; + out->addr_phys = spi_flash_cache2phys(lua_flash_store_reserved); + if (out->addr_phys == SPI_FLASH_CACHE2PHYS_FAIL) { + NODE_ERR("spi_flash_cache2phys failed\n"); + return false; + } + else + return true; +#else + const esp_partition_t *part = esp_partition_find_first( + PLATFORM_PARTITION_TYPE_NODEMCU, + PLATFORM_PARTITION_SUBTYPE_NODEMCU_LFS, + NULL); + if (!part) + return false; // Nothing to do if no LFS partition available + + out->size = part->size; // in bytes + out->addr_mem = spi_flash_phys2cache(out->addr_phys, SPI_FLASH_MMAP_DATA); + out->addr_phys = part->address; + if (!out->addr_mem) { // not already mmap'd, have to do it ourselves + spi_flash_mmap_handle_t ignored; + esp_err_t err = spi_flash_mmap( + out->addr_phys, out->size, SPI_FLASH_MMAP_DATA, &out->addr_mem, &ignored); + if (err != ESP_OK) { + NODE_ERR("Unable to access LFS partition - is it 64kB aligned as it needs to be?\n"); + return false; + } + } + return true; +#endif +} + +#define LFS_LOAD_NS "lfsload" +#define LFS_LOAD_FILE_KEY "filename" + +bool lfs_get_load_filename(char *buf, size_t bufsiz) +{ + bool res = false; + nvs_handle_t handle; + esp_err_t err = nvs_open(LFS_LOAD_NS, NVS_READONLY, &handle); + if (err != ESP_OK) + goto out; + err = nvs_get_str(handle, LFS_LOAD_FILE_KEY, buf, &bufsiz); + if (err != ESP_OK) + goto close_out; + res = true; +close_out: + nvs_close(handle); +out: + return res; +} + + +bool lfs_set_load_filename(const char *fname) +{ + bool res = false; + nvs_handle_t handle; + esp_err_t err = nvs_open(LFS_LOAD_NS, NVS_READWRITE, &handle); + if (err != ESP_OK) + goto out; + err = nvs_set_str(handle, LFS_LOAD_FILE_KEY, fname); + if (err != ESP_OK) + goto close_out; + res = true; +close_out: + nvs_close(handle); +out: + return res; +} + + +bool lfs_clear_load_filename(void) +{ + bool res = false; + nvs_handle_t handle; + esp_err_t err = nvs_open(LFS_LOAD_NS, NVS_READWRITE, &handle); + if (err != ESP_OK) + goto out; + err = nvs_erase_key(handle, LFS_LOAD_FILE_KEY); + if (err != ESP_OK) + goto close_out; + res = true; +close_out: + nvs_close(handle); +out: + return res; +} diff --git a/components/lua/common/lfs.h b/components/lua/common/lfs.h new file mode 100644 index 00000000..4c55c708 --- /dev/null +++ b/components/lua/common/lfs.h @@ -0,0 +1,21 @@ +#ifndef _LFS_H_ +#define _LFS_H_ + +#include +#include +#include + +typedef struct { + uint32_t size; + uint32_t addr_phys; // physical address in flash + const void *addr_mem; // memory mapped address +} lfs_location_info_t; + +bool lfs_get_location(lfs_location_info_t *out); + +// Setting & getting of filename during reboot/load cycle +bool lfs_get_load_filename(char *buf, size_t bufsiz); +bool lfs_set_load_filename(const char *fname); +bool lfs_clear_load_filename(void); + +#endif diff --git a/components/lua/common/linit.c b/components/lua/common/linit.c new file mode 100644 index 00000000..0e063f60 --- /dev/null +++ b/components/lua/common/linit.c @@ -0,0 +1,170 @@ +/* +** $Id: linit.c,v 1.14.1.1 2007/12/27 13:02:25 roberto Exp $ +** Initialization of libraries for lua.c +** See Copyright Notice in lua.h +*/ + + +#define linit_c +#define LUA_LIB +#define LUA_CORE + +/* +** NodeMCU uses RO segment based static ROTable declarations for all library +** tables, including the index of library tables itself (the ROM table). These +** tables can be moved from RAM to flash ROM on the ESPs. +** +** On the ESPs targets, we can marshal the table entries through linker-based +** PSECTs to enable the library initiation tables to be bound during the link +** process rather than being statically declared here. This simplifies the +** addition of new modules and configuring builds with a subset of the total +** modules available. +** +** Such a linker-based approach is not practical for cross compiler builds that +** must link on a range of platforms, and where we don't have control of PSECT +** placement. However unlike the target builds, the luac.cross builds only +** use a small and fixed list of libraries and so in this case all of libraries +** are defined here, avoiding the need for linker magic on host builds. +** +** Note that a separate ROTable is defined in lbaselib.c on luac.cross builds +** for the base functions. (These use linker based entries on target builds) +** and there is a metatable index cascade from _G to this base function table +** to the master rotables table. In the target build, the linker marshals the +** table, hence the LROT_BREAK() macros which don't 0 terminate the lists and +** skip generating the ROtable header. + */ +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" +#include "lstate.h" +#include "lnodemcu.h" +#if LUA_VERSION_NUM == 501 +#include "lflash.h" +#endif + +extern LROT_TABLE(strlib); +extern LROT_TABLE(tab_funcs); +extern LROT_TABLE(dblib); +extern LROT_TABLE(co_funcs); +extern LROT_TABLE(mathlib); +extern LROT_TABLE(utf8); + +#if defined(LUA_CROSS_COMPILER) + +/* _G __index -> rotables __index -> base_func */ +extern LROT_TABLE(rotables_meta); +extern LROT_TABLE(base_func); +#if LUA_VERSION_NUM == 501 +extern LROT_TABLE(oslib); +extern LROT_TABLE(iolib); +#endif + +LROT_BEGIN(rotables_meta, NULL, LROT_MASK_INDEX) + LROT_TABENTRY( __index, base_func) +LROT_END(rotables_meta, NULL, LROT_MASK_INDEX) + +LROT_BEGIN(rotables, LROT_TABLEREF(rotables_meta), 0) + LROT_TABENTRY( string, strlib ) + LROT_TABENTRY( table, tab_funcs ) + LROT_TABENTRY( coroutine, co_funcs ) + LROT_TABENTRY( debug, dblib) + LROT_TABENTRY( math, mathlib ) +#if LUA_VERSION_NUM >= 503 + LROT_TABENTRY( utf8, utf8 ) +#endif + LROT_TABENTRY( ROM, rotables ) +#if LUA_VERSION_NUM == 501 + LROT_TABENTRY( os, oslib ) + LROT_TABENTRY( io, iolib ) +#endif +LROT_END(rotables, LROT_TABLEREF(rotables_meta), 0) + +LROT_BEGIN(lua_libs, NULL, 0) + LROT_FUNCENTRY( _G, luaopen_base ) + LROT_FUNCENTRY( package, luaopen_package ) + LROT_FUNCENTRY( string, luaopen_string ) +#if LUA_VERSION_NUM >= 503 + LROT_FUNCENTRY( nodemcu, luaN_init ) +#endif + LROT_FUNCENTRY( io, luaopen_io ) + LROT_FUNCENTRY( is, luaopen_os ) +LROT_END(lua_libs, NULL, 0) + +#else + +/* These symbols get created by the linker fragment mapping:nodemcu + * at the head of the lua libs init table and the rotables, respectively. + */ +extern const ROTable_entry _lua_libs_map_start[]; +extern const ROTable_entry _lua_rotables_map_start[]; + +ROTable rotables_ROTable; /* NOT const in this case */ + +LROT_ENTRIES_IN_SECTION(rotables, rotable) +#ifdef CONFIG_LUA_BUILTIN_STRING + LROT_TABENTRY( string, strlib ) +#endif +#ifdef CONFIG_LUA_BUILTIN_TABLE + LROT_TABENTRY( table, tab_funcs ) +#endif +#ifdef CONFIG_LUA_BUILTIN_COROUTINE + LROT_TABENTRY( coroutine, co_funcs ) +#endif +#ifdef CONFIG_LUA_BUILTIN_DEBUG + LROT_TABENTRY( debug, dblib) +#endif +#ifdef CONFIG_LUA_BUILTIN_MATH + LROT_TABENTRY( math, mathlib ) +#endif +#ifdef CONFIG_LUA_BUILTIN_UTF8 + LROT_TABENTRY( utf8, utf8 ) +#endif + LROT_TABENTRY( ROM, rotables ) +LROT_BREAK(lua_rotables_part) + + +LROT_ENTRIES_IN_SECTION(lua_libs, libs) + LROT_FUNCENTRY( _G, luaopen_base ) + LROT_FUNCENTRY( package, luaopen_package ) +#ifdef CONFIG_LUA_BUILTIN_STRING + LROT_FUNCENTRY( string, luaopen_string ) +#endif + LROT_FUNCENTRY( nodemcu, luaN_init ) +LROT_BREAK(lua_libs) + +#endif + +/* Historically the linker script took care of zero terminating both the + * lua_libs and lua_rotable arrays, but the IDF currently does not + * support injecting LONG(0) entries. To compensate, we have explicit + * end markers here which the linker fragment then place appropriately + * to terminate aforementioned arrays. + */ +const ROTable_entry LOCK_IN_SECTION(libs_end_marker) libs_end_marker= { 0, }; +const ROTable_entry LOCK_IN_SECTION(rotable_end_marker) rotable_end_marker = { 0, }; + +void luaL_openlibs (lua_State *L) { +#ifdef LUA_CROSS_COMPILER + const ROTable_entry *p = LROT_TABLEREF(lua_libs)->entry; +#else + const ROTable_entry *p = _lua_libs_map_start; + lua_createrotable(L, LROT_TABLEREF(rotables), _lua_rotables_map_start, NULL); +#endif + for ( ; p->key; p++) { +#if LUA_VERSION_NUM == 501 + if (ttislightfunction(&p->value) && fvalue(&p->value)) { + lua_pushcfunction(L, fvalue(&p->value)); + lua_pushstring(L, p->key); + lua_call(L, 1, 0); // call luaopen_XXX(libname) + } +#else + if (ttislcf(&p->value) && fvalue(&p->value)) + luaL_requiref(L, p->key, fvalue(&p->value), 1); +#endif + } +} + + +#ifndef LUA_CROSS_COMPILER +_Static_assert(_Alignof(ROTable_entry) <= 8, "Unexpected alignment of module registration - update the linker script snippets to match!"); +#endif diff --git a/components/lua/common/linput.c b/components/lua/common/linput.c new file mode 100644 index 00000000..2dba1cfd --- /dev/null +++ b/components/lua/common/linput.c @@ -0,0 +1,119 @@ +#include "platform.h" +#include "linput.h" +#include "lua.h" +#include "lauxlib.h" +#include + +static struct input_state { + char *data; + int line_pos; + size_t len; + const char *prompt; + char last_nl_char; +} ins = {0}; + +#define NUL '\0' +#define BS '\010' +#define CR '\r' +#define LF '\n' +#define DEL 0x7f +#define BS_OVER "\010 \010" + +bool input_echo = true; +bool run_input = true; + +/* +** The input state (ins) is private, so input_setup() exposes the necessary +** access to public properties and is called in user_init() before the Lua +** enviroment is initialised. +*/ +void input_setup(int bufsize, const char *prompt) { + // Initialise non-zero elements + ins.data = malloc(bufsize); + ins.len = bufsize; + ins.prompt = prompt; +} + +void input_setprompt (const char *prompt) { + ins.prompt = prompt; +} + + +size_t feed_lua_input(const char *buf, size_t n) +{ + for (size_t i = 0; i < n; ++i) { + char ch = buf[i]; + if (!run_input) // We're no longer interested in the remaining bytes + return i; + + /* handle CR & LF characters and aggregate \n\r and \r\n pairs */ + char tmp_last_nl_char = ins.last_nl_char; + /* handle CR & LF characters + filters second char of LF&CR (\n\r) or CR&LF (\r\n) sequences */ + if ((ch == CR && tmp_last_nl_char == LF) || // \n\r sequence -> skip \r + (ch == LF && tmp_last_nl_char == CR)) // \r\n sequence -> skip \n + { + continue; + } + + /* backspace key */ + if (ch == DEL || ch == BS) { + if (ins.line_pos > 0) { + if(input_echo) printf(BS_OVER); + ins.line_pos--; + } + ins.data[ins.line_pos] = 0; + continue; + } + + /* end of data */ + if (ch == CR || ch == LF) { + ins.last_nl_char = ch; + + if (input_echo) putchar(LF); + if (ins.line_pos == 0) { + /* Get a empty line, then go to get a new line */ + printf(ins.prompt); + fflush(stdout); + } else { + ins.data[ins.line_pos++] = LF; + lua_input_string(ins.data, ins.line_pos); + ins.line_pos = 0; + } + continue; + } + else + ins.last_nl_char = NUL; + + if(input_echo) putchar(ch); + + /* it's a large line, discard it */ + if ( ins.line_pos + 1 >= ins.len ){ + ins.line_pos = 0; + } + + ins.data[ins.line_pos++] = ch; + } + + return n; // we consumed/buffered all the provided data +} + + +void output_redirect(const char *str, size_t l) { + lua_State *L = lua_getstate(); + int n = lua_gettop(L); + lua_pushliteral(L, "stdout"); + lua_rawget(L, LUA_REGISTRYINDEX); /* fetch reg.stdout */ + if (lua_istable(L, -1)) { /* reg.stdout is pipe */ + lua_rawgeti(L, -1, 1); /* get the pipe_write func from stdout[1] */ + lua_insert(L, -2); /* and move above the pipe ref */ + lua_pushlstring(L, str, l); + if (lua_pcall(L, 2, 0, 0) != LUA_OK) { /* Reg.stdout:write(str) */ + lua_writestringerror("error calling stdout:write(%s)\n", lua_tostring(L, -1)); + esp_restart(); + } + } else { /* reg.stdout == nil */ + printf(str, l); + } + lua_settop(L, n); /* Make sure all code paths leave stack unchanged */ +} diff --git a/components/lua/common/linput.h b/components/lua/common/linput.h new file mode 100644 index 00000000..af19fb2a --- /dev/null +++ b/components/lua/common/linput.h @@ -0,0 +1,15 @@ +#ifndef _LINPUT_H_ +#define _LINPUT_H_ + +#include +#include + +void input_setup(int bufsize, const char *prompt); +void input_setprompt (const char *prompt); + +unsigned feed_lua_input(const char *buf, size_t n); + +extern bool input_echo; +extern bool run_input; + +#endif /* READLINE_APP_H */ diff --git a/components/base_nodemcu/lnodeaux.c b/components/lua/common/lnodeaux.c similarity index 99% rename from components/base_nodemcu/lnodeaux.c rename to components/lua/common/lnodeaux.c index 1a9a104e..009f9389 100644 --- a/components/base_nodemcu/lnodeaux.c +++ b/components/lua/common/lnodeaux.c @@ -99,7 +99,7 @@ char* luaX_alloc_string(lua_State* L, int idx, int max_length) { // luaX_free_string deallocates memory of a string allocated with luaX_alloc_string void luaX_free_string(lua_State* L, char* st) { if (st) - luaM_freearray(L, st, strlen(st) + 1, char); + luaN_freearray(L, st, strlen(st) + 1); } // luaX_unset_ref unpins a reference to a lua object in the registry diff --git a/components/base_nodemcu/include/lnodeaux.h b/components/lua/common/lnodeaux.h similarity index 99% rename from components/base_nodemcu/include/lnodeaux.h rename to components/lua/common/lnodeaux.h index 63424d42..d32d43a0 100644 --- a/components/base_nodemcu/include/lnodeaux.h +++ b/components/lua/common/lnodeaux.h @@ -36,6 +36,7 @@ #define _NODEMCU_LNODEAUX_H_ #include "lua.h" +#include // lua_ref_t represents a reference to a lua object in the registry typedef int lua_ref_t; diff --git a/components/lua/common/lpanic.c b/components/lua/common/lpanic.c new file mode 100644 index 00000000..d8e9a491 --- /dev/null +++ b/components/lua/common/lpanic.c @@ -0,0 +1,54 @@ +#include "lpanic.h" +#include "lauxlib.h" +#include +#include +#include +#ifndef LUA_CROSS_COMPILER +#include "esp_system.h" +/* defined in esp_system_internal.h */ +void esp_reset_reason_set_hint(esp_reset_reason_t hint); +#endif + + +#ifndef LUA_CROSS_COMPILER +/* + * upper 28 bit have magic value 0xD1EC0DE0 + * if paniclevel is valid (i.e. matches magic value) + * lower 4 bits have paniclevel: + * 0 = no panic occurred + * 1..15 = one..fifteen subsequent panic(s) occurred + */ +static __NOINIT_ATTR uint32_t l_rtc_panic_val; + +void panic_clear_nvval() { + l_rtc_panic_val = 0xD1EC0DE0; +} + +int panic_get_nvval() { + if ((l_rtc_panic_val & 0xfffffff0) == 0xD1EC0DE0) { + return (l_rtc_panic_val & 0xf); + } + panic_clear_nvval(); + return 0; +} +#endif + + +int lpanic (lua_State *L) { + (void)L; /* to avoid warnings */ +#ifndef LUA_CROSS_COMPILER + uint8_t paniclevel = panic_get_nvval(); + if (paniclevel < 15) paniclevel++; + l_rtc_panic_val = 0xD1EC0DE0 | paniclevel; +#endif + lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", + lua_tostring(L, -1)); +#ifndef LUA_CROSS_COMPILER + fflush(stdout); + /* call abort() directly - we don't want another reset cause to intervene */ + esp_reset_reason_set_hint(ESP_RST_PANIC); +#endif + abort(); + while (1) {} + return 0; +} diff --git a/components/lua/common/lpanic.h b/components/lua/common/lpanic.h new file mode 100644 index 00000000..6caf7103 --- /dev/null +++ b/components/lua/common/lpanic.h @@ -0,0 +1,10 @@ +#ifndef _LUA_PANIC_H_ +#define _LUA_PANIC_H_ + +#include "lua.h" + +void panic_clear_nvval (void); +int panic_get_nvval (void); +int lpanic (lua_State *L); + +#endif diff --git a/components/lua/legc.c b/components/lua/legc.c deleted file mode 100644 index c0bf07a6..00000000 --- a/components/lua/legc.c +++ /dev/null @@ -1,12 +0,0 @@ -// Lua EGC (Emergeny Garbage Collector) interface - -#include "legc.h" -#include "lstate.h" - -void legc_set_mode(lua_State *L, int mode, int limit) { - global_State *g = G(L); - - g->egcmode = mode; - g->memlimit = limit; -} - diff --git a/components/lua/legc.h b/components/lua/legc.h deleted file mode 100644 index c85ebb6b..00000000 --- a/components/lua/legc.h +++ /dev/null @@ -1,17 +0,0 @@ -// Lua EGC (Emergeny Garbage Collector) interface - -#ifndef __LEGC_H__ -#define __LEGC_H__ - -#include "lstate.h" - -// EGC operations modes -#define EGC_NOT_ACTIVE 0 // EGC disabled -#define EGC_ON_ALLOC_FAILURE 1 // run EGC on allocation failure -#define EGC_ON_MEM_LIMIT 2 // run EGC when an upper memory limit is hit -#define EGC_ALWAYS 4 // always run EGC before an allocation - -void legc_set_mode(lua_State *L, int mode, int limit); - -#endif - diff --git a/components/lua/link_lua.lf b/components/lua/link_lua.lf new file mode 100644 index 00000000..f88b1e5e --- /dev/null +++ b/components/lua/link_lua.lf @@ -0,0 +1,35 @@ +[sections:lua_libs] +entries: + .lua_libs + +[sections:lua_libs_end_marker] +entries: + .lua_libs_end_marker + +[sections:lua_rotable] +entries: + .lua_rotable + +[sections:lua_rotable_end_marker] +entries: + .lua_rotable_end_marker + +[scheme:lua_arrays] +entries: + lua_libs -> flash_rodata + lua_libs_end_marker -> flash_rodata + lua_rotable -> flash_rodata + lua_rotable_end_marker -> flash_rodata + + +# Important: don't change the alignments below without also updating the +# _Static_assert over in linit.c! + +[mapping:lua] +archive: * +entries: + * (lua_arrays); + lua_libs -> flash_rodata KEEP() ALIGN(8) SURROUND(lua_libs_map), + lua_libs_end_marker -> flash_rodata KEEP(), + lua_rotable -> flash_rodata KEEP() ALIGN(8) SURROUND(lua_rotables_map), + lua_rotable_end_marker -> flash_rodata KEEP() diff --git a/components/lua/lrotable.c b/components/lua/lrotable.c deleted file mode 100644 index 07cf19ed..00000000 --- a/components/lua/lrotable.c +++ /dev/null @@ -1,157 +0,0 @@ -/* Read-only tables for Lua */ -#define LUAC_CROSS_FILE - -#include "lua.h" -#include -#include "lrotable.h" -#include "lauxlib.h" -#include "lstring.h" -#include "lobject.h" -#include "lapi.h" - -#ifdef _MSC_VER -#define ALIGNED_STRING __declspec( align( 4 ) ) char -#else -#define ALIGNED_STRING __attribute__((aligned(4))) char -#endif -#define LA_LINES 32 -#define LA_SLOTS 4 -//#define COLLECT_STATS - -/* - * All keyed ROtable access passes through luaR_findentry(). ROTables - * are simply a list of pairs. The existing algo - * did a linear scan of this vector of pairs looking for a match. - * - * A N×M lookaside cache has been added, with a simple hash on the key's - * TString addr and the ROTable addr to identify one of N lines. Each - * line has M slots which are scanned. This is all done in RAM and is - * perhaps 20x faster than the corresponding random Flash accesses which - * will cause flash faults. - * - * If a match is found and the table addresses match, then this entry is - * probed first. In practice the hit-rate here is over 99% so the code - * rarely fails back to doing the linear scan in ROM. - * - * Note that this hash does a couple of prime multiples and a modulus 2^X - * with is all evaluated in H/W, and adequately randomizes the lookup. - */ -#define HASH(a,b) ((((519*(size_t)(a)))>>4) + ((b) ? (b)->tsv.hash: 0)) - -static struct { - unsigned hash; - unsigned addr:24; - unsigned ndx:8; -} cache[LA_LINES][LA_SLOTS]; - -#ifdef COLLECT_STATS -unsigned cache_stats[3]; -#define COUNT(i) cache_stats[i]++ -#else -#define COUNT(i) -#endif - -static int lookup_cache(unsigned hash, ROTable *rotable) { - int i = (hash>>2) & (LA_LINES-1), j; - - for (j = 0; j>2 & (LA_LINES-1), j; - COUNT(2); - if (ndx>0xffu) - return; - for (j = LA_SLOTS-1; j>0; j--) - cache[i][j] = cache[i][j-1]; - cache[i][0].hash = hash; - cache[i][0].addr = (size_t) rotable; - cache[i][0].ndx = ndx; -} -/* - * Find a string key entry in a rotable and return it. Note that this internally - * uses a null key to denote a metatable search. - */ -const TValue* luaR_findentry(ROTable *rotable, TString *key, unsigned *ppos) { - const luaR_entry *pentry = rotable; - static const ALIGNED_STRING metatablestr[] = "__metatable"; - const char *strkey = key ? getstr(key) : metatablestr; - unsigned hash = HASH(rotable, key); - - unsigned i = 0; - int j = lookup_cache(hash, rotable); - unsigned l = key ? key->tsv.len : sizeof("__metatable")-1; - - if (pentry) { - if (j >= 0 && !strcmp(pentry[j].key, strkey)) { - if (ppos) - *ppos = j; -//printf("%3d hit %p %s\n", (hash>>2) & (LA_LINES-1), rotable, strkey); - return &pentry[j].value; - } - /* - * The invariants for 1st word comparison are deferred to here since they - * aren't needed if there is a cache hit. Note that the termination null - * is included so a "on\0" has a mask of 0xFFFFFF and "a\0" has 0xFFFF. - */ - unsigned name4, mask4 = l > 2 ? (~0u) : (~0u)>>((3-l)*8); - memcpy(&name4, strkey, sizeof(name4)); - - for(;pentry->key != NULL; i++, pentry++) { - if (((*(unsigned *)pentry->key ^ name4) & mask4) == 0 && - !strcmp(pentry->key, strkey)) { -//printf("%p %s hit after %d probes \n", rotable, strkey, (int)(pentry-rotable)); - if (ppos) - *ppos = i; - update_cache(hash, rotable, pentry - rotable); -//printf("%3d %3d %p %s\n", (hash>>2) & (LA_LINES-1), (int)(pentry-rotable), rotable, strkey); - return &pentry->value; - } - } - } -//printf("%p %s miss after %d probes \n", rotable, strkey, (int)(pentry-rotable)); - return luaO_nilobject; -} - -/* Find the metatable of a given table */ -void* luaR_getmeta(ROTable *rotable) { - const TValue *res = luaR_findentry(rotable, NULL, NULL); - return res && ttisrotable(res) ? rvalue(res) : NULL; -} - -static void luaR_next_helper(lua_State *L, ROTable *pentries, int pos, - TValue *key, TValue *val) { - if (pentries[pos].key) { - /* Found an entry */ - setsvalue(L, key, luaS_new(L, pentries[pos].key)); - setobj2s(L, val, &pentries[pos].value); - } else { - setnilvalue(key); - setnilvalue(val); - } -} - - -/* next (used for iteration) */ -void luaR_next(lua_State *L, ROTable *rotable, TValue *key, TValue *val) { - unsigned keypos; - - /* Special case: if key is nil, return the first element of the rotable */ - if (ttisnil(key)) - luaR_next_helper(L, rotable, 0, key, val); - else if (ttisstring(key)) { - /* Find the previous key again */ - luaR_findentry(rotable, rawtsvalue(key), &keypos); - /* Advance to next key */ - keypos ++; - luaR_next_helper(L, rotable, keypos, key, val); - } -} diff --git a/components/lua/lrotable.h b/components/lua/lrotable.h deleted file mode 100644 index 6bf7b91d..00000000 --- a/components/lua/lrotable.h +++ /dev/null @@ -1,99 +0,0 @@ -/* Read-only tables for Lua */ - -#ifndef lrotable_h -#define lrotable_h - -#include "lua.h" -#include "luaconf.h" -#include "lobject.h" -#include "llimits.h" - -/* Macros one can use to define rotable entries */ -#define LRO_FUNCVAL(v) {{.p = v}, LUA_TLIGHTFUNCTION} -#define LRO_LUDATA(v) {{.p = v}, LUA_TLIGHTUSERDATA} -#define LRO_NUMVAL(v) {{.n = v}, LUA_TNUMBER} -#define LRO_ROVAL(v) {{.p = (void*)v}, LUA_TROTABLE} -#define LRO_NILVAL {{.p = NULL}, LUA_TNIL} - -#ifdef LUA_CROSS_COMPILER -#define LRO_STRKEY(k) k -#else -#define LRO_STRKEY(k) ((__attribute__((aligned(4))) char *) k) -#endif - -#define LROT_TABLE(t) static const LUA_REG_TYPE t ## _map[]; -#define LROT_PUBLIC_TABLE(t) const LUA_REG_TYPE t ## _map[]; -#define LROT_TABLEREF(t) ((void *) t ## _map) -#define LROT_BEGIN(t) static const LUA_REG_TYPE t ## _map [] = { -#define LROT_PUBLIC_BEGIN(t) const LUA_REG_TYPE t ## _map[] = { -#define LROT_EXTERN(t) extern const LUA_REG_TYPE t ## _map[] -#define LROT_TABENTRY(n,t) {LRO_STRKEY(#n), LRO_ROVAL(t ## _map)}, -#define LROT_FUNCENTRY(n,f) {LRO_STRKEY(#n), LRO_FUNCVAL(f)}, -#define LROT_NUMENTRY(n,x) {LRO_STRKEY(#n), LRO_NUMVAL(x)}, -#define LROT_LUDENTRY(n,x) {LRO_STRKEY(#n), LRO_LUDATA((void *) x)}, -#define LROT_END(t,mt, f) {NULL, LRO_NILVAL} }; -#define LROT_BREAK(t) }; - -#define LUA_REG_TYPE luaR_entry -#define LREGISTER(L, name, table) return 0 - -/* Maximum length of a rotable name and of a string key*/ -#define LUA_MAX_ROTABLE_NAME 32 - -/* Type of a numeric key in a rotable */ -typedef int luaR_numkey; - -/* An entry in the read only table */ -typedef struct luaR_entry { - const char *key; - const TValue value; -} luaR_entry; - -/* - * The current ROTable implmentation is a vector of luaR_entry terminated by a - * nil record. The convention is to use ROtable * to refer to the entire vector - * as a logical ROTable. - */ -typedef const struct luaR_entry ROTable; - -const TValue* luaR_findentry(ROTable *tab, TString *key, unsigned *ppos); -const TValue* luaR_findentryN(ROTable *tab, luaR_numkey numkey, unsigned *ppos); -void luaR_next(lua_State *L, ROTable *tab, TValue *key, TValue *val); -void* luaR_getmeta(ROTable *tab); -int luaR_isrotable(void *p); - -/* - * Set inRO check depending on platform. Note that this implementation needs - * to work on both the host (luac.cross) and ESP targets. The luac.cross - * VM is used for the -e option, and is primarily used to be able to debug - * VM changes on the more developer-friendly hot gdb environment. - */ -#if defined(LUA_CROSS_COMPILER) - -#if defined(_MSC_VER) -//msvc build uses these dummy vars to locate the beginning and ending addresses of the RO data -extern const char _ro_start[], _ro_end[]; -#define IN_RODATA_AREA(p) (((const char*)(p)) >= _ro_start && ((const char *)(p)) <= _ro_end) -#else /* one of the POSIX variants */ -#if defined(__CYGWIN__) -#define _RODATA_END __end__ -#elif defined(__MINGW32__) -#define _RODATA_END end -#else -#define _RODATA_END _edata -#endif -extern const char _RODATA_END[]; -#define IN_RODATA_AREA(p) (((const char *)(p)) < _RODATA_END) -#endif /* defined(_MSC_VER) */ - -#else /* xtensa tool chain for ESP32 target */ - -#include "compiler.h" -#define IN_RODATA_AREA(p) (((const char *)p) >= RODATA_START_ADDRESS && ((const char *)p) <= RODATA_END_ADDRESS) - -#endif /* defined(LUA_CROSS_COMPILER) */ - -/* Return 1 if the given pointer is a rotable */ -#define luaR_isrotable(p) IN_RODATA_AREA(p) - -#endif diff --git a/components/lua/compiler.h b/components/lua/lua-5.1/compiler.h similarity index 100% rename from components/lua/compiler.h rename to components/lua/lua-5.1/compiler.h diff --git a/components/lua/lua-5.1/host/idf.mk b/components/lua/lua-5.1/host/idf.mk new file mode 100644 index 00000000..8732cad3 --- /dev/null +++ b/components/lua/lua-5.1/host/idf.mk @@ -0,0 +1,68 @@ +all: build + +HOSTCC?=$(PYTHON) -m ziglang cc + +ifeq ($V,) + Q:=@ +endif + +LUAC_OBJ_DIR:=$(LUAC_BUILD_DIR)/$(notdir $(LUA_PATH)) + +LUAC_CFLAGS:= \ + -I$(LUAC_BUILD_DIR) \ + -I$(LUA_PATH) \ + -I$(LUA_PATH)/host \ + -I$(LUA_PATH)/../common \ + -I$(LUA_PATH)/../../uzlib \ + -O2 -g -Wall -Wextra -Wno-sign-compare + +LUAC_LDFLAGS:= -ldl -lm + +LUAC_DEFINES += \ + -DLUA_CROSS_COMPILER \ + -DLUA_USE_HOST \ + -DLUA_USE_STDIO \ + +vpath %.c $(LUA_PATH)/host $(LUA_PATH) $(LUA_PATH)/../common $(LUA_PATH)/../../uzlib + +LUA_SRCS:=\ + luac.c lflashimg.c loslib.c print.c liolib.c \ + lapi.c lauxlib.c lbaselib.c lcode.c ldblib.c ldebug.c \ + ldo.c ldump.c lfunc.c lgc.c llex.c \ + lmathlib.c lmem.c loadlib.c lobject.c lopcodes.c lparser.c \ + lnodemcu.c lstate.c lstring.c lstrlib.c ltable.c ltablib.c \ + ltm.c lundump.c lvm.c lzio.c \ + linit.c lpanic.c \ + uzlib_deflate.c crc32.c \ + +LUAC_OBJS:=$(LUA_SRCS:%.c=$(LUAC_OBJ_DIR)/%.o) +LUAC_CROSS:=$(LUAC_BUILD_DIR)/luac.cross + +$(LUAC_OBJ_DIR): + @mkdir -p "$@" + +$(LUAC_OBJ_DIR)/%.o: %.c | $(LUAC_OBJ_DIR) + @echo '[hostcc] $(notdir $@)' + $Q$(HOSTCC) $(LUAC_DEFINES) $(LUAC_CFLAGS) "$<" -c -o "$@" + +$(LUAC_OBJ_DIR)/%.d: SHELL=/bin/bash +$(LUAC_OBJ_DIR)/%.d: %.c | $(LUAC_OBJ_DIR) + @echo '[ dep] $<' + @rm -f "$@" + $Qset -eo pipefail; $(HOSTCC) $(LUAC_DEFINES) $(LUAC_CFLAGS) -M "$<" | sed 's,\($*\.o\)[ :]*,$(LUAC_OBJ_DIR)/\1 $@ : ,g' > "$@.tmp"; mv "$@.tmp" "$@" + +build: $(LUAC_DEPS) $(LUAC_CROSS) + +$(LUAC_CROSS): $(LUAC_OBJS) + @echo '[ link] $(notdir $@)' + $Q$(HOSTCC) $(LUAC_CFLAGS) $^ $(LUAC_LDFLAGS) -o "$@" + +# zig cc (0.8.0 at least) seems to get itself all confused with its cache +# when we're running a separate path for dependencies, so we skip them for +# now as for most people they're not needed anyway. +ifneq ($(findstring zig,$(HOSTCC)),zig) + LUAC_DEPS:=$(LUAC_OBJS:%.o=%.d) + ifneq ($(MAKECMDGOALS),clean) + -include $(LUAC_DEPS) + endif +endif diff --git a/components/luac_cross/lflashimg.c b/components/lua/lua-5.1/host/lflashimg.c similarity index 96% rename from components/luac_cross/lflashimg.c rename to components/lua/lua-5.1/host/lflashimg.c index 59ce8560..65edf07e 100644 --- a/components/luac_cross/lflashimg.c +++ b/components/lua/lua-5.1/host/lflashimg.c @@ -6,7 +6,6 @@ #define LUAC_CROSS_FILE -#include "luac_cross.h" #include #include #include @@ -109,10 +108,11 @@ static uint *flashAddrTag = flashImage + LUA_MAX_FLASH_SIZE; #define setFlashAddrTag(v) flashAddrTag[_TW(v)] |= _TB(v) #define getFlashAddrTag(v) ((flashAddrTag[_TW(v)]&_TB(v)) != 0) +#define fatal luac_fatal #ifdef _MSC_VER -extern void __declspec( noreturn ) fatal( const char* message ); +extern void __declspec( noreturn ) luac_fatal( const char* message ); #else -extern void __attribute__((noreturn)) fatal(const char* message); +extern void __attribute__((noreturn)) luac_fatal(const char* message); #endif #ifdef LOCAL_DEBUG @@ -188,10 +188,8 @@ static void scanProtoStrings(lua_State *L, const Proto* f) { if (f->source) addTS(L, f->source); -#ifdef LUA_OPTIMIZE_DEBUG if (f->packedlineinfo) addTS(L, luaS_new(L, cast(const char *, f->packedlineinfo))); -#endif for (i = 0; i < f->sizek; i++) { if (ttisstring(f->k + i)) @@ -357,11 +355,7 @@ static void *flashCopy(lua_State* L, int n, const char *fmt, void *src) { } /* The debug optimised version has a different Proto layout */ -#ifdef LUA_OPTIMIZE_DEBUG #define PROTO_COPY_MASK "AHAAAAAASIIIIIIIAI" -#else -#define PROTO_COPY_MASK "AHAAAAAASIIIIIIIIAI" -#endif /* * Do the actual prototype copy. @@ -385,14 +379,10 @@ static void *functionToFlash(lua_State* L, const Proto* orig) { f.k = cast(TValue *, flashCopy(L, f.sizek, "V", f.k)); f.code = cast(Instruction *, flashCopy(L, f.sizecode, "I", f.code)); -#ifdef LUA_OPTIMIZE_DEBUG if (f.packedlineinfo) { TString *ts=luaS_new(L, cast(const char *,f.packedlineinfo)); f.packedlineinfo = cast(unsigned char *, resolveTString(L, ts)) + sizeof (FlashTS); } -#else - f.lineinfo = cast(int *, flashCopy(L, f.sizelineinfo, "I", f.lineinfo)); -#endif f.locvars = cast(struct LocVar *, flashCopy(L, f.sizelocvars, "SII", f.locvars)); f.upvalues = cast(TString **, flashCopy(L, f.sizeupvalues, "S", f.upvalues)); return cast(void *, flashCopy(L, 1, PROTO_COPY_MASK, &f)); @@ -401,10 +391,10 @@ static void *functionToFlash(lua_State* L, const Proto* orig) { uint dumpToFlashImage (lua_State* L, const Proto *main, lua_Writer w, void* data, int strip, lu_int32 address, lu_int32 maxSize) { - (void)strip; // parameter strip is ignored for now + (void)strip; FlashHeader *fh = cast(FlashHeader *, flashAlloc(L, sizeof(FlashHeader))); - int status; + int i, status; lua_newtable(L); scanProtoStrings(L, main); createROstrt(L, fh); @@ -416,7 +406,7 @@ uint dumpToFlashImage (lua_State* L, const Proto *main, lua_Writer w, fatal ("The image is too large for specfied LFS size"); } if (address) { /* in absolute mode convert addresses to mapped address */ - for (uint i = 0 ; i < curOffset; i++) + for (i = 0 ; i < curOffset; i++) if (getFlashAddrTag(i)) flashImage[i] = 4*flashImage[i] + address; lua_unlock(L); @@ -434,7 +424,7 @@ uint dumpToFlashImage (lua_State* L, const Proto *main, lua_Writer w, status = uzlib_compress (&oBuf, &oLen, (const uint8_t *)flashImage, bmLen+fh->flash_size); if (status != UZLIB_OK) { - fatal("Out of memory during image compression"); + luac_fatal("Out of memory during image compression"); } lua_unlock(L); #if 0 diff --git a/components/luac_cross/liolib.c b/components/lua/lua-5.1/host/liolib.c similarity index 98% rename from components/luac_cross/liolib.c rename to components/lua/lua-5.1/host/liolib.c index 3eda7856..ce4b6035 100644 --- a/components/luac_cross/liolib.c +++ b/components/lua/lua-5.1/host/liolib.c @@ -17,7 +17,7 @@ #include "lauxlib.h" #include "lualib.h" -#include "lrotable.h" +#include "lnodemcu.h" #define IO_INPUT 1 #define IO_OUTPUT 2 @@ -439,7 +439,10 @@ static int f_flush (lua_State *L) { return pushresult(L, fflush(tofile(L)) == 0, NULL); } -LROT_PUBLIC_BEGIN(iolib) +LROT_TABLE(iolib); + +LROT_BEGIN(iolib, NULL, LROT_MASK_GC_INDEX) + LROT_TABENTRY( __index, iolib ) LROT_FUNCENTRY( close, io_close ) LROT_FUNCENTRY( flush, io_flush ) LROT_FUNCENTRY( input, io_input ) @@ -449,10 +452,14 @@ LROT_PUBLIC_BEGIN(iolib) LROT_FUNCENTRY( read, io_read ) LROT_FUNCENTRY( type, io_type ) LROT_FUNCENTRY( write, io_write ) - LROT_TABENTRY( __index, iolib ) -LROT_END(iolib, NULL, 0) +LROT_END(iolib, NULL, LROT_MASK_GC_INDEX) -LROT_BEGIN(flib) +LROT_TABLE(flib); + +LROT_BEGIN(flib, NULL, LROT_MASK_GC_INDEX) + LROT_FUNCENTRY( __gc, io_gc ) + LROT_TABENTRY( __index, flib ) + LROT_FUNCENTRY( __tostring, io_tostring ) LROT_FUNCENTRY( close, io_close ) LROT_FUNCENTRY( flush, f_flush ) LROT_FUNCENTRY( lines, f_lines ) @@ -460,9 +467,6 @@ LROT_BEGIN(flib) LROT_FUNCENTRY( seek, f_seek ) LROT_FUNCENTRY( setvbuf, f_setvbuf ) LROT_FUNCENTRY( write, f_write ) - LROT_FUNCENTRY( __gc, io_gc ) - LROT_FUNCENTRY( __tostring, io_tostring ) - LROT_TABENTRY( __index, flib ) LROT_END(flib, NULL, LROT_MASK_GC_INDEX) static const luaL_Reg io_base[] = {{NULL, NULL}}; diff --git a/components/luac_cross/loslib.c b/components/lua/lua-5.1/host/loslib.c similarity index 89% rename from components/luac_cross/loslib.c rename to components/lua/lua-5.1/host/loslib.c index 5887bf56..6b024c6f 100644 --- a/components/luac_cross/loslib.c +++ b/components/lua/lua-5.1/host/loslib.c @@ -6,7 +6,6 @@ #define LUAC_CROSS_FILE -#include "luac_cross.h" #include #include #include @@ -20,8 +19,7 @@ #include "lauxlib.h" #include "lualib.h" -#include "lrotable.h" - +#include "lnodemcu.h" static int os_pushresult (lua_State *L, int i, const char *filename) { int en = errno; /* calls to Lua API may change this value */ @@ -221,32 +219,26 @@ static int os_exit (lua_State *L) { exit(luaL_optint(L, 1, EXIT_SUCCESS)); } -#undef MIN_OPT_LEVEL -#define MIN_OPT_LEVEL 1 -#include "lrotable.h" -LROT_PUBLIC_BEGIN(oslib) - LROT_FUNCENTRY(clock, os_clock) - LROT_FUNCENTRY(date, os_date) +LROT_BEGIN(oslib, NULL, 0) + LROT_FUNCENTRY( clock, os_clock ) + LROT_FUNCENTRY( date, os_date ) #if !defined LUA_NUMBER_INTEGRAL - LROT_FUNCENTRY(difftime, os_difftime) + LROT_FUNCENTRY( difftime, os_difftime ) #endif - LROT_FUNCENTRY(execute, os_execute) - LROT_FUNCENTRY(exit, os_exit) - LROT_FUNCENTRY(getenv, os_getenv) - LROT_FUNCENTRY(remove, os_remove) - LROT_FUNCENTRY(rename, os_rename) - LROT_FUNCENTRY(setlocale, os_setlocale) - LROT_FUNCENTRY(time, os_time) - LROT_FUNCENTRY(tmpname, os_tmpname) + LROT_FUNCENTRY( execute, os_execute ) + LROT_FUNCENTRY( exit, os_exit ) + LROT_FUNCENTRY( getenv, os_getenv ) + LROT_FUNCENTRY( remove, os_remove ) + LROT_FUNCENTRY( rename, os_rename ) + LROT_FUNCENTRY( setlocale, os_setlocale ) + LROT_FUNCENTRY( time, os_time ) + LROT_FUNCENTRY( tmpname, os_tmpname ) LROT_END(oslib, NULL, 0) - - /* }====================================================== */ LUALIB_API int luaopen_os (lua_State *L) { (void)L; - //LREGISTER(L, LUA_OSLIBNAME, oslib); // <------------- ??? - return 0; + return 1; } diff --git a/components/luac_cross/luac.c b/components/lua/lua-5.1/host/luac.c similarity index 99% rename from components/luac_cross/luac.c rename to components/lua/lua-5.1/host/luac.c index 729937bd..62e0f38b 100644 --- a/components/luac_cross/luac.c +++ b/components/lua/lua-5.1/host/luac.c @@ -5,15 +5,15 @@ */ #define LUAC_CROSS_FILE +#define luac_c +#define LUA_CORE -#include "luac_cross.h" #include #include #include #include +#include -#define luac_c -#define LUA_CORE #include "lua.h" #include "lauxlib.h" @@ -42,11 +42,12 @@ static const char* execute; /* executed a Lua file */ static const char* progname=PROGNAME; /* actual program name */ static DumpTargetInfo target; -void fatal(const char* message) +void luac_fatal(const char* message) { fprintf(stderr,"%s: %s\n",progname,message); exit(EXIT_FAILURE); } +#define fatal(s) luac_fatal(s) static void cannot(const char* what) { @@ -280,8 +281,8 @@ static int pmain(lua_State* L) if (!lua_checkstack(L,argc)) fatal("too many input files"); if (execute) { - if (luaL_loadfile(L,execute)!=0) fatal(lua_tostring(L,-1)); luaL_openlibs(L); + if (luaL_loadfile(L,execute)!=0) fatal(lua_tostring(L,-1)); lua_pushstring(L, execute); if (lua_pcall(L, 1, 1, 0)) fatal(lua_tostring(L,-1)); if (!lua_isfunction(L, -1)) diff --git a/components/luac_cross/print.c b/components/lua/lua-5.1/host/print.c similarity index 99% rename from components/luac_cross/print.c rename to components/lua/lua-5.1/host/print.c index 71b8352a..b55c19b5 100644 --- a/components/luac_cross/print.c +++ b/components/lua/lua-5.1/host/print.c @@ -6,7 +6,6 @@ #define LUAC_CROSS_FILE -#include "luac_cross.h" #include #include diff --git a/components/lua/lapi.c b/components/lua/lua-5.1/lapi.c similarity index 83% rename from components/lua/lapi.c rename to components/lua/lua-5.1/lapi.c index 371c09fa..86941161 100644 --- a/components/lua/lapi.c +++ b/components/lua/lua-5.1/lapi.c @@ -6,11 +6,9 @@ #define lapi_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" -//#include #include #include #include "lapi.h" @@ -26,7 +24,6 @@ #include "ltm.h" #include "lundump.h" #include "lvm.h" -#include "lrotable.h" #if 0 const char lua_ident[] = @@ -155,6 +152,16 @@ LUA_API lua_State *lua_newthread (lua_State *L) { */ +/* +** convert an acceptable stack index into an absolute index +*/ +LUA_API int lua_absindex (lua_State *L, int idx) { + return (idx > 0 || idx <= LUA_REGISTRYINDEX) + ? idx + : cast_int(L->top - L->base) - 1 + idx; +} + + LUA_API int lua_gettop (lua_State *L) { return cast_int(L->top - L->base); } @@ -243,6 +250,12 @@ LUA_API void lua_pushvalue (lua_State *L, int idx) { LUA_API int lua_type (lua_State *L, int idx) { + StkId o = index2adr(L, idx); + return (o == luaO_nilobject) ? LUA_TNONE : ttnov(o); +} + + +LUA_API int lua_fulltype (lua_State *L, int idx) { StkId o = index2adr(L, idx); return (o == luaO_nilobject) ? LUA_TNONE : ttype(o); } @@ -250,7 +263,7 @@ LUA_API int lua_type (lua_State *L, int idx) { LUA_API const char *lua_typename (lua_State *L, int t) { UNUSED(L); - return (t == LUA_TNONE) ? "no value" : luaT_typenames[t]; + return (t == LUA_TNONE || t >= LUA_NUMTAGS) ? "no value" : luaT_typenames[t]; } @@ -287,32 +300,25 @@ LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { } -LUA_API int lua_equal (lua_State *L, int index1, int index2) { +LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) { StkId o1, o2; - int i; + int i = 0; lua_lock(L); /* may call tag method */ o1 = index2adr(L, index1); o2 = index2adr(L, index2); - i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2); + if (o1 != luaO_nilobject && o2 != luaO_nilobject) { + switch (op) { + case LUA_OPEQ: i = luaV_equalval(L, o1, o2); break; + case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break; + case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break; + default: api_check(L, 0); + } + } lua_unlock(L); return i; } -LUA_API int lua_lessthan (lua_State *L, int index1, int index2) { - StkId o1, o2; - int i; - lua_lock(L); /* may call tag method */ - o1 = index2adr(L, index1); - o2 = index2adr(L, index2); - i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 - : luaV_lessthan(L, o1, o2); - lua_unlock(L); - return i; -} - - - LUA_API lua_Number lua_tonumber (lua_State *L, int idx) { TValue n; const TValue *o = index2adr(L, idx); @@ -363,11 +369,10 @@ LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { LUA_API size_t lua_objlen (lua_State *L, int idx) { StkId o = index2adr(L, idx); - switch (ttype(o)) { + switch (ttnov(o)) { case LUA_TSTRING: return tsvalue(o)->len; case LUA_TUSERDATA: return uvalue(o)->len; case LUA_TTABLE: return luaH_getn(hvalue(o)); - case LUA_TROTABLE: return luaH_getn_ro(rvalue(o)); case LUA_TNUMBER: { size_t l; lua_lock(L); /* `luaV_tostring' may create a new string */ @@ -405,16 +410,14 @@ LUA_API lua_State *lua_tothread (lua_State *L, int idx) { LUA_API const void *lua_topointer (lua_State *L, int idx) { StkId o = index2adr(L, idx); switch (ttype(o)) { - case LUA_TTABLE: return hvalue(o); + case LUA_TTABLE: + case LUA_TROTABLE: + return hvalue(o); case LUA_TFUNCTION: return clvalue(o); case LUA_TTHREAD: return thvalue(o); - case LUA_TUSERDATA: - case LUA_TLIGHTUSERDATA: - return lua_touserdata(L, idx); - case LUA_TROTABLE: - return rvalue(o); - case LUA_TLIGHTFUNCTION: - return fvalue(o); + case LUA_TUSERDATA: return lua_touserdata(L, idx); + case LUA_TLIGHTUSERDATA: return pvalue(o); + case LUA_TLIGHTFUNCTION: return fvalue(o); default: return NULL; } } @@ -492,18 +495,23 @@ LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { - Closure *cl; lua_lock(L); - luaC_checkGC(L); - api_checknelems(L, n); - cl = luaF_newCclosure(L, n, getcurrenv(L)); - cl->c.f = fn; - L->top -= n; - while (n--) - setobj2n(L, &cl->c.upvalue[n], L->top+n); - setclvalue(L, L->top, cl); - lua_assert(iswhite(obj2gco(cl))); - api_incr_top(L); + if (n == 0) { + setfvalue(L->top, fn); + api_incr_top(L); + } else { + Closure *cl; + luaC_checkGC(L); + api_checknelems(L, n); + cl = luaF_newCclosure(L, n, getcurrenv(L)); + cl->c.f = fn; + L->top -= n; + while (n--) + setobj2n(L, &cl->c.upvalue[n], L->top+n); + setclvalue(L, L->top, cl); + lua_assert(iswhite(obj2gco(cl))); + api_incr_top(L); + } lua_unlock(L); } @@ -523,16 +531,10 @@ LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { lua_unlock(L); } -LUA_API void lua_pushrotable (lua_State *L, void *p) { - lua_lock(L); - setrvalue(L->top, p); - api_incr_top(L); - lua_unlock(L); -} -LUA_API void lua_pushlightfunction(lua_State *L, void *p) { +LUA_API void lua_pushrotable (lua_State *L, const ROTable *t) { lua_lock(L); - setfvalue(L->top, p); + sethvalue(L, L->top, cast(ROTable *,t)); api_incr_top(L); lua_unlock(L); } @@ -553,17 +555,17 @@ LUA_API int lua_pushthread (lua_State *L) { */ -LUA_API void lua_gettable (lua_State *L, int idx) { +LUA_API int lua_gettable (lua_State *L, int idx) { StkId t; lua_lock(L); t = index2adr(L, idx); api_checkvalidindex(L, t); luaV_gettable(L, t, L->top - 1, L->top - 1); lua_unlock(L); + return ttnov(L->top - 1); } - -LUA_API void lua_getfield (lua_State *L, int idx, const char *k) { +LUA_API int lua_getfield (lua_State *L, int idx, const char *k) { StkId t; TValue key; lua_lock(L); @@ -575,29 +577,58 @@ LUA_API void lua_getfield (lua_State *L, int idx, const char *k) { luaV_gettable(L, t, &key, L->top); api_incr_top(L); lua_unlock(L); + return ttnov(L->top - 1); } - -LUA_API void lua_rawget (lua_State *L, int idx) { +LUA_API int lua_geti (lua_State *L, int idx, int n) { StkId t; - const TValue *res; + TValue key; lua_lock(L); t = index2adr(L, idx); - api_check(L, ttistable(t) || ttisrotable(t)); - res = ttistable(t) ? luaH_get(hvalue(t), L->top - 1) : luaH_get_ro(rvalue(t), L->top - 1); - setobj2s(L, L->top - 1, res); + api_checkvalidindex(L, t); + fixedstack(L); + setnvalue(&key, n); + unfixedstack(L); + luaV_gettable(L, t, &key, L->top); + api_incr_top(L); lua_unlock(L); + return ttnov(L->top - 1); +} + +LUA_API int lua_rawget (lua_State *L, int idx) { + StkId t; + lua_lock(L); + t = index2adr(L, idx); + api_check(L, ttistable(t)); + setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1)); + lua_unlock(L); + return ttnov(L->top - 1); } -LUA_API void lua_rawgeti (lua_State *L, int idx, int n) { +LUA_API int lua_rawgeti (lua_State *L, int idx, int n) { StkId o; lua_lock(L); o = index2adr(L, idx); - api_check(L, ttistable(o) || ttisrotable(o)); - setobj2s(L, L->top, ttistable(o) ? luaH_getnum(hvalue(o), n) : luaH_getnum_ro(rvalue(o), n)) + api_check(L, ttistable(o)); + setobj2s(L, L->top, luaH_getnum(hvalue(o), n)); api_incr_top(L); lua_unlock(L); + return ttnov(L->top - 1); +} + + +LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) { + StkId t; + TValue k; + lua_lock(L); + t = index2adr(L, idx); + api_check(L, ttistable(t)); + setpvalue(&k, cast(void *, p)); + setobj2s(L, L->top, luaH_get(hvalue(t), &k)); + api_incr_top(L); + lua_unlock(L); + return ttnov(L->top - 1); } @@ -616,27 +647,21 @@ LUA_API int lua_getmetatable (lua_State *L, int objindex) { int res; lua_lock(L); obj = index2adr(L, objindex); - switch (ttype(obj)) { + switch (ttnov(obj)) { case LUA_TTABLE: mt = hvalue(obj)->metatable; break; case LUA_TUSERDATA: mt = uvalue(obj)->metatable; break; - case LUA_TROTABLE: - mt = (Table*)luaR_getmeta(rvalue(obj)); - break; default: - mt = G(L)->mt[ttype(obj)]; + mt = G(L)->mt[ttnov(obj)]; break; } if (mt == NULL) res = 0; else { - if(luaR_isrotable(mt)) - setrvalue(L->top, mt) - else - sethvalue(L, L->top, mt) + sethvalue(L, L->top, mt) api_incr_top(L); res = 1; } @@ -730,40 +755,54 @@ LUA_API void lua_rawseti (lua_State *L, int idx, int n) { } +LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) { + StkId o; + TValue k; + lua_lock(L); + api_checknelems(L, 1); + o = index2adr(L, idx); + api_check(L, ttistable(o)); + fixedstack(L); + setpvalue(&k, cast(void *, p)) + setobj2t(L, luaH_set(L, hvalue(o), &k), L->top-1); + unfixedstack(L); + luaC_barriert(L, hvalue(o), L->top-1); + L->top--; + lua_unlock(L); +} + + LUA_API int lua_setmetatable (lua_State *L, int objindex) { TValue *obj; Table *mt; - int isrometa = 0; lua_lock(L); api_checknelems(L, 1); obj = index2adr(L, objindex); api_checkvalidindex(L, obj); - if (ttisnil(L->top - 1)) + if (ttisnil(L->top - 1)) { mt = NULL; - else { - api_check(L, ttistable(L->top - 1) || ttisrotable(L->top - 1)); - if (ttistable(L->top - 1)) - mt = hvalue(L->top - 1); - else { - mt = (Table*)rvalue(L->top - 1); - isrometa = 1; - } + } else { + api_check(L, ttistable(L->top - 1)); + mt = hvalue(L->top - 1); } - switch (ttype(obj)) { + switch (ttype(obj)) { /* use basetype to retain subtypes*/ case LUA_TTABLE: { hvalue(obj)->metatable = mt; - if (mt && !isrometa) + if (mt && !isrotable(mt)) luaC_objbarriert(L, hvalue(obj), mt); break; } case LUA_TUSERDATA: { uvalue(obj)->metatable = mt; - if (mt && !isrometa) + if (mt && !isrotable(mt)) luaC_objbarrier(L, rawuvalue(obj), mt); break; } + case LUA_TISROTABLE: { /* Ignore any changes to a ROTable MT */ + break; + } default: { - G(L)->mt[ttype(obj)] = mt; + G(L)->mt[ttnov(obj)] = mt; break; } } @@ -813,7 +852,7 @@ LUA_API int lua_setfenv (lua_State *L, int idx) { #define checkresults(L,na,nr) \ api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na))) - + LUA_API void lua_call (lua_State *L, int nargs, int nresults) { StkId func; @@ -914,14 +953,14 @@ LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, } -LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) { +LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int stripping) { int status; TValue *o; lua_lock(L); api_checknelems(L, 1); o = L->top - 1; if (isLfunction(o)) - status = luaU_dump(L, clvalue(o)->l.p, writer, data, 0); + status = luaU_dump(L, clvalue(o)->l.p, writer, data, stripping); else status = 1; lua_unlock(L); @@ -929,6 +968,30 @@ LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) { } +LUA_API int lua_stripdebug (lua_State *L, int stripping){ + TValue *o = L->top - 1; + Proto *p = NULL; + int res = -1; + lua_lock(L); + api_checknelems(L, 1); + if (isLfunction(o)) { + p = clvalue(o)->l.p; + if (p && !isLFSobject(p) && (unsigned) stripping < 3 ) { + // found a valid proto to strip + res = luaG_stripdebug(L, p, stripping, 1); + } + } else if (ttisnil(L->top - 1)) { + // get or set the default strip level + if ((unsigned) stripping < 3) + G(L)->stripdefault = stripping; + res = G(L)->stripdefault; + } + L->top--; + lua_unlock(L); + return res; +} + + LUA_API int lua_status (lua_State *L) { return L->status; } @@ -1039,8 +1102,8 @@ LUA_API int lua_next (lua_State *L, int idx) { int more; lua_lock(L); t = index2adr(L, idx); - api_check(L, ttistable(t) || ttisrotable(t)); - more = ttistable(t) ? luaH_next(L, hvalue(t), L->top - 1) : luaH_next_ro(L, rvalue(t), L->top - 1); + api_check(L, ttistable(t)); + more = luaH_next(L, hvalue(t), L->top - 1); if (more) { api_incr_top(L); } @@ -1149,3 +1212,15 @@ LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { return name; } +LUA_API void lua_setegcmode ( lua_State *L, int mode, int limit) { + G(L)->egcmode = mode; + G(L)->memlimit = limit; +} + +LUA_API void lua_getegcinfo (lua_State *L, int *totals) { + if (totals) { + totals[0] = G(L)->totalbytes; + totals[1] = G(L)->estimate; + } +} + diff --git a/components/lua/lapi.h b/components/lua/lua-5.1/lapi.h similarity index 100% rename from components/lua/lapi.h rename to components/lua/lua-5.1/lapi.h diff --git a/components/lua/lauxlib.c b/components/lua/lua-5.1/lauxlib.c similarity index 83% rename from components/lua/lauxlib.c rename to components/lua/lua-5.1/lauxlib.c index fd364794..82c99c1c 100644 --- a/components/lua/lauxlib.c +++ b/components/lua/lua-5.1/lauxlib.c @@ -4,20 +4,16 @@ ** See Copyright Notice in lua.h */ -#define LUAC_CROSS_FILE - #include "lua.h" #include #include #include #include #include +#include #ifndef LUA_CROSS_COMPILER #include "esp_system.h" #include "vfs.h" -/* defined in esp_system_internal.h */ -void esp_reset_reason_set_hint(esp_reset_reason_t hint); -#else #endif /* This file uses only the official API of Lua. @@ -27,14 +23,14 @@ void esp_reset_reason_set_hint(esp_reset_reason_t hint); #define lauxlib_c #define LUA_LIB -#include "lrotable.h" +#include "lnodemcu.h" #include "lauxlib.h" #include "lgc.h" #include "ldo.h" #include "lobject.h" #include "lstate.h" -#include "legc.h" +#include "lpanic.h" #define FREELIST_REF 0 /* free list of references */ @@ -277,7 +273,7 @@ LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { return 1; } -LUALIB_API int luaL_rometatable (lua_State *L, const char* tname, void *p) { +LUALIB_API int luaL_rometatable (lua_State *L, const char* tname, const ROTable *p) { lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */ if (!lua_isnil(L, -1)) /* name already in use? */ return 0; /* leave previous value on top, but return 0 */ @@ -288,21 +284,25 @@ LUALIB_API int luaL_rometatable (lua_State *L, const char* tname, void *p) { return 1; } -LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { +LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) { void *p = lua_touserdata(L, ud); if (p != NULL) { /* value is a userdata? */ if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ - if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */ - lua_pop(L, 2); /* remove both metatables */ - return p; - } + if (!lua_rawequal(L, -1, -2)) /* not the same? */ + p = NULL; /* value is a userdata with wrong metatable */ + lua_pop(L, 2); /* remove both metatables */ + return p; } } - luaL_typerror(L, ud, tname); /* else error */ - return NULL; /* to avoid warnings */ + return NULL; /* value is not a userdata with a metatable */ } +LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { + void *p = luaL_testudata(L, ud, tname); + if (p == NULL) luaL_typerror(L, ud, tname); + return p; +} LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) { if (!lua_checkstack(L, space)) @@ -315,22 +315,6 @@ LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) { tag_error(L, narg, t); } -LUALIB_API void luaL_checkanyfunction (lua_State *L, int narg) { - if (lua_type(L, narg) != LUA_TFUNCTION && lua_type(L, narg) != LUA_TLIGHTFUNCTION) { - const char *msg = lua_pushfstring(L, "function or lightfunction expected, got %s", - luaL_typename(L, narg)); - luaL_argerror(L, narg, msg); - } -} - -LUALIB_API void luaL_checkanytable (lua_State *L, int narg) { - if (lua_type(L, narg) != LUA_TTABLE && lua_type(L, narg) != LUA_TROTABLE) { - const char *msg = lua_pushfstring(L, "table or rotable expected, got %s", - luaL_typename(L, narg)); - luaL_argerror(L, narg, msg); - } -} - LUALIB_API void luaL_checkany (lua_State *L, int narg) { if (lua_type(L, narg) == LUA_TNONE) @@ -449,7 +433,7 @@ LUALIB_API void luaI_openlib (lua_State *L, const char *libname, for (i=0; ifunc); + lua_pushcfunction(L, l->func); else lua_pushcclosure(L, l->func, nup); lua_setfield(L, -(nup+2), l->name); @@ -561,7 +545,7 @@ LUALIB_API const char *luaL_findtable (lua_State *L, int idx, lua_pushvalue(L, -2); lua_settable(L, -4); /* set new table into field */ } - else if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) { /* field has a non-table value? */ + else if (!lua_istable(L, -1)) { /* field has a non-table value? */ lua_pop(L, 2); /* remove table and value */ return fname; /* return problematic part of the name */ } @@ -703,6 +687,26 @@ LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { } +LUALIB_API void (luaL_reref) (lua_State *L, int t, int *ref) { + int reft; +/* + * If the ref is positive and the entry in table t exists then + * overwrite the value otherwise fall through to luaL_ref() + */ + if (ref) { + if (*ref >= 0) { + t = abs_index(L, t); + lua_rawgeti(L, t, *ref); + reft = lua_type(L, -1); + lua_pop(L, 1); + if (reft != LUA_TNIL) { + lua_rawseti(L, t, *ref); + return; + } + } + *ref = luaL_ref(L, t); + } +} /* ** {====================================================== @@ -710,14 +714,33 @@ LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { ** ======================================================= */ -#ifdef LUA_CROSS_COMPILER - typedef struct LoadF { int extraline; +#ifdef LUA_CROSS_COMPILER FILE *f; +#else + int f; +#endif char buff[LUAL_BUFFERSIZE]; } LoadF; +#ifdef LUA_CROSS_COMPILER +# define freopen_bin(f,fn) freopen(f,"rb",fn) +# define read_buff(b,f) fread(b, 1, sizeof (b), f) +#else +# define strerror(n) "" +#undef feof +# define feof(f) vfs_eof(f) +#undef fopen +# define fopen(f, m) vfs_open(f, m) +# define freopen_bin(fn,f) ((void) vfs_close(f), vfs_open(fn, "r")) +#undef getc +# define getc(f) vfs_getc(f) +#undef ungetc +# define ungetc(c,f) vfs_ungetc(c, f) +# define read_buff(b,f) vfs_read(f, b, sizeof (b)) +#endif + static const char *getF (lua_State *L, void *ud, size_t *size) { LoadF *lf = (LoadF *)ud; @@ -728,7 +751,7 @@ static const char *getF (lua_State *L, void *ud, size_t *size) { return "\n"; } if (feof(lf->f)) return NULL; - *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); + *size = read_buff(lf->buff, lf->f); return (*size > 0) ? lf->buff : NULL; } @@ -748,14 +771,19 @@ LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) { int c; int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ lf.extraline = 0; + if (filename == NULL) { +#ifdef LUA_CROSS_COMPILER lua_pushliteral(L, "=stdin"); lf.f = stdin; +#else + return luaL_error(L, "filename is NULL"); +#endif } else { lua_pushfstring(L, "@%s", filename); lf.f = fopen(filename, "r"); - if (lf.f == NULL) return errfile(L, "open", fnameindex); + if (!lf.f) return errfile(L, "open", fnameindex); } c = getc(lf.f); if (c == '#') { /* Unix exec. file? */ @@ -764,8 +792,8 @@ LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) { if (c == '\n') c = getc(lf.f); } if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ - lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ - if (lf.f == NULL) return errfile(L, "reopen", fnameindex); + lf.f = freopen_bin(filename, lf.f); /* reopen in binary mode */ + if (!lf.f) return errfile(L, "reopen", fnameindex); /* skip eventual `#!...' */ while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) {} @@ -773,95 +801,21 @@ LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) { } ungetc(c, lf.f); status = lua_load(L, getF, &lf, lua_tostring(L, -1)); +#ifdef LUA_CROSS_COMPILER readstatus = ferror(lf.f); if (filename) fclose(lf.f); /* close file (even in case of errors) */ if (readstatus) { lua_settop(L, fnameindex); /* ignore results from `lua_load' */ return errfile(L, "read", fnameindex); } - lua_remove(L, fnameindex); - return status; -} - #else - -#include - -typedef struct LoadFSF { - int extraline; - int f; - char buff[LUAL_BUFFERSIZE]; -} LoadFSF; - - -static const char *getFSF (lua_State *L, void *ud, size_t *size) { - LoadFSF *lf = (LoadFSF *)ud; - (void)L; - - if (L == NULL && size == NULL) // Direct mode check - return NULL; - - if (lf->extraline) { - lf->extraline = 0; - *size = 1; - return "\n"; - } - - if (vfs_eof(lf->f)) return NULL; - *size = vfs_read(lf->f, lf->buff, sizeof(lf->buff)); - - return (*size > 0) ? lf->buff : NULL; -} - - -static int errfsfile (lua_State *L, const char *what, int fnameindex) { - const char *filename = lua_tostring(L, fnameindex) + 1; - lua_pushfstring(L, "cannot %s %s", what, filename); - lua_remove(L, fnameindex); - return LUA_ERRFILE; -} - - -LUALIB_API int luaL_loadfsfile (lua_State *L, const char *filename) { - LoadFSF lf; - int status; - int c; - int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ - lf.extraline = 0; - if (filename == NULL) { - return luaL_error(L, "filename is NULL"); - } - else { - lua_pushfstring(L, "@%s", filename); - lf.f = vfs_open(filename, "r"); - if (!lf.f) return errfsfile(L, "open", fnameindex); - } - // if(fs_size(lf.f)>LUAL_BUFFERSIZE) - // return luaL_error(L, "file is too big"); - c = vfs_getc(lf.f); - if (c == '#') { /* Unix exec. file? */ - lf.extraline = 1; - while ((c = vfs_getc(lf.f)) != VFS_EOF && c != '\n') ; /* skip first line */ - if (c == '\n') c = vfs_getc(lf.f); - } - if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ - vfs_close(lf.f); - lf.f = vfs_open(filename, "r"); /* reopen in binary mode */ - if (!lf.f) return errfsfile(L, "reopen", fnameindex); - /* skip eventual `#!...' */ - while ((c = vfs_getc(lf.f)) != VFS_EOF && c != LUA_SIGNATURE[0]) - ; - lf.extraline = 0; - } - vfs_ungetc(c, lf.f); - status = lua_load(L, getFSF, &lf, lua_tostring(L, -1)); - - if (filename) vfs_close(lf.f); /* close file (even in case of errors) */ + (void) readstatus; + if (filename) vfs_close(lf.f); /* close file (even in case of errors) */ +#endif lua_remove(L, fnameindex); return status; } -#endif typedef struct LoadS { const char *s; @@ -959,56 +913,11 @@ LUALIB_API void luaL_assertfail(const char *file, int line, const char *message) #endif } -#ifndef LUA_CROSS_COMPILER -/* - * upper 28 bit have magic value 0xD1EC0DE0 - * if paniclevel is valid (i.e. matches magic value) - * lower 4 bits have paniclevel: - * 0 = no panic occurred - * 1..15 = one..fifteen subsequent panic(s) occurred - */ -static __NOINIT_ATTR uint32_t l_rtc_panic_val; - -int panic_get_nvval() { - if ((l_rtc_panic_val & 0xfffffff0) == 0xD1EC0DE0) { - return (l_rtc_panic_val & 0xf); - } - panic_clear_nvval(); - return 0; -} - -void panic_clear_nvval() { - l_rtc_panic_val = 0xD1EC0DE0; -} -#endif - -static int panic (lua_State *L) { - (void)L; /* to avoid warnings */ -#ifndef LUA_CROSS_COMPILER - uint8_t paniclevel = panic_get_nvval(); - if (paniclevel < 15) paniclevel++; - l_rtc_panic_val = 0xD1EC0DE0 | paniclevel; -#endif -#if defined(LUA_USE_STDIO) - fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n", - lua_tostring(L, -1)); -#else - luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", - lua_tostring(L, -1)); -#endif -#ifndef LUA_CROSS_COMPILER - /* call abort() directly - we don't want another reset cause to intervene */ - esp_reset_reason_set_hint(ESP_RST_PANIC); - abort(); -#endif - while (1) {} - return 0; -} LUALIB_API lua_State *luaL_newstate (void) { lua_State *L = lua_newstate(l_alloc, NULL); lua_setallocf(L, l_alloc, L); /* allocator need lua_State. */ - if (L) lua_atpanic(L, &panic); + if (L) lua_atpanic(L, lpanic); return L; } diff --git a/components/lua/lauxlib.h b/components/lua/lua-5.1/lauxlib.h similarity index 83% rename from components/lua/lauxlib.h rename to components/lua/lua-5.1/lauxlib.h index ff96906c..92cdf590 100644 --- a/components/lua/lauxlib.h +++ b/components/lua/lua-5.1/lauxlib.h @@ -8,12 +8,13 @@ #ifndef lauxlib_h #define lauxlib_h - #include "lua.h" +#ifdef LUA_LIB +#include "lnodemcu.h" +#endif #include - #if defined(LUA_COMPAT_GETN) LUALIB_API int (luaL_getn) (lua_State *L, int t); LUALIB_API void (luaL_setn) (lua_State *L, int t, int n); @@ -43,7 +44,7 @@ LUALIB_API void (luaI_openlib) (lua_State *L, const char *libname, LUALIB_API void (luaL_register) (lua_State *L, const char *libname, const luaL_Reg *l); LUALIB_API void (luaL_register_light) (lua_State *L, const char *libname, - const luaL_Reg *l); + const luaL_Reg *l); LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); LUALIB_API int (luaL_typerror) (lua_State *L, int narg, const char *tname); @@ -62,11 +63,10 @@ LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg, LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t); LUALIB_API void (luaL_checkany) (lua_State *L, int narg); -LUALIB_API void (luaL_checkanyfunction) (lua_State *L, int narg); -LUALIB_API void (luaL_checkanytable) (lua_State *L, int narg); LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); -LUALIB_API int (luaL_rometatable) (lua_State *L, const char* tname, void *p); +LUALIB_API int (luaL_rometatable) (lua_State *L, const char* tname, const ROTable *p); +LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); LUALIB_API void (luaL_where) (lua_State *L, int lvl); @@ -77,12 +77,11 @@ LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def, LUALIB_API int (luaL_ref) (lua_State *L, int t); LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); +#define luaL_unref2(l,t,r) do {luaL_unref(L, (t), (r)); r = LUA_NOREF;} while (0) +LUALIB_API void (luaL_reref) (lua_State *L, int t, int *ref); -#ifdef LUA_CROSS_COMPILER LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename); -#else -LUALIB_API int (luaL_loadfsfile) (lua_State *L, const char *filename); -#endif + LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz, const char *name); LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); @@ -112,7 +111,12 @@ LUALIB_API void luaL_assertfail(const char *file, int line, const char *message) #define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) #define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) #define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) +#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a)) #define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) +#define luaL_optunsigned(L,a,d) ((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d))) +#define luaL_checktable(L,n) luaL_checktype(L, (n), LUA_TTABLE); +#define luaL_checkfunction(L,n) luaL_checktype(L, (n), LUA_TFUNCTION); + #define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) @@ -121,7 +125,7 @@ LUALIB_API void luaL_assertfail(const char *file, int line, const char *message) (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) #else #define luaL_dofile(L, fn) \ - (luaL_loadfsfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) + (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) #endif #define luaL_dostring(L, s) \ @@ -165,6 +169,18 @@ LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); /* }====================================================== */ +LUALIB_API int (luaL_pushlfsmodules) (lua_State *L); +LUALIB_API int (luaL_pushlfsmodule) (lua_State *L); +LUALIB_API int (luaL_pushlfsdts) (lua_State *L); + +LUALIB_API void (luaL_lfsreload) (lua_State *L); +LUALIB_API int (luaL_pcallx) (lua_State *L, int narg, int nres); +LUALIB_API int (luaL_posttask) ( lua_State* L, int prio ); +#define LUA_TASK_LOW 0 +#define LUA_TASK_MEDIUM 1 +#define LUA_TASK_HIGH 2 + +/* }====================================================== */ /* compatibility with ref system */ @@ -184,7 +200,3 @@ LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); #endif -#ifndef LUA_CROSS_COMPILER -int panic_get_nvval(); -void panic_clear_nvval(); -#endif diff --git a/components/lua/lbaselib.c b/components/lua/lua-5.1/lbaselib.c similarity index 89% rename from components/lua/lbaselib.c rename to components/lua/lua-5.1/lbaselib.c index e0121522..160e9640 100644 --- a/components/lua/lbaselib.c +++ b/components/lua/lua-5.1/lbaselib.c @@ -8,17 +8,14 @@ #define lbaselib_c #define LUA_LIB -#define LUAC_CROSS_FILE #include "lua.h" + #include #include #include #include "lauxlib.h" #include "lualib.h" -#include "lrotable.h" - - /* @@ -27,6 +24,10 @@ ** model but changing `fputs' to put the strings at a proper place ** (a console window or a log file, for instance). */ +#ifdef LUA_CROSS_COMPILER +#undef puts +#define puts(s) printf("%s",s) +#endif static int luaB_print (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ int i; @@ -40,20 +41,11 @@ static int luaB_print (lua_State *L) { if (s == NULL) return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print")); -#if defined(LUA_USE_STDIO) - if (i>1) fputs("\t", stdout); - fputs(s, stdout); -#else - if (i>1) luai_writestring("\t", 1); - luai_writestring(s, strlen(s)); -#endif + if (i>1) puts("\t"); + puts(s); lua_pop(L, 1); /* pop result */ } -#if defined(LUA_USE_STDIO) - fputs("\n", stdout); -#else - luai_writeline(); -#endif + puts("\n"); return 0; } @@ -112,7 +104,7 @@ static int luaB_getmetatable (lua_State *L) { static int luaB_setmetatable (lua_State *L) { int t = lua_type(L, 2); luaL_checktype(L, 1, LUA_TTABLE); - luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE || t == LUA_TROTABLE, 2, + luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table expected"); if (luaL_getmetafield(L, 1, "__metatable")) luaL_error(L, "cannot change a protected metatable"); @@ -175,7 +167,7 @@ static int luaB_rawequal (lua_State *L) { static int luaB_rawget (lua_State *L) { - luaL_checkanytable(L, 1); + luaL_checktable(L, 1); luaL_checkany(L, 2); lua_settop(L, 2); lua_rawget(L, 1); @@ -183,7 +175,7 @@ static int luaB_rawget (lua_State *L) { } static int luaB_rawset (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); + luaL_checktable(L, 1); luaL_checkany(L, 2); luaL_checkany(L, 3); lua_settop(L, 3); @@ -233,7 +225,7 @@ static int luaB_type (lua_State *L) { static int luaB_next (lua_State *L) { - luaL_checkanytable(L, 1); + luaL_checktable(L, 1); lua_settop(L, 2); /* create a 2nd argument if there isn't one */ if (lua_next(L, 1)) return 2; @@ -245,7 +237,7 @@ static int luaB_next (lua_State *L) { static int luaB_pairs (lua_State *L) { - luaL_checkanytable(L, 1); + luaL_checktable(L, 1); lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */ lua_pushvalue(L, 1); /* state, */ lua_pushnil(L); /* and initial value */ @@ -255,7 +247,7 @@ static int luaB_pairs (lua_State *L) { static int ipairsaux (lua_State *L) { int i = luaL_checkint(L, 2); - luaL_checkanytable(L, 1); + luaL_checktable(L, 1); i++; /* next value */ lua_pushinteger(L, i); lua_rawgeti(L, 1, i); @@ -264,7 +256,7 @@ static int ipairsaux (lua_State *L) { static int luaB_ipairs (lua_State *L) { - luaL_checkanytable(L, 1); + luaL_checktable(L, 1); lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */ lua_pushvalue(L, 1); /* state, */ lua_pushinteger(L, 0); /* and initial value */ @@ -296,7 +288,7 @@ static int luaB_loadfile (lua_State *L) { #ifdef LUA_CROSS_COMPILER return load_aux(L, luaL_loadfile(L, fname)); #else - return load_aux(L, luaL_loadfsfile(L, fname)); + return load_aux(L, luaL_loadfile(L, fname)); #endif } @@ -343,7 +335,7 @@ static int luaB_dofile (lua_State *L) { #ifdef LUA_CROSS_COMPILER if (luaL_loadfile(L, fname) != 0) lua_error(L); #else - if (luaL_loadfsfile(L, fname) != 0) lua_error(L); + if (luaL_loadfile(L, fname) != 0) lua_error(L); #endif lua_call(L, 0, LUA_MULTRET); return lua_gettop(L) - n; @@ -462,29 +454,24 @@ static int luaB_newproxy (lua_State *L) { return 1; } -#include "lrotable.h" - -LROT_EXTERN(lua_rotable_base); /* - * Separate ROTables are used for the base functions and library ROTables, with - * the base functions ROTable declared below. The library ROTable is chained - * from this using its __index meta-method. - * - * ESP builds use specific linker directives to marshal all the ROTable entries - * for the library modules into a single ROTable in the PSECT ".lua_rotable". - * This is not practical on Posix builds using a standard GNU link, so the - * equivalent ROTable for the core libraries defined in linit.c for the cross- - * compiler build. - */ - -LROT_EXTERN(lua_rotables); - -LROT_PUBLIC_BEGIN(base_func_meta) - LROT_TABENTRY( __index, lua_rotables ) -LROT_END(base_func, base_func_meta, LROT_MASK_INDEX) - -LROT_PUBLIC_BEGIN(base_func) +** ESP builds use specific linker directives to marshal all the ROTable entries +** for the library modules including the base library into an entry vector in +** the PSECT ".lua_rotable" including the base library entries; this is bound +** into a ROTable in linit.c which then hooked into the __index metaentry for +** _G so that base library and ROM tables are directly resolved through _G. +** +** The host-based luac.cross builds which must use a standard GNU link or +** MSVC so this linker-specfic assembly approach can't be used. In this case +** luaopen_base returns a base_func ROTable so a two cascade resolution. See +** description in init.c for further details. +*/ +#ifdef LUA_CROSS_COMPILER +LROT_BEGIN(base_func, NULL, 0) +#else +LROT_ENTRIES_IN_SECTION(base_func, rotable) +#endif LROT_FUNCENTRY(assert, luaB_assert) LROT_FUNCENTRY(collectgarbage, luaB_collectgarbage) LROT_FUNCENTRY(dofile, luaB_dofile) @@ -509,13 +496,11 @@ LROT_PUBLIC_BEGIN(base_func) LROT_FUNCENTRY(type, luaB_type) LROT_FUNCENTRY(unpack, luaB_unpack) LROT_FUNCENTRY(xpcall, luaB_xpcall) - LROT_TABENTRY(__metatable, base_func_meta) -LROT_END(base_func, base_func_meta, LROT_MASK_INDEX) - -LROT_BEGIN(G_meta) - LROT_TABENTRY( __index, base_func ) -LROT_END(G_meta, NULL, 0) - +#ifdef LUA_CROSS_COMPILER +LROT_END(base_func, NULL, 0) +#else +LROT_BREAK(base_func) +#endif /* ** {====================================================== @@ -645,14 +630,14 @@ static int luaB_corunning (lua_State *L) { return 1; } -LROT_PUBLIC_BEGIN(co_funcs) +LROT_BEGIN(co_funcs, NULL, 0) LROT_FUNCENTRY( create, luaB_cocreate ) LROT_FUNCENTRY( resume, luaB_coresume ) LROT_FUNCENTRY( running, luaB_corunning ) LROT_FUNCENTRY( status, luaB_costatus ) LROT_FUNCENTRY( wrap, luaB_cowrap ) LROT_FUNCENTRY( yield, luaB_yield ) -LROT_END (co_funcs, NULL, 0) +LROT_END(co_funcs, NULL, 0) /* }====================================================== */ @@ -661,19 +646,13 @@ static void auxopen (lua_State *L, const char *name, lua_CFunction f, lua_CFunction u) { lua_pushcfunction(L, u); lua_pushcclosure(L, f, 1); - lua_setfield(L, -2, name); + lua_setglobal(L, name); } -static void base_open (lua_State *L) { - /* set global _G */ +extern LROT_TABLE(rotables); +LUALIB_API int luaopen_base (lua_State *L) { lua_pushvalue(L, LUA_GLOBALSINDEX); - lua_setglobal(L, "_G"); - - /* open lib into global table */ - luaL_register_light(L, "_G", &((luaL_Reg) {0})); - lua_pushrotable(L, LROT_TABLEREF(G_meta)); - lua_setmetatable(L, LUA_GLOBALSINDEX); - + lua_settable(L, LUA_GLOBALSINDEX); /* set global _G */ lua_pushliteral(L, LUA_VERSION); lua_setglobal(L, "_VERSION"); /* set global _VERSION */ /* `ipairs' and `pairs' need auxliliary functions as upvalues */ @@ -681,16 +660,15 @@ static void base_open (lua_State *L) { auxopen(L, "pairs", luaB_pairs, luaB_next); /* `newproxy' needs a weaktable as upvalue */ lua_createtable(L, 0, 1); /* new table `w' */ - lua_pushvalue(L, -1); /* `w' will be its own metatable */ - lua_setmetatable(L, -2); lua_pushliteral(L, "kv"); lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */ - lua_pushcclosure(L, luaB_newproxy, 1); + lua_pushvalue(L, -1); /* `w' will be its own metatable */ + lua_setmetatable(L, -2); + lua_pushcclosure(L, luaB_newproxy, 1); /* Upval is table w */ lua_setglobal(L, "newproxy"); /* set global `newproxy' */ -} - - -LUALIB_API int luaopen_base (lua_State *L) { - base_open(L); - return 1; + lua_pushrotable(L, LROT_TABLEREF(rotables)); + lua_setglobal(L, "__index"); + lua_pushvalue(L, LUA_GLOBALSINDEX); /* _G is its own metatable */ + lua_setmetatable(L, LUA_GLOBALSINDEX); + return 0; } diff --git a/components/lua/lcode.c b/components/lua/lua-5.1/lcode.c similarity index 98% rename from components/lua/lcode.c rename to components/lua/lua-5.1/lcode.c index 5fa535ce..508e865c 100644 --- a/components/lua/lcode.c +++ b/components/lua/lua-5.1/lcode.c @@ -7,7 +7,6 @@ #define lcode_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -781,8 +780,6 @@ void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) { } -#ifdef LUA_OPTIMIZE_DEBUG - /* * Attempted to write to last (null terminator) byte of lineinfo, so need * to grow the lineinfo vector and extend the fill bytes @@ -829,10 +826,8 @@ static void generateInfoDeltaLine(FuncState *fs, int line) { fs->lastlineOffset = p - fs->f->packedlineinfo - 1; #undef addDLbyte } -#endif void luaK_fixline (FuncState *fs, int line) { -#ifdef LUA_OPTIMIZE_DEBUG /* The fixup line can be the same as existing one and in this case there's nothing to do */ if (line != fs->lastline) { /* first remove the current line reference */ @@ -863,9 +858,6 @@ void luaK_fixline (FuncState *fs, int line) { /* Then add the new line reference */ generateInfoDeltaLine(fs, line); } -#else - fs->f->lineinfo[fs->pc - 1] = line; -#endif } @@ -877,7 +869,6 @@ static int luaK_code (FuncState *fs, Instruction i, int line) { MAX_INT, "code size overflow"); f->code[fs->pc] = i; /* save corresponding line information */ -#ifdef LUA_OPTIMIZE_DEBUG /* note that frst time fs->lastline==0 through, so the else branch is taken */ if (fs->pc == fs->lineinfoLastPC+1) { if (line == fs->lastline && f->packedlineinfo[fs->lastlineOffset] < INFO_MAX_LINECNT) { @@ -891,11 +882,6 @@ static int luaK_code (FuncState *fs, Instruction i, int line) { luaK_fixline(fs,line); } fs->lineinfoLastPC = fs->pc; -#else - luaM_growvector(fs->L, f->lineinfo, fs->pc, f->sizelineinfo, int, - MAX_INT, "code size overflow"); - f->lineinfo[fs->pc] = line; -#endif return fs->pc++; } diff --git a/components/lua/lcode.h b/components/lua/lua-5.1/lcode.h similarity index 100% rename from components/lua/lcode.h rename to components/lua/lua-5.1/lcode.h diff --git a/components/lua/ldblib.c b/components/lua/lua-5.1/ldblib.c similarity index 89% rename from components/lua/ldblib.c rename to components/lua/lua-5.1/ldblib.c index a33c29fc..392431ce 100644 --- a/components/lua/ldblib.c +++ b/components/lua/lua-5.1/ldblib.c @@ -7,7 +7,6 @@ #define ldblib_c #define LUA_LIB -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -18,8 +17,6 @@ #include "lualib.h" #include "lstring.h" #include "lflash.h" -#include "lrotable.h" -#include "sdkconfig.h" static int db_getregistry (lua_State *L) { @@ -28,34 +25,16 @@ static int db_getregistry (lua_State *L) { } static int db_getstrings (lua_State *L) { - size_t i,n=0; - stringtable *tb; - GCObject *o; -#ifndef LUA_CROSS_COMPILER - const char *opt = lua_tolstring (L, 1, &n); - if (n==3 && memcmp(opt, "ROM", 4) == 0) { - if (G(L)->ROstrt.hash == NULL) - return 0; - tb = &G(L)->ROstrt; - } - else -#endif - tb = &G(L)->strt; - lua_settop(L, 0); - lua_createtable(L, tb->nuse, 0); /* create table the same size as the strt */ - for (i=0, n=1; isize; i++) { - for(o = tb->hash[i]; o; o=o->gch.next) { - TString *ts =cast(TString *, o); - lua_pushnil(L); - setsvalue2s(L, L->top-1, ts); - lua_rawseti(L, -2, n++); /* enumerate the strt, adding elements */ + static const char *const opts[] = {"RAM","ROM",NULL}; + int opt = luaL_checkoption(L, 1, "RAM", opts); + if (lua_pushstringsarray(L, opt)) { + if(lua_getglobal(L, "table") == LUA_TTABLE) { + lua_getfield(L, -1, "sort"); /* look up table.sort function */ + lua_replace(L, -2); /* dump the table table */ + lua_pushvalue(L, -2); /* duplicate the strt_copy ref */ + lua_call(L, 1, 0); /* table.sort(strt_copy) */ } } - lua_getfield(L, LUA_GLOBALSINDEX, "table"); - lua_getfield(L, -1, "sort"); /* look up table.sort function */ - lua_replace(L, -2); /* dump the table table */ - lua_pushvalue(L, -2); /* duplicate the strt_copy ref */ - lua_call(L, 1, 0); /* table.sort(strt_copy) */ return 1; } @@ -144,7 +123,7 @@ static int db_getinfo (lua_State *L) { return 1; } } - else if (lua_isfunction(L, arg+1) || lua_islightfunction(L, arg+1)) { + else if (lua_isfunction(L, arg+1)) { lua_pushfstring(L, ">%s", options); options = lua_tostring(L, -1); lua_pushvalue(L, arg+1); @@ -302,7 +281,7 @@ static int db_sethook (lua_State *L) { } else { const char *smask = luaL_checkstring(L, arg+2); - luaL_checkanyfunction(L, arg+1); + luaL_checkfunction(L, arg+1); count = luaL_optint(L, arg+3, 0); func = hookf; mask = makemask(smask, count); } @@ -367,7 +346,7 @@ static int db_debug (lua_State *L) { #define LEVELS1 12 /* size of the first part of the stack */ #define LEVELS2 10 /* size of the second part of the stack */ -static int db_errorfb (lua_State *L) { +static int debug_errorfb (lua_State *L) { int level; int firstpart = 1; /* still before eventual `...' */ int arg; @@ -419,7 +398,7 @@ static int db_errorfb (lua_State *L) { return 1; } -LROT_PUBLIC_BEGIN(dblib) +LROT_BEGIN(dblib, NULL, 0) #ifndef CONFIG_LUA_BUILTIN_DEBUG_MINIMAL #if defined(LUA_CROSS_COMPILER) LROT_FUNCENTRY( debug, db_debug ) @@ -440,7 +419,7 @@ LROT_PUBLIC_BEGIN(dblib) LROT_FUNCENTRY( setmetatable, db_setmetatable ) LROT_FUNCENTRY( setupvalue, db_setupvalue ) #endif - LROT_FUNCENTRY( traceback, db_errorfb ) + LROT_FUNCENTRY( traceback, debug_errorfb ) LROT_END(dblib, NULL, 0) LUALIB_API int luaopen_debug (lua_State *L) { diff --git a/components/lua/ldebug.c b/components/lua/lua-5.1/ldebug.c similarity index 93% rename from components/lua/ldebug.c rename to components/lua/lua-5.1/ldebug.c index 8562a135..57bd376b 100644 --- a/components/lua/ldebug.c +++ b/components/lua/lua-5.1/ldebug.c @@ -7,7 +7,6 @@ #define ldebug_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -183,8 +182,7 @@ static void info_tailcall (lua_Debug *ar) { # define INFO_DELTA_7BITS 0x7F # define INFO_MAX_LINECNT 126 - Table *t = luaH_new(L, 0, 0); -#ifdef LUA_OPTIMIZE_DEBUG + Table *t = luaH_new(L, 0, 0); int line = 0; unsigned char *p = f->l.p->packedlineinfo; if (p) { @@ -204,18 +202,11 @@ static void info_tailcall (lua_Debug *ar) { setbvalue(luaH_setnum(L, t, line), 1); } } -#else - int *lineinfo = f->l.p->lineinfo; - int i; - for (i=0; il.p->sizelineinfo; i++) - setbvalue(luaH_setnum(L, t, lineinfo[i]), 1); -#endif - sethvalue(L, L->top, t); + sethvalue(L, L->top, t); } incr_top(L); } -#ifdef LUA_OPTIMIZE_DEBUG /* * This may seem expensive but this is only accessed frequently in traceexec * and the while loop will be executed roughly half the number of non-blank @@ -250,19 +241,18 @@ int luaG_getline (const Proto *f, int pc) { static int stripdebug (lua_State *L, Proto *f, int level) { int len = 0, sizepackedlineinfo; - TString* dummy; switch (level) { - case 3: - sizepackedlineinfo = strlen(cast(char *, f->packedlineinfo))+1; - f->packedlineinfo = luaM_freearray(L, f->packedlineinfo, sizepackedlineinfo, unsigned char); - len += sizepackedlineinfo; - // fall-through case 2: - len += f->sizelocvars * (sizeof(struct LocVar) + sizeof(dummy->tsv) + sizeof(struct LocVar *)); + if (f->packedlineinfo) { + sizepackedlineinfo = strlen(cast(char *, f->packedlineinfo))+1; + f->packedlineinfo = luaM_freearray(L, f->packedlineinfo, sizepackedlineinfo, unsigned char); + len += sizepackedlineinfo; + } + // fall-through + case 1: f->locvars = luaM_freearray(L, f->locvars, f->sizelocvars, struct LocVar); f->upvalues = luaM_freearray(L, f->upvalues, f->sizeupvalues, TString *); - len += f->sizelocvars * (sizeof(struct LocVar) + sizeof(dummy->tsv) + sizeof(struct LocVar *)) + - f->sizeupvalues * (sizeof(dummy->tsv) + sizeof(TString *)); + len += f->sizelocvars*sizeof(struct LocVar) + f->sizeupvalues*sizeof(TString *); f->sizelocvars = 0; f->sizeupvalues = 0; } @@ -278,7 +268,6 @@ LUA_API int luaG_stripdebug (lua_State *L, Proto *f, int level, int recv){ len += stripdebug (L, f, level); return len; } -#endif static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, @@ -328,21 +317,21 @@ LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { lua_lock(L); if (*what == '>') { StkId func = L->top - 1; - luai_apicheck(L, ttisfunction(func) || ttislightfunction(func)); + luai_apicheck(L, ttisfunction(func)); what++; /* skip the '>' */ - if (ttisfunction(func)) - f = clvalue(func); - else + if (ttislightfunction(func)) plight = fvalue(func); + else + f = clvalue(func); L->top--; /* pop function */ } else if (ar->i_ci != 0) { /* no tail call? */ ci = L->base_ci + ar->i_ci; - lua_assert(ttisfunction(ci->func) || ttislightfunction(ci->func)); - if (ttisfunction(ci->func)) - f = clvalue(ci->func); - else + lua_assert(ttisfunction(ci->func)); + if (ttislightfunction(ci->func)) plight = fvalue(ci->func); + else + f = clvalue(ci->func); } status = auxgetinfo(L, what, ar, f, plight, ci); if (strchr(what, 'f')) { @@ -381,9 +370,6 @@ static int precheck (const Proto *pt) { check(!(pt->is_vararg & VARARG_NEEDSARG) || (pt->is_vararg & VARARG_HASARG)); check(pt->sizeupvalues <= pt->nups); -#ifndef LUA_OPTIMIZE_DEBUG - check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0); -#endif check(pt->sizecode > 0 && GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN); return 1; } @@ -670,7 +656,7 @@ static int isinstack (CallInfo *ci, const TValue *o) { void luaG_typeerror (lua_State *L, const TValue *o, const char *op) { const char *name = NULL; - const char *t = luaT_typenames[ttype(o)]; + const char *t = luaT_typenames[ttnov(o)]; const char *kind = (isinstack(L->ci, o)) ? getobjname(L, L->ci, cast_int(o - L->base), &name) : NULL; @@ -698,8 +684,8 @@ void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) { int luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { - const char *t1 = luaT_typenames[ttype(p1)]; - const char *t2 = luaT_typenames[ttype(p2)]; + const char *t1 = luaT_typenames[ttnov(p1)]; + const char *t2 = luaT_typenames[ttnov(p2)]; if (t1[2] == t2[2]) luaG_runerror(L, "attempt to compare two %s values", t1); else @@ -722,7 +708,7 @@ static void addinfo (lua_State *L, const char *msg) { void luaG_errormsg (lua_State *L) { if (L->errfunc != 0) { /* is there an error handling function? */ StkId errfunc = restorestack(L, L->errfunc); - if (!ttisfunction(errfunc) && !ttislightfunction(errfunc)) luaD_throw(L, LUA_ERRERR); + if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR); setobjs2s(L, L->top, L->top - 1); /* move argument */ setobjs2s(L, L->top - 1, errfunc); /* push function */ incr_top(L); diff --git a/components/lua/ldebug.h b/components/lua/lua-5.1/ldebug.h similarity index 91% rename from components/lua/ldebug.h rename to components/lua/lua-5.1/ldebug.h index 1da88361..8bffa0c8 100644 --- a/components/lua/ldebug.h +++ b/components/lua/lua-5.1/ldebug.h @@ -13,7 +13,6 @@ #define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1) -#ifdef LUA_OPTIMIZE_DEBUG # include "lvm.h" # define getline(f,pc) (((f)->packedlineinfo) ? luaG_getline((f), pc) : 0) # define INFO_FILL_BYTE 0x7F @@ -23,9 +22,6 @@ # define INFO_DELTA_7BITS 0x7F # define INFO_MAX_LINECNT 126 # define lineInfoTop(fs) ((fs)->f->packedlineinfo + (fs)->lastlineOffset) -#else -# define getline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0) -#endif #define resethookcount(L) (L->hookcount = L->basehookcount) @@ -41,9 +37,7 @@ LUAI_FUNC void luaG_runerror (lua_State *L, const char *fmt, ...); LUAI_FUNC void luaG_errormsg (lua_State *L); LUAI_FUNC int luaG_checkcode (const Proto *pt); LUAI_FUNC int luaG_checkopenop (Instruction i); -#ifdef LUA_OPTIMIZE_DEBUG LUAI_FUNC int luaG_getline (const Proto *f, int pc); LUAI_FUNC int luaG_stripdebug (lua_State *L, Proto *f, int level, int recv); -#endif #endif diff --git a/components/lua/ldo.c b/components/lua/lua-5.1/ldo.c similarity index 98% rename from components/lua/ldo.c rename to components/lua/lua-5.1/ldo.c index 7694ab8f..f002b9ba 100644 --- a/components/lua/ldo.c +++ b/components/lua/lua-5.1/ldo.c @@ -8,7 +8,6 @@ #define ldo_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -106,7 +105,7 @@ void luaD_throw (lua_State *L, int errcode) { lua_unlock(L); G(L)->panic(L); } - // exit(EXIT_FAILURE); + // c_exit(EXIT_FAILURE); } } @@ -254,13 +253,13 @@ static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { return base; } - static StkId tryfuncTM (lua_State *L, StkId func) { const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); StkId p; ptrdiff_t funcr = savestack(L, func); - if (!ttisfunction(tm)) + if (!ttisfunction(tm)) { luaG_typeerror(L, func, "call"); + } /* Open a hole inside the stack at `func' */ for (p = L->top; p > func; p--) setobjs2s(L, p, p-1); incr_top(L); @@ -279,10 +278,10 @@ static StkId tryfuncTM (lua_State *L, StkId func) { int luaD_precall (lua_State *L, StkId func, int nresults) { ptrdiff_t funcr; LClosure *cl = NULL; - if (!ttisfunction(func) && !ttislightfunction(func)) /* `func' is not a function? */ + if (!ttisfunction(func)) /* `func' is not a function? */ func = tryfuncTM(L, func); /* check the `function' tag method */ funcr = savestack(L, func); - if (ttisfunction(func)) + if (!ttislightfunction(func)) cl = &clvalue(func)->l; L->ci->savedpc = L->savedpc; if (cl && !cl->isC) { /* Lua function? prepare its call */ @@ -332,10 +331,10 @@ int luaD_precall (lua_State *L, StkId func, int nresults) { if (L->hookmask & LUA_MASKCALL) luaD_callhook(L, LUA_HOOKCALL, -1); lua_unlock(L); - if (ttisfunction(ci->func)) - n = (*curr_func(L)->c.f)(L); /* do the actual call */ - else + if (ttislightfunction(ci->func)) n = ((lua_CFunction)fvalue(ci->func))(L); /* do the actual call */ + else + n = (*curr_func(L)->c.f)(L); /* do the actual call */ lua_lock(L); if (n < 0) /* yielding? */ return PCRYIELD; @@ -384,7 +383,7 @@ int luaD_poscall (lua_State *L, StkId firstResult) { ** The arguments are on the stack, right after the function. ** When returns, all the results are on the stack, starting at the original ** function position. -*/ +*/ void luaD_call (lua_State *L, StkId func, int nResults) { if (++L->nCcalls >= LUAI_MAXCCALLS) { if (L->nCcalls == LUAI_MAXCCALLS) diff --git a/components/lua/ldo.h b/components/lua/lua-5.1/ldo.h similarity index 100% rename from components/lua/ldo.h rename to components/lua/lua-5.1/ldo.h diff --git a/components/lua/ldump.c b/components/lua/lua-5.1/ldump.c similarity index 97% rename from components/lua/ldump.c rename to components/lua/lua-5.1/ldump.c index db2a0362..5ff5530f 100644 --- a/components/lua/ldump.c +++ b/components/lua/lua-5.1/ldump.c @@ -6,7 +6,6 @@ #define ldump_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -229,7 +228,6 @@ static void DumpDebug(const Proto* f, DumpState* D) { int i,n; -#ifdef LUA_OPTIMIZE_DEBUG n = (D->strip || f->packedlineinfo == NULL) ? 0: strlen(cast(char *,f->packedlineinfo))+1; DumpInt(n,D); Align4(D); @@ -237,15 +235,6 @@ static void DumpDebug(const Proto* f, DumpState* D) { DumpBlock(f->packedlineinfo, n, D); } -#else - n= (D->strip) ? 0 : f->sizelineinfo; - DumpInt(n,D); - Align4(D); - for (i=0; ilineinfo[i],D); - } - #endif n= (D->strip) ? 0 : f->sizelocvars; DumpInt(n,D); diff --git a/components/lua/lflash.c b/components/lua/lua-5.1/lflash.c similarity index 80% rename from components/lua/lflash.c rename to components/lua/lua-5.1/lflash.c index 116ee812..a70114f3 100644 --- a/components/lua/lflash.c +++ b/components/lua/lua-5.1/lflash.c @@ -5,7 +5,6 @@ #define lflash_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include "lobject.h" @@ -24,6 +23,8 @@ #include #include +#include "lfs.h" + /* * Flash memory is a fixed memory addressable block that is serially allocated by the * luac build process and the out image can be downloaded into SPIFSS and loaded into @@ -72,7 +73,7 @@ struct OUTPUT { outBlock buffer; int ndx; uint32_t crc; - int (*fullBlkCB) (void); + void (*fullBlkCB) (void); int flashLen; int flagsLen; int flagsNdx; @@ -80,12 +81,6 @@ struct OUTPUT { const char *error; } *out; - -#ifdef CONFIG_NODEMCU_EMBEDDED_LFS_SIZE - extern const char lua_flash_store_reserved[0]; -#endif - - #ifdef NODE_DEBUG extern void printf(const char *fmt, ...) __attribute__ ((format (printf, 1, 2))); void dumpStrt(stringtable *tb, const char *type) { @@ -97,9 +92,8 @@ void dumpStrt(stringtable *tb, const char *type) { for (i=0; isize; i++) for(o = tb->hash[i], j=0; o; (o=o->gch.next), j++ ) { TString *ts =cast(TString *, o); - NODE_DBG("%5d %5d %08x %08x %5d %1s %s\n", - i, j, (size_t) ts, ts->tsv.hash, ts->tsv.len, - ts_isreadonly(ts) ? "R" : " ", getstr(ts)); + NODE_DBG("%5d %5d %08x %08x %5d %s\n", + i, j, (size_t) ts, ts->tsv.hash, ts->tsv.len, getstr(ts)); } } @@ -117,17 +111,25 @@ LUA_API void dumpStrings(lua_State *L) { * writes are suppressed if the global writeToFlash is false. This is used in * phase I where the pass is used to size the structures in flash. */ -static void flashSetPosition(uint32_t offset){ - NODE_DBG("flashSetPosition(%04x)\n", offset); - curOffset = offset; +static const char *flashPosition(void){ + return flashAddr + curOffset; } -static void flashBlock(const void* b, size_t size) { - NODE_DBG("flashBlock((%04x),%08x,%04x)\n", curOffset,(unsigned int)b,size); +static const char *flashSetPosition(uint32_t offset){ + NODE_DBG("flashSetPosition(%04x)\n", offset); + curOffset = offset; + return flashPosition(); +} + + +static const char *flashBlock(const void* b, size_t size) { + const void *cur = flashPosition(); + NODE_DBG("flashBlock((%04x),%p,%04x)\n", curOffset,b,size); lua_assert(ALIGN_BITS(b) == 0 && ALIGN_BITS(size) == 0); platform_flash_write(b, flashAddrPhys+curOffset, size); curOffset += size; + return cur; } @@ -142,11 +144,11 @@ static void flashErase(uint32_t start, uint32_t end){ static int loadLFS (lua_State *L); static int loadLFSgc (lua_State *L); -static int procFirstPass (void); +static void procFirstPass (void); #endif /* ===================================================================================== - * luaN_init(), luaN_reload_reboot() and luaN_index() are exported via lflash.h. + * luaN_init() is exported via lflash.h. * The first is the startup hook used in lstate.c and the last two are * implementations of the node.flash API calls. */ @@ -155,40 +157,15 @@ static int procFirstPass (void); * Hook in lstate.c:f_luaopen() to set up ROstrt and ROpvmain if needed */ LUAI_FUNC void luaN_init (lua_State *L) { -#ifdef CONFIG_NODEMCU_EMBEDDED_LFS_SIZE - flashSize = CONFIG_NODEMCU_EMBEDDED_LFS_SIZE; - flashAddr = lua_flash_store_reserved; - flashAddrPhys = spi_flash_cache2phys(lua_flash_store_reserved); - if (flashAddrPhys == SPI_FLASH_CACHE2PHYS_FAIL) { - NODE_ERR("spi_flash_cache2phys failed\n"); + lfs_location_info_t lfs_loc; + if (!lfs_get_location(&lfs_loc)) return; - } -#else - const esp_partition_t *part = esp_partition_find_first( - PLATFORM_PARTITION_TYPE_NODEMCU, - PLATFORM_PARTITION_SUBTYPE_NODEMCU_LFS, - NULL); - if (!part) - return; // Nothing to do if the size is zero - flashSize = part->size; // in bytes - flashAddrPhys = part->address; - flashAddr = spi_flash_phys2cache(flashAddrPhys, SPI_FLASH_MMAP_DATA); - if (!flashAddr) { - spi_flash_mmap_handle_t ignored; - esp_err_t err = spi_flash_mmap( - flashAddrPhys, flashSize, SPI_FLASH_MMAP_DATA, - cast(const void **, &flashAddr), &ignored); - if (err != ESP_OK) { - NODE_ERR("Unable to access LFS partition - is it 64kB aligned as it needs to be?\n"); - return; - } - } -#endif - G(L)->LFSsize = flashSize; - flashSector = platform_flash_get_sector_of_address(flashAddrPhys); - - FlashHeader *fh = cast(FlashHeader *, flashAddr); + G(L)->LFSsize = flashSize = lfs_loc.size; + flashAddr = lfs_loc.addr_mem; + flashAddrPhys = lfs_loc.addr_phys; + flashSector = platform_flash_get_sector_of_address(lfs_loc.addr_phys); + FlashHeader *fh = cast(FlashHeader *, lfs_loc.addr_mem); curOffset = 0; /* @@ -204,15 +181,15 @@ LUAI_FUNC void luaN_init (lua_State *L) { } if ((fh->flash_sig & (~FLASH_SIG_ABSOLUTE)) != FLASH_SIG ) { - NODE_ERR("Flash sig not correct: %u vs %u\n", + NODE_ERR("LFS sig not correct: 0x%x vs expected 0x%x\n", fh->flash_sig & (~FLASH_SIG_ABSOLUTE), FLASH_SIG); return; } if (fh->pROhash == ALL_SET || ((fh->mainProto - cast(FlashAddr, fh)) >= fh->flash_size)) { - NODE_ERR("Flash size check failed: %x vs 0xFFFFFFFF; size: %u\n", - fh->mainProto - cast(FlashAddr, fh), fh->flash_size); + NODE_ERR("Flash size check failed: 0x%08x vs 0xFFFFFFFF; 0x%08x >= 0x%08x\n", + fh->pROhash, fh->mainProto - cast(FlashAddr, fh), fh->flash_size); return; } @@ -222,23 +199,24 @@ LUAI_FUNC void luaN_init (lua_State *L) { G(L)->ROpvmain = cast(Proto *,fh->mainProto); } +/* luaL_lfsreload() is exported via lauxlib.h */ + /* * Library function called by node.flashreload(filename). */ -LUALIB_API int luaN_reload_reboot (lua_State *L) { +LUALIB_API void luaL_lfsreload (lua_State *L) { #ifdef CONFIG_NODEMCU_EMBEDDED_LFS_SIZE // Updating the LFS section is disabled for now because any changes to the // image requires updating its checksum to prevent boot failure. lua_pushstring(L, "Not allowed to write to LFS section"); - return 1; + return; #else - // luaL_dbgbreak(); const char *fn = lua_tostring(L, 1), *msg = ""; int status; if (G(L)->LFSsize == 0) { lua_pushstring(L, "No LFS partition allocated"); - return 1; + return; } @@ -270,7 +248,7 @@ LUALIB_API int luaN_reload_reboot (lua_State *L) { lua_cpcall(L, &loadLFSgc, NULL); lua_settop(L, 0); lua_pushstring(L, msg); - return 1; + return; } if (status == 0) { @@ -290,62 +268,22 @@ LUALIB_API int luaN_reload_reboot (lua_State *L) { NODE_ERR("%s\n", msg); esp_restart(); - return 0; #endif // CONFIG_NODEMCU_EMBEDDED_LFS_SIZE } -/* - * If the arg is a valid LFS module name then return the LClosure - * pointing to it. Otherwise return: - * - The Unix time that the LFS was built - * - The base address and length of the LFS - * - An array of the module names in the LFS - */ -LUAI_FUNC int luaN_index (lua_State *L) { - int n = lua_gettop(L); - - /* Return nil + the LFS base address if the LFS size > 0 and it isn't loaded */ - if (!(G(L)->ROpvmain)) { - lua_settop(L, 0); - lua_pushnil(L); - if (G(L)->LFSsize) { - lua_pushinteger(L, (lua_Integer) flashAddr); - lua_pushinteger(L, flashAddrPhys); - lua_pushinteger(L, G(L)->LFSsize); - return 4; - } else { - return 1; - } - } - - /* Push the LClosure of the LFS index function */ - Closure *cl = luaF_newLclosure(L, 0, hvalue(gt(L))); - cl->l.p = G(L)->ROpvmain; - lua_settop(L, n+1); - setclvalue(L, L->top-1, cl); - - /* Move it infront of the arguments and call the index function */ - lua_insert(L, 1); - lua_call(L, n, LUA_MULTRET); - - /* Return it if the response if a single value (the function) */ - if (lua_gettop(L) == 1) - return 1; - - lua_assert(lua_gettop(L) == 2); - - /* Otherwise add the base address of the LFS, and its size bewteen the */ - /* Unix time and the module list, then return all 4 params. */ - lua_pushinteger(L, (lua_Integer) flashAddr); - lua_insert(L, 2); - lua_pushinteger(L, flashAddrPhys); - lua_insert(L, 3); - lua_pushinteger(L, cast(FlashHeader *, flashAddr)->flash_size); - lua_insert(L, 4); - return 5; +LUA_API void lua_getlfsconfig (lua_State *L, intptr_t *config) { + if (!config) + return; + config[0] = (intptr_t) flashAddr; /* LFS region mapped address */ + config[1] = flashAddrPhys; /* LFS region base flash address */ + config[2] = G(L)->LFSsize; /* LFS region actual size */ + config[3] = (G(L)->ROstrt.hash) ? cast(FlashHeader *, flashAddr)->flash_size : 0; + /* LFS region used */ + config[4] = 0; /* Not used in Lua 5.1 */ } + #ifndef CONFIG_NODEMCU_EMBEDDED_LFS_SIZE /* ===================================================================================== * The following routines use my uzlib which was based on pfalcon's inflate and @@ -440,7 +378,7 @@ static uint8_t recall_byte (uint32_t offset) { * - Once the flags array is in-buffer this is also captured. * This logic is slightly complicated by the last buffer is typically short. */ -int procFirstPass (void) { +void procFirstPass (void) { int len = (out->ndx % WRITE_BLOCKSIZE) ? out->ndx % WRITE_BLOCKSIZE : WRITE_BLOCKSIZE; if (out->ndx <= WRITE_BLOCKSIZE) { @@ -475,12 +413,10 @@ int procFirstPass (void) { memcpy(out->flags + out->flagsNdx, out->block[0]->byte + start, len - start); out->flagsNdx += (len -start) / WORDSIZE; /* flashLen and len are word aligned */ } - - return 1; } -int procSecondPass (void) { +void procSecondPass (void) { /* * The length rules are different for the second pass since this only processes * upto the flashLen and not the full image. This also works in word units. @@ -518,12 +454,10 @@ int procSecondPass (void) { flashBlock(&out->flash_sig, WORDSIZE); out->fullBlkCB = NULL; } - - return 1; } /* - * loadLFS)() is protected called from luaN_reload_reboot so that it can recover + * loadLFS)() is protected called from luaL_lfsreload so that it can recover * from out of memory and other thrown errors. loadLFSgc() GCs any resources. */ static int loadLFS (lua_State *L) { @@ -548,7 +482,7 @@ static int loadLFS (lua_State *L) { in->len = vfs_size(in->fd); if (in->len <= 200 || /* size of an empty luac output */ vfs_lseek(in->fd, in->len-4, VFS_SEEK_SET) != in->len-4 || - vfs_read(in->fd, &out->len, sizeof(uint)) != sizeof(uint)) + vfs_read(in->fd, &out->len, sizeof(uint32_t)) != sizeof(uint32_t)) flash_error("read error on LFS image file"); vfs_lseek(in->fd, 0, VFS_SEEK_SET); diff --git a/components/lua/lflash.h b/components/lua/lua-5.1/lflash.h similarity index 90% rename from components/lua/lflash.h rename to components/lua/lua-5.1/lflash.h index 722d0f36..b2a17b51 100644 --- a/components/lua/lflash.h +++ b/components/lua/lua-5.1/lflash.h @@ -43,8 +43,5 @@ typedef struct { } FlashHeader; LUAI_FUNC void luaN_init (lua_State *L); -LUAI_FUNC int luaN_flashSetup (lua_State *L); -LUAI_FUNC int luaN_reload_reboot (lua_State *L); -LUAI_FUNC int luaN_index (lua_State *L); #endif diff --git a/components/lua/lfunc.c b/components/lua/lua-5.1/lfunc.c similarity index 91% rename from components/lua/lfunc.c rename to components/lua/lua-5.1/lfunc.c index a9c6e2d9..97e1a2ea 100644 --- a/components/lua/lfunc.c +++ b/components/lua/lua-5.1/lfunc.c @@ -6,7 +6,6 @@ #define lfunc_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -126,12 +125,7 @@ Proto *luaF_newproto (lua_State *L) { f->numparams = 0; f->is_vararg = 0; f->maxstacksize = 0; -#ifdef LUA_OPTIMIZE_DEBUG f->packedlineinfo = NULL; -#else - f->sizelineinfo = 0; - f->lineinfo = NULL; -#endif f->sizelocvars = 0; f->locvars = NULL; f->linedefined = 0; @@ -146,15 +140,9 @@ void luaF_freeproto (lua_State *L, Proto *f) { luaM_freearray(L, f->k, f->sizek, TValue); luaM_freearray(L, f->locvars, f->sizelocvars, struct LocVar); luaM_freearray(L, f->upvalues, f->sizeupvalues, TString *); - if (!proto_isreadonly(f)) { - luaM_freearray(L, f->code, f->sizecode, Instruction); -#ifdef LUA_OPTIMIZE_DEBUG - if (f->packedlineinfo) { - luaM_freearray(L, f->packedlineinfo, strlen(cast(char *, f->packedlineinfo))+1, unsigned char); - } -#else - luaM_freearray(L, f->lineinfo, f->sizelineinfo, int); -#endif + luaM_freearray(L, f->code, f->sizecode, Instruction); + if (f->packedlineinfo) { + luaM_freearray(L, f->packedlineinfo, strlen(cast(char *, f->packedlineinfo))+1, unsigned char); } luaM_free(L, f); } diff --git a/components/lua/lfunc.h b/components/lua/lua-5.1/lfunc.h similarity index 100% rename from components/lua/lfunc.h rename to components/lua/lua-5.1/lfunc.h diff --git a/components/lua/lgc.c b/components/lua/lua-5.1/lgc.c similarity index 96% rename from components/lua/lgc.c rename to components/lua/lua-5.1/lgc.c index 044f66ab..99f41611 100644 --- a/components/lua/lgc.c +++ b/components/lua/lua-5.1/lgc.c @@ -6,7 +6,6 @@ #define lgc_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -21,14 +20,12 @@ #include "lstring.h" #include "ltable.h" #include "ltm.h" -#include "lrotable.h" #define GCSTEPSIZE 1024u #define GCSWEEPMAX 40 #define GCSWEEPCOST 10 #define GCFINALIZECOST 100 - #define maskmarks cast_byte(~(bitmask(BLACKBIT)|WHITEBITS)) #define makewhite(g,x) \ @@ -55,7 +52,6 @@ #define markobject(g,t) { if (iswhite(obj2gco(t))) \ reallymarkobject(g, obj2gco(t)); } - #define setthreshold(g) (g->GCthreshold = (g->estimate/100) * g->gcpause) @@ -82,7 +78,7 @@ static void reallymarkobject (global_State *g, GCObject *o) { case LUA_TUSERDATA: { Table *mt = gco2u(o)->metatable; gray2black(o); /* udata are never gray */ - if (mt && !luaR_isrotable(mt)) markobject(g, mt); + if (mt && isrwtable(mt)) markobject(g, mt); markobject(g, gco2u(o)->env); return; } @@ -160,7 +156,6 @@ size_t luaC_separateudata (lua_State *L, int all) { return deadmem; } - static int traversetable (global_State *g, Table *h) { int i; int weakkey = 0; @@ -168,7 +163,7 @@ static int traversetable (global_State *g, Table *h) { const TValue *mode = luaO_nilobject; if (h->metatable) { - if (!luaR_isrotable(h->metatable)) + if (isrwtable(h->metatable)) markobject(g, h->metatable); mode = gfasttm(g, h->metatable, TM_MODE); } @@ -331,14 +326,8 @@ static l_mem propagatemark (global_State *g) { sizeof(TValue) * p->sizek + sizeof(LocVar) * p->sizelocvars + sizeof(TString *) * p->sizeupvalues + - (proto_isreadonly(p) ? 0 : sizeof(Instruction) * p->sizecode + -#ifdef LUA_OPTIMIZE_DEBUG - (p->packedlineinfo ? - strlen(cast(char *, p->packedlineinfo))+1 : - 0)); -#else - sizeof(int) * p->sizelineinfo); -#endif + sizeof(Instruction) * p->sizecode + + (p->packedlineinfo ? strlen(cast(char *, p->packedlineinfo))+1 : 0); } default: lua_assert(0); return 0; } @@ -522,8 +511,8 @@ void luaC_freeall (lua_State *L) { static void markmt (global_State *g) { int i; - for (i=0; imt[i] && !luaR_isrotable(g->mt[i])) markobject(g, g->mt[i]); + for (i=0; imt[i] && isrwtable(g->mt[i])) markobject(g, g->mt[i]); } @@ -713,7 +702,7 @@ void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v) { global_State *g = G(L); lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause); - lua_assert(o->gch.tt != LUA_TTABLE); + lua_assert((gettt(o) & LUA_TMASK) != LUA_TTABLE); /* must keep invariant? */ if (g->gcstate == GCSpropagate) reallymarkobject(g, v); /* Restore invariant */ diff --git a/components/lua/lgc.h b/components/lua/lua-5.1/lgc.h similarity index 100% rename from components/lua/lgc.h rename to components/lua/lua-5.1/lgc.h diff --git a/components/lua/llex.c b/components/lua/lua-5.1/llex.c similarity index 99% rename from components/lua/llex.c rename to components/lua/lua-5.1/llex.c index 69140d82..9e73c317 100644 --- a/components/lua/llex.c +++ b/components/lua/lua-5.1/llex.c @@ -7,7 +7,6 @@ #define llex_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -62,6 +61,7 @@ static void save (LexState *ls, int c) { void luaX_init (lua_State *L) { + (void)L; } diff --git a/components/lua/llex.h b/components/lua/lua-5.1/llex.h similarity index 100% rename from components/lua/llex.h rename to components/lua/lua-5.1/llex.h diff --git a/components/lua/llimits.h b/components/lua/lua-5.1/llimits.h similarity index 97% rename from components/lua/llimits.h rename to components/lua/lua-5.1/llimits.h index b882da06..21db9d3d 100644 --- a/components/lua/llimits.h +++ b/components/lua/lua-5.1/llimits.h @@ -8,8 +8,6 @@ #define llimits_h -//#include - #include "lua.h" typedef LUAI_UINT32 lu_int32; @@ -104,7 +102,7 @@ typedef lu_int32 Instruction; #ifndef lua_lock -#define lua_lock(L) ((void) 0) +#define lua_lock(L) ((void) 0) #define lua_unlock(L) ((void) 0) #endif @@ -115,7 +113,7 @@ typedef lu_int32 Instruction; /* ** macro to control inclusion of some hard tests on stack reallocation -*/ +*/ #ifndef HARDSTACKTESTS #define condhardstacktests(x) ((void)0) #else diff --git a/components/lua/lmathlib.c b/components/lua/lua-5.1/lmathlib.c similarity index 98% rename from components/lua/lmathlib.c rename to components/lua/lua-5.1/lmathlib.c index e4dcdfb8..2d1d3bcf 100644 --- a/components/lua/lmathlib.c +++ b/components/lua/lua-5.1/lmathlib.c @@ -7,7 +7,6 @@ #define lmathlib_c #define LUA_LIB -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -15,7 +14,6 @@ #include "lauxlib.h" #include "lualib.h" -#include "lrotable.h" #undef PI #define PI (3.14159265358979323846) @@ -309,7 +307,7 @@ static int math_randomseed (lua_State *L) { return 0; } -LROT_PUBLIC_BEGIN(math) +LROT_BEGIN(mathlib, NULL, 0) #ifdef LUA_NUMBER_INTEGRAL LROT_FUNCENTRY( abs, math_abs ) LROT_FUNCENTRY( ceil, math_identity ) @@ -354,7 +352,7 @@ LROT_PUBLIC_BEGIN(math) LROT_NUMENTRY( pi, PI ) LROT_NUMENTRY( huge, HUGE_VAL ) #endif // #ifdef LUA_NUMBER_INTEGRAL -LROT_END(math, NULL, 0) +LROT_END(mathlib, NULL, 0) /* diff --git a/components/lua/lmem.c b/components/lua/lua-5.1/lmem.c similarity index 98% rename from components/lua/lmem.c rename to components/lua/lua-5.1/lmem.c index 9886b771..ae244a9f 100644 --- a/components/lua/lmem.c +++ b/components/lua/lua-5.1/lmem.c @@ -7,7 +7,6 @@ #define lmem_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" diff --git a/components/lua/lmem.h b/components/lua/lua-5.1/lmem.h similarity index 94% rename from components/lua/lmem.h rename to components/lua/lua-5.1/lmem.h index 4766454f..4ef11997 100644 --- a/components/lua/lmem.h +++ b/components/lua/lua-5.1/lmem.h @@ -8,12 +8,6 @@ #define lmem_h -//#ifdef LUA_CROSS_COMPILER -//#include -//#else -//#include "c_stddef.h" -//#endif - #include "llimits.h" #include "lua.h" diff --git a/components/lua/lua-5.1/lnodemcu.c b/components/lua/lua-5.1/lnodemcu.c new file mode 100644 index 00000000..fe87010a --- /dev/null +++ b/components/lua/lua-5.1/lnodemcu.c @@ -0,0 +1,259 @@ +/* +** $Id: ltm.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $ +** Tag methods +** See Copyright Notice in lua.h +*/ + + +#define lnodemcu_c +#define LUA_CORE + +#include "lua.h" +#include + +#include "lobject.h" +#include "lstate.h" +#include "lauxlib.h" +#include "lgc.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lnodemcu.h" + +//== NodeMCU lauxlib.h API extensions ========================================// +#ifdef LUA_USE_ESP +#include "task/task.h" +#include "platform.h" + +/* +** Error Reporting Task. We can't pass a string parameter to the error reporter +** directly through the task interface the call is wrapped in a C closure with +** the error string as an Upval and this is posted to call the Lua reporter. +*/ +static int errhandler_aux (lua_State *L) { + lua_getfield(L, LUA_REGISTRYINDEX, "onerror"); + if (!lua_isfunction(L, -1)) { + lua_pop(L, 1); + lua_getglobal(L, "print"); + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_call(L, 1, 0); /* Using an error handler would cause an infinite loop! */ + return 0; +} + +/* +** Error handler for luaL_pcallx(), called from the lua_pcall() with a single +** argument -- the thrown error. This plus depth=2 is passed to debug.traceback() +** to convert into an error message which it handles in a separate posted task. +*/ +static int errhandler (lua_State *L) { + lua_getglobal(L, "debug"); + lua_getfield(L, -1, "traceback"); + if (lua_isfunction(L, -1)) { + lua_insert(L, 1); /* insert tracback function above error */ + lua_pop(L, 1); /* dump the debug table entry */ + lua_pushinteger(L, 2); /* skip this function and traceback */ + lua_call(L, 2, 1); /* call debug.traceback and return it as a string */ + lua_pushcclosure(L, errhandler_aux, 1); /* report with str as upval */ + luaL_posttask(L, LUA_TASK_HIGH); + } + return 0; +} + +/* +** Use in CBs and other C functions to call a Lua function. This includes +** an error handler which will catch any error and then post this to the +** registered reporter function as a separate follow-on task. +*/ +LUALIB_API int luaL_pcallx (lua_State *L, int narg, int nres) { // [-narg, +0, v] + int status; + int base = lua_gettop(L) - narg; + lua_pushcfunction(L, errhandler); + lua_insert(L, base); /* put under args */ + status = lua_pcall(L, narg, nres, base); + lua_remove(L, base); /* remove traceback function */ + if (status != LUA_OK && status != LUA_ERRRUN) { + lua_gc(L, LUA_GCCOLLECT, 0); /* call onerror directly if handler failed */ + lua_pushliteral(L, "out of memory"); + lua_pushcclosure(L, errhandler_aux, 1); /* report EOM as upval */ + luaL_posttask(L, LUA_TASK_HIGH); + } + return status; +} + +static task_handle_t task_handle = 0; + +/* +** Task callback handler. Uses luaN_call to do a protected call with full traceback +*/ +static void do_task (task_param_t task_fn_ref, task_prio_t prio) { + lua_State* L = lua_getstate(); + if (prio < 0|| prio > 2) + luaL_error(L, "invalid posk task"); + +/* Pop the CB func from the Reg */ +//dbg_printf("calling Reg[%u]\n", task_fn_ref); + lua_rawgeti(L, LUA_REGISTRYINDEX, (int) task_fn_ref); + luaL_checkfunction(L, -1); + luaL_unref(L, LUA_REGISTRYINDEX, (int) task_fn_ref); + lua_pushinteger(L, prio); + luaL_pcallx(L, 1, 0); +} + +/* +** Schedule a Lua function for task execution +*/ +LUALIB_API int luaL_posttask( lua_State* L, int prio ) { // [-1, +0, -] + if (!task_handle) + task_handle = task_get_id(do_task); + + if (!lua_isfunction(L, -1) || prio < LUA_TASK_LOW|| prio > LUA_TASK_HIGH) + luaL_error(L, "invalid posk task"); +//void *cl = clvalue(L->top-1); + int task_fn_ref = luaL_ref(L, LUA_REGISTRYINDEX); +//dbg_printf("posting Reg[%u]=%p\n",task_fn_ref,cl); + if(!task_post(prio, task_handle, (task_param_t)task_fn_ref)) { + luaL_unref(L, LUA_REGISTRYINDEX, task_fn_ref); + luaL_error(L, "Task queue overflow. Task not posted"); + } + return task_fn_ref; +} +#else +LUALIB_API int luaL_posttask( lua_State* L, int prio ) { + (void)L; (void)prio; + return 0; +} /* Dummy stub on host */ +#endif + +#ifdef LUA_USE_ESP +/* + * Return an LFS function + */ +LUALIB_API int luaL_pushlfsmodule (lua_State *L) { + if (lua_pushlfsindex(L) == LUA_TNIL) { + lua_remove(L,-2); /* dump the name to balance the stack */ + return 0; /* return nil if LFS not loaded */ + } + lua_insert(L, -2); + lua_call(L, 1, 1); + if (!lua_isfunction(L, -1)) { + lua_pop(L, 1); + lua_pushnil(L); /* replace DTS by nil */ + } + return 1; +} + +/* + * Return an array of functions in LFS + */ +LUALIB_API int luaL_pushlfsmodules (lua_State *L) { + if (lua_pushlfsindex(L) == LUA_TNIL) + return 0; /* return nil if LFS not loaded */ + lua_call(L, 0, 2); + lua_remove(L, -2); /* remove DTS leaving array */ + return 1; + +} + +/* + * Return the Unix timestamp of the LFS image creation + */ +LUALIB_API int luaL_pushlfsdts (lua_State *L) { + if (lua_pushlfsindex(L) == LUA_TNIL) + return 0; /* return nil if LFS not loaded */ + lua_call(L, 0, 1); + return 1; +} +#endif + +//== NodeMCU lua.h API extensions ============================================// + +LUA_API int lua_freeheap (void) { +#ifdef LUA_USE_HOST + return MAX_INT; +#else + return (int)esp_get_free_heap_size(); +#endif +} + +#define api_incr_top(L) {api_check(L, L->top < L->ci->top); L->top++;} +LUA_API int lua_pushstringsarray(lua_State *L, int opt) { + stringtable *tb = NULL; + int i, j; + + lua_lock(L); + if (opt == 0) + tb = &G(L)->strt; +#ifdef LUA_USE_ESP + else if (opt == 1 && G(L)->ROstrt.hash) + tb = &G(L)->ROstrt; +#endif + if (tb == NULL) { + setnilvalue(L->top); + api_incr_top(L); + lua_unlock(L); + return 0; + } + + Table *t = luaH_new(L, tb->nuse, 0); + sethvalue(L, L->top, t); + api_incr_top(L); + luaC_checkGC(L); + lua_unlock(L); + + for (i = 0, j = 1; i < tb->size; i++) { + GCObject *o; + for(o = tb->hash[i]; o; o = o->gch.next) { + TValue v; + setsvalue(L, &v, o); + setobj2s(L, luaH_setnum(L, hvalue(L->top-1), j++), &v); + } + } + return 1; +} + +LUA_API void lua_createrotable (lua_State *L, ROTable *t, const ROTable_entry *e, ROTable *mt) { + int i, j; + lu_byte flags = ~0; + const char *plast = (char *)"_"; + for (i = 0; e[i].key; i++) { + if (e[i].key[0] == '_' && strcmp(e[i].key,plast)) { + plast = e[i].key; + lua_pushstring(L,e[i].key); + for (j=0; jtop-1)==G(L)->tmname[i]) { + flags |= cast_byte(1u<next = (GCObject *)1; + t->tt = LUA_TROTABLE; + t->marked = LROT_MARKED; + t->flags = flags; + t->lsizenode = i; + t->metatable = cast(Table *, mt); + t->entry = cast(ROTable_entry *, e); +} + +#ifdef LUA_USE_ESP +#include "lfunc.h" + +/* Push the LClosure of the LFS index function */ +LUA_API int lua_pushlfsindex (lua_State *L) { + lua_lock(L); + Proto *p = G(L)->ROpvmain; + if (p) { + Closure *cl = luaF_newLclosure(L, 0, hvalue(gt(L))); + cl->l.p = p; + setclvalue(L, L->top, cl); + } else { + setnilvalue(L->top); + } + api_incr_top(L); + lua_unlock(L); + return p ? LUA_TFUNCTION : LUA_TNIL; +} +#endif diff --git a/components/lua/lua-5.1/lnodemcu.h b/components/lua/lua-5.1/lnodemcu.h new file mode 100644 index 00000000..e9e2ee1a --- /dev/null +++ b/components/lua/lua-5.1/lnodemcu.h @@ -0,0 +1,73 @@ +/* + * NodeMCU extensions to Lua 5.1 for readonly Flash memory support + */ +#ifndef lnodemcu_h +#define lnodemcu_h + +#include "lua.h" +#include "lobject.h" +#include "llimits.h" +#include "ltm.h" + +#ifdef LUA_USE_HOST +#define LRO_STRKEY(k) k +#define LOCK_IN_SECTION(s) +#else +#define LRO_STRKEY(k) ((__attribute__((aligned(4))) const char *) k) +#define LOCK_IN_SECTION(s) __attribute__((used,unused,section(".lua_" #s))) +#endif + +/* Macros used to declare rotable entries */ + +#define LRO_FUNCVAL(v) {{.p = v}, LUA_TLIGHTFUNCTION} +#define LRO_LUDATA(v) {{.p = cast(void*,v)}, LUA_TLIGHTUSERDATA} +#define LRO_NILVAL {{.p = NULL}, LUA_TNIL} +#define LRO_NUMVAL(v) {{.n = v}, LUA_TNUMBER} +#define LRO_INTVAL(v) LRO_NUMVAL(v) +#define LRO_FLOATVAL(v) LRO_NUMVAL(v) +#define LRO_ROVAL(v) {{.gc = cast(GCObject *, &(v ## _ROTable))}, LUA_TROTABLE} + +#define LROT_MARKED 0 //<<<<<<<<<< *** TBD *** >>>>>>>>>>> + +#define LROT_FUNCENTRY(n,f) {LRO_STRKEY(#n), LRO_FUNCVAL(f)}, +#define LROT_LUDENTRY(n,x) {LRO_STRKEY(#n), LRO_LUDATA(x)}, +#define LROT_NUMENTRY(n,x) {LRO_STRKEY(#n), LRO_NUMVAL(x)}, +#define LROT_INTENTRY(n,x) LROT_NUMENTRY(n,x) +#define LROT_FLOATENTRY(n,x) LROT_NUMENTRY(n,x) +#define LROT_TABENTRY(n,t) {LRO_STRKEY(#n), LRO_ROVAL(t)}, + +#define LROT_TABLE(rt) const ROTable rt ## _ROTable +#define LROT_ENTRYREF(rt) (rt ##_entries) +#define LROT_TABLEREF(rt) (&rt ##_ROTable) +#define LROT_BEGIN(rt,mt,f) LROT_TABLE(rt); \ + static ROTable_entry rt ## _entries[] = { +#define LROT_ENTRIES_IN_SECTION(rt,s) \ + static ROTable_entry LOCK_IN_SECTION(s) rt ## _entries[] = { +#define LROT_END(rt,mt,f) {NULL, LRO_NILVAL} }; \ + const ROTable rt ## _ROTable = { \ + (GCObject *)1, LUA_TROTABLE, LROT_MARKED, \ + cast(lu_byte, ~(f)), (sizeof(rt ## _entries)/sizeof(ROTable_entry)) - 1, \ + cast(Table *, mt), cast(ROTable_entry *, rt ## _entries) }; +#define LROT_BREAK(rt) }; + +#define LROT_MASK(m) cast(lu_byte, 1< @@ -24,7 +23,6 @@ #include "lauxlib.h" #include "lualib.h" -#include "lrotable.h" /* prefix for open functions in C libraries */ #define LUA_POF "luaopen_" @@ -394,11 +392,7 @@ static int loader_Lua (lua_State *L) { const char *name = luaL_checkstring(L, 1); filename = findfile(L, name, "path"); if (filename == NULL) return 1; /* library not found in this path */ -#ifdef LUA_CROSS_COMPILER if (luaL_loadfile(L, filename) != 0) -#else - if (luaL_loadfsfile(L, filename) != 0) -#endif loaderror(L, filename); return 1; /* library loaded successfully */ } @@ -479,7 +473,7 @@ static int ll_require (lua_State *L) { } /* Is this a readonly table? */ lua_getfield(L, LUA_GLOBALSINDEX, name); - if(lua_isrotable(L,-1)) { + if(lua_istable(L,-1)) { return 1; } else { lua_pop(L, 1); @@ -572,7 +566,7 @@ static int ll_module (lua_State *L) { const char *modname = luaL_checkstring(L, 1); /* Is this a readonly table? */ lua_getfield(L, LUA_GLOBALSINDEX, modname); - if(lua_isrotable(L,-1)) { + if(lua_istable(L,-1)) { return 0; } else { lua_pop(L, 1); @@ -658,9 +652,9 @@ static const luaL_Reg ll_funcs[] = { static const lua_CFunction loaders[] = {loader_preload, loader_Lua, loader_C, loader_Croot, NULL}; -LROT_PUBLIC_BEGIN(lmt) - LROT_FUNCENTRY(__gc,gctm) -LROT_END(lmt,lmt, LROT_MASK_GC) +LROT_BEGIN(lmt, NULL, LROT_MASK_GC) + LROT_FUNCENTRY( __gc, gctm ) +LROT_END(lmt, NULL, LROT_MASK_GC) LUALIB_API int luaopen_package (lua_State *L) { int i; diff --git a/components/lua/lobject.c b/components/lua/lua-5.1/lobject.c similarity index 86% rename from components/lua/lobject.c rename to components/lua/lua-5.1/lobject.c index c757583b..39512b8c 100644 --- a/components/lua/lobject.c +++ b/components/lua/lua-5.1/lobject.c @@ -1,3 +1,4 @@ + /* ** $Id: lobject.c,v 2.22.1.1 2007/12/27 13:02:25 roberto Exp $ ** Some generic functions over Lua objects @@ -7,7 +8,6 @@ #define lobject_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -25,7 +25,6 @@ #else #include #endif - const TValue luaO_nilobject_ = {LUA_TVALUE_NIL}; @@ -54,7 +53,23 @@ int luaO_fb2int (int x) { int luaO_log2 (unsigned int x) { +#ifdef LUA_CROSS_COMPILER + static const lu_byte log_2[256] = { + 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 + }; + int l = -1; + while (x >= 256) { l += 8; x >>= 8; } + return l + log_2[x]; +#else return 31 - __builtin_clz(x); +#endif } @@ -70,7 +85,7 @@ int luaO_rawequalObj (const TValue *t1, const TValue *t2) { case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); case LUA_TROTABLE: - return rvalue(t1) == rvalue(t2); + return hvalue(t1) == hvalue(t2); case LUA_TLIGHTFUNCTION: return fvalue(t1) == fvalue(t2); default: @@ -85,11 +100,11 @@ int luaO_str2d (const char *s, lua_Number *result) { *result = lua_str2number(s, &endptr); if (endptr == s) return 0; /* conversion failed */ if (*endptr == 'x' || *endptr == 'X') /* maybe an hexadecimal constant? */ -#if defined(LUA_CROSS_COMPILER) +#if defined(LUA_CROSS_COMPILER) { long lres = strtoul(s, &endptr, 16); -#if LONG_MAX != 2147483647L - if (lres & ~0xffffffffL) +#if INT_MAX != 2147483647L + if (lres & ~0xffffffffL) *result = cast_num(-1); else if (lres & 0x80000000L) *result = cast_num(lres | ~0x7fffffffL); diff --git a/components/lua/lobject.h b/components/lua/lua-5.1/lobject.h similarity index 79% rename from components/lua/lobject.h rename to components/lua/lua-5.1/lobject.h index 3f76bfe1..0e8e8478 100644 --- a/components/lua/lobject.h +++ b/components/lua/lua-5.1/lobject.h @@ -17,7 +17,7 @@ /* tags for values visible from Lua */ #define LAST_TAG LUA_TTHREAD -#define NUM_TAGS (LAST_TAG+1) +#define LUA_NUMTAGS (LAST_TAG+1) #define READONLYMASK (1<<7) /* denormalised bitmask for READONLYBIT and */ #define LFSMASK (1<<6) /* LFSBIT to avoid include proliferation */ @@ -28,15 +28,18 @@ #define LUA_TUPVAL (LAST_TAG+2) #define LUA_TDEADKEY (LAST_TAG+3) -#ifdef __XTENSA__ +#ifdef LUA_USE_ESP8266 /* ** force aligned access to critical fields in Flash-based structures ** wo is the offset of aligned word in bytes 0,4,8,.. ** bo is the field within the word in bits 0..31 +** +** Note that this returns a lu_int32 as returning a byte can cause the +** gcc code generator to emit an extra extui instruction. */ #define GET_BYTE_FN(name,t,wo,bo) \ -static inline lu_byte get ## name(void *o) { \ - lu_byte res; /* extract named field */ \ +static inline lu_int32 get ## name(void *o) { \ + lu_int32 res; /* extract named field */ \ asm ("l32i %0, %1, " #wo "; extui %0, %0, " #bo ", 8;" : "=r"(res) : "r"(o) : );\ return res; } #else @@ -49,14 +52,12 @@ static inline lu_byte get ## name(void *o) { return ((t *)o)->name; } */ typedef union GCObject GCObject; - /* ** Common Header for all collectable objects (in macro form, to be ** included in other objects) */ #define CommonHeader GCObject *next; lu_byte tt; lu_byte marked - /* ** Common header in struct form */ @@ -93,43 +94,47 @@ typedef union { #define TValuefields Value value; int tt #define LUA_TVALUE_NIL {NULL}, LUA_TNIL -#if defined(LUA_PACK_TVALUES) && !defined(LUA_CROSS_COMPILER) -#pragma pack(4) +#ifdef LUA_USE_ESP +# pragma pack(4) #endif + typedef struct lua_TValue { TValuefields; } TValue; -#if defined(LUA_PACK_TVALUES) && !defined(LUA_CROSS_COMPILER) -#pragma pack() + +#ifdef LUA_USE_ESP +# pragma pack() #endif /* Macros to test type */ -#define ttisnil(o) (ttype(o) == LUA_TNIL) -#define ttisnumber(o) (ttype(o) == LUA_TNUMBER) -#define ttisstring(o) (ttype(o) == LUA_TSTRING) -#define ttistable(o) (ttype(o) == LUA_TTABLE) -#define ttisfunction(o) (ttype(o) == LUA_TFUNCTION) -#define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN) -#define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA) -#define ttisthread(o) (ttype(o) == LUA_TTHREAD) -#define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA) -#define ttisrotable(o) (ttype(o) == LUA_TROTABLE) -#define ttislightfunction(o) (ttype(o) == LUA_TLIGHTFUNCTION) +#define ttisnil(o) (ttype(o) == LUA_TNIL) +#define ttisnumber(o) (ttype(o) == LUA_TNUMBER) +#define ttisstring(o) (ttype(o) == LUA_TSTRING) +#define ttistable(o) (ttnov(o) == LUA_TTABLE) +#define ttisrwtable(o) (type(o) == LUA_TTABLE) +#define ttisrotable(o) (ttype(o) & LUA_TISROTABLE) +#define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN) +#define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA) +#define ttisthread(o) (ttype(o) == LUA_TTHREAD) +#define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA) +#define ttislightfunction(o) (ttype(o) == LUA_TLIGHTFUNCTION) +#define ttisclfunction(o) (ttype(o) == LUA_TFUNCTION) +#define ttisfunction(o) (ttnov(o) == LUA_TFUNCTION) /* Macros to access values */ #define ttype(o) ((void) (o)->value, (o)->tt) +#define ttnov(o) ((void) (o)->value, ((o)->tt & LUA_TMASK)) #define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc) #define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p) -#define rvalue(o) check_exp(ttisrotable(o), (o)->value.p) -#define fvalue(o) check_exp(ttislightfunction(o), (o)->value.p) +#define fvalue(o) check_exp(ttislightfunction(o), (o)->value.p) #define nvalue(o) check_exp(ttisnumber(o), (o)->value.n) #define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts) #define tsvalue(o) (&rawtsvalue(o)->tsv) #define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u) #define uvalue(o) (&rawuvalue(o)->uv) -#define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl) +#define clvalue(o) check_exp(ttisclfunction(o), &(o)->value.gc->cl) #define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h) #define bvalue(o) check_exp(ttisboolean(o), (o)->value.b) #define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th) @@ -156,9 +161,6 @@ typedef struct lua_TValue { #define setpvalue(obj,x) \ { void *i_x = (x); TValue *i_o=(obj); i_o->value.p=i_x; i_o->tt=LUA_TLIGHTUSERDATA; } -#define setrvalue(obj,x) \ - { void *i_x = (x); TValue *i_o=(obj); i_o->value.p=i_x; i_o->tt=LUA_TROTABLE; } - #define setfvalue(obj,x) \ { void *i_x = (x); TValue *i_o=(obj); i_o->value.p=i_x; i_o->tt=LUA_TLIGHTFUNCTION; } @@ -192,7 +194,7 @@ typedef struct lua_TValue { #define sethvalue(L,obj,x) \ { GCObject *i_x = cast(GCObject *, (x)); \ TValue *i_o=(obj); \ - i_o->value.gc=i_x; i_o->tt=LUA_TTABLE; \ + i_o->value.gc=i_x; i_o->tt=gettt(x); \ checkliveness(G(L),i_o); } #define setptvalue(L,obj,x) \ @@ -227,7 +229,7 @@ typedef struct lua_TValue { #define setttype(obj, stt) ((void) (obj)->value, (obj)->tt = (stt)) -#define iscollectable(o) (ttype(o) >= LUA_TSTRING) +#define iscollectable(o) (ttype(o) >= LUA_TSTRING && ttype(o) <= LUA_TMASK) typedef TValue *StkId; /* index to stack elements */ @@ -245,19 +247,10 @@ typedef union TString { } tsv; } TString; -#ifdef LUA_CROSS_COMPILER -#define isreadonly(o) (0) -#else -#define isreadonly(o) ((o).marked & READONLYMASK) -#endif -#define ts_isreadonly(ts) isreadonly((ts)->tsv) -#define getstr(ts) (ts_isreadonly(ts) ? \ - cast(const char *, *(const char**)((ts) + 1)) : \ - cast(const char *, (ts) + 1)) +#define getstr(ts) cast(const char *, (ts) + 1) #define svalue(o) getstr(rawtsvalue(o)) - typedef union Udata { L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ struct { @@ -268,7 +261,12 @@ typedef union Udata { } uv; } Udata; - +#ifdef LUA_CROSS_COMPILER +#define isreadonly(o) (0) +#else +#define isreadonly(o) (getmarked(o) & READONLYMASK) +#endif +#define islfs(o) (getmarked(o) & LFSMASK) /* @@ -279,20 +277,13 @@ typedef struct Proto { TValue *k; /* constants used by the function */ Instruction *code; struct Proto **p; /* functions defined inside the function */ -#ifdef LUA_OPTIMIZE_DEBUG unsigned char *packedlineinfo; -#else - int *lineinfo; /* map from opcodes to source lines */ -#endif struct LocVar *locvars; /* information about local variables */ TString **upvalues; /* upvalue names */ TString *source; int sizeupvalues; int sizek; /* size of `k' */ int sizecode; -#ifndef LUA_OPTIMIZE_DEBUG - int sizelineinfo; -#endif int sizep; /* size of `p' */ int sizelocvars; int linedefined; @@ -303,7 +294,6 @@ typedef struct Proto { lu_byte is_vararg; lu_byte maxstacksize; } Proto; -#define proto_isreadonly(p) isreadonly(*(p)) /* masks for new-style vararg */ @@ -373,6 +363,18 @@ typedef union Closure { ** Tables */ +/* +** Common Table fields for both table versions (like CommonHeader in +** macro form, to be included in table structure definitions). +** +** Note that the sethvalue() macro works much like the setsvalue() +** macro and handles the abstracted type. the hvalue(o) macro can be +** used to access CommonTable fields and rw Table fields +*/ + +#define CommonTable CommonHeader; \ + lu_byte flags; lu_byte lsizenode; struct Table *metatable + typedef union TKey { struct { TValuefields; @@ -390,10 +392,7 @@ typedef struct Node { typedef struct Table { - CommonHeader; - lu_byte flags; /* 1<

C) then pc++ */ -OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ +OP_TEST,/* A C if not (R(A) <=> C) then pc++ */ +OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */ OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ @@ -197,8 +197,8 @@ OP_FORLOOP,/* A sBx R(A)+=R(A+2); if R(A) =) R(A)*/ @@ -240,7 +240,7 @@ OP_VARARG/* A B R(A), R(A+1), ..., R(A+B-1) = vararg */ ** bits 4-5: B arg mode ** bit 6: instruction set register A ** bit 7: operator is a test -*/ +*/ enum OpArgMask { OpArgN, /* argument is not used */ diff --git a/components/lua/lparser.c b/components/lua/lua-5.1/lparser.c similarity index 98% rename from components/lua/lparser.c rename to components/lua/lua-5.1/lparser.c index 097d1a84..e37d1450 100644 --- a/components/lua/lparser.c +++ b/components/lua/lua-5.1/lparser.c @@ -7,7 +7,6 @@ #define lparser_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -344,12 +343,10 @@ static void open_func (LexState *ls, FuncState *fs) { fs->bl = NULL; f->source = ls->source; f->maxstacksize = 2; /* registers 0/1 are always valid */ -#ifdef LUA_OPTIMIZE_DEBUG fs->packedlineinfoSize = 0; fs->lastline = 0; fs->lastlineOffset = 0; fs->lineinfoLastPC = -1; -#endif fs->h = luaH_new(L, 0, 0); /* anchor table of constants and prototype (to avoid being collected) */ sethvalue2s(L, L->top, fs->h); @@ -367,15 +364,9 @@ static void close_func (LexState *ls) { luaK_ret(fs, 0, 0); /* final return */ luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); f->sizecode = fs->pc; -#ifdef LUA_OPTIMIZE_DEBUG f->packedlineinfo[fs->lastlineOffset+1]=0; luaM_reallocvector(L, f->packedlineinfo, fs->packedlineinfoSize, fs->lastlineOffset+2, unsigned char); -#else - luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int); - f->sizelineinfo = fs->pc; -#endif - luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue); f->sizek = fs->nk; luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *); @@ -392,20 +383,11 @@ static void close_func (LexState *ls) { L->top -= 2; /* remove table and prototype from the stack */ } -#ifdef LUA_OPTIMIZE_DEBUG static void compile_stripdebug(lua_State *L, Proto *f) { - int level; - lua_pushlightuserdata(L, &luaG_stripdebug ); - lua_gettable(L, LUA_REGISTRYINDEX); - level = lua_isnil(L, -1) ? LUA_OPTIMIZE_DEBUG : lua_tointeger(L, -1); - lua_pop(L, 1); - - if (level > 1) { - int len = luaG_stripdebug(L, f, level, 1); - UNUSED(len); - } + int level = G(L)->stripdefault; + if (level > 0) + luaG_stripdebug(L, f, level, 1); } -#endif Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) { @@ -422,9 +404,7 @@ Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) { chunk(&lexstate); check(&lexstate, TK_EOS); close_func(&lexstate); -#ifdef LUA_OPTIMIZE_DEBUG compile_stripdebug(L, funcstate.f); -#endif L->top--; /* remove 'name' from stack */ lua_assert(funcstate.prev == NULL); lua_assert(funcstate.f->nups == 0); diff --git a/components/lua/lparser.h b/components/lua/lua-5.1/lparser.h similarity index 98% rename from components/lua/lparser.h rename to components/lua/lua-5.1/lparser.h index 74b7aa6e..be0a6c9a 100644 --- a/components/lua/lparser.h +++ b/components/lua/lua-5.1/lparser.h @@ -72,12 +72,10 @@ typedef struct FuncState { lu_byte nactvar; /* number of active local variables */ upvaldesc upvalues[LUAI_MAXUPVALUES]; /* upvalues */ unsigned short actvar[LUAI_MAXVARS]; /* declared-variable stack */ -#ifdef LUA_OPTIMIZE_DEBUG int packedlineinfoSize; /* only used during compilation for line info */ int lastline; /* ditto */ int lastlineOffset; /* ditto */ int lineinfoLastPC; /* ditto */ -#endif } FuncState; diff --git a/components/lua/lstate.c b/components/lua/lua-5.1/lstate.c similarity index 95% rename from components/lua/lstate.c rename to components/lua/lua-5.1/lstate.c index cb663246..c6f95445 100644 --- a/components/lua/lstate.c +++ b/components/lua/lua-5.1/lstate.c @@ -7,7 +7,6 @@ #define lstate_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" @@ -35,7 +34,7 @@ typedef struct LG { lua_State l; global_State g; } LG; - + static void stack_init (lua_State *L1, lua_State *L) { @@ -185,6 +184,7 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { g->memlimit = 0; g->gcpause = LUAI_GCPAUSE; g->gcstepmul = LUAI_GCMUL; + g->stripdefault = CONFIG_LUA_OPTIMIZE_DEBUG; g->gcdept = 0; #ifdef EGC_INITIAL_MODE g->egcmode = EGC_INITIAL_MODE; @@ -197,13 +197,14 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { g->memlimit = 0; #endif #ifndef LUA_CROSS_COMPILER - g->ROstrt.size = 0; - g->ROstrt.nuse = 0; - g->ROstrt.hash = NULL; - g->ROpvmain = NULL; - g->LFSsize = 0; + g->ROstrt.size = 0; + g->ROstrt.nuse = 0; + g->ROstrt.hash = NULL; + g->ROpvmain = NULL; + g->LFSsize = 0; + g->error_reporter = 0; #endif - for (i=0; imt[i] = NULL; + for (i=0; imt[i] = NULL; if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) { /* memory allocation error: free partial state */ close_state(L); @@ -225,20 +226,17 @@ extern lua_State *luaL_newstate (void); static lua_State *lua_crtstate; lua_State *lua_open(void) { - lua_crtstate = luaL_newstate(); + lua_crtstate = luaL_newstate(); return lua_crtstate; } -lua_State *lua_getstate(void) { - return lua_crtstate; -} LUA_API void lua_close (lua_State *L) { -#ifndef LUA_CROSS_COMPILER +#ifndef LUA_CROSS_COMPILER lua_sethook( L, NULL, 0, 0 ); lua_crtstate = NULL; lua_pushnil( L ); // lua_rawseti( L, LUA_REGISTRYINDEX, LUA_INT_HANDLER_KEY ); -#endif +#endif L = G(L)->mainthread; /* only the main thread can be closed */ lua_lock(L); luaF_close(L, L->stack); /* close all upvalues for this thread */ diff --git a/components/lua/lstate.h b/components/lua/lua-5.1/lstate.h similarity index 93% rename from components/lua/lstate.h rename to components/lua/lua-5.1/lstate.h index 88b7d57f..807e9466 100644 --- a/components/lua/lstate.h +++ b/components/lua/lua-5.1/lstate.h @@ -56,7 +56,7 @@ typedef struct CallInfo { -#define curr_func(L) (ttisfunction(L->ci->func) ? clvalue(L->ci->func) : NULL) +#define curr_func(L) (ttisclfunction(L->ci->func) ? clvalue(L->ci->func) : NULL) #define ci_func(ci) (ttisfunction((ci)->func) ? clvalue((ci)->func) : NULL) #define f_isLua(ci) (!ttislightfunction((ci)->func) && !ci_func(ci)->c.isC) #define isLua(ci) (ttisfunction((ci)->func) && f_isLua(ci)) @@ -87,17 +87,19 @@ typedef struct global_State { lu_mem gcdept; /* how much GC is `behind schedule' */ int gcpause; /* size of pause between successive GCs */ int gcstepmul; /* GC `granularity' */ + int stripdefault; /* default stripping level for compilation */ int egcmode; /* emergency garbage collection operation mode */ lua_CFunction panic; /* to be called in unprotected errors */ TValue l_registry; struct lua_State *mainthread; UpVal uvhead; /* head of double-linked list of all open upvalues */ - struct Table *mt[NUM_TAGS]; /* metatables for basic types */ + struct Table *mt[LUA_NUMTAGS]; /* metatables for basic types */ TString *tmname[TM_N]; /* array with tag-method names */ #ifndef LUA_CROSS_COMPILER stringtable ROstrt; /* Flash-based hash table for RO strings */ Proto *ROpvmain; /* Flash-based Proto main */ int LFSsize; /* Size of Lua Flash Store */ + int error_reporter; /* Registry Index of error reporter task */ #endif } global_State; @@ -159,7 +161,7 @@ union GCObject { #define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u)) #define gco2u(o) (&rawgco2u(o)->uv) #define gco2cl(o) check_exp((o)->gch.tt == LUA_TFUNCTION, &((o)->cl)) -#define gco2h(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h)) +#define gco2h(o) check_exp(((o)->gch.tt & LUA_TMASK) == LUA_TTABLE, &((o)->h)) #define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p)) #define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv)) #define ngcotouv(o) \ diff --git a/components/lua/lstring.c b/components/lua/lua-5.1/lstring.c similarity index 77% rename from components/lua/lstring.c rename to components/lua/lua-5.1/lstring.c index c4d1746a..f2c4372d 100644 --- a/components/lua/lstring.c +++ b/components/lua/lua-5.1/lstring.c @@ -8,7 +8,6 @@ #define lstring_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -18,8 +17,6 @@ #include "lstate.h" #include "lstring.h" -#define LUAS_READONLY_STRING 1 -#define LUAS_REGULAR_STRING 0 void luaS_resize (lua_State *L, int newsize) { stringtable *tb; @@ -53,26 +50,20 @@ void luaS_resize (lua_State *L, int newsize) { } static TString *newlstr (lua_State *L, const char *str, size_t l, - unsigned int h, int readonly) { + unsigned int h) { TString *ts; - stringtable *tb; + stringtable *tb = &G(L)->strt; if (l+1 > (MAX_SIZET - sizeof(TString))/sizeof(char)) luaM_toobig(L); - tb = &G(L)->strt; if ((tb->nuse + 1) > cast(lu_int32, tb->size) && tb->size <= MAX_INT/2) luaS_resize(L, tb->size*2); /* too crowded */ - ts = cast(TString *, luaM_malloc(L, sizeof(TString) + (readonly ? sizeof(char**) : (l+1)*sizeof(char)))); + ts = cast(TString *, luaM_malloc(L, sizeof(TString) + (l+1)*sizeof(char))); ts->tsv.len = l; ts->tsv.hash = h; ts->tsv.marked = luaC_white(G(L)); ts->tsv.tt = LUA_TSTRING; - if (!readonly) { - memcpy(ts+1, str, l*sizeof(char)); - ((char *)(ts+1))[l] = '\0'; /* ending 0 */ - } else { - *(char **)(ts+1) = (char *)str; - l_setbit((ts)->tsv.marked, READONLYBIT); - } + memcpy(ts+1, str, l*sizeof(char)); + ((char *)(ts+1))[l] = '\0'; /* ending 0 */ h = lmod(h, tb->size); ts->tsv.next = tb->hash[h]; /* chain new entry */ tb->hash[h] = obj2gco(ts); @@ -80,15 +71,6 @@ static TString *newlstr (lua_State *L, const char *str, size_t l, return ts; } -static int lua_is_ptr_in_ro_area(const char *p) { -#ifdef LUA_CROSS_COMPILER - (void)p; - return 0; // TStrings are never in RO in luac.cross -#else - return IN_RODATA_AREA(p); -#endif -} - /* * The string algorithm has been modified to be LFS-friendly. The previous eLua * algo used the address of the string was in flash and the string was >4 bytes @@ -129,11 +111,7 @@ LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { } } #endif - /* New additions to the RAM strt are tagged as readonly if the string address - * is in the CTEXT segment (target only, not luac.cross) */ - int readonly = (lua_is_ptr_in_ro_area(str) && l+1 > sizeof(char**) && - l == strlen(str) ? LUAS_READONLY_STRING : LUAS_REGULAR_STRING); - return newlstr(L, str, l, h, readonly); /* not found */ + return newlstr(L, str, l, h); /* not found */ } diff --git a/components/lua/lstring.h b/components/lua/lua-5.1/lstring.h similarity index 84% rename from components/lua/lstring.h rename to components/lua/lua-5.1/lstring.h index 366f92b3..41823ef2 100644 --- a/components/lua/lstring.h +++ b/components/lua/lua-5.1/lstring.h @@ -13,8 +13,7 @@ #include "lstate.h" -#define sizestring(s) (sizeof(union TString)+(testbit(getmarked(s), READONLYBIT) ? sizeof(char **) : ((s)->len+1)*sizeof(char))) - +#define sizestring(s) (sizeof(union TString)+((s)->len+1)*sizeof(char)) #define sizeudata(u) (sizeof(union Udata)+(u)->len) #define luaS_new(L, s) (luaS_newlstr(L, s, strlen(s))) diff --git a/components/lua/lstrlib.c b/components/lua/lua-5.1/lstrlib.c similarity index 96% rename from components/lua/lstrlib.c rename to components/lua/lua-5.1/lstrlib.c index 39e86048..fd1dddce 100644 --- a/components/lua/lstrlib.c +++ b/components/lua/lua-5.1/lstrlib.c @@ -7,7 +7,6 @@ #define lstrlib_c #define LUA_LIB -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -15,13 +14,11 @@ #include "lauxlib.h" #include "lualib.h" -#include "lrotable.h" /* macro to `unsign' a character */ #define uchar(c) ((unsigned char)(c)) - static int str_len (lua_State *L) { size_t l; luaL_checklstring(L, 1, &l); @@ -143,17 +140,25 @@ static int writer (lua_State *L, const void* b, size_t size, void* B) { static int str_dump (lua_State *L) { luaL_Buffer b; + int strip, tstrip = lua_type(L, 2); + if (tstrip == LUA_TBOOLEAN) { + strip = lua_toboolean(L, 2) ? 2 : 0; + } else if (tstrip == LUA_TNONE || tstrip == LUA_TNIL) { + strip = -1; /* This tells lua_dump to use the global strip default */ + } else { + strip = lua_tointeger(L, 2); + luaL_argcheck(L, (unsigned)(strip) < 3, 2, "strip out of range"); + } luaL_checktype(L, 1, LUA_TFUNCTION); lua_settop(L, 1); luaL_buffinit(L,&b); - if (lua_dump(L, writer, &b) != 0) - luaL_error(L, "unable to dump given function"); + if (lua_dump(L, writer, &b, strip) != 0) + return luaL_error(L, "unable to dump given function"); luaL_pushresult(&b); return 1; } - /* ** {====================================================== ** PATTERN MATCHING @@ -634,7 +639,7 @@ static void add_value (MatchState *ms, luaL_Buffer *b, const char *s, lua_pushlstring(L, s, e - s); /* keep original text */ } else if (!lua_isstring(L, -1)) - luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); + luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); luaL_addvalue(b); /* add result to accumulator */ } @@ -787,7 +792,7 @@ static int str_format (lua_State *L) { sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg)); break; } -#if !defined LUA_NUMBER_INTEGRAL +#if !defined LUA_NUMBER_INTEGRAL case 'e': case 'E': case 'f': case 'g': case 'G': { sprintf(buff, form, (double)luaL_checknumber(L, arg)); @@ -825,7 +830,21 @@ static int str_format (lua_State *L) { return 1; } -LROT_PUBLIC_BEGIN(strlib) +static int str_format2 (lua_State *L) { + if (lua_type(L, 2) == LUA_TTABLE) { + int i,n=lua_objlen(L,2); + lua_settop(L,2); + for (i = 1; i <= n; i++) + lua_rawgeti(L, 2, i); + lua_remove(L, 2); + } + return str_format(L); +} + + +LROT_BEGIN(strlib, NULL, LROT_MASK_INDEX) + LROT_TABENTRY( __index, strlib ) + LROT_FUNCENTRY( __mod, str_format2 ) LROT_FUNCENTRY( byte, str_byte ) LROT_FUNCENTRY( char, str_char ) LROT_FUNCENTRY( dump, str_dump ) @@ -845,8 +864,7 @@ LROT_PUBLIC_BEGIN(strlib) LROT_FUNCENTRY( reverse, str_reverse ) LROT_FUNCENTRY( sub, str_sub ) LROT_FUNCENTRY( upper, str_upper ) - LROT_TABENTRY( __index, strlib ) -LROT_END(strlib, NULL, 0) // OR DO WE NEED LRTO_MASK_INDEX **TODO** +LROT_END(strlib, NULL, LROT_MASK_INDEX) /* ** Open string library diff --git a/components/lua/ltable.c b/components/lua/lua-5.1/ltable.c similarity index 76% rename from components/lua/ltable.c rename to components/lua/lua-5.1/ltable.c index 1d85166d..9bfd0abc 100644 --- a/components/lua/ltable.c +++ b/components/lua/lua-5.1/ltable.c @@ -20,7 +20,6 @@ #define ltable_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -33,7 +32,8 @@ #include "lobject.h" #include "lstate.h" #include "ltable.h" -#include "lrotable.h" +#include "lstring.h" + /* ** max size of array part is 2^MAXBITS @@ -48,7 +48,7 @@ #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) - + #define hashstr(t,str) hashpow2(t, (str)->tsv.hash) #define hashboolean(t,p) hashpow2(t, p) @@ -68,6 +68,10 @@ */ #define numints cast_int(sizeof(lua_Number)/sizeof(int)) +static const TValue* rotable_findentry(ROTable *rotable, TString *key, unsigned *ppos); +static void rotable_next_helper(lua_State *L, ROTable *pentries, int pos, + TValue *key, TValue *val); +static void rotable_next(lua_State *L, ROTable *rotable, TValue *key, TValue *val); #define dummynode (&dummynode_) @@ -105,11 +109,11 @@ static Node *mainposition (const Table *t, const TValue *key) { return hashstr(t, rawtsvalue(key)); case LUA_TBOOLEAN: return hashboolean(t, bvalue(key)); - case LUA_TROTABLE: - return hashpointer(t, rvalue(key)); case LUA_TLIGHTUSERDATA: case LUA_TLIGHTFUNCTION: return hashpointer(t, pvalue(key)); + case LUA_TROTABLE: + return hashpointer(t, hvalue(key)); default: return hashpointer(t, gcvalue(key)); } @@ -163,7 +167,12 @@ static int findindex (lua_State *L, Table *t, StkId key) { int luaH_next (lua_State *L, Table *t, StkId key) { - int i = findindex(L, t, key); /* find original element */ + int i; + if (isrotable(t)) { + rotable_next(L, (ROTable *) t, key, key+1); + return ttisnil(key) ? 0 : 1; + } + i = findindex(L, t, key); /* find original element */ for (i++; i < t->sizearray; i++) { /* try first array part */ if (!ttisnil(&t->array[i])) { /* a non-nil value? */ setnvalue(key, cast_num(i+1)); @@ -182,12 +191,6 @@ int luaH_next (lua_State *L, Table *t, StkId key) { } -int luaH_next_ro (lua_State *L, void *t, StkId key) { - luaR_next(L, t, key, key+1); - return ttisnil(key) ? 0 : 1; -} - - /* ** {============================================================= ** Rehash @@ -330,7 +333,7 @@ static Node *find_prev_node(Node *mp, Node *next) { ** first, check whether the moving node's main position is free. If not, check whether ** colliding node is in its main position or not: if it is not, move colliding ** node to an empty place and put moving node in its main position; otherwise -** (colliding node is in its main position), moving node goes to an empty position. +** (colliding node is in its main position), moving node goes to an empty position. */ static int move_node (lua_State *L, Table *t, Node *node) { (void)L; @@ -372,7 +375,7 @@ static int move_node (lua_State *L, Table *t, Node *node) { static int move_number (lua_State *L, Table *t, Node *node) { - (void)L; (void)t; + (void)L; int key; lua_Number n = nvalue(key2tval(node)); lua_number2int(key, n); @@ -565,6 +568,8 @@ static TValue *newkey (lua_State *L, Table *t, const TValue *key) { ** search function for integers */ const TValue *luaH_getnum (Table *t, int key) { + if (isrotable(t)) + return luaO_nilobject; /* (1 <= key && key <= t->sizearray) */ if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray)) return &t->array[key-1]; @@ -580,18 +585,16 @@ const TValue *luaH_getnum (Table *t, int key) { } } -/* same thing for rotables */ -const TValue *luaH_getnum_ro (void *t, int key) { - (void)t; (void)key; - const TValue *res = NULL; // integer values not supported: luaR_findentryN(t, key, NULL); - return res ? res : luaO_nilobject; -} - - /* ** search function for strings */ const TValue *luaH_getstr (Table *t, TString *key) { + + if (isrotable(t)) { + if (key->tsv.len>LUA_MAX_ROTABLE_NAME) + return luaO_nilobject; + return rotable_findentry((ROTable*) t, key, NULL); + } Node *n = hashstr(t, key); do { /* check whether `key' is somewhere in the chain */ if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key) @@ -601,65 +604,41 @@ const TValue *luaH_getstr (Table *t, TString *key) { return luaO_nilobject; } -/* same thing for rotables */ -const TValue *luaH_getstr_ro (void *t, TString *key) { - if (!t || key->tsv.len>LUA_MAX_ROTABLE_NAME) - return luaO_nilobject; - return luaR_findentry(t, key, NULL); -} - /* ** main search function */ const TValue *luaH_get (Table *t, const TValue *key) { - switch (ttype(key)) { - case LUA_TNIL: return luaO_nilobject; - case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key)); - case LUA_TNUMBER: { - int k; - lua_Number n = nvalue(key); - lua_number2int(k, n); - if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */ - return luaH_getnum(t, k); /* use specialized version */ - /* else go through */ - } - /* fall-through */ - default: { - Node *n = mainposition(t, key); - do { /* check whether `key' is somewhere in the chain */ - if (luaO_rawequalObj(key2tval(n), key)) - return gval(n); /* that's it */ - else n = gnext(n); - } while (n); - return luaO_nilobject; - } - } -} - -/* same thing for rotables */ -const TValue *luaH_get_ro (void *t, const TValue *key) { - switch (ttype(key)) { - case LUA_TNIL: return luaO_nilobject; - case LUA_TSTRING: return luaH_getstr_ro(t, rawtsvalue(key)); - case LUA_TNUMBER: { - int k; - lua_Number n = nvalue(key); - lua_number2int(k, n); - if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */ - return luaH_getnum_ro(t, k); /* use specialized version */ - /* else go through */ - } - /* fall-through */ - default: { - return luaO_nilobject; - } + int type = ttype(key); + if (type == LUA_TNIL) + return luaO_nilobject; + if (type == LUA_TSTRING) + return luaH_getstr(t, rawtsvalue(key)); + if (isrotable(t)) + return luaO_nilobject; + if (type == LUA_TNUMBER) { + int k; + lua_Number n = nvalue(key); + lua_number2int(k, n); + if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */ + return luaH_getnum(t, k); /* use specialized version */ } + /* default */ + Node *n = mainposition(t, key); + do { /* check whether `key' is somewhere in the chain */ + if (luaO_rawequalObj(key2tval(n), key)) + return gval(n); /* that's it */ + else n = gnext(n); + } while (n); + return luaO_nilobject; } TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { - const TValue *p = luaH_get(t, key); + const TValue *p; + if (isrotable(t)) + luaG_runerror(L, "table is readonly"); + p = luaH_get(t, key); t->flags = 0; if (p != luaO_nilobject) return cast(TValue *, p); @@ -673,7 +652,10 @@ TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { TValue *luaH_setnum (lua_State *L, Table *t, int key) { - const TValue *p = luaH_getnum(t, key); + const TValue *p; + if (isrotable(t)) + luaG_runerror(L, "table is readonly"); + p = luaH_getnum(t, key); if (p != luaO_nilobject) return cast(TValue *, p); else { @@ -685,7 +667,10 @@ TValue *luaH_setnum (lua_State *L, Table *t, int key) { TValue *luaH_setstr (lua_State *L, Table *t, TString *key) { - const TValue *p = luaH_getstr(t, key); + const TValue *p; + if (isrotable(t)) + luaG_runerror(L, "table is readonly"); + p = luaH_getstr(t, key); if (p != luaO_nilobject) return cast(TValue *, p); else { @@ -725,7 +710,10 @@ static int unbound_search (Table *t, unsigned int j) { ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil). */ int luaH_getn (Table *t) { - unsigned int j = t->sizearray; + unsigned int j; + if(isrotable(t)) + return 0; + j = t->sizearray; if (j > 0 && ttisnil(&t->array[j - 1])) { /* there is a boundary in the array part: (binary) search for it */ unsigned int i = 0; @@ -742,14 +730,138 @@ int luaH_getn (Table *t) { else return unbound_search(t, j); } -/* same thing for rotables */ -int luaH_getn_ro (void *t) { - (void)t; - return 0; // Integer Keys are not currently supported for ROTables -} int luaH_isdummy (Node *n) { return n == dummynode; } + +/* +** All keyed ROTable access passes through rotable_findentry(). ROTables +** are simply a list of pairs. +** +** The global KeyCache is used to avoid a relatively expensive Flash memory +** vector scan. A simple hash on the key's TString addr and the ROTable +** addr selects the cache line. The line's slots are then scanned for a +** hit. +** +** Unlike the standard hast which uses a prime line count therefore requires +** the use of modulus operation which is expensive on an IoT processor +** without H/W divide. This hash is power of 2 based which might not be +** quite so uniform but can be calcuated without using H/W-based instructions. +** +** If a match is found and the table addresses match, then this entry is +** probed first. In practice the hit-rate here is over 99% so the code +** rarely fails back to doing the linear scan in ROM. +** Note that this hash does a couple of prime multiples and a modulus 2^X +** with is all evaluated in H/W, and adequately randomizes the lookup. +*/ +#define LA_LINES 32 +#define LA_SLOTS 4 +static size_t cache [LA_LINES][LA_SLOTS]; + +#define HASH(a,b) ((((29*(size_t)(a)) ^ (37*((b)->tsv.hash)))>>4) % LA_LINES) +#define NDX_SHFT 24 +#define ADDR_MASK (((size_t) 1<<24)-1) + +/* + * Find a string key entry in a rotable and return it. Note that this internally + * uses a null key to denote a metatable search. + */ +static const TValue* rotable_findentry(ROTable *t, TString *key, unsigned *ppos) { + const ROTable_entry *e = cast(const ROTable_entry *, t->entry); + const int tl = getlsizenode(t); + const char *strkey = getstr(key); + size_t *cl = cache[HASH(t, key)]; + int i, j = 1, l; + + if (!e || gettt(key) != LUA_TSTRING) + return luaO_nilobject; + + l = key->tsv.len; + /* scan the ROTable lookaside cache and return if hit found */ + for (i=0; i> NDX_SHFT; + if ((((size_t)t - cl[i]) & ADDR_MASK) == 0 && cl_ndx < tl && + strcmp(e[cl_ndx].key, strkey) == 0) { + if (ppos) + *ppos = cl_ndx; + return &e[cl_ndx].value; + } + } + + /* + * A lot of search misses are metavalues, but tables typically only have at + * most a couple of them, so these are always put at the front of the table + * in ascending order and the metavalue scan short circuits using a straight + * strcmp() + */ + lu_int32 name4 = *(lu_int32 *) strkey; + if (*(char*)&name4 == '_') { + for(i = 0; i < tl; i++) { + j = strcmp(e[i].key, strkey); + if (j>=0) + break; + } + } else { + /* + * Ordinary (non-meta) keys can be unsorted. This is for legacy compatiblity, + * plus misses are pretty rare in this case. The masked name4 comparison is + * safe 4-byte comparison that nearly always avoids the more costly strcmp() + * for an actual hit validation. + */ + lu_int32 mask4 = l > 2 ? (~0u) : (~0u)>>((3-l)*8); + for(i = 0; i < tl; i++) { + if (((*(lu_int32 *)e[i].key ^ name4) & mask4) != 0) + continue; + j = strcmp(e[i].key, strkey); + if (j==0) + break; + } + } + if (j) + return luaO_nilobject; + if (ppos) + *ppos = i; + /* In the case of a hit, update the lookaside cache */ + for (j = LA_SLOTS-1; j>0; j--) + cl[j] = cl[j-1]; + cl[0] = ((size_t)t & ADDR_MASK) + (i << NDX_SHFT); + return &e[i].value; +} + + +static void rotable_next_helper(lua_State *L, ROTable *t, int pos, + TValue *key, TValue *val) { + const ROTable_entry *e = cast(const ROTable_entry *, t->entry); + if (pos < getlsizenode(t)) { + /* Found an entry */ + setsvalue(L, key, luaS_new(L, e[pos].key)); + setobj2s(L, val, &e[pos].value); + } else { + setnilvalue(key); + setnilvalue(val); + } +} + + +/* next (used for iteration) */ +static void rotable_next(lua_State *L, ROTable *t, TValue *key, TValue *val) { + unsigned keypos = getlsizenode(t); + + /* Special case: if key is nil, return the first element of the rotable */ + if (ttisnil(key)) + rotable_next_helper(L, t, 0, key, val); + else if (ttisstring(key)) { + /* Find the previous key again */ + if (ttisstring(key)) { + rotable_findentry(t, rawtsvalue(key), &keypos); + } + /* Advance to next key */ + rotable_next_helper(L, t, ++keypos, key, val); + } +} + + + #if defined(LUA_DEBUG) Node *luaH_mainposition (const Table *t, const TValue *key) { return mainposition(t, key); diff --git a/components/lua/ltable.h b/components/lua/lua-5.1/ltable.h similarity index 80% rename from components/lua/ltable.h rename to components/lua/lua-5.1/ltable.h index d8c26d9a..eb844ba1 100644 --- a/components/lua/ltable.h +++ b/components/lua/lua-5.1/ltable.h @@ -16,26 +16,24 @@ #define gnext(n) ((n)->i_key.nk.next) #define key2tval(n) (&(n)->i_key.tvk) - +#define isrotable(t) (gettt(t)==LUA_TROTABLE) +#define isrwtable(t) (gettt(t)==LUA_TTABLE) LUAI_FUNC const TValue *luaH_getnum (Table *t, int key); -LUAI_FUNC const TValue *luaH_getnum_ro (void *t, int key); LUAI_FUNC TValue *luaH_setnum (lua_State *L, Table *t, int key); LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); -LUAI_FUNC const TValue *luaH_getstr_ro (void *t, TString *key); LUAI_FUNC TValue *luaH_setstr (lua_State *L, Table *t, TString *key); LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); -LUAI_FUNC const TValue *luaH_get_ro (void *t, const TValue *key); LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key); LUAI_FUNC Table *luaH_new (lua_State *L, int narray, int lnhash); LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize); LUAI_FUNC void luaH_free (lua_State *L, Table *t); LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); -LUAI_FUNC int luaH_next_ro (lua_State *L, void *t, StkId key); LUAI_FUNC int luaH_getn (Table *t); -LUAI_FUNC int luaH_getn_ro (void *t); LUAI_FUNC int luaH_isdummy (Node *n); +#define LUA_MAX_ROTABLE_NAME 32 + #if defined(LUA_DEBUG) LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); #endif diff --git a/components/lua/ltablib.c b/components/lua/lua-5.1/ltablib.c similarity index 98% rename from components/lua/ltablib.c rename to components/lua/lua-5.1/ltablib.c index 16035813..57e66e24 100644 --- a/components/lua/ltablib.c +++ b/components/lua/lua-5.1/ltablib.c @@ -7,13 +7,11 @@ #define ltablib_c #define LUA_LIB -#define LUAC_CROSS_FILE #include "lua.h" #include "lauxlib.h" #include "lualib.h" -#include "lrotable.h" #define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_getn(L, n)) @@ -22,7 +20,7 @@ static int foreachi (lua_State *L) { int i; int n = aux_getn(L, 1); - luaL_checkanyfunction(L, 2); + luaL_checkfunction(L, 2); for (i=1; i <= n; i++) { lua_pushvalue(L, 2); /* function */ lua_pushinteger(L, i); /* 1st argument */ @@ -38,7 +36,7 @@ static int foreachi (lua_State *L) { static int foreach (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); - luaL_checkanyfunction(L, 2); + luaL_checkfunction(L, 2); lua_pushnil(L); /* first key */ while (lua_next(L, 1)) { lua_pushvalue(L, 2); /* function */ @@ -266,7 +264,7 @@ static int sort (lua_State *L) { /* }====================================================== */ -LROT_PUBLIC_BEGIN(tab_funcs) +LROT_BEGIN(tab_funcs, NULL, 0) LROT_FUNCENTRY( concat, tconcat ) LROT_FUNCENTRY( foreach, foreach ) LROT_FUNCENTRY( foreachi, foreachi ) diff --git a/components/lua/ltm.c b/components/lua/lua-5.1/ltm.c similarity index 62% rename from components/lua/ltm.c rename to components/lua/lua-5.1/ltm.c index 6f5962db..15578245 100644 --- a/components/lua/ltm.c +++ b/components/lua/lua-5.1/ltm.c @@ -5,37 +5,35 @@ */ +#include + #define ltm_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" -#include #include "lobject.h" #include "lstate.h" -#include "lgc.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" -#include "lrotable.h" - +/* These must be correspond to the LUA_T* defines in lua.h */ const char *const luaT_typenames[] = { - "nil", "boolean", "romtable", "lightfunction", "userdata", "number", - "string", "table", "function", "userdata", "thread", + "nil", "boolean", "lightfunction","number", // base type = 0, 1, 2, 3 + "string", "table", "function", "userdata", "thread", // base type = 4, 5, 6, 7, 8 "proto", "upval" }; - void luaT_init (lua_State *L) { static const char *const luaT_eventname[] = { /* ORDER TM */ "__index", "__newindex", "__gc", "__mode", "__eq", "__add", "__sub", "__mul", "__div", "__mod", "__pow", "__unm", "__len", "__lt", "__le", - "__concat", "__call" + "__concat", "__call", + "__metatable" }; int i; for (i=0; iflags |= cast_byte(1u<flags |= cast_byte(1u<metatable; - break; case LUA_TROTABLE: - mt = (Table*)luaR_getmeta(rvalue(o)); + mt = hvalue(o)->metatable; break; case LUA_TUSERDATA: mt = uvalue(o)->metatable; break; default: - mt = G(L)->mt[ttype(o)]; + mt = G(L)->mt[ttnov(o)]; } - if (!mt) - return luaO_nilobject; - else if (luaR_isrotable(mt)) - return luaH_getstr_ro(mt, G(L)->tmname[event]); - else - return luaH_getstr(mt, G(L)->tmname[event]); + return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject); } diff --git a/components/lua/ltm.h b/components/lua/lua-5.1/ltm.h similarity index 82% rename from components/lua/ltm.h rename to components/lua/lua-5.1/ltm.h index b5fe8e36..d0b18671 100644 --- a/components/lua/ltm.h +++ b/components/lua/lua-5.1/ltm.h @@ -7,10 +7,6 @@ #ifndef ltm_h #define ltm_h - -#include "lobject.h" -#include "lrotable.h" - /* * WARNING: if you change the order of this enumeration, * grep "ORDER TM" @@ -33,13 +29,16 @@ typedef enum { TM_LE, TM_CONCAT, TM_CALL, + TM_METATABLE, TM_N /* number of elements in the enum */ } TMS; -#define gfasttm(g,et,e) ((et) == NULL ? NULL : \ - (!luaR_isrotable(et) && ((et)->flags & (1u<<(e)))) ? NULL : luaT_gettm(et, e, (g)->tmname[e])) +//#include "lobject.h" -#define fasttm(l,et,e) gfasttm(G(l), et, e) +#define gfasttm(g,et,e) ((et) == NULL ? NULL : \ + (getflags(et) & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e])) + +#define fasttm(l,et,e) gfasttm(G(l), et, e) LUAI_DATA const char *const luaT_typenames[]; diff --git a/components/lua/lua-5.1/lua.c b/components/lua/lua-5.1/lua.c new file mode 100644 index 00000000..39b5d01b --- /dev/null +++ b/components/lua/lua-5.1/lua.c @@ -0,0 +1,5 @@ +#include "llimits.h" +#include "lauxlib.h" +#include "lualib.h" +#define LUA_VERSION_51 +#include "../lua-5.3/lua.c" diff --git a/components/lua/lua.h b/components/lua/lua-5.1/lua.h similarity index 75% rename from components/lua/lua.h rename to components/lua/lua-5.1/lua.h index 25348c31..a184c398 100644 --- a/components/lua/lua.h +++ b/components/lua/lua-5.1/lua.h @@ -8,13 +8,11 @@ #ifndef lua_h #define lua_h -#ifdef LUAC_CROSS_FILE -#include "luac_cross.h" -#endif +#include #include #include #include -#include + #include "luaconf.h" @@ -41,7 +39,8 @@ #define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i)) -/* thread status; 0 is OK */ +/* thread status */ +#define LUA_OK 0 #define LUA_YIELD 1 #define LUA_ERRRUN 2 #define LUA_ERRSYNTAX 3 @@ -72,18 +71,22 @@ typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); ** basic types */ #define LUA_TNONE (-1) - #define LUA_TNIL 0 #define LUA_TBOOLEAN 1 -#define LUA_TROTABLE 2 -#define LUA_TLIGHTFUNCTION 3 -#define LUA_TLIGHTUSERDATA 4 -#define LUA_TNUMBER 5 -#define LUA_TSTRING 6 -#define LUA_TTABLE 7 -#define LUA_TFUNCTION 8 -#define LUA_TUSERDATA 9 -#define LUA_TTHREAD 10 +#define LUA_TLIGHTUSERDATA 2 +#define LUA_TNUMBER 3 +#define LUA_TSTRING 4 +#define LUA_TTABLE 5 +#define LUA_TFUNCTION 6 +#define LUA_TUSERDATA 7 +#define LUA_TTHREAD 8 + +#define LUA_TISROTABLE (1<<4) +#define LUA_TISLIGHTFUNC (1<<5) +#define LUA_TMASK 15 + +#define LUA_TROTABLE (LUA_TTABLE + LUA_TISROTABLE) +#define LUA_TLIGHTFUNCTION (LUA_TFUNCTION + LUA_TISLIGHTFUNC) /* minimum Lua stack available to a C function */ #define LUA_MINSTACK 20 @@ -96,18 +99,14 @@ typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); #include LUA_USER_H #endif -#if defined(LUA_OPTIMIZE_DEBUG) && LUA_OPTIMIZE_DEBUG == 0 -#undef LUA_OPTIMIZE_DEBUG -#endif - /* type of numbers in Lua */ typedef LUA_NUMBER lua_Number; +typedef LUA_FLOAT lua_Float; /* type for integer functions */ typedef LUA_INTEGER lua_Integer; - - +typedef LUAI_UINT32 lua_Unsigned; /* ** state manipulation @@ -122,6 +121,7 @@ LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); /* ** basic stack manipulation */ +LUA_API int (lua_absindex) (lua_State *L, int idx); LUA_API int (lua_gettop) (lua_State *L); LUA_API void (lua_settop) (lua_State *L, int idx); LUA_API void (lua_pushvalue) (lua_State *L, int idx); @@ -142,11 +142,14 @@ LUA_API int (lua_isstring) (lua_State *L, int idx); LUA_API int (lua_iscfunction) (lua_State *L, int idx); LUA_API int (lua_isuserdata) (lua_State *L, int idx); LUA_API int (lua_type) (lua_State *L, int idx); +LUA_API int (lua_fulltype) (lua_State *L, int idx); LUA_API const char *(lua_typename) (lua_State *L, int tp); -LUA_API int (lua_equal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2); +LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); +#define LUA_OPEQ 0 +#define LUA_OPLT 1 +#define LUA_OPLE 2 +LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op); LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx); LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx); @@ -173,18 +176,17 @@ LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); LUA_API void (lua_pushboolean) (lua_State *L, int b); LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); -LUA_API void (lua_pushlightfunction) (lua_State *L, void *p); -LUA_API void (lua_pushrotable) (lua_State *L, void *p); LUA_API int (lua_pushthread) (lua_State *L); /* ** get functions (Lua -> stack) */ -LUA_API void (lua_gettable) (lua_State *L, int idx); -LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawget) (lua_State *L, int idx); -LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); +LUA_API int (lua_gettable) (lua_State *L, int idx); +LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k); +LUA_API int (lua_rawget) (lua_State *L, int idx); +LUA_API int (lua_rawgeti) (lua_State *L, int idx, int n); +LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p); LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); LUA_API int (lua_getmetatable) (lua_State *L, int objindex); @@ -198,6 +200,7 @@ LUA_API void (lua_settable) (lua_State *L, int idx); LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); LUA_API void (lua_rawset) (lua_State *L, int idx); LUA_API void (lua_rawseti) (lua_State *L, int idx, int n); +LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p); LUA_API int (lua_setmetatable) (lua_State *L, int objindex); LUA_API int (lua_setfenv) (lua_State *L, int idx); @@ -210,8 +213,8 @@ LUA_API int (lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc); LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud); LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, const char *chunkname); - -LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data); +LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int stripping); +LUA_API int (lua_stripdebug) (lua_State *L, int stripping); /* @@ -271,10 +274,8 @@ LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); #define lua_strlen(L,i) lua_objlen(L, (i)) #define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) -#define lua_islightfunction(L,n) (lua_type(L, (n)) == LUA_TLIGHTFUNCTION) #define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) -#define lua_isrotable(L,n) (lua_type(L, (n)) == LUA_TROTABLE) -#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) +#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) #define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) #define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) #define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) @@ -289,14 +290,24 @@ LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); #define lua_tostring(L,i) lua_tolstring(L, (i), NULL) +#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) +#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) +#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) +#define lua_tounsigned(L,i) ((lua_Unsigned)lua_tointeger(L,i)) + +/* error codes from cross-compiler returned by lua_dump */ +/* 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 /* ** compatibility macros and functions */ // BogdanM: modified for eLua interrupt support -//#define lua_open() luaL_newstate() lua_State* lua_open(void); lua_State* lua_getstate(void); @@ -372,24 +383,62 @@ struct lua_Debug { int i_ci; /* active function */ }; +int lua_main(void); +void lua_input_string (const char *line, int len); + /* }====================================================================== */ -typedef struct __lua_load{ - lua_State *L; - int firstline; - char *line; - int line_position; - size_t len; - int done; - const char *prmt; -}lua_Load; +/* NodeMCU extensions to the standard API */ -int lua_main( int argc, char **argv ); +typedef struct ROTable ROTable; +typedef const struct ROTable_entry ROTable_entry; + +LUA_API void (lua_pushrotable) (lua_State *L, const ROTable *p); +LUA_API void (lua_createrotable) (lua_State *L, ROTable *t, ROTable_entry *e, ROTable *mt); +LUA_API int (lua_pushstringsarray) (lua_State *L, int opt); +LUA_API int (lua_freeheap) (void); + +LUA_API void (lua_getlfsconfig) (lua_State *L, int *); +LUA_API int (lua_pushlfsindex) (lua_State *L); + +#define EGC_NOT_ACTIVE 0 // EGC disabled +#define EGC_ON_ALLOC_FAILURE 1 // run EGC on allocation failure +#define EGC_ON_MEM_LIMIT 2 // run EGC when an upper memory limit is hit +#define EGC_ALWAYS 4 // always run EGC before an allocation + +#ifdef LUA_USE_ESP + +#define LUA_QUEUE_APP 0 +#define LUA_QUEUE_UART 1 + +/**DEBUG**/extern void dbg_printf(const char *fmt, ...) + __attribute__ ((format (printf, 1, 2))); +#define luaN_freearray(L,b,l) luaM_freearray(L,b,l,sizeof(*b)) + +LUA_API void (lua_setegcmode) (lua_State *L, int mode, int limit); +LUA_API void (lua_getegcinfo) (lua_State *L, int *totals); + +#else + +#define ICACHE_RODATA_ATTR +#define dbg_printf printf -#ifndef LUA_CROSS_COMPILER -void lua_handle_input (bool force); #endif +#ifdef DEVELOPMENT_USE_GDB +LUALIB_API void (lua_debugbreak)(void); +#else +#define lua_debugbreak() (void)(0) +#endif + +// EGC operations modes +#define EGC_NOT_ACTIVE 0 // EGC disabled +#define EGC_ON_ALLOC_FAILURE 1 // run EGC on allocation failure +#define EGC_ON_MEM_LIMIT 2 // run EGC when an upper memory limit is hit +#define EGC_ALWAYS 4 // always run EGC before an allocation + +void legc_set_mode(lua_State *L, int mode, int limit); + /****************************************************************************** * Copyright (C) 1994-2008 Lua.org, PUC-Rio. All rights reserved. * diff --git a/components/lua/luaconf.h b/components/lua/lua-5.1/luaconf.h similarity index 93% rename from components/lua/luaconf.h rename to components/lua/lua-5.1/luaconf.h index 075fc24e..fc78d2ef 100644 --- a/components/lua/luaconf.h +++ b/components/lua/lua-5.1/luaconf.h @@ -155,6 +155,11 @@ #define LUA_EXECDIR "!" #define LUA_IGMARK "-" +#ifdef CONFIG_LUA_NUMBER_INTEGRAL +# define LUA_NUMBER_INTEGRAL +#else +# define LUA_PACK_TVALUES +#endif /* @@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger. @@ -265,16 +270,6 @@ #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. ** CHANGE it if your stand-alone interpreter has a different name and @@ -299,54 +294,34 @@ ** CHANGE them if you want to improve this functionality (e.g., by using ** GNU readline and history facilities). */ -#if defined(LUA_USE_STDIO) -#if defined(LUA_CROSS_COMPILER) && defined(LUA_USE_READLINE) -#include -#include -#include -#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, stdout), fflush(stdout), /* show prompt */ \ - fgets(b, LUA_MAXINPUT, 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_saveline(L,idx) { (void)L; (void)idx; } #define lua_freeline(L,b) { (void)L; (void)b; } 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/lua_writeline define how 'print' prints its results. ** They are only used in libraries and the stand-alone program. (The #if ** avoids including 'stdio.h' everywhere.) */ -#if !defined(LUA_USE_STDIO) -#define luai_writestring(s, l) fwrite(s, 1, l, stdout) -#define luai_writeline() puts("") -#endif // defined(LUA_USE_STDIO) +#ifdef LUA_USE_ESP +void output_redirect(const char *str, size_t l); +#define lua_writestring(s,l) output_redirect((s),(l)) +#else +#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...) */ -#if !defined(LUA_USE_STDIO) -#define luai_writestringerror(s,p) printf((s), (p)) -#endif // defined(LUA_USE_STDIO) - - -/* }================================================================== */ +#ifdef LUA_USE_ESP +#define lua_writestringerror(s,p) dbg_printf((s), (p)) +#else +#define lua_writestringerror(s,p) fprintf(stderr, (s), (p)) +#endif /* @@ -586,6 +561,7 @@ extern int readline4lua(const char *prompt, char *buffer, int length); #define LUA_NUMBER_DOUBLE #define LUA_NUMBER double #endif +#define LUA_FLOAT double /* @@ LUAI_UACNUMBER is the result of an 'usual argument conversion' @@ -897,4 +873,6 @@ union luai_Cast { double l_d; long l_l; }; #error "Pipes not supported NodeMCU firmware" #endif +#define LUA_DEBUG_HOOK lua_debugbreak + #endif diff --git a/components/lua/lualib.h b/components/lua/lua-5.1/lualib.h similarity index 95% rename from components/lua/lualib.h rename to components/lua/lua-5.1/lualib.h index 9e4e7aea..f116a65b 100644 --- a/components/lua/lualib.h +++ b/components/lua/lua-5.1/lualib.h @@ -41,7 +41,7 @@ LUALIB_API int (luaopen_package) (lua_State *L); /* open all previous libraries */ -LUALIB_API void (luaL_openlibs) (lua_State *L); +LUALIB_API void (luaL_openlibs) (lua_State *L); diff --git a/components/lua/lundump.c b/components/lua/lua-5.1/lundump.c similarity index 84% rename from components/lua/lundump.c rename to components/lua/lua-5.1/lundump.c index 4def50de..eb35a26e 100644 --- a/components/lua/lundump.c +++ b/components/lua/lua-5.1/lundump.c @@ -6,7 +6,6 @@ #define lundump_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -164,16 +163,9 @@ static TString* LoadString(LoadState* S) return NULL; else { - char* s; - if (!luaZ_direct_mode(S->Z)) { - s = luaZ_openspace(S->L,S->b,size); - 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); - } + char* s = luaZ_openspace(S->L,S->b,size); + LoadBlock(S,s,size); + return luaS_newlstr(S->L,s,size-1); /* remove trailing zero */ } } @@ -181,13 +173,8 @@ static void LoadCode(LoadState* S, Proto* f) { int n=LoadInt(S); Align4(S); - if (!luaZ_direct_mode(S->Z)) { - f->code=luaM_newvector(S->L,n,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->code=luaM_newvector(S->L,n,Instruction); + LoadVector(S,f->code,n,sizeof(Instruction)); f->sizecode=n; } @@ -236,28 +223,12 @@ static void LoadDebug(LoadState* S, Proto* f) n=LoadInt(S); Align4(S); -#ifdef LUA_OPTIMIZE_DEBUG if(n) { - if (!luaZ_direct_mode(S->Z)) { - f->packedlineinfo=luaM_newvector(S->L,n,unsigned char); - LoadBlock(S,f->packedlineinfo,n); - } else { - f->packedlineinfo=(unsigned char*)luaZ_get_crt_address(S->Z); - LoadBlock(S,NULL,n); - } + f->packedlineinfo=luaM_newvector(S->L,n,unsigned char); + LoadBlock(S,f->packedlineinfo,n); } else { f->packedlineinfo=NULL; } -#else - if (!luaZ_direct_mode(S->Z)) { - f->lineinfo=luaM_newvector(S->L,n,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; - #endif n=LoadInt(S); f->locvars=luaM_newvector(S->L,n,LocVar); f->sizelocvars=n; @@ -280,7 +251,6 @@ static Proto* LoadFunction(LoadState* S, TString* p) Proto* f; if (++S->L->nCcalls > LUAI_MAXCCALLS) error(S,"code too deep"); 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); f->source=LoadString(S); if (f->source==NULL) f->source=p; f->linedefined=LoadInt(S); diff --git a/components/lua/lundump.h b/components/lua/lua-5.1/lundump.h similarity index 85% rename from components/lua/lundump.h rename to components/lua/lua-5.1/lundump.h index eaa58597..ce3e60f1 100644 --- a/components/lua/lundump.h +++ b/components/lua/lua-5.1/lundump.h @@ -50,11 +50,4 @@ LUAI_FUNC void luaU_print (const Proto* f, int full); /* size of header of binary files */ #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 diff --git a/components/lua/lvm.c b/components/lua/lua-5.1/lvm.c similarity index 96% rename from components/lua/lvm.c rename to components/lua/lua-5.1/lvm.c index c3c971c6..c41ab1be 100644 --- a/components/lua/lvm.c +++ b/components/lua/lua-5.1/lvm.c @@ -7,7 +7,6 @@ #define lvm_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -25,7 +24,6 @@ #include "ltable.h" #include "ltm.h" #include "lvm.h" -#include "lrotable.h" /* limit for table tag-method chains (to avoid loops) */ @@ -41,7 +39,7 @@ LUA_NUMBER luai_ipow(LUA_NUMBER a, LUA_NUMBER b) { LUA_NUMBER c = 1; for (;;) { if (b & 1) - c *= a; + c *= a; b = b >> 1; if (b == 0) return c; @@ -134,26 +132,17 @@ void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { if (ttistable(t)) { /* `t' is a table? */ Table *h = hvalue(t); 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? */ setobj2s(L, val, res); return; } /* 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))) luaG_typeerror(L, t, "index"); - if (ttisfunction(tm) || ttislightfunction(tm)) { + if (ttisfunction(tm)) { callTMres(L, val, tm, t, key); return; } @@ -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))) luaG_typeerror(L, t, "index"); - if (ttisfunction(tm) || ttislightfunction(tm)) { + if (ttisfunction(tm)) { L->top--; unfixedstack(L); callTM(L, tm, t, key, val); @@ -282,7 +271,7 @@ int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { } -static int lessequal (lua_State *L, const TValue *l, const TValue *r) { +int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) { int res; if (ttype(l) != ttype(r)) return luaG_ordererror(L, l, r); @@ -305,8 +294,6 @@ int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) { case LUA_TNIL: return 1; case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); 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_TLIGHTFUNCTION: return pvalue(t1) == pvalue(t2); @@ -316,6 +303,8 @@ int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) { TM_EQ); break; /* will try TM */ } + case LUA_TROTABLE: + return hvalue(t1) == hvalue(t2); case LUA_TTABLE: { if (hvalue(t1) == hvalue(t2)) return 1; 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, } - void luaV_execute (lua_State *L, int nexeccalls) { LClosure *cl; StkId base; @@ -582,10 +570,9 @@ void luaV_execute (lua_State *L, int nexeccalls) { } case OP_LEN: { const TValue *rb = RB(i); - switch (ttype(rb)) { - case LUA_TTABLE: - case LUA_TROTABLE: { - setnvalue(ra, ttistable(rb) ? cast_num(luaH_getn(hvalue(rb))) : cast_num(luaH_getn_ro(rvalue(rb)))); + switch (ttnov(rb)) { + case LUA_TTABLE: { + setnvalue(ra, cast_num(luaH_getn(hvalue(rb)))); break; } case LUA_TSTRING: { @@ -633,7 +620,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { } case OP_LE: { Protect( - if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i)) + if (luaV_lessequal(L, RKB(i), RKC(i)) == GETARG_A(i)) dojump(L, pc, GETARG_sBx(*pc)); ) pc++; @@ -785,7 +772,7 @@ void luaV_execute (lua_State *L, int nexeccalls) { setobj2t(L, luaH_setnum(L, h, last--), val); luaC_barriert(L, h, val); } - L->top = L->ci->top; + L->top = L->ci->top; unfixedstack(L); continue; } diff --git a/components/lua/lvm.h b/components/lua/lua-5.1/lvm.h similarity index 93% rename from components/lua/lvm.h rename to components/lua/lua-5.1/lvm.h index bfe4f567..2c618593 100644 --- a/components/lua/lvm.h +++ b/components/lua/lua-5.1/lvm.h @@ -23,6 +23,7 @@ LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); +LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r); LUAI_FUNC int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2); LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n); LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj); diff --git a/components/lua/lzio.c b/components/lua/lua-5.1/lzio.c similarity index 96% rename from components/lua/lzio.c rename to components/lua/lua-5.1/lzio.c index 16108489..52166e18 100644 --- a/components/lua/lzio.c +++ b/components/lua/lua-5.1/lzio.c @@ -7,7 +7,6 @@ #define lzio_c #define LUA_CORE -#define LUAC_CROSS_FILE #include "lua.h" #include @@ -49,7 +48,7 @@ void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { z->L = L; z->reader = reader; z->data = data; - z->n = z->i = 0; + z->n = 0; z->p = NULL; } @@ -64,7 +63,6 @@ size_t luaZ_read (ZIO *z, void *b, size_t n) { if (b) memcpy(b, z->p, m); z->n -= m; - z->i += m; z->p += m; if (b) b = (char *)b + m; diff --git a/components/lua/lzio.h b/components/lua/lua-5.1/lzio.h similarity index 85% rename from components/lua/lzio.h rename to components/lua/lua-5.1/lzio.h index 7a31475e..d446af40 100644 --- a/components/lua/lzio.h +++ b/components/lua/lua-5.1/lzio.h @@ -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_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 void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, @@ -59,7 +56,6 @@ LUAI_FUNC int luaZ_lookahead (ZIO *z); struct Zio { size_t n; /* bytes still unread */ - size_t i; /* buffer offset */ const char *p; /* current position in buffer */ lua_Reader reader; void* data; /* additional data */ diff --git a/components/lua/lua-5.3/Makefile b/components/lua/lua-5.3/Makefile new file mode 100644 index 00000000..47c39abb --- /dev/null +++ b/components/lua/lua-5.3/Makefile @@ -0,0 +1,52 @@ + +############################################################# +# 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 + + +# Validate LUA setting +ifeq ("$(LUA)","53") + # ok +else ifeq ("$(LUA)","51") + $(error Your variable LUA="$(LUA)" looks like you probably want \ + app/lua/Makefile instead) +else + $(error Expected environment variable "LUA" to be "53", not "$(LUA)") +endif + + +############################################################# +# 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 diff --git a/components/lua/lua-5.3/host/idf.mk b/components/lua/lua-5.3/host/idf.mk new file mode 100644 index 00000000..8dfba397 --- /dev/null +++ b/components/lua/lua-5.3/host/idf.mk @@ -0,0 +1,69 @@ +all: build + +HOSTCC?=$(PYTHON) -m ziglang cc + +ifeq ($V,) + Q:=@ +endif + +LUAC_OBJ_DIR:=$(LUAC_BUILD_DIR)/$(notdir $(LUA_PATH)) + +LUAC_CFLAGS:= \ + -I$(LUAC_BUILD_DIR) \ + -I$(LUA_PATH) \ + -I$(LUA_PATH)/host \ + -I$(LUA_PATH)/../common \ + -I$(LUA_PATH)/../../uzlib \ + -O2 -g -Wall -Wextra -Wno-sign-compare -Wno-string-plus-int + +LUAC_LDFLAGS:= -ldl -lm + +LUAC_DEFINES += \ + -DLUA_CROSS_COMPILER \ + -DLUA_USE_HOST \ + -DLUA_USE_STDIO \ + +vpath %.c $(LUA_PATH)/host $(LUA_PATH) $(LUA_PATH)/../common $(LUA_PATH)/../../uzlib + +LUA_SRCS:=\ + luac.c loslib.c liolib.c \ + lapi.c lauxlib.c lbaselib.c lbitlib.c lcode.c lcorolib.c \ + lctype.c ldblib.c ldebug.c ldo.c ldump.c lfunc.c \ + lgc.c llex.c lmathlib.c lmem.c lnodemcu.c loadlib.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 \ + linit.c lpanic.c \ + uzlib_deflate.c crc32.c \ + +LUAC_OBJS:=$(LUA_SRCS:%.c=$(LUAC_OBJ_DIR)/%.o) +LUAC_CROSS:=$(LUAC_BUILD_DIR)/luac.cross + +$(LUAC_OBJ_DIR): + @mkdir -p "$@" + +$(LUAC_OBJ_DIR)/%.o: %.c | $(LUAC_OBJ_DIR) + @echo '[hostcc] $(notdir $@)' + $Q$(HOSTCC) $(LUAC_DEFINES) $(LUAC_CFLAGS) "$<" -c -o "$@" + +$(LUAC_OBJ_DIR)/%.d: SHELL=/bin/bash +$(LUAC_OBJ_DIR)/%.d: %.c | $(LUAC_OBJ_DIR) + @echo '[ dep] $<' + @rm -f "$@" + $Qset -eo pipefail; $(HOSTCC) $(LUAC_DEFINES) $(LUAC_CFLAGS) -M "$<" | sed 's,\($*\.o\)[ :]*,$(LUAC_OBJ_DIR)/\1 $@ : ,g' > "$@.tmp"; mv "$@.tmp" "$@" + +build: $(LUAC_DEPS) $(LUAC_CROSS) + +$(LUAC_CROSS): $(LUAC_OBJS) + @echo '[ link] $(notdir $@)' + $Q$(HOSTCC) $(LUAC_CFLAGS) $^ $(LUAC_LDFLAGS) -o "$@" + +# zig cc (0.8.0 at least) seems to get itself all confused with its cache +# when we're running a separate path for dependencies, so we skip them for +# now as for most people they're not needed anyway. +ifneq ($(findstring zig,$(HOSTCC)),zig) + LUAC_DEPS:=$(LUAC_OBJS:%.o=%.d) + ifneq ($(MAKECMDGOALS),clean) + -include $(LUAC_DEPS) + endif +endif diff --git a/components/lua/lua-5.3/host/liolib.c b/components/lua/lua-5.3/host/liolib.c new file mode 100644 index 00000000..8a9e75cd --- /dev/null +++ b/components/lua/lua-5.3/host/liolib.c @@ -0,0 +1,776 @@ +/* +** $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 +#include +#include +#include +#include +#include + +#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 + +#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; +} + diff --git a/components/lua/lua-5.3/host/loslib.c b/components/lua/lua-5.3/host/loslib.c new file mode 100644 index 00000000..7079ca4d --- /dev/null +++ b/components/lua/lua-5.3/host/loslib.c @@ -0,0 +1,409 @@ +/* +** $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 +#include +#include +#include +#include + +#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 + +#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; +} + diff --git a/components/lua/lua-5.3/host/luac.c b/components/lua/lua-5.3/host/luac.c new file mode 100644 index 00000000..02a55389 --- /dev/null +++ b/components/lua/lua-5.3/host/luac.c @@ -0,0 +1,623 @@ +/* + ** $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 +#include +#include +#include +#include +#include +#include + +#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; + +#if 0 +#define IROM0_SEG 0x40200000ul +#define IROM0_SEGMAX 0x00100000ul +#define IROM_OFFSET(a) (cast(lu_int32, (a)) - IROM0_SEG) +#else +// Safety checks disabled for now; would need to handle ESP32/ESP32S/ESP32C3 +#define IROM_OFFSET(a) +#endif + + +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); +#if 0 + offset = IROM_OFFSET(address); + if (offset == 0 || offset > IROM0_SEGMAX) + usage("\"-a\" absolute address must be valid flash address"); +#endif + } 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("\"-m\" 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) { + (void)L; + 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) { + const char *res = luaL_optstring(L, -1, ""); + if (strcmp(res, "!LFSrestart!") == 0) { + /*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 +#include + +#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; ik[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; pc0) 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; isizelocvars; + printf("locals (%d) for %p:\n",n,VOID(f)); + for (i=0; ilocvars[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; iupvalues[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; ip[i],full); +} diff --git a/components/lua/lua-5.3/lapi.c b/components/lua/lua-5.3/lapi.c new file mode 100644 index 00000000..4619b14a --- /dev/null +++ b/components/lua/lua-5.3/lapi.c @@ -0,0 +1,1348 @@ +/* +** $Id: lapi.c,v 2.259.1.2 2017/12/06 18:35:12 roberto Exp $ +** Lua API +** See Copyright Notice in lua.h +*/ + +#define lapi_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include + +#include "lua.h" + +#include "lapi.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lundump.h" +#include "lvm.h" + + + +const char lua_ident[] = + "$LuaVersion: " LUA_COPYRIGHT " $" + "$LuaAuthors: " LUA_AUTHORS " $"; + + +/* value at a non-valid index */ +#define NONVALIDVALUE cast(TValue *, luaO_nilobject) + +/* corresponding test */ +#define isvalid(o) ((o) != luaO_nilobject) + +/* test for pseudo index */ +#define ispseudo(i) ((i) <= LUA_REGISTRYINDEX) + +/* test for upvalue */ +#define isupvalue(i) ((i) < LUA_REGISTRYINDEX) + +/* test for valid but not pseudo index */ +#define isstackindex(i, o) (isvalid(o) && !ispseudo(i)) + +#define api_checkvalidindex(l,o) api_check(l, isvalid(o), "invalid index") + +#define api_checkstackindex(l, i, o) \ + api_check(l, isstackindex(i, o), "index not in the stack") + + +static TValue *index2addr (lua_State *L, int idx) { + CallInfo *ci = L->ci; + if (idx > 0) { + TValue *o = ci->func + idx; + api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index"); + if (o >= L->top) return NONVALIDVALUE; + else return o; + } + else if (!ispseudo(idx)) { /* negative index */ + api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index"); + return L->top + idx; + } + else if (idx == LUA_REGISTRYINDEX) + return &G(L)->l_registry; + else { /* upvalues */ + idx = LUA_REGISTRYINDEX - idx; + api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large"); + if (ttislcf(ci->func)) /* light C function? */ + return NONVALIDVALUE; /* it has no upvalues */ + else { + CClosure *func = clCvalue(ci->func); + return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : NONVALIDVALUE; + } + } +} + + +/* +** to be called by 'lua_checkstack' in protected mode, to grow stack +** capturing memory errors +*/ +static void growstack (lua_State *L, void *ud) { + int size = *(int *)ud; + luaD_growstack(L, size); +} + + +LUA_API int lua_checkstack (lua_State *L, int n) { + int res; + CallInfo *ci = L->ci; + lua_lock(L); + api_check(L, n >= 0, "negative 'n'"); + if (L->stack_last - L->top > n) /* stack large enough? */ + res = 1; /* yes; check is OK */ + else { /* no; need to grow stack */ + int inuse = cast_int(L->top - L->stack) + EXTRA_STACK; + if (inuse > LUAI_MAXSTACK - n) /* can grow without overflow? */ + res = 0; /* no */ + else /* try to grow stack */ + res = (luaD_rawrunprotected(L, &growstack, &n) == LUA_OK); + } + if (res && ci->top < L->top + n) + ci->top = L->top + n; /* adjust frame top */ + lua_unlock(L); + return res; +} + + +LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { + int i; + if (from == to) return; + lua_lock(to); + api_checknelems(from, n); + api_check(from, G(from) == G(to), "moving among independent states"); + api_check(from, to->ci->top - to->top >= n, "stack overflow"); + from->top -= n; + for (i = 0; i < n; i++) { + setobj2s(to, to->top, from->top + i); + to->top++; /* stack already checked by previous 'api_check' */ + } + lua_unlock(to); +} + + +LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) { + lua_CFunction old; + lua_lock(L); + old = G(L)->panic; + G(L)->panic = panicf; + lua_unlock(L); + return old; +} + + +LUA_API const lua_Number *lua_version (lua_State *L) { + static const lua_Number version = LUA_VERSION_NUM; + if (L == NULL) return &version; + else return G(L)->version; +} + + + +/* +** basic stack manipulation +*/ + + +/* +** convert an acceptable stack index into an absolute index +*/ +LUA_API int lua_absindex (lua_State *L, int idx) { + return (idx > 0 || ispseudo(idx)) + ? idx + : cast_int(L->top - L->ci->func) + idx; +} + + +LUA_API int lua_gettop (lua_State *L) { + return cast_int(L->top - (L->ci->func + 1)); +} + + +LUA_API void lua_settop (lua_State *L, int idx) { + StkId func = L->ci->func; + lua_lock(L); + if (idx >= 0) { + api_check(L, idx <= L->stack_last - (func + 1), "new top too large"); + while (L->top < (func + 1) + idx) + setnilvalue(L->top++); + L->top = (func + 1) + idx; + } + else { + api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top"); + L->top += idx+1; /* 'subtract' index (index is negative) */ + } + lua_unlock(L); +} + + +/* +** Reverse the stack segment from 'from' to 'to' +** (auxiliary to 'lua_rotate') +*/ +static void reverse (lua_State *L, StkId from, StkId to) { + for (; from < to; from++, to--) { + TValue temp; + setobj(L, &temp, from); + setobjs2s(L, from, to); + setobj2s(L, to, &temp); + } +} + + +/* +** Let x = AB, where A is a prefix of length 'n'. Then, +** rotate x n == BA. But BA == (A^r . B^r)^r. +*/ +LUA_API void lua_rotate (lua_State *L, int idx, int n) { + StkId p, t, m; + lua_lock(L); + t = L->top - 1; /* end of stack segment being rotated */ + p = index2addr(L, idx); /* start of segment */ + api_checkstackindex(L, idx, p); + api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'"); + m = (n >= 0 ? t - n : p - n - 1); /* end of prefix */ + reverse(L, p, m); /* reverse the prefix with length 'n' */ + reverse(L, m + 1, t); /* reverse the suffix */ + reverse(L, p, t); /* reverse the entire segment */ + lua_unlock(L); +} + + +LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) { + TValue *fr, *to; + lua_lock(L); + fr = index2addr(L, fromidx); + to = index2addr(L, toidx); + api_checkvalidindex(L, to); + setobj(L, to, fr); + if (isupvalue(toidx)) /* function upvalue? */ + luaC_barrier(L, clCvalue(L->ci->func), fr); + /* LUA_REGISTRYINDEX does not need gc barrier + (collector revisits it before finishing collection) */ + lua_unlock(L); +} + + +LUA_API void lua_pushvalue (lua_State *L, int idx) { + lua_lock(L); + setobj2s(L, L->top, index2addr(L, idx)); + api_incr_top(L); + lua_unlock(L); +} + + + +/* +** access functions (stack -> C) +*/ + + +LUA_API int lua_type (lua_State *L, int idx) { + + StkId o = index2addr(L, idx); + return (isvalid(o) ? ttnov(o) : LUA_TNONE); +} + + +LUA_API const char *lua_typename (lua_State *L, int t) { + UNUSED(L); + api_check(L, LUA_TNONE <= t && t < LUA_NUMTAGS, "invalid tag"); + return ttypename(t); +} + + +LUA_API int lua_iscfunction (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + return (ttislcf(o) || (ttisCclosure(o))); +} + + +LUA_API int lua_isinteger (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + return ttisinteger(o); +} + + +LUA_API int lua_isnumber (lua_State *L, int idx) { + lua_Number n; + const TValue *o = index2addr(L, idx); + return tonumber(o, &n); +} + + +LUA_API int lua_isstring (lua_State *L, int idx) { + const TValue *o = index2addr(L, idx); + return (ttisstring(o) || cvt2str(o)); +} + + +LUA_API int lua_isuserdata (lua_State *L, int idx) { + const TValue *o = index2addr(L, idx); + return (ttisfulluserdata(o) || ttislightuserdata(o)); +} + + +LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { + StkId o1 = index2addr(L, index1); + StkId o2 = index2addr(L, index2); + return (isvalid(o1) && isvalid(o2)) ? luaV_rawequalobj(o1, o2) : 0; +} + + +LUA_API void lua_arith (lua_State *L, int op) { + lua_lock(L); + if (op != LUA_OPUNM && op != LUA_OPBNOT) + api_checknelems(L, 2); /* all other operations expect two operands */ + else { /* for unary operations, add fake 2nd operand */ + api_checknelems(L, 1); + setobjs2s(L, L->top, L->top - 1); + api_incr_top(L); + } + /* first operand at top - 2, second at top - 1; result go to top - 2 */ + luaO_arith(L, op, L->top - 2, L->top - 1, L->top - 2); + L->top--; /* remove second operand */ + lua_unlock(L); +} + + +LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) { + StkId o1, o2; + int i = 0; + lua_lock(L); /* may call tag method */ + o1 = index2addr(L, index1); + o2 = index2addr(L, index2); + if (isvalid(o1) && isvalid(o2)) { + switch (op) { + case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break; + case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break; + case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break; + default: api_check(L, 0, "invalid option"); + } + } + lua_unlock(L); + return i; +} + + +LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) { + size_t sz = luaO_str2num(s, L->top); + if (sz != 0) + api_incr_top(L); + return sz; +} + + +LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) { + lua_Number n; + const TValue *o = index2addr(L, idx); + int isnum = tonumber(o, &n); + if (!isnum) + n = 0; /* call to 'tonumber' may change 'n' even if it fails */ + if (pisnum) *pisnum = isnum; + return n; +} + + +LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) { + lua_Integer res; + const TValue *o = index2addr(L, idx); + int isnum = tointeger(o, &res); + if (!isnum) + res = 0; /* call to 'tointeger' may change 'n' even if it fails */ + if (pisnum) *pisnum = isnum; + return res; +} + + +LUA_API int lua_toboolean (lua_State *L, int idx) { + const TValue *o = index2addr(L, idx); + return !l_isfalse(o); +} + + +LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { + StkId o = index2addr(L, idx); + if (!ttisstring(o)) { + if (!cvt2str(o)) { /* not convertible? */ + if (len != NULL) *len = 0; + return NULL; + } + lua_lock(L); /* 'luaO_tostring' may create a new string */ + luaO_tostring(L, o); + luaC_checkGC(L); + o = index2addr(L, idx); /* previous call may reallocate the stack */ + lua_unlock(L); + } + if (len != NULL) + *len = vslen(o); + return svalue(o); +} + + +LUA_API size_t lua_rawlen (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + switch (ttype(o)) { + case LUA_TSHRSTR: return getshrlen(tsvalue(o)); + case LUA_TLNGSTR: return tsvalue(o)->u.lnglen; + case LUA_TUSERDATA: return uvalue(o)->len; + case LUA_TTBLRAM: return luaH_getn(hvalue(o)); + default: return 0; + } +} + + +LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + if (ttislcf(o)) return fvalue(o); + else if (ttisCclosure(o)) + return clCvalue(o)->f; + else return NULL; /* not a C function */ +} + + +LUA_API void *lua_touserdata (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + switch (ttnov(o)) { + case LUA_TUSERDATA: return getudatamem(uvalue(o)); + case LUA_TLIGHTUSERDATA: return pvalue(o); + default: return NULL; + } +} + + +LUA_API lua_State *lua_tothread (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + return (!ttisthread(o)) ? NULL : thvalue(o); +} + + +LUA_API const void *lua_topointer (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + switch (ttype(o)) { + case LUA_TTBLRAM: + case LUA_TTBLROF: return hvalue(o); + case LUA_TLCL: return clLvalue(o); + case LUA_TCCL: return clCvalue(o); + case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o))); + case LUA_TTHREAD: return thvalue(o); + case LUA_TUSERDATA: return getudatamem(uvalue(o)); + case LUA_TLIGHTUSERDATA: return pvalue(o); + default: return NULL; + } +} + + + +/* +** push functions (C -> stack) +*/ + + +LUA_API void lua_pushnil (lua_State *L) { + lua_lock(L); + setnilvalue(L->top); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { + lua_lock(L); + setfltvalue(L->top, n); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { + lua_lock(L); + setivalue(L->top, n); + api_incr_top(L); + lua_unlock(L); +} + + +/* +** Pushes on the stack a string with given length. Avoid using 's' when +** 'len' == 0 (as 's' can be NULL in that case), due to later use of +** 'memcmp' and 'memcpy'. +*/ +LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) { + TString *ts; + lua_lock(L); + ts = (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len); + setsvalue2s(L, L->top, ts); + api_incr_top(L); + luaC_checkGC(L); + lua_unlock(L); + return getstr(ts); +} + + +LUA_API const char *lua_pushstring (lua_State *L, const char *s) { + lua_lock(L); + if (s == NULL) + setnilvalue(L->top); + else { + TString *ts; + ts = luaS_new(L, s); + setsvalue2s(L, L->top, ts); + s = getstr(ts); /* internal copy's address */ + } + api_incr_top(L); + luaC_checkGC(L); + lua_unlock(L); + return s; +} + + +LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, + va_list argp) { + const char *ret; + lua_lock(L); + ret = luaO_pushvfstring(L, fmt, argp); + luaC_checkGC(L); + lua_unlock(L); + return ret; +} + + +LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { + const char *ret; + va_list argp; + lua_lock(L); + va_start(argp, fmt); + ret = luaO_pushvfstring(L, fmt, argp); + va_end(argp); + luaC_checkGC(L); + lua_unlock(L); + return ret; +} + + +LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { + lua_lock(L); + if (n == 0) { + setfvalue(L->top, fn); + api_incr_top(L); + } + else { + CClosure *cl; + api_checknelems(L, n); + api_check(L, n <= MAXUPVAL, "upvalue index too large"); + cl = luaF_newCclosure(L, n); + cl->f = fn; + L->top -= n; + while (n--) { + setobj2n(L, &cl->upvalue[n], L->top + n); + /* does not need barrier because closure is white */ + } + setclCvalue(L, L->top, cl); + api_incr_top(L); + luaC_checkGC(L); + } + lua_unlock(L); +} + + +LUA_API void lua_pushboolean (lua_State *L, int b) { + lua_lock(L); + setbvalue(L->top, (b != 0)); /* ensure that true is 1 */ + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { + lua_lock(L); + setpvalue(L->top, p); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API int lua_pushthread (lua_State *L) { + lua_lock(L); + setthvalue(L, L->top, L); + api_incr_top(L); + lua_unlock(L); + return (G(L)->mainthread == L); +} + + +LUA_API void lua_pushrotable (lua_State *L, const ROTable *t) { + lua_lock(L); + sethvalue(L, L->top, cast(Table *, t)); + api_incr_top(L); + lua_unlock(L); +} + + +/* +** get functions (Lua -> stack) +*/ + + +static int auxgetstr (lua_State *L, const TValue *t, const char *k) { + const TValue *slot; + TString *str = luaS_new(L, k); + if (luaV_fastget(L, t, str, slot, luaH_getstr)) { + setobj2s(L, L->top, slot); + api_incr_top(L); + } + else { + setsvalue2s(L, L->top, str); + api_incr_top(L); + luaV_finishget(L, t, L->top - 1, L->top - 1, slot); + } + lua_unlock(L); + return ttnov(L->top - 1); +} + + +LUA_API int lua_getglobal (lua_State *L, const char *name) { + Table *reg = hvalue(&G(L)->l_registry); + lua_lock(L); + return auxgetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name); +} + + +LUA_API int lua_gettable (lua_State *L, int idx) { + StkId t; + lua_lock(L); + t = index2addr(L, idx); + luaV_gettable(L, t, L->top - 1, L->top - 1); + lua_unlock(L); + return ttnov(L->top - 1); +} + + +LUA_API int lua_getfield (lua_State *L, int idx, const char *k) { + lua_lock(L); + return auxgetstr(L, index2addr(L, idx), k); +} + + +LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) { + StkId t; + const TValue *slot; + lua_lock(L); + t = index2addr(L, idx); + if (luaV_fastget(L, t, n, slot, luaH_getint)) { + setobj2s(L, L->top, slot); + api_incr_top(L); + } + else { + setivalue(L->top, n); + api_incr_top(L); + luaV_finishget(L, t, L->top - 1, L->top - 1, slot); + } + lua_unlock(L); + return ttnov(L->top - 1); +} + + +LUA_API int lua_rawget (lua_State *L, int idx) { + StkId t; + lua_lock(L); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1)); + lua_unlock(L); + return ttnov(L->top - 1); +} + + +LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) { + StkId t; + lua_lock(L); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + setobj2s(L, L->top, luaH_getint(hvalue(t), n)); + api_incr_top(L); + lua_unlock(L); + return ttnov(L->top - 1); +} + + +LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) { + StkId t; + TValue k; + lua_lock(L); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + setpvalue(&k, cast(void *, p)); + setobj2s(L, L->top, luaH_get(hvalue(t), &k)); + api_incr_top(L); + lua_unlock(L); + return ttnov(L->top - 1); +} + + +LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { + Table *t; + lua_lock(L); + t = luaH_new(L); + sethvalue(L, L->top, t); + api_incr_top(L); + if (narray > 0 || nrec > 0) + luaH_resize(L, t, narray, nrec); + luaC_checkGC(L); + lua_unlock(L); +} + + +LUA_API int lua_getmetatable (lua_State *L, int objindex) { + const TValue *obj; + Table *mt; + int res = 0; + lua_lock(L); + obj = index2addr(L, objindex); + switch (ttnov(obj)) { + case LUA_TTABLE: + mt = hvalue(obj)->metatable; + break; + case LUA_TUSERDATA: + mt = uvalue(obj)->metatable; + break; + default: + mt = G(L)->mt[ttnov(obj)]; + break; + } + if (mt != NULL) { + sethvalue(L, L->top, mt); + api_incr_top(L); + res = 1; + } + lua_unlock(L); + return res; +} + + +LUA_API int lua_getuservalue (lua_State *L, int idx) { + StkId o; + lua_lock(L); + o = index2addr(L, idx); + api_check(L, ttisfulluserdata(o), "full userdata expected"); + getuservalue(L, uvalue(o), L->top); + api_incr_top(L); + lua_unlock(L); + return ttnov(L->top - 1); +} + + +/* +** set functions (stack -> Lua) +*/ + +/* +** t[k] = value at the top of the stack (where 'k' is a string) +*/ +static void auxsetstr (lua_State *L, const TValue *t, const char *k) { + const TValue *slot; + TString *str = luaS_new(L, k); + api_checknelems(L, 1); + if (luaV_fastset(L, t, str, slot, luaH_getstr, L->top - 1)) + L->top--; /* pop value */ + else { + setsvalue2s(L, L->top, str); /* push 'str' (to make it a TValue) */ + api_incr_top(L); + luaV_finishset(L, t, L->top - 1, L->top - 2, slot); + L->top -= 2; /* pop value and key */ + } + lua_unlock(L); /* lock done by caller */ +} + + +LUA_API void lua_setglobal (lua_State *L, const char *name) { + Table *reg = hvalue(&G(L)->l_registry); + lua_lock(L); /* unlock done in 'auxsetstr' */ + auxsetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name); +} + + +LUA_API void lua_settable (lua_State *L, int idx) { + StkId t; + lua_lock(L); + api_checknelems(L, 2); + t = index2addr(L, idx); + luaV_settable(L, t, L->top - 2, L->top - 1); + L->top -= 2; /* pop index and value */ + lua_unlock(L); +} + + +LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { + lua_lock(L); /* unlock done in 'auxsetstr' */ + auxsetstr(L, index2addr(L, idx), k); +} + + +LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) { + StkId t; + const TValue *slot; + lua_lock(L); + api_checknelems(L, 1); + t = index2addr(L, idx); + if (luaV_fastset(L, t, n, slot, luaH_getint, L->top - 1)) + L->top--; /* pop value */ + else { + setivalue(L->top, n); + api_incr_top(L); + luaV_finishset(L, t, L->top - 1, L->top - 2, slot); + L->top -= 2; /* pop value and key */ + } + lua_unlock(L); +} + + +LUA_API void lua_rawset (lua_State *L, int idx) { + StkId o; + TValue *slot; + lua_lock(L); + api_checknelems(L, 2); + o = index2addr(L, idx); + api_check(L, ttisrwtable(o), "RW table expected"); + slot = luaH_set(L, hvalue(o), L->top - 2); + setobj2t(L, slot, L->top - 1); + invalidateTMcache(hvalue(o)); + luaC_barrierback(L, hvalue(o), L->top-1); + L->top -= 2; + lua_unlock(L); +} + + +LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) { + StkId o; + lua_lock(L); + api_checknelems(L, 1); + o = index2addr(L, idx); + api_check(L, ttisrwtable(o), "RW table expected"); + luaH_setint(L, hvalue(o), n, L->top - 1); + luaC_barrierback(L, hvalue(o), L->top-1); + L->top--; + lua_unlock(L); +} + + +LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) { + StkId o; + TValue k, *slot; + lua_lock(L); + api_checknelems(L, 1); + o = index2addr(L, idx); + api_check(L, ttisrwtable(o), "RW table expected"); + setpvalue(&k, cast(void *, p)); + slot = luaH_set(L, hvalue(o), &k); + setobj2t(L, slot, L->top - 1); + luaC_barrierback(L, hvalue(o), L->top - 1); + L->top--; + lua_unlock(L); +} + + +LUA_API int lua_setmetatable (lua_State *L, int objindex) { + TValue *obj; + Table *mt; + lua_lock(L); + api_checknelems(L, 1); + obj = index2addr(L, objindex); + if (ttisnil(L->top - 1)) + mt = NULL; + else { + api_check(L, ttistable(L->top - 1), "table expected"); + mt = hvalue(L->top - 1); + } + switch (ttype(obj)) { + case LUA_TTBLRAM: { + hvalue(obj)->metatable = mt; + if (mt) { + luaC_objbarrier(L, gcvalue(obj), mt); + luaC_checkfinalizer(L, gcvalue(obj), mt); + } + break; + } + case LUA_TTBLROF: { + luai_apicheck(L, "RW table expected"); + } + case LUA_TUSERDATA: { + uvalue(obj)->metatable = mt; + if (mt) { + luaC_objbarrier(L, uvalue(obj), mt); + luaC_checkfinalizer(L, gcvalue(obj), mt); + } + break; + } + default: { + G(L)->mt[ttnov(obj)] = mt; + break; + } + } + L->top--; + lua_unlock(L); + return 1; +} + + +LUA_API void lua_setuservalue (lua_State *L, int idx) { + StkId o; + lua_lock(L); + api_checknelems(L, 1); + o = index2addr(L, idx); + api_check(L, ttisfulluserdata(o), "full userdata expected"); + setuservalue(L, uvalue(o), L->top - 1); + luaC_barrier(L, gcvalue(o), L->top - 1); + L->top--; + lua_unlock(L); +} + + +/* +** 'load' and 'call' functions (run Lua code) +*/ + + +#define checkresults(L,na,nr) \ + api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \ + "results from function overflow current stack size") + + +LUA_API void lua_callk (lua_State *L, int nargs, int nresults, + lua_KContext ctx, lua_KFunction k) { + StkId func; + lua_lock(L); + api_check(L, k == NULL || !isLua(L->ci), + "cannot use continuations inside hooks"); + api_checknelems(L, nargs+1); + api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); + checkresults(L, nargs, nresults); + func = L->top - (nargs+1); + if (k != NULL && L->nny == 0) { /* need to prepare continuation? */ + L->ci->u.c.k = k; /* save continuation */ + L->ci->u.c.ctx = ctx; /* save context */ + luaD_call(L, func, nresults); /* do the call */ + } + else /* no continuation or no yieldable */ + luaD_callnoyield(L, func, nresults); /* just do the call */ + adjustresults(L, nresults); + lua_unlock(L); +} + + + +/* +** Execute a protected call. +*/ +struct CallS { /* data to 'f_call' */ + StkId func; + int nresults; +}; + + +static void f_call (lua_State *L, void *ud) { + struct CallS *c = cast(struct CallS *, ud); + luaD_callnoyield(L, c->func, c->nresults); +} + + + +LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc, + lua_KContext ctx, lua_KFunction k) { + struct CallS c; + int status; + ptrdiff_t func; + lua_lock(L); + api_check(L, k == NULL || !isLua(L->ci), + "cannot use continuations inside hooks"); + api_checknelems(L, nargs+1); + api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); + checkresults(L, nargs, nresults); + if (errfunc == 0) + func = 0; + else { + StkId o = index2addr(L, errfunc); + api_checkstackindex(L, errfunc, o); + func = savestack(L, o); + } + c.func = L->top - (nargs+1); /* function to be called */ + if (k == NULL || L->nny > 0) { /* no continuation or no yieldable? */ + c.nresults = nresults; /* do a 'conventional' protected call */ + status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); + } + else { /* prepare continuation (call is already protected by 'resume') */ + CallInfo *ci = L->ci; + ci->u.c.k = k; /* save continuation */ + ci->u.c.ctx = ctx; /* save context */ + /* save information for error recovery */ + ci->extra = savestack(L, c.func); + ci->u.c.old_errfunc = L->errfunc; + L->errfunc = func; + setoah(ci->callstatus, L->allowhook); /* save value of 'allowhook' */ + ci->callstatus |= CIST_YPCALL; /* function can do error recovery */ + luaD_call(L, c.func, nresults); /* do the call */ + ci->callstatus &= ~CIST_YPCALL; + L->errfunc = ci->u.c.old_errfunc; + status = LUA_OK; /* if it is here, there were no errors */ + } + adjustresults(L, nresults); + lua_unlock(L); + return status; +} + + +LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, + const char *chunkname, const char *mode) { + ZIO z; + int status; + lua_lock(L); + if (!chunkname) chunkname = "?"; + luaZ_init(L, &z, reader, data); + status = luaD_protectedparser(L, &z, chunkname, mode); + if (status == LUA_OK) { /* no errors? */ + LClosure *f = clLvalue(L->top - 1); /* get newly created function */ + if (f->nupvalues >= 1) { /* does it have an upvalue? */ + /* get global table from registry */ + Table *reg = hvalue(&G(L)->l_registry); + const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS); + /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */ + setobj(L, f->upvals[0]->v, gt); + luaC_upvalbarrier(L, f->upvals[0]); + } + } + lua_unlock(L); + return status; +} + + +LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) { + int status; + TValue *o; + lua_lock(L); + api_checknelems(L, 1); + o = L->top - 1; + if (strip == -1) + strip = G(L)->stripdefault; + if (isLfunction(o)) + status = luaU_dump(L, getproto(o), writer, data, strip); + else + status = 1; + lua_unlock(L); + return status; +} + + +LUA_API int lua_stripdebug (lua_State *L, int stripping){ + TValue *o = L->top - 1; + Proto *p = NULL; + int res = -1; + lua_lock(L); + api_checknelems(L, 1); + if (isLfunction(o)) { + p = getproto(o); + if (p && !isLFSobj(p) && (unsigned) stripping < 3 ) { + // found a valid proto to strip + res = luaU_stripdebug(L, p, stripping, 1); + } + } else if (ttisnil(L->top - 1)) { + // get or set the default strip level + if ((unsigned) stripping < 3) + G(L)->stripdefault = stripping; + res = G(L)->stripdefault; + } + L->top--; + lua_unlock(L); + return res; +} + + +LUA_API int lua_status (lua_State *L) { + return L->status; +} + + +/* +** Garbage-collection function +*/ + +LUA_API int lua_gc (lua_State *L, int what, int data) { + int res = 0; + global_State *g; + lua_lock(L); + g = G(L); + switch (what) { + case LUA_GCSTOP: { + g->gcrunning = 0; + break; + } + case LUA_GCRESTART: { + luaE_setdebt(g, 0); + g->gcrunning = 1; + break; + } + case LUA_GCCOLLECT: { + luaC_fullgc(L, 0); + break; + } + case LUA_GCCOUNT: { + /* GC values are expressed in Kbytes: #bytes/2^10 */ + res = cast_int(gettotalbytes(g) >> 10); + break; + } + case LUA_GCCOUNTB: { + res = cast_int(gettotalbytes(g) & 0x3ff); + break; + } + case LUA_GCSTEP: { + l_mem debt = 1; /* =1 to signal that it did an actual step */ + lu_byte oldrunning = g->gcrunning; + g->gcrunning = 1; /* allow GC to run */ + if (data == 0) { + luaE_setdebt(g, -GCSTEPSIZE); /* to do a "small" step */ + luaC_step(L); + } + else { /* add 'data' to total debt */ + debt = cast(l_mem, data) * 1024 + g->GCdebt; + luaE_setdebt(g, debt); + luaC_checkGC(L); + } + g->gcrunning = oldrunning; /* restore previous state */ + if (debt > 0 && g->gcstate == GCSpause) /* end of cycle? */ + res = 1; /* signal it */ + break; + } + case LUA_GCSETPAUSE: { + res = g->gcpause; + g->gcpause = data; + break; + } + case LUA_GCSETSTEPMUL: { + res = g->gcstepmul; + if (data < 40) data = 40; /* avoid ridiculous low values (and 0) */ + g->gcstepmul = data; + break; + } + case LUA_GCSETMEMLIMIT: { + /* GC values are expressed in Kbytes: #bytes/2^10 */ + l_mem new_memlimit = cast(l_mem, data) << 10; + if(new_memlimit > lua_freeheap()) /* run a full GC */ + luaC_fullgc(L, 0); + g->gcmemfreeboard = new_memlimit; + /* new memlimit might be > then requested memlimit. */ + res = cast_int(new_memlimit >> 10); + break; + } + + case LUA_GCISRUNNING: { + res = g->gcrunning; + break; + } + default: res = -1; /* invalid option */ + } + lua_unlock(L); + return res; +} + + + +/* +** miscellaneous functions +*/ + + +LUA_API int lua_error (lua_State *L) { + lua_lock(L); + api_checknelems(L, 1); + luaG_errormsg(L); + /* code unreachable; will unlock when control actually leaves the kernel */ + return 0; /* to avoid warnings */ +} + + +LUA_API int lua_next (lua_State *L, int idx) { + StkId t; + int more; + lua_lock(L); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + more = luaH_next(L, hvalue(t), L->top - 1); + if (more) { + api_incr_top(L); + } + else /* no more elements */ + L->top -= 1; /* remove key */ + lua_unlock(L); + return more; +} + + +LUA_API void lua_concat (lua_State *L, int n) { + lua_lock(L); + api_checknelems(L, n); + if (n >= 2) { + luaV_concat(L, n); + } + else if (n == 0) { /* push empty string */ + setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); + api_incr_top(L); + } + /* else n == 1; nothing to do */ + luaC_checkGC(L); + lua_unlock(L); +} + + +LUA_API void lua_len (lua_State *L, int idx) { + StkId t; + lua_lock(L); + t = index2addr(L, idx); + luaV_objlen(L, L->top, t); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) { + lua_Alloc f; + lua_lock(L); + if (ud) *ud = G(L)->ud; + f = G(L)->frealloc; + lua_unlock(L); + return f; +} + + +LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) { + lua_lock(L); + G(L)->ud = ud; + G(L)->frealloc = f; + lua_unlock(L); +} + + +LUA_API void *lua_newuserdata (lua_State *L, size_t size) { + Udata *u; + lua_lock(L); + u = luaS_newudata(L, size); + setuvalue(L, L->top, u); + api_incr_top(L); + luaC_checkGC(L); + lua_unlock(L); + return getudatamem(u); +} + + + +static const char *aux_upvalue (StkId fi, int n, TValue **val, + CClosure **owner, UpVal **uv) { + switch (ttype(fi)) { + case LUA_TCCL: { /* C closure */ + CClosure *f = clCvalue(fi); + if (!(1 <= n && n <= f->nupvalues)) return NULL; + *val = &f->upvalue[n-1]; + if (owner) *owner = f; + return ""; + } + case LUA_TLCL: { /* Lua closure */ + LClosure *f = clLvalue(fi); + TString *name; + Proto *p = f->p; + if (!(1 <= n && n <= p->sizeupvalues)) return NULL; + *val = f->upvals[n-1]->v; + if (uv) *uv = f->upvals[n - 1]; + name = p->upvalues[n-1].name; + return (name == NULL) ? "(*no name)" : getstr(name); + } + default: return NULL; /* not a closure */ + } +} + + +LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { + const char *name; + TValue *val = NULL; /* to avoid warnings */ + lua_lock(L); + name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL, NULL); + if (name) { + setobj2s(L, L->top, val); + api_incr_top(L); + } + lua_unlock(L); + return name; +} + + +LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { + const char *name; + TValue *val = NULL; /* to avoid warnings */ + CClosure *owner = NULL; + UpVal *uv = NULL; + StkId fi; + lua_lock(L); + fi = index2addr(L, funcindex); + api_checknelems(L, 1); + name = aux_upvalue(fi, n, &val, &owner, &uv); + if (name) { + L->top--; + setobj(L, val, L->top); + if (owner) { luaC_barrier(L, owner, L->top); } + else if (uv) { luaC_upvalbarrier(L, uv); } + } + lua_unlock(L); + return name; +} + + +static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) { + LClosure *f; + StkId fi = index2addr(L, fidx); + api_check(L, ttisLclosure(fi), "Lua function expected"); + f = clLvalue(fi); + api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index"); + if (pf) *pf = f; + return &f->upvals[n - 1]; /* get its upvalue pointer */ +} + + +LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) { + StkId fi = index2addr(L, fidx); + switch (ttype(fi)) { + case LUA_TLCL: { /* lua closure */ + return *getupvalref(L, fidx, n, NULL); + } + case LUA_TCCL: { /* C closure */ + CClosure *f = clCvalue(fi); + api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index"); + return &f->upvalue[n - 1]; + } + default: { + api_check(L, 0, "closure expected"); + return NULL; + } + } +} + + +LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1, + int fidx2, int n2) { + LClosure *f1; + UpVal **up1 = getupvalref(L, fidx1, n1, &f1); + UpVal **up2 = getupvalref(L, fidx2, n2, NULL); + luaC_upvdeccount(L, *up1); + *up1 = *up2; + (*up1)->refcount++; + if (upisopen(*up1)) (*up1)->u.open.touched = 1; + luaC_upvalbarrier(L, *up1); +} + + diff --git a/components/lua/lua-5.3/lapi.h b/components/lua/lua-5.3/lapi.h new file mode 100644 index 00000000..8e16ad53 --- /dev/null +++ b/components/lua/lua-5.3/lapi.h @@ -0,0 +1,24 @@ +/* +** $Id: lapi.h,v 2.9.1.1 2017/04/19 17:20:42 roberto Exp $ +** Auxiliary functions from Lua API +** See Copyright Notice in lua.h +*/ + +#ifndef lapi_h +#define lapi_h + + +#include "llimits.h" +#include "lstate.h" + +#define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \ + "stack overflow");} + +#define adjustresults(L,nres) \ + { if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; } + +#define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \ + "not enough elements in the stack") + + +#endif diff --git a/components/lua/lua-5.3/lauxlib.c b/components/lua/lua-5.3/lauxlib.c new file mode 100644 index 00000000..30c34144 --- /dev/null +++ b/components/lua/lua-5.3/lauxlib.c @@ -0,0 +1,1178 @@ +/* +** $Id: lauxlib.c,v 1.289.1.1 2017/04/19 17:20:42 roberto Exp $ +** Auxiliary functions for building Lua libraries +** See Copyright Notice in lua.h +*/ + +#define lauxlib_c + +#include "lprefix.h" + + +#if defined(LUA_USE_HOST) && defined(_MSC_VER) +#undef errno //msvc #defines errno, which interferes with our #include macro +#else +#include +#endif + +#include +#include +#include +#include + +/* +** This file uses only the official API of Lua. +** Any function declared here could be written as an application function. +*/ + +#include "lua.h" + +#include "lauxlib.h" +#include "lpanic.h" +#define LUA_LIB + +#ifdef LUA_USE_ESP +#include "platform.h" +#include "vfs.h" +#include +#endif + + +/* +** {====================================================== +** Traceback +** ======================================================= +*/ + + +#define LEVELS1 10 /* size of the first part of the stack */ +#define LEVELS2 11 /* size of the second part of the stack */ + + + +/* +** search for 'objidx' in table at index -1. +** return 1 + string at top if find a good name. +*/ +static int findfield (lua_State *L, int objidx, int level) { + if (level == 0 || !lua_istable(L, -1)) + return 0; /* not found */ + lua_pushnil(L); /* start 'next' loop */ + while (lua_next(L, -2)) { /* for each pair in table */ + if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ + if (lua_rawequal(L, objidx, -1)) { /* found object? */ + lua_pop(L, 1); /* remove value (but keep name) */ + return 1; + } + else if (findfield(L, objidx, level - 1)) { /* try recursively */ + lua_remove(L, -2); /* remove table (but keep name) */ + lua_pushliteral(L, "."); + lua_insert(L, -2); /* place '.' between the two names */ + lua_concat(L, 3); + return 1; + } + } + lua_pop(L, 1); /* remove value */ + } + return 0; /* not found */ +} + + +/* +** Search for a name for a function in all loaded and ROM modules +*/ +static int pushglobalfuncname (lua_State *L, lua_Debug *ar) { + int top = lua_gettop(L); + lua_getinfo(L, "f", ar); /* push function */ + lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); + if (!findfield(L, top + 1, 2)) { + lua_settop(L, top+1); /* remove global table */ + lua_getglobal(L, "ROM"); + if (!findfield(L, top + 1, 2)) { + lua_settop(L, top); /* remove function and global table */ + return 0; + } + } + const char *name = lua_tostring(L, -1); + if (strncmp(name, "_G.", 3) == 0) { /* name start with '_G.'? */ + lua_pushstring(L, name + 3); /* push name without prefix */ + lua_remove(L, -2); /* remove original name */ + } + lua_copy(L, -1, top + 1); /* move name to proper place */ + lua_pop(L, 2); /* remove pushed values */ + return 1; +} + + +static void pushfuncname (lua_State *L, lua_Debug *ar) { + if (pushglobalfuncname(L, ar)) { /* try first a global name */ + lua_pushfstring(L, "function '%s'", lua_tostring(L, -1)); + lua_remove(L, -2); /* remove name */ + } + else if (*ar->namewhat != '\0') /* is there a name from code? */ + lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */ + else if (*ar->what == 'm') /* main? */ + lua_pushliteral(L, "main chunk"); + else if (*ar->what != 'C') /* for Lua functions, use */ + lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); + else /* nothing left... */ + lua_pushliteral(L, "?"); +} + + +static int lastlevel (lua_State *L) { + lua_Debug ar; + int li = 1, le = 1; + /* find an upper bound */ + while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } + /* do a binary search */ + while (li < le) { + int m = (li + le)/2; + if (lua_getstack(L, m, &ar)) li = m + 1; + else le = m; + } + return le - 1; +} + + +LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, + const char *msg, int level) { + lua_Debug ar; + int top = lua_gettop(L); + int last = lastlevel(L1); + int n1 = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1; + if (msg) + lua_pushfstring(L, "%s\n", msg); + luaL_checkstack(L, 10, NULL); + lua_pushliteral(L, "stack traceback:"); + while (lua_getstack(L1, level++, &ar)) { + if (n1-- == 0) { /* too many levels? */ + lua_pushliteral(L, "\n\t..."); /* add a '...' */ + level = last - LEVELS2 + 1; /* and skip to last ones */ + } + else { + lua_getinfo(L1, "Slnt", &ar); + lua_pushfstring(L, "\n\t%s:", ar.short_src); + if (ar.currentline > 0) + lua_pushfstring(L, "%d:", ar.currentline); + lua_pushliteral(L, " in "); + pushfuncname(L, &ar); + if (ar.istailcall) + lua_pushliteral(L, "\n\t(...tail calls...)"); + lua_concat(L, lua_gettop(L) - top); + } + } + lua_concat(L, lua_gettop(L) - top); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Error-report functions +** ======================================================= +*/ + +LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) { + lua_Debug ar; + if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ + return luaL_error(L, "bad argument #%d (%s)", arg, extramsg); + lua_getinfo(L, "n", &ar); + if (strcmp(ar.namewhat, "method") == 0) { + arg--; /* do not count 'self' */ + if (arg == 0) /* error is in the self argument itself? */ + return luaL_error(L, "calling '%s' on bad self (%s)", + ar.name, extramsg); + } + if (ar.name == NULL) + ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?"; + return luaL_error(L, "bad argument #%d to '%s' (%s)", + arg, ar.name, extramsg); +} + + +static int typeerror (lua_State *L, int arg, const char *tname) { + const char *msg; + const char *typearg; /* name for the type of the actual argument */ + if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING) + typearg = lua_tostring(L, -1); /* use the given type name */ + else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA) + typearg = "light userdata"; /* special name for messages */ + else + typearg = luaL_typename(L, arg); /* standard name */ + msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg); + return luaL_argerror(L, arg, msg); +} + + +static void tag_error (lua_State *L, int arg, int tag) { + typeerror(L, arg, lua_typename(L, tag)); +} + + +/* +** The use of 'lua_pushfstring' ensures this function does not +** need reserved stack space when called. +*/ +LUALIB_API void luaL_where (lua_State *L, int level) { + lua_Debug ar; + if (lua_getstack(L, level, &ar)) { /* check function at level */ + lua_getinfo(L, "Sl", &ar); /* get info about it */ + if (ar.currentline > 0) { /* is there info? */ + lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); + return; + } + } + lua_pushfstring(L, ""); /* else, no information available... */ +} + + +/* +** Again, the use of 'lua_pushvfstring' ensures this function does +** not need reserved stack space when called. (At worst, it generates +** an error with "stack overflow" instead of the given message.) +*/ +LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { + va_list argp; + va_start(argp, fmt); + luaL_where(L, 1); + lua_pushvfstring(L, fmt, argp); + va_end(argp); + lua_concat(L, 2); + return lua_error(L); +} + + +LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) { + int en = errno; /* calls to Lua API may change this value */ + if (stat) { + lua_pushboolean(L, 1); + return 1; + } + else { + lua_pushnil(L); + if (fname) + lua_pushfstring(L, "%s: %s", fname, strerror(en)); + else + lua_pushstring(L, strerror(en)); + lua_pushinteger(L, en); + return 3; + } +} + + +#if !defined(l_inspectstat) /* { */ + +#if defined(LUA_USE_POSIX) + +#include + +/* +** use appropriate macros to interpret 'pclose' return status +*/ +#define l_inspectstat(stat,what) \ + if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \ + else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; } + +#else + +#define l_inspectstat(stat,what) /* no op */ + +#endif + +#endif /* } */ + + +LUALIB_API int luaL_execresult (lua_State *L, int stat) { + const char *what = "exit"; /* type of termination */ + if (stat == -1) /* error? */ + return luaL_fileresult(L, 0, NULL); + else { + l_inspectstat(stat, what); /* interpret result */ + if (*what == 'e' && stat == 0) /* successful termination? */ + lua_pushboolean(L, 1); + else + lua_pushnil(L); + lua_pushstring(L, what); + lua_pushinteger(L, stat); + return 3; /* return true/nil,what,code */ + } +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Userdata's metatable manipulation +** ======================================================= +*/ + +LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { + if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */ + return 0; /* leave previous value on top, but return 0 */ + lua_pop(L, 1); + lua_createtable(L, 0, 2); /* create metatable */ + lua_pushstring(L, tname); + lua_setfield(L, -2, "__name"); /* metatable.__name = tname */ + lua_pushvalue(L, -1); + lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ + return 1; +} + + +LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) { + luaL_getmetatable(L, tname); + lua_setmetatable(L, -2); +} + + +LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) { + void *p = lua_touserdata(L, ud); + if (p != NULL) { /* value is a userdata? */ + if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ + luaL_getmetatable(L, tname); /* get correct metatable */ + if (!lua_rawequal(L, -1, -2)) /* not the same? */ + p = NULL; /* value is a userdata with wrong metatable */ + lua_pop(L, 2); /* remove both metatables */ + return p; + } + } + return NULL; /* value is not a userdata with a metatable */ +} + + +LUALIB_API int luaL_rometatable (lua_State *L, const char* tname, const ROTable *p) { + lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */ + if (!lua_isnil(L, -1)) /* name already in use? */ + return 0; /* leave previous value on top, but return 0 */ + lua_pop(L, 1); + lua_pushrotable(L, p); + lua_pushvalue(L, -1); + lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ + return 1; +} + + +LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { + void *p = luaL_testudata(L, ud, tname); + if (p == NULL) typeerror(L, ud, tname); + return p; +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Argument check functions +** ======================================================= +*/ + +LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def, + const char *const lst[]) { + const char *name = (def) ? luaL_optstring(L, arg, def) : + luaL_checkstring(L, arg); + int i; + for (i=0; lst[i]; i++) + if (strcmp(lst[i], name) == 0) + return i; + return luaL_argerror(L, arg, + lua_pushfstring(L, "invalid option '%s'", name)); +} + + +/* +** Ensures the stack has at least 'space' extra slots, raising an error +** if it cannot fulfill the request. (The error handling needs a few +** extra slots to format the error message. In case of an error without +** this extra space, Lua will generate the same 'stack overflow' error, +** but without 'msg'.) +*/ +LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) { + if (!lua_checkstack(L, space)) { + if (msg) + luaL_error(L, "stack overflow (%s)", msg); + else + luaL_error(L, "stack overflow"); + } +} + + +LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) { + if (lua_type(L, arg) != t) + tag_error(L, arg, t); +} + + +LUALIB_API void luaL_checkany (lua_State *L, int arg) { + if (lua_type(L, arg) == LUA_TNONE) + luaL_argerror(L, arg, "value expected"); +} + + +LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) { + const char *s = lua_tolstring(L, arg, len); + if (!s) tag_error(L, arg, LUA_TSTRING); + return s; +} + + +LUALIB_API const char *luaL_optlstring (lua_State *L, int arg, + const char *def, size_t *len) { + if (lua_isnoneornil(L, arg)) { + if (len) + *len = (def ? strlen(def) : 0); + return def; + } + else return luaL_checklstring(L, arg, len); +} + + +LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) { + int isnum; + lua_Number d = lua_tonumberx(L, arg, &isnum); + if (!isnum) + tag_error(L, arg, LUA_TNUMBER); + return d; +} + + +LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) { + return luaL_opt(L, luaL_checknumber, arg, def); +} + + +static void interror (lua_State *L, int arg) { + if (lua_isnumber(L, arg)) + luaL_argerror(L, arg, "number has no integer representation"); + else + tag_error(L, arg, LUA_TNUMBER); +} + + +LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) { + int isnum; + lua_Integer d = lua_tointegerx(L, arg, &isnum); + if (!isnum) { + interror(L, arg); + } + return d; +} + + +LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg, + lua_Integer def) { + return luaL_opt(L, luaL_checkinteger, arg, def); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Generic Buffer manipulation +** ======================================================= +*/ + +/* userdata to box arbitrary data */ +typedef struct UBox { + void *box; + size_t bsize; +} UBox; + + +static void *resizebox (lua_State *L, int idx, size_t newsize) { + void *ud; + lua_Alloc allocf = lua_getallocf(L, &ud); + UBox *box = (UBox *)lua_touserdata(L, idx); + void *temp = allocf(ud, box->box, box->bsize, newsize); + if (temp == NULL && newsize > 0) { /* allocation error? */ + resizebox(L, idx, 0); /* free buffer */ + luaL_error(L, "not enough memory for buffer allocation"); + } + box->box = temp; + box->bsize = newsize; + return temp; +} + + +static int boxgc (lua_State *L) { + resizebox(L, 1, 0); + return 0; +} + + +static void *newbox (lua_State *L, size_t newsize) { + UBox *box = (UBox *)lua_newuserdata(L, sizeof(UBox)); + box->box = NULL; + box->bsize = 0; + if (luaL_newmetatable(L, "LUABOX")) { /* creating metatable? */ + lua_pushcfunction(L, boxgc); + lua_setfield(L, -2, "__gc"); /* metatable.__gc = boxgc */ + } + lua_setmetatable(L, -2); + return resizebox(L, -1, newsize); +} + + +/* +** check whether buffer is using a userdata on the stack as a temporary +** buffer +*/ +#define buffonstack(B) ((B)->b != (B)->initb) + + +/* +** returns a pointer to a free area with at least 'sz' bytes +*/ +LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { + lua_State *L = B->L; + if (B->size - B->n < sz) { /* not enough space? */ + char *newbuff; + size_t newsize = B->size * 2; /* double buffer size */ + if (newsize - B->n < sz) /* not big enough? */ + newsize = B->n + sz; + if (newsize < B->n || newsize - B->n < sz) + luaL_error(L, "buffer too large"); + /* create larger buffer */ + if (buffonstack(B)) + newbuff = (char *)resizebox(L, -1, newsize); + else { /* no buffer yet */ + newbuff = (char *)newbox(L, newsize); + memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */ + } + B->b = newbuff; + B->size = newsize; + } + return &B->b[B->n]; +} + + +LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { + if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */ + char *b = luaL_prepbuffsize(B, l); + memcpy(b, s, l * sizeof(char)); + luaL_addsize(B, l); + } +} + + +LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { + luaL_addlstring(B, s, strlen(s)); +} + + +LUALIB_API void luaL_pushresult (luaL_Buffer *B) { + lua_State *L = B->L; + lua_pushlstring(L, B->b, B->n); + if (buffonstack(B)) { + resizebox(L, -2, 0); /* delete old buffer */ + lua_remove(L, -2); /* remove its header from the stack */ + } +} + + +LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) { + luaL_addsize(B, sz); + luaL_pushresult(B); +} + + +LUALIB_API void luaL_addvalue (luaL_Buffer *B) { + lua_State *L = B->L; + size_t l; + const char *s = lua_tolstring(L, -1, &l); + if (buffonstack(B)) + lua_insert(L, -2); /* put value below buffer */ + luaL_addlstring(B, s, l); + lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */ +} + + +LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { + B->L = L; + B->b = B->initb; + B->n = 0; + B->size = LUAL_BUFFERSIZE; +} + + +LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) { + luaL_buffinit(L, B); + return luaL_prepbuffsize(B, sz); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Reference system +** ======================================================= +*/ + +/* index of free-list header */ +#define freelist 0 + + +LUALIB_API int luaL_ref (lua_State *L, int t) { + int ref; + if (lua_isnil(L, -1)) { + lua_pop(L, 1); /* remove from stack */ + return LUA_REFNIL; /* 'nil' has a unique fixed reference */ + } + t = lua_absindex(L, t); + lua_rawgeti(L, t, freelist); /* get first free element */ + ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */ + lua_pop(L, 1); /* remove it from stack */ + if (ref != 0) { /* any free element? */ + lua_rawgeti(L, t, ref); /* remove it from list */ + lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */ + } + else /* no free elements */ + ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */ + lua_rawseti(L, t, ref); + return ref; +} + + +LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { + if (ref >= 0) { + t = lua_absindex(L, t); + lua_rawgeti(L, t, freelist); + lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */ + lua_pushinteger(L, ref); + lua_rawseti(L, t, freelist); /* t[freelist] = ref */ + } +} + + +LUALIB_API void (luaL_reref) (lua_State *L, int t, int *ref) { +/* + * If the ref is positive and the entry in table t exists then + * overwrite the value otherwise fall through to luaL_ref() + */ + if (ref) { + if (*ref >= 0) { + t = lua_absindex(L, t); + int reft = lua_rawgeti(L, t, *ref); + lua_pop(L, 1); + if (reft != LUA_TNIL) { + lua_rawseti(L, t, *ref); + return; + } + } + *ref = luaL_ref(L, t); + } +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Load functions +** ======================================================= +*/ + +#ifdef LUA_CROSS_COMPILER +# define file(f) FILE *f +# define freopen_bin(f,fn) freopen(f,"rb",fn) +# define read_buff(b,f) fread(b, 1, sizeof (b), f) +#else /* map stdio API and macros to vfs */ +# undef feof +# undef fopen +# undef getc +# undef ungetc +# define file(f) int f +# define strerror(n) "" +# define feof(f) vfs_eof(f) +# define fopen(f, m) vfs_open(f, m) +# define freopen_bin(fn,f) ((void) vfs_close(f), vfs_open(fn, "r")) +# define getc(f) vfs_getc(f) +# define ungetc(c,f) vfs_ungetc(c, f) +# define read_buff(b,f) vfs_read(f, b, sizeof (b)) +#endif +#define LAUXLIB_TYPE 0 +typedef struct LoadF { + int type; + int n; /* number of pre-read characters */ + file(f); /* file being read */ + char buff[BUFSIZ]; /* area for reading file */ +} LoadF; + +static const char *getF (lua_State *L, void *ud, size_t *size) { + LoadF *lf = (LoadF *)ud; + (void)L; /* not used */ + if (lf->n > 0) { /* are there pre-read characters to be read? */ + *size = lf->n; /* return them (chars already in buffer) */ + lf->n = 0; /* no more pre-read characters */ + } + else { /* read a block from file */ + /* 'fread' can return > 0 *and* set the EOF flag. If next call to + 'getF' called 'fread', it might still wait for user input. + The next check avoids this problem. */ + if (feof(lf->f)) return NULL; + *size = read_buff(lf->buff, lf->f); /* read block */ + } + return lf->buff; +} + + +static int errfile (lua_State *L, const char *what, int fnameindex) { + const char *serr = strerror(errno); + const char *filename = lua_tostring(L, fnameindex) + 1; + lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); + lua_remove(L, fnameindex); + return LUA_ERRFILE; +} + + +static int skipBOM (LoadF *lf) { + const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */ + int c; + lf->n = 0; + do { + c = getc(lf->f); + if (c == EOF || c != *(const unsigned char *)p++) return c; + lf->buff[lf->n++] = c; /* to be read by the parser */ + } while (*p != '\0'); + lf->n = 0; /* prefix matched; discard it */ + return getc(lf->f); /* return next character */ +} + + +/* +** reads the first character of file 'f' and skips an optional BOM mark +** in its beginning plus its first line if it starts with '#'. Returns +** true if it skipped the first line. In any case, '*cp' has the +** first "valid" character of the file (after the optional BOM and +** a first-line comment). +*/ +static int skipcomment (LoadF *lf, int *cp) { + int c = *cp = skipBOM(lf); + if (c == '#') { /* first line is a comment (Unix exec. file)? */ + do { /* skip first line */ + c = getc(lf->f); + } while (c != EOF && c != '\n'); + *cp = getc(lf->f); /* skip end-of-line, if present */ + return 1; /* there was a comment */ + } + else return 0; /* no comment */ +} + + +LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, + const char *mode) { + LoadF lf; + int status, readstatus; + int c; + int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ + if (filename == NULL) { +#ifdef LUA_CROSS_COMPILER + lua_pushliteral(L, "=stdin"); + lf.f = stdin; +#else + return luaL_error(L, "filename is NULL"); +#endif + } + else { + lua_pushfstring(L, "@%s", filename); + lf.f = fopen(filename, "r"); + if (!lf.f) return errfile(L, "open", fnameindex); + } + lf.type = 0; + if (skipcomment(&lf, &c)) /* read initial portion */ + lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */ + if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ + lf.f = freopen_bin(filename, lf.f); /* reopen in binary mode */ + if (!lf.f) return errfile(L, "reopen", fnameindex); + skipcomment(&lf, &c); /* re-read initial portion */ + } + if (c != EOF) + lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */ + status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode); +#ifdef LUA_CROSS_COMPILER + readstatus = ferror(lf.f); + if (filename) fclose(lf.f); /* close file (even in case of errors) */ + if (readstatus) { + lua_settop(L, fnameindex); /* ignore results from 'lua_load' */ + return errfile(L, "read", fnameindex); + } +#else + (void) readstatus; /* avoid compile error */ + if (filename) vfs_close(lf.f); /* close file (even in case of errors) */ +#endif + lua_remove(L, fnameindex); + return status; +} + + +typedef struct LoadS { + const char *s; + size_t size; +} LoadS; + + +static const char *getS (lua_State *L, void *ud, size_t *size) { + LoadS *ls = (LoadS *)ud; + (void)L; /* not used */ + if (ls->size == 0) return NULL; + *size = ls->size; + ls->size = 0; + return ls->s; +} + + +LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size, + const char *name, const char *mode) { + LoadS ls; + ls.s = buff; + ls.size = size; + return lua_load(L, getS, &ls, name, mode); +} + + +LUALIB_API int luaL_loadstring (lua_State *L, const char *s) { + return luaL_loadbuffer(L, s, strlen(s), s); +} + +/* }====================================================== */ + + + +LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { + if (!lua_getmetatable(L, obj)) /* no metatable? */ + return LUA_TNIL; + else { + int tt; + lua_pushstring(L, event); + tt = lua_rawget(L, -2); + if (tt == LUA_TNIL) /* is metafield nil? */ + lua_pop(L, 2); /* remove metatable and metafield */ + else + lua_remove(L, -2); /* remove only metatable */ + return tt; /* return metafield type */ + } +} + + +LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { + obj = lua_absindex(L, obj); + if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */ + return 0; + lua_pushvalue(L, obj); + lua_call(L, 1, 1); + return 1; +} + + +LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) { + lua_Integer l; + int isnum; + lua_len(L, idx); + l = lua_tointegerx(L, -1, &isnum); + if (!isnum) + luaL_error(L, "object length is not an integer"); + lua_pop(L, 1); /* remove object */ + return l; +} + + +LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { + if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */ + if (!lua_isstring(L, -1)) + luaL_error(L, "'__tostring' must return a string"); + } + else { + switch (lua_type(L, idx)) { + case LUA_TNUMBER: { + if (lua_isinteger(L, idx)) + lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx)); + else + lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx)); + break; + } + case LUA_TSTRING: + lua_pushvalue(L, idx); + break; + case LUA_TBOOLEAN: + lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false")); + break; + case LUA_TNIL: + lua_pushliteral(L, "nil"); + break; + default: { + int tt = luaL_getmetafield(L, idx, "__name"); /* try name */ + const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) : + luaL_typename(L, idx); + lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx)); + if (tt != LUA_TNIL) + lua_remove(L, -2); /* remove '__name' */ + break; + } + } + } + return lua_tolstring(L, -1, len); +} + + +/* +** {====================================================== +** Compatibility with 5.1 module functions +** ======================================================= +*/ +#if defined(LUA_COMPAT_MODULE) + +static const char *luaL_findtable (lua_State *L, int idx, + const char *fname, int szhint) { + const char *e; + if (idx) lua_pushvalue(L, idx); + do { + e = strchr(fname, '.'); + if (e == NULL) e = fname + strlen(fname); + lua_pushlstring(L, fname, e - fname); + if (lua_rawget(L, -2) == LUA_TNIL) { /* no such field? */ + lua_pop(L, 1); /* remove this nil */ + lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */ + lua_pushlstring(L, fname, e - fname); + lua_pushvalue(L, -2); + lua_settable(L, -4); /* set new table into field */ + } + else if (!lua_istable(L, -1)) { /* field has a non-table value? */ + lua_pop(L, 2); /* remove table and value */ + return fname; /* return problematic part of the name */ + } + lua_remove(L, -2); /* remove previous table */ + fname = e + 1; + } while (*e == '.'); + return NULL; +} + + +/* +** Count number of elements in a luaL_Reg list. +*/ +static int libsize (const luaL_Reg *l) { + int size = 0; + for (; l && l->name; l++) size++; + return size; +} + + +/* +** Find or create a module table with a given name. The function +** first looks at the LOADED table and, if that fails, try a +** global variable with that name. In any case, leaves on the stack +** the module table. +*/ +LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname, + int sizehint) { + luaL_findtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE, 1); + if (lua_getfield(L, -1, modname) != LUA_TTABLE) { /* no LOADED[modname]? */ + lua_pop(L, 1); /* remove previous result */ + /* try global variable (and create one if it does not exist) */ + lua_pushglobaltable(L); + if (luaL_findtable(L, 0, modname, sizehint) != NULL) + luaL_error(L, "name conflict for module '%s'", modname); + lua_pushvalue(L, -1); + lua_setfield(L, -3, modname); /* LOADED[modname] = new table */ + } + lua_remove(L, -2); /* remove LOADED table */ +} + + +LUALIB_API void luaL_openlib (lua_State *L, const char *libname, + const luaL_Reg *l, int nup) { + luaL_checkversion(L); + if (libname) { + luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */ + lua_insert(L, -(nup + 1)); /* move library table to below upvalues */ + } + if (l) + luaL_setfuncs(L, l, nup); + else + lua_pop(L, nup); /* remove upvalues */ +} + +#endif +/* }====================================================== */ + +/* +** set functions from list 'l' into table at top - 'nup'; each +** function gets the 'nup' elements at the top as upvalues. +** Returns with only the table at the stack. +*/ +LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { + luaL_checkstack(L, nup, "too many upvalues"); + for (; l->name != NULL; l++) { /* fill the table with given functions */ + int i; + for (i = 0; i < nup; i++) /* copy upvalues to the top */ + lua_pushvalue(L, -nup); + lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ + lua_setfield(L, -(nup + 2), l->name); + } + lua_pop(L, nup); /* remove upvalues */ +} + + +/* +** ensure that stack[idx][fname] has a table and push that table +** into the stack +*/ +LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) { + if (lua_getfield(L, idx, fname) == LUA_TTABLE) + return 1; /* table already there */ + else { + lua_pop(L, 1); /* remove previous result */ + idx = lua_absindex(L, idx); + lua_newtable(L); + lua_pushvalue(L, -1); /* copy to be left at top */ + lua_setfield(L, idx, fname); /* assign new table to field */ + return 0; /* false, because did not find table there */ + } +} + + +/* +** Stripped-down 'require' used in linit.c and ltests.c. After checking +** "loaded" and ROM tables, calls 'openf' to open a module, registers the +** result in 'package.loaded' table and, if 'glb' is true, also registers +** the result in the global table. Leaves resulting module on the top. +*/ +LUALIB_API void luaL_requiref (lua_State *L, const char *modname, + lua_CFunction openf, int glb) { + int inROM = 0; + luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); + lua_getfield(L, -1, modname); /* LOADED[modname] */ + if (!lua_toboolean(L, -1)) { /* package not in LOADED table? */ + lua_getglobal(L, "ROM"); /* try the ROM entry */ + if(!lua_isnil(L,-1)) { + lua_getfield(L, -1, modname); /* ROM[name] */ + inROM = lua_toboolean(L, -1); + lua_pop(L, 3); + } else + lua_pop(L, 2); + + if (inROM) /* package is in ROM */ + glb = 0; /* suppress setting _G entry */ + lua_pushcfunction(L, openf); + lua_pushstring(L, modname); /* argument to open function */ + lua_call(L, 1, 1); /* call 'openf' to open module */ + if (lua_toboolean(L, -1) && !inROM) { /* if not in ROM & result is returned */ + lua_pushvalue(L, -1); /* make copy of module (call result) */ + lua_setfield(L, -3, modname); /* LOADED[modname] = module */ + } + } + lua_remove(L, -2); /* remove LOADED table */ + if (glb) { + lua_pushvalue(L, -1); /* copy of module */ + lua_setglobal(L, modname); /* _G[modname] = module */ + } +} + + +LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, + const char *r) { + const char *wild; + size_t l = strlen(p); + luaL_Buffer b; + luaL_buffinit(L, &b); + while ((wild = strstr(s, p)) != NULL) { + luaL_addlstring(&b, s, wild - s); /* push prefix */ + luaL_addstring(&b, r); /* push replacement in place of pattern */ + s = wild + l; /* continue after 'p' */ + } + luaL_addstring(&b, s); /* push last suffix */ + luaL_pushresult(&b); + return lua_tostring(L, -1); +} + + +static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { + (void)ud; (void)osize; /* not used */ + if (nsize == 0) { + free(ptr); + return NULL; + } + else + return realloc(ptr, nsize); +} + + +LUALIB_API lua_State *luaL_newstate (void) { + lua_State *L = lua_newstate(l_alloc, NULL); + if (L) lua_atpanic(L, lpanic); + return L; +} + + +LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) { + const lua_Number *v = lua_version(L); + if (sz != LUAL_NUMSIZES) /* check numeric types */ + luaL_error(L, "core and library have incompatible numeric types"); + if (v != lua_version(NULL)) + luaL_error(L, "multiple Lua VMs detected"); + else if (*v != ver) + luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f", + (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)*v); +} + +#ifdef LUA_USE_ESP +/* +** Error Reporting Task. We can't pass a string parameter to the error reporter +** directly through the task interface the call is wrapped in a C closure with +** the error string as an Upval and this is posted to call the Lua reporter. +*/ +static int errhandler_aux (lua_State *L) { + lua_getfield(L, LUA_REGISTRYINDEX, "onerror"); + if (!lua_isfunction(L, -1)) { + lua_pop(L, 1); + lua_getglobal(L, "print"); + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_call(L, 1, 0); /* Using an error handler would cause an infinite loop! */ + return 0; +} + +/* +** Error handler for luaL_pcallx(), called from the lua_pcall() with a single +** argument -- the thrown error. This plus depth=2 is passed to debug.traceback() +** to convert into an error message which it handles in a separate posted task. +*/ +static int errhandler (lua_State *L) { + lua_getglobal(L, "debug"); + lua_getfield(L, -1, "traceback"); + if (lua_isfunction(L, -1)) { + lua_insert(L, 1); /* insert tracback function above error */ + lua_pop(L, 1); /* dump the debug table entry */ + lua_pushinteger(L, 2); /* skip this function and traceback */ + lua_call(L, 2, 1); /* call debug.traceback and return it as a string */ + lua_pushcclosure(L, errhandler_aux, 1); /* report with str as upval */ + luaL_posttask(L, LUA_TASK_HIGH); + } + return 0; +} + +/* +** Extended interface to 'lua_pcall', which sets appropriate message and Lua +** stack trackback. On error a separate task is posted to report the error. +*/ +LUALIB_API int luaL_pcallx (lua_State *L, int narg, int nres) { + int status; + int base = lua_gettop(L) - narg; /* function index */ + lua_pushcfunction(L, errhandler); /* push message handler */ + lua_insert(L, base); /* put it under function and args */ + status = lua_pcall(L, narg, nres, base); + lua_remove(L, base); /* remove message handler from the stack */ + if (status != LUA_OK && status != LUA_ERRRUN) { + lua_gc(L, LUA_GCCOLLECT, 0); /* call onerror directly if handler failed */ + lua_pushliteral(L, "out of memory"); + lua_pushcclosure(L, errhandler_aux, 1); /* report EOM as upval */ + luaL_posttask(L, LUA_TASK_HIGH); + } + return status; +} +#endif diff --git a/components/lua/lua-5.3/lauxlib.h b/components/lua/lua-5.3/lauxlib.h new file mode 100644 index 00000000..2aff96ba --- /dev/null +++ b/components/lua/lua-5.3/lauxlib.h @@ -0,0 +1,306 @@ +/* +** $Id: lauxlib.h,v 1.131.1.1 2017/04/19 17:20:42 roberto Exp $ +** Auxiliary functions for building Lua libraries +** See Copyright Notice in lua.h +*/ + + +#ifndef lauxlib_h +#define lauxlib_h + + +#include +#include + +#include "lua.h" + +#ifdef LUA_LIB +#include "lnodemcu.h" +#endif + + +/* extra error code for 'luaL_loadfilex' */ +#define LUA_ERRFILE (LUA_ERRERR+1) + + +/* key, in the registry, for table of loaded modules */ +#define LUA_LOADED_TABLE "_LOADED" + + +/* key, in the registry, for table of preloaded loaders */ +#define LUA_PRELOAD_TABLE "_PRELOAD" + + +typedef struct luaL_Reg { + const char *name; + lua_CFunction func; +} luaL_Reg; + + +#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number)) + +LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz); +#define luaL_checkversion(L) \ + luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES) + +LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); +LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); +LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len); +LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg); +LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg, + size_t *l); +LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg, + const char *def, size_t *l); +LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg); +LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def); + +LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg); +LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg, + lua_Integer def); + +LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); +LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t); +LUALIB_API void (luaL_checkany) (lua_State *L, int arg); + +LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); +LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); +LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); +LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); +LUALIB_API int (luaL_rometatable) (lua_State *L, const char* tname, const ROTable *p); +LUALIB_API void (luaL_where) (lua_State *L, int lvl); +LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); + +LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def, + const char *const lst[]); + +LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname); +LUALIB_API int (luaL_execresult) (lua_State *L, int stat); + +/* predefined references */ +#define LUA_NOREF (-2) +#define LUA_REFNIL (-1) + +LUALIB_API int (luaL_ref) (lua_State *L, int t); +LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); +#define luaL_unref2(l,t,r) do {luaL_unref(L, (t), (r)); r = LUA_NOREF;} while (0) +LUALIB_API void (luaL_reref) (lua_State *L, int t, int *ref); + +LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, + const char *mode); + +#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) + +LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, + const char *name, const char *mode); +LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); + +LUALIB_API lua_State *(luaL_newstate) (void); + +LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx); + +LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, + const char *r); + +LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); + +LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname); + +LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1, + const char *msg, int level); + +LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname, + lua_CFunction openf, int glb); + +/* +** =============================================================== +** some useful macros +** =============================================================== +*/ + + +#define luaL_newlibtable(L,l) \ + lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) + +#define luaL_newlib(L,l) \ + (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) + +#define luaL_argcheck(L, cond,arg,extramsg) \ + ((void)((cond) || luaL_argerror(L, (arg), (extramsg)))) +#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) +#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) + +#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) + +#define luaL_dofile(L, fn) \ + (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) + +#define luaL_dostring(L, s) \ + (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) + +#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) + +#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) + +#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) + + +#define luaL_checkfunction(L,n) luaL_checktype(L, (n), LUA_TFUNCTION); +#define luaL_checktable(L,n) luaL_checktype(L, (n), LUA_TTABLE); + +/* +** {====================================================== +** Generic Buffer manipulation +** ======================================================= +*/ + +typedef struct luaL_Buffer { + char *b; /* buffer address */ + size_t size; /* buffer size */ + size_t n; /* number of characters in buffer */ + lua_State *L; + char initb[LUAL_BUFFERSIZE]; /* initial buffer */ +} luaL_Buffer; + + +#define luaL_addchar(B,c) \ + ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \ + ((B)->b[(B)->n++] = (c))) + +#define luaL_addsize(B,s) ((B)->n += (s)) + +LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); +LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz); +LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); +LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); +LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); +LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); +LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz); +LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz); + +#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) + +/* }====================================================== */ + + + +/* +** {====================================================== +** File handles for IO library +** ======================================================= +*/ + +/* +** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and +** initial structure 'luaL_Stream' (it may contain other fields +** after that initial structure). +*/ + +#define LUA_FILEHANDLE "FILE*" + + +typedef struct luaL_Stream { + FILE *f; /* stream (NULL for incompletely created streams) */ + lua_CFunction closef; /* to close stream (NULL for closed streams) */ +} luaL_Stream; + +/* }====================================================== */ + +LUALIB_API int (luaL_rometatable) (lua_State *L, const char* tname, const ROTable *t); + +/* }====================================================== */ + +/* compatibility with old module system */ +#if defined(LUA_COMPAT_MODULE) + +LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname, + int sizehint); +LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname, + const luaL_Reg *l, int nup); + +#define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0)) + +#endif + + +/* +** {================================================================== +** "Abstraction Layer" for basic report of messages and errors +** =================================================================== +*/ + +/* print a string */ +#if !defined(lua_writestring) +#ifdef LUA_USE_ESP +void output_redirect(const char *str, size_t l); +#define lua_writestring(s,l) output_redirect((s),(l)) +#else +#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) +#endif +#endif + +/* print a newline and flush the output */ +#if !defined(lua_writeline) +#ifdef LUA_USE_ESP8266 +#define lua_writeline() lua_writestring("\n", 1) +#else +#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout)) +#endif +#endif + +/* print an error message. This is a primitive error output */ +#if !defined(lua_writestringerror) +#ifdef LUA_USE_ESP8266 +extern void dbg_printf(const char *fmt, ...); +#define lua_writestringerror(s,p) dbg_printf((s), (p)) +#else +#define lua_writestringerror(s,p) (fprintf(stderr, (s), (p)), fflush(stderr)) +#endif +#endif + +/* }================================================================== */ + +/* +** {============================================================ +** Compatibility with deprecated conversions +** ============================================================= +*/ +#if defined(LUA_COMPAT_APIINTCASTS) + +#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a)) +#define luaL_optunsigned(L,a,d) \ + ((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d))) + +#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) +#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) + +#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) +#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) + +#endif +/* }============================================================ */ + +/* +** {================================================================== +** NodeMCU extensions +** =================================================================== +*/ + +#define LUA_TASK_LOW 0 +#define LUA_TASK_MEDIUM 1 +#define LUA_TASK_HIGH 2 + +LUALIB_API int (luaL_pushlfsmodules) (lua_State *L); +LUALIB_API int (luaL_pushlfsdts) (lua_State *L); +LUALIB_API void (luaL_lfsreload) (lua_State *L); +LUALIB_API int (luaL_posttask) (lua_State* L, int prio); +LUALIB_API int (luaL_pcallx) (lua_State *L, int narg, int nres); +#define luaL_pushlfsmodule(l) lua_pushlfsfunc(L) + +/* }============================================================ */ + +#ifndef LUA_CROSS_COMPILER +int panic_get_nvval(void); +void panic_clear_nvval(void); +#endif + +#endif diff --git a/components/lua/lua-5.3/lbaselib.c b/components/lua/lua-5.3/lbaselib.c new file mode 100644 index 00000000..fabe3374 --- /dev/null +++ b/components/lua/lua-5.3/lbaselib.c @@ -0,0 +1,525 @@ +/* +** $Id: lbaselib.c,v 1.314.1.1 2017/04/19 17:39:34 roberto Exp $ +** Basic library +** See Copyright Notice in lua.h +*/ + +#define lbaselib_c +#define LUA_LIB + +#include "lprefix.h" + +#include +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +static int luaB_print (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int i; + lua_getglobal(L, "tostring"); + for (i=1; i<=n; i++) { + const char *s; + size_t l; + lua_pushvalue(L, -1); /* function to be called */ + lua_pushvalue(L, i); /* value to print */ + lua_call(L, 1, 1); + s = lua_tolstring(L, -1, &l); /* get result */ + if (s == NULL) + return luaL_error(L, "'tostring' must return a string to 'print'"); + if (i>1) lua_writestring("\t", 1); + lua_writestring(s, l); + lua_pop(L, 1); /* pop result */ + } + lua_writeline(); + return 0; +} + + +#define SPACECHARS " \f\n\r\t\v" + +static const char *b_str2int (const char *s, int base, lua_Integer *pn) { + lua_Unsigned n = 0; + int neg = 0; + s += strspn(s, SPACECHARS); /* skip initial spaces */ + if (*s == '-') { s++; neg = 1; } /* handle signal */ + else if (*s == '+') s++; + if (!isalnum((unsigned char)*s)) /* no digit? */ + return NULL; + do { + int digit = (isdigit((unsigned char)*s)) ? *s - '0' + : (toupper((unsigned char)*s) - 'A') + 10; + if (digit >= base) return NULL; /* invalid numeral */ + n = n * base + digit; + s++; + } while (isalnum((unsigned char)*s)); + s += strspn(s, SPACECHARS); /* skip trailing spaces */ + *pn = (lua_Integer)((neg) ? (0u - n) : n); + return s; +} + + +static int luaB_tonumber (lua_State *L) { + if (lua_isnoneornil(L, 2)) { /* standard conversion? */ + luaL_checkany(L, 1); + if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */ + lua_settop(L, 1); /* yes; return it */ + return 1; + } + else { + size_t l; + const char *s = lua_tolstring(L, 1, &l); + if (s != NULL && lua_stringtonumber(L, s) == l + 1) + return 1; /* successful conversion to number */ + /* else not a number */ + } + } + else { + size_t l; + const char *s; + lua_Integer n = 0; /* to avoid warnings */ + lua_Integer base = luaL_checkinteger(L, 2); + luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */ + s = lua_tolstring(L, 1, &l); + luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); + if (b_str2int(s, (int)base, &n) == s + l) { + lua_pushinteger(L, n); + return 1; + } /* else not a number */ + } /* else not a number */ + lua_pushnil(L); /* not a number */ + return 1; +} + + +static int luaB_error (lua_State *L) { + int level = (int)luaL_optinteger(L, 2, 1); + lua_settop(L, 1); + if (lua_type(L, 1) == LUA_TSTRING && level > 0) { + luaL_where(L, level); /* add extra information */ + lua_pushvalue(L, 1); + lua_concat(L, 2); + } + return lua_error(L); +} + + +static int luaB_getmetatable (lua_State *L) { + luaL_checkany(L, 1); + if (!lua_getmetatable(L, 1)) { + lua_pushnil(L); + return 1; /* no metatable */ + } + luaL_getmetafield(L, 1, "__metatable"); + return 1; /* returns either __metatable field (if present) or metatable */ +} + + +static int luaB_setmetatable (lua_State *L) { + int t = lua_type(L, 2); + luaL_checktype(L, 1, LUA_TTABLE); + luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, + "nil or table expected"); + if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL) + return luaL_error(L, "cannot change a protected metatable"); + lua_settop(L, 2); + lua_setmetatable(L, 1); + return 1; +} + + +static int luaB_rawequal (lua_State *L) { + luaL_checkany(L, 1); + luaL_checkany(L, 2); + lua_pushboolean(L, lua_rawequal(L, 1, 2)); + return 1; +} + + +static int luaB_rawlen (lua_State *L) { + int t = lua_type(L, 1); + luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1, + "table or string expected"); + lua_pushinteger(L, lua_rawlen(L, 1)); + return 1; +} + + +static int luaB_rawget (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + luaL_checkany(L, 2); + lua_settop(L, 2); + lua_rawget(L, 1); + return 1; +} + +static int luaB_rawset (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + luaL_checkany(L, 2); + luaL_checkany(L, 3); + lua_settop(L, 3); + lua_rawset(L, 1); + return 1; +} + + +static int luaB_collectgarbage (lua_State *L) { + static const char *const opts[] = {"stop", "restart", "collect", + "count", "step", "setpause", "setstepmul", "setmemlimit", + "isrunning", NULL}; + static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, + LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL, + LUA_GCISRUNNING}; + int o = optsnum[luaL_checkoption(L, 1, "collect", opts)]; + int ex = (int)luaL_optinteger(L, 2, 0); + int res = lua_gc(L, o, ex); + switch (o) { + case LUA_GCCOUNT: { + int b = lua_gc(L, LUA_GCCOUNTB, 0); + lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024)); + return 1; + } + case LUA_GCSTEP: case LUA_GCISRUNNING: { + lua_pushboolean(L, res); + return 1; + } + default: { + lua_pushinteger(L, res); + return 1; + } + } +} + + +static int luaB_type (lua_State *L) { + int t = lua_type(L, 1); + luaL_argcheck(L, t != LUA_TNONE, 1, "value expected"); + lua_pushstring(L, lua_typename(L, t)); + return 1; +} + + +static int pairsmeta (lua_State *L, const char *method, int iszero, + lua_CFunction iter) { + luaL_checkany(L, 1); + if (luaL_getmetafield(L, 1, method) == LUA_TNIL) { /* no metamethod? */ + lua_pushcfunction(L, iter); /* will return generator, */ + lua_pushvalue(L, 1); /* state, */ + if (iszero) lua_pushinteger(L, 0); /* and initial value */ + else lua_pushnil(L); + } + else { + lua_pushvalue(L, 1); /* argument 'self' to metamethod */ + lua_call(L, 1, 3); /* get 3 values from metamethod */ + } + return 3; +} + + +static int luaB_next (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + lua_settop(L, 2); /* create a 2nd argument if there isn't one */ + if (lua_next(L, 1)) + return 2; + else { + lua_pushnil(L); + return 1; + } +} + + +static int luaB_pairs (lua_State *L) { + return pairsmeta(L, "__pairs", 0, luaB_next); +} + + +/* +** Traversal function for 'ipairs' +*/ +static int ipairsaux (lua_State *L) { + lua_Integer i = luaL_checkinteger(L, 2) + 1; + lua_pushinteger(L, i); + return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2; +} + + +/* +** 'ipairs' function. Returns 'ipairsaux', given "table", 0. +** (The given "table" may not be a table.) +*/ +static int luaB_ipairs (lua_State *L) { +#if defined(LUA_COMPAT_IPAIRS) + return pairsmeta(L, "__ipairs", 1, ipairsaux); +#else + luaL_checkany(L, 1); + lua_pushcfunction(L, ipairsaux); /* iteration function */ + lua_pushvalue(L, 1); /* state */ + lua_pushinteger(L, 0); /* initial value */ + return 3; +#endif +} + + +static int load_aux (lua_State *L, int status, int envidx) { + if (status == LUA_OK) { + if (envidx != 0) { /* 'env' parameter? */ + lua_pushvalue(L, envidx); /* environment for loaded function */ + if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */ + lua_pop(L, 1); /* remove 'env' if not used by previous call */ + } + return 1; + } + else { /* error (message is on top of the stack) */ + lua_pushnil(L); + lua_insert(L, -2); /* put before error message */ + return 2; /* return nil plus error message */ + } +} + + +static int luaB_loadfile (lua_State *L) { + const char *fname = luaL_optstring(L, 1, NULL); + const char *mode = luaL_optstring(L, 2, NULL); + int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */ + int status = luaL_loadfilex(L, fname, mode); + return load_aux(L, status, env); +} + + +/* +** {====================================================== +** Generic Read function +** ======================================================= +*/ + + +/* +** reserved slot, above all arguments, to hold a copy of the returned +** string to avoid it being collected while parsed. 'load' has four +** optional arguments (chunk, source name, mode, and environment). +*/ +#define RESERVEDSLOT 5 + + +/* +** Reader for generic 'load' function: 'lua_load' uses the +** stack for internal stuff, so the reader cannot change the +** stack top. Instead, it keeps its resulting string in a +** reserved slot inside the stack. +*/ +static const char *generic_reader (lua_State *L, void *ud, size_t *size) { + (void)(ud); /* not used */ + luaL_checkstack(L, 2, "too many nested functions"); + lua_pushvalue(L, 1); /* get function */ + lua_call(L, 0, 1); /* call it */ + if (lua_isnil(L, -1)) { + lua_pop(L, 1); /* pop result */ + *size = 0; + return NULL; + } + else if (!lua_isstring(L, -1)) + luaL_error(L, "reader function must return a string"); + lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */ + return lua_tolstring(L, RESERVEDSLOT, size); +} + + +static int luaB_load (lua_State *L) { + int status; + size_t l; + const char *s = lua_tolstring(L, 1, &l); + const char *mode = luaL_optstring(L, 3, "bt"); + int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */ + if (s != NULL) { /* loading a string? */ + const char *chunkname = luaL_optstring(L, 2, s); + status = luaL_loadbufferx(L, s, l, chunkname, mode); + } + else { /* loading from a reader function */ + const char *chunkname = luaL_optstring(L, 2, "=(load)"); + luaL_checktype(L, 1, LUA_TFUNCTION); + lua_settop(L, RESERVEDSLOT); /* create reserved slot */ + status = lua_load(L, generic_reader, NULL, chunkname, mode); + } + return load_aux(L, status, env); +} + +/* }====================================================== */ + + +static int dofilecont (lua_State *L, int d1, lua_KContext d2) { + (void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */ + return lua_gettop(L) - 1; +} + + +static int luaB_dofile (lua_State *L) { + const char *fname = luaL_optstring(L, 1, NULL); + lua_settop(L, 1); + if (luaL_loadfile(L, fname) != LUA_OK) + return lua_error(L); + lua_callk(L, 0, LUA_MULTRET, 0, dofilecont); + return dofilecont(L, 0, 0); +} + + +static int luaB_assert (lua_State *L) { + if (lua_toboolean(L, 1)) /* condition is true? */ + return lua_gettop(L); /* return all arguments */ + else { /* error */ + luaL_checkany(L, 1); /* there must be a condition */ + lua_remove(L, 1); /* remove it */ + lua_pushliteral(L, "assertion failed!"); /* default message */ + lua_settop(L, 1); /* leave only message (default if no other one) */ + return luaB_error(L); /* call 'error' */ + } +} + + +static int luaB_select (lua_State *L) { + int n = lua_gettop(L); + if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { + lua_pushinteger(L, n-1); + return 1; + } + else { + lua_Integer i = luaL_checkinteger(L, 1); + if (i < 0) i = n + i; + else if (i > n) i = n; + luaL_argcheck(L, 1 <= i, 1, "index out of range"); + return n - (int)i; + } +} + + +/* +** Continuation function for 'pcall' and 'xpcall'. Both functions +** already pushed a 'true' before doing the call, so in case of success +** 'finishpcall' only has to return everything in the stack minus +** 'extra' values (where 'extra' is exactly the number of items to be +** ignored). +*/ +static int finishpcall (lua_State *L, int status, lua_KContext extra) { + if (status != LUA_OK && status != LUA_YIELD) { /* error? */ + lua_pushboolean(L, 0); /* first result (false) */ + lua_pushvalue(L, -2); /* error message */ + return 2; /* return false, msg */ + } + else + return lua_gettop(L) - (int)extra; /* return all results */ +} + + +static int luaB_pcall (lua_State *L) { + int status; + luaL_checkany(L, 1); + lua_pushboolean(L, 1); /* first result if no errors */ + lua_insert(L, 1); /* put it in place */ + status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall); + return finishpcall(L, status, 0); +} + + +/* +** Do a protected call with error handling. After 'lua_rotate', the +** stack will have ; so, the function passes +** 2 to 'finishpcall' to skip the 2 first values when returning results. +*/ +static int luaB_xpcall (lua_State *L) { + int status; + int n = lua_gettop(L); + luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */ + lua_pushboolean(L, 1); /* first result */ + lua_pushvalue(L, 1); /* function */ + lua_rotate(L, 3, 2); /* move them below function's arguments */ + status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall); + return finishpcall(L, status, 2); +} + + +static int luaB_tostring (lua_State *L) { + luaL_checkany(L, 1); + luaL_tolstring(L, 1, NULL); + return 1; +} + +#if defined(LUA_COMPAT_UNPACK) +static int luaB_unpack (lua_State *L) { + int n = lua_gettop(L); /* number of elements to pack */ + lua_getglobal(L, "table"); + lua_getfield(L, -1, "unpack"); + lua_insert(L, 1); + lua_pop(L, 1); + lua_call(L, n, LUA_MULTRET); + return lua_gettop(L); +} +#endif + + +/* +** ESP builds use specific linker directives to marshal all the ROTable entries +** for the library modules including the base library into an entry vector in +** the PSECT ".lua_rotable" including the base library entries; this is bound +** into a ROTable in linit.c which then hooked into the __index metaentry for +** _G so that base library and ROM tables are directly resolved through _G. +** +** The host-based luac.cross builds which must use a standard GNU link or +** MSVC so this linker-specfic assembly approach can't be used. In this case +** luaopen_base returns a base_func ROTable so a two cascade resolution. See +** description in init.c for further details. + */ +#ifdef LUA_CROSS_COMPILER +LROT_BEGIN(base_func, NULL, 0) +#else +LROT_ENTRIES_IN_SECTION(base_func, rotable) +#endif + LROT_FUNCENTRY(assert, luaB_assert) + LROT_FUNCENTRY(collectgarbage, luaB_collectgarbage) + LROT_FUNCENTRY(dofile, luaB_dofile) + LROT_FUNCENTRY(error, luaB_error) + LROT_FUNCENTRY(getmetatable, luaB_getmetatable) + LROT_FUNCENTRY(ipairs, luaB_ipairs) + LROT_FUNCENTRY(loadfile, luaB_loadfile) + LROT_FUNCENTRY(load, luaB_load) +#if defined(LUA_COMPAT_LOADSTRING) + LROT_FUNCENTRY(loadstring, luaB_load) +#endif + LROT_FUNCENTRY(next, luaB_next) + LROT_FUNCENTRY(pairs, luaB_pairs) + LROT_FUNCENTRY(pcall, luaB_pcall) + LROT_FUNCENTRY(print, luaB_print) + LROT_FUNCENTRY(rawequal, luaB_rawequal) + LROT_FUNCENTRY(rawlen, luaB_rawlen) + LROT_FUNCENTRY(rawget, luaB_rawget) + LROT_FUNCENTRY(rawset, luaB_rawset) + LROT_FUNCENTRY(select, luaB_select) + LROT_FUNCENTRY(setmetatable, luaB_setmetatable) + LROT_FUNCENTRY(tonumber, luaB_tonumber) + LROT_FUNCENTRY(tostring, luaB_tostring) + LROT_FUNCENTRY(type, luaB_type) +#if defined(LUA_COMPAT_UNPACK) + LROT_FUNCENTRY(unpack, luaB_unpack) +#endif + LROT_FUNCENTRY(xpcall, luaB_xpcall) +#ifdef LUA_CROSS_COMPILER +LROT_END(base_func, NULL, 0) +#else +LROT_BREAK(base_func) +#endif + +extern LROT_TABLE(rotables); +LUAMOD_API int luaopen_base (lua_State *L) { + lua_pushglobaltable(L); /* set global _G */ + lua_pushliteral(L, LUA_VERSION); /* set global _VERSION */ + lua_setfield(L, -2, "_VERSION"); + lua_createtable (L, 0, 1); /* mt for _G */ + lua_pushrotable(L, LROT_TABLEREF(rotables)); + lua_setfield(L, -2, "__index"); /* mt.__index=ROM table */ + lua_setmetatable(L, -2); + return 1; /* returns _G */ +} diff --git a/components/lua/lua-5.3/lbitlib.c b/components/lua/lua-5.3/lbitlib.c new file mode 100644 index 00000000..4e8ed189 --- /dev/null +++ b/components/lua/lua-5.3/lbitlib.c @@ -0,0 +1,233 @@ +/* +** $Id: lbitlib.c,v 1.30.1.1 2017/04/19 17:20:42 roberto Exp $ +** Standard library for bitwise operations +** See Copyright Notice in lua.h +*/ + +#define lbitlib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +#if defined(LUA_COMPAT_BITLIB) /* { */ + + +#define pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) +#define checkunsigned(L,i) ((lua_Unsigned)luaL_checkinteger(L,i)) + + +/* number of bits to consider in a number */ +#if !defined(LUA_NBITS) +#define LUA_NBITS 32 +#endif + + +/* +** a lua_Unsigned with its first LUA_NBITS bits equal to 1. (Shift must +** be made in two parts to avoid problems when LUA_NBITS is equal to the +** number of bits in a lua_Unsigned.) +*/ +#define ALLONES (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1)) + + +/* macro to trim extra bits */ +#define trim(x) ((x) & ALLONES) + + +/* builds a number with 'n' ones (1 <= n <= LUA_NBITS) */ +#define mask(n) (~((ALLONES << 1) << ((n) - 1))) + + + +static lua_Unsigned andaux (lua_State *L) { + int i, n = lua_gettop(L); + lua_Unsigned r = ~(lua_Unsigned)0; + for (i = 1; i <= n; i++) + r &= checkunsigned(L, i); + return trim(r); +} + + +static int b_and (lua_State *L) { + lua_Unsigned r = andaux(L); + pushunsigned(L, r); + return 1; +} + + +static int b_test (lua_State *L) { + lua_Unsigned r = andaux(L); + lua_pushboolean(L, r != 0); + return 1; +} + + +static int b_or (lua_State *L) { + int i, n = lua_gettop(L); + lua_Unsigned r = 0; + for (i = 1; i <= n; i++) + r |= checkunsigned(L, i); + pushunsigned(L, trim(r)); + return 1; +} + + +static int b_xor (lua_State *L) { + int i, n = lua_gettop(L); + lua_Unsigned r = 0; + for (i = 1; i <= n; i++) + r ^= checkunsigned(L, i); + pushunsigned(L, trim(r)); + return 1; +} + + +static int b_not (lua_State *L) { + lua_Unsigned r = ~checkunsigned(L, 1); + pushunsigned(L, trim(r)); + return 1; +} + + +static int b_shift (lua_State *L, lua_Unsigned r, lua_Integer i) { + if (i < 0) { /* shift right? */ + i = -i; + r = trim(r); + if (i >= LUA_NBITS) r = 0; + else r >>= i; + } + else { /* shift left */ + if (i >= LUA_NBITS) r = 0; + else r <<= i; + r = trim(r); + } + pushunsigned(L, r); + return 1; +} + + +static int b_lshift (lua_State *L) { + return b_shift(L, checkunsigned(L, 1), luaL_checkinteger(L, 2)); +} + + +static int b_rshift (lua_State *L) { + return b_shift(L, checkunsigned(L, 1), -luaL_checkinteger(L, 2)); +} + + +static int b_arshift (lua_State *L) { + lua_Unsigned r = checkunsigned(L, 1); + lua_Integer i = luaL_checkinteger(L, 2); + if (i < 0 || !(r & ((lua_Unsigned)1 << (LUA_NBITS - 1)))) + return b_shift(L, r, -i); + else { /* arithmetic shift for 'negative' number */ + if (i >= LUA_NBITS) r = ALLONES; + else + r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i)); /* add signal bit */ + pushunsigned(L, r); + return 1; + } +} + + +static int b_rot (lua_State *L, lua_Integer d) { + lua_Unsigned r = checkunsigned(L, 1); + int i = d & (LUA_NBITS - 1); /* i = d % NBITS */ + r = trim(r); + if (i != 0) /* avoid undefined shift of LUA_NBITS when i == 0 */ + r = (r << i) | (r >> (LUA_NBITS - i)); + pushunsigned(L, trim(r)); + return 1; +} + + +static int b_lrot (lua_State *L) { + return b_rot(L, luaL_checkinteger(L, 2)); +} + + +static int b_rrot (lua_State *L) { + return b_rot(L, -luaL_checkinteger(L, 2)); +} + + +/* +** get field and width arguments for field-manipulation functions, +** checking whether they are valid. +** ('luaL_error' called without 'return' to avoid later warnings about +** 'width' being used uninitialized.) +*/ +static int fieldargs (lua_State *L, int farg, int *width) { + lua_Integer f = luaL_checkinteger(L, farg); + lua_Integer w = luaL_optinteger(L, farg + 1, 1); + luaL_argcheck(L, 0 <= f, farg, "field cannot be negative"); + luaL_argcheck(L, 0 < w, farg + 1, "width must be positive"); + if (f + w > LUA_NBITS) + luaL_error(L, "trying to access non-existent bits"); + *width = (int)w; + return (int)f; +} + + +static int b_extract (lua_State *L) { + int w; + lua_Unsigned r = trim(checkunsigned(L, 1)); + int f = fieldargs(L, 2, &w); + r = (r >> f) & mask(w); + pushunsigned(L, r); + return 1; +} + + +static int b_replace (lua_State *L) { + int w; + lua_Unsigned r = trim(checkunsigned(L, 1)); + lua_Unsigned v = trim(checkunsigned(L, 2)); + int f = fieldargs(L, 3, &w); + lua_Unsigned m = mask(w); + r = (r & ~(m << f)) | ((v & m) << f); + pushunsigned(L, r); + return 1; +} + + +static const luaL_Reg bitlib[] = { + {"arshift", b_arshift}, + {"band", b_and}, + {"bnot", b_not}, + {"bor", b_or}, + {"bxor", b_xor}, + {"btest", b_test}, + {"extract", b_extract}, + {"lrotate", b_lrot}, + {"lshift", b_lshift}, + {"replace", b_replace}, + {"rrotate", b_rrot}, + {"rshift", b_rshift}, + {NULL, NULL} +}; + + + +LUAMOD_API int luaopen_bit32 (lua_State *L) { + luaL_newlib(L, bitlib); + return 0; +} + + +#else /* }{ */ + + +LUAMOD_API int luaopen_bit32 (lua_State *L) { + return luaL_error(L, "library 'bit32' has been deprecated"); +} + +#endif /* } */ diff --git a/components/lua/lua-5.3/lcode.c b/components/lua/lua-5.3/lcode.c new file mode 100644 index 00000000..7529f2a8 --- /dev/null +++ b/components/lua/lua-5.3/lcode.c @@ -0,0 +1,1299 @@ +/* +** $Id: lcode.c,v 2.112.1.1 2017/04/19 17:20:42 roberto Exp $ +** Code generator for Lua +** See Copyright Notice in lua.h +*/ + +#define lcode_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include + +#include "lua.h" + +#include "lcode.h" +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "llex.h" +#include "lmem.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" +#include "lstring.h" +#include "ltable.h" +#include "lvm.h" + + +/* Maximum number of registers in a Lua function (must fit in 8 bits) */ +#define MAXREGS 255 + + +#define hasjumps(e) ((e)->t != (e)->f) + + +/* +** If expression is a numeric constant, fills 'v' with its value +** and returns 1. Otherwise, returns 0. +*/ +static int tonumeral(const expdesc *e, TValue *v) { + if (hasjumps(e)) + return 0; /* not a numeral */ + switch (e->k) { + case VKINT: + if (v) setivalue(v, e->u.ival); + return 1; + case VKFLT: + if (v) setfltvalue(v, e->u.nval); + return 1; + default: return 0; + } +} + + +/* +** Create a OP_LOADNIL instruction, but try to optimize: if the previous +** instruction is also OP_LOADNIL and ranges are compatible, adjust +** range of previous instruction instead of emitting a new one. (For +** instance, 'local a; local b' will generate a single opcode.) +*/ +void luaK_nil (FuncState *fs, int from, int n) { + Instruction *previous; + int l = from + n - 1; /* last register to set nil */ + if (fs->pc > fs->lasttarget) { /* no jumps to current position? */ + previous = &fs->f->code[fs->pc-1]; + if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */ + int pfrom = GETARG_A(*previous); /* get previous range */ + int pl = pfrom + GETARG_B(*previous); + if ((pfrom <= from && from <= pl + 1) || + (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ + if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ + if (pl > l) l = pl; /* l = max(l, pl) */ + SETARG_A(*previous, from); + SETARG_B(*previous, l - from); + return; + } + } /* else go through */ + } + luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ +} + + +/* +** Gets the destination address of a jump instruction. Used to traverse +** a list of jumps. +*/ +static int getjump (FuncState *fs, int pc) { + int offset = GETARG_sBx(fs->f->code[pc]); + if (offset == NO_JUMP) /* point to itself represents end of list */ + return NO_JUMP; /* end of list */ + else + return (pc+1)+offset; /* turn offset into absolute position */ +} + + +/* +** Fix jump instruction at position 'pc' to jump to 'dest'. +** (Jump addresses are relative in Lua) +*/ +static void fixjump (FuncState *fs, int pc, int dest) { + Instruction *jmp = &fs->f->code[pc]; + int offset = dest - (pc + 1); + lua_assert(dest != NO_JUMP); + if (abs(offset) > MAXARG_sBx) + luaX_syntaxerror(fs->ls, "control structure too long"); + SETARG_sBx(*jmp, offset); +} + + +/* +** Concatenate jump-list 'l2' into jump-list 'l1' +*/ +void luaK_concat (FuncState *fs, int *l1, int l2) { + if (l2 == NO_JUMP) return; /* nothing to concatenate? */ + else if (*l1 == NO_JUMP) /* no original list? */ + *l1 = l2; /* 'l1' points to 'l2' */ + else { + int list = *l1; + int next; + while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ + list = next; + fixjump(fs, list, l2); /* last element links to 'l2' */ + } +} + + +/* +** Create a jump instruction and return its position, so its destination +** can be fixed later (with 'fixjump'). If there are jumps to +** this position (kept in 'jpc'), link them all together so that +** 'patchlistaux' will fix all them directly to the final destination. +*/ +int luaK_jump (FuncState *fs) { + int jpc = fs->jpc; /* save list of jumps to here */ + int j; + fs->jpc = NO_JUMP; /* no more jumps to here */ + j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP); + luaK_concat(fs, &j, jpc); /* keep them on hold */ + return j; +} + + +/* +** Code a 'return' instruction +*/ +void luaK_ret (FuncState *fs, int first, int nret) { + luaK_codeABC(fs, OP_RETURN, first, nret+1, 0); +} + + +/* +** Code a "conditional jump", that is, a test or comparison opcode +** followed by a jump. Return jump position. +*/ +static int condjump (FuncState *fs, OpCode op, int A, int B, int C) { + luaK_codeABC(fs, op, A, B, C); + return luaK_jump(fs); +} + + +/* +** returns current 'pc' and marks it as a jump target (to avoid wrong +** optimizations with consecutive instructions not in the same basic block). +*/ +int luaK_getlabel (FuncState *fs) { + fs->lasttarget = fs->pc; + return fs->pc; +} + + +/* +** Returns the position of the instruction "controlling" a given +** jump (that is, its condition), or the jump itself if it is +** unconditional. +*/ +static Instruction *getjumpcontrol (FuncState *fs, int pc) { + Instruction *pi = &fs->f->code[pc]; + if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) + return pi-1; + else + return pi; +} + + +/* +** Patch destination register for a TESTSET instruction. +** If instruction in position 'node' is not a TESTSET, return 0 ("fails"). +** Otherwise, if 'reg' is not 'NO_REG', set it as the destination +** register. Otherwise, change instruction to a simple 'TEST' (produces +** no register value) +*/ +static int patchtestreg (FuncState *fs, int node, int reg) { + Instruction *i = getjumpcontrol(fs, node); + if (GET_OPCODE(*i) != OP_TESTSET) + return 0; /* cannot patch other instructions */ + if (reg != NO_REG && reg != GETARG_B(*i)) + SETARG_A(*i, reg); + else { + /* no register to put value or register already has the value; + change instruction to simple test */ + *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i)); + } + return 1; +} + + +/* +** Traverse a list of tests ensuring no one produces a value +*/ +static void removevalues (FuncState *fs, int list) { + for (; list != NO_JUMP; list = getjump(fs, list)) + patchtestreg(fs, list, NO_REG); +} + + +/* +** Traverse a list of tests, patching their destination address and +** registers: tests producing values jump to 'vtarget' (and put their +** values in 'reg'), other tests jump to 'dtarget'. +*/ +static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, + int dtarget) { + while (list != NO_JUMP) { + int next = getjump(fs, list); + if (patchtestreg(fs, list, reg)) + fixjump(fs, list, vtarget); + else + fixjump(fs, list, dtarget); /* jump to default target */ + list = next; + } +} + + +/* +** Ensure all pending jumps to current position are fixed (jumping +** to current position with no values) and reset list of pending +** jumps +*/ +static void dischargejpc (FuncState *fs) { + patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc); + fs->jpc = NO_JUMP; +} + + +/* +** Add elements in 'list' to list of pending jumps to "here" +** (current position) +*/ +void luaK_patchtohere (FuncState *fs, int list) { + luaK_getlabel(fs); /* mark "here" as a jump target */ + luaK_concat(fs, &fs->jpc, list); +} + + +/* +** Path all jumps in 'list' to jump to 'target'. +** (The assert means that we cannot fix a jump to a forward address +** because we only know addresses once code is generated.) +*/ +void luaK_patchlist (FuncState *fs, int list, int target) { + if (target == fs->pc) /* 'target' is current position? */ + luaK_patchtohere(fs, list); /* add list to pending jumps */ + else { + lua_assert(target < fs->pc); + patchlistaux(fs, list, target, NO_REG, target); + } +} + + +/* +** Path all jumps in 'list' to close upvalues up to given 'level' +** (The assertion checks that jumps either were closing nothing +** or were closing higher levels, from inner blocks.) +*/ +void luaK_patchclose (FuncState *fs, int list, int level) { + level++; /* argument is +1 to reserve 0 as non-op */ + for (; list != NO_JUMP; list = getjump(fs, list)) { + lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP && + (GETARG_A(fs->f->code[list]) == 0 || + GETARG_A(fs->f->code[list]) >= level)); + SETARG_A(fs->f->code[list], level); + } +} + + +/* +** Emit instruction 'i', checking for array sizes and saving also its +** line information. Return 'i' position. +*/ +static int luaK_code (FuncState *fs, Instruction i) { + Proto *f = fs->f; + dischargejpc(fs); /* 'pc' will change */ + /* put new instruction in code array */ + luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, + MAX_INT, "opcodes"); + f->code[fs->pc] = i; + /* Map fs->pc to fs->ls->lastline */ + luaK_addlineinfo(fs, fs->pc, fs->ls->lastline); + return fs->pc++; +} + + +/* +** Format and emit an 'iABC' instruction. (Assertions check consistency +** of parameters versus opcode.) +*/ +int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) { + lua_assert(getOpMode(o) == iABC); + lua_assert(getBMode(o) != OpArgN || b == 0); + lua_assert(getCMode(o) != OpArgN || c == 0); + lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C); + return luaK_code(fs, CREATE_ABC(o, a, b, c)); +} + + +/* +** Format and emit an 'iABx' instruction. +*/ +int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { + lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx); + lua_assert(getCMode(o) == OpArgN); + lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx); + return luaK_code(fs, CREATE_ABx(o, a, bc)); +} + + +/* +** Emit an "extra argument" instruction (format 'iAx') +*/ +static int codeextraarg (FuncState *fs, int a) { + lua_assert(a <= MAXARG_Ax); + return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a)); +} + + +/* +** Emit a "load constant" instruction, using either 'OP_LOADK' +** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX' +** instruction with "extra argument". +*/ +int luaK_codek (FuncState *fs, int reg, int k) { + if (k <= MAXARG_Bx) + return luaK_codeABx(fs, OP_LOADK, reg, k); + else { + int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); + codeextraarg(fs, k); + return p; + } +} + + +/* +** Check register-stack level, keeping track of its maximum size +** in field 'maxstacksize' +*/ +void luaK_checkstack (FuncState *fs, int n) { + int newstack = fs->freereg + n; + if (newstack > fs->f->maxstacksize) { + if (newstack >= MAXREGS) + luaX_syntaxerror(fs->ls, + "function or expression needs too many registers"); + fs->f->maxstacksize = cast_byte(newstack); + } +} + + +/* +** Reserve 'n' registers in register stack +*/ +void luaK_reserveregs (FuncState *fs, int n) { + luaK_checkstack(fs, n); + fs->freereg += n; +} + + +/* +** Free register 'reg', if it is neither a constant index nor +** a local variable. +) +*/ +static void freereg (FuncState *fs, int reg) { + if (!ISK(reg) && reg >= fs->nactvar) { + fs->freereg--; + lua_assert(reg == fs->freereg); + } +} + + +/* +** Free register used by expression 'e' (if any) +*/ +static void freeexp (FuncState *fs, expdesc *e) { + if (e->k == VNONRELOC) + freereg(fs, e->u.info); +} + + +/* +** Free registers used by expressions 'e1' and 'e2' (if any) in proper +** order. +*/ +static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) { + int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1; + int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1; + if (r1 > r2) { + freereg(fs, r1); + freereg(fs, r2); + } + else { + freereg(fs, r2); + freereg(fs, r1); + } +} + + +/* +** Add constant 'v' to prototype's list of constants (field 'k'). +** Use scanner's table to cache position of constants in constant list +** and try to reuse constants. Because some values should not be used +** as keys (nil cannot be a key, integer keys can collapse with float +** keys), the caller must provide a useful 'key' for indexing the cache. +*/ +static int addk (FuncState *fs, TValue *key, TValue *v) { + lua_State *L = fs->ls->L; + Proto *f = fs->f; + TValue *idx = luaH_set(L, fs->ls->h, key); /* index scanner table */ + int k, oldsize; + if (ttisinteger(idx)) { /* is there an index there? */ + k = cast_int(ivalue(idx)); + /* correct value? (warning: must distinguish floats from integers!) */ + if (k < fs->nk && ttype(&f->k[k]) == ttype(v) && + luaV_rawequalobj(&f->k[k], v)) + return k; /* reuse index */ + } + /* constant not found; create a new entry */ + oldsize = f->sizek; + k = fs->nk; + /* numerical value does not need GC barrier; + table has no metatable, so it does not need to invalidate cache */ + setivalue(idx, k); + luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); + while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); + setobj(L, &f->k[k], v); + fs->nk++; + luaC_barrier(L, f, v); + return k; +} + + +/* +** Add a string to list of constants and return its index. +*/ +int luaK_stringK (FuncState *fs, TString *s) { + TValue o; + setsvalue(fs->ls->L, &o, s); + return addk(fs, &o, &o); /* use string itself as key */ +} + + +/* +** Add an integer to list of constants and return its index. +** Integers use userdata as keys to avoid collision with floats with +** same value; conversion to 'void*' is used only for hashing, so there +** are no "precision" problems. +*/ +int luaK_intK (FuncState *fs, lua_Integer n) { + TValue k, o; + setpvalue(&k, cast(void*, cast(size_t, n))); + setivalue(&o, n); + return addk(fs, &k, &o); +} + +/* +** Add a float to list of constants and return its index. +*/ +static int luaK_numberK (FuncState *fs, lua_Number r) { + TValue o; + setfltvalue(&o, r); + return addk(fs, &o, &o); /* use number itself as key */ +} + + +/* +** Add a boolean to list of constants and return its index. +*/ +static int boolK (FuncState *fs, int b) { + TValue o; + setbvalue(&o, b); + return addk(fs, &o, &o); /* use boolean itself as key */ +} + + +/* +** Add nil to list of constants and return its index. +*/ +static int nilK (FuncState *fs) { + TValue k, v; + setnilvalue(&v); + /* cannot use nil as key; instead use table itself to represent nil */ + sethvalue(fs->ls->L, &k, fs->ls->h); + return addk(fs, &k, &v); +} + + +/* +** Fix an expression to return the number of results 'nresults'. +** Either 'e' is a multi-ret expression (function call or vararg) +** or 'nresults' is LUA_MULTRET (as any expression can satisfy that). +*/ +void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { + if (e->k == VCALL) { /* expression is an open function call? */ + SETARG_C(getinstruction(fs, e), nresults + 1); + } + else if (e->k == VVARARG) { + Instruction *pc = &getinstruction(fs, e); + SETARG_B(*pc, nresults + 1); + SETARG_A(*pc, fs->freereg); + luaK_reserveregs(fs, 1); + } + else lua_assert(nresults == LUA_MULTRET); +} + + +/* +** Fix an expression to return one result. +** If expression is not a multi-ret expression (function call or +** vararg), it already returns one result, so nothing needs to be done. +** Function calls become VNONRELOC expressions (as its result comes +** fixed in the base register of the call), while vararg expressions +** become VRELOCABLE (as OP_VARARG puts its results where it wants). +** (Calls are created returning one result, so that does not need +** to be fixed.) +*/ +void luaK_setoneret (FuncState *fs, expdesc *e) { + if (e->k == VCALL) { /* expression is an open function call? */ + /* already returns 1 value */ + lua_assert(GETARG_C(getinstruction(fs, e)) == 2); + e->k = VNONRELOC; /* result has fixed position */ + e->u.info = GETARG_A(getinstruction(fs, e)); + } + else if (e->k == VVARARG) { + SETARG_B(getinstruction(fs, e), 2); + e->k = VRELOCABLE; /* can relocate its simple result */ + } +} + + +/* +** Ensure that expression 'e' is not a variable. +*/ +void luaK_dischargevars (FuncState *fs, expdesc *e) { + switch (e->k) { + case VLOCAL: { /* already in a register */ + e->k = VNONRELOC; /* becomes a non-relocatable value */ + break; + } + case VUPVAL: { /* move value to some (pending) register */ + e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); + e->k = VRELOCABLE; + break; + } + case VINDEXED: { + OpCode op; + freereg(fs, e->u.ind.idx); + if (e->u.ind.vt == VLOCAL) { /* is 't' in a register? */ + freereg(fs, e->u.ind.t); + op = OP_GETTABLE; + } + else { + lua_assert(e->u.ind.vt == VUPVAL); + op = OP_GETTABUP; /* 't' is in an upvalue */ + } + e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx); + e->k = VRELOCABLE; + break; + } + case VVARARG: case VCALL: { + luaK_setoneret(fs, e); + break; + } + default: break; /* there is one value available (somewhere) */ + } +} + + +/* +** Ensures expression value is in register 'reg' (and therefore +** 'e' will become a non-relocatable expression). +*/ +static void discharge2reg (FuncState *fs, expdesc *e, int reg) { + luaK_dischargevars(fs, e); + switch (e->k) { + case VNIL: { + luaK_nil(fs, reg, 1); + break; + } + case VFALSE: case VTRUE: { + luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0); + break; + } + case VK: { + luaK_codek(fs, reg, e->u.info); + break; + } + case VKFLT: { + luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval)); + break; + } + case VKINT: { + luaK_codek(fs, reg, luaK_intK(fs, e->u.ival)); + break; + } + case VRELOCABLE: { + Instruction *pc = &getinstruction(fs, e); + SETARG_A(*pc, reg); /* instruction will put result in 'reg' */ + break; + } + case VNONRELOC: { + if (reg != e->u.info) + luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); + break; + } + default: { + lua_assert(e->k == VJMP); + return; /* nothing to do... */ + } + } + e->u.info = reg; + e->k = VNONRELOC; +} + + +/* +** Ensures expression value is in any register. +*/ +static void discharge2anyreg (FuncState *fs, expdesc *e) { + if (e->k != VNONRELOC) { /* no fixed register yet? */ + luaK_reserveregs(fs, 1); /* get a register */ + discharge2reg(fs, e, fs->freereg-1); /* put value there */ + } +} + + +static int code_loadbool (FuncState *fs, int A, int b, int jump) { + luaK_getlabel(fs); /* those instructions may be jump targets */ + return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump); +} + + +/* +** check whether list has any jump that do not produce a value +** or produce an inverted value +*/ +static int need_value (FuncState *fs, int list) { + for (; list != NO_JUMP; list = getjump(fs, list)) { + Instruction i = *getjumpcontrol(fs, list); + if (GET_OPCODE(i) != OP_TESTSET) return 1; + } + return 0; /* not found */ +} + + +/* +** Ensures final expression result (including results from its jump +** lists) is in register 'reg'. +** If expression has jumps, need to patch these jumps either to +** its final position or to "load" instructions (for those tests +** that do not produce values). +*/ +static void exp2reg (FuncState *fs, expdesc *e, int reg) { + discharge2reg(fs, e, reg); + if (e->k == VJMP) /* expression itself is a test? */ + luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */ + if (hasjumps(e)) { + int final; /* position after whole expression */ + int p_f = NO_JUMP; /* position of an eventual LOAD false */ + int p_t = NO_JUMP; /* position of an eventual LOAD true */ + if (need_value(fs, e->t) || need_value(fs, e->f)) { + int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); + p_f = code_loadbool(fs, reg, 0, 1); + p_t = code_loadbool(fs, reg, 1, 0); + luaK_patchtohere(fs, fj); + } + final = luaK_getlabel(fs); + patchlistaux(fs, e->f, final, reg, p_f); + patchlistaux(fs, e->t, final, reg, p_t); + } + e->f = e->t = NO_JUMP; + e->u.info = reg; + e->k = VNONRELOC; +} + + +/* +** Ensures final expression result (including results from its jump +** lists) is in next available register. +*/ +void luaK_exp2nextreg (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + freeexp(fs, e); + luaK_reserveregs(fs, 1); + exp2reg(fs, e, fs->freereg - 1); +} + + +/* +** Ensures final expression result (including results from its jump +** lists) is in some (any) register and return that register. +*/ +int luaK_exp2anyreg (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + if (e->k == VNONRELOC) { /* expression already has a register? */ + if (!hasjumps(e)) /* no jumps? */ + return e->u.info; /* result is already in a register */ + if (e->u.info >= fs->nactvar) { /* reg. is not a local? */ + exp2reg(fs, e, e->u.info); /* put final result in it */ + return e->u.info; + } + } + luaK_exp2nextreg(fs, e); /* otherwise, use next available register */ + return e->u.info; +} + + +/* +** Ensures final expression result is either in a register or in an +** upvalue. +*/ +void luaK_exp2anyregup (FuncState *fs, expdesc *e) { + if (e->k != VUPVAL || hasjumps(e)) + luaK_exp2anyreg(fs, e); +} + + +/* +** Ensures final expression result is either in a register or it is +** a constant. +*/ +void luaK_exp2val (FuncState *fs, expdesc *e) { + if (hasjumps(e)) + luaK_exp2anyreg(fs, e); + else + luaK_dischargevars(fs, e); +} + + +/* +** Ensures final expression result is in a valid R/K index +** (that is, it is either in a register or in 'k' with an index +** in the range of R/K indices). +** Returns R/K index. +*/ +int luaK_exp2RK (FuncState *fs, expdesc *e) { + luaK_exp2val(fs, e); + switch (e->k) { /* move constants to 'k' */ + case VTRUE: e->u.info = boolK(fs, 1); goto vk; + case VFALSE: e->u.info = boolK(fs, 0); goto vk; + case VNIL: e->u.info = nilK(fs); goto vk; + case VKINT: e->u.info = luaK_intK(fs, e->u.ival); goto vk; + case VKFLT: e->u.info = luaK_numberK(fs, e->u.nval); goto vk; + case VK: + vk: + e->k = VK; + if (e->u.info <= MAXINDEXRK) /* constant fits in 'argC'? */ + return RKASK(e->u.info); + else break; + default: break; + } + /* not a constant in the right range: put it in a register */ + return luaK_exp2anyreg(fs, e); +} + + +/* +** Generate code to store result of expression 'ex' into variable 'var'. +*/ +void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { + switch (var->k) { + case VLOCAL: { + freeexp(fs, ex); + exp2reg(fs, ex, var->u.info); /* compute 'ex' into proper place */ + return; + } + case VUPVAL: { + int e = luaK_exp2anyreg(fs, ex); + luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); + break; + } + case VINDEXED: { + OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP; + int e = luaK_exp2RK(fs, ex); + luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e); + break; + } + default: lua_assert(0); /* invalid var kind to store */ + } + freeexp(fs, ex); +} + + +/* +** Emit SELF instruction (convert expression 'e' into 'e:key(e,'). +*/ +void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { + int ereg; + luaK_exp2anyreg(fs, e); + ereg = e->u.info; /* register where 'e' was placed */ + freeexp(fs, e); + e->u.info = fs->freereg; /* base register for op_self */ + e->k = VNONRELOC; /* self expression has a fixed register */ + luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */ + luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key)); + freeexp(fs, key); +} + + +/* +** Negate condition 'e' (where 'e' is a comparison). +*/ +static void negatecondition (FuncState *fs, expdesc *e) { + Instruction *pc = getjumpcontrol(fs, e->u.info); + lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && + GET_OPCODE(*pc) != OP_TEST); + SETARG_A(*pc, !(GETARG_A(*pc))); +} + + +/* +** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond' +** is true, code will jump if 'e' is true.) Return jump position. +** Optimize when 'e' is 'not' something, inverting the condition +** and removing the 'not'. +*/ +static int jumponcond (FuncState *fs, expdesc *e, int cond) { + if (e->k == VRELOCABLE) { + Instruction ie = getinstruction(fs, e); + if (GET_OPCODE(ie) == OP_NOT) { + fs->pc--; /* remove previous OP_NOT */ + return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond); + } + /* else go through */ + } + discharge2anyreg(fs, e); + freeexp(fs, e); + return condjump(fs, OP_TESTSET, NO_REG, e->u.info, cond); +} + + +/* +** Emit code to go through if 'e' is true, jump otherwise. +*/ +void luaK_goiftrue (FuncState *fs, expdesc *e) { + int pc; /* pc of new jump */ + luaK_dischargevars(fs, e); + switch (e->k) { + case VJMP: { /* condition? */ + negatecondition(fs, e); /* jump when it is false */ + pc = e->u.info; /* save jump position */ + break; + } + case VK: case VKFLT: case VKINT: case VTRUE: { + pc = NO_JUMP; /* always true; do nothing */ + break; + } + default: { + pc = jumponcond(fs, e, 0); /* jump when false */ + break; + } + } + luaK_concat(fs, &e->f, pc); /* insert new jump in false list */ + luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */ + e->t = NO_JUMP; +} + + +/* +** Emit code to go through if 'e' is false, jump otherwise. +*/ +void luaK_goiffalse (FuncState *fs, expdesc *e) { + int pc; /* pc of new jump */ + luaK_dischargevars(fs, e); + switch (e->k) { + case VJMP: { + pc = e->u.info; /* already jump if true */ + break; + } + case VNIL: case VFALSE: { + pc = NO_JUMP; /* always false; do nothing */ + break; + } + default: { + pc = jumponcond(fs, e, 1); /* jump if true */ + break; + } + } + luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */ + luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */ + e->f = NO_JUMP; +} + + +/* +** Code 'not e', doing constant folding. +*/ +static void codenot (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + switch (e->k) { + case VNIL: case VFALSE: { + e->k = VTRUE; /* true == not nil == not false */ + break; + } + case VK: case VKFLT: case VKINT: case VTRUE: { + e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */ + break; + } + case VJMP: { + negatecondition(fs, e); + break; + } + case VRELOCABLE: + case VNONRELOC: { + discharge2anyreg(fs, e); + freeexp(fs, e); + e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); + e->k = VRELOCABLE; + break; + } + default: lua_assert(0); /* cannot happen */ + } + /* interchange true and false lists */ + { int temp = e->f; e->f = e->t; e->t = temp; } + removevalues(fs, e->f); /* values are useless when negated */ + removevalues(fs, e->t); +} + + +/* +** Create expression 't[k]'. 't' must have its final result already in a +** register or upvalue. +*/ +void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { + lua_assert(!hasjumps(t) && (vkisinreg(t->k) || t->k == VUPVAL)); + t->u.ind.t = t->u.info; /* register or upvalue index */ + t->u.ind.idx = luaK_exp2RK(fs, k); /* R/K index for key */ + t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL : VLOCAL; + t->k = VINDEXED; +} + + +/* +** Return false if folding can raise an error. +** Bitwise operations need operands convertible to integers; division +** operations cannot have 0 as divisor. +*/ +static int validop (int op, TValue *v1, TValue *v2) { + switch (op) { + case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: + case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */ + lua_Integer i; + return (tointeger(v1, &i) && tointeger(v2, &i)); + } + case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */ + return (nvalue(v2) != 0); + default: return 1; /* everything else is valid */ + } +} + + +/* +** Try to "constant-fold" an operation; return 1 iff successful. +** (In this case, 'e1' has the final result.) +*/ +static int constfolding (FuncState *fs, int op, expdesc *e1, + const expdesc *e2) { + TValue v1, v2, res; + if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2)) + return 0; /* non-numeric operands or not safe to fold */ + luaO_arith(fs->ls->L, op, &v1, &v2, &res); /* does operation */ + if (ttisinteger(&res)) { + e1->k = VKINT; + e1->u.ival = ivalue(&res); + } + else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */ + lua_Number n = fltvalue(&res); + if (luai_numisnan(n) || n == 0) + return 0; + e1->k = VKFLT; + e1->u.nval = n; + } + return 1; +} + + +/* +** Emit code for unary expressions that "produce values" +** (everything but 'not'). +** Expression to produce final result will be encoded in 'e'. +*/ +static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) { + int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */ + freeexp(fs, e); + e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */ + e->k = VRELOCABLE; /* all those operations are relocatable */ + luaK_addlineinfo(fs, fs->pc - 1, line); +} + + +/* +** Emit code for binary expressions that "produce values" +** (everything but logical operators 'and'/'or' and comparison +** operators). +** Expression to produce final result will be encoded in 'e1'. +** Because 'luaK_exp2RK' can free registers, its calls must be +** in "stack order" (that is, first on 'e2', which may have more +** recent registers to be released). +*/ +static void codebinexpval (FuncState *fs, OpCode op, + expdesc *e1, expdesc *e2, int line) { + int rk2 = luaK_exp2RK(fs, e2); /* both operands are "RK" */ + int rk1 = luaK_exp2RK(fs, e1); + freeexps(fs, e1, e2); + e1->u.info = luaK_codeABC(fs, op, 0, rk1, rk2); /* generate opcode */ + e1->k = VRELOCABLE; /* all those operations are relocatable */ + luaK_addlineinfo(fs, fs->pc -1, line); +} + + +/* +** Emit code for comparisons. +** 'e1' was already put in R/K form by 'luaK_infix'. +*/ +static void codecomp (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { + int rk1 = (e1->k == VK) ? RKASK(e1->u.info) + : check_exp(e1->k == VNONRELOC, e1->u.info); + int rk2 = luaK_exp2RK(fs, e2); + freeexps(fs, e1, e2); + switch (opr) { + case OPR_NE: { /* '(a ~= b)' ==> 'not (a == b)' */ + e1->u.info = condjump(fs, OP_EQ, 0, rk1, rk2); + break; + } + case OPR_GT: case OPR_GE: { + /* '(a > b)' ==> '(b < a)'; '(a >= b)' ==> '(b <= a)' */ + OpCode op = cast(OpCode, (opr - OPR_NE) + OP_EQ); + e1->u.info = condjump(fs, op, 1, rk2, rk1); /* invert operands */ + break; + } + default: { /* '==', '<', '<=' use their own opcodes */ + OpCode op = cast(OpCode, (opr - OPR_EQ) + OP_EQ); + e1->u.info = condjump(fs, op, 1, rk1, rk2); + break; + } + } + e1->k = VJMP; +} + + +/* +** Aplly prefix operation 'op' to expression 'e'. +*/ +void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) { + static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP}; + switch (op) { + case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */ + if (constfolding(fs, op + LUA_OPUNM, e, &ef)) + break; + /* FALLTHROUGH */ + case OPR_LEN: + codeunexpval(fs, cast(OpCode, op + OP_UNM), e, line); + break; + case OPR_NOT: codenot(fs, e); break; + default: lua_assert(0); + } +} + + +/* +** Process 1st operand 'v' of binary operation 'op' before reading +** 2nd operand. +*/ +void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { + switch (op) { + case OPR_AND: { + luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */ + break; + } + case OPR_OR: { + luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */ + break; + } + case OPR_CONCAT: { + luaK_exp2nextreg(fs, v); /* operand must be on the 'stack' */ + break; + } + case OPR_ADD: case OPR_SUB: + case OPR_MUL: case OPR_DIV: case OPR_IDIV: + case OPR_MOD: case OPR_POW: + case OPR_BAND: case OPR_BOR: case OPR_BXOR: + case OPR_SHL: case OPR_SHR: { + if (!tonumeral(v, NULL)) + luaK_exp2RK(fs, v); + /* else keep numeral, which may be folded with 2nd operand */ + break; + } + default: { + luaK_exp2RK(fs, v); + break; + } + } +} + + +/* +** Finalize code for binary operation, after reading 2nd operand. +** For '(a .. b .. c)' (which is '(a .. (b .. c))', because +** concatenation is right associative), merge second CONCAT into first +** one. +*/ +void luaK_posfix (FuncState *fs, BinOpr op, + expdesc *e1, expdesc *e2, int line) { + switch (op) { + case OPR_AND: { + lua_assert(e1->t == NO_JUMP); /* list closed by 'luK_infix' */ + luaK_dischargevars(fs, e2); + luaK_concat(fs, &e2->f, e1->f); + *e1 = *e2; + break; + } + case OPR_OR: { + lua_assert(e1->f == NO_JUMP); /* list closed by 'luK_infix' */ + luaK_dischargevars(fs, e2); + luaK_concat(fs, &e2->t, e1->t); + *e1 = *e2; + break; + } + case OPR_CONCAT: { + luaK_exp2val(fs, e2); + if (e2->k == VRELOCABLE && + GET_OPCODE(getinstruction(fs, e2)) == OP_CONCAT) { + lua_assert(e1->u.info == GETARG_B(getinstruction(fs, e2))-1); + freeexp(fs, e1); + SETARG_B(getinstruction(fs, e2), e1->u.info); + e1->k = VRELOCABLE; e1->u.info = e2->u.info; + } + else { + luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */ + codebinexpval(fs, OP_CONCAT, e1, e2, line); + } + break; + } + case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: + case OPR_IDIV: case OPR_MOD: case OPR_POW: + case OPR_BAND: case OPR_BOR: case OPR_BXOR: + case OPR_SHL: case OPR_SHR: { + if (!constfolding(fs, op + LUA_OPADD, e1, e2)) + codebinexpval(fs, cast(OpCode, op + OP_ADD), e1, e2, line); + break; + } + case OPR_EQ: case OPR_LT: case OPR_LE: + case OPR_NE: case OPR_GT: case OPR_GE: { + codecomp(fs, op, e1, e2); + break; + } + default: lua_assert(0); + } +} + + +/* +** Emit a SETLIST instruction. +** 'base' is register that keeps table; +** 'nelems' is #table plus those to be stored now; +** 'tostore' is number of values (in registers 'base + 1',...) to add to +** table (or LUA_MULTRET to add up to stack top). +*/ +void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { + int c = (nelems - 1) / LFIELDS_PER_FLUSH + 1; + int b = (tostore == LUA_MULTRET) ? 0 : tostore; + lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH); + if (c <= MAXARG_C) + luaK_codeABC(fs, OP_SETLIST, base, b, c); + else if (c <= MAXARG_Ax) { + luaK_codeABC(fs, OP_SETLIST, base, b, 0); + codeextraarg(fs, c); + } + else + luaX_syntaxerror(fs->ls, "constructor too long"); + fs->freereg = base + 1; /* free registers with list values */ +} + +/* +** Packed line info support. +** +** This encoding scheme is designed to replace the standard int[PC count] vector +** by a packed byte array which takes just over 1 byte per non-blank Lua line. +** This packing scheme still allows line information to be recovered but with a +** storage scheme that is typically an order denser than standard info coding. +** This comprises a repeat of (optional) line delta (LD) + VM instruction count +** (IC) for that line starting from a base line number of zero. LDs are optional +** because a LD of +1 is assumed as default and an LD:1 is always omitted. +** +** ICs are stored as a single byte with the high bit set to zero. Sequences +** longer than 127 instructions are encoded using a multi byte sequence using 0 +** LDs, e.g. IC:127 LD:0 IC:23 for a line generating 150 VM instructions. +** +** LDs are have to be signed because the code generator can emit instructions +** out of line sequence. LD are in little-endian ones-compliment (binary) format +** 1snnnnnnn [1nnnnnnn]* and are delimited by the following IC. Since -0 +** represents 1 and 1 is always omitted positive values are offset by 2. This +** means that a single byte is used to encode line deltas in the range -63..65; +** 2 bytes used to encode line deltas in the range -8191..8193, etc.. +** +** This approach has no arbitrary limits, in that it can accommodate any LD or IC. +** In practice, most LDs are omitted and hence each LD IC pair is represented by a +** single IC byte. Also note that the code 0x00 is reserved in this scheme, and +** is used to terminate the vector. +** +** Generation of the line info is done serially within the Proto lineinfo array, +** either adding a line reference for the next instruction or replacing the line +** reference for the last instruction. This also simplifies proper CG of lineinfo +** resources if a compile error is thrown as GC cleanup is of the Proto hierarchy. +*/ +#define LD_BN 7 +#define LD_MARKER (1<f; + int lastpc = fs->lastpc, lastline = fs->lastline; + lu_byte *p = f->lineinfo + fs->sizelineinfo - 1; + if (pc == lastpc) { + if (line == lastline) /* same line and pc is a no-op so return */ + return; + /* if the line is different then undo the last addline info. */ + /* in this case the last byte will always be an IC byte */ + if (*p > 1) { /* decrement the IC if a multi-instruction line */ + (*p)--; + } else { /* The last two bytes were LD:N IC:1 */ + int delta; + p--; /* drop the IC:1 byte */ + if (*p & LD_MARKER) { /* an LD sequence is present */ + delta = 0; + while (p[-1] & LD_MARKER) + delta = (delta << LD_BN) + LD_BITS(7,*p--); + delta = LD_BITS(6,*p); + delta = (*p-- & (1<<(LD_BN-1))) ? -delta : delta + 2; + } else { /* LD sequence missing so default to 1 */ + delta = 1; + } + lastline-= delta; + } + fs->sizelineinfo = p - f->lineinfo + 1; + lastpc--; + } + /* on this path pc follows lastpc and the last lineinfo entry is an IC */ + lua_assert(pc == lastpc+1 && (line != lastline || !(*p & LD_MARKER))); + + if (line == lastline && *p < 127) { + /* the most frequent case is another instruction for the same line */ + (*p)++; /* just bump the last IC */ + } else { + /* we need to write a new (DL),IC:1 so make sure that we have headroom */ + if (fs->sizelineinfo+4 > f->sizelineinfo) { + f->lineinfo = cast(lu_byte *, luaM_growaux_( + fs->ls->L, f->lineinfo, &f->sizelineinfo, + sizeof(lu_byte), MAX_INT, "line codes")); + p = f->lineinfo + fs->sizelineinfo - 1; /* lineinfo has moved */ + } + if (line == lastline) { /* at max val so emit LD:0 IC:1 */ + lua_assert(*p == 127); + *++p = LD_BYTE0(1,0); + } else { /* line break so compute delta and emit LD:n IC:1 */ + int delta = line - lastline; + if (delta != 1) { /* can skip a the default LD:1 */ + int sign = (delta <= 0) ? 1 : 0; + delta = sign ? -delta : delta - 2; + *++p = LD_BYTE0(sign,delta); + delta >>= LD_BN - 1; + while (delta > 0) { + *++p = LD_BYTE(delta); + delta >>= LD_BN; + } + } + } + *++p = 1; + lua_assert(f->sizelineinfo >= fs->sizelineinfo); + fs->sizelineinfo = p + 1 - f->lineinfo; + } + fs->lastline = line; + fs->lastpc = pc; +} diff --git a/components/lua/lua-5.3/lcode.h b/components/lua/lua-5.3/lcode.h new file mode 100644 index 00000000..93c27477 --- /dev/null +++ b/components/lua/lua-5.3/lcode.h @@ -0,0 +1,87 @@ +/* +** $Id: lcode.h,v 1.64.1.1 2017/04/19 17:20:42 roberto Exp $ +** Code generator for Lua +** See Copyright Notice in lua.h +*/ + +#ifndef lcode_h +#define lcode_h + +#include "llex.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" + + +/* +** Marks the end of a patch list. It is an invalid value both as an absolute +** address, and as a list link (would link an element to itself). +*/ +#define NO_JUMP (-1) + + +/* +** grep "ORDER OPR" if you change these enums (ORDER OP) +*/ +typedef enum BinOpr { + OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW, + OPR_DIV, + OPR_IDIV, + OPR_BAND, OPR_BOR, OPR_BXOR, + OPR_SHL, OPR_SHR, + OPR_CONCAT, + OPR_EQ, OPR_LT, OPR_LE, + OPR_NE, OPR_GT, OPR_GE, + OPR_AND, OPR_OR, + OPR_NOBINOPR +} BinOpr; + + +typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; + + +/* get (pointer to) instruction of given 'expdesc' */ +#define getinstruction(fs,e) ((fs)->f->code[(e)->u.info]) + +#define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx) + +#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) + +#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t) + +LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx); +LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C); +LUAI_FUNC int luaK_codek (FuncState *fs, int reg, int k); +LUAI_FUNC void luaK_fixline (FuncState *fs, int line); +LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); +LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); +LUAI_FUNC void luaK_checkstack (FuncState *fs, int n); +LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s); +LUAI_FUNC int luaK_intK (FuncState *fs, lua_Integer n); +LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); +LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e); +LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key); +LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k); +LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_goiffalse (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e); +LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults); +LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e); +LUAI_FUNC int luaK_jump (FuncState *fs); +LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret); +LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); +LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list); +LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level); +LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2); +LUAI_FUNC int luaK_getlabel (FuncState *fs); +LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line); +LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v); +LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, + expdesc *v2, int line); +LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore); +LUAI_FUNC void luaK_addlineinfo (FuncState *fs, int pc, int line); +#endif diff --git a/components/lua/lua-5.3/lcorolib.c b/components/lua/lua-5.3/lcorolib.c new file mode 100644 index 00000000..bb8825c9 --- /dev/null +++ b/components/lua/lua-5.3/lcorolib.c @@ -0,0 +1,159 @@ +/* +** $Id: lcorolib.c,v 1.10.1.1 2017/04/19 17:20:42 roberto Exp $ +** Coroutine Library +** See Copyright Notice in lua.h +*/ + +#define lcorolib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +static lua_State *getco (lua_State *L) { + lua_State *co = lua_tothread(L, 1); + luaL_argcheck(L, co, 1, "thread expected"); + return co; +} + + +static int auxresume (lua_State *L, lua_State *co, int narg) { + int status; + if (!lua_checkstack(co, narg)) { + lua_pushliteral(L, "too many arguments to resume"); + return -1; /* error flag */ + } + if (lua_status(co) == LUA_OK && lua_gettop(co) == 0) { + lua_pushliteral(L, "cannot resume dead coroutine"); + return -1; /* error flag */ + } + lua_xmove(L, co, narg); + status = lua_resume(co, L, narg); + if (status == LUA_OK || status == LUA_YIELD) { + int nres = lua_gettop(co); + if (!lua_checkstack(L, nres + 1)) { + lua_pop(co, nres); /* remove results anyway */ + lua_pushliteral(L, "too many results to resume"); + return -1; /* error flag */ + } + lua_xmove(co, L, nres); /* move yielded values */ + return nres; + } + else { + lua_xmove(co, L, 1); /* move error message */ + return -1; /* error flag */ + } +} + + +static int luaB_coresume (lua_State *L) { + lua_State *co = getco(L); + int r; + r = auxresume(L, co, lua_gettop(L) - 1); + if (r < 0) { + lua_pushboolean(L, 0); + lua_insert(L, -2); + return 2; /* return false + error message */ + } + else { + lua_pushboolean(L, 1); + lua_insert(L, -(r + 1)); + return r + 1; /* return true + 'resume' returns */ + } +} + + +static int luaB_auxwrap (lua_State *L) { + lua_State *co = lua_tothread(L, lua_upvalueindex(1)); + int r = auxresume(L, co, lua_gettop(L)); + if (r < 0) { + if (lua_type(L, -1) == LUA_TSTRING) { /* error object is a string? */ + luaL_where(L, 1); /* add extra info */ + lua_insert(L, -2); + lua_concat(L, 2); + } + return lua_error(L); /* propagate error */ + } + return r; +} + + +static int luaB_cocreate (lua_State *L) { + lua_State *NL; + luaL_checktype(L, 1, LUA_TFUNCTION); + NL = lua_newthread(L); + lua_pushvalue(L, 1); /* move function to top */ + lua_xmove(L, NL, 1); /* move function from L to NL */ + return 1; +} + + +static int luaB_cowrap (lua_State *L) { + luaB_cocreate(L); + lua_pushcclosure(L, luaB_auxwrap, 1); + return 1; +} + + +static int luaB_yield (lua_State *L) { + return lua_yield(L, lua_gettop(L)); +} + + +static int luaB_costatus (lua_State *L) { + lua_State *co = getco(L); + if (L == co) lua_pushliteral(L, "running"); + else { + switch (lua_status(co)) { + case LUA_YIELD: + lua_pushliteral(L, "suspended"); + break; + case LUA_OK: { + lua_Debug ar; + if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */ + lua_pushliteral(L, "normal"); /* it is running */ + else if (lua_gettop(co) == 0) + lua_pushliteral(L, "dead"); + else + lua_pushliteral(L, "suspended"); /* initial state */ + break; + } + default: /* some error occurred */ + lua_pushliteral(L, "dead"); + break; + } + } + return 1; +} + + +static int luaB_yieldable (lua_State *L) { + lua_pushboolean(L, lua_isyieldable(L)); + return 1; +} + + +static int luaB_corunning (lua_State *L) { + int ismain = lua_pushthread(L); + lua_pushboolean(L, ismain); + return 2; +} + +LROT_BEGIN(co_funcs, NULL, 0) + LROT_FUNCENTRY( create, luaB_cocreate ) + LROT_FUNCENTRY( resume, luaB_coresume ) + LROT_FUNCENTRY( running, luaB_corunning ) + LROT_FUNCENTRY( status, luaB_costatus ) + LROT_FUNCENTRY( wrap, luaB_cowrap ) + LROT_FUNCENTRY( yield, luaB_yield ) + LROT_FUNCENTRY( isyieldable, luaB_yieldable) +LROT_END(co_funcs, NULL, 0) + diff --git a/components/lua/lua-5.3/lctype.c b/components/lua/lua-5.3/lctype.c new file mode 100644 index 00000000..f8ad7a2e --- /dev/null +++ b/components/lua/lua-5.3/lctype.c @@ -0,0 +1,55 @@ +/* +** $Id: lctype.c,v 1.12.1.1 2017/04/19 17:20:42 roberto Exp $ +** 'ctype' functions for Lua +** See Copyright Notice in lua.h +*/ + +#define lctype_c +#define LUA_CORE + +#include "lprefix.h" + + +#include "lctype.h" + +#if !LUA_USE_CTYPE /* { */ + +#include + +LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = { + 0x00, /* EOZ */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */ + 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */ + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */ + 0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */ + 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05, + 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */ + 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 9. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; + +#endif /* } */ diff --git a/components/lua/lua-5.3/lctype.h b/components/lua/lua-5.3/lctype.h new file mode 100644 index 00000000..b09b21a3 --- /dev/null +++ b/components/lua/lua-5.3/lctype.h @@ -0,0 +1,95 @@ +/* +** $Id: lctype.h,v 1.12.1.1 2013/04/12 18:48:47 roberto Exp $ +** 'ctype' functions for Lua +** See Copyright Notice in lua.h +*/ + +#ifndef lctype_h +#define lctype_h + +#include "lua.h" + + +/* +** WARNING: the functions defined here do not necessarily correspond +** to the similar functions in the standard C ctype.h. They are +** optimized for the specific needs of Lua +*/ + +#if !defined(LUA_USE_CTYPE) + +#if 'A' == 65 && '0' == 48 +/* ASCII case: can use its own tables; faster and fixed */ +#define LUA_USE_CTYPE 0 +#else +/* must use standard C ctype */ +#define LUA_USE_CTYPE 1 +#endif + +#endif + + +#if !LUA_USE_CTYPE /* { */ + +#include + +#include "llimits.h" + + +#define ALPHABIT 0 +#define DIGITBIT 1 +#define PRINTBIT 2 +#define SPACEBIT 3 +#define XDIGITBIT 4 + + +#define MASK(B) (1 << (B)) + + +/* +** add 1 to char to allow index -1 (EOZ) +*/ +#define testprop(c,p) (luai_ctype_[(c)+1] & (p)) + +/* +** 'lalpha' (Lua alphabetic) and 'lalnum' (Lua alphanumeric) both include '_' +*/ +#define lislalpha(c) testprop(c, MASK(ALPHABIT)) +#define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT))) +#define lisdigit(c) testprop(c, MASK(DIGITBIT)) +#define lisspace(c) testprop(c, MASK(SPACEBIT)) +#define lisprint(c) testprop(c, MASK(PRINTBIT)) +#define lisxdigit(c) testprop(c, MASK(XDIGITBIT)) + +/* +** this 'ltolower' only works for alphabetic characters +*/ +#define ltolower(c) ((c) | ('A' ^ 'a')) + + +/* two more entries for 0 and -1 (EOZ) */ +LUAI_DDEC const lu_byte luai_ctype_[UCHAR_MAX + 2]; + + +#else /* }{ */ + +/* +** use standard C ctypes +*/ + +#include + + +#define lislalpha(c) (isalpha(c) || (c) == '_') +#define lislalnum(c) (isalnum(c) || (c) == '_') +#define lisdigit(c) (isdigit(c)) +#define lisspace(c) (isspace(c)) +#define lisprint(c) (isprint(c)) +#define lisxdigit(c) (isxdigit(c)) + +#define ltolower(c) (tolower(c)) + +#endif /* } */ + +#endif + diff --git a/components/lua/lua-5.3/ldblib.c b/components/lua/lua-5.3/ldblib.c new file mode 100644 index 00000000..5be2ece2 --- /dev/null +++ b/components/lua/lua-5.3/ldblib.c @@ -0,0 +1,470 @@ +/* +** $Id: ldblib.c,v 1.151.1.1 2017/04/19 17:20:42 roberto Exp $ +** Interface from Lua to its debug API +** See Copyright Notice in lua.h +*/ + +#define ldblib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* +** The hook table at registry[&HOOKKEY] maps threads to their current +** hook function. (We only need the unique address of 'HOOKKEY'.) +*/ +static const int HOOKKEY = 0; + + +/* +** If L1 != L, L1 can be in any state, and therefore there are no +** guarantees about its stack space; any push in L1 must be +** checked. +*/ +static void checkstack (lua_State *L, lua_State *L1, int n) { + if (L != L1 && !lua_checkstack(L1, n)) + luaL_error(L, "stack overflow"); +} + + +static int db_getregistry (lua_State *L) { + lua_pushvalue(L, LUA_REGISTRYINDEX); + return 1; +} + + +static int db_getstrings (lua_State *L) { + static const char *const opts[] = {"RAM","ROM",NULL}; + int opt = luaL_checkoption(L, 1, "RAM", opts); + if (lua_pushstringsarray(L, opt)) { + if(lua_getglobal(L, "table") == LUA_TTABLE) { + lua_getfield(L, -1, "sort"); /* look up table.sort function */ + lua_pushvalue(L, -3); /* dup the strings_table to ToS */ + lua_call(L, 1, 0); /* table.sort(strings_table) */ + lua_pop(L, 1); /* dump the table entry */ + } + } + return 1; +} + +static int db_getmetatable (lua_State *L) { + luaL_checkany(L, 1); + if (!lua_getmetatable(L, 1)) { + lua_pushnil(L); /* no metatable */ + } + return 1; +} + + +static int db_setmetatable (lua_State *L) { + int t = lua_type(L, 2); + luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, + "nil or table expected"); + lua_settop(L, 2); + lua_setmetatable(L, 1); + return 1; /* return 1st argument */ +} + + +static int db_getuservalue (lua_State *L) { + if (lua_type(L, 1) != LUA_TUSERDATA) + lua_pushnil(L); + else + lua_getuservalue(L, 1); + return 1; +} + + +static int db_setuservalue (lua_State *L) { + luaL_checktype(L, 1, LUA_TUSERDATA); + luaL_checkany(L, 2); + lua_settop(L, 2); + lua_setuservalue(L, 1); + return 1; +} + + +/* +** Auxiliary function used by several library functions: check for +** an optional thread as function's first argument and set 'arg' with +** 1 if this argument is present (so that functions can skip it to +** access their other arguments) +*/ +static lua_State *getthread (lua_State *L, int *arg) { + if (lua_isthread(L, 1)) { + *arg = 1; + return lua_tothread(L, 1); + } + else { + *arg = 0; + return L; /* function will operate over current thread */ + } +} + + +/* +** Variations of 'lua_settable', used by 'db_getinfo' to put results +** from 'lua_getinfo' into result table. Key is always a string; +** value can be a string, an int, or a boolean. +*/ +static void settabss (lua_State *L, const char *k, const char *v) { + lua_pushstring(L, v); + lua_setfield(L, -2, k); +} + +static void settabsi (lua_State *L, const char *k, int v) { + lua_pushinteger(L, v); + lua_setfield(L, -2, k); +} + +static void settabsb (lua_State *L, const char *k, int v) { + lua_pushboolean(L, v); + lua_setfield(L, -2, k); +} + + +/* +** In function 'db_getinfo', the call to 'lua_getinfo' may push +** results on the stack; later it creates the result table to put +** these objects. Function 'treatstackoption' puts the result from +** 'lua_getinfo' on top of the result table so that it can call +** 'lua_setfield'. +*/ +static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) { + if (L == L1) + lua_rotate(L, -2, 1); /* exchange object and table */ + else + lua_xmove(L1, L, 1); /* move object to the "main" stack */ + lua_setfield(L, -2, fname); /* put object into table */ +} + + +/* +** Calls 'lua_getinfo' and collects all results in a new table. +** L1 needs stack space for an optional input (function) plus +** two optional outputs (function and line table) from function +** 'lua_getinfo'. +*/ +static int db_getinfo (lua_State *L) { + lua_Debug ar; + int arg; + lua_State *L1 = getthread(L, &arg); + const char *options = luaL_optstring(L, arg+2, "flnStu"); + checkstack(L, L1, 3); + if (lua_isfunction(L, arg + 1)) { /* info about a function? */ + options = lua_pushfstring(L, ">%s", options); /* add '>' to 'options' */ + lua_pushvalue(L, arg + 1); /* move function to 'L1' stack */ + lua_xmove(L, L1, 1); + } + else { /* stack level */ + if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) { + lua_pushnil(L); /* level out of range */ + return 1; + } + } + if (!lua_getinfo(L1, options, &ar)) + return luaL_argerror(L, arg+2, "invalid option"); + lua_newtable(L); /* table to collect results */ + if (strchr(options, 'S')) { + settabss(L, "source", ar.source); + settabss(L, "short_src", ar.short_src); + settabsi(L, "linedefined", ar.linedefined); + settabsi(L, "lastlinedefined", ar.lastlinedefined); + settabss(L, "what", ar.what); + } + if (strchr(options, 'l')) + settabsi(L, "currentline", ar.currentline); + if (strchr(options, 'u')) { + settabsi(L, "nups", ar.nups); + settabsi(L, "nparams", ar.nparams); + settabsb(L, "isvararg", ar.isvararg); + } + if (strchr(options, 'n')) { + settabss(L, "name", ar.name); + settabss(L, "namewhat", ar.namewhat); + } + if (strchr(options, 't')) + settabsb(L, "istailcall", ar.istailcall); + if (strchr(options, 'L')) + treatstackoption(L, L1, "activelines"); + if (strchr(options, 'f')) + treatstackoption(L, L1, "func"); + return 1; /* return table */ +} + + +static int db_getlocal (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + lua_Debug ar; + const char *name; + int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */ + if (lua_isfunction(L, arg + 1)) { /* function argument? */ + lua_pushvalue(L, arg + 1); /* push function */ + lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */ + return 1; /* return only name (there is no value) */ + } + else { /* stack-level argument */ + int level = (int)luaL_checkinteger(L, arg + 1); + if (!lua_getstack(L1, level, &ar)) /* out of range? */ + return luaL_argerror(L, arg+1, "level out of range"); + checkstack(L, L1, 1); + name = lua_getlocal(L1, &ar, nvar); + if (name) { + lua_xmove(L1, L, 1); /* move local value */ + lua_pushstring(L, name); /* push name */ + lua_rotate(L, -2, 1); /* re-order */ + return 2; + } + else { + lua_pushnil(L); /* no name (nor value) */ + return 1; + } + } +} + + +static int db_setlocal (lua_State *L) { + int arg; + const char *name; + lua_State *L1 = getthread(L, &arg); + lua_Debug ar; + int level = (int)luaL_checkinteger(L, arg + 1); + int nvar = (int)luaL_checkinteger(L, arg + 2); + if (!lua_getstack(L1, level, &ar)) /* out of range? */ + return luaL_argerror(L, arg+1, "level out of range"); + luaL_checkany(L, arg+3); + lua_settop(L, arg+3); + checkstack(L, L1, 1); + lua_xmove(L, L1, 1); + name = lua_setlocal(L1, &ar, nvar); + if (name == NULL) + lua_pop(L1, 1); /* pop value (if not popped by 'lua_setlocal') */ + lua_pushstring(L, name); + return 1; +} + + +/* +** get (if 'get' is true) or set an upvalue from a closure +*/ +static int auxupvalue (lua_State *L, int get) { + const char *name; + int n = (int)luaL_checkinteger(L, 2); /* upvalue index */ + luaL_checktype(L, 1, LUA_TFUNCTION); /* closure */ + name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); + if (name == NULL) return 0; + lua_pushstring(L, name); + lua_insert(L, -(get+1)); /* no-op if get is false */ + return get + 1; +} + + +static int db_getupvalue (lua_State *L) { + return auxupvalue(L, 1); +} + + +static int db_setupvalue (lua_State *L) { + luaL_checkany(L, 3); + return auxupvalue(L, 0); +} + + +/* +** Check whether a given upvalue from a given closure exists and +** returns its index +*/ +static int checkupval (lua_State *L, int argf, int argnup) { + int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */ + luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */ + luaL_argcheck(L, (lua_getupvalue(L, argf, nup) != NULL), argnup, + "invalid upvalue index"); + return nup; +} + + +static int db_upvalueid (lua_State *L) { + int n = checkupval(L, 1, 2); + lua_pushlightuserdata(L, lua_upvalueid(L, 1, n)); + return 1; +} + + +static int db_upvaluejoin (lua_State *L) { + int n1 = checkupval(L, 1, 2); + int n2 = checkupval(L, 3, 4); + luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected"); + luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected"); + lua_upvaluejoin(L, 1, n1, 3, n2); + return 0; +} + + +/* +** Call hook function registered at hook table for the current +** thread (if there is one) +*/ +static void hookf (lua_State *L, lua_Debug *ar) { + static const char *const hooknames[] = + {"call", "return", "line", "count", "tail call"}; + lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY); + lua_pushthread(L); + if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */ + lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */ + if (ar->currentline >= 0) + lua_pushinteger(L, ar->currentline); /* push current line */ + else lua_pushnil(L); + lua_assert(lua_getinfo(L, "lS", ar)); + lua_call(L, 2, 0); /* call hook function */ + } +} + + +/* +** Convert a string mask (for 'sethook') into a bit mask +*/ +static int makemask (const char *smask, int count) { + 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; + return mask; +} + + +/* +** Convert a bit mask (for 'gethook') into a string mask +*/ +static char *unmakemask (int mask, char *smask) { + int i = 0; + if (mask & LUA_MASKCALL) smask[i++] = 'c'; + if (mask & LUA_MASKRET) smask[i++] = 'r'; + if (mask & LUA_MASKLINE) smask[i++] = 'l'; + smask[i] = '\0'; + return smask; +} + + +static int db_sethook (lua_State *L) { + int arg, mask, count; + lua_Hook func; + lua_State *L1 = getthread(L, &arg); + if (lua_isnoneornil(L, arg+1)) { /* no hook? */ + lua_settop(L, arg+1); + func = NULL; mask = 0; count = 0; /* turn off hooks */ + } + else { + const char *smask = luaL_checkstring(L, arg+2); + luaL_checktype(L, arg+1, LUA_TFUNCTION); + count = (int)luaL_optinteger(L, arg + 3, 0); + func = hookf; mask = makemask(smask, count); + } + if (lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY) == LUA_TNIL) { + lua_createtable(L, 0, 2); /* create a hook table */ + lua_pushvalue(L, -1); + lua_rawsetp(L, LUA_REGISTRYINDEX, &HOOKKEY); /* set it in position */ + lua_pushstring(L, "k"); + lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */ + lua_pushvalue(L, -1); + lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */ + } + checkstack(L, L1, 1); + lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */ + lua_pushvalue(L, arg + 1); /* value (hook function) */ + lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */ + lua_sethook(L1, func, mask, count); + return 0; +} + + +static int db_gethook (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + char buff[5]; + int mask = lua_gethookmask(L1); + lua_Hook hook = lua_gethook(L1); + if (hook == NULL) /* no hook? */ + lua_pushnil(L); + else if (hook != hookf) /* external hook? */ + lua_pushliteral(L, "external hook"); + else { /* hook table must exist */ + lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY); + checkstack(L, L1, 1); + lua_pushthread(L1); lua_xmove(L1, L, 1); + lua_rawget(L, -2); /* 1st result = hooktable[L1] */ + lua_remove(L, -2); /* remove hook table */ + } + lua_pushstring(L, unmakemask(mask, buff)); /* 2nd result = mask */ + lua_pushinteger(L, lua_gethookcount(L1)); /* 3rd result = count */ + return 3; +} + +#ifdef LUA_USE_HOST +static int db_debug (lua_State *L) { + for (;;) { + char buffer[250]; + lua_writestringerror("%s", "lua_debug> "); + if (fgets(buffer, sizeof(buffer), stdin) == 0 || + strcmp(buffer, "cont\n") == 0) + return 0; + if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || + lua_pcall(L, 0, 0, 0)) + lua_writestringerror("%s\n", lua_tostring(L, -1)); + lua_settop(L, 0); /* remove eventual returns */ + } +} +#endif + +static int db_traceback (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + const char *msg = lua_tostring(L, arg + 1); + if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */ + lua_pushvalue(L, arg + 1); /* return it untouched */ + else { + int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0); + luaL_traceback(L, L1, msg, level); + } + return 1; +} + +LROT_BEGIN(dblib, NULL, 0) +#ifdef LUA_USE_HOST + LROT_FUNCENTRY( debug, db_debug ) +#endif + LROT_FUNCENTRY( getuservalue, db_getuservalue ) + LROT_FUNCENTRY( gethook, db_gethook ) + LROT_FUNCENTRY( getinfo, db_getinfo ) + LROT_FUNCENTRY( getlocal, db_getlocal ) + LROT_FUNCENTRY( getregistry, db_getregistry ) + LROT_FUNCENTRY( getstrings, db_getstrings ) + LROT_FUNCENTRY( getmetatable, db_getmetatable ) + LROT_FUNCENTRY( getupvalue, db_getupvalue ) + LROT_FUNCENTRY( upvaluejoin, db_upvaluejoin ) + LROT_FUNCENTRY( upvalueid, db_upvalueid ) + LROT_FUNCENTRY( setuservalue, db_setuservalue ) + LROT_FUNCENTRY( sethook, db_sethook ) + LROT_FUNCENTRY( setlocal, db_setlocal ) + LROT_FUNCENTRY( setmetatable, db_setmetatable ) + LROT_FUNCENTRY( setupvalue, db_setupvalue ) + LROT_FUNCENTRY( traceback, db_traceback ) +LROT_END(dblib, NULL, 0) + +LUAMOD_API int luaopen_debug (lua_State *L) { + (void)L; + return 0; +} + diff --git a/components/lua/lua-5.3/ldebug.c b/components/lua/lua-5.3/ldebug.c new file mode 100644 index 00000000..7f02f78c --- /dev/null +++ b/components/lua/lua-5.3/ldebug.c @@ -0,0 +1,754 @@ +/* +** $Id: ldebug.c,v 2.121.1.2 2017/07/10 17:21:50 roberto Exp $ +** Debug Interface +** See Copyright Notice in lua.h +*/ + +#define ldebug_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lapi.h" +#include "lcode.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lvm.h" + + + +#define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_TCCL) + + +/* Active Lua function (given call info) */ +#define ci_func(ci) (clLvalue((ci)->func)) + +static const char *funcnamefromcode (lua_State *L, CallInfo *ci, + const char **name); + + +static int currentpc (CallInfo *ci) { + lua_assert(isLua(ci)); + return pcRel(ci->u.l.savedpc, ci_func(ci)->p); +} + + +static int currentline (CallInfo *ci) { + return getfuncline(ci_func(ci)->p, currentpc(ci)); +} + + +/* +** If function yielded, its 'func' can be in the 'extra' field. The +** next function restores 'func' to its correct value for debugging +** purposes. (It exchanges 'func' and 'extra'; so, when called again, +** after debugging, it also "re-restores" ** 'func' to its altered value. +*/ +static void swapextra (lua_State *L) { + if (L->status == LUA_YIELD) { + CallInfo *ci = L->ci; /* get function that yielded */ + StkId temp = ci->func; /* exchange its 'func' and 'extra' values */ + ci->func = restorestack(L, ci->extra); + ci->extra = savestack(L, temp); + } +} + + +/* +** This function can be called asynchronously (e.g. during a signal). +** Fields 'oldpc', 'basehookcount', and 'hookcount' (set by +** 'resethookcount') are for debug only, and it is no problem if they +** get arbitrary values (causes at most one wrong hook call). 'hookmask' +** is an atomic value. We assume that pointers are atomic too (e.g., gcc +** ensures that for all platforms where it runs). Moreover, 'hook' is +** always checked before being called (see 'luaD_hook'). +*/ +LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { + if (func == NULL || mask == 0) { /* turn off hooks? */ + mask = 0; + func = NULL; + } + if (isLua(L->ci)) + L->oldpc = L->ci->u.l.savedpc; + L->hook = func; + L->basehookcount = count; + resethookcount(L); + L->hookmask = cast_byte(mask); +} + + +LUA_API lua_Hook lua_gethook (lua_State *L) { + return L->hook; +} + + +LUA_API int lua_gethookmask (lua_State *L) { + return L->hookmask; +} + + +LUA_API int lua_gethookcount (lua_State *L) { + return L->basehookcount; +} + + +LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { + int status; + CallInfo *ci; + if (level < 0) return 0; /* invalid (negative) level */ + lua_lock(L); + for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous) + level--; + if (level == 0 && ci != &L->base_ci) { /* level found? */ + status = 1; + ar->i_ci = ci; + } + else status = 0; /* no such level */ + lua_unlock(L); + return status; +} + + +static const char *upvalname (Proto *p, int uv) { + TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name); + if (s == NULL) return "?"; + else return getstr(s); +} + + +static const char *findvararg (CallInfo *ci, int n, StkId *pos) { + int nparams = getnumparams(clLvalue(ci->func)->p); + if (n >= cast_int(ci->u.l.base - ci->func) - nparams) + return NULL; /* no such vararg */ + else { + *pos = ci->func + nparams + n; + return "(*vararg)"; /* generic name for any vararg */ + } +} + + +static const char *findlocal (lua_State *L, CallInfo *ci, int n, + StkId *pos) { + const char *name = NULL; + StkId base; + if (isLua(ci)) { + if (n < 0) /* access to vararg values? */ + return findvararg(ci, -n, pos); + else { + base = ci->u.l.base; + name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci)); + } + } + else + base = ci->func + 1; + if (name == NULL) { /* no 'standard' name? */ + StkId limit = (ci == L->ci) ? L->top : ci->next->func; + if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */ + name = "(*temporary)"; /* generic name for any valid slot */ + else + return NULL; /* no name */ + } + *pos = base + (n - 1); + return name; +} + + +LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { + const char *name; + lua_lock(L); + swapextra(L); + if (ar == NULL) { /* information about non-active function? */ + if (!isLfunction(L->top - 1)) /* not a Lua function? */ + name = NULL; + else /* consider live variables at function start (parameters) */ + name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0); + } + else { /* active function; get information through 'ar' */ + StkId pos = NULL; /* to avoid warnings */ + name = findlocal(L, ar->i_ci, n, &pos); + if (name) { + setobj2s(L, L->top, pos); + api_incr_top(L); + } + } + swapextra(L); + lua_unlock(L); + return name; +} + + +LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { + StkId pos = NULL; /* to avoid warnings */ + const char *name; + lua_lock(L); + swapextra(L); + name = findlocal(L, ar->i_ci, n, &pos); + if (name) { + setobjs2s(L, pos, L->top - 1); + L->top--; /* pop value */ + } + swapextra(L); + lua_unlock(L); + return name; +} + + +static void funcinfo (lua_Debug *ar, Closure *cl) { + if (noLuaClosure(cl)) { + ar->source = "=[C]"; + ar->linedefined = -1; + ar->lastlinedefined = -1; + ar->what = "C"; + } + else { + Proto *p = cl->l.p; + ar->source = p->source ? getstr(p->source) : "=?"; + ar->linedefined = p->linedefined; + ar->lastlinedefined = p->lastlinedefined; + ar->what = (ar->linedefined == 0) ? "main" : "Lua"; + } + luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); +} + +#define LD_BN 7 +#define LD_MARKER (1<lineinfo); + /* the union is Flash-friendly to fetch the lineinfo in word-aligned chunks */ + union { unsigned u; lu_byte c[sizeof(unsigned)]; } buf; + lu_byte *p; + if (!u) + return -1; + + while (pc < f->sizecode) { + buf.u = *u++; + for (i = 0, p = buf.c; i < sizeof(unsigned); i++, p++) { + if (*p & LD_MARKER) { /* line delta */ + if (shift == 0) { /* if shift == 0 then 1st LD byte */ + sign = (*p & (1<<6)) ? 1 : 0; + delta = LD_BITS(6, *p); + shift = 6; + } else { + delta += LD_BITS(7, *p)<top-2), line, L->top-1); + } else if (pc <= ins_pc && ins_pc < (pc + *p)) { + /* if L is NULL and pc in current line range then return the line */ + return line; + } + pc += *p; + } + } + } + return 0; +} + + +static void collectvalidlines (lua_State *L, Closure *f) { + if (noLuaClosure(f)) { + setnilvalue(L->top); + api_incr_top(L); + } else { + sethvalue(L, L->top, luaH_new(L)); /* ToS = new table to store active lines */ + api_incr_top(L); + if (f->l.p->lineinfo) { + setbvalue(L->top, 1); /* ToS = boolean 'true' to be the value of all indices */ + api_incr_top(L); + luaG_getfuncline(L, f->l.p, 0); /* call with PC=0 to do table collection */ + L->top--; /* dump boolean leaving table as ToS */ + } + } +} + + +static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { + if (ci == NULL) /* no 'ci'? */ + return NULL; /* no info */ + else if (ci->callstatus & CIST_FIN) { /* is this a finalizer? */ + *name = "__gc"; + return "metamethod"; /* report it as such */ + } + /* calling function is a known Lua function? */ + else if (!(ci->callstatus & CIST_TAIL) && isLua(ci->previous)) + return funcnamefromcode(L, ci->previous, name); + else return NULL; /* no way to find a name */ +} + + +static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, + Closure *f, CallInfo *ci) { + int status = 1; + for (; *what; what++) { + switch (*what) { + case 'S': { + funcinfo(ar, f); + break; + } + case 'l': { + ar->currentline = (ci && isLua(ci)) ? currentline(ci) : -1; + break; + } + case 'u': { + ar->nups = (f == NULL) ? 0 : f->c.nupvalues; + if (noLuaClosure(f)) { + ar->isvararg = 1; + ar->nparams = 0; + } + else { + ar->isvararg = getis_vararg(f->l.p); + ar->nparams = getnumparams(f->l.p); + } + break; + } + case 't': { + ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0; + break; + } + case 'n': { + ar->namewhat = getfuncname(L, ci, &ar->name); + if (ar->namewhat == NULL) { + ar->namewhat = ""; /* not found */ + ar->name = NULL; + } + break; + } + case 'L': + case 'f': /* handled by lua_getinfo */ + break; + default: status = 0; /* invalid option */ + } + } + return status; +} + + +LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { + int status; + Closure *cl; + CallInfo *ci; + StkId func; + lua_lock(L); + swapextra(L); + if (*what == '>') { + ci = NULL; + func = L->top - 1; + api_check(L, ttisfunction(func), "function expected"); + what++; /* skip the '>' */ + L->top--; /* pop function */ + } + else { + ci = ar->i_ci; + func = ci->func; + lua_assert(ttisfunction(ci->func)); + } + cl = ttisclosure(func) ? clvalue(func) : NULL; + status = auxgetinfo(L, what, ar, cl, ci); + if (strchr(what, 'f')) { + setobjs2s(L, L->top, func); + api_incr_top(L); + } + swapextra(L); /* correct before option 'L', which can raise a mem. error */ + if (strchr(what, 'L')) + collectvalidlines(L, cl); + lua_unlock(L); + return status; +} + + +/* +** {====================================================== +** Symbolic Execution +** ======================================================= +*/ + +static const char *getobjname (Proto *p, int lastpc, int reg, + const char **name); + + +/* +** find a "name" for the RK value 'c' +*/ +static void kname (Proto *p, int pc, int c, const char **name) { + if (ISK(c)) { /* is 'c' a constant? */ + TValue *kvalue = &p->k[INDEXK(c)]; + if (ttisstring(kvalue)) { /* literal constant? */ + *name = svalue(kvalue); /* it is its own name */ + return; + } + /* else no reasonable name found */ + } + else { /* 'c' is a register */ + const char *what = getobjname(p, pc, c, name); /* search for 'c' */ + if (what && *what == 'c') { /* found a constant name? */ + return; /* 'name' already filled */ + } + /* else no reasonable name found */ + } + *name = "?"; /* no reasonable name found */ +} + + +static int filterpc (int pc, int jmptarget) { + if (pc < jmptarget) /* is code conditional (inside a jump)? */ + return -1; /* cannot know who sets that register */ + else return pc; /* current position sets that register */ +} + + +/* +** try to find last instruction before 'lastpc' that modified register 'reg' +*/ +static int findsetreg (Proto *p, int lastpc, int reg) { + int pc; + int setreg = -1; /* keep last instruction that changed 'reg' */ + int jmptarget = 0; /* any code before this address is conditional */ + for (pc = 0; pc < lastpc; pc++) { + Instruction i = p->code[pc]; + OpCode op = GET_OPCODE(i); + int a = GETARG_A(i); + switch (op) { + case OP_LOADNIL: { + int b = GETARG_B(i); + if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */ + setreg = filterpc(pc, jmptarget); + break; + } + case OP_TFORCALL: { + if (reg >= a + 2) /* affect all regs above its base */ + setreg = filterpc(pc, jmptarget); + break; + } + case OP_CALL: + case OP_TAILCALL: { + if (reg >= a) /* affect all registers above base */ + setreg = filterpc(pc, jmptarget); + break; + } + case OP_JMP: { + int b = GETARG_sBx(i); + int dest = pc + 1 + b; + /* jump is forward and do not skip 'lastpc'? */ + if (pc < dest && dest <= lastpc) { + if (dest > jmptarget) + jmptarget = dest; /* update 'jmptarget' */ + } + break; + } + default: + if (testAMode(op) && reg == a) /* any instruction that set A */ + setreg = filterpc(pc, jmptarget); + break; + } + } + return setreg; +} + + +static const char *getobjname (Proto *p, int lastpc, int reg, + const char **name) { + int pc; + *name = luaF_getlocalname(p, reg + 1, lastpc); + if (*name) /* is a local? */ + return "local"; + /* else try symbolic execution */ + pc = findsetreg(p, lastpc, reg); + if (pc != -1) { /* could find instruction? */ + Instruction i = p->code[pc]; + OpCode op = GET_OPCODE(i); + switch (op) { + case OP_MOVE: { + int b = GETARG_B(i); /* move from 'b' to 'a' */ + if (b < GETARG_A(i)) + return getobjname(p, pc, b, name); /* get name for 'b' */ + break; + } + case OP_GETTABUP: + case OP_GETTABLE: { + int k = GETARG_C(i); /* key index */ + int t = GETARG_B(i); /* table index */ + const char *vn = (op == OP_GETTABLE) /* name of indexed variable */ + ? luaF_getlocalname(p, t + 1, pc) + : upvalname(p, t); + kname(p, pc, k, name); + return (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field"; + } + case OP_GETUPVAL: { + *name = upvalname(p, GETARG_B(i)); + return "upvalue"; + } + case OP_LOADK: + case OP_LOADKX: { + int b = (op == OP_LOADK) ? GETARG_Bx(i) + : GETARG_Ax(p->code[pc + 1]); + if (ttisstring(&p->k[b])) { + *name = svalue(&p->k[b]); + return "constant"; + } + break; + } + case OP_SELF: { + int k = GETARG_C(i); /* key index */ + kname(p, pc, k, name); + return "method"; + } + default: break; /* go through to return NULL */ + } + } + return NULL; /* could not find reasonable name */ +} + + +/* +** Try to find a name for a function based on the code that called it. +** (Only works when function was called by a Lua function.) +** Returns what the name is (e.g., "for iterator", "method", +** "metamethod") and sets '*name' to point to the name. +*/ +static const char *funcnamefromcode (lua_State *L, CallInfo *ci, + const char **name) { + TMS tm = (TMS)0; /* (initial value avoids warnings) */ + Proto *p = ci_func(ci)->p; /* calling function */ + int pc = currentpc(ci); /* calling instruction index */ + Instruction i = p->code[pc]; /* calling instruction */ + if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */ + *name = "?"; + return "hook"; + } + switch (GET_OPCODE(i)) { + case OP_CALL: + case OP_TAILCALL: + return getobjname(p, pc, GETARG_A(i), name); /* get function name */ + case OP_TFORCALL: { /* for iterator */ + *name = "for iterator"; + return "for iterator"; + } + /* other instructions can do calls through metamethods */ + case OP_SELF: case OP_GETTABUP: case OP_GETTABLE: + tm = TM_INDEX; + break; + case OP_SETTABUP: case OP_SETTABLE: + tm = TM_NEWINDEX; + break; + 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: { + int offset = cast_int(GET_OPCODE(i)) - cast_int(OP_ADD); /* ORDER OP */ + tm = cast(TMS, offset + cast_int(TM_ADD)); /* ORDER TM */ + break; + } + case OP_UNM: tm = TM_UNM; break; + case OP_BNOT: tm = TM_BNOT; break; + case OP_LEN: tm = TM_LEN; break; + case OP_CONCAT: tm = TM_CONCAT; break; + case OP_EQ: tm = TM_EQ; break; + case OP_LT: tm = TM_LT; break; + case OP_LE: tm = TM_LE; break; + default: + return NULL; /* cannot find a reasonable name */ + } + *name = getstr(G(L)->tmname[tm]); + return "metamethod"; +} + +/* }====================================================== */ + + + +/* +** The subtraction of two potentially unrelated pointers is +** not ISO C, but it should not crash a program; the subsequent +** checks are ISO C and ensure a correct result. +*/ +static int isinstack (CallInfo *ci, const TValue *o) { + ptrdiff_t i = o - ci->u.l.base; + return (0 <= i && i < (ci->top - ci->u.l.base) && ci->u.l.base + i == o); +} + + +/* +** Checks whether value 'o' came from an upvalue. (That can only happen +** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on +** upvalues.) +*/ +static const char *getupvalname (CallInfo *ci, const TValue *o, + const char **name) { + LClosure *c = ci_func(ci); + int i; + for (i = 0; i < c->nupvalues; i++) { + if (c->upvals[i]->v == o) { + *name = upvalname(c->p, i); + return "upvalue"; + } + } + return NULL; +} + + +static const char *varinfo (lua_State *L, const TValue *o) { + const char *name = NULL; /* to avoid warnings */ + CallInfo *ci = L->ci; + const char *kind = NULL; + if (isLua(ci)) { + kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */ + if (!kind && isinstack(ci, o)) /* no? try a register */ + kind = getobjname(ci_func(ci)->p, currentpc(ci), + cast_int(o - ci->u.l.base), &name); + } + return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : ""; +} + + +l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) { + const char *t = luaT_objtypename(L, o); + const char *info = varinfo(L, o); + luaG_runerror(L, "attempt to %s a %s value%s", op, t, info); +} + + +l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) { + if (ttisstring(p1) || cvt2str(p1)) p1 = p2; + luaG_typeerror(L, p1, "concatenate"); +} + + +l_noret luaG_opinterror (lua_State *L, const TValue *p1, + const TValue *p2, const char *msg) { + lua_Number temp; + if (!tonumber(p1, &temp)) /* first operand is wrong? */ + p2 = p1; /* now second is wrong */ + luaG_typeerror(L, p2, msg); +} + + +/* +** Error when both values are convertible to numbers, but not to integers +*/ +l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) { + lua_Integer temp; + if (!tointeger(p1, &temp)) + p2 = p1; + luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2)); +} + + +l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { + const char *t1 = luaT_objtypename(L, p1); + const char *t2 = luaT_objtypename(L, p2); + if (strcmp(t1, t2) == 0) + luaG_runerror(L, "attempt to compare two %s values", t1); + else + luaG_runerror(L, "attempt to compare %s with %s", t1, t2); +} + + +/* add src:line information to 'msg' */ +const char *luaG_addinfo (lua_State *L, const char *msg, TString *src, + int line) { + char buff[LUA_IDSIZE]; + if (src) + luaO_chunkid(buff, getstr(src), LUA_IDSIZE); + else { /* no source available; use "?" instead */ + buff[0] = '?'; buff[1] = '\0'; + } + return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); +} + + +l_noret luaG_errormsg (lua_State *L) { + if (L->errfunc != 0) { /* is there an error handling function? */ + StkId errfunc = restorestack(L, L->errfunc); + setobjs2s(L, L->top, L->top - 1); /* move argument */ + setobjs2s(L, L->top - 1, errfunc); /* push function */ + L->top++; /* assume EXTRA_STACK */ + luaD_callnoyield(L, L->top - 2, 1); /* call it */ + } + luaD_throw(L, LUA_ERRRUN); +} + + +l_noret luaG_runerror (lua_State *L, const char *fmt, ...) { + CallInfo *ci = L->ci; + const char *msg; + va_list argp; + + luaC_checkGC(L); /* error message uses memory */ + va_start(argp, fmt); + msg = luaO_pushvfstring(L, fmt, argp); /* format message */ + va_end(argp); + if (isLua(ci)) /* if Lua function, add source:line information */ + luaG_addinfo(L, msg, ci_func(ci)->p->source, currentline(ci)); + luaG_errormsg(L); +} + + +void luaG_traceexec (lua_State *L) { + CallInfo *ci = L->ci; + lu_byte mask = L->hookmask; + int counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT)); + if (counthook) + resethookcount(L); /* reset count */ + else if (!(mask & LUA_MASKLINE)) + return; /* no line hook and count != 0; nothing to be done */ + if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */ + ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */ + return; /* do not call hook again (VM yielded, so it did not move) */ + } + if (counthook) + luaD_hook(L, LUA_HOOKCOUNT, -1); /* call count hook */ + if (mask & LUA_MASKLINE) { + Proto *p = ci_func(ci)->p; + int npc = pcRel(ci->u.l.savedpc, p); + int newline = getfuncline(p, npc); + if (npc == 0 || /* call linehook when enter a new function, */ + ci->u.l.savedpc <= L->oldpc || /* when jump back (loop), or when */ + newline != getfuncline(p, pcRel(L->oldpc, p))) /* enter a new line */ + luaD_hook(L, LUA_HOOKLINE, newline); /* call line hook */ + } + L->oldpc = ci->u.l.savedpc; + if (L->status == LUA_YIELD) { /* did hook yield? */ + if (counthook) + L->hookcount = 1; /* undo decrement to zero */ + ci->u.l.savedpc--; /* undo increment (resume will increment it again) */ + ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */ + ci->func = L->top - 1; /* protect stack below results */ + luaD_throw(L, LUA_YIELD); + } +} + diff --git a/components/lua/lua-5.3/ldebug.h b/components/lua/lua-5.3/ldebug.h new file mode 100644 index 00000000..4e4575ae --- /dev/null +++ b/components/lua/lua-5.3/ldebug.h @@ -0,0 +1,39 @@ +/* +** $Id: ldebug.h,v 2.14.1.1 2017/04/19 17:20:42 roberto Exp $ +** Auxiliary functions from Debug Interface module +** See Copyright Notice in lua.h +*/ + +#ifndef ldebug_h +#define ldebug_h + + +#include "lstate.h" + + +#define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1) + +#define getfuncline(f,pc) (luaG_getfuncline(NULL,f,pc)) + +#define resethookcount(L) (L->hookcount = L->basehookcount) + + +LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o, + const char *opname); +LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1, + const TValue *p2); +LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1, + const TValue *p2, + const char *msg); +LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1, + const TValue *p2); +LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1, + const TValue *p2); +LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...); +LUAI_FUNC const char *luaG_addinfo (lua_State *L, const char *msg, + TString *src, int line); +LUAI_FUNC l_noret luaG_errormsg (lua_State *L); +LUAI_FUNC void luaG_traceexec (lua_State *L); +LUAI_FUNC int luaG_getfuncline (lua_State *L, const Proto *f, int ins_pc); + +#endif diff --git a/components/lua/lua-5.3/ldo.c b/components/lua/lua-5.3/ldo.c new file mode 100644 index 00000000..6b75eb1f --- /dev/null +++ b/components/lua/lua-5.3/ldo.c @@ -0,0 +1,806 @@ +/* +** $Id: ldo.c,v 2.157.1.1 2017/04/19 17:20:42 roberto Exp $ +** Stack and Call structure of Lua +** See Copyright Notice in lua.h +*/ + +#define ldo_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lapi.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lundump.h" +#include "lvm.h" +#include "lzio.h" + + + +#define errorstatus(s) ((s) > LUA_YIELD) + + +/* +** {====================================================== +** Error-recovery functions +** ======================================================= +*/ + +/* +** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By +** default, Lua handles errors with exceptions when compiling as +** C++ code, with _longjmp/_setjmp when asked to use them, and with +** longjmp/setjmp otherwise. +*/ +#if !defined(LUAI_THROW) /* { */ + +#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */ + +/* C++ exceptions */ +#define LUAI_THROW(L,c) throw(c) +#define LUAI_TRY(L,c,a) \ + try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; } +#define luai_jmpbuf int /* dummy variable */ + +#elif defined(LUA_USE_POSIX) /* }{ */ + +/* in POSIX, try _longjmp/_setjmp (more efficient) */ +#define LUAI_THROW(L,c) _longjmp((c)->b, 1) +#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } +#define luai_jmpbuf jmp_buf + +#else /* }{ */ + +/* ISO C handling with long jumps */ +#define LUAI_THROW(L,c) longjmp((c)->b, 1) +#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } +#define luai_jmpbuf jmp_buf + +#endif /* } */ + +#endif /* } */ + + + +/* chain list of long jump buffers */ +struct lua_longjmp { + struct lua_longjmp *previous; + luai_jmpbuf b; + volatile int status; /* error code */ +}; + + +static void seterrorobj (lua_State *L, int errcode, StkId oldtop) { + switch (errcode) { + case LUA_ERRMEM: { /* memory error? */ + setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */ + break; + } + case LUA_ERRERR: { + setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); + break; + } + default: { + setobjs2s(L, oldtop, L->top - 1); /* error message on current top */ + break; + } + } + L->top = oldtop + 1; +} + + +l_noret luaD_throw (lua_State *L, int errcode) { + if (L->errorJmp) { /* thread has an error handler? */ + L->errorJmp->status = errcode; /* set status */ + LUAI_THROW(L, L->errorJmp); /* jump to it */ + } + else { /* thread has no error handler */ + global_State *g = G(L); + L->status = cast_byte(errcode); /* mark it as dead */ + if (g->mainthread->errorJmp) { /* main thread has a handler? */ + setobjs2s(L, g->mainthread->top++, L->top - 1); /* copy error obj. */ + luaD_throw(g->mainthread, errcode); /* re-throw in main thread */ + } + else { /* no handler at all; abort */ + if (g->panic) { /* panic function? */ + seterrorobj(L, errcode, L->top); /* assume EXTRA_STACK */ + if (L->ci->top < L->top) + L->ci->top = L->top; /* pushing msg. can break this invariant */ + lua_unlock(L); + g->panic(L); /* call panic function (last chance to jump out) */ + } +#ifdef LUA_USE_ESP8266 + while(1) {}; +#else + abort(); +#endif + } + } +} + + +int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { + unsigned short oldnCcalls = L->nCcalls; + struct lua_longjmp lj; + lj.status = LUA_OK; + lj.previous = L->errorJmp; /* chain new error handler */ + L->errorJmp = &lj; + LUAI_TRY(L, &lj, + (*f)(L, ud); + ); + L->errorJmp = lj.previous; /* restore old error handler */ + L->nCcalls = oldnCcalls; + return lj.status; +} + +/* }====================================================== */ + + +/* +** {================================================================== +** Stack reallocation +** =================================================================== +*/ +static void correctstack (lua_State *L, TValue *oldstack) { + CallInfo *ci; + UpVal *up; + L->top = (L->top - oldstack) + L->stack; + for (up = L->openupval; up != NULL; up = up->u.open.next) + up->v = (up->v - oldstack) + L->stack; + for (ci = L->ci; ci != NULL; ci = ci->previous) { + ci->top = (ci->top - oldstack) + L->stack; + ci->func = (ci->func - oldstack) + L->stack; + if (isLua(ci)) + ci->u.l.base = (ci->u.l.base - oldstack) + L->stack; + } +} + + +/* some space for error handling */ +#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200) + + +void luaD_reallocstack (lua_State *L, int newsize) { + TValue *oldstack = L->stack; + int lim = L->stacksize; + lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE); + lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK); + luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue); + for (; lim < newsize; lim++) + setnilvalue(L->stack + lim); /* erase new segment */ + L->stacksize = newsize; + L->stack_last = L->stack + newsize - EXTRA_STACK; + correctstack(L, oldstack); +} + + +void luaD_growstack (lua_State *L, int n) { + int size = L->stacksize; + if (size > LUAI_MAXSTACK) /* error after extra size? */ + luaD_throw(L, LUA_ERRERR); + else { + int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK; + int newsize = 2 * size; + if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK; + if (newsize < needed) newsize = needed; + if (newsize > LUAI_MAXSTACK) { /* stack overflow? */ + luaD_reallocstack(L, ERRORSTACKSIZE); + luaG_runerror(L, "stack overflow"); + } + else + luaD_reallocstack(L, newsize); + } +} + + +static int stackinuse (lua_State *L) { + CallInfo *ci; + StkId lim = L->top; + for (ci = L->ci; ci != NULL; ci = ci->previous) { + if (lim < ci->top) lim = ci->top; + } + lua_assert(lim <= L->stack_last); + return cast_int(lim - L->stack) + 1; /* part of stack in use */ +} + + +void luaD_shrinkstack (lua_State *L) { + int inuse = stackinuse(L); + int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK; + if (goodsize > LUAI_MAXSTACK) + goodsize = LUAI_MAXSTACK; /* respect stack limit */ + if (L->stacksize > LUAI_MAXSTACK) /* had been handling stack overflow? */ + luaE_freeCI(L); /* free all CIs (list grew because of an error) */ + else + luaE_shrinkCI(L); /* shrink list */ + /* if thread is currently not handling a stack overflow and its + good size is smaller than current size, shrink its stack */ + if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) && + goodsize < L->stacksize) + luaD_reallocstack(L, goodsize); + else /* don't change stack */ + condmovestack(L,{},{}); /* (change only for debugging) */ +} + + +void luaD_inctop (lua_State *L) { + luaD_checkstack(L, 1); + L->top++; +} + +/* }================================================================== */ + + +/* +** Call a hook for the given event. Make sure there is a hook to be +** called. (Both 'L->hook' and 'L->hookmask', which triggers this +** function, can be changed asynchronously by signals.) +*/ +void luaD_hook (lua_State *L, int event, int line) { + lua_Hook hook = L->hook; + if (hook && L->allowhook) { /* make sure there is a hook */ + CallInfo *ci = L->ci; + ptrdiff_t top = savestack(L, L->top); + ptrdiff_t ci_top = savestack(L, ci->top); + lua_Debug ar; + ar.event = event; + ar.currentline = line; + ar.i_ci = ci; + luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ + ci->top = L->top + LUA_MINSTACK; + lua_assert(ci->top <= L->stack_last); + L->allowhook = 0; /* cannot call hooks inside a hook */ + ci->callstatus |= CIST_HOOKED; + lua_unlock(L); + (*hook)(L, &ar); + lua_lock(L); + lua_assert(!L->allowhook); + L->allowhook = 1; + ci->top = restorestack(L, ci_top); + L->top = restorestack(L, top); + ci->callstatus &= ~CIST_HOOKED; + } +} + + +static void callhook (lua_State *L, CallInfo *ci) { + int hook = LUA_HOOKCALL; + ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */ + if (isLua(ci->previous) && + GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) { + ci->callstatus |= CIST_TAIL; + hook = LUA_HOOKTAILCALL; + } + luaD_hook(L, hook, -1); + ci->u.l.savedpc--; /* correct 'pc' */ +} + + +static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { + int i; + int nfixargs = getnumparams(p); + StkId base, fixed; + /* move fixed parameters to final position */ + fixed = L->top - actual; /* first fixed argument */ + base = L->top; /* final position of first argument */ + for (i = 0; i < nfixargs && i < actual; i++) { + setobjs2s(L, L->top++, fixed + i); + setnilvalue(fixed + i); /* erase original copy (for GC) */ + } + for (; i < nfixargs; i++) + setnilvalue(L->top++); /* complete missing arguments */ + return base; +} + + +/* +** Check whether __call metafield of 'func' is a function. If so, put +** it in stack below original 'func' so that 'luaD_precall' can call +** it. Raise an error if __call metafield is not a function. +*/ +static void tryfuncTM (lua_State *L, StkId func) { + const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); + StkId p; + if (!ttisfunction(tm)) + luaG_typeerror(L, func, "call"); + /* Open a hole inside the stack at 'func' */ + for (p = L->top; p > func; p--) + setobjs2s(L, p, p-1); + L->top++; /* slot ensured by caller */ + setobj2s(L, func, tm); /* tag method is the new function to be called */ +} + + +/* +** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'. +** Handle most typical cases (zero results for commands, one result for +** expressions, multiple results for tail calls/single parameters) +** separated. +*/ +static int moveresults (lua_State *L, const TValue *firstResult, StkId res, + int nres, int wanted) { + switch (wanted) { /* handle typical cases separately */ + case 0: break; /* nothing to move */ + case 1: { /* one result needed */ + if (nres == 0) /* no results? */ + firstResult = luaO_nilobject; /* adjust with nil */ + setobjs2s(L, res, firstResult); /* move it to proper place */ + break; + } + case LUA_MULTRET: { + int i; + for (i = 0; i < nres; i++) /* move all results to correct place */ + setobjs2s(L, res + i, firstResult + i); + L->top = res + nres; + return 0; /* wanted == LUA_MULTRET */ + } + default: { + int i; + if (wanted <= nres) { /* enough results? */ + for (i = 0; i < wanted; i++) /* move wanted results to correct place */ + setobjs2s(L, res + i, firstResult + i); + } + else { /* not enough results; use all of them plus nils */ + for (i = 0; i < nres; i++) /* move all results to correct place */ + setobjs2s(L, res + i, firstResult + i); + for (; i < wanted; i++) /* complete wanted number of results */ + setnilvalue(res + i); + } + break; + } + } + L->top = res + wanted; /* top points after the last result */ + return 1; +} + + +/* +** Finishes a function call: calls hook if necessary, removes CallInfo, +** moves current number of results to proper place; returns 0 iff call +** wanted multiple (variable number of) results. +*/ +int luaD_poscall (lua_State *L, CallInfo *ci, StkId firstResult, int nres) { + StkId res; + int wanted = ci->nresults; + if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) { + if (L->hookmask & LUA_MASKRET) { + ptrdiff_t fr = savestack(L, firstResult); /* hook may change stack */ + luaD_hook(L, LUA_HOOKRET, -1); + firstResult = restorestack(L, fr); + } + L->oldpc = ci->previous->u.l.savedpc; /* 'oldpc' for caller function */ + } + res = ci->func; /* res == final position of 1st result */ + L->ci = ci->previous; /* back to caller */ + /* move results to proper place */ + return moveresults(L, firstResult, res, nres, wanted); +} + + + +#define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L))) + + +/* macro to check stack size, preserving 'p' */ +#define checkstackp(L,n,p) \ + luaD_checkstackaux(L, n, \ + ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \ + luaC_checkGC(L), /* stack grow uses memory */ \ + p = restorestack(L, t__)) /* 'pos' part: restore 'p' */ + + +/* +** Prepares a function call: checks the stack, creates a new CallInfo +** entry, fills in the relevant information, calls hook if needed. +** If function is a C function, does the call, too. (Otherwise, leave +** the execution ('luaV_execute') to the caller, to allow stackless +** calls.) Returns true iff function has been executed (C function). +*/ +int luaD_precall (lua_State *L, StkId func, int nresults) { + lua_CFunction f; + CallInfo *ci; + switch (ttype(func)) { + case LUA_TCCL: /* C closure */ + f = clCvalue(func)->f; + goto Cfunc; + case LUA_TLCF: /* light C function */ + f = fvalue(func); + Cfunc: { + int n; /* number of returns */ + checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */ + ci = next_ci(L); /* now 'enter' new function */ + ci->nresults = nresults; + ci->func = func; + ci->top = L->top + LUA_MINSTACK; + lua_assert(ci->top <= L->stack_last); + ci->callstatus = 0; + if (L->hookmask & LUA_MASKCALL) + luaD_hook(L, LUA_HOOKCALL, -1); + lua_unlock(L); + n = (*f)(L); /* do the actual call */ + lua_lock(L); + api_checknelems(L, n); + luaD_poscall(L, ci, L->top - n, n); + return 1; + } + case LUA_TLCL: { /* Lua function: prepare its call */ + StkId base; + Proto *p = clLvalue(func)->p; + int n = cast_int(L->top - func) - 1; /* number of real arguments */ + int fsize = getmaxstacksize(p); /* frame size */ + checkstackp(L, fsize, func); + if (getis_vararg(p)) + base = adjust_varargs(L, p, n); + else { /* non vararg function */ + for (; n < getnumparams(p); n++) + setnilvalue(L->top++); /* complete missing arguments */ + base = func + 1; + } + ci = next_ci(L); /* now 'enter' new function */ + ci->nresults = nresults; + ci->func = func; + ci->u.l.base = base; + L->top = ci->top = base + fsize; + lua_assert(ci->top <= L->stack_last); + ci->u.l.savedpc = p->code; /* starting point */ + ci->callstatus = CIST_LUA; + if (L->hookmask & LUA_MASKCALL) + callhook(L, ci); + return 0; + } + default: { /* not a function */ + checkstackp(L, 1, func); /* ensure space for metamethod */ + tryfuncTM(L, func); /* try to get '__call' metamethod */ + return luaD_precall(L, func, nresults); /* now it must be a function */ + } + } +} + + +/* +** Check appropriate error for stack overflow ("regular" overflow or +** overflow while handling stack overflow). If 'nCalls' is larger than +** LUAI_MAXCCALLS (which means it is handling a "regular" overflow) but +** smaller than 9/8 of LUAI_MAXCCALLS, does not report an error (to +** allow overflow handling to work) +*/ +static void stackerror (lua_State *L) { + if (L->nCcalls == LUAI_MAXCCALLS) + luaG_runerror(L, "C stack overflow"); + else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) + luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ +} + + +/* +** Call a function (C or Lua). The function to be called is at *func. +** The arguments are on the stack, right after the function. +** When returns, all the results are on the stack, starting at the original +** function position. +*/ +void luaD_call (lua_State *L, StkId func, int nResults) { + if (++L->nCcalls >= LUAI_MAXCCALLS) + stackerror(L); + if (!luaD_precall(L, func, nResults)) /* is a Lua function? */ + luaV_execute(L); /* call it */ + L->nCcalls--; +} + + +/* +** Similar to 'luaD_call', but does not allow yields during the call +*/ +void luaD_callnoyield (lua_State *L, StkId func, int nResults) { + L->nny++; + luaD_call(L, func, nResults); + L->nny--; +} + + +/* +** Completes the execution of an interrupted C function, calling its +** continuation function. +*/ +static void finishCcall (lua_State *L, int status) { + CallInfo *ci = L->ci; + int n; + /* must have a continuation and must be able to call it */ + lua_assert(ci->u.c.k != NULL && L->nny == 0); + /* error status can only happen in a protected call */ + lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD); + if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */ + ci->callstatus &= ~CIST_YPCALL; /* continuation is also inside it */ + L->errfunc = ci->u.c.old_errfunc; /* with the same error function */ + } + /* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already + handled */ + adjustresults(L, ci->nresults); + lua_unlock(L); + n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation function */ + lua_lock(L); + api_checknelems(L, n); + luaD_poscall(L, ci, L->top - n, n); /* finish 'luaD_precall' */ +} + + +/* +** Executes "full continuation" (everything in the stack) of a +** previously interrupted coroutine until the stack is empty (or another +** interruption long-jumps out of the loop). If the coroutine is +** recovering from an error, 'ud' points to the error status, which must +** be passed to the first continuation function (otherwise the default +** status is LUA_YIELD). +*/ +static void unroll (lua_State *L, void *ud) { + if (ud != NULL) /* error status? */ + finishCcall(L, *(int *)ud); /* finish 'lua_pcallk' callee */ + while (L->ci != &L->base_ci) { /* something in the stack */ + if (!isLua(L->ci)) /* C function? */ + finishCcall(L, LUA_YIELD); /* complete its execution */ + else { /* Lua function */ + luaV_finishOp(L); /* finish interrupted instruction */ + luaV_execute(L); /* execute down to higher C 'boundary' */ + } + } +} + + +/* +** Try to find a suspended protected call (a "recover point") for the +** given thread. +*/ +static CallInfo *findpcall (lua_State *L) { + CallInfo *ci; + for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */ + if (ci->callstatus & CIST_YPCALL) + return ci; + } + return NULL; /* no pending pcall */ +} + + +/* +** Recovers from an error in a coroutine. Finds a recover point (if +** there is one) and completes the execution of the interrupted +** 'luaD_pcall'. If there is no recover point, returns zero. +*/ +static int recover (lua_State *L, int status) { + StkId oldtop; + CallInfo *ci = findpcall(L); + if (ci == NULL) return 0; /* no recovery point */ + /* "finish" luaD_pcall */ + oldtop = restorestack(L, ci->extra); + luaF_close(L, oldtop); + seterrorobj(L, status, oldtop); + L->ci = ci; + L->allowhook = getoah(ci->callstatus); /* restore original 'allowhook' */ + L->nny = 0; /* should be zero to be yieldable */ + luaD_shrinkstack(L); + L->errfunc = ci->u.c.old_errfunc; + return 1; /* continue running the coroutine */ +} + + +/* +** Signal an error in the call to 'lua_resume', not in the execution +** of the coroutine itself. (Such errors should not be handled by any +** coroutine error handler and should not kill the coroutine.) +*/ +static int resume_error (lua_State *L, const char *msg, int narg) { + L->top -= narg; /* remove args from the stack */ + setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */ + api_incr_top(L); + lua_unlock(L); + return LUA_ERRRUN; +} + + +/* +** Do the work for 'lua_resume' in protected mode. Most of the work +** depends on the status of the coroutine: initial state, suspended +** inside a hook, or regularly suspended (optionally with a continuation +** function), plus erroneous cases: non-suspended coroutine or dead +** coroutine. +*/ +static void resume (lua_State *L, void *ud) { + int n = *(cast(int*, ud)); /* number of arguments */ + StkId firstArg = L->top - n; /* first argument */ + CallInfo *ci = L->ci; + if (L->status == LUA_OK) { /* starting a coroutine? */ + if (!luaD_precall(L, firstArg - 1, LUA_MULTRET)) /* Lua function? */ + luaV_execute(L); /* call it */ + } + else { /* resuming from previous yield */ + lua_assert(L->status == LUA_YIELD); + L->status = LUA_OK; /* mark that it is running (again) */ + ci->func = restorestack(L, ci->extra); + if (isLua(ci)) /* yielded inside a hook? */ + luaV_execute(L); /* just continue running Lua code */ + else { /* 'common' yield */ + if (ci->u.c.k != NULL) { /* does it have a continuation function? */ + lua_unlock(L); + n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */ + lua_lock(L); + api_checknelems(L, n); + firstArg = L->top - n; /* yield results come from continuation */ + } + luaD_poscall(L, ci, firstArg, n); /* finish 'luaD_precall' */ + } + unroll(L, NULL); /* run continuation */ + } +} + + +LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) { + int status; + unsigned short oldnny = L->nny; /* save "number of non-yieldable" calls */ + lua_lock(L); + if (L->status == LUA_OK) { /* may be starting a coroutine */ + if (L->ci != &L->base_ci) /* not in base level? */ + return resume_error(L, "cannot resume non-suspended coroutine", nargs); + } + else if (L->status != LUA_YIELD) + return resume_error(L, "cannot resume dead coroutine", nargs); + L->nCcalls = (from) ? from->nCcalls + 1 : 1; + if (L->nCcalls >= LUAI_MAXCCALLS) + return resume_error(L, "C stack overflow", nargs); + luai_userstateresume(L, nargs); + L->nny = 0; /* allow yields */ + api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs); + status = luaD_rawrunprotected(L, resume, &nargs); + if (status == -1) /* error calling 'lua_resume'? */ + status = LUA_ERRRUN; + else { /* continue running after recoverable errors */ + while (errorstatus(status) && recover(L, status)) { + /* unroll continuation */ + status = luaD_rawrunprotected(L, unroll, &status); + } + if (errorstatus(status)) { /* unrecoverable error? */ + L->status = cast_byte(status); /* mark thread as 'dead' */ + seterrorobj(L, status, L->top); /* push error message */ + L->ci->top = L->top; + } + else lua_assert(status == L->status); /* normal end or yield */ + } + L->nny = oldnny; /* restore 'nny' */ + L->nCcalls--; + lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0)); + lua_unlock(L); + return status; +} + + +LUA_API int lua_isyieldable (lua_State *L) { + return (L->nny == 0); +} + + +LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx, + lua_KFunction k) { + CallInfo *ci = L->ci; + luai_userstateyield(L, nresults); + lua_lock(L); + api_checknelems(L, nresults); + if (L->nny > 0) { + if (L != G(L)->mainthread) + luaG_runerror(L, "attempt to yield across a C-call boundary"); + else + luaG_runerror(L, "attempt to yield from outside a coroutine"); + } + L->status = LUA_YIELD; + ci->extra = savestack(L, ci->func); /* save current 'func' */ + if (isLua(ci)) { /* inside a hook? */ + api_check(L, k == NULL, "hooks cannot continue after yielding"); + } + else { + if ((ci->u.c.k = k) != NULL) /* is there a continuation? */ + ci->u.c.ctx = ctx; /* save context */ + ci->func = L->top - nresults - 1; /* protect stack below results */ + luaD_throw(L, LUA_YIELD); + } + lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */ + lua_unlock(L); + return 0; /* return to 'luaD_hook' */ +} + + +int luaD_pcall (lua_State *L, Pfunc func, void *u, + ptrdiff_t old_top, ptrdiff_t ef) { + int status; + CallInfo *old_ci = L->ci; + lu_byte old_allowhooks = L->allowhook; + unsigned short old_nny = L->nny; + ptrdiff_t old_errfunc = L->errfunc; + L->errfunc = ef; + status = luaD_rawrunprotected(L, func, u); + if (status != LUA_OK) { /* an error occurred? */ + StkId oldtop = restorestack(L, old_top); + luaF_close(L, oldtop); /* close possible pending closures */ + seterrorobj(L, status, oldtop); + L->ci = old_ci; + L->allowhook = old_allowhooks; + L->nny = old_nny; + luaD_shrinkstack(L); + } + L->errfunc = old_errfunc; + return status; +} + + + +/* +** Execute a protected parser. +*/ +struct SParser { /* data to 'f_parser' */ + ZIO *z; + Mbuffer buff; /* dynamic structure used by the scanner */ + Dyndata dyd; /* dynamic structures used by the parser */ + const char *mode; + const char *name; +}; + + +static void checkmode (lua_State *L, const char *mode, const char *x) { + if (mode && strchr(mode, x[0]) == NULL) { + luaO_pushfstring(L, + "attempt to load a %s chunk (mode is '%s')", x, mode); + luaD_throw(L, LUA_ERRSYNTAX); + } +} + + +static void f_parser (lua_State *L, void *ud) { + LClosure *cl; + struct SParser *p = cast(struct SParser *, ud); + int c = zgetc(p->z); /* read first character */ + if (c == LUA_SIGNATURE[0]) { + checkmode(L, p->mode, "binary"); + cl = luaU_undump(L, p->z, p->name); + } + else { + checkmode(L, p->mode, "text"); + cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c); + } + lua_assert(cl->nupvalues == cl->p->sizeupvalues); + luaF_initupvals(L, cl); +} + + +int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, + const char *mode) { + struct SParser p; + int status; + L->nny++; /* cannot yield during parsing */ + p.z = z; p.name = name; p.mode = mode; + p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0; + p.dyd.gt.arr = NULL; p.dyd.gt.size = 0; + p.dyd.label.arr = NULL; p.dyd.label.size = 0; + luaZ_initbuffer(L, &p.buff); + status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); + luaZ_freebuffer(L, &p.buff); + luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size); + luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size); + luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size); + L->nny--; + return status; +} + + diff --git a/components/lua/lua-5.3/ldo.h b/components/lua/lua-5.3/ldo.h new file mode 100644 index 00000000..3b2983a3 --- /dev/null +++ b/components/lua/lua-5.3/ldo.h @@ -0,0 +1,58 @@ +/* +** $Id: ldo.h,v 2.29.1.1 2017/04/19 17:20:42 roberto Exp $ +** Stack and Call structure of Lua +** See Copyright Notice in lua.h +*/ + +#ifndef ldo_h +#define ldo_h + + +#include "lobject.h" +#include "lstate.h" +#include "lzio.h" + + +/* +** Macro to check stack size and grow stack if needed. Parameters +** 'pre'/'pos' allow the macro to preserve a pointer into the +** stack across reallocations, doing the work only when needed. +** 'condmovestack' is used in heavy tests to force a stack reallocation +** at every check. +*/ +#define luaD_checkstackaux(L,n,pre,pos) \ + if (L->stack_last - L->top <= (n)) \ + { pre; luaD_growstack(L, n); pos; } else { condmovestack(L,pre,pos); } + +/* In general, 'pre'/'pos' are empty (nothing to save) */ +#define luaD_checkstack(L,n) luaD_checkstackaux(L,n,(void)0,(void)0) + + + +#define savestack(L,p) ((char *)(p) - (char *)L->stack) +#define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) + + +/* type of protected functions, to be ran by 'runprotected' */ +typedef void (*Pfunc) (lua_State *L, void *ud); + +LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, + const char *mode); +LUAI_FUNC void luaD_hook (lua_State *L, int event, int line); +LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults); +LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); +LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults); +LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, + ptrdiff_t oldtop, ptrdiff_t ef); +LUAI_FUNC int luaD_poscall (lua_State *L, CallInfo *ci, StkId firstResult, + int nres); +LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize); +LUAI_FUNC void luaD_growstack (lua_State *L, int n); +LUAI_FUNC void luaD_shrinkstack (lua_State *L); +LUAI_FUNC void luaD_inctop (lua_State *L); + +LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode); +LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); + +#endif + diff --git a/components/lua/lua-5.3/ldump.c b/components/lua/lua-5.3/ldump.c new file mode 100644 index 00000000..3dfee3c6 --- /dev/null +++ b/components/lua/lua-5.3/ldump.c @@ -0,0 +1,449 @@ +/* +** $Id: ldump.c,v 2.37.1.1 2017/04/19 17:20:42 roberto Exp $ +** save precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#define ldump_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" +#include "lapi.h" +#include "lauxlib.h" +#include "llex.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "lundump.h" + + +typedef struct { + lua_State *L; + lua_Writer writer; + void *data; + int strip; + int status; +#ifdef LUA_USE_HOST + int useStrRefs; + Table *stringIndex; + int sTScnt; + int lTScnt; + int nFixed; +#endif +} DumpState; + +/* +** To ensure that dump files are loadable onto the ESP architectures: +** 1. Integers are in the range -2^31 .. 2^31-1 (sint32_t) +** 2. Floats are the IEEE 4 or 8 byte format, with a 4 byte default. +** +** The file formats are also different to standard because of two add +** additional goals: +** 3. The file must be serially loadable into a programmable flash +** memory through a file-write like API call. +** 4. Compactness of dump files is a key design goal. +*/ + +#define DumpVector(v,n,D) DumpBlock(v,(n)*sizeof((v)[0]),D) + +#define DumpLiteral(s,D) DumpBlock(s, sizeof(s) - sizeof(char), D) + + +static void DumpBlock (const void *b, size_t size, DumpState *D) { + if (D->status == 0 && size > 0) { + lua_unlock(D->L); + D->status = (*D->writer)(D->L, b, size, D->data); + lua_lock(D->L); + } +} + + +#define DumpVar(x,D) DumpVector(&x,1,D) + + +static void DumpByte (lu_byte x, DumpState *D) { + DumpVar(x, D); +} + +/* +** Dump (unsigned) int 0..MAXINT using multibyte encoding (MBE). DumpInt +** is used for context dependent counts and sizes; no type information +** is embedded. +*/ +static void DumpInt (lua_Integer x, DumpState *D) { + lu_byte buf[sizeof(lua_Integer) + 2]; + lu_byte *b = buf + sizeof(buf) - 1; + lua_assert(x>=0); + *b-- = x & 0x7f; x >>= 7; + while(x) { *b-- = 0x80 + (x & 0x7f); x >>= 7; } + b++; + lua_assert (b >= buf); + DumpVector(b, (buf - b) + sizeof(buf), D); +} + + +static void DumpNumber (lua_Number x, DumpState *D) { + DumpByte(LUAU_TNUMFLT, D); + DumpVar(x, D); +} + + +/* +** DumpIntTT is MBE and embeds a type encoding for string length and integers. +** It also handles negative integers by forcing the type to LUAU_TNUMNINT. +** 0TTTNNNN or 1TTTNNNN (1NNNNNNN)* 0NNNNNNN +*/ +static void DumpIntTT (lu_byte tt, lua_Integer y, DumpState *D) { + lua_Integer x = y < 0 ? -(y + 1) : y; + lu_byte buf[sizeof(lua_Integer) + 3]; + lu_byte *b = buf + sizeof(buf) - 1; + *b-- = x & 0x7f; x >>= 7; + while(x) { *b-- = 0x80 + (x & 0x7f); x >>= 7; } + b++; + if (*b & cast(lu_byte, LUAU_TMASK) )/* Need an extra byte for the type bits? */ + *--b = 0x80; + *b |= (y >= 0) ? tt: LUAU_TNUMNINT; + lua_assert (b >= buf); + DumpVector(b, (buf - b) + sizeof(buf), D); +} +#define DumpInteger(i, D) DumpIntTT(LUAU_TNUMPINT, i, D); + + +/* +** Strings are stored in LFS uniquely, any string references use this index. +** The table at D->stringIndex is used to lookup this unique index. +*/ +static void DumpString (const TString *s, DumpState *D) { + if (s == NULL) { + DumpByte(LUAU_TSSTRING + 0, D); + } else { + lu_byte tt = (gettt(s) == LUA_TSHRSTR) ? LUAU_TSSTRING : LUAU_TLSTRING; + size_t l = tsslen(s); + const char *str = getstr(s); +#ifdef LUA_USE_HOST + if (D->useStrRefs) { + const TValue *o = luaH_getstr(D->stringIndex, cast(TString *,s)); + DumpIntTT(tt, ivalue(o), D); + return; + } +#endif + DumpIntTT(tt, l + 1, D); /* include trailing '\0' */ + DumpVector(str, l, D); /* no need to save '\0' */ + } +} + + +static void DumpCode (const Proto *f, DumpState *D) { + DumpInt(f->sizecode, D); + DumpVector(f->code, f->sizecode, D); +} + + +static void DumpFunction(const Proto *f, TString *psource, DumpState *D); + +static void DumpConstants (const Proto *f, DumpState *D) { + int i; + int n = f->sizek; + DumpInt(n, D); + for (i = 0; i < n; i++) { + const TValue *o = &f->k[i]; + switch (ttype(o)) { + case LUA_TNIL: + DumpByte(LUAU_TNIL, D); + break; + case LUA_TBOOLEAN: + DumpByte(LUAU_TBOOLEAN + bvalue(o), D); + break; + case LUA_TNUMFLT : + DumpNumber(fltvalue(o), D); + break; + case LUA_TNUMINT: + DumpInteger(ivalue(o), D); + break; + case LUA_TSHRSTR: + case LUA_TLNGSTR: + DumpString(tsvalue(o), D); + break; + default: + lua_assert(0); + } + } +} + + +static void DumpProtos (const Proto *f, DumpState *D) { + int i; + int n = f->sizep; + DumpInt(n, D); + for (i = 0; i < n; i++) + DumpFunction(f->p[i], f->source, D); +} + + +static void DumpUpvalues (const Proto *f, DumpState *D) { + int i, n = f->sizeupvalues, nostrip = (D->strip == 0); + DumpByte(nostrip, D); + DumpInt(n, D); + for (i = 0; i < n; i++) { + if (nostrip) + DumpString(f->upvalues[i].name, D); + DumpByte(f->upvalues[i].instack, D); + DumpByte(f->upvalues[i].idx, D); + } +} + + +static void DumpDebug (const Proto *f, DumpState *D) { + int i, keepli = (D->strip <= 1), keeplv = (D->strip == 0); + int n = keepli ? f->sizelineinfo : 0; + DumpInt(n, D); + DumpVector(f->lineinfo, n, D); + n = keeplv ? f->sizelocvars : 0; + DumpInt(n, D); + for (i = 0; i < n; i++) { + DumpString(f->locvars[i].varname, D); + DumpInt(f->locvars[i].startpc, D); + DumpInt(f->locvars[i].endpc, D); + } +} + + +static void DumpFunction (const Proto *f, TString *psource, DumpState *D) { + if (f->source == psource) + DumpString(NULL, D); /* same source as its parent */ + else + DumpString(f->source, D); + DumpInt(f->linedefined, D); + DumpInt(f->lastlinedefined, D); + DumpByte(getnumparams(f), D); + DumpByte(getis_vararg(f), D); + DumpByte(getmaxstacksize(f), D); + DumpProtos(f, D); + DumpCode(f, D); + DumpConstants(f, D); + DumpUpvalues(f, D); + DumpDebug(f, D); +} + + +static void DumpHeader (DumpState *D, int format) { + DumpLiteral(LUA_SIGNATURE, D); + DumpByte(LUAC_VERSION, D); + DumpByte(format, D); + DumpLiteral(LUAC_DATA, D); + DumpByte(sizeof(int), D); + DumpByte(sizeof(Instruction), D); + DumpByte(sizeof(lua_Integer), D); + DumpByte(sizeof(lua_Number), D); +/* Note that we multi-byte encoded integers so need to check size_t or endian */ + DumpNumber(LUAC_NUM, D); +} + + +/* +** Dump Lua function as precompiled chunk +*/ +int luaU_dump (lua_State *L, const Proto *f, lua_Writer w, void *data, + int strip) { + DumpState D = {0}; + D.L = L; + D.writer = w; + D.data = data; + D.strip = strip; + DumpHeader(&D, LUAC_FORMAT); + DumpByte(f->sizeupvalues, &D); + DumpFunction(f, NULL, &D); + return D.status; +} + +static int stripdebug (lua_State *L, Proto *f, int level) { + int i, len = 0; + switch (level) { + case 2: + if (f->lineinfo) { + f->lineinfo = luaM_freearray(L, f->lineinfo, f->sizelineinfo); + len += f->sizelineinfo; + } + // fall-through + case 1: + for (i=0; isizeupvalues; i++) + f->upvalues[i].name = NULL; + f->locvars = luaM_freearray(L, f->locvars, f->sizelocvars); + len += f->sizelocvars * sizeof(LocVar); + f->sizelocvars = 0; + } + return len; +} + +/* This is a recursive function so it's stack size has been kept to a minimum! */ +int luaU_stripdebug (lua_State *L, Proto *f, int level, int recv){ + int len = 0, i; + if (recv != 0 && f->sizep != 0) { + for(i=0;isizep;i++) len += luaU_stripdebug(L, f->p[i], level, recv); + } + len += stripdebug (L, f, level); + return len; +} + + + +/*============================================================================** +** +** NodeMCU extensions for LFS support and dumping. Note that to keep lua_lock +** pairing for testing, this dump/unload functionality works within a locked +** window and therefore has to use the core luaH, ..., APIs rather than the +** public Lua and lauxlib APIs. +** +**============================================================================*/ +#ifdef LUA_USE_HOST + +/* +** Add a TS found in the Proto Load to the table at the ToS. Note that this is +** a unified table of {string = index} for both short and long TStrings. +*/ +static void addTS (TString *ts, DumpState *D) { + lua_State *L = D->L; + if (!ts) + return; + if (ttisnil(luaH_getstr(D->stringIndex, ts))) { + TValue k, v, *slot; + gettt(ts)<=LUA_TSHRSTR ? D->sTScnt++ : D->lTScnt++; + setsvalue(L, &k, ts); + setivalue(&v, D->sTScnt + D->lTScnt); + slot = luaH_set(L, D->stringIndex, &k); + setobj2t(L, slot, &v); + luaC_barrierback(L, D->stringIndex, &v); + } +} + + +/* +** Add the fixed TS that are created by the luaX and LuaT initialisation +** and fixed so not collectable. This are always loaded into LFS to save +** RAM and can be implicitly referenced in any Proto. +*/ +static void addFixedStrings (DumpState *D) { + int i; + const char *p; + for (i = 0; (p = luaX_getstr(i, 0))!=NULL; i++) + addTS(luaS_new(D->L, p), D); + addTS(G(D->L)->memerrmsg, D); + addTS(luaS_new(D->L, LUA_ENV), D); + for (i = 0; (p = luaT_getstr(i))!=NULL; i++) + addTS(luaS_new(D->L, p), D); + lua_assert(D->lTScnt == 0); /* all of these fixed strings should be short */ + D->nFixed = D->sTScnt; /* book mark for later skipping */ +} + + +/* +** Dump all LFS strings. If there are 71 fixed and 17 LFS strings, say, in +** the stringIndex, then these fixed and LFS strings are numbered 1..71 and +** 72..88 respectively; this numbering is swapped to 18..88 and 1..17. The +** fixed strings are fixed and can be omitted from the LFS image. +*/ +static void DumpLFSstrings(DumpState *D) { + lua_State *L = D->L; + int n = D->sTScnt + D->lTScnt; + int i, maxlen = 0, nStrings = n - D->nFixed; + Table *revT = luaH_new(L); + + sethvalue(L, L->top++, revT); /* Put on stack to prevent GC */ + luaH_resize(L, revT, n, 0); + luaC_checkGC(L); + /* luaH_next scan of stringIndex table using two top of stack entries */ + setnilvalue(L->top++); + api_incr_top(L); + while (luaH_next(L, D->stringIndex, L->top-2)) { + /* + * Update the value to swap fix and LFS order, then insert (v, k) into + * the reverse index table. Note that luaC_barrier checks not required + * for overwrites and non-collectable values. + */ + int len = tsslen(tsvalue(L->top-2)); + lua_Integer *i = &L->top[-1].value_.i; + *i += *i > D->nFixed ? -D->nFixed : nStrings; /* recalc index and */ + luaH_set(L, D->stringIndex, L->top-2)->value_.i = *i; /* update table value */ + luaH_setint(L, revT, ivalue(L->top-1), L->top-2); /* Add str to reverse T */ + if (len > maxlen) maxlen = len; /* roll up maximum string size */ + } + L->top -= 2; /* discard key and value stack slots */ + DumpInt(maxlen, D); + DumpInt(D->sTScnt, D); + DumpInt(D->lTScnt, D); + DumpInt(nStrings, D); + + for (i = 1; i <= nStrings; i++) { /* dump out non-fixed strings in order */ + const TValue *o = luaH_getint(revT, i); + DumpString(tsvalue(o), D); + } + L->top--; /* pop revT stack entry */ + luaC_checkGC(L); +} + + +/* +** Recursive scan all of the Protos in the Proto hierarchy +** to collect all referenced strings in 2 Lua Arrays at ToS. +*/ +#define OVER(n) for (i = 0; i < (n); i++) +static void scanProtoStrings(const Proto *f, DumpState *D) { + int i; + addTS(f->source, D); + OVER(f->sizek) if (ttisstring(f->k + i)) + addTS(tsvalue(f->k + i), D); + OVER(f->sizeupvalues) addTS(f->upvalues[i].name, D); + OVER(f->sizelocvars) addTS(f->locvars[i].varname, D); + OVER(f->sizep) scanProtoStrings(f->p[i], D); +} + + +/* +** An LFS image comprises a prologue segment of all of the strings used in +** the image, followed by a set of Proto dumps. Each of these is essentially +** the same as standard lua_dump format, except that string constants don't +** contain the string inline, but are instead an index into the prologue. +** Separating out the strings in this way simplifies loading the image +** content into an LFS region. +** +** A dummy container Proto, main, is used to hold all of the Protos to go +** into the image. The Proto main itself is not callable; it is used as the +** image Proto index and only contains a Proto vector and a constant vector +** where each constant in the string names the corresponding Proto. +*/ +int luaU_DumpAllProtos(lua_State *L, const Proto *m, lua_Writer w, + void *data, int strip) { + DumpState D = {0}; + D.L = L; + D.writer = w; + D.data = data; + D.strip = strip; + + lua_assert(L->stack_last - L->top > 5); /* This dump uses 5 stack slots */ + DumpHeader(&D, LUAC_LFS_IMAGE_FORMAT); + DumpInteger(G(L)->seed, &D); + D.stringIndex = luaH_new(L); + sethvalue(L, L->top++, D.stringIndex); /* Put on stack to prevent GC */ + /* Add fixed strings + strings used in the Protos, then swap fixed/added blocks */ + addFixedStrings(&D); + scanProtoStrings(m, &D); + /* Dump out all non-fixed strings */ + DumpLiteral(LUA_STRING_SIG, &D); + DumpLFSstrings(&D); + /* Switch to string reference mode and add the Protos themselves */ + D.useStrRefs = 1; + DumpLiteral(LUA_PROTO_SIG, &D); + DumpProtos(m, &D); + DumpConstants(m, &D); /* Dump Function name vector */ + L->top--; + return D.status; +} +#endif diff --git a/components/lua/lua-5.3/lfunc.c b/components/lua/lua-5.3/lfunc.c new file mode 100644 index 00000000..3d61e6e4 --- /dev/null +++ b/components/lua/lua-5.3/lfunc.c @@ -0,0 +1,151 @@ +/* +** $Id: lfunc.c,v 2.45.1.1 2017/04/19 17:39:34 roberto Exp $ +** Auxiliary functions to manipulate prototypes and closures +** See Copyright Notice in lua.h +*/ + +#define lfunc_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" + + + +CClosure *luaF_newCclosure (lua_State *L, int n) { + GCObject *o = luaC_newobj(L, LUA_TCCL, sizeCclosure(n)); + CClosure *c = gco2ccl(o); + c->nupvalues = cast_byte(n); + return c; +} + + +LClosure *luaF_newLclosure (lua_State *L, int n) { + GCObject *o = luaC_newobj(L, LUA_TLCL, sizeLclosure(n)); + LClosure *c = gco2lcl(o); + c->p = NULL; + c->nupvalues = cast_byte(n); + while (n--) c->upvals[n] = NULL; + return c; +} + +/* +** fill a closure with new closed upvalues +*/ +void luaF_initupvals (lua_State *L, LClosure *cl) { + int i; + for (i = 0; i < cl->nupvalues; i++) { + UpVal *uv = luaM_new(L, UpVal); + uv->refcount = 1; + uv->v = &uv->u.value; /* make it closed */ + setnilvalue(uv->v); + cl->upvals[i] = uv; + } +} + + +UpVal *luaF_findupval (lua_State *L, StkId level) { + UpVal **pp = &L->openupval; + UpVal *p; + UpVal *uv; + lua_assert(isintwups(L) || L->openupval == NULL); + while (*pp != NULL && (p = *pp)->v >= level) { + lua_assert(upisopen(p)); + if (p->v == level) /* found a corresponding upvalue? */ + return p; /* return it */ + pp = &p->u.open.next; + } + /* not found: create a new upvalue */ + uv = luaM_new(L, UpVal); + uv->refcount = 0; + uv->u.open.next = *pp; /* link it to list of open upvalues */ + uv->u.open.touched = 1; + *pp = uv; + uv->v = level; /* current value lives in the stack */ + if (!isintwups(L)) { /* thread not in list of threads with upvalues? */ + L->twups = G(L)->twups; /* link it to the list */ + G(L)->twups = L; + } + return uv; +} + + +void luaF_close (lua_State *L, StkId level) { + UpVal *uv; + while (L->openupval != NULL && (uv = L->openupval)->v >= level) { + lua_assert(upisopen(uv)); + L->openupval = uv->u.open.next; /* remove from 'open' list */ + if (uv->refcount == 0) /* no references? */ + luaM_free(L, uv); /* free upvalue */ + else { + setobj(L, &uv->u.value, uv->v); /* move value to upvalue slot */ + uv->v = &uv->u.value; /* now current value lives here */ + luaC_upvalbarrier(L, uv); + } + } +} + + +Proto *luaF_newproto (lua_State *L) { + GCObject *o = luaC_newobj(L, LUA_TPROTO, sizeof(Proto)); + Proto *f = gco2p(o); + f->k = NULL; + f->sizek = 0; + f->p = NULL; + f->sizep = 0; + f->code = NULL; + f->sizecode = 0; + f->lineinfo = NULL; + f->upvalues = NULL; + f->sizelineinfo = 0; + f->sizeupvalues = 0; + f->numparams = 0; + f->is_vararg = 0; + f->maxstacksize = 0; + f->locvars = NULL; + f->sizelocvars = 0; + f->linedefined = 0; + f->lastlinedefined = 0; + f->source = NULL; + f->gclist = NULL; + return f; +} + + +void luaF_freeproto (lua_State *L, Proto *f) { + luaM_freearray(L, f->code, f->sizecode); + luaM_freearray(L, f->p, f->sizep); + luaM_freearray(L, f->k, f->sizek); + luaM_freearray(L, cast(char *,f->lineinfo), f->sizelineinfo); + luaM_freearray(L, f->locvars, f->sizelocvars); + luaM_freearray(L, f->upvalues, f->sizeupvalues); + luaM_free(L, f); +} + + +/* +** Look for n-th local variable at line 'line' in function 'func'. +** Returns NULL if not found. +*/ +const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { + int i; + for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) { + if (pc < f->locvars[i].endpc) { /* is variable active? */ + local_number--; + if (local_number == 0) + return getstr(f->locvars[i].varname); + } + } + return NULL; /* not found */ +} + diff --git a/components/lua/lua-5.3/lfunc.h b/components/lua/lua-5.3/lfunc.h new file mode 100644 index 00000000..c916e987 --- /dev/null +++ b/components/lua/lua-5.3/lfunc.h @@ -0,0 +1,61 @@ +/* +** $Id: lfunc.h,v 2.15.1.1 2017/04/19 17:39:34 roberto Exp $ +** Auxiliary functions to manipulate prototypes and closures +** See Copyright Notice in lua.h +*/ + +#ifndef lfunc_h +#define lfunc_h + + +#include "lobject.h" + + +#define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \ + cast(int, sizeof(TValue)*((n)-1))) + +#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \ + cast(int, sizeof(TValue *)*((n)-1))) + + +/* test whether thread is in 'twups' list */ +#define isintwups(L) (L->twups != L) + + +/* +** maximum number of upvalues in a closure (both C and Lua). (Value +** must fit in a VM register.) +*/ +#define MAXUPVAL 255 + + +/* +** Upvalues for Lua closures +*/ +struct UpVal { + TValue *v; /* points to stack or to its own value */ + lu_mem refcount; /* reference counter */ + union { + struct { /* (when open) */ + UpVal *next; /* linked list */ + int touched; /* mark to avoid cycles with dead threads */ + } open; + TValue value; /* the value (when closed) */ + } u; +}; + +#define upisopen(up) ((up)->v != &(up)->u.value) + + +LUAI_FUNC Proto *luaF_newproto (lua_State *L); +LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nelems); +LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nelems); +LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl); +LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); +LUAI_FUNC void luaF_close (lua_State *L, StkId level); +LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); +LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, + int pc); + + +#endif diff --git a/components/lua/lua-5.3/lgc.c b/components/lua/lua-5.3/lgc.c new file mode 100644 index 00000000..a4f06d17 --- /dev/null +++ b/components/lua/lua-5.3/lgc.c @@ -0,0 +1,1197 @@ +/* +** $Id: lgc.c,v 2.215.1.2 2017/08/31 16:15:27 roberto Exp $ +** Garbage Collector +** See Copyright Notice in lua.h +*/ + +#define lgc_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" + + +/* +** internal state for collector while inside the atomic phase. The +** collector should never be in this state while running regular code. +*/ +#define GCSinsideatomic (GCSpause + 1) + +/* +** cost of sweeping one element (the size of a small object divided +** by some adjust for the sweep speed) +*/ +#define GCSWEEPCOST ((sizeof(TString) + 4) / 4) + +/* maximum number of elements to sweep in each single step */ +#define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4)) + +/* cost of calling one finalizer */ +#define GCFINALIZECOST GCSWEEPCOST + + +/* +** macro to adjust 'stepmul': 'stepmul' is actually used like +** 'stepmul / STEPMULADJ' (value chosen by tests) +*/ +#define STEPMULADJ 200 + + +/* +** macro to adjust 'pause': 'pause' is actually used like +** 'pause / PAUSEADJ' (value chosen by tests) +*/ +#define PAUSEADJ 100 + + +/* +** 'makewhite' erases all color bits then sets only the current white +** bit +*/ +#define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS)) +#define makewhite(g,x) \ + (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g))) + +#define white2gray(x) resetbits(x->marked, WHITEBITS) +#define black2gray(x) resetbit(x->marked, BLACKBIT) + + +#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) + +#define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n))) + + +#define checkconsistency(obj) \ + lua_longassert(!iscollectable(obj) || righttt(obj)) + + +#define markvalue(g,o) { checkconsistency(o); \ + if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } + +#define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); } + +/* +** mark an object that can be NULL (either because it is really optional, +** or it was stripped as debug info, or inside an uncompleted structure) +*/ +#define markobjectN(g,t) { if (t) markobject(g,t); } + +static void reallymarkobject (global_State *g, GCObject *o); + + +/* +** {====================================================== +** Generic functions +** ======================================================= +*/ + + +/* +** one after last element in a hash array +*/ +#define gnodelast(h) gnode(h, cast(size_t, sizenode(h))) + + +/* +** link collectable object 'o' into list pointed by 'p' +*/ +#define linkgclist(o,p) ((o)->gclist = (p), (p) = obj2gco(o)) + + +/* +** If key is not marked, mark its entry as dead. This allows key to be +** collected, but keeps its entry in the table. A dead node is needed +** when Lua looks up for a key (it may be part of a chain) and when +** traversing a weak table (key might be removed from the table during +** traversal). Other places never manipulate dead keys, because its +** associated nil value is enough to signal that the entry is logically +** empty. +*/ +static void removeentry (Node *n) { + lua_assert(ttisnil(gval(n))); + if (valiswhite(gkey(n))) + setdeadvalue(wgkey(n)); /* unused and unmarked key; remove it */ +} + + +/* +** tells whether a key or value can be cleared from a weak +** table. Non-collectable objects are never removed from weak +** tables. Strings behave as 'values', so are never removed too. for +** other objects: if really collected, cannot keep them; for objects +** being finalized, keep them in keys, but not in values +*/ +static int iscleared (global_State *g, const TValue *o) { + if (!iscollectable(o)) return 0; + else if (ttisstring(o)) { + markobject(g, tsvalue(o)); /* strings are 'values', so are never weak */ + return 0; + } + else return iswhite(gcvalue(o)); +} + + +/* +** barrier that moves collector forward, that is, mark the white object +** being pointed by a black object. (If in sweep phase, clear the black +** object to white [sweep it] to avoid other barrier calls for this +** same object.) +*/ +void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) { + global_State *g = G(L); + lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); + if (keepinvariant(g)) /* must keep invariant? */ + reallymarkobject(g, v); /* restore invariant */ + else { /* sweep phase */ + lua_assert(issweepphase(g)); + makewhite(g, o); /* mark main obj. as white to avoid other barriers */ + } +} + + +/* +** barrier that moves collector backward, that is, mark the black object +** pointing to a white object as gray again. +*/ +void luaC_barrierback_ (lua_State *L, Table *t) { + global_State *g = G(L); + lua_assert(isblack(t) && !isdead(g, t)); + black2gray(t); /* make table gray (again) */ + linkgclist(t, g->grayagain); +} + + +/* +** barrier for assignments to closed upvalues. Because upvalues are +** shared among closures, it is impossible to know the color of all +** closures pointing to it. So, we assume that the object being assigned +** must be marked. +*/ +void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) { + global_State *g = G(L); + GCObject *o = gcvalue(uv->v); + lua_assert(!upisopen(uv)); /* ensured by macro luaC_upvalbarrier */ + if (keepinvariant(g)) + markobject(g, o); +} + + +void luaC_fix (lua_State *L, GCObject *o) { + global_State *g = G(L); + lu_byte marked = getmarked(o); + if((marked & WHITEBITS)==0 || (marked & bitmask(LFSBIT))) + return; /* no point in trying to fix an object in LFS */ + lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */ + white2gray(o); /* they will be gray forever */ + g->allgc = o->next; /* remove object from 'allgc' list */ + o->next = g->fixedgc; /* link it to 'fixedgc' list */ + g->fixedgc = o; +} + + +/* +** create a new collectable object (with given type and size) and link +** it to 'allgc' list. +*/ +GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) { + global_State *g = G(L); + GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz)); + o->marked = luaC_white(g); + o->tt = tt; + o->next = g->allgc; + g->allgc = o; + return o; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** Mark functions +** ======================================================= +*/ + + +/* +** mark an object. Userdata, strings, and closed upvalues are visited +** and turned black here. Other objects are marked gray and added +** to appropriate list to be visited (and turned black) later. (Open +** upvalues are already linked in 'headuv' list.) +*/ +static void reallymarkobject (global_State *g, GCObject *o) { + reentry: + if (isLFSobj(o)) + return; + /* DEBUG: Catch any attempt to mark an unmarked LFS object */ + lua_assert((unsigned)(((char *) o)-((char *) g->l_LFS)) > g->LFSsize); + white2gray(o); + switch (gettt(o)) { + case LUA_TSHRSTR: { + gray2black(o); + g->GCmemtrav += sizelstring(gco2ts(o)->shrlen); + break; + } + case LUA_TLNGSTR: { + gray2black(o); + g->GCmemtrav += sizelstring(gco2ts(o)->u.lnglen); + break; + } + case LUA_TUSERDATA: { + TValue uvalue; + markobjectN(g, gco2u(o)->metatable); /* mark its metatable */ + gray2black(o); + g->GCmemtrav += sizeudata(gco2u(o)); + getuservalue(g->mainthread, gco2u(o), &uvalue); + if (valiswhite(&uvalue)) { /* markvalue(g, &uvalue); */ + o = gcvalue(&uvalue); + goto reentry; + } + break; + } + case LUA_TLCL: { + linkgclist(gco2lcl(o), g->gray); + break; + } + case LUA_TCCL: { + linkgclist(gco2ccl(o), g->gray); + break; + } + case LUA_TTABLE: { + linkgclist(gco2t(o), g->gray); + break; + } + case LUA_TTHREAD: { + linkgclist(gco2th(o), g->gray); + break; + } + case LUA_TPROTO: { + linkgclist(gco2p(o), g->gray); + break; + } + default: lua_assert(0); break; + } +} + + +/* +** mark metamethods for basic types +*/ +static void markmt (global_State *g) { + int i; + for (i=0; i < LUA_NUMTAGS; i++) + markobjectN(g, g->mt[i]); +} + + +/* +** mark all objects in list of being-finalized +*/ +static void markbeingfnz (global_State *g) { + GCObject *o; + for (o = g->tobefnz; o != NULL; o = o->next) + markobject(g, o); +} + + +/* +** Mark all values stored in marked open upvalues from non-marked threads. +** (Values from marked threads were already marked when traversing the +** thread.) Remove from the list threads that no longer have upvalues and +** not-marked threads. +*/ +static void remarkupvals (global_State *g) { + lua_State *thread; + lua_State **p = &g->twups; + while ((thread = *p) != NULL) { + lua_assert(!isblack(thread)); /* threads are never black */ + if (isgray(thread) && thread->openupval != NULL) + p = &thread->twups; /* keep marked thread with upvalues in the list */ + else { /* thread is not marked or without upvalues */ + UpVal *uv; + *p = thread->twups; /* remove thread from the list */ + thread->twups = thread; /* mark that it is out of list */ + for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) { + if (uv->u.open.touched) { + markvalue(g, uv->v); /* remark upvalue's value */ + uv->u.open.touched = 0; + } + } + } + } +} + + +/* +** mark root set and reset all gray lists, to start a new collection +*/ +static void restartcollection (global_State *g) { + g->gray = g->grayagain = NULL; + g->weak = g->allweak = g->ephemeron = NULL; + markobject(g, g->mainthread); + markvalue(g, &g->l_registry); + markmt(g); + markbeingfnz(g); /* mark any finalizing object left from previous cycle */ +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Traverse functions +** ======================================================= +*/ + +/* +** Traverse a table with weak values and link it to proper list. During +** propagate phase, keep it in 'grayagain' list, to be revisited in the +** atomic phase. In the atomic phase, if table has any white value, +** put it in 'weak' list, to be cleared. +*/ +static void traverseweakvalue (global_State *g, Table *h) { + Node *n, *limit = gnodelast(h); + /* if there is array part, assume it may have white values (it is not + worth traversing it now just to check) */ + int hasclears = (h->sizearray > 0); + for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ + checkdeadkey(n); + if (ttisnil(gval(n))) /* entry is empty? */ + removeentry(n); /* remove it */ + else { + lua_assert(!ttisnil(gkey(n))); + markvalue(g, gkey(n)); /* mark key */ + if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */ + hasclears = 1; /* table will have to be cleared */ + } + } + if (g->gcstate == GCSpropagate) + linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ + else if (hasclears) + linkgclist(h, g->weak); /* has to be cleared later */ +} + + +/* +** Traverse an ephemeron table and link it to proper list. Returns true +** iff any object was marked during this traversal (which implies that +** convergence has to continue). During propagation phase, keep table +** in 'grayagain' list, to be visited again in the atomic phase. In +** the atomic phase, if table has any white->white entry, it has to +** be revisited during ephemeron convergence (as that key may turn +** black). Otherwise, if it has any white key, table has to be cleared +** (in the atomic phase). +*/ +static int traverseephemeron (global_State *g, Table *h) { + int marked = 0; /* true if an object is marked in this traversal */ + int hasclears = 0; /* true if table has white keys */ + int hasww = 0; /* true if table has entry "white-key -> white-value" */ + Node *n, *limit = gnodelast(h); + unsigned int i; + /* traverse array part */ + for (i = 0; i < h->sizearray; i++) { + if (valiswhite(&h->array[i])) { + marked = 1; + reallymarkobject(g, gcvalue(&h->array[i])); + } + } + /* traverse hash part */ + for (n = gnode(h, 0); n < limit; n++) { + checkdeadkey(n); + if (ttisnil(gval(n))) /* entry is empty? */ + removeentry(n); /* remove it */ + else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */ + hasclears = 1; /* table must be cleared */ + if (valiswhite(gval(n))) /* value not marked yet? */ + hasww = 1; /* white-white entry */ + } + else if (valiswhite(gval(n))) { /* value not marked yet? */ + marked = 1; + reallymarkobject(g, gcvalue(gval(n))); /* mark it now */ + } + } + /* link table into proper list */ + if (g->gcstate == GCSpropagate) + linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ + else if (hasww) /* table has white->white entries? */ + linkgclist(h, g->ephemeron); /* have to propagate again */ + else if (hasclears) /* table has white keys? */ + linkgclist(h, g->allweak); /* may have to clean white keys */ + return marked; +} + + +static void traversestrongtable (global_State *g, Table *h) { + Node *n, *limit = gnodelast(h); + unsigned int i; + for (i = 0; i < h->sizearray; i++) /* traverse array part */ + markvalue(g, &h->array[i]); + for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ + checkdeadkey(n); + if (ttisnil(gval(n))) /* entry is empty? */ + removeentry(n); /* remove it */ + else { + lua_assert(!ttisnil(gkey(n))); + markvalue(g, gkey(n)); /* mark key */ + markvalue(g, gval(n)); /* mark value */ + } + } +} + + +static lu_mem traversetable (global_State *g, Table *h) { + const char *weakkey, *weakvalue; + const TValue *mode = gfasttm(g, h->metatable, TM_MODE); + markobjectN(g, h->metatable); + if (mode && ttisstring(mode) && /* is there a weak mode? */ + ((weakkey = strchr(svalue(mode), 'k')), + (weakvalue = strchr(svalue(mode), 'v')), + (weakkey || weakvalue))) { /* is really weak? */ + black2gray(h); /* keep table gray */ + if (!weakkey) /* strong keys? */ + traverseweakvalue(g, h); + else if (!weakvalue) /* strong values? */ + traverseephemeron(g, h); + else /* all weak */ + linkgclist(h, g->allweak); /* nothing to traverse now */ + } + else /* not weak */ + traversestrongtable(g, h); + return sizeof(Table) + sizeof(TValue) * h->sizearray + + sizeof(Node) * cast(size_t, allocsizenode(h)); +} + + +/* +** Traverse a prototype. (While a prototype is being build, its +** arrays can be larger than needed; the extra slots are filled with +** NULL, so the use of 'markobjectN') +*/ +static int traverseproto (global_State *g, Proto *f) { + int i; + markobjectN(g, f->source); + for (i = 0; i < f->sizek; i++) /* mark literals */ + markvalue(g, &f->k[i]); + for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */ + markobjectN(g, f->upvalues[i].name); + for (i = 0; i < f->sizep; i++) /* mark nested protos */ + markobjectN(g, f->p[i]); + for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */ + markobjectN(g, f->locvars[i].varname); + return sizeof(Proto) + sizeof(Instruction) * f->sizecode + + sizeof(Proto *) * f->sizep + + sizeof(TValue) * f->sizek + + sizeof(char) * f->sizelineinfo + + sizeof(LocVar) * f->sizelocvars + + sizeof(Upvaldesc) * f->sizeupvalues; +} + + +static lu_mem traverseCclosure (global_State *g, CClosure *cl) { + int i; + for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ + markvalue(g, &cl->upvalue[i]); + return sizeCclosure(cl->nupvalues); +} + +/* +** open upvalues point to values in a thread, so those values should +** be marked when the thread is traversed except in the atomic phase +** (because then the value cannot be changed by the thread and the +** thread may not be traversed again) +*/ +static lu_mem traverseLclosure (global_State *g, LClosure *cl) { + int i; + if (!isLFSobj(cl->p)) + markobjectN(g, cl->p); /* mark its prototype */ + for (i = 0; i < cl->nupvalues; i++) { /* mark its upvalues */ + UpVal *uv = cl->upvals[i]; + if (uv != NULL) { + if (upisopen(uv) && g->gcstate != GCSinsideatomic) + uv->u.open.touched = 1; /* can be marked in 'remarkupvals' */ + else + markvalue(g, uv->v); + } + } + return sizeLclosure(cl->nupvalues); +} + + +static lu_mem traversethread (global_State *g, lua_State *th) { + StkId o = th->stack; + if (o == NULL) + return 1; /* stack not completely built yet */ + lua_assert(g->gcstate == GCSinsideatomic || + th->openupval == NULL || isintwups(th)); + for (; o < th->top; o++) /* mark live elements in the stack */ + markvalue(g, o); + if (g->gcstate == GCSinsideatomic) { /* final traversal? */ + StkId lim = th->stack + th->stacksize; /* real end of stack */ + for (; o < lim; o++) /* clear not-marked stack slice */ + setnilvalue(o); + /* 'remarkupvals' may have removed thread from 'twups' list */ + if (!isintwups(th) && th->openupval != NULL) { + th->twups = g->twups; /* link it back to the list */ + g->twups = th; + } + } + else if (g->gckind != KGC_EMERGENCY) + luaD_shrinkstack(th); /* do not change stack in emergency cycle */ + return (sizeof(lua_State) + sizeof(TValue) * th->stacksize + + sizeof(CallInfo) * th->nci); +} + + +/* +** traverse one gray object, turning it to black (except for threads, +** which are always gray). +*/ +static void propagatemark (global_State *g) { + lu_mem size; + GCObject *o = g->gray; + lua_assert(isgray(o)); + gray2black(o); + switch (gettt(o)) { + case LUA_TTABLE: { + Table *h = gco2t(o); + g->gray = h->gclist; /* remove from 'gray' list */ + size = traversetable(g, h); + break; + } + case LUA_TLCL: { + LClosure *cl = gco2lcl(o); + g->gray = cl->gclist; /* remove from 'gray' list */ + size = traverseLclosure(g, cl); + break; + } + case LUA_TCCL: { + CClosure *cl = gco2ccl(o); + g->gray = cl->gclist; /* remove from 'gray' list */ + size = traverseCclosure(g, cl); + break; + } + case LUA_TTHREAD: { + lua_State *th = gco2th(o); + g->gray = th->gclist; /* remove from 'gray' list */ + linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ + black2gray(o); + size = traversethread(g, th); + break; + } + case LUA_TPROTO: { + Proto *p = gco2p(o); + g->gray = p->gclist; /* remove from 'gray' list */ + size = traverseproto(g, p); + break; + } + default: lua_assert(0); return; + } + g->GCmemtrav += size; +} + + +static void propagateall (global_State *g) { + while (g->gray) propagatemark(g); +} + + +static void convergeephemerons (global_State *g) { + int changed; + do { + GCObject *w; + GCObject *next = g->ephemeron; /* get ephemeron list */ + g->ephemeron = NULL; /* tables may return to this list when traversed */ + changed = 0; + while ((w = next) != NULL) { + next = gco2t(w)->gclist; + if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */ + propagateall(g); /* propagate changes */ + changed = 1; /* will have to revisit all ephemeron tables */ + } + } + } while (changed); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Sweep Functions +** ======================================================= +*/ + + +/* +** clear entries with unmarked keys from all weaktables in list 'l' up +** to element 'f' +*/ +static void clearkeys (global_State *g, GCObject *l, GCObject *f) { + for (; l != f; l = gco2t(l)->gclist) { + Table *h = gco2t(l); + Node *n, *limit = gnodelast(h); + for (n = gnode(h, 0); n < limit; n++) { + if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) { + setnilvalue(gval(n)); /* remove value ... */ + } + if (ttisnil(gval(n))) /* is entry empty? */ + removeentry(n); /* remove entry from table */ + } + } +} + + +/* +** clear entries with unmarked values from all weaktables in list 'l' up +** to element 'f' +*/ +static void clearvalues (global_State *g, GCObject *l, GCObject *f) { + for (; l != f; l = gco2t(l)->gclist) { + Table *h = gco2t(l); + Node *n, *limit = gnodelast(h); + unsigned int i; + for (i = 0; i < h->sizearray; i++) { + TValue *o = &h->array[i]; + if (iscleared(g, o)) /* value was collected? */ + setnilvalue(o); /* remove value */ + } + for (n = gnode(h, 0); n < limit; n++) { + if (!ttisnil(gval(n)) && iscleared(g, gval(n))) { + setnilvalue(gval(n)); /* remove value ... */ + removeentry(n); /* and remove entry from table */ + } + } + } +} + + +void luaC_upvdeccount (lua_State *L, UpVal *uv) { + lua_assert(uv->refcount > 0); + uv->refcount--; + if (uv->refcount == 0 && !upisopen(uv)) + luaM_free(L, uv); +} + + +static void freeLclosure (lua_State *L, LClosure *cl) { + int i; + for (i = 0; i < cl->nupvalues; i++) { + UpVal *uv = cl->upvals[i]; + if (uv) + luaC_upvdeccount(L, uv); + } + luaM_freemem(L, cl, sizeLclosure(cl->nupvalues)); +} + + +static void freeobj (lua_State *L, GCObject *o) { + + switch (gettt(o)) { + case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break; + case LUA_TLCL: { + freeLclosure(L, gco2lcl(o)); + break; + } + case LUA_TCCL: { + luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues)); + break; + } + case LUA_TTABLE: luaH_free(L, gco2t(o)); break; + case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break; + case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break; + case LUA_TSHRSTR: + luaS_remove(L, gco2ts(o)); /* remove it from hash table */ + luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen)); + break; + case LUA_TLNGSTR: { + luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen)); + break; + } + default: lua_assert(0); + } +} + + +#define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM) +static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count); + + +/* +** sweep at most 'count' elements from a list of GCObjects erasing dead +** objects, where a dead object is one marked with the old (non current) +** white; change all non-dead objects back to white, preparing for next +** collection cycle. Return where to continue the traversal or NULL if +** list is finished. +*/ +static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { + global_State *g = G(L); + int ow = otherwhite(g); + int white = luaC_white(g); /* current white */ + while (*p != NULL && count-- > 0) { + GCObject *curr = *p; + int marked = curr->marked; + if (isdeadm(ow, marked)) { /* is 'curr' dead? */ + *p = curr->next; /* remove 'curr' from list */ + freeobj(L, curr); /* erase 'curr' */ + } + else { /* change mark to 'white' */ + curr->marked = cast_byte((marked & maskcolors) | white); + p = &curr->next; /* go to next element */ + } + } + return (*p == NULL) ? NULL : p; +} + + +/* +** sweep a list until a live object (or end of list) +*/ +static GCObject **sweeptolive (lua_State *L, GCObject **p) { + GCObject **old = p; + do { + p = sweeplist(L, p, 1); + } while (p == old); + return p; +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Finalization +** ======================================================= +*/ + +/* +** If possible, shrink string table +*/ +static void checkSizes (lua_State *L, global_State *g) { + if (g->gckind != KGC_EMERGENCY) { + l_mem olddebt = g->GCdebt; + if (g->strt.nuse < g->strt.size / 4) /* string table too big? */ + luaS_resize(L, g->strt.size / 2); /* shrink it a little */ + g->GCestimate += g->GCdebt - olddebt; /* update estimate */ + } +} + + +static GCObject *udata2finalize (global_State *g) { + GCObject *o = g->tobefnz; /* get first element */ + lua_assert(tofinalize(o)); + g->tobefnz = o->next; /* remove it from 'tobefnz' list */ + o->next = g->allgc; /* return it to 'allgc' list */ + g->allgc = o; + resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */ + if (issweepphase(g)) + makewhite(g, o); /* "sweep" object */ + return o; +} + + +static void dothecall (lua_State *L, void *ud) { + UNUSED(ud); + luaD_callnoyield(L, L->top - 2, 0); +} + + +static void GCTM (lua_State *L, int propagateerrors) { + global_State *g = G(L); + const TValue *tm; + TValue v; + setgcovalue(L, &v, udata2finalize(g)); + tm = luaT_gettmbyobj(L, &v, TM_GC); + if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */ + int status; + lu_byte oldah = L->allowhook; + int running = g->gcrunning; + L->allowhook = 0; /* stop debug hooks during GC metamethod */ + g->gcrunning = 0; /* avoid GC steps */ + setobj2s(L, L->top, tm); /* push finalizer... */ + setobj2s(L, L->top + 1, &v); /* ... and its argument */ + L->top += 2; /* and (next line) call the finalizer */ + L->ci->callstatus |= CIST_FIN; /* will run a finalizer */ + status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0); + L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */ + L->allowhook = oldah; /* restore hooks */ + g->gcrunning = running; /* restore state */ + if (status != LUA_OK && propagateerrors) { /* error while running __gc? */ + if (status == LUA_ERRRUN) { /* is there an error object? */ + const char *msg = (ttisstring(L->top - 1)) + ? svalue(L->top - 1) + : "no message"; + luaO_pushfstring(L, "error in __gc metamethod (%s)", msg); + status = LUA_ERRGCMM; /* error in __gc metamethod */ + } + luaD_throw(L, status); /* re-throw error */ + } + } +} + + +/* +** call a few (up to 'g->gcfinnum') finalizers +*/ +static int runafewfinalizers (lua_State *L) { + global_State *g = G(L); + unsigned int i; + lua_assert(!g->tobefnz || g->gcfinnum > 0); + for (i = 0; g->tobefnz && i < g->gcfinnum; i++) + GCTM(L, 1); /* call one finalizer */ + g->gcfinnum = (!g->tobefnz) ? 0 /* nothing more to finalize? */ + : g->gcfinnum * 2; /* else call a few more next time */ + return i; +} + + +/* +** call all pending finalizers +*/ +static void callallpendingfinalizers (lua_State *L) { + global_State *g = G(L); + while (g->tobefnz) + GCTM(L, 0); +} + + +/* +** find last 'next' field in list 'p' list (to add elements in its end) +*/ +static GCObject **findlast (GCObject **p) { + while (*p != NULL) + p = &(*p)->next; + return p; +} + + +/* +** move all unreachable objects (or 'all' objects) that need +** finalization from list 'finobj' to list 'tobefnz' (to be finalized) +*/ +static void separatetobefnz (global_State *g, int all) { + GCObject *curr; + GCObject **p = &g->finobj; + GCObject **lastnext = findlast(&g->tobefnz); + while ((curr = *p) != NULL) { /* traverse all finalizable objects */ + lua_assert(tofinalize(curr)); + if (!(iswhite(curr) || all)) /* not being collected? */ + p = &curr->next; /* don't bother with it */ + else { + *p = curr->next; /* remove 'curr' from 'finobj' list */ + curr->next = *lastnext; /* link at the end of 'tobefnz' list */ + *lastnext = curr; + lastnext = &curr->next; + } + } +} + + +/* +** if object 'o' has a finalizer, remove it from 'allgc' list (must +** search the list to find it) and link it in 'finobj' list. +*/ +void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { + global_State *g = G(L); + if (tofinalize(o) || /* obj. is already marked... */ + gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */ + return; /* nothing to be done */ + else { /* move 'o' to 'finobj' list */ + GCObject **p; + if (issweepphase(g)) { + makewhite(g, o); /* "sweep" object 'o' */ + if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */ + g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */ + } + /* search for pointer pointing to 'o' */ + for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ } + *p = o->next; /* remove 'o' from 'allgc' list */ + o->next = g->finobj; /* link it in 'finobj' list */ + g->finobj = o; + l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */ + } +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** GC control +** ======================================================= +*/ + + +/* +** Set a reasonable "time" to wait before starting a new GC cycle; cycle +** will start when memory use hits threshold. (Division by 'estimate' +** should be OK: it cannot be zero (because Lua cannot even start with +** less than PAUSEADJ bytes). +*/ +static void setpause (global_State *g) { + l_mem threshold, debt; + l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */ + lua_assert(estimate > 0); + threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */ + ? estimate * g->gcpause /* no overflow */ + : MAX_LMEM; /* overflow; truncate to maximum */ + debt = gettotalbytes(g) - threshold; + luaE_setdebt(g, debt); +} + + +/* +** Enter first sweep phase. +** The call to 'sweeplist' tries to make pointer point to an object +** inside the list (instead of to the header), so that the real sweep do +** not need to skip objects created between "now" and the start of the +** real sweep. +*/ +static void entersweep (lua_State *L) { + global_State *g = G(L); + g->gcstate = GCSswpallgc; + lua_assert(g->sweepgc == NULL); + g->sweepgc = sweeplist(L, &g->allgc, 1); +} + + +void luaC_freeallobjects (lua_State *L) { + global_State *g = G(L); + separatetobefnz(g, 1); /* separate all objects with finalizers */ + lua_assert(g->finobj == NULL); + callallpendingfinalizers(L); + lua_assert(g->tobefnz == NULL); + g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */ + g->gckind = KGC_NORMAL; + sweepwholelist(L, &g->finobj); + sweepwholelist(L, &g->allgc); + sweepwholelist(L, &g->fixedgc); /* collect fixed objects */ + lua_assert(g->strt.nuse == 0); +} + + +static l_mem atomic (lua_State *L) { + global_State *g = G(L); + l_mem work; + GCObject *origweak, *origall; + GCObject *grayagain = g->grayagain; /* save original list */ + lua_assert(g->ephemeron == NULL && g->weak == NULL); + lua_assert(!iswhite(g->mainthread)); + g->gcstate = GCSinsideatomic; + g->GCmemtrav = 0; /* start counting work */ + markobject(g, L); /* mark running thread */ + /* registry and global metatables may be changed by API */ + markvalue(g, &g->l_registry); + markmt(g); /* mark global metatables */ + /* remark occasional upvalues of (maybe) dead threads */ + remarkupvals(g); + propagateall(g); /* propagate changes */ + work = g->GCmemtrav; /* stop counting (do not recount 'grayagain') */ + g->gray = grayagain; + propagateall(g); /* traverse 'grayagain' list */ + g->GCmemtrav = 0; /* restart counting */ + convergeephemerons(g); + /* at this point, all strongly accessible objects are marked. */ + /* Clear values from weak tables, before checking finalizers */ + clearvalues(g, g->weak, NULL); + clearvalues(g, g->allweak, NULL); + origweak = g->weak; origall = g->allweak; + work += g->GCmemtrav; /* stop counting (objects being finalized) */ + separatetobefnz(g, 0); /* separate objects to be finalized */ + g->gcfinnum = 1; /* there may be objects to be finalized */ + markbeingfnz(g); /* mark objects that will be finalized */ + propagateall(g); /* remark, to propagate 'resurrection' */ + g->GCmemtrav = 0; /* restart counting */ + convergeephemerons(g); + /* at this point, all resurrected objects are marked. */ + /* remove dead objects from weak tables */ + clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */ + clearkeys(g, g->allweak, NULL); /* clear keys from all 'allweak' tables */ + /* clear values from resurrected weak tables */ + clearvalues(g, g->weak, origweak); + clearvalues(g, g->allweak, origall); + luaS_clearcache(g); + g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ + work += g->GCmemtrav; /* complete counting */ + return work; /* estimate of memory marked by 'atomic' */ +} + + +static lu_mem sweepstep (lua_State *L, global_State *g, + int nextstate, GCObject **nextlist) { + if (g->sweepgc) { + l_mem olddebt = g->GCdebt; + g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX); + g->GCestimate += g->GCdebt - olddebt; /* update estimate */ + if (g->sweepgc) /* is there still something to sweep? */ + return (GCSWEEPMAX * GCSWEEPCOST); + } + /* else enter next state */ + g->gcstate = nextstate; + g->sweepgc = nextlist; + return 0; +} + + +static lu_mem singlestep (lua_State *L) { + global_State *g = G(L); + switch (g->gcstate) { + case GCSpause: { + g->GCmemtrav = g->strt.size * sizeof(GCObject*); + restartcollection(g); + g->gcstate = GCSpropagate; + return g->GCmemtrav; + } + case GCSpropagate: { + g->GCmemtrav = 0; + lua_assert(g->gray); + propagatemark(g); + if (g->gray == NULL) /* no more gray objects? */ + g->gcstate = GCSatomic; /* finish propagate phase */ + return g->GCmemtrav; /* memory traversed in this step */ + } + case GCSatomic: { + lu_mem work; + propagateall(g); /* make sure gray list is empty */ + work = atomic(L); /* work is what was traversed by 'atomic' */ + entersweep(L); + g->GCestimate = gettotalbytes(g); /* first estimate */; + return work; + } + case GCSswpallgc: { /* sweep "regular" objects */ + return sweepstep(L, g, GCSswpfinobj, &g->finobj); + } + case GCSswpfinobj: { /* sweep objects with finalizers */ + return sweepstep(L, g, GCSswptobefnz, &g->tobefnz); + } + case GCSswptobefnz: { /* sweep objects to be finalized */ + return sweepstep(L, g, GCSswpend, NULL); + } + case GCSswpend: { /* finish sweeps */ + makewhite(g, g->mainthread); /* sweep main thread */ + checkSizes(L, g); + g->gcstate = GCScallfin; + return 0; + } + case GCScallfin: { /* call remaining finalizers */ + if (g->tobefnz && g->gckind != KGC_EMERGENCY) { + int n = runafewfinalizers(L); + return (n * GCFINALIZECOST); + } + else { /* emergency mode or no more finalizers */ + g->gcstate = GCSpause; /* finish collection */ + return 0; + } + } + default: lua_assert(0); return 0; + } +} + + +/* +** advances the garbage collector until it reaches a state allowed +** by 'statemask' +*/ +void luaC_runtilstate (lua_State *L, int statesmask) { + global_State *g = G(L); + while (!testbit(statesmask, g->gcstate)) + singlestep(L); +} + + +/* +** get GC debt and convert it from Kb to 'work units' (avoid zero debt +** and overflows) +*/ +static l_mem getdebt (global_State *g) { + l_mem debt = g->GCdebt; + int stepmul = g->gcstepmul; + if (debt <= 0) return 0; /* minimal debt */ + else { + debt = (debt / STEPMULADJ) + 1; + debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM; + return debt; + } +} + +/* +** performs a basic GC step when collector is running +*/ +#ifdef LUA_USE_ESP8266 /*DEBUG*/ +extern void dbg_printf(const char *fmt, ...); +#define CCOUNT_REG ({ int32_t r; asm volatile("rsr %0, ccount" : "=r"(r)); r;}) +#else /*DEBUG*/ +#define dbg_printf(...) +#define CCOUNT_REG 0 +#endif /*DEBUG*/ +void luaC_step (lua_State *L) { + global_State *g = G(L); + l_mem debt = getdebt(g); /* GC deficit (be paid now) */ + if (!g->gcrunning) { /* not running? */ + luaE_setdebt(g, -GCSTEPSIZE * 10); /* avoid being called too often */ + return; + } + do { /* repeat until pause or enough "credit" (negative debt) */ +/*DEBUG int32_t start = CCOUNT_REG; */ + lu_mem work = singlestep(L); /* perform one single step */ + debt -= work; +/*DEBUG dbg_printf("singlestep - %d, %d, %u \n", debt, lua_freeheap(), CCOUNT_REG-start); */ + } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause); + if (g->gcstate == GCSpause) + setpause(g); /* pause until next cycle */ + else { +/*DEBUG int32_t start = CCOUNT_REG; */ + debt = (debt / g->gcstepmul) * STEPMULADJ; /* convert 'work units' to Kb */ + luaE_setdebt(g, debt); + runafewfinalizers(L); +/*DEBUG dbg_printf("new debt - %d, %d, %u \n", debt, lua_freeheap(), CCOUNT_REG-start); */ + } +} + + +/* +** Performs a full GC cycle; if 'isemergency', set a flag to avoid +** some operations which could change the interpreter state in some +** unexpected ways (running finalizers and shrinking some structures). +** Before running the collection, check 'keepinvariant'; if it is true, +** there may be some objects marked as black, so the collector has +** to sweep all objects to turn them back to white (as white has not +** changed, nothing will be collected). +*/ +void luaC_fullgc (lua_State *L, int isemergency) { + global_State *g = G(L); + lua_assert(g->gckind == KGC_NORMAL); + if (isemergency) g->gckind = KGC_EMERGENCY; /* set flag */ + if (keepinvariant(g)) { /* black objects? */ + entersweep(L); /* sweep everything to turn them back to white */ + } + /* finish any pending sweep phase to start a new cycle */ + luaC_runtilstate(L, bitmask(GCSpause)); + luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */ + luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */ + /* estimate must be correct after a full GC cycle */ + lua_assert(g->GCestimate == gettotalbytes(g)); + luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ + g->gckind = KGC_NORMAL; + setpause(g); +} + +/* }====================================================== */ + + diff --git a/components/lua/lua-5.3/lgc.h b/components/lua/lua-5.3/lgc.h new file mode 100644 index 00000000..aa372527 --- /dev/null +++ b/components/lua/lua-5.3/lgc.h @@ -0,0 +1,149 @@ +/* +** $Id: lgc.h,v 2.91.1.1 2017/04/19 17:39:34 roberto Exp $ +** Garbage Collector +** See Copyright Notice in lua.h +*/ + +#ifndef lgc_h +#define lgc_h + + +#include "lobject.h" +#include "lstate.h" + +/* +** Collectable objects may have one of three colors: white, which +** means the object is not marked; gray, which means the +** object is marked, but its references may be not marked; and +** black, which means that the object and all its references are marked. +** The main invariant of the garbage collector, while marking objects, +** is that a black object can never point to a white one. Moreover, +** any gray object must be in a "gray list" (gray, grayagain, weak, +** allweak, ephemeron) so that it can be visited again before finishing +** the collection cycle. These lists have no meaning when the invariant +** is not being enforced (e.g., sweep phase). +*/ + + + +/* how much to allocate before next GC step */ +#if !defined(GCSTEPSIZE) +/* ~100 small strings */ +#define GCSTEPSIZE (cast_int(100 * sizeof(TString))) +#endif + + +/* +** Possible states of the Garbage Collector +*/ +#define GCSpropagate 0 +#define GCSatomic 1 +#define GCSswpallgc 2 +#define GCSswpfinobj 3 +#define GCSswptobefnz 4 +#define GCSswpend 5 +#define GCScallfin 6 +#define GCSpause 7 + + +#define issweepphase(g) \ + (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend) + + +/* +** macro to tell when main invariant (white objects cannot point to black +** ones) must be kept. During a collection, the sweep +** phase may break the invariant, as objects turned white may point to +** still-black objects. The invariant is restored when sweep ends and +** all objects are white again. +*/ + +#define keepinvariant(g) ((g)->gcstate <= GCSatomic) + + +/* +** some useful bit tricks +*/ +#define resetbits(x,m) ((x) &= cast(lu_byte, ~(m))) +#define setbits(x,m) ((x) |= (m)) +#define testbits(x,m) ((x) & (m)) +#define bitmask(b) (1<<(b)) +#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) +#define l_setbit(x,b) setbits(x, bitmask(b)) +#define resetbit(x,b) resetbits(x, bitmask(b)) +#define testbit(x,b) testbits(x, bitmask(b)) + + +/* Layout for bit use in 'marked' field: */ +#define WHITE0BIT 0 /* object is white (type 0) */ +#define WHITE1BIT 1 /* object is white (type 1) */ +#define BLACKBIT 2 /* object is black */ +#define FINALIZEDBIT 3 /* object has been marked for finalization */ +#define LFSBIT 5 /* object is in LFS and is skipped in marking */ +/* bit 7 is currently used by tests (luaL_checkmemory) */ + +#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) + + +#define iswhite(x) testbits(getmarked(x), WHITEBITS) +#define isblack(x) testbit(getmarked(x), BLACKBIT) +#define isgray(x) /* neither white nor black */ \ + (!testbits(getmarked(x), WHITEBITS | bitmask(BLACKBIT))) + +#define tofinalize(x) testbit(getmarked(x), FINALIZEDBIT) + +#define otherwhite(g) ((g)->currentwhite ^ WHITEBITS) +#define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow))) +#define isdead(g,v) isdeadm(otherwhite(g), getmarked(v)) + +#define changewhite(x) ((x)->marked ^= WHITEBITS) +#define gray2black(x) l_setbit((x)->marked, BLACKBIT) + +#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) + +#define isLFSobj(x) testbit(getmarked(x), LFSBIT) +#define setLFSbit(x) l_setbit((x)->marked, LFSBIT) +/* +** Does one step of collection when debt becomes positive. 'pre'/'pos' +** allows some adjustments to be done only when needed. macro +** 'condchangemem' is used only for heavy tests (forcing a full +** GC cycle on every opportunity) +*/ +#define luaC_condGC(L,pre,pos) \ + { if (G(L)->GCdebt > 0) { pre; luaC_step(L); pos;}; \ + condchangemem(L,pre,pos); } + +/* more often than not, 'pre'/'pos' are empty */ +#define luaC_checkGC(L) luaC_condGC(L,(void)0,(void)0) + + +#define luaC_barrier(L,p,v) ( \ + (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ + luaC_barrier_(L,obj2gco(p),gcvalue(v)) : cast_void(0)) + +#define luaC_barrierback(L,p,v) ( \ + (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ + luaC_barrierback_(L,p) : cast_void(0)) + +#define luaC_objbarrier(L,p,o) ( \ + (isblack(p) && iswhite(o)) ? \ + luaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0)) + +#define luaC_upvalbarrier(L,uv) ( \ + (iscollectable((uv)->v) && !upisopen(uv)) ? \ + luaC_upvalbarrier_(L,uv) : cast_void(0)) + +LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o); +LUAI_FUNC void luaC_freeallobjects (lua_State *L); +LUAI_FUNC void luaC_step (lua_State *L); +LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask); +LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency); +LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz); +LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v); +LUAI_FUNC void luaC_barrierback_ (lua_State *L, Table *o); +LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv); +LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt); +LUAI_FUNC void luaC_upvdeccount (lua_State *L, UpVal *uv); + + +#endif diff --git a/components/lua/lua-5.3/llex.c b/components/lua/lua-5.3/llex.c new file mode 100644 index 00000000..a582b9f5 --- /dev/null +++ b/components/lua/lua-5.3/llex.c @@ -0,0 +1,577 @@ +/* +** $Id: llex.c,v 2.96.1.1 2017/04/19 17:20:42 roberto Exp $ +** Lexical Analyzer +** See Copyright Notice in lua.h +*/ + +#define llex_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include + +#include "lua.h" + +#include "lctype.h" +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "llex.h" +#include "lobject.h" +#include "lparser.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "lzio.h" + + + +#define next(ls) (ls->current = zgetc(ls->z)) + + + +#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') + + +/* ORDER RESERVED */ +static const char *const luaX_tokens [] = { + "and", "break", "do", "else", "elseif", + "end", "false", "for", "function", "goto", "if", + "in", "local", "nil", "not", "or", "repeat", + "return", "then", "true", "until", "while", + "//", "..", "...", "==", ">=", "<=", "~=", + "<<", ">>", "::", "", + "", "", "", "" +}; + + +#define save_and_next(ls) (save(ls, ls->current), next(ls)) + + +static l_noret lexerror (LexState *ls, const char *msg, int token); + + +static void save (LexState *ls, int c) { + Mbuffer *b = ls->buff; + if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) { + size_t newsize; + if (luaZ_sizebuffer(b) >= MAX_SIZE/2) + lexerror(ls, "lexical element too long", 0); + newsize = luaZ_sizebuffer(b) * 2; + luaZ_resizebuffer(ls->L, b, newsize); + } + b->buffer[luaZ_bufflen(b)++] = cast(char, c); +} + + +void luaX_init (lua_State *L) { + int i; + TString *e = luaS_newliteral(L, LUA_ENV); /* create env name */ + luaC_fix(L, obj2gco(e)); /* never collect this name */ + for (i=0; iextra = cast_byte(i+1); /* reserved word */ + else + lua_assert(ts->extra == cast_byte(i+1)); /* LFS version should match */ + } +} + +/* Access method to expose luaX_fixed strings */ +const char *luaX_getstr (unsigned int i, int *extra) { + if (i == sizeof(luaX_tokens)/sizeof(*luaX_tokens)) + return NULL; + if (extra) + *extra = (iL, "'%c'", token); + } + else { + const char *s = luaX_tokens[token - FIRST_RESERVED]; + if (token < TK_EOS) /* fixed format (symbols and reserved words)? */ + return luaO_pushfstring(ls->L, "'%s'", s); + else /* names, strings, and numerals */ + return s; + } +} + + +static const char *txtToken (LexState *ls, int token) { + switch (token) { + case TK_NAME: case TK_STRING: + case TK_FLT: case TK_INT: + save(ls, '\0'); + return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff)); + default: + return luaX_token2str(ls, token); + } +} + + +static l_noret lexerror (LexState *ls, const char *msg, int token) { + msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber); + if (token) + luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token)); + luaD_throw(ls->L, LUA_ERRSYNTAX); +} + + +l_noret luaX_syntaxerror (LexState *ls, const char *msg) { + lexerror(ls, msg, ls->t.token); +} + + +/* +** creates a new string and anchors it in scanner's table so that +** it will not be collected until the end of the compilation +** (by that time it should be anchored somewhere) +*/ +TString *luaX_newstring (LexState *ls, const char *str, size_t l) { + lua_State *L = ls->L; + TValue *o; /* entry for 'str' */ + TString *ts = luaS_newlstr(L, str, l); /* create new string */ + setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */ + o = luaH_set(L, ls->h, L->top - 1); + if (ttisnil(o)) { /* not in use yet? */ + /* boolean value does not need GC barrier; + table has no metatable, so it does not need to invalidate cache */ + setbvalue(o, 1); /* t[string] = true */ + luaC_checkGC(L); + } + else { /* string already present */ + ts = tsvalue(keyfromval(o)); /* re-use value previously stored */ + } + L->top--; /* remove string from stack */ + return ts; +} + + +/* +** increment line number and skips newline sequence (any of +** \n, \r, \n\r, or \r\n) +*/ +static void inclinenumber (LexState *ls) { + int old = ls->current; + lua_assert(currIsNewline(ls)); + next(ls); /* skip '\n' or '\r' */ + if (currIsNewline(ls) && ls->current != old) + next(ls); /* skip '\n\r' or '\r\n' */ + if (++ls->linenumber >= MAX_INT) + lexerror(ls, "chunk has too many lines", 0); +} + + +void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, + int firstchar) { + ls->t.token = 0; + ls->L = L; + ls->current = firstchar; + ls->lookahead.token = TK_EOS; /* no look-ahead token */ + ls->z = z; + ls->fs = NULL; + ls->linenumber = 1; + ls->lastline = 1; + ls->source = source; + ls->envn = luaS_newliteral(L, LUA_ENV); /* get env name */ + luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ +} + + + +/* +** ======================================================= +** LEXICAL ANALYZER +** ======================================================= +*/ + + +static int check_next1 (LexState *ls, int c) { + if (ls->current == c) { + next(ls); + return 1; + } + else return 0; +} + + +/* +** Check whether current char is in set 'set' (with two chars) and +** saves it +*/ +static int check_next2 (LexState *ls, const char *set) { + lua_assert(set[2] == '\0'); + if (ls->current == set[0] || ls->current == set[1]) { + save_and_next(ls); + return 1; + } + else return 0; +} + + +/* LUA_NUMBER */ +/* +** this function is quite liberal in what it accepts, as 'luaO_str2num' +** will reject ill-formed numerals. +*/ +static int read_numeral (LexState *ls, SemInfo *seminfo) { + TValue obj; + const char *expo = "Ee"; + int first = ls->current; + lua_assert(lisdigit(ls->current)); + save_and_next(ls); + if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */ + expo = "Pp"; + for (;;) { + if (check_next2(ls, expo)) /* exponent part? */ + check_next2(ls, "-+"); /* optional exponent sign */ + if (lisxdigit(ls->current)) + save_and_next(ls); + else if (ls->current == '.') + save_and_next(ls); + else break; + } + save(ls, '\0'); + if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */ + lexerror(ls, "malformed number", TK_FLT); + if (ttisinteger(&obj)) { + seminfo->i = ivalue(&obj); + return TK_INT; + } + else { + lua_assert(ttisfloat(&obj)); + seminfo->r = fltvalue(&obj); + return TK_FLT; + } +} + + +/* +** skip a sequence '[=*[' or ']=*]'; if sequence is well formed, return +** its number of '='s; otherwise, return a negative number (-1 iff there +** are no '='s after initial bracket) +*/ +static int skip_sep (LexState *ls) { + int count = 0; + int s = ls->current; + lua_assert(s == '[' || s == ']'); + save_and_next(ls); + while (ls->current == '=') { + save_and_next(ls); + count++; + } + return (ls->current == s) ? count : (-count) - 1; +} + + +static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { + int line = ls->linenumber; /* initial line (for error message) */ + save_and_next(ls); /* skip 2nd '[' */ + if (currIsNewline(ls)) /* string starts with a newline? */ + inclinenumber(ls); /* skip it */ + for (;;) { + switch (ls->current) { + case EOZ: { /* error */ + const char *what = (seminfo ? "string" : "comment"); + const char *msg = luaO_pushfstring(ls->L, + "unfinished long %s (starting at line %d)", what, line); + lexerror(ls, msg, TK_EOS); + break; /* to avoid warnings */ + } + case ']': { + if (skip_sep(ls) == sep) { + save_and_next(ls); /* skip 2nd ']' */ + goto endloop; + } + break; + } + case '\n': case '\r': { + save(ls, '\n'); + inclinenumber(ls); + if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ + break; + } + default: { + if (seminfo) save_and_next(ls); + else next(ls); + } + } + } endloop: + if (seminfo) + seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep), + luaZ_bufflen(ls->buff) - 2*(2 + sep)); +} + + +static void esccheck (LexState *ls, int c, const char *msg) { + if (!c) { + if (ls->current != EOZ) + save_and_next(ls); /* add current to buffer for error message */ + lexerror(ls, msg, TK_STRING); + } +} + + +static int gethexa (LexState *ls) { + save_and_next(ls); + esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected"); + return luaO_hexavalue(ls->current); +} + + +static int readhexaesc (LexState *ls) { + int r = gethexa(ls); + r = (r << 4) + gethexa(ls); + luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */ + return r; +} + + +static unsigned long readutf8esc (LexState *ls) { + unsigned long r; + int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */ + save_and_next(ls); /* skip 'u' */ + esccheck(ls, ls->current == '{', "missing '{'"); + r = gethexa(ls); /* must have at least one digit */ + while ((save_and_next(ls), lisxdigit(ls->current))) { + i++; + r = (r << 4) + luaO_hexavalue(ls->current); + esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large"); + } + esccheck(ls, ls->current == '}', "missing '}'"); + next(ls); /* skip '}' */ + luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */ + return r; +} + + +static void utf8esc (LexState *ls) { + char buff[UTF8BUFFSZ]; + int n = luaO_utf8esc(buff, readutf8esc(ls)); + for (; n > 0; n--) /* add 'buff' to string */ + save(ls, buff[UTF8BUFFSZ - n]); +} + + +static int readdecesc (LexState *ls) { + int i; + int r = 0; /* result accumulator */ + for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */ + r = 10*r + ls->current - '0'; + save_and_next(ls); + } + esccheck(ls, r <= UCHAR_MAX, "decimal escape too large"); + luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */ + return r; +} + + +static void read_string (LexState *ls, int del, SemInfo *seminfo) { + save_and_next(ls); /* keep delimiter (for error messages) */ + while (ls->current != del) { + switch (ls->current) { + case EOZ: + lexerror(ls, "unfinished string", TK_EOS); + break; /* to avoid warnings */ + case '\n': + case '\r': + lexerror(ls, "unfinished string", TK_STRING); + break; /* to avoid warnings */ + case '\\': { /* escape sequences */ + int c; /* final character to be saved */ + save_and_next(ls); /* keep '\\' for error messages */ + switch (ls->current) { + case 'a': c = '\a'; goto read_save; + case 'b': c = '\b'; goto read_save; + case 'f': c = '\f'; goto read_save; + case 'n': c = '\n'; goto read_save; + case 'r': c = '\r'; goto read_save; + case 't': c = '\t'; goto read_save; + case 'v': c = '\v'; goto read_save; + case 'x': c = readhexaesc(ls); goto read_save; + case 'u': utf8esc(ls); goto no_save; + case '\n': case '\r': + inclinenumber(ls); c = '\n'; goto only_save; + case '\\': case '\"': case '\'': + c = ls->current; goto read_save; + case EOZ: goto no_save; /* will raise an error next loop */ + case 'z': { /* zap following span of spaces */ + luaZ_buffremove(ls->buff, 1); /* remove '\\' */ + next(ls); /* skip the 'z' */ + while (lisspace(ls->current)) { + if (currIsNewline(ls)) inclinenumber(ls); + else next(ls); + } + goto no_save; + } + default: { + esccheck(ls, lisdigit(ls->current), "invalid escape sequence"); + c = readdecesc(ls); /* digital escape '\ddd' */ + goto only_save; + } + } + read_save: + next(ls); + /* go through */ + only_save: + luaZ_buffremove(ls->buff, 1); /* remove '\\' */ + save(ls, c); + /* go through */ + no_save: break; + } + default: + save_and_next(ls); + } + } + save_and_next(ls); /* skip delimiter */ + seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, + luaZ_bufflen(ls->buff) - 2); +} + + +static int llex (LexState *ls, SemInfo *seminfo) { + luaZ_resetbuffer(ls->buff); + for (;;) { + switch (ls->current) { + case '\n': case '\r': { /* line breaks */ + inclinenumber(ls); + break; + } + case ' ': case '\f': case '\t': case '\v': { /* spaces */ + next(ls); + break; + } + case '-': { /* '-' or '--' (comment) */ + next(ls); + if (ls->current != '-') return '-'; + /* else is a comment */ + next(ls); + if (ls->current == '[') { /* long comment? */ + int sep = skip_sep(ls); + luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */ + if (sep >= 0) { + read_long_string(ls, NULL, sep); /* skip long comment */ + luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ + break; + } + } + /* else short comment */ + while (!currIsNewline(ls) && ls->current != EOZ) + next(ls); /* skip until end of line (or end of file) */ + break; + } + case '[': { /* long string or simply '[' */ + int sep = skip_sep(ls); + if (sep >= 0) { + read_long_string(ls, seminfo, sep); + return TK_STRING; + } + else if (sep != -1) /* '[=...' missing second bracket */ + lexerror(ls, "invalid long string delimiter", TK_STRING); + return '['; + } + case '=': { + next(ls); + if (check_next1(ls, '=')) return TK_EQ; + else return '='; + } + case '<': { + next(ls); + if (check_next1(ls, '=')) return TK_LE; + else if (check_next1(ls, '<')) return TK_SHL; + else return '<'; + } + case '>': { + next(ls); + if (check_next1(ls, '=')) return TK_GE; + else if (check_next1(ls, '>')) return TK_SHR; + else return '>'; + } + case '/': { + next(ls); + if (check_next1(ls, '/')) return TK_IDIV; + else return '/'; + } + case '~': { + next(ls); + if (check_next1(ls, '=')) return TK_NE; + else return '~'; + } + case ':': { + next(ls); + if (check_next1(ls, ':')) return TK_DBCOLON; + else return ':'; + } + case '"': case '\'': { /* short literal strings */ + read_string(ls, ls->current, seminfo); + return TK_STRING; + } + case '.': { /* '.', '..', '...', or number */ + save_and_next(ls); + if (check_next1(ls, '.')) { + if (check_next1(ls, '.')) + return TK_DOTS; /* '...' */ + else return TK_CONCAT; /* '..' */ + } + else if (!lisdigit(ls->current)) return '.'; + else return read_numeral(ls, seminfo); + } + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + return read_numeral(ls, seminfo); + } + case EOZ: { + return TK_EOS; + } + default: { + if (lislalpha(ls->current)) { /* identifier or reserved word? */ + TString *ts; + do { + save_and_next(ls); + } while (lislalnum(ls->current)); + ts = luaX_newstring(ls, luaZ_buffer(ls->buff), + luaZ_bufflen(ls->buff)); + seminfo->ts = ts; + if (isreserved(ts)) /* reserved word? */ + return ts->extra - 1 + FIRST_RESERVED; + else { + return TK_NAME; + } + } + else { /* single-char tokens (+ - / ...) */ + int c = ls->current; + next(ls); + return c; + } + } + } + } +} + + +void luaX_next (LexState *ls) { + ls->lastline = ls->linenumber; + if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ + ls->t = ls->lookahead; /* use this one */ + ls->lookahead.token = TK_EOS; /* and discharge it */ + } + else + ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ +} + + +int luaX_lookahead (LexState *ls) { + lua_assert(ls->lookahead.token == TK_EOS); + ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); + return ls->lookahead.token; +} + diff --git a/components/lua/lua-5.3/llex.h b/components/lua/lua-5.3/llex.h new file mode 100644 index 00000000..c7cc30ea --- /dev/null +++ b/components/lua/lua-5.3/llex.h @@ -0,0 +1,86 @@ +/* +** $Id: llex.h,v 1.79.1.1 2017/04/19 17:20:42 roberto Exp $ +** Lexical Analyzer +** See Copyright Notice in lua.h +*/ + +#ifndef llex_h +#define llex_h + +#include "lobject.h" +#include "lzio.h" + + +#define FIRST_RESERVED 257 + + +#if !defined(LUA_ENV) +#define LUA_ENV "_ENV" +#endif + + +/* +* WARNING: if you change the order of this enumeration, +* grep "ORDER RESERVED" +*/ +enum RESERVED { + /* terminal symbols denoted by reserved words */ + TK_AND = FIRST_RESERVED, TK_BREAK, + TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, + TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, + TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, + /* other terminal symbols */ + TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, + TK_SHL, TK_SHR, + TK_DBCOLON, TK_EOS, + TK_FLT, TK_INT, TK_NAME, TK_STRING +}; + +/* number of reserved words */ +#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1)) + + +typedef union { + lua_Number r; + lua_Integer i; + TString *ts; +} SemInfo; /* semantics information */ + + +typedef struct Token { + int token; + SemInfo seminfo; +} Token; + + +/* state of the lexer plus state of the parser when shared by all + functions */ +typedef struct LexState { + int current; /* current character (charint) */ + int linenumber; /* input line counter */ + int lastline; /* line of last token 'consumed' */ + Token t; /* current token */ + Token lookahead; /* look ahead token */ + struct FuncState *fs; /* current function (parser) */ + struct lua_State *L; + ZIO *z; /* input stream */ + Mbuffer *buff; /* buffer for tokens */ + Table *h; /* to avoid collection/reuse strings */ + struct Dyndata *dyd; /* dynamic structures used by the parser */ + TString *source; /* current source name */ + TString *envn; /* environment variable name */ +} LexState; + + +LUAI_FUNC void luaX_init (lua_State *L); +LUAI_FUNC const char *luaX_getstr (unsigned int i, int *extra); +LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, + TString *source, int firstchar); +LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l); +LUAI_FUNC void luaX_next (LexState *ls); +LUAI_FUNC int luaX_lookahead (LexState *ls); +LUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s); +LUAI_FUNC const char *luaX_token2str (LexState *ls, int token); + + +#endif diff --git a/components/lua/lua-5.3/llimits.h b/components/lua/lua-5.3/llimits.h new file mode 100644 index 00000000..f9855b1c --- /dev/null +++ b/components/lua/lua-5.3/llimits.h @@ -0,0 +1,337 @@ +/* +** $Id: llimits.h,v 1.141.1.1 2017/04/19 17:20:42 roberto Exp $ +** Limits, basic types, and some other 'installation-dependent' definitions +** See Copyright Notice in lua.h +*/ + +#ifndef llimits_h +#define llimits_h + + +#include +#include +#include + + +#include "lua.h" + +/* +** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count +** the total memory used by Lua (in bytes). Usually, 'size_t' and +** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines. +*/ +#if defined(LUAI_MEM) /* { external definitions? */ +typedef LUAI_UMEM lu_mem; +typedef LUAI_MEM l_mem; +#elif LUAI_BITSINT >= 32 /* }{ */ +typedef size_t lu_mem; +typedef ptrdiff_t l_mem; +#else /* 16-bit ints */ /* }{ */ +typedef unsigned long lu_mem; +typedef long l_mem; +#endif /* } */ + + +/* chars used as small naturals (so that 'char' is reserved for characters) */ +typedef unsigned char lu_byte; + +/* unsigned 32 bit integers are core the the ESP architectures so we have a type specficially addressing this */ +typedef uint32_t lu_int32; + +/* maximum value for size_t */ +#define MAX_SIZET ((size_t)(~(size_t)0)) + +/* maximum size visible for Lua (must be representable in a lua_Integer */ +#define MAX_SIZE (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \ + : (size_t)(LUA_MAXINTEGER)) + + +#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)) + +#define MAX_LMEM ((l_mem)(MAX_LUMEM >> 1)) + + +#define MAX_INT INT_MAX /* maximum value of an int */ + + +/* +** conversion of pointer to unsigned integer: +** this is for hashing only; there is no problem if the integer +** cannot hold the whole pointer value +*/ +#define point2uint(p) ((unsigned int)((size_t)(p) & UINT_MAX)) + + + +/* type to ensure maximum alignment */ +#if defined(LUAI_USER_ALIGNMENT_T) +typedef LUAI_USER_ALIGNMENT_T L_Umaxalign; +#else +typedef union { + lua_Number n; + double u; + void *s; + lua_Integer i; + long l; +} L_Umaxalign; +#endif + + + +/* types of 'usual argument conversions' for lua_Number and lua_Integer */ +typedef LUAI_UACNUMBER l_uacNumber; +typedef LUAI_UACINT l_uacInt; + +#if defined(DEVELOPMENT_USE_GDB) && !defined(lua_assert) +# define lua_assert(c) ((c) ? (void) 0 : lua_debugbreak()) +#endif + +/* internal assertions for in-house debugging */ +#if defined(lua_assert) +#define check_exp(c,e) (lua_assert(c), (e)) +/* to avoid problems with conditions too long */ +#define lua_longassert(c) ((c) ? (void)0 : lua_assert(0)) +#else +#define lua_assert(c) ((void)0) +#define check_exp(c,e) (e) +#define lua_longassert(c) ((void)0) +#endif + +/* +** assertion for checking API calls +*/ +#if !defined(luai_apicheck) +#define luai_apicheck(l,e) lua_assert(e) +#endif + +#define api_check(l,e,msg) luai_apicheck(l,(e) && msg) + + +/* macro to avoid warnings about unused variables */ +#if !defined(UNUSED) +#define UNUSED(x) ((void)(x)) +#endif + + +/* type casts (a macro highlights casts in the code) */ +#define cast(t, exp) ((t)(exp)) + +#define cast_void(i) cast(void, (i)) +#define cast_byte(i) cast(lu_byte, (i)) +#define cast_num(i) cast(lua_Number, (i)) +#define cast_int(i) cast(int, (i)) +#define cast_uchar(i) cast(unsigned char, (i)) + + +/* cast a signed lua_Integer to lua_Unsigned */ +#if !defined(l_castS2U) +#define l_castS2U(i) ((lua_Unsigned)(i)) +#endif + +/* +** cast a lua_Unsigned to a signed lua_Integer; this cast is +** not strict ISO C, but two-complement architectures should +** work fine. +*/ +#if !defined(l_castU2S) +#define l_castU2S(i) ((lua_Integer)(i)) +#endif + + +/* +** non-return type +*/ +#if defined(__GNUC__) +#define l_noret void __attribute__((noreturn)) +#elif defined(_MSC_VER) && _MSC_VER >= 1200 +#define l_noret void __declspec(noreturn) +#else +#define l_noret void +#endif + + + +/* +** maximum depth for nested C calls and syntactical nested non-terminals +** in a program. (Value must fit in an unsigned short int.) +*/ +#if !defined(LUAI_MAXCCALLS) +#define LUAI_MAXCCALLS 200 +#endif + + + +/* +** type for virtual-machine instructions; +** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h) +*/ +#if LUAI_BITSINT >= 32 +typedef unsigned int Instruction; +#else +typedef unsigned long Instruction; +#endif + + + +/* +** Maximum length for short strings, that is, strings that are +** internalized. (Cannot be smaller than reserved words or tags for +** metamethods, as these strings must be internalized; +** #("function") = 8, #("__newindex") = 10.) +*/ +#if !defined(LUAI_MAXSHORTLEN) +#define LUAI_MAXSHORTLEN 40 +#endif + + +/* +** Initial size for the string table (must be power of 2). +** The Lua core alone registers ~50 strings (reserved words + +** metaevent keys + a few others). Libraries would typically add +** a few dozens more. +*/ +#if !defined(MINSTRTABSIZE) +#define MINSTRTABSIZE 128 +#endif + + +/* +** Size of cache for strings in the API. 'N' is the number of +** sets (better be a prime) and "M" is the size of each set (M == 1 +** makes a direct cache.) +*/ +#if !defined(KEYCACHE_N) +#define KEYCACHE_N 32 +#define KEYCACHE_M 4 +#endif + + +/* minimum size for string buffer */ +#if !defined(LUA_MINBUFFER) +#define LUA_MINBUFFER 32 +#endif + + +/* +** macros that are executed whenever program enters the Lua core +** ('lua_lock') and leaves the core ('lua_unlock') +*/ +#if !defined(lua_lock) +#define lua_lock(L) ((void) 0) +#define lua_unlock(L) ((void) 0) +#endif + +/* +** macro executed during Lua functions at points where the +** function can yield. +*/ +#if !defined(luai_threadyield) +#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} +#endif + + +/* +** these macros allow user-specific actions on threads when you defined +** LUAI_EXTRASPACE and need to do something extra when a thread is +** created/deleted/resumed/yielded. +*/ +#if !defined(luai_userstateopen) +#define luai_userstateopen(L) ((void)L) +#endif + +#if !defined(luai_userstateclose) +#define luai_userstateclose(L) ((void)L) +#endif + +#if !defined(luai_userstatethread) +#define luai_userstatethread(L,L1) ((void)L) +#endif + +#if !defined(luai_userstatefree) +#define luai_userstatefree(L,L1) ((void)L) +#endif + +#if !defined(luai_userstateresume) +#define luai_userstateresume(L,n) ((void)L) +#endif + +#if !defined(luai_userstateyield) +#define luai_userstateyield(L,n) ((void)L) +#endif + + + +/* +** The luai_num* macros define the primitive operations over numbers. +*/ + +/* floor division (defined as 'floor(a/b)') */ +#if !defined(luai_numidiv) +#define luai_numidiv(L,a,b) ((void)L, l_floor(luai_numdiv(L,a,b))) +#endif + +/* float division */ +#if !defined(luai_numdiv) +#define luai_numdiv(L,a,b) ((a)/(b)) +#endif + +/* +** modulo: defined as 'a - floor(a/b)*b'; this definition gives NaN when +** 'b' is huge, but the result should be 'a'. 'fmod' gives the result of +** 'a - trunc(a/b)*b', and therefore must be corrected when 'trunc(a/b) +** ~= floor(a/b)'. That happens when the division has a non-integer +** negative result, which is equivalent to the test below. +*/ +#ifdef LUA_USE_ESP8266 +#define luai_nummod(L,a,b,m) do { \ + if (b==0) luaG_runerror(L,"modulo by zero"); \ + (m) = (a) - floor((a)/(b))*(b); \ + if ((m)*(b) < 0) (m) += (b); \ +} while (0) +#endif + +#if !defined(luai_nummod) +#define luai_nummod(L,a,b,m) \ + { (m) = l_mathop(fmod)(a,b); if ((m)*(b) < 0) (m) += (b); } +#endif + +/* exponentiation */ +#if !defined(luai_numpow) +#define luai_numpow(L,a,b) ((void)L, l_mathop(pow)(a,b)) +#endif + +/* the others are quite standard operations */ +#if !defined(luai_numadd) +#define luai_numadd(L,a,b) ((a)+(b)) +#define luai_numsub(L,a,b) ((a)-(b)) +#define luai_nummul(L,a,b) ((a)*(b)) +#define luai_numunm(L,a) (-(a)) +#define luai_numeq(a,b) ((a)==(b)) +#define luai_numlt(a,b) ((a)<(b)) +#define luai_numle(a,b) ((a)<=(b)) +#define luai_numisnan(a) (!luai_numeq((a), (a))) +#endif + + + + + +/* +** macro to control inclusion of some hard tests on stack reallocation +*/ +#if !defined(HARDSTACKTESTS) +#define condmovestack(L,pre,pos) ((void)0) +#else +/* realloc stack keeping its size */ +#define condmovestack(L,pre,pos) \ + { int sz_ = (L)->stacksize; pre; luaD_reallocstack((L), sz_); pos; } +#endif + +#if !defined(HARDMEMTESTS) +#define condchangemem(L,pre,pos) ((void)0) +#else +#define condchangemem(L,pre,pos) \ + { if (G(L)->gcrunning) { pre; luaC_fullgc(L, 0); pos; } } +#endif + +#endif diff --git a/components/lua/lua-5.3/lmathlib.c b/components/lua/lua-5.3/lmathlib.c new file mode 100644 index 00000000..352249cb --- /dev/null +++ b/components/lua/lua-5.3/lmathlib.c @@ -0,0 +1,400 @@ +/* +** $Id: lmathlib.c,v 1.119.1.1 2017/04/19 17:20:42 roberto Exp $ +** Standard mathematical library +** See Copyright Notice in lua.h +*/ + +#define lmathlib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + +#undef PI +#define PI (l_mathop(3.141592653589793238462643383279502884)) + + +#if !defined(l_rand) /* { */ +#if defined(LUA_USE_POSIX) +#define l_rand() random() +#define l_srand(x) srandom(x) +#define L_RANDMAX 2147483647 /* (2^31 - 1), following POSIX */ +#else +#define l_rand() rand() +#define l_srand(x) srand(x) +#define L_RANDMAX RAND_MAX +#endif +#endif /* } */ + + +static int math_abs (lua_State *L) { + if (lua_isinteger(L, 1)) { + lua_Integer n = lua_tointeger(L, 1); + if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n); + lua_pushinteger(L, n); + } + else + lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_sin (lua_State *L) { + lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_cos (lua_State *L) { + lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_tan (lua_State *L) { + lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_asin (lua_State *L) { + lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_acos (lua_State *L) { + lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_atan (lua_State *L) { + lua_Number y = luaL_checknumber(L, 1); + lua_Number x = luaL_optnumber(L, 2, 1); + lua_pushnumber(L, l_mathop(atan2)(y, x)); + return 1; +} + + +static int math_toint (lua_State *L) { + int valid; + lua_Integer n = lua_tointegerx(L, 1, &valid); + if (valid) + lua_pushinteger(L, n); + else { + luaL_checkany(L, 1); + lua_pushnil(L); /* value is not convertible to integer */ + } + return 1; +} + + +static void pushnumint (lua_State *L, lua_Number d) { + lua_Integer n; + if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */ + lua_pushinteger(L, n); /* result is integer */ + else + lua_pushnumber(L, d); /* result is float */ +} + + +static int math_floor (lua_State *L) { + if (lua_isinteger(L, 1)) + lua_settop(L, 1); /* integer is its own floor */ + else { + lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1)); + pushnumint(L, d); + } + return 1; +} + + +static int math_ceil (lua_State *L) { + if (lua_isinteger(L, 1)) + lua_settop(L, 1); /* integer is its own ceil */ + else { + lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1)); + pushnumint(L, d); + } + return 1; +} + + +static int math_fmod (lua_State *L) { + if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) { + lua_Integer d = lua_tointeger(L, 2); + if ((lua_Unsigned)d + 1u <= 1u) { /* special cases: -1 or 0 */ + luaL_argcheck(L, d != 0, 2, "zero"); + lua_pushinteger(L, 0); /* avoid overflow with 0x80000... / -1 */ + } + else + lua_pushinteger(L, lua_tointeger(L, 1) % d); + } else { + lua_Number m, a=luaL_checknumber(L, 1), b=luaL_checknumber(L, 2); + if (b==0) luaL_error(L,"modulo by zero"); + m = a/b; + lua_pushnumber(L, a - b*(m > 0.0 ? floor(m) : ceil(m))); + } + return 1; +} + + +/* +** next function does not use 'modf', avoiding problems with 'double*' +** (which is not compatible with 'float*') when lua_Number is not +** 'double'. +*/ +static int math_modf (lua_State *L) { + if (lua_isinteger(L ,1)) { + lua_settop(L, 1); /* number is its own integer part */ + lua_pushnumber(L, 0); /* no fractional part */ + } + else { + lua_Number n = luaL_checknumber(L, 1); + /* integer part (rounds toward zero) */ + lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n); + pushnumint(L, ip); + /* fractional part (test needed for inf/-inf) */ + lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip)); + } + return 2; +} + + +static int math_sqrt (lua_State *L) { + lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1))); + return 1; +} + + +static int math_ult (lua_State *L) { + lua_Integer a = luaL_checkinteger(L, 1); + lua_Integer b = luaL_checkinteger(L, 2); + lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b); + return 1; +} + +static int math_log (lua_State *L) { + lua_Number x = luaL_checknumber(L, 1); + lua_Number res; + if (lua_isnoneornil(L, 2)) + res = l_mathop(log)(x); + else { + lua_Number base = luaL_checknumber(L, 2); +#if !defined(LUA_USE_C89) + if (base == l_mathop(2.0)) + res = l_mathop(log2)(x); else +#endif + if (base == l_mathop(10.0)) + res = l_mathop(log10)(x); + else + res = l_mathop(log)(x)/l_mathop(log)(base); + } + lua_pushnumber(L, res); + return 1; +} + +static int math_exp (lua_State *L) { + lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_deg (lua_State *L) { + lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI)); + return 1; +} + +static int math_rad (lua_State *L) { + lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0))); + return 1; +} + + +static int math_min (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int imin = 1; /* index of current minimum value */ + int i; + luaL_argcheck(L, n >= 1, 1, "value expected"); + for (i = 2; i <= n; i++) { + if (lua_compare(L, i, imin, LUA_OPLT)) + imin = i; + } + lua_pushvalue(L, imin); + return 1; +} + + +static int math_max (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int imax = 1; /* index of current maximum value */ + int i; + luaL_argcheck(L, n >= 1, 1, "value expected"); + for (i = 2; i <= n; i++) { + if (lua_compare(L, imax, i, LUA_OPLT)) + imax = i; + } + lua_pushvalue(L, imax); + return 1; +} + +/* +** This function uses 'double' (instead of 'lua_Number') to ensure that +** all bits from 'l_rand' can be represented, and that 'RANDMAX + 1.0' +** will keep full precision (ensuring that 'r' is always less than 1.0.) +*/ +static int math_random (lua_State *L) { + lua_Integer low, up; + double r = (double)l_rand() * (1.0 / ((double)L_RANDMAX + 1.0)); + switch (lua_gettop(L)) { /* check number of arguments */ + case 0: { /* no arguments */ + lua_pushnumber(L, (lua_Number)r); /* Number between 0 and 1 */ + return 1; + } + case 1: { /* only upper limit */ + low = 1; + up = luaL_checkinteger(L, 1); + break; + } + case 2: { /* lower and upper limits */ + low = luaL_checkinteger(L, 1); + up = luaL_checkinteger(L, 2); + break; + } + default: return luaL_error(L, "wrong number of arguments"); + } + /* random integer in the interval [low, up] */ + luaL_argcheck(L, low <= up, 1, "interval is empty"); + luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1, + "interval too large"); + r *= (double)(up - low) + 1.0; + lua_pushinteger(L, (lua_Integer)r + low); + return 1; +} + + +static int math_randomseed (lua_State *L) { + l_srand((unsigned int)(lua_Integer)luaL_checknumber(L, 1)); + (void)l_rand(); /* discard first value to avoid undesirable correlations */ + return 0; +} + + +static int math_type (lua_State *L) { + if (lua_type(L, 1) == LUA_TNUMBER) { + if (lua_isinteger(L, 1)) + lua_pushliteral(L, "integer"); + else + lua_pushliteral(L, "float"); + } + else { + luaL_checkany(L, 1); + lua_pushnil(L); + } + return 1; +} + + +/* +** {================================================================== +** Deprecated functions (for compatibility only) +** =================================================================== +*/ +#if defined(LUA_COMPAT_MATHLIB) + +static int math_cosh (lua_State *L) { + lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_sinh (lua_State *L) { + lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_tanh (lua_State *L) { + lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_pow (lua_State *L) { + lua_Number x = luaL_checknumber(L, 1); + lua_Number y = luaL_checknumber(L, 2); + lua_pushnumber(L, l_mathop(pow)(x, y)); + return 1; +} + +static int math_frexp (lua_State *L) { + int e; + lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e)); + lua_pushinteger(L, e); + return 2; +} + +static int math_ldexp (lua_State *L) { + lua_Number x = luaL_checknumber(L, 1); + int ep = (int)luaL_checkinteger(L, 2); + lua_pushnumber(L, l_mathop(ldexp)(x, ep)); + return 1; +} + +static int math_log10 (lua_State *L) { + lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1))); + return 1; +} + +#endif +/* }================================================================== */ + + +LROT_BEGIN(mathlib, NULL, 0) + LROT_FUNCENTRY( abs, math_abs) + LROT_FUNCENTRY( acos, math_acos) + LROT_FUNCENTRY( asin, math_asin) + LROT_FUNCENTRY( atan, math_atan) + LROT_FUNCENTRY( ceil, math_ceil) + LROT_FUNCENTRY( cos, math_cos) + LROT_FUNCENTRY( deg, math_deg) + LROT_FUNCENTRY( exp, math_exp) + LROT_FUNCENTRY( tointeger, math_toint) + LROT_FUNCENTRY( floor, math_floor) + LROT_FUNCENTRY( fmod, math_fmod) + LROT_FUNCENTRY( ult, math_ult) + LROT_FUNCENTRY( log, math_log) + LROT_FUNCENTRY( max, math_max) + LROT_FUNCENTRY( min, math_min) + LROT_FUNCENTRY( modf, math_modf) + LROT_FUNCENTRY( rad, math_rad) + LROT_FUNCENTRY( random, math_random) + LROT_FUNCENTRY( randomseed, math_randomseed) + LROT_FUNCENTRY( sin, math_sin) + LROT_FUNCENTRY( sqrt, math_sqrt) + LROT_FUNCENTRY( tan, math_tan) + LROT_FUNCENTRY( type, math_type) +#if defined(LUA_COMPAT_MATHLIB) + LROT_FUNCENTRY( atan2, math_atan) + LROT_FUNCENTRY( cosh, math_cosh) + LROT_FUNCENTRY( sinh, math_sinh) + LROT_FUNCENTRY( tanh, math_tanh) + LROT_FUNCENTRY( pow, math_pow) + LROT_FUNCENTRY( frexp, math_frexp) + LROT_FUNCENTRY( ldexp, math_ldexp) + LROT_FUNCENTRY( log10, math_log10) +#endif + LROT_FLOATENTRY( pi, PI) + LROT_FLOATENTRY( huge,(lua_Number)HUGE_VAL) + LROT_INTENTRY( maxinteger, LUA_MAXINTEGER) + LROT_INTENTRY( mininteger, LUA_MININTEGER) +LROT_END(mathlib, NULL, 0) + + +/* +** Open math library +*/ +LUAMOD_API int luaopen_math (lua_State *L) { + (void)L; + return 0; +} + diff --git a/components/lua/lua-5.3/lmem.c b/components/lua/lua-5.3/lmem.c new file mode 100644 index 00000000..0241cc3b --- /dev/null +++ b/components/lua/lua-5.3/lmem.c @@ -0,0 +1,100 @@ +/* +** $Id: lmem.c,v 1.91.1.1 2017/04/19 17:20:42 roberto Exp $ +** Interface to Memory Manager +** See Copyright Notice in lua.h +*/ + +#define lmem_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" + + + +/* +** About the realloc function: +** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize); +** ('osize' is the old size, 'nsize' is the new size) +** +** * frealloc(ud, NULL, x, s) creates a new block of size 's' (no +** matter 'x'). +** +** * frealloc(ud, p, x, 0) frees the block 'p' +** (in this specific case, frealloc must return NULL); +** particularly, frealloc(ud, NULL, 0, 0) does nothing +** (which is equivalent to free(NULL) in ISO C) +** +** frealloc returns NULL if it cannot create or reallocate the area +** (any reallocation to an equal or smaller size cannot fail!) +*/ + + + +#define MINSIZEARRAY 4 + + +void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems, + int limit, const char *what) { + void *newblock; + int newsize; + if (*size >= limit/2) { /* cannot double it? */ + if (*size >= limit) /* cannot grow even a little? */ + luaG_runerror(L, "too many %s (limit is %d)", what, limit); + newsize = limit; /* still have at least one free place */ + } + else { + newsize = (*size)*2; + if (newsize < MINSIZEARRAY) + newsize = MINSIZEARRAY; /* minimum size */ + } + newblock = luaM_reallocv(L, block, *size, newsize, size_elems); + *size = newsize; /* update only when everything else is OK */ + return newblock; +} + + +l_noret luaM_toobig (lua_State *L) { + luaG_runerror(L, "memory allocation error: block too big"); +} + + + +/* +** generic allocation routine. +*/ +void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { + void *newblock; + global_State *g = G(L); + size_t realosize = (block) ? osize : 0; + lua_assert((realosize == 0) == (block == NULL)); +#if defined(HARDMEMTESTS) + if (nsize > realosize && g->gcrunning) + luaC_fullgc(L, 1); /* force a GC whenever possible */ +#endif + newblock = (*g->frealloc)(g->ud, block, osize, nsize); + if (newblock == NULL && nsize > 0) { + lua_assert(nsize > realosize); /* cannot fail when shrinking a block */ + if (g->version) { /* is state fully built? */ + luaC_fullgc(L, 1); /* try to free some memory... */ + newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */ + } + if (newblock == NULL) + luaD_throw(L, LUA_ERRMEM); + } + lua_assert((nsize == 0) == (newblock == NULL)); + g->GCdebt = (g->GCdebt + nsize) - realosize; + return newblock; +} + diff --git a/components/lua/lua-5.3/lmem.h b/components/lua/lua-5.3/lmem.h new file mode 100644 index 00000000..357b1e43 --- /dev/null +++ b/components/lua/lua-5.3/lmem.h @@ -0,0 +1,69 @@ +/* +** $Id: lmem.h,v 1.43.1.1 2017/04/19 17:20:42 roberto Exp $ +** Interface to Memory Manager +** See Copyright Notice in lua.h +*/ + +#ifndef lmem_h +#define lmem_h + + +#include + +#include "llimits.h" +#include "lua.h" + + +/* +** This macro reallocs a vector 'b' from 'on' to 'n' elements, where +** each element has size 'e'. In case of arithmetic overflow of the +** product 'n'*'e', it raises an error (calling 'luaM_toobig'). Because +** 'e' is always constant, it avoids the runtime division MAX_SIZET/(e). +** +** (The macro is somewhat complex to avoid warnings: The 'sizeof' +** comparison avoids a runtime comparison when overflow cannot occur. +** The compiler should be able to optimize the real test by itself, but +** when it does it, it may give a warning about "comparison is always +** false due to limited range of data type"; the +1 tricks the compiler, +** avoiding this warning but also this optimization.) +*/ +#define luaM_reallocv(L,b,on,n,e) \ + (((sizeof(n) >= sizeof(size_t) && cast(size_t, (n)) + 1 > MAX_SIZET/(e)) \ + ? luaM_toobig(L) : cast_void(0)) , \ + luaM_realloc_(L, (b), (on)*(e), (n)*(e))) + +/* +** Arrays of chars do not need any test +*/ +#define luaM_reallocvchar(L,b,on,n) \ + cast(char *, luaM_realloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char))) + +#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0) +#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0) +#define luaM_freearray(L, b, n) luaM_realloc_(L, (b), (n)*sizeof(*(b)), 0) + +#define luaM_malloc(L,s) luaM_realloc_(L, NULL, 0, (s)) +#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t))) +#define luaM_newvector(L,n,t) \ + cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t))) + +#define luaM_newobject(L,tag,s) luaM_realloc_(L, NULL, tag, (s)) + +#define luaM_growvector(L,v,nelems,size,t,limit,e) \ + if ((nelems)+1 > (size)) \ + ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e))) + +#define luaM_reallocvector(L, v,oldn,n,t) \ + ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t)))) + +LUAI_FUNC l_noret luaM_toobig (lua_State *L); + +/* not to be called directly */ +LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, + size_t size); +LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size, + size_t size_elem, int limit, + const char *what); + +#endif + diff --git a/components/lua/lua-5.3/lnodemcu.c b/components/lua/lua-5.3/lnodemcu.c new file mode 100644 index 00000000..9816e781 --- /dev/null +++ b/components/lua/lua-5.3/lnodemcu.c @@ -0,0 +1,706 @@ +#define LUA_CORE +#include "lua.h" +#include +#include + +#include "lobject.h" +#include "lstate.h" +#include "lapi.h" +#include "lauxlib.h" +#include "lfunc.h" +#include "lgc.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lnodemcu.h" +#include "lundump.h" +#include "lzio.h" + +#include "lfs.h" + +#ifdef LUA_USE_ESP +#include "platform.h" +#include "vfs.h" +#include "task/task.h" +#else +// On the cross-compiler we do need the LFS reload mechanism, regardless +#undef CONFIG_NODEMCU_EMBEDDED_LFS_SIZE +#endif + +/* +** This is a mixed bag of NodeMCU additions broken into the following sections: +** * POSIX vs VFS file API abstraction +** * Emulate Platform_XXX() API +** * ESP and HOST lua_debugbreak() test stubs +** * NodeMCU lua.h LUA_API extensions +** * NodeMCU lauxlib.h LUALIB_API extensions +** * NodeMCU bootstrap to set up and to reimage LFS resources +** +** Just search down for //== or ==// to flip through the sections. +*/ + +#define byte_addr(p) cast(char *,p) +#define byteptr(p) cast(lu_byte *, p) +#define byteoffset(p,q) ((int) cast(ptrdiff_t, (byteptr(p) - byteptr(q)))) +#define wordptr(p) cast(lu_int32 *, p) +#define wordoffset(p,q) (wordptr(p) - wordptr(q)) + + +//====================== Wrap POSIX and VFS file API =========================// +#ifdef LUA_USE_ESP +int luaopen_file(lua_State *L); +# define l_file(f) int f +# define l_open(f) vfs_open(f, "r") +# define l_close(f) vfs_close(f) +# define l_feof(f) vfs_eof(f) +# define l_read(f,b) vfs_read(f, b, sizeof (b)) +# define l_rewind(f) vfs_lseek(f, 0, VFS_SEEK_SET) +#else +# define l_file(f) FILE *f +# define l_open(n) fopen(n,"rb") +# define l_close(f) fclose(f) +# define l_feof(f) feof(f) +# define l_read(f,b) fread(b, 1, sizeof (b), f) +# define l_rewind(f) rewind(f) +#endif + +#ifdef LUA_USE_ESP + +extern void dbg_printf(const char *fmt, ...); // DEBUG +#undef printf +#define printf(...) dbg_printf(__VA_ARGS__) // DEBUG + +#define FLASH_PAGE_SIZE INTERNAL_FLASH_SECTOR_SIZE +/* Erasing the LFS invalidates ESP instruction cache, so doing a block 64Kb */ +/* read is the simplest way to flush the icache, restoring cache coherency */ +#define flush_icache(F) \ + UNUSED(memcmp(F->addr, F->addr+(0x8000/sizeof(*F->addr)), 0x8000)); +#define unlockFlashWrite() +#define lockFlashWrite() + +#else // LUA_USE_HOST + +//==== Emulate Platform_XXX() API within host luac.cross -e environement =====// + +#include // DEBUG +/* +** The ESP implementation use a platform_XXX() API to provide a level of +** H/W abstraction. The following functions and macros emulate a subset +** of this API for the host environment. LFSregion is the true address in +** the luac process address space of the mapped LFS region. All actual +** erasing and writing is done relative to this address. +** +** In normal LFS emulation the LFSaddr is also set to this LFSregion address +** so that any subsequent execution using LFS refers to the correct memory +** address. +** +** The second LFS mode is used to create absolute LFS images for directly +** downloading to the ESP or including in a firmware image, and in this case +** LFSaddr refers to the actual ESP mapped address of the ESP LFS region. +** This is a 32-bit address typically in the address range 0x40210000-0x402FFFFF +** (and with the high 32bits set to 0 in the case of 64-bit execution). Such +** images are solely intended for ESP execution and any attempt to execute +** them in a host execution environment will result in an address exception. +*/ +#define PLATFORM_RCR_FLASHLFS 4 +#define LFS_SIZE 0x40000 +#define FLASH_PAGE_SIZE 0x1000 +#define FLASH_BASE 0x90000 /* Some 'Random' but typical value */ + +void *LFSregion = NULL; +static void *LFSaddr = NULL; +static size_t LFSbase = FLASH_BASE; +extern char *LFSimageName; + +#ifdef __unix__ +/* On POSIX systems we can toggle the "Flash" write attribute */ +#include +#define aligned_malloc(a,n) posix_memalign(&a, FLASH_PAGE_SIZE, (n)) +#define unlockFlashWrite() mprotect(LFSaddr, LFS_SIZE, PROT_READ| PROT_WRITE) +#define lockFlashWrite() mprotect(LFSaddr, LFS_SIZE, PROT_READ) +#else +#define aligned_malloc(a,n) ((a = malloc(n)) == NULL) +#define unlockFlashWrite() +#define lockFlashWrite() +#endif + +#define platform_flash_get_sector_of_address(n) ((n)>>12) + +void luaN_setabsolute(lu_int32 addr) { + LFSaddr = cast(void *, cast(intptr_t, addr)); + LFSbase = addr; +} + +bool lfs_get_location(lfs_location_info_t *out) +{ + if (!LFSregion) { + if(aligned_malloc(LFSregion, LFS_SIZE)) + return false; + memset(LFSregion, ~0, LFS_SIZE); + lockFlashWrite(); + } + if(LFSaddr == NULL) + LFSaddr = LFSregion; + + out->size = LFS_SIZE; + out->addr_mem = LFSaddr; + out->addr_phys = LFSbase; + return true; +} + +bool lfs_get_load_filename(char *buf, size_t bufsiz) +{ + if (LFSimageName) + strncpy(buf, LFSimageName, bufsiz); + else if (buf && bufsiz) + *buf = 0; + return true; +} + +bool lfs_clear_load_filename(void) +{ + LFSimageName = NULL; + return true; +} + +static void platform_flash_erase_sector(lu_int32 i) { + lua_assert (i >= LFSbase/FLASH_PAGE_SIZE && + i < (LFSbase+LFS_SIZE)/FLASH_PAGE_SIZE); + unlockFlashWrite(); + memset(byteptr(LFSregion) + (i*FLASH_PAGE_SIZE - LFSbase), ~(0), FLASH_PAGE_SIZE); + lockFlashWrite(); +} + +static void platform_s_flash_write(const void *from, lu_int32 to, lu_int32 len) { + lua_assert(to >= LFSbase && to + len < LFSbase + LFS_SIZE); /* DEBUG */ + unlockFlashWrite(); + memcpy(byteptr(LFSregion) + (to-LFSbase), from, len); + lockFlashWrite(); +} + +#define flush_icache(F) /* not needed */ + +#endif + +//============= ESP and HOST lua_debugbreak() test stubs =====================// + +#ifdef DEVELOPMENT_USE_GDB +/* + * lua_debugbreak is a stub used by lua_assert() if DEVELOPMENT_USE_GDB is + * defined. On the ESP, instead of crashing out with an assert error, this hook + * starts the GDB remote stub if not already running and then issues a break. + * The rationale here is that when testing the developer might be using screen / + * PuTTY to work interactively with the Lua Interpreter via UART0. However if + * an assert triggers, then there is the option to exit the interactive session + * and start the Xtensa remote GDB which will then sync up with the remote GDB + * client to allow forensics of the error. On the host it is an stub which can + * be set as a breakpoint in the gdb debugger. + */ +extern void gdbstub_init(void); +extern void gdbstub_redirect_output(int); + +LUALIB_API void lua_debugbreak(void) { +#ifdef LUA_USE_HOST + /* allows debug backtrace analysis of assert fails */ + lua_writestring(" lua_debugbreak ", sizeof(" lua_debugbreak ")-1); +#else + static int repeat_entry = 0; + if (repeat_entry == 0) { + dbg_printf("Start up the gdb stub if not already started\n"); + gdbstub_init(); + gdbstub_redirect_output(1); + repeat_entry = 1; + } + asm("break 0,0" ::); +#endif +} +#endif + +//===================== NodeMCU lua.h API extensions =========================// + +LUA_API int lua_freeheap (void) { +#ifdef LUA_USE_HOST + return MAX_INT; +#else + return (int)esp_get_free_heap_size(); +#endif +} + +LUA_API int lua_pushstringsarray(lua_State *L, int opt) { + stringtable *strt = NULL; + int i, j = 1; + + lua_lock(L); + if (opt == 0) + strt = &G(L)->strt; +#ifdef LUA_USE_ESP + else if (opt == 1 && G(L)->ROstrt.hash) + strt = &G(L)->ROstrt; +#endif + if (strt == NULL) { + setnilvalue(L->top); + api_incr_top(L); + lua_unlock(L); + return 0; + } + + Table *t = luaH_new(L); + sethvalue(L, L->top, t); + api_incr_top(L); + luaH_resize(L, t, strt->nuse, 0); + luaC_checkGC(L); + lua_unlock(L); + + /* loop around all strt hash entries */ + for (i = 0, j = 1; i < strt->size; i++) { + TString *e; + /* loop around all TStings in this entry's chain */ + for(e = strt->hash[i]; e; e = e->u.hnext) { + TValue s; + setsvalue(L, &s, e); + luaH_setint(L, hvalue(L->top-1), j++, &s); + } + } + return 1; +} + +LUA_API void lua_createrotable (lua_State *L, ROTable *t, + const ROTable_entry *e, ROTable *mt) { + int i, j; + lu_byte flags = ~0; + const char *plast = (char *)"_"; + for (i = 0; e[i].key; i++) { + if (e[i].key[0] == '_' && strcmp(e[i].key,plast)) { + plast = e[i].key; + lua_pushstring(L,e[i].key); + for (j=0; jtop-1)==G(L)->tmname[i]) { + flags |= cast_byte(1u<next = (GCObject *)1; + t->tt = LUA_TTBLROF; + t->marked = LROT_MARKED; + t->flags = flags; + t->lsizenode = i; + t->metatable = cast(Table *, mt); + t->entry = cast(ROTable_entry *, e); +} + +LUA_API void lua_getlfsconfig (lua_State *L, intptr_t *config) { + global_State *g = G(L); + LFSHeader *l = g->l_LFS; + if (!config) + return; + lfs_location_info_t lfs_loc; + if (lfs_get_location(&lfs_loc) && lfs_loc.addr_mem == l) + { + config[0] = (intptr_t)lfs_loc.addr_mem; + config[1] = (intptr_t)lfs_loc.addr_phys; + config[2] = (intptr_t)lfs_loc.size; + } + if (g->ROstrt.hash) { + config[3] = l->flash_size; /* LFS region used */ + config[4] = l->timestamp; /* LFS region timestamp */ + } else { + config[3] = config[4] = 0; + } +} + +LUA_API int lua_pushlfsindex(lua_State *L) { + lua_lock(L); + setobj2n(L, L->top, &G(L)->LFStable); + api_incr_top(L); + lua_unlock(L); + return ttnov(L->top-1); +} + +/* + * In Lua 5.3 luac.cross generates a top level Proto for each source file with + * one upvalue that must be the set to the _ENV variable when its closure is + * created, and as such this parallels some ldo.c processing. + */ +LUA_API int lua_pushlfsfunc(lua_State *L) { + lua_lock(L); + const TValue *t = &G(L)->LFStable; + if (ttisstring(L->top-1) && ttistable(t)) { + const TValue *v = luaH_getstr (hvalue(t), tsvalue(L->top-1)); + if (ttislightuserdata(v)) { + Proto *f = pvalue(v); /* The pvalue is a Proto * for the Lua function */ + LClosure *cl = luaF_newLclosure(L, f->sizeupvalues); + setclLvalue(L, L->top-1, cl); + luaF_initupvals(L, cl); + cl->p = f; + if (cl->nupvalues >= 1) { /* does it have an upvalue? */ + UpVal *uv1 = cl->upvals[0]; + TValue *val = uv1->v; + /* set 1st upvalue as global env table from registry */ + setobj(L, val, luaH_getint(hvalue(&G(L)->l_registry), LUA_RIDX_GLOBALS)); + luaC_upvalbarrier(L, uv1); + } + return 1; + } + } + setnilvalue(L->top-1); + lua_unlock(L); + return 0; +} + + +//================ NodeMCU lauxlib.h LUALIB_API extensions ===================// + +/* + * Return an array of functions in LFS + */ +LUALIB_API int luaL_pushlfsmodules(lua_State *L) { + int i = 1; + if (lua_pushlfsindex(L) == LUA_TNIL) + return 0; /* return nil if LFS not loaded */ + lua_newtable(L); /* create dest table and move above LFS index ROTable */ + lua_insert(L, -2); + lua_pushnil(L); + while (lua_next(L, -2) != 0) { + lua_pop(L, 1); /* dump the value (ptr to the Proto) */ + lua_pushvalue(L, -1); /* dup key (module name) */ + lua_rawseti(L, -4, i++); + } + lua_pop(L, 1); /* dump the LFS index ROTable */ + return 1; +} + +LUALIB_API int luaL_pushlfsdts(lua_State *L) { + intptr_t config[5]; + lua_getlfsconfig(L, config); + lua_pushinteger(L, config[4]); + return 1; +} + +//======== NodeMCU bootstrap to set up and to reimage LFS resources ==========// +/* +** This processing uses 2 init hooks during the Lua startup. The first is +** called early in the Lua state setup to initialize the LFS if present. The +** second is only used to rebuild the LFS region; this requires the Lua +** environment to be in place, so this second hook is immediately before +** processing LUA_INIT. +** +** An application library initiates an LFS rebuild by writing a FLASHLFS +** message to the Reboot Config Record area (RCR), and then restarting the +** processor. This RCR record is read during startup by the 2nd hook. The +** content is the name of the Lua LFS image file to be loaded. If present then +** the LFS reload process is initiated instead of LUA_INIT. This uses lundump +** functions to load the components directly into the LFS region. +** +** FlashState used to share context with the low level lua_load write routines +** is passed as a ZIO data field. Note this is only within the phase +** processing and not across phases. +*/ + + +typedef struct LFSflashState { + lua_State *L; + LFSHeader hdr; + l_file(f); + lu_int32 *addr; + lu_int32 oNdx; /* in size_t units */ + lu_int32 oChunkNdx; /* in size_t units */ + lu_int32 *oBuff; /* FLASH_PAGE_SIZE bytes */ + lu_byte *inBuff; /* FLASH_PAGE_SIZE bytes */ + lu_int32 inNdx; /* in bytes */ + lu_int32 addrPhys; + lu_int32 size; + lu_int32 allocmask; + stringtable ROstrt; + GCObject *pLTShead; +} LFSflashState; +#define WORDSIZE sizeof(lu_int32) +#define OSIZE (FLASH_PAGE_SIZE/WORDSIZE) +#define ISIZE (FLASH_PAGE_SIZE) +#ifdef LUA_USE_ESP +#define ALIGN(F,n) (n + WORDSIZE - 1) / WORDSIZE; +#else +#define ALIGN(F,n) ((n + F->allocmask) & ~(F->allocmask)) / WORDSIZE; +#endif + +#ifndef CONFIG_NODEMCU_EMBEDDED_LFS_SIZE +/* This conforms to the ZIO lua_Reader spec, hence the L parameter */ +static const char *readF (lua_State *L, void *ud, size_t *size) { + UNUSED(L); + LFSflashState *F = cast(LFSflashState *, ud); + if (F->inNdx > 0) { + *size = F->inNdx; + F->inNdx = 0; + } else { + if (l_feof(F->f)) return NULL; + *size = l_read(F->f, F->inBuff) ; /* read block */ + } + return cast(const char *,F->inBuff); +} + +static void eraseLFS(LFSflashState *F) { + lu_int32 i; +#ifdef LUA_USE_ESP + printf("\nErasing LFS from flash addr 0x%06x", F->addrPhys); +#endif + unlockFlashWrite(); + for (i = 0; i < F->size; i += FLASH_PAGE_SIZE) { + size_t *f = cast(size_t *, F->addr + i/sizeof(*f)); + lu_int32 s = platform_flash_get_sector_of_address(F->addrPhys + i); + /* it is far faster not erasing if you don't need to */ +#ifdef LUA_USE_ESP + if (*f == ~0 && !memcmp(f, f + 1, FLASH_PAGE_SIZE - sizeof(*f))) + continue; + printf("."); +#endif + platform_flash_erase_sector(s); + } +#ifdef LUA_USE_ESP + printf(" to 0x%06x\n", F->addrPhys + F->size-1); +#endif + flush_icache(F); + lockFlashWrite(); +} +#endif + +LUAI_FUNC void luaN_setFlash(void *F, unsigned int o) { + luaN_flushFlash(F); /* flush the pending write buffer */ + lua_assert((o & (WORDSIZE-1))==0); + cast(LFSflashState *,F)->oChunkNdx = o/WORDSIZE; +} + +LUAI_FUNC void luaN_flushFlash(void *vF) { + LFSflashState *F = cast(LFSflashState *, vF); + lu_int32 start = F->addrPhys + F->oChunkNdx*WORDSIZE; + lu_int32 size = F->oNdx * WORDSIZE; + lua_assert(start + size < F->addrPhys + F->size); /* is write in bounds? */ +//printf("Flush Buf: %6x (%u)\n", F->oNdx, size); //DEBUG + platform_s_flash_write(F->oBuff, start, size); + F->oChunkNdx += F->oNdx; + F->oNdx = 0; +} + +LUAI_FUNC void *luaN_writeFlash(void *vF, const void *rec, size_t n) { + LFSflashState *F = cast(LFSflashState *, vF); + lu_byte *p = byteptr(F->addr + F->oChunkNdx + F->oNdx); +//int i; printf("writing %4u bytes:", (lu_int32) n); for (i=0;ioNdx + nw > OSIZE) { + /* record overflows the buffer so fill buffer, flush and repeat */ + int rem = OSIZE - F->oNdx; + if (rem) + memcpy(F->oBuff+F->oNdx, rec, rem * WORDSIZE); + rec = cast(void *, cast(lu_int32 *, rec) + rem); + n -= rem * WORDSIZE; + F->oNdx = OSIZE; + luaN_flushFlash(F); + } else { + /* append remaining record to buffer */ + F->oBuff[F->oNdx+nw-1] = 0; /* ensure any trailing odd byte are 0 */ + memcpy(F->oBuff+F->oNdx, rec, n); + F->oNdx += nw; + break; + } + } +//int i; for (i=0;i<(rem * WORDSIZE); i++) {printf("%c%02x",i?' ':'.',*((lu_byte*)rec+i));} +//for (i=0;ioBuff = wordptr(F + 1); + F->inBuff = byteptr(F->oBuff + OSIZE); + + lfs_location_info_t lfs_loc; + if (lfs_get_location(&lfs_loc)) + { + F->size = lfs_loc.size; + F->addr = cast(lu_int32 *, lfs_loc.addr_mem); + F->addrPhys = lfs_loc.addr_phys; + + fh = cast(LFSHeader *, F->addr); + if (!have_load_file) { + global_State *g = G(L); + g->LFSsize = F->size; + g->l_LFS = fh; + /* Set up LFS hooks on normal Entry */ + if (fh->flash_sig == FLASH_SIG) { + g->seed = fh->seed; + g->ROstrt.hash = cast(TString **, F->addr + fh->oROhash); + g->ROstrt.nuse = fh->nROuse ; + g->ROstrt.size = fh->nROsize; + sethvalue(L, &g->LFStable, cast(Table *, F->addr + fh->protoROTable)); + lua_writestringerror("LFS image %s\n", "loaded"); + } else if ((fh->flash_sig != 0 && fh->flash_sig != ~0)) { + lua_writestringerror("LFS image %s\n", "corrupted."); +#ifndef CONFIG_NODEMCU_EMBEDDED_LFS_SIZE + eraseLFS(F); +#endif + } + } + } + return 0; + } else { /* hook 2 called from protected pmain, so can throw errors. */ +#ifndef CONFIG_NODEMCU_EMBEDDED_LFS_SIZE + int status = 0; + if (have_load_file) { /* hook == 2 LFS image load */ + ZIO z; + /* + * To avoid reboot loops, the load is only attempted once, so we + * always deleted the RCR record if we enter this path. Also note + * that this load process can throw errors and if so these are + * caught by the parent function in lua.c + */ +#ifdef DEVELOPMENT_USE_GDB +/* For GDB builds, prefixing the filename with ! forces a break in the hook */ + if (fname[0] == '!') { + lua_debugbreak(); + F->LFSfileName++; + } +#endif + lfs_clear_load_filename(); +#ifdef LUA_USE_ESP + luaopen_file(L); +#endif + if (!(F->f = l_open(fname))) { + free(F); + return luaL_error(L, "cannot open %s", fname); + } + eraseLFS(F); + luaZ_init(L, &z, readF, F); + lua_lock(L); +#ifdef LUA_USE_HOST + F->allocmask = (LFSaddr == LFSregion) ? sizeof(size_t) - 1 : + sizeof(lu_int32) - 1; + status = luaU_undumpLFS(L, &z, LFSaddr != LFSregion); +#else + status = luaU_undumpLFS(L, &z, 0); +#endif + lua_unlock(L); + l_close(F->f); + free(F); + F = NULL; + if (status == LUA_OK) + lua_pushstring(L, "!LFSrestart!"); /* Signal a restart */ + lua_error(L); /* throw error / restart request */ + } else { /* hook == 2, Normal startup */ + free(F); + F = NULL; + } + return status; +#else + return 0; // Embedded LFS - no reloading possible +#endif + } +} + + +// ============================================================================= +#define getfield(L,t,f) \ + lua_getglobal(L, #t); luaL_getmetafield( L, 1, #f ); lua_remove(L, -2); + +LUALIB_API void luaL_lfsreload (lua_State *L) { +#if defined(CONFIG_NODEMCU_EMBEDDED_FLS_SIZE) + (void)L; + lua_pushstring(L, "Not allowed to write to LFS section"); + return 1; +#else +#ifdef LUA_USE_ESP + size_t l; + int off = 0; + const char *img = lua_tolstring(L, 1, &l); +#ifdef DEVELOPMENT_USE_GDB + if (*img == '!') /* For GDB builds, any leading ! is ignored for checking */ + off = 1; /* existence. This forces a debug break in the init hook */ +#endif + lua_settop(L, 1); + lua_getglobal(L, "file"); + if (lua_isnil(L, 2)) { + lua_pushstring(L, "No file system mounted"); + return; + } + lua_getfield(L, 2, "exists"); + lua_pushstring(L, img + off); + lua_call(L, 1, 1); + if (G(L)->LFSsize == 0 || lua_toboolean(L, -1) == 0) { + lua_pushstring(L, "No LFS partition allocated"); + return; + } + if (lfs_set_load_filename(img)) + { + esp_restart(); + luaL_error(L, "system restarting"); + } +#else + (void)L; +#endif +#endif +} + + +#ifdef LUA_USE_ESP +/* +** Task callback handler to support pcallx with full traceback +*/ +static void do_task (task_param_t task_fn_ref, task_prio_t prio) { + lua_State* L = lua_getstate(); + if (prio < LUA_TASK_LOW || prio > LUA_TASK_HIGH) + luaL_error(L, "invalid post task"); +/* Pop the CB func from the Reg */ + lua_rawgeti(L, LUA_REGISTRYINDEX, (int) task_fn_ref); + luaL_checktype(L, -1, LUA_TFUNCTION); + luaL_unref(L, LUA_REGISTRYINDEX, (int) task_fn_ref); + lua_pushinteger(L, prio); + luaL_pcallx(L, 1, 0); +} + +/* +** Schedule a Lua function for task execution +*/ +LUALIB_API int luaL_posttask ( lua_State* L, int prio ) { // [-1, +0, -] + static task_handle_t task_handle = 0; + if (!task_handle) + task_handle = task_get_id(do_task); + if (lua_isfunction(L, -1) && prio >= LUA_TASK_LOW && prio <= LUA_TASK_HIGH) { + int task_fn_ref = luaL_ref(L, LUA_REGISTRYINDEX); + if(!task_post(prio, task_handle, (task_param_t)task_fn_ref)) { + luaL_unref(L, LUA_REGISTRYINDEX, task_fn_ref); + luaL_error(L, "Task queue overflow. Task not posted"); + } + return task_fn_ref; + } else { + return luaL_error(L, "invalid post task"); + } +} +#else +/* +** Task execution isn't supported on HOST builds so returns a -1 status +*/ +LUALIB_API int luaL_posttask( lua_State* L, int prio ) { // [-1, +0, -] + (void)L; (void)prio; + return -1; +} +#endif diff --git a/components/lua/lua-5.3/lnodemcu.h b/components/lua/lua-5.3/lnodemcu.h new file mode 100644 index 00000000..7b501755 --- /dev/null +++ b/components/lua/lua-5.3/lnodemcu.h @@ -0,0 +1,82 @@ +/* + * NodeMCU extensions to Lua 5.3 for readonly Flash memory support + */ +#ifndef lnodemcu_h +#define lnodemcu_h + +#include "lua.h" +#include "lobject.h" +#include "llimits.h" +#include "ltm.h" + +#ifdef LUA_USE_HOST +#define LRO_STRKEY(k) k +#define LOCK_IN_SECTION(s) +#else +#define LRO_STRKEY(k) ((__attribute__((aligned(4))) const char *) k) +#define LOCK_IN_SECTION(s) __attribute__((used,unused,section(".lua_" #s))) +#endif + +/* Macros used to declare rotable entries */ + +#define LRO_FUNCVAL(v) {{.f = v}, LUA_TLCF} +#define LRO_LUDATA(v) {{.p = (void *) v}, LUA_TLIGHTUSERDATA} +#define LRO_NILVAL {{.p = NULL}, LUA_TNIL} +#define LRO_NUMVAL(v) {{.i = v}, LUA_TNUMINT} +#define LRO_INTVAL(v) LRO_NUMVAL(v) +#define LRO_FLOATVAL(v) {{.n = v}, LUA_TNUMFLT} +#define LRO_ROVAL(v) {{.gc = cast(GCObject *, &(v ## _ROTable))}, LUA_TTBLROF} + +#define LROT_MARKED 0 //<<<<<<<<<< *** TBD *** >>>>>>>>>>> + +#define LROT_FUNCENTRY(n,f) {LRO_STRKEY(#n), LRO_FUNCVAL(f)}, +#define LROT_LUDENTRY(n,x) {LRO_STRKEY(#n), LRO_LUDATA(x)}, +#define LROT_NUMENTRY(n,x) {LRO_STRKEY(#n), LRO_NUMVAL(x)}, +#define LROT_INTENTRY(n,x) LROT_NUMENTRY(n,x) +#define LROT_FLOATENTRY(n,x) {LRO_STRKEY(#n), LRO_FLOATVAL(x)}, +#define LROT_TABENTRY(n,t) {LRO_STRKEY(#n), LRO_ROVAL(t)}, + +#define LROT_TABLE(rt) const ROTable rt ## _ROTable +#define LROT_ENTRYREF(rt) (rt ##_entries) +#define LROT_TABLEREF(rt) (&rt ##_ROTable) +#define LROT_BEGIN(rt,mt,f) LROT_TABLE(rt); \ + static ROTable_entry rt ## _entries[] = { +#define LROT_ENTRIES_IN_SECTION(rt,s) \ + static ROTable_entry LOCK_IN_SECTION(s) rt ## _entries[] = { +#define LROT_END(rt,mt,f) {NULL, LRO_NILVAL} }; \ + const ROTable rt ## _ROTable = { \ + (GCObject *)1, LUA_TTBLROF, LROT_MARKED, \ + cast(lu_byte, ~(f)), (sizeof(rt ## _entries)/sizeof(ROTable_entry)) - 1, \ + cast(Table *, mt), cast(ROTable_entry *, rt ## _entries) }; +#define LROT_BREAK(rt) }; + +#define LROT_MASK(m) cast(lu_byte, 1< +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + +#ifndef LUA_USE_HOST +#include +#include "vfs.h" +#endif + +/* +** LUA_IGMARK is a mark to ignore all before it when building the +** luaopen_ function name. +*/ +#if !defined (LUA_IGMARK) +#define LUA_IGMARK "-" +#endif + + +/* +** LUA_CSUBSEP is the character that replaces dots in submodule names +** when searching for a C loader. +** LUA_LSUBSEP is the character that replaces dots in submodule names +** when searching for a Lua loader. +*/ +#if !defined(LUA_CSUBSEP) +#define LUA_CSUBSEP LUA_DIRSEP +#endif + +#if !defined(LUA_LSUBSEP) +#define LUA_LSUBSEP LUA_DIRSEP +#endif + + +/* prefix for open functions in C libraries */ +#define LUA_POF "luaopen_" + +/* separator for open functions in C libraries */ +#define LUA_OFSEP "_" + +#ifndef LUA_NODEMCU_NOCLOADERS +/* +** unique key for table in the registry that keeps handles +** for all loaded C libraries +*/ +static const int CLIBS = 0; +#endif + +#define LIB_FAIL "open" + + +#define setprogdir(L) ((void)0) + + +/* +** system-dependent functions +*/ + +/* +** unload library 'lib' +*/ +#ifndef LUA_NODEMCU_NOCLOADERS +static void lsys_unloadlib (void *lib); + +/* +** load C library in file 'path'. If 'seeglb', load with all names in +** the library global. +** Returns the library; in case of error, returns NULL plus an +** error string in the stack. +*/ +static void *lsys_load (lua_State *L, const char *path, int seeglb); + +/* +** Try to find a function named 'sym' in library 'lib'. +** Returns the function; in case of error, returns NULL plus an +** error string in the stack. +*/ +static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym); +#endif + + +#ifndef LUA_NODEMCU_NOCLOADERS +#if defined(LUA_USE_DLOPEN) /* { */ +/* +** {======================================================================== +** This is an implementation of loadlib based on the dlfcn interface. +** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD, +** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least +** as an emulation layer on top of native functions. +** ========================================================================= +*/ + +#include + +/* +** Macro to convert pointer-to-void* to pointer-to-function. This cast +** is undefined according to ISO C, but POSIX assumes that it works. +** (The '__extension__' in gnu compilers is only to avoid warnings.) +*/ +#if defined(__GNUC__) +#define cast_func(p) (__extension__ (lua_CFunction)(p)) +#else +#define cast_func(p) ((lua_CFunction)(p)) +#endif + + +static void lsys_unloadlib (void *lib) { + dlclose(lib); +} + + +static void *lsys_load (lua_State *L, const char *path, int seeglb) { + void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL)); + if (lib == NULL) lua_pushstring(L, dlerror()); + return lib; +} + + +static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { + lua_CFunction f = cast_func(dlsym(lib, sym)); + if (f == NULL) lua_pushstring(L, dlerror()); + return f; +} + +/* }====================================================== */ + + + +#elif defined(LUA_DL_DLL) /* }{ */ +/* +** {====================================================================== +** This is an implementation of loadlib for Windows using native functions. +** ======================================================================= +*/ + +#include + + +/* +** optional flags for LoadLibraryEx +*/ +#if !defined(LUA_LLE_FLAGS) +#define LUA_LLE_FLAGS 0 +#endif + + +#undef setprogdir + + +/* +** Replace in the path (on the top of the stack) any occurrence +** of LUA_EXEC_DIR with the executable's path. +*/ +static void setprogdir (lua_State *L) { + char buff[MAX_PATH + 1]; + char *lb; + DWORD nsize = sizeof(buff)/sizeof(char); + DWORD n = GetModuleFileNameA(NULL, buff, nsize); /* get exec. name */ + if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) + luaL_error(L, "unable to get ModuleFileName"); + else { + *lb = '\0'; /* cut name on the last '\\' to get the path */ + luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff); + lua_remove(L, -2); /* remove original string */ + } +} + + + + +static void pusherror (lua_State *L) { + int error = GetLastError(); + char buffer[128]; + if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL)) + lua_pushstring(L, buffer); + else + lua_pushfstring(L, "system error %d\n", error); +} + +static void lsys_unloadlib (void *lib) { + FreeLibrary((HMODULE)lib); +} + + +static void *lsys_load (lua_State *L, const char *path, int seeglb) { + HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS); + (void)(seeglb); /* not used: symbols are 'global' by default */ + if (lib == NULL) pusherror(L); + return lib; +} + + +static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { + lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym); + if (f == NULL) pusherror(L); + return f; +} + +/* }====================================================== */ + + +#else /* }{ */ +/* +** {====================================================== +** Fallback for other systems +** ======================================================= +*/ + +#undef LIB_FAIL +#define LIB_FAIL "absent" + + +#define DLMSG "dynamic libraries not enabled; check your Lua installation" + + +static void lsys_unloadlib (void *lib) { + (void)(lib); /* not used */ +} + + +static void *lsys_load (lua_State *L, const char *path, int seeglb) { + (void)(path); (void)(seeglb); /* not used */ + lua_pushliteral(L, DLMSG); + return NULL; +} + + +static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { + (void)(lib); (void)(sym); /* not used */ + lua_pushliteral(L, DLMSG); + return NULL; +} + +/* }====================================================== */ +#endif /* } */ +#endif /* LUA_NODEMCU_NOCLOADERS */ + + +/* +** {================================================================== +** Set Paths +** =================================================================== +*/ + +/* +** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment +** variables that Lua check to set its paths. +*/ +#if !defined(LUA_PATH_VAR) +#define LUA_PATH_VAR "LUA_PATH" +#endif + +#if !defined(LUA_CPATH_VAR) +#define LUA_CPATH_VAR "LUA_CPATH" +#endif + + +#define AUXMARK "\1" /* auxiliary mark */ + + +/* +** return registry.LUA_NOENV as a boolean +*/ +static int noenv (lua_State *L) { + int b; + lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); + b = lua_toboolean(L, -1); + lua_pop(L, 1); /* remove value */ + return b; +} + + +/* +** Set a path +*/ +static void setpath (lua_State *L, const char *fieldname, + const char *envname, + const char *dft) { + const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX); + const char *path = getenv(nver); /* use versioned name */ + if (path == NULL) /* no environment variable? */ + path = getenv(envname); /* try unversioned name */ + if (path == NULL || noenv(L)) /* no environment variable? */ + lua_pushstring(L, dft); /* use default */ + else { + /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */ + path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP, + LUA_PATH_SEP AUXMARK LUA_PATH_SEP); + luaL_gsub(L, path, AUXMARK, dft); + lua_remove(L, -2); /* remove result from 1st 'gsub' */ + } + setprogdir(L); + lua_setfield(L, -3, fieldname); /* package[fieldname] = path value */ + lua_pop(L, 1); /* pop versioned variable name */ +} + +/* }================================================================== */ + +#ifndef LUA_NODEMCU_NOCLOADERS +/* +** return registry.CLIBS[path] +*/ +static void *checkclib (lua_State *L, const char *path) { + void *plib; + lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS); + lua_getfield(L, -1, path); + plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ + lua_pop(L, 2); /* pop CLIBS table and 'plib' */ + return plib; +} + + +/* +** registry.CLIBS[path] = plib -- for queries +** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries +*/ +static void addtoclib (lua_State *L, const char *path, void *plib) { + lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS); + lua_pushlightuserdata(L, plib); + lua_pushvalue(L, -1); + lua_setfield(L, -3, path); /* CLIBS[path] = plib */ + lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */ + lua_pop(L, 1); /* pop CLIBS table */ +} + + +/* +** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib +** handles in list CLIBS +*/ +static int gctm (lua_State *L) { + lua_Integer n = luaL_len(L, 1); + for (; n >= 1; n--) { /* for each handle, in reverse order */ + lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */ + lsys_unloadlib(lua_touserdata(L, -1)); + lua_pop(L, 1); /* pop handle */ + } + return 0; +} +#endif + + +/* error codes for 'lookforfunc' */ +#define ERRLIB 1 +#define ERRFUNC 2 + +#ifndef LUA_NODEMCU_NOCLOADERS +/* +** Look for a C function named 'sym' in a dynamically loaded library +** 'path'. +** First, check whether the library is already loaded; if not, try +** to load it. +** Then, if 'sym' is '*', return true (as library has been loaded). +** Otherwise, look for symbol 'sym' in the library and push a +** C function with that symbol. +** Return 0 and 'true' or a function in the stack; in case of +** errors, return an error code and an error message in the stack. +*/ +static int lookforfunc (lua_State *L, const char *path, const char *sym) { + void *reg = checkclib(L, path); /* check loaded C libraries */ + if (reg == NULL) { /* must load library? */ + reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */ + if (reg == NULL) return ERRLIB; /* unable to load library */ + addtoclib(L, path, reg); + } + if (*sym == '*') { /* loading only library (no function)? */ + lua_pushboolean(L, 1); /* return 'true' */ + return 0; /* no errors */ + } + else { + lua_CFunction f = lsys_sym(L, reg, sym); + if (f == NULL) + return ERRFUNC; /* unable to find function */ + lua_pushcfunction(L, f); /* else create new function */ + return 0; /* no errors */ + } +} + + +static int ll_loadlib (lua_State *L) { + const char *path = luaL_checkstring(L, 1); + const char *init = luaL_checkstring(L, 2); + int stat = lookforfunc(L, path, init); + if (stat == 0) /* no errors? */ + return 1; /* return the loaded function */ + else { /* error; error message is on stack top */ + lua_pushnil(L); + lua_insert(L, -2); + lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); + return 3; /* return nil, error message, and where */ + } +} +#endif + + + +/* +** {====================================================== +** 'require' function +** ======================================================= +*/ + +#ifdef LUA_USE_ESP +#define file_t int +#undef fopen +#undef fclose +#define fopen(n,m) vfs_open(n,m) +#define fclose(f) vfs_close(f) +#else +#define file_t FILE * +#endif + +static int readable (const char *filename) { + file_t f = fopen(filename, "r"); /* try to open file */ + if (!f) return 0; /* open failed */ + fclose(f); + return 1; +} + + +static const char *pushnexttemplate (lua_State *L, const char *path) { + const char *l; + while (*path == *LUA_PATH_SEP) path++; /* skip separators */ + if (*path == '\0') return NULL; /* no more templates */ + l = strchr(path, *LUA_PATH_SEP); /* find next separator */ + if (l == NULL) l = path + strlen(path); + lua_pushlstring(L, path, l - path); /* template */ + return l; +} + + +static const char *searchpath (lua_State *L, const char *name, + const char *path, + const char *sep, + const char *dirsep) { + luaL_Buffer msg; /* to build error message */ + luaL_buffinit(L, &msg); + if (*sep != '\0') /* non-empty separator? */ + name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ + while ((path = pushnexttemplate(L, path)) != NULL) { + const char *filename = luaL_gsub(L, lua_tostring(L, -1), + LUA_PATH_MARK, name); + lua_remove(L, -2); /* remove path template */ + if (readable(filename)) /* does file exist and is readable? */ + return filename; /* return that file name */ + lua_pushfstring(L, "\n\tno file '%s'", filename); + lua_remove(L, -2); /* remove file name */ + luaL_addvalue(&msg); /* concatenate error msg. entry */ + } + luaL_pushresult(&msg); /* create error message */ + return NULL; /* not found */ +} + + +static int ll_searchpath (lua_State *L) { + const char *f = searchpath(L, luaL_checkstring(L, 1), + luaL_checkstring(L, 2), + luaL_optstring(L, 3, "."), + luaL_optstring(L, 4, LUA_DIRSEP)); + if (f != NULL) return 1; + else { /* error message is on top of the stack */ + lua_pushnil(L); + lua_insert(L, -2); + return 2; /* return nil + error message */ + } +} + + +static const char *findfile (lua_State *L, const char *name, + const char *pname, + const char *dirsep) { + const char *path; + lua_getfield(L, lua_upvalueindex(1), pname); + path = lua_tostring(L, -1); + if (path == NULL) + luaL_error(L, "'package.%s' must be a string", pname); + return searchpath(L, name, path, ".", dirsep); +} + + +static int checkload (lua_State *L, int stat, const char *filename) { + if (stat) { /* module loaded successfully? */ + lua_pushstring(L, filename); /* will be 2nd argument to module */ + return 2; /* return open function and file name */ + } + else + return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s", + lua_tostring(L, 1), filename, lua_tostring(L, -1)); +} + + +static int searcher_Lua (lua_State *L) { + const char *filename; + const char *name = luaL_checkstring(L, 1); + filename = findfile(L, name, "path", LUA_LSUBSEP); + if (filename == NULL) return 1; /* module not found in this path */ + return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename); +} + +#ifndef LUA_NODEMCU_NOCLOADERS +/* +** Try to find a load function for module 'modname' at file 'filename'. +** First, change '.' to '_' in 'modname'; then, if 'modname' has +** the form X-Y (that is, it has an "ignore mark"), build a function +** name "luaopen_X" and look for it. (For compatibility, if that +** fails, it also tries "luaopen_Y".) If there is no ignore mark, +** look for a function named "luaopen_modname". +*/ +static int loadfunc (lua_State *L, const char *filename, const char *modname) { + const char *openfunc; + const char *mark; + modname = luaL_gsub(L, modname, ".", LUA_OFSEP); + mark = strchr(modname, *LUA_IGMARK); + if (mark) { + int stat; + openfunc = lua_pushlstring(L, modname, mark - modname); + openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc); + stat = lookforfunc(L, filename, openfunc); + if (stat != ERRFUNC) return stat; + modname = mark + 1; /* else go ahead and try old-style name */ + } + openfunc = lua_pushfstring(L, LUA_POF"%s", modname); + return lookforfunc(L, filename, openfunc); +} + +static int searcher_C (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); + if (filename == NULL) return 1; /* module not found in this path */ + return checkload(L, (loadfunc(L, filename, name) == 0), filename); +} + + +static int searcher_Croot (lua_State *L) { + const char *filename; + const char *name = luaL_checkstring(L, 1); + const char *p = strchr(name, '.'); + int stat; + if (p == NULL) return 0; /* is root */ + lua_pushlstring(L, name, p - name); + filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP); + if (filename == NULL) return 1; /* root not found */ + if ((stat = loadfunc(L, filename, name)) != 0) { + if (stat != ERRFUNC) + return checkload(L, 0, filename); /* real error */ + else { /* open function not found */ + lua_pushfstring(L, "\n\tno module '%s' in file '%s'", name, filename); + return 1; + } + } + lua_pushstring(L, filename); /* will be 2nd argument to module */ + return 2; +} +#endif + +static int searcher_preload (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); + if (lua_getfield(L, -1, name) == LUA_TNIL) /* not found? */ + lua_pushfstring(L, "\n\tno field package.preload['%s']", name); + return 1; +} + + +static void findloader (lua_State *L, const char *name) { + int i; + luaL_Buffer msg; /* to build error message */ + luaL_buffinit(L, &msg); + /* push 'package.searchers' to index 3 in the stack */ + if (lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE) + luaL_error(L, "'package.searchers' must be a table"); + /* iterate over available searchers to find a loader */ + for (i = 1; ; i++) { + if (lua_rawgeti(L, 3, i) == LUA_TNIL) { /* no more searchers? */ + lua_pop(L, 1); /* remove nil */ + luaL_pushresult(&msg); /* create error message */ + luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1)); + } + lua_pushstring(L, name); + lua_call(L, 1, 2); /* call it */ + if (lua_isfunction(L, -2)) /* did it find a loader? */ + return; /* module loader found */ + else if (lua_isstring(L, -2)) { /* searcher returned error message? */ + lua_pop(L, 1); /* remove extra return */ + luaL_addvalue(&msg); /* concatenate error message */ + } + else + lua_pop(L, 2); /* remove both returns */ + } +} + + +static int ll_require (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + lua_settop(L, 1); /* LOADED table will be at index 2 */ + lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); + lua_getfield(L, 2, name); /* LOADED[name] */ + if (lua_toboolean(L, -1)) /* is it there? */ + return 1; /* package is already loaded */ + lua_getglobal(L, "ROM"); + lua_getfield(L, -1, name); /* ROM[name] */ + if (lua_toboolean(L, -1)) /* is it there? */ + return 1; /* package is already loaded */ + lua_pop(L, 3); /* remove ROM and 2 × 'getfield' results */ + /* else must load package */ + findloader(L, name); + lua_pushstring(L, name); /* pass name as argument to module loader */ + lua_insert(L, -2); /* name is 1st argument (before search data) */ + lua_call(L, 2, 1); /* run loader to load module */ + if (!lua_isnil(L, -1)) /* non-nil return? */ + lua_setfield(L, 2, name); /* LOADED[name] = returned value */ + if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */ + lua_pushboolean(L, 1); /* use true as result */ + lua_pushvalue(L, -1); /* extra copy to be returned */ + lua_setfield(L, 2, name); /* LOADED[name] = true */ + } + return 1; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** 'module' function +** ======================================================= +*/ +#if defined(LUA_COMPAT_MODULE) + +/* +** changes the environment variable of calling function +*/ +static void set_env (lua_State *L) { + lua_Debug ar; + if (lua_getstack(L, 1, &ar) == 0 || + lua_getinfo(L, "f", &ar) == 0 || /* get calling function */ + lua_iscfunction(L, -1)) + luaL_error(L, "'module' not called from a Lua function"); + lua_pushvalue(L, -2); /* copy new environment table to top */ + lua_setupvalue(L, -2, 1); + lua_pop(L, 1); /* remove function */ +} + + +static void dooptions (lua_State *L, int n) { + int i; + for (i = 2; i <= n; i++) { + if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */ + lua_pushvalue(L, i); /* get option (a function) */ + lua_pushvalue(L, -2); /* module */ + lua_call(L, 1, 0); + } + } +} + + +static void modinit (lua_State *L, const char *modname) { + const char *dot; + lua_pushvalue(L, -1); + lua_setfield(L, -2, "_M"); /* module._M = module */ + lua_pushstring(L, modname); + lua_setfield(L, -2, "_NAME"); + dot = strrchr(modname, '.'); /* look for last dot in module name */ + if (dot == NULL) dot = modname; + else dot++; + /* set _PACKAGE as package name (full module name minus last part) */ + lua_pushlstring(L, modname, dot - modname); + lua_setfield(L, -2, "_PACKAGE"); +} + + +static int ll_module (lua_State *L) { + const char *modname = luaL_checkstring(L, 1); + int lastarg = lua_gettop(L); /* last parameter */ + luaL_pushmodule(L, modname, 1); /* get/create module table */ + /* check whether table already has a _NAME field */ + if (lua_getfield(L, -1, "_NAME") != LUA_TNIL) + lua_pop(L, 1); /* table is an initialized module */ + else { /* no; initialize it */ + lua_pop(L, 1); + modinit(L, modname); + } + lua_pushvalue(L, -1); + set_env(L); + dooptions(L, lastarg); + return 1; +} + + +static int ll_seeall (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + if (!lua_getmetatable(L, 1)) { + lua_createtable(L, 0, 1); /* create new metatable */ + lua_pushvalue(L, -1); + lua_setmetatable(L, 1); + } + lua_pushglobaltable(L); + lua_setfield(L, -2, "__index"); /* mt.__index = _G */ + return 0; +} + +#endif +/* }====================================================== */ + + + +static const luaL_Reg pk_funcs[] = { +#ifndef LUA_NODEMCU_NOCLOADERS + {"loadlib", ll_loadlib}, + {"cpath", NULL}, +#endif + {"searchpath", ll_searchpath}, +#if defined(LUA_COMPAT_MODULE) + {"seeall", ll_seeall}, +#endif + /* placeholders */ + {"preload", NULL}, + {"path", NULL}, + {"searchers", NULL}, + {"loaded", NULL}, + {NULL, NULL} +}; + + +static const luaL_Reg ll_funcs[] = { +#if defined(LUA_COMPAT_MODULE) + {"module", ll_module}, +#endif + {"require", ll_require}, + {NULL, NULL} +}; + + +static void createsearcherstable (lua_State *L) { + static const lua_CFunction searchers[] = + {searcher_preload, searcher_Lua, +#ifndef LUA_NODEMCU_NOCLOADERS + searcher_C, searcher_Croot, +#endif + NULL}; + int i; + /* create 'searchers' table */ + lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); + /* fill it with predefined searchers */ + for (i=0; searchers[i] != NULL; i++) { + lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ + lua_pushcclosure(L, searchers[i], 1); + lua_rawseti(L, -2, i+1); + } +#if defined(LUA_COMPAT_LOADERS) + lua_pushvalue(L, -1); /* make a copy of 'searchers' table */ + lua_setfield(L, -3, "loaders"); /* put it in field 'loaders' */ +#endif + lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ +} + +#ifndef LUA_NODEMCU_NOCLOADERS +/* +** create table CLIBS to keep track of loaded C libraries, +** setting a finalizer to close all libraries when closing state. +*/ +static void createclibstable (lua_State *L) { + lua_newtable(L); /* create CLIBS table */ + lua_createtable(L, 0, 1); /* create metatable for CLIBS */ + lua_pushcfunction(L, gctm); + lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */ + lua_setmetatable(L, -2); + lua_rawsetp(L, LUA_REGISTRYINDEX, &CLIBS); /* set CLIBS table in registry */ +} +#endif + +LUAMOD_API int luaopen_package (lua_State *L) { +#ifndef LUA_NODEMCU_NOCLOADERS + createclibstable(L); +#endif + luaL_newlib(L, pk_funcs); /* create 'package' table */ + createsearcherstable(L); + /* set paths */ + setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT); + // setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT); + /* store config information */ + lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" + LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); + lua_setfield(L, -2, "config"); + /* set field 'loaded' */ + luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); + lua_setfield(L, -2, "loaded"); + /* set field 'preload' */ + luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); + lua_setfield(L, -2, "preload"); + lua_pushglobaltable(L); + lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ + luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ + lua_pop(L, 1); /* pop global table */ + return 1; /* return 'package' table */ +} + diff --git a/components/lua/lua-5.3/lobject.c b/components/lua/lua-5.3/lobject.c new file mode 100644 index 00000000..867720f7 --- /dev/null +++ b/components/lua/lua-5.3/lobject.c @@ -0,0 +1,526 @@ +/* +** $Id: lobject.c,v 2.113.1.1 2017/04/19 17:29:57 roberto Exp $ +** Some generic functions over Lua objects +** See Copyright Notice in lua.h +*/ + +#define lobject_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include +#include +#include +#include +#include + +#include "lua.h" + +#include "lctype.h" +#include "ldebug.h" +#include "ldo.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "lvm.h" + + + +LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT}; + + +/* +** converts an integer to a "floating point byte", represented as +** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if +** eeeee != 0 and (xxx) otherwise. +*/ +int luaO_int2fb (unsigned int x) { + int e = 0; /* exponent */ + if (x < 8) return x; + while (x >= (8 << 4)) { /* coarse steps */ + x = (x + 0xf) >> 4; /* x = ceil(x / 16) */ + e += 4; + } + while (x >= (8 << 1)) { /* fine steps */ + x = (x + 1) >> 1; /* x = ceil(x / 2) */ + e++; + } + return ((e+1) << 3) | (cast_int(x) - 8); +} + + +/* converts back */ +int luaO_fb2int (int x) { + return (x < 8) ? x : ((x & 7) + 8) << ((x >> 3) - 1); +} + + +/* +** Computes ceil(log2(x)) +*/ +int luaO_ceillog2 (unsigned int x) { +#ifdef LUA_CROSS_COMPILER + static const lu_byte log_2[256] = { /* log_2[i] = ceil(log2(i - 1)) */ + 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 + }; + int l = 0; + x--; + while (x >= 256) { l += 8; x >>= 8; } + return l + log_2[x]; +#else + return (x == 1) ? 0 : 32 - __builtin_clz(x - 1); +#endif +} + + +static lua_Integer intarith (lua_State *L, int op, lua_Integer v1, + lua_Integer v2) { + switch (op) { + case LUA_OPADD: return intop(+, v1, v2); + case LUA_OPSUB:return intop(-, v1, v2); + case LUA_OPMUL:return intop(*, v1, v2); + case LUA_OPMOD: return luaV_mod(L, v1, v2); + case LUA_OPIDIV: return luaV_div(L, v1, v2); + case LUA_OPBAND: return intop(&, v1, v2); + case LUA_OPBOR: return intop(|, v1, v2); + case LUA_OPBXOR: return intop(^, v1, v2); + case LUA_OPSHL: return luaV_shiftl(v1, v2); + case LUA_OPSHR: return luaV_shiftl(v1, -v2); + case LUA_OPUNM: return intop(-, 0, v1); + case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1); + default: lua_assert(0); return 0; + } +} + + +static lua_Number numarith (lua_State *L, int op, lua_Number v1, + lua_Number v2) { + switch (op) { + case LUA_OPADD: return luai_numadd(L, v1, v2); + case LUA_OPSUB: return luai_numsub(L, v1, v2); + case LUA_OPMUL: return luai_nummul(L, v1, v2); + case LUA_OPDIV: return luai_numdiv(L, v1, v2); + case LUA_OPPOW: return luai_numpow(L, v1, v2); + case LUA_OPIDIV: return luai_numidiv(L, v1, v2); + case LUA_OPUNM: return luai_numunm(L, v1); + case LUA_OPMOD: { + lua_Number m; + luai_nummod(L, v1, v2, m); + return m; + } + default: lua_assert(0); return 0; + } +} + + +void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2, + TValue *res) { + switch (op) { + case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: + case LUA_OPSHL: case LUA_OPSHR: + case LUA_OPBNOT: { /* operate only on integers */ + lua_Integer i1; lua_Integer i2; + if (tointeger(p1, &i1) && tointeger(p2, &i2)) { + setivalue(res, intarith(L, op, i1, i2)); + return; + } + else break; /* go to the end */ + } + case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */ + lua_Number n1; lua_Number n2; + if (tonumber(p1, &n1) && tonumber(p2, &n2)) { + setfltvalue(res, numarith(L, op, n1, n2)); + return; + } + else break; /* go to the end */ + } + default: { /* other operations */ + lua_Number n1; lua_Number n2; + if (ttisinteger(p1) && ttisinteger(p2)) { + setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2))); + return; + } + else if (tonumber(p1, &n1) && tonumber(p2, &n2)) { + setfltvalue(res, numarith(L, op, n1, n2)); + return; + } + else break; /* go to the end */ + } + } + /* could not perform raw operation; try metamethod */ + lua_assert(L != NULL); /* should not fail when folding (compile time) */ + luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD)); +} + + +int luaO_hexavalue (int c) { + if (lisdigit(c)) return c - '0'; + else return (ltolower(c) - 'a') + 10; +} + + +static int isneg (const char **s) { + if (**s == '-') { (*s)++; return 1; } + else if (**s == '+') (*s)++; + return 0; +} + + + +/* +** {================================================================== +** Lua's implementation for 'lua_strx2number' +** =================================================================== +*/ + +#if !defined(lua_strx2number) + +/* maximum number of significant digits to read (to avoid overflows + even with single floats) */ +#define MAXSIGDIG 30 + +/* +** convert an hexadecimal numeric string to a number, following +** C99 specification for 'strtod' +*/ +static lua_Number lua_strx2number (const char *s, char **endptr) { + int dot = lua_getlocaledecpoint(); + lua_Number r = 0.0; /* result (accumulator) */ + int sigdig = 0; /* number of significant digits */ + int nosigdig = 0; /* number of non-significant digits */ + int e = 0; /* exponent correction */ + int neg; /* 1 if number is negative */ + int hasdot = 0; /* true after seen a dot */ + *endptr = cast(char *, s); /* nothing is valid yet */ + while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ + neg = isneg(&s); /* check signal */ + if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */ + return 0.0; /* invalid format (no '0x') */ + for (s += 2; ; s++) { /* skip '0x' and read numeral */ + if (*s == dot) { + if (hasdot) break; /* second dot? stop loop */ + else hasdot = 1; + } + else if (lisxdigit(cast_uchar(*s))) { + if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */ + nosigdig++; + else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */ + r = (r * cast_num(16.0)) + luaO_hexavalue(*s); + else e++; /* too many digits; ignore, but still count for exponent */ + if (hasdot) e--; /* decimal digit? correct exponent */ + } + else break; /* neither a dot nor a digit */ + } + if (nosigdig + sigdig == 0) /* no digits? */ + return 0.0; /* invalid format */ + *endptr = cast(char *, s); /* valid up to here */ + e *= 4; /* each digit multiplies/divides value by 2^4 */ + if (*s == 'p' || *s == 'P') { /* exponent part? */ + int exp1 = 0; /* exponent value */ + int neg1; /* exponent signal */ + s++; /* skip 'p' */ + neg1 = isneg(&s); /* signal */ + if (!lisdigit(cast_uchar(*s))) + return 0.0; /* invalid; must have at least one digit */ + while (lisdigit(cast_uchar(*s))) /* read exponent */ + exp1 = exp1 * 10 + *(s++) - '0'; + if (neg1) exp1 = -exp1; + e += exp1; + *endptr = cast(char *, s); /* valid up to here */ + } + if (neg) r = -r; + return l_mathop(ldexp)(r, e); +} + +#endif +/* }====================================================== */ + + +/* maximum length of a numeral */ +#if !defined (L_MAXLENNUM) +#define L_MAXLENNUM 200 +#endif + +static const char *l_str2dloc (const char *s, lua_Number *result, int mode) { + char *endptr; + *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */ + : lua_str2number(s, &endptr); + if (endptr == s) return NULL; /* nothing recognized? */ + while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */ + return (*endptr == '\0') ? endptr : NULL; /* OK if no trailing characters */ +} + + +/* +** Convert string 's' to a Lua number (put in 'result'). Return NULL +** on fail or the address of the ending '\0' on success. +** 'pmode' points to (and 'mode' contains) special things in the string: +** - 'x'/'X' means an hexadecimal numeral +** - 'n'/'N' means 'inf' or 'nan' (which should be rejected) +** - '.' just optimizes the search for the common case (nothing special) +** This function accepts both the current locale or a dot as the radix +** mark. If the convertion fails, it may mean number has a dot but +** locale accepts something else. In that case, the code copies 's' +** to a buffer (because 's' is read-only), changes the dot to the +** current locale radix mark, and tries to convert again. +*/ +static const char *l_str2d (const char *s, lua_Number *result) { + const char *endptr; + const char *pmode = strpbrk(s, ".xXnN"); + int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0; + if (mode == 'n') /* reject 'inf' and 'nan' */ + return NULL; + endptr = l_str2dloc(s, result, mode); /* try to convert */ + if (endptr == NULL) { /* failed? may be a different locale */ + char buff[L_MAXLENNUM + 1]; + const char *pdot = strchr(s, '.'); + if (strlen(s) > L_MAXLENNUM || pdot == NULL) + return NULL; /* string too long or no dot; fail */ + strcpy(buff, s); /* copy string to buffer */ + buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */ + endptr = l_str2dloc(buff, result, mode); /* try again */ + if (endptr != NULL) + endptr = s + (endptr - buff); /* make relative to 's' */ + } + return endptr; +} + + +#define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10) +#define MAXLASTD cast_int(LUA_MAXINTEGER % 10) + +static const char *l_str2int (const char *s, lua_Integer *result) { + lua_Unsigned a = 0; + int empty = 1; + int neg; + while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ + neg = isneg(&s); + if (s[0] == '0' && + (s[1] == 'x' || s[1] == 'X')) { /* hex? */ + s += 2; /* skip '0x' */ + for (; lisxdigit(cast_uchar(*s)); s++) { + a = a * 16 + luaO_hexavalue(*s); + empty = 0; + } + } + else { /* decimal */ + for (; lisdigit(cast_uchar(*s)); s++) { + int d = *s - '0'; + if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */ + return NULL; /* do not accept it (as integer) */ + a = a * 10 + d; + empty = 0; + } + } + while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */ + if (empty || *s != '\0') return NULL; /* something wrong in the numeral */ + else { + *result = l_castU2S((neg) ? 0u - a : a); + return s; + } +} + + +size_t luaO_str2num (const char *s, TValue *o) { + lua_Integer i; lua_Number n; + const char *e; + if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */ + setivalue(o, i); + } + else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */ + setfltvalue(o, n); + } + else + return 0; /* conversion failed */ + return (e - s) + 1; /* success; return string size */ +} + + +int luaO_utf8esc (char *buff, unsigned long x) { + int n = 1; /* number of bytes put in buffer (backwards) */ + lua_assert(x <= 0x10FFFF); + if (x < 0x80) /* ascii? */ + buff[UTF8BUFFSZ - 1] = cast(char, x); + else { /* need continuation bytes */ + unsigned int mfb = 0x3f; /* maximum that fits in first byte */ + do { /* add continuation bytes */ + buff[UTF8BUFFSZ - (n++)] = cast(char, 0x80 | (x & 0x3f)); + x >>= 6; /* remove added bits */ + mfb >>= 1; /* now there is one less bit available in first byte */ + } while (x > mfb); /* still needs continuation byte? */ + buff[UTF8BUFFSZ - n] = cast(char, (~mfb << 1) | x); /* add first byte */ + } + return n; +} + + +/* maximum length of the conversion of a number to a string */ +#define MAXNUMBER2STR 50 + + +/* +** Convert a number object to a string +*/ +void luaO_tostring (lua_State *L, StkId obj) { + char buff[MAXNUMBER2STR]; + size_t len; + lua_assert(ttisnumber(obj)); + if (ttisinteger(obj)) + len = lua_integer2str(buff, sizeof(buff), ivalue(obj)); + else { + len = lua_number2str(buff, sizeof(buff), fltvalue(obj)); +#if !defined(LUA_COMPAT_FLOATSTRING) + if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */ + buff[len++] = lua_getlocaledecpoint(); + buff[len++] = '0'; /* adds '.0' to result */ + } +#endif + } + setsvalue2s(L, obj, luaS_newlstr(L, buff, len)); +} + + +static void pushstr (lua_State *L, const char *str, size_t l) { + setsvalue2s(L, L->top, luaS_newlstr(L, str, l)); + luaD_inctop(L); +} + + +/* +** this function handles only '%d', '%c', '%f', '%p', and '%s' + conventional formats, plus Lua-specific '%I' and '%U' +*/ +const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { + int n = 0; + for (;;) { + const char *e = strchr(fmt, '%'); + if (e == NULL) break; + pushstr(L, fmt, e - fmt); + switch (*(e+1)) { + case 's': { /* zero-terminated string */ + const char *s = va_arg(argp, char *); + if (s == NULL) s = "(null)"; + pushstr(L, s, strlen(s)); + break; + } + case 'c': { /* an 'int' as a character */ + char buff = cast(char, va_arg(argp, int)); + if (lisprint(cast_uchar(buff))) + pushstr(L, &buff, 1); + else /* non-printable character; print its code */ + luaO_pushfstring(L, "<\\%d>", cast_uchar(buff)); + break; + } + case 'd': { /* an 'int' */ + setivalue(L->top, va_arg(argp, int)); + goto top2str; + } + case 'I': { /* a 'lua_Integer' */ + setivalue(L->top, cast(lua_Integer, va_arg(argp, l_uacInt))); + goto top2str; + } + case 'f': { /* a 'lua_Number' */ + setfltvalue(L->top, cast_num(va_arg(argp, l_uacNumber))); + top2str: /* convert the top element to a string */ + luaD_inctop(L); + luaO_tostring(L, L->top - 1); + break; + } + case 'p': { /* a pointer */ + char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */ + void *p = va_arg(argp, void *); + int l = lua_pointer2str(buff, sizeof(buff), p); + pushstr(L, buff, l); + break; + } + case 'U': { /* an 'int' as a UTF-8 sequence */ + char buff[UTF8BUFFSZ]; + int l = luaO_utf8esc(buff, cast(long, va_arg(argp, long))); + pushstr(L, buff + UTF8BUFFSZ - l, l); + break; + } + case '%': { + pushstr(L, "%", 1); + break; + } + default: { + luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'", + *(e + 1)); + } + } + n += 2; + fmt = e+2; + } + luaD_checkstack(L, 1); + pushstr(L, fmt, strlen(fmt)); + if (n > 0) luaV_concat(L, n + 1); + return svalue(L->top - 1); +} + + +const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { + const char *msg; + va_list argp; + va_start(argp, fmt); + msg = luaO_pushvfstring(L, fmt, argp); + va_end(argp); + return msg; +} + + +/* number of chars of a literal string without the ending \0 */ +#define LL(x) (sizeof(x)/sizeof(char) - 1) + +#define RETS "..." +#define PRE "[string \"" +#define POS "\"]" + +#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) ) + +void luaO_chunkid (char *out, const char *source, size_t bufflen) { + size_t l = strlen(source); + if (*source == '=') { /* 'literal' source */ + if (l <= bufflen) /* small enough? */ + memcpy(out, source + 1, l * sizeof(char)); + else { /* truncate it */ + addstr(out, source + 1, bufflen - 1); + *out = '\0'; + } + } + else if (*source == '@') { /* file name */ + if (l <= bufflen) /* small enough? */ + memcpy(out, source + 1, l * sizeof(char)); + else { /* add '...' before rest of name */ + addstr(out, RETS, LL(RETS)); + bufflen -= LL(RETS); + memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char)); + } + } + else { /* string; format as [string "source"] */ + const char *nl = strchr(source, '\n'); /* find first new line (if any) */ + addstr(out, PRE, LL(PRE)); /* add prefix */ + bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */ + if (l < bufflen && nl == NULL) { /* small one-line source? */ + addstr(out, source, l); /* keep it */ + } + else { + if (nl != NULL) l = nl - source; /* stop at first newline */ + if (l > bufflen) l = bufflen; + addstr(out, source, l); + addstr(out, RETS, LL(RETS)); + } + memcpy(out, POS, (LL(POS) + 1) * sizeof(char)); + } +} + diff --git a/components/lua/lua-5.3/lobject.h b/components/lua/lua-5.3/lobject.h new file mode 100644 index 00000000..7e01944c --- /dev/null +++ b/components/lua/lua-5.3/lobject.h @@ -0,0 +1,613 @@ +/* +** $Id: lobject.h,v 2.117.1.1 2017/04/19 17:39:34 roberto Exp $ +** Type definitions for Lua objects +** See Copyright Notice in lua.h +*/ + + +#ifndef lobject_h +#define lobject_h + + +#include + + +#include "llimits.h" +#include "lua.h" + + +/* +** Extra tags for non-values +*/ +#define LUA_TPROTO LUA_NUMTAGS /* function prototypes */ +#define LUA_TDEADKEY (LUA_NUMTAGS+1) /* removed keys in tables */ + +/* +** number of all possible tags (including LUA_TNONE but excluding DEADKEY) +*/ +#define LUA_TOTALTAGS (LUA_TPROTO + 2) + + +/* +** tags for Tagged Values have the following use of bits: +** bits 0-3: actual tag (a LUA_T* value) +** bits 4-5: variant bits +** bit 6: whether value is collectable +*/ + + +/* +** LUA_TFUNCTION variants: +** 0 - Lua function +** 1 - light C function +** 2 - regular C function (closure) +*/ + +/* Variant tags for functions */ +#define LUA_TLCL (LUA_TFUNCTION | (0 << 4)) /* Lua closure */ +#define LUA_TLCF (LUA_TFUNCTION | (1 << 4)) /* light C function */ +#define LUA_TCCL (LUA_TFUNCTION | (2 << 4)) /* C closure */ + + +/* Variant tags for strings */ +#define LUA_TSHRSTR (LUA_TSTRING | (0 << 4)) /* short strings */ +#define LUA_TLNGSTR (LUA_TSTRING | (1 << 4)) /* long strings */ + + +/* Variant tags for numbers */ +#define LUA_TNUMFLT (LUA_TNUMBER | (0 << 4)) /* float numbers */ +#define LUA_TNUMINT (LUA_TNUMBER | (1 << 4)) /* integer numbers */ + + +/* Bit mark for collectable types */ +#define LUA_TTBLRAM (LUA_TTABLE | (0 << 4)) /* RAM based Table */ +#define LUA_TTBLROF (LUA_TTABLE | (1 << 4)) /* RO Flash based ROTable */ + + +/* Bit mark for collectable types */ +#define BIT_ISCOLLECTABLE (1 << 6) + +/* mark a tag as collectable */ +#define ctb(t) ((t) | BIT_ISCOLLECTABLE) + +/* +** Byte field access macro. On ESP targets this causes the compiler to emit +** a l32i + extui instruction pair instead of a single l8ui avoiding a call +** the S/W unaligned exception handler. This is used to force aligned access +** to commonly accessed fields in Flash-based record structures. It is not +** needed for RAM-only structures. +** +** wo is the offset of aligned word in bytes 0,4,8,.. +** bo is the field within the word in bits 0..31 +*/ +#if defined(LUA_USE_ESP8266) +#define GET_BYTE_FN(name,t,wo,bo) \ +static inline lu_int32 get ## name(const void *o) { \ + lu_int32 res; /* extract named field */ \ + asm ("l32i %0, %1, " #wo "; extui %0, %0, " #bo ", 8;" : "=r"(res) : "r"(o) : );\ + return res; } +#else +#define GET_BYTE_FN(name,t,wo,bo) \ +static inline lu_byte get ## name(const void *o) { return (cast(const t *,o))->name; } +#endif + +/* +** Common type for all collectable objects +*/ +typedef struct GCObject GCObject; + + +/* +** Common Header for all collectable objects (in macro form, to be +** included in other objects) +*/ +#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked + + +/* +** Common type has only the common header +*/ +struct GCObject { + CommonHeader; +}; +GET_BYTE_FN(tt,GCObject,4,0) +GET_BYTE_FN(marked,GCObject,4,8) + + +/* +** Tagged Values. This is the basic representation of values in Lua, +** an actual value plus a tag with its type. +*/ + +/* +** Union of all Lua values +*/ +typedef union Value { + GCObject *gc; /* collectable objects */ + void *p; /* light userdata */ + int b; /* booleans */ + lua_CFunction f; /* light C functions */ + lua_Integer i; /* integer numbers */ + lua_Number n; /* float numbers */ +} Value; + + +#define TValuefields Value value_; int tt_ + +#ifdef LUA_USE_ESP +# pragma pack(4) +#endif + +typedef struct lua_TValue { + TValuefields; +} TValue; + +#ifdef LUA_USE_ESP +# pragma pack() +#endif + +/* macro defining a nil value */ +#define NILCONSTANT {NULL}, LUA_TNIL + + +#define val_(o) ((o)->value_) + + +/* raw type tag of a TValue */ +#define rttype(o) ((o)->tt_) + +/* tag with no variants (bits 0-3) */ +#define novariant(x) ((x) & 0x0F) + +/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */ +#define ttype(o) (rttype(o) & 0x3F) + +/* type tag of a TValue with no variants (bits 0-3) */ +#define ttnov(o) (novariant(rttype(o))) + + +/* Macros to test type */ +#define checktag(o,t) (rttype(o) == (t)) +#define checktype(o,t) (ttnov(o) == (t)) +#define ttisnumber(o) checktype((o), LUA_TNUMBER) +#define ttisfloat(o) checktag((o), LUA_TNUMFLT) +#define ttisinteger(o) checktag((o), LUA_TNUMINT) +#define ttisnil(o) checktag((o), LUA_TNIL) +#define ttisboolean(o) checktag((o), LUA_TBOOLEAN) +#define ttislightuserdata(o) checktag((o), LUA_TLIGHTUSERDATA) +#define ttisstring(o) checktype((o), LUA_TSTRING) +#define ttisshrstring(o) checktag((o), ctb(LUA_TSHRSTR)) +#define ttislngstring(o) checktag((o), ctb(LUA_TLNGSTR)) +#define ttistable(o) checktype((o), LUA_TTABLE) +#define ttisrwtable(o) checktag((o), ctb(LUA_TTBLRAM)) +#define ttisrotable(o) checktag((o), ctb(LUA_TTBLROF)) +#define ttisfunction(o) checktype(o, LUA_TFUNCTION) +#define ttisclosure(o) ((rttype(o) & 0x1F) == LUA_TFUNCTION) +#define ttisCclosure(o) checktag((o), ctb(LUA_TCCL)) +#define ttisLclosure(o) checktag((o), ctb(LUA_TLCL)) +#define ttislcf(o) checktag((o), LUA_TLCF) +#define ttisfulluserdata(o) checktag((o), ctb(LUA_TUSERDATA)) +#define ttisthread(o) checktag((o), ctb(LUA_TTHREAD)) +#define ttisdeadkey(o) checktag((o), LUA_TDEADKEY) + + +/* Macros to access values */ +#define ivalue(o) check_exp(ttisinteger(o), val_(o).i) +#define fltvalue(o) check_exp(ttisfloat(o), val_(o).n) +#define nvalue(o) check_exp(ttisnumber(o), \ + (ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o))) +#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc) +#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p) +#define tsvalue(o) check_exp(ttisstring(o), gco2ts(val_(o).gc)) +#define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc)) +#define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc)) +#define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc)) +#define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc)) +#define fvalue(o) check_exp(ttislcf(o), val_(o).f) +#define hvalue(o) check_exp(ttistable(o), gco2t(val_(o).gc)) +#define rwhvalue(o) check_exp(ttisrwtable(o), gco2rot(val_(o).gc)) +#define rohvalue(o) check_exp(ttisrotable(o), gco2rwt(val_(o).gc)) +#define bvalue(o) check_exp(ttisboolean(o), val_(o).b) +#define thvalue(o) check_exp(ttisthread(o), gco2th(val_(o).gc)) +/* a dead value may get the 'gc' field, but cannot access its contents */ +#define deadvalue(o) check_exp(ttisdeadkey(o), cast(void *, val_(o).gc)) + +#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) + + +#define iscollectable(o) (rttype(o) & BIT_ISCOLLECTABLE) + + +/* Macros for internal tests */ +#define righttt(obj) (ttype(obj) == gettt(gcvalue(obj))) + +#define checkliveness(L,obj) \ + lua_longassert(!iscollectable(obj) || \ + (righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj))))) + + +/* Macros to set values */ +#define settt_(o,t) ((o)->tt_=(t)) + +#define setfltvalue(obj,x) \ + { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_TNUMFLT); } + +#define chgfltvalue(obj,x) \ + { TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); } + +#define setivalue(obj,x) \ + { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_TNUMINT); } + +#define chgivalue(obj,x) \ + { TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); } + +#define setnilvalue(obj) settt_(obj, LUA_TNIL) + +#define setfvalue(obj,x) \ + { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); } + +#define setpvalue(obj,x) \ + { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); } + +#define setbvalue(obj,x) \ + { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); } + +#define setgcovalue(L,obj,x) \ + { TValue *io = (obj); GCObject *i_g=(x); \ + val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); } + +#define setsvalue(L,obj,x) \ + { TValue *io = (obj); TString *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(gettt(x_))); \ + checkliveness(L,io); } + +#define setuvalue(L,obj,x) \ + { TValue *io = (obj); Udata *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TUSERDATA)); \ + checkliveness(L,io); } + +#define setthvalue(L,obj,x) \ + { TValue *io = (obj); lua_State *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTHREAD)); \ + checkliveness(L,io); } + +#define setclLvalue(L,obj,x) \ + { TValue *io = (obj); LClosure *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TLCL)); \ + checkliveness(L,io); } + +#define setclCvalue(L,obj,x) \ + { TValue *io = (obj); CClosure *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TCCL)); \ + checkliveness(L,io); } + +#define sethvalue(L,obj,x) \ + { TValue *io = (obj); Table *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(gettt(x_))); \ + checkliveness(L,io); } + +#define setdeadvalue(obj) settt_(obj, LUA_TDEADKEY) + + + +#define setobj(L,obj1,obj2) \ + { TValue *io1=(obj1); *io1 = *(obj2); \ + (void)L; checkliveness(L,io1); } + + +/* +** different types of assignments, according to destination +*/ + +/* from stack to (same) stack */ +#define setobjs2s setobj +/* to stack (not from same stack) */ +#define setobj2s setobj +#define setsvalue2s setsvalue +#define sethvalue2s sethvalue +#define setptvalue2s setptvalue +/* from table to same table */ +#define setobjt2t setobj +/* to new object */ +#define setobj2n setobj +#define setsvalue2n setsvalue + +/* to table (define it as an expression to be used in macros) */ +#define setobj2t(L,o1,o2) ((void)L, *(o1)=*(o2), checkliveness(L,(o1))) + + + + +/* +** {====================================================== +** types and prototypes +** ======================================================= +*/ + + +typedef TValue *StkId; /* index to stack elements */ + + + + +/* +** Header for string value; string bytes follow the end of this structure +** (aligned according to 'UTString'; see next). +*/ +typedef struct TString { + CommonHeader; + lu_byte extra; /* reserved words for short strings; "has hash" for longs */ + lu_byte shrlen; /* length for short strings */ + unsigned int hash; + union { + size_t lnglen; /* length for long strings */ + struct TString *hnext; /* linked list for hash table */ + } u; +} TString; +GET_BYTE_FN(extra,TString,4,16) +GET_BYTE_FN(shrlen,TString,4,24) + + +/* +** Ensures that address after this type is always fully aligned. +*/ +typedef union UTString { + L_Umaxalign dummy; /* ensures maximum alignment for strings */ + TString tsv; +} UTString; + + +/* +** Get the actual string (array of bytes) from a 'TString'. +** (Access to 'extra' ensures that value is really a 'TString'.) +*/ +#define getstr(ts) \ + check_exp(sizeof((ts)->extra), cast(char *, (ts)) + sizeof(UTString)) + + +/* get the actual string (array of bytes) from a Lua value */ +#define svalue(o) getstr(tsvalue(o)) + +/* get string length from 'TString *s' */ +#define tsslen(s) (gettt(s) == LUA_TSHRSTR ? getshrlen(s) : (s)->u.lnglen) + +/* get string length from 'TValue *o' */ +#define vslen(o) tsslen(tsvalue(o)) + + +/* +** Header for userdata; memory area follows the end of this structure +** (aligned according to 'UUdata'; see next). +*/ +typedef struct Udata { + CommonHeader; + lu_byte ttuv_; /* user value's tag */ + struct Table *metatable; + size_t len; /* number of bytes */ + union Value user_; /* user value */ +} Udata; + + +/* +** Ensures that address after this type is always fully aligned. +*/ +typedef union UUdata { + L_Umaxalign dummy; /* ensures maximum alignment for 'local' udata */ + Udata uv; +} UUdata; + + +/* +** Get the address of memory block inside 'Udata'. +** (Access to 'ttuv_' ensures that value is really a 'Udata'.) +*/ +#define getudatamem(u) \ + check_exp(sizeof((u)->ttuv_), (cast(char*, (u)) + sizeof(UUdata))) + +#define setuservalue(L,u,o) \ + { const TValue *io=(o); Udata *iu = (u); \ + iu->user_ = io->value_; iu->ttuv_ = rttype(io); \ + checkliveness(L,io); } + + +#define getuservalue(L,u,o) \ + { TValue *io=(o); const Udata *iu = (u); \ + io->value_ = iu->user_; settt_(io, iu->ttuv_); \ + checkliveness(L,io); } + + +/* +** Description of an upvalue for function prototypes +*/ +typedef struct Upvaldesc { + TString *name; /* upvalue name (for debug information) */ + lu_byte instack; /* whether it is in stack (register) */ + lu_byte idx; /* index of upvalue (in stack or in outer function's list) */ +} Upvaldesc; + + +/* +** Description of a local variable for function prototypes +** (used for debug information) +*/ +typedef struct LocVar { + TString *varname; + int startpc; /* first point where variable is active */ + int endpc; /* first point where variable is dead */ +} LocVar; + + +/* +** Function Prototypes +*/ +typedef struct Proto { + CommonHeader; + lu_byte numparams; /* number of fixed parameters */ + lu_byte is_vararg; + lu_byte maxstacksize; /* number of registers needed by this function */ + int sizeupvalues; /* size of 'upvalues' */ + int sizek; /* size of 'k' */ + int sizecode; + int sizelineinfo; + int sizep; /* size of 'p' */ + int sizelocvars; + int linedefined; /* debug information */ + int lastlinedefined; /* debug information */ + TValue *k; /* constants used by the function */ + Instruction *code; /* opcodes */ + struct Proto **p; /* functions defined inside the function */ + lu_byte *lineinfo; /* packedmap from opcodes to source lines (debug inf) */ + LocVar *locvars; /* information about local variables (debug information) */ + Upvaldesc *upvalues; /* upvalue information */ + TString *source; /* used for debug information */ + GCObject *gclist; +} Proto; + +GET_BYTE_FN(numparams,Proto,4,16) +GET_BYTE_FN(is_vararg,Proto,4,24) +GET_BYTE_FN(maxstacksize,Proto,8,0) + + +/* +** Lua Upvalues +*/ +typedef struct UpVal UpVal; + + +/* +** Closures +*/ + +#define ClosureHeader \ + CommonHeader; lu_byte nupvalues; GCObject *gclist + +typedef struct CClosure { + ClosureHeader; + lua_CFunction f; + TValue upvalue[1]; /* list of upvalues */ +} CClosure; + + +typedef struct LClosure { + ClosureHeader; + struct Proto *p; + UpVal *upvals[1]; /* list of upvalues */ +} LClosure; + + +typedef union Closure { + CClosure c; + LClosure l; +} Closure; + + +#define isLfunction(o) ttisLclosure(o) + +#define getproto(o) (clLvalue(o)->p) + + +/* +** Common Table fields for both table versions (like CommonHeader in +** macro form, to be included in table structure definitions). +** +** Note that the sethvalue() macro works much like the setsvalue() +** macro and handles the abstracted type. the hvalue(o) macro can be +** used to access CommonTable fields, but the rwhvalue(o) and +** rohvalue(o) value variants must be used if accessing variant-specfic +** fields +*/ + +#define CommonTable CommonHeader; \ + lu_byte flags; lu_byte lsizenode; struct Table *metatable; +/* +** Tables +*/ + +typedef union TKey { + struct { + TValuefields; + int next; /* for chaining (offset for next node) */ + } nk; + TValue tvk; +} TKey; + + +/* copy a value into a key without messing up field 'next' */ +#define setnodekey(L,key,obj) \ + { TKey *k_=(key); const TValue *io_=(obj); \ + k_->nk.value_ = io_->value_; k_->nk.tt_ = io_->tt_; \ + (void)L; checkliveness(L,io_); } + + +typedef struct Node { + TValue i_val; + TKey i_key; +} Node; + +typedef struct Table { + /* flags & 1<

lsizenode)) + + +/* +** (address of) a fixed nil value +*/ +#define luaO_nilobject (&luaO_nilobject_) + +LUAI_DDEC const TValue luaO_nilobject_; + +/* size of buffer for 'luaO_utf8esc' function */ +#define UTF8BUFFSZ 8 + +LUAI_FUNC int luaO_int2fb (unsigned int x); +LUAI_FUNC int luaO_fb2int (int x); +LUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x); +LUAI_FUNC int luaO_ceillog2 (unsigned int x); +LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1, + const TValue *p2, TValue *res); +LUAI_FUNC size_t luaO_str2num (const char *s, TValue *o); +LUAI_FUNC int luaO_hexavalue (int c); +LUAI_FUNC void luaO_tostring (lua_State *L, StkId obj); +LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, + va_list argp); +LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); +LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len); + + +#endif + diff --git a/components/lua/lua-5.3/lopcodes.c b/components/lua/lua-5.3/lopcodes.c new file mode 100644 index 00000000..5ca3eb26 --- /dev/null +++ b/components/lua/lua-5.3/lopcodes.c @@ -0,0 +1,124 @@ +/* +** $Id: lopcodes.c,v 1.55.1.1 2017/04/19 17:20:42 roberto Exp $ +** Opcodes for Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#define lopcodes_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lopcodes.h" + + +/* ORDER OP */ + +LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = { + "MOVE", + "LOADK", + "LOADKX", + "LOADBOOL", + "LOADNIL", + "GETUPVAL", + "GETTABUP", + "GETTABLE", + "SETTABUP", + "SETUPVAL", + "SETTABLE", + "NEWTABLE", + "SELF", + "ADD", + "SUB", + "MUL", + "MOD", + "POW", + "DIV", + "IDIV", + "BAND", + "BOR", + "BXOR", + "SHL", + "SHR", + "UNM", + "BNOT", + "NOT", + "LEN", + "CONCAT", + "JMP", + "EQ", + "LT", + "LE", + "TEST", + "TESTSET", + "CALL", + "TAILCALL", + "RETURN", + "FORLOOP", + "FORPREP", + "TFORCALL", + "TFORLOOP", + "SETLIST", + "CLOSURE", + "VARARG", + "EXTRAARG", + NULL +}; + + +#define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m)) + +LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { +/* T A B C mode opcode */ + opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */ + ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */ + ,opmode(0, 1, OpArgN, OpArgN, iABx) /* OP_LOADKX */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */ + ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_LOADNIL */ + ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */ + ,opmode(0, 1, OpArgU, OpArgK, iABC) /* OP_GETTABUP */ + ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */ + ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABUP */ + ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_SETUPVAL */ + ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABLE */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_NEWTABLE */ + ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_SELF */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ADD */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SUB */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MUL */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MOD */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_IDIV */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BAND */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BOR */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BXOR */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHL */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHR */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_BNOT */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */ + ,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */ + ,opmode(0, 0, OpArgR, OpArgN, iAsBx) /* OP_JMP */ + ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */ + ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */ + ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */ + ,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TEST */ + ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */ + ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_RETURN */ + ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORLOOP */ + ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORPREP */ + ,opmode(0, 0, OpArgN, OpArgU, iABC) /* OP_TFORCALL */ + ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_TFORLOOP */ + ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */ + ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */ + ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */ + ,opmode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */ +}; + diff --git a/components/lua/lua-5.3/lopcodes.h b/components/lua/lua-5.3/lopcodes.h new file mode 100644 index 00000000..6feaa1cd --- /dev/null +++ b/components/lua/lua-5.3/lopcodes.h @@ -0,0 +1,297 @@ +/* +** $Id: lopcodes.h,v 1.149.1.1 2017/04/19 17:20:42 roberto Exp $ +** Opcodes for Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#ifndef lopcodes_h +#define lopcodes_h + +#include "llimits.h" + + +/*=========================================================================== + We assume that instructions are unsigned numbers. + All instructions have an opcode in the first 6 bits. + Instructions can have the following fields: + 'A' : 8 bits + 'B' : 9 bits + 'C' : 9 bits + 'Ax' : 26 bits ('A', 'B', and 'C' together) + 'Bx' : 18 bits ('B' and 'C' together) + 'sBx' : signed Bx + + A signed argument is represented in excess K; that is, the number + value is the unsigned value minus K. K is exactly the maximum value + for that argument (so that -max is represented by 0, and +max is + represented by 2*max), which is half the maximum for the corresponding + unsigned argument. +===========================================================================*/ + + +enum OpMode {iABC, iABx, iAsBx, iAx}; /* basic instruction format */ + + +/* +** size and position of opcode arguments. +*/ +#define SIZE_C 9 +#define SIZE_B 9 +#define SIZE_Bx (SIZE_C + SIZE_B) +#define SIZE_A 8 +#define SIZE_Ax (SIZE_C + SIZE_B + SIZE_A) + +#define SIZE_OP 6 + +#define POS_OP 0 +#define POS_A (POS_OP + SIZE_OP) +#define POS_C (POS_A + SIZE_A) +#define POS_B (POS_C + SIZE_C) +#define POS_Bx POS_C +#define POS_Ax POS_A + + +/* +** limits for opcode arguments. +** we use (signed) int to manipulate most arguments, +** so they must fit in LUAI_BITSINT-1 bits (-1 for sign) +*/ +#if SIZE_Bx < LUAI_BITSINT-1 +#define MAXARG_Bx ((1<>1) /* 'sBx' is signed */ +#else +#define MAXARG_Bx MAX_INT +#define MAXARG_sBx MAX_INT +#endif + +#if SIZE_Ax < LUAI_BITSINT-1 +#define MAXARG_Ax ((1<>POS_OP) & MASK1(SIZE_OP,0))) +#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \ + ((cast(Instruction, o)<>pos) & MASK1(size,0))) +#define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \ + ((cast(Instruction, v)<> RK(C) */ +OP_UNM,/* A B R(A) := -R(B) */ +OP_BNOT,/* A B R(A) := ~R(B) */ +OP_NOT,/* A B R(A) := not R(B) */ +OP_LEN,/* A B R(A) := length of R(B) */ + +OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */ + +OP_JMP,/* A sBx pc+=sBx; if (A) close all upvalues >= R(A - 1) */ +OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ +OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ +OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ + +OP_TEST,/* A C if not (R(A) <=> C) then pc++ */ +OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ + +OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */ +OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ +OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */ + +OP_FORLOOP,/* A sBx R(A)+=R(A+2); + if R(A) > 4) & 3)) +#define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3)) +#define testAMode(m) (luaP_opmodes[m] & (1 << 6)) +#define testTMode(m) (luaP_opmodes[m] & (1 << 7)) + + +LUAI_DDEC const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */ + + +/* number of list items to accumulate before a SETLIST instruction */ +#define LFIELDS_PER_FLUSH 50 + + +#endif diff --git a/components/lua/lua-5.3/lparser.c b/components/lua/lua-5.3/lparser.c new file mode 100644 index 00000000..d65a5869 --- /dev/null +++ b/components/lua/lua-5.3/lparser.c @@ -0,0 +1,1668 @@ +/* +** $Id: lparser.c,v 2.155.1.2 2017/04/29 18:11:40 roberto Exp $ +** Lua Parser +** See Copyright Notice in lua.h +*/ + +#define lparser_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "lcode.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "llex.h" +#include "lmem.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" +#include "lstring.h" +#include "ltable.h" +#include "lundump.h" + + + +/* maximum number of local variables per function (must be smaller + than 250, due to the bytecode format) */ +#define MAXVARS 200 + + +#define hasmultret(k) ((k) == VCALL || (k) == VVARARG) + + +/* because all strings are unified by the scanner, the parser + can use pointer equality for string equality */ +#define eqstr(a,b) ((a) == (b)) + + +/* +** nodes for block list (list of active blocks) +*/ +typedef struct BlockCnt { + struct BlockCnt *previous; /* chain */ + int firstlabel; /* index of first label in this block */ + int firstgoto; /* index of first pending goto in this block */ + lu_byte nactvar; /* # active locals outside the block */ + lu_byte upval; /* true if some variable in the block is an upvalue */ + lu_byte isloop; /* true if 'block' is a loop */ +} BlockCnt; + + + +/* +** prototypes for recursive non-terminal functions +*/ +static void statement (LexState *ls); +static void expr (LexState *ls, expdesc *v); + + +/* semantic error */ +static l_noret semerror (LexState *ls, const char *msg) { + ls->t.token = 0; /* remove "near " from final message */ + luaX_syntaxerror(ls, msg); +} + + +static l_noret error_expected (LexState *ls, int token) { + luaX_syntaxerror(ls, + luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); +} + + +static l_noret errorlimit (FuncState *fs, int limit, const char *what) { + lua_State *L = fs->ls->L; + const char *msg; + int line = fs->f->linedefined; + const char *where = (line == 0) + ? "main function" + : luaO_pushfstring(L, "function at line %d", line); + msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s", + what, limit, where); + luaX_syntaxerror(fs->ls, msg); +} + + +static void checklimit (FuncState *fs, int v, int l, const char *what) { + if (v > l) errorlimit(fs, l, what); +} + + +static int testnext (LexState *ls, int c) { + if (ls->t.token == c) { + luaX_next(ls); + return 1; + } + else return 0; +} + + +static void check (LexState *ls, int c) { + if (ls->t.token != c) + error_expected(ls, c); +} + + +static void checknext (LexState *ls, int c) { + check(ls, c); + luaX_next(ls); +} + + +#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } + + + +static void check_match (LexState *ls, int what, int who, int where) { + if (!testnext(ls, what)) { + if (where == ls->linenumber) + error_expected(ls, what); + else { + luaX_syntaxerror(ls, luaO_pushfstring(ls->L, + "%s expected (to close %s at line %d)", + luaX_token2str(ls, what), luaX_token2str(ls, who), where)); + } + } +} + + +static TString *str_checkname (LexState *ls) { + TString *ts; + check(ls, TK_NAME); + ts = ls->t.seminfo.ts; + luaX_next(ls); + return ts; +} + + +static void init_exp (expdesc *e, expkind k, int i) { + e->f = e->t = NO_JUMP; + e->k = k; + e->u.info = i; +} + + +static void codestring (LexState *ls, expdesc *e, TString *s) { + init_exp(e, VK, luaK_stringK(ls->fs, s)); +} + + +static void checkname (LexState *ls, expdesc *e) { + codestring(ls, e, str_checkname(ls)); +} + + +static int registerlocalvar (LexState *ls, TString *varname) { + FuncState *fs = ls->fs; + Proto *f = fs->f; + int oldsize = f->sizelocvars; + luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars, + LocVar, SHRT_MAX, "local variables"); + while (oldsize < f->sizelocvars) + f->locvars[oldsize++].varname = NULL; + f->locvars[fs->nlocvars].varname = varname; + luaC_objbarrier(ls->L, f, varname); + return fs->nlocvars++; +} + + +static void new_localvar (LexState *ls, TString *name) { + FuncState *fs = ls->fs; + Dyndata *dyd = ls->dyd; + int reg = registerlocalvar(ls, name); + checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal, + MAXVARS, "local variables"); + luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1, + dyd->actvar.size, Vardesc, MAX_INT, "local variables"); + dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg); +} + + +static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) { + new_localvar(ls, luaX_newstring(ls, name, sz)); +} + +#define new_localvarliteral(ls,v) \ + new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1) + + +static LocVar *getlocvar (FuncState *fs, int i) { + int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx; + lua_assert(idx < fs->nlocvars); + return &fs->f->locvars[idx]; +} + + +static void adjustlocalvars (LexState *ls, int nvars) { + FuncState *fs = ls->fs; + fs->nactvar = cast_byte(fs->nactvar + nvars); + for (; nvars; nvars--) { + getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc; + } +} + + +static void removevars (FuncState *fs, int tolevel) { + fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel); + while (fs->nactvar > tolevel) + getlocvar(fs, --fs->nactvar)->endpc = fs->pc; +} + + +static int searchupvalue (FuncState *fs, TString *name) { + int i; + Upvaldesc *up = fs->f->upvalues; + for (i = 0; i < fs->nups; i++) { + if (eqstr(up[i].name, name)) return i; + } + return -1; /* not found */ +} + + +static int newupvalue (FuncState *fs, TString *name, expdesc *v) { + Proto *f = fs->f; + int oldsize = f->sizeupvalues; + checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); + luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues, + Upvaldesc, MAXUPVAL, "upvalues"); + while (oldsize < f->sizeupvalues) + f->upvalues[oldsize++].name = NULL; + f->upvalues[fs->nups].instack = (v->k == VLOCAL); + f->upvalues[fs->nups].idx = cast_byte(v->u.info); + f->upvalues[fs->nups].name = name; + luaC_objbarrier(fs->ls->L, f, name); + return fs->nups++; +} + + +static int searchvar (FuncState *fs, TString *n) { + int i; + for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) { + if (eqstr(n, getlocvar(fs, i)->varname)) + return i; + } + return -1; /* not found */ +} + + +/* + Mark block where variable at given level was defined + (to emit close instructions later). +*/ +static void markupval (FuncState *fs, int level) { + BlockCnt *bl = fs->bl; + while (bl->nactvar > level) + bl = bl->previous; + bl->upval = 1; +} + + +/* + Find variable with given name 'n'. If it is an upvalue, add this + upvalue into all intermediate functions. +*/ +static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { + if (fs == NULL) /* no more levels? */ + init_exp(var, VVOID, 0); /* default is global */ + else { + int v = searchvar(fs, n); /* look up locals at current level */ + if (v >= 0) { /* found? */ + init_exp(var, VLOCAL, v); /* variable is local */ + if (!base) + markupval(fs, v); /* local will be used as an upval */ + } + else { /* not found as local at current level; try upvalues */ + int idx = searchupvalue(fs, n); /* try existing upvalues */ + if (idx < 0) { /* not found? */ + singlevaraux(fs->prev, n, var, 0); /* try upper levels */ + if (var->k == VVOID) /* not found? */ + return; /* it is a global */ + /* else was LOCAL or UPVAL */ + idx = newupvalue(fs, n, var); /* will be a new upvalue */ + } + init_exp(var, VUPVAL, idx); /* new or old upvalue */ + } + } +} + + +static void singlevar (LexState *ls, expdesc *var) { + TString *varname = str_checkname(ls); + FuncState *fs = ls->fs; + singlevaraux(fs, varname, var, 1); + if (var->k == VVOID) { /* global name? */ + expdesc key; + singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ + lua_assert(var->k != VVOID); /* this one must exist */ + codestring(ls, &key, varname); /* key is variable name */ + luaK_indexed(fs, var, &key); /* env[varname] */ + } +} + + +static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { + FuncState *fs = ls->fs; + int extra = nvars - nexps; + if (hasmultret(e->k)) { + extra++; /* includes call itself */ + if (extra < 0) extra = 0; + luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ + if (extra > 1) luaK_reserveregs(fs, extra-1); + } + else { + if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */ + if (extra > 0) { + int reg = fs->freereg; + luaK_reserveregs(fs, extra); + luaK_nil(fs, reg, extra); + } + } + if (nexps > nvars) + ls->fs->freereg -= nexps - nvars; /* remove extra values */ +} + + +static void enterlevel (LexState *ls) { + lua_State *L = ls->L; + ++L->nCcalls; + checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels"); +} + + +#define leavelevel(ls) ((ls)->L->nCcalls--) + + +static void closegoto (LexState *ls, int g, Labeldesc *label) { + int i; + FuncState *fs = ls->fs; + Labellist *gl = &ls->dyd->gt; + Labeldesc *gt = &gl->arr[g]; + lua_assert(eqstr(gt->name, label->name)); + if (gt->nactvar < label->nactvar) { + TString *vname = getlocvar(fs, gt->nactvar)->varname; + const char *msg = luaO_pushfstring(ls->L, + " at line %d jumps into the scope of local '%s'", + getstr(gt->name), gt->line, getstr(vname)); + semerror(ls, msg); + } + luaK_patchlist(fs, gt->pc, label->pc); + /* remove goto from pending list */ + for (i = g; i < gl->n - 1; i++) + gl->arr[i] = gl->arr[i + 1]; + gl->n--; +} + + +/* +** try to close a goto with existing labels; this solves backward jumps +*/ +static int findlabel (LexState *ls, int g) { + int i; + BlockCnt *bl = ls->fs->bl; + Dyndata *dyd = ls->dyd; + Labeldesc *gt = &dyd->gt.arr[g]; + /* check labels in current block for a match */ + for (i = bl->firstlabel; i < dyd->label.n; i++) { + Labeldesc *lb = &dyd->label.arr[i]; + if (eqstr(lb->name, gt->name)) { /* correct label? */ + if (gt->nactvar > lb->nactvar && + (bl->upval || dyd->label.n > bl->firstlabel)) + luaK_patchclose(ls->fs, gt->pc, lb->nactvar); + closegoto(ls, g, lb); /* close it */ + return 1; + } + } + return 0; /* label not found; cannot close goto */ +} + + +static int newlabelentry (LexState *ls, Labellist *l, TString *name, + int line, int pc) { + int n = l->n; + luaM_growvector(ls->L, l->arr, n, l->size, + Labeldesc, SHRT_MAX, "labels/gotos"); + l->arr[n].name = name; + l->arr[n].line = line; + l->arr[n].nactvar = ls->fs->nactvar; + l->arr[n].pc = pc; + l->n = n + 1; + return n; +} + + +/* +** check whether new label 'lb' matches any pending gotos in current +** block; solves forward jumps +*/ +static void findgotos (LexState *ls, Labeldesc *lb) { + Labellist *gl = &ls->dyd->gt; + int i = ls->fs->bl->firstgoto; + while (i < gl->n) { + if (eqstr(gl->arr[i].name, lb->name)) + closegoto(ls, i, lb); + else + i++; + } +} + + +/* +** export pending gotos to outer level, to check them against +** outer labels; if the block being exited has upvalues, and +** the goto exits the scope of any variable (which can be the +** upvalue), close those variables being exited. +*/ +static void movegotosout (FuncState *fs, BlockCnt *bl) { + int i = bl->firstgoto; + Labellist *gl = &fs->ls->dyd->gt; + /* correct pending gotos to current block and try to close it + with visible labels */ + while (i < gl->n) { + Labeldesc *gt = &gl->arr[i]; + if (gt->nactvar > bl->nactvar) { + if (bl->upval) + luaK_patchclose(fs, gt->pc, bl->nactvar); + gt->nactvar = bl->nactvar; + } + if (!findlabel(fs->ls, i)) + i++; /* move to next one */ + } +} + + +static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) { + bl->isloop = isloop; + bl->nactvar = fs->nactvar; + bl->firstlabel = fs->ls->dyd->label.n; + bl->firstgoto = fs->ls->dyd->gt.n; + bl->upval = 0; + bl->previous = fs->bl; + fs->bl = bl; + lua_assert(fs->freereg == fs->nactvar); +} + + +/* +** create a label named 'break' to resolve break statements +*/ +static void breaklabel (LexState *ls) { + TString *n = luaS_new(ls->L, "break"); + int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc); + findgotos(ls, &ls->dyd->label.arr[l]); +} + +/* +** generates an error for an undefined 'goto'; choose appropriate +** message when label name is a reserved word (which can only be 'break') +*/ +static l_noret undefgoto (LexState *ls, Labeldesc *gt) { + const char *msg = isreserved(gt->name) + ? "<%s> at line %d not inside a loop" + : "no visible label '%s' for at line %d"; + msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line); + semerror(ls, msg); +} + + +static void leaveblock (FuncState *fs) { + BlockCnt *bl = fs->bl; + LexState *ls = fs->ls; + if (bl->previous && bl->upval) { + /* create a 'jump to here' to close upvalues */ + int j = luaK_jump(fs); + luaK_patchclose(fs, j, bl->nactvar); + luaK_patchtohere(fs, j); + } + if (bl->isloop) + breaklabel(ls); /* close pending breaks */ + fs->bl = bl->previous; + removevars(fs, bl->nactvar); + lua_assert(bl->nactvar == fs->nactvar); + fs->freereg = fs->nactvar; /* free registers */ + ls->dyd->label.n = bl->firstlabel; /* remove local labels */ + if (bl->previous) /* inner block? */ + movegotosout(fs, bl); /* update pending gotos to outer block */ + else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */ + undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */ +} + + +/* +** adds a new prototype into list of prototypes +*/ +static Proto *addprototype (LexState *ls) { + Proto *clp; + lua_State *L = ls->L; + FuncState *fs = ls->fs; + Proto *f = fs->f; /* prototype of current function */ + if (fs->np >= f->sizep) { + int oldsize = f->sizep; + luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions"); + while (oldsize < f->sizep) + f->p[oldsize++] = NULL; + } + f->p[fs->np++] = clp = luaF_newproto(L); + luaC_objbarrier(L, f, clp); + return clp; +} + + +/* +** codes instruction to create new closure in parent function. +** The OP_CLOSURE instruction must use the last available register, +** so that, if it invokes the GC, the GC knows which registers +** are in use at that time. +*/ +static void codeclosure (LexState *ls, expdesc *v) { + FuncState *fs = ls->fs->prev; + init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1)); + luaK_exp2nextreg(fs, v); /* fix it at the last register */ +} + + +static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) { + Proto *f; + /* Initialise all fields in fs apart from fs->f which is done in the caller */ + fs->prev = ls->fs; /* linked list of funcstates */ + fs->ls = ls; + ls->fs = fs; + fs->pc = 0; + fs->lasttarget = 0; + fs->jpc = NO_JUMP; + fs->freereg = 0; + fs->nk = 0; + fs->np = 0; + fs->nups = 0; + fs->nlocvars = 0; + fs->nactvar = 0; + fs->firstlocal = ls->dyd->actvar.n; + fs->bl = NULL; + f = fs->f; + f->source = ls->source; + f->maxstacksize = 2; /* registers 0/1 are always valid */ + f->lineinfo = 0; + fs->sizelineinfo = 0; + fs->lastline = 0; + fs->lastpc = -1; + + enterblock(fs, bl, 0); +} + + +static void close_func (LexState *ls) { + lua_State *L = ls->L; + FuncState *fs = ls->fs; + Proto *f = fs->f; + luaK_ret(fs, 0, 0); /* final return */ + leaveblock(fs); + luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); + f->sizecode = fs->pc; + luaM_growvector(fs->ls->L, f->lineinfo, fs->sizelineinfo, f->sizelineinfo, + lu_byte, MAX_INT, "line codes"); + f->lineinfo[fs->sizelineinfo++] = 0; + luaM_reallocvector(fs->ls->L, f->lineinfo, f->sizelineinfo, fs->sizelineinfo, + lu_byte); + f->sizelineinfo = fs->sizelineinfo; + luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue); + f->sizek = fs->nk; + luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *); + f->sizep = fs->np; + luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar); + f->sizelocvars = fs->nlocvars; + luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc); + f->sizeupvalues = fs->nups; + lua_assert(fs->bl == NULL); + ls->fs = fs->prev; + luaC_checkGC(L); +} + + + +/*============================================================*/ +/* GRAMMAR RULES */ +/*============================================================*/ + + +/* +** check whether current token is in the follow set of a block. +** 'until' closes syntactical blocks, but do not close scope, +** so it is handled in separate. +*/ +static int block_follow (LexState *ls, int withuntil) { + switch (ls->t.token) { + case TK_ELSE: case TK_ELSEIF: + case TK_END: case TK_EOS: + return 1; + case TK_UNTIL: return withuntil; + default: return 0; + } +} + + +static void statlist (LexState *ls) { + /* statlist -> { stat [';'] } */ + while (!block_follow(ls, 1)) { + if (ls->t.token == TK_RETURN) { + statement(ls); + return; /* 'return' must be last statement */ + } + statement(ls); + } +} + + +static void fieldsel (LexState *ls, expdesc *v) { + /* fieldsel -> ['.' | ':'] NAME */ + FuncState *fs = ls->fs; + expdesc key; + luaK_exp2anyregup(fs, v); + luaX_next(ls); /* skip the dot or colon */ + checkname(ls, &key); + luaK_indexed(fs, v, &key); +} + + +static void yindex (LexState *ls, expdesc *v) { + /* index -> '[' expr ']' */ + luaX_next(ls); /* skip the '[' */ + expr(ls, v); + luaK_exp2val(ls->fs, v); + checknext(ls, ']'); +} + + +/* +** {====================================================================== +** Rules for Constructors +** ======================================================================= +*/ + + +struct ConsControl { + expdesc v; /* last list item read */ + expdesc *t; /* table descriptor */ + int nh; /* total number of 'record' elements */ + int na; /* total number of array elements */ + int tostore; /* number of array elements pending to be stored */ +}; + + +static void recfield (LexState *ls, struct ConsControl *cc) { + /* recfield -> (NAME | '['exp1']') = exp1 */ + FuncState *fs = ls->fs; + int reg = ls->fs->freereg; + expdesc key, val; + int rkkey; + if (ls->t.token == TK_NAME) { + checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); + checkname(ls, &key); + } + else /* ls->t.token == '[' */ + yindex(ls, &key); + cc->nh++; + checknext(ls, '='); + rkkey = luaK_exp2RK(fs, &key); + expr(ls, &val); + luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val)); + fs->freereg = reg; /* free registers */ +} + + +static void closelistfield (FuncState *fs, struct ConsControl *cc) { + if (cc->v.k == VVOID) return; /* there is no list item */ + luaK_exp2nextreg(fs, &cc->v); + cc->v.k = VVOID; + if (cc->tostore == LFIELDS_PER_FLUSH) { + luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */ + cc->tostore = 0; /* no more items pending */ + } +} + + +static void lastlistfield (FuncState *fs, struct ConsControl *cc) { + if (cc->tostore == 0) return; + if (hasmultret(cc->v.k)) { + luaK_setmultret(fs, &cc->v); + luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET); + cc->na--; /* do not count last expression (unknown number of elements) */ + } + else { + if (cc->v.k != VVOID) + luaK_exp2nextreg(fs, &cc->v); + luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); + } +} + + +static void listfield (LexState *ls, struct ConsControl *cc) { + /* listfield -> exp */ + expr(ls, &cc->v); + checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor"); + cc->na++; + cc->tostore++; +} + + +static void field (LexState *ls, struct ConsControl *cc) { + /* field -> listfield | recfield */ + switch(ls->t.token) { + case TK_NAME: { /* may be 'listfield' or 'recfield' */ + if (luaX_lookahead(ls) != '=') /* expression? */ + listfield(ls, cc); + else + recfield(ls, cc); + break; + } + case '[': { + recfield(ls, cc); + break; + } + default: { + listfield(ls, cc); + break; + } + } +} + + +static void constructor (LexState *ls, expdesc *t) { + /* constructor -> '{' [ field { sep field } [sep] ] '}' + sep -> ',' | ';' */ + FuncState *fs = ls->fs; + int line = ls->linenumber; + int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); + struct ConsControl cc; + cc.na = cc.nh = cc.tostore = 0; + cc.t = t; + init_exp(t, VRELOCABLE, pc); + init_exp(&cc.v, VVOID, 0); /* no value (yet) */ + luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */ + checknext(ls, '{'); + do { + lua_assert(cc.v.k == VVOID || cc.tostore > 0); + if (ls->t.token == '}') break; + closelistfield(fs, &cc); + field(ls, &cc); + } while (testnext(ls, ',') || testnext(ls, ';')); + check_match(ls, '}', '{', line); + lastlistfield(fs, &cc); + SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */ + SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */ +} + +/* }====================================================================== */ + + + +static void parlist (LexState *ls) { + /* parlist -> [ param { ',' param } ] */ + FuncState *fs = ls->fs; + Proto *f = fs->f; + int nparams = 0; + f->is_vararg = 0; + if (ls->t.token != ')') { /* is 'parlist' not empty? */ + do { + switch (ls->t.token) { + case TK_NAME: { /* param -> NAME */ + new_localvar(ls, str_checkname(ls)); + nparams++; + break; + } + case TK_DOTS: { /* param -> '...' */ + luaX_next(ls); + f->is_vararg = 1; /* declared vararg */ + break; + } + default: luaX_syntaxerror(ls, " or '...' expected"); + } + } while (!f->is_vararg && testnext(ls, ',')); + } + adjustlocalvars(ls, nparams); + f->numparams = cast_byte(fs->nactvar); + luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */ +} + + +static void body (LexState *ls, expdesc *e, int ismethod, int line) { + /* body -> '(' parlist ')' block END */ + FuncState new_fs; + BlockCnt bl; + new_fs.f = addprototype(ls); + new_fs.f->linedefined = line; + open_func(ls, &new_fs, &bl); + checknext(ls, '('); + if (ismethod) { + new_localvarliteral(ls, "self"); /* create 'self' parameter */ + adjustlocalvars(ls, 1); + } + parlist(ls); + checknext(ls, ')'); + statlist(ls); + new_fs.f->lastlinedefined = ls->linenumber; + check_match(ls, TK_END, TK_FUNCTION, line); + codeclosure(ls, e); + close_func(ls); +} + + +static int explist (LexState *ls, expdesc *v) { + /* explist -> expr { ',' expr } */ + int n = 1; /* at least one expression */ + expr(ls, v); + while (testnext(ls, ',')) { + luaK_exp2nextreg(ls->fs, v); + expr(ls, v); + n++; + } + return n; +} + + +static void funcargs (LexState *ls, expdesc *f, int line) { + FuncState *fs = ls->fs; + expdesc args; + int base, nparams; + switch (ls->t.token) { + case '(': { /* funcargs -> '(' [ explist ] ')' */ + luaX_next(ls); + if (ls->t.token == ')') /* arg list is empty? */ + args.k = VVOID; + else { + explist(ls, &args); + luaK_setmultret(fs, &args); + } + check_match(ls, ')', '(', line); + break; + } + case '{': { /* funcargs -> constructor */ + constructor(ls, &args); + break; + } + case TK_STRING: { /* funcargs -> STRING */ + codestring(ls, &args, ls->t.seminfo.ts); + luaX_next(ls); /* must use 'seminfo' before 'next' */ + break; + } + default: { + luaX_syntaxerror(ls, "function arguments expected"); + } + } + lua_assert(f->k == VNONRELOC); + base = f->u.info; /* base register for call */ + if (hasmultret(args.k)) + nparams = LUA_MULTRET; /* open call */ + else { + if (args.k != VVOID) + luaK_exp2nextreg(fs, &args); /* close last argument */ + nparams = fs->freereg - (base+1); + } + init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); + luaK_addlineinfo(fs, fs->pc - 1, line); + fs->freereg = base+1; /* call remove function and arguments and leaves + (unless changed) one result */ +} + + + + +/* +** {====================================================================== +** Expression parsing +** ======================================================================= +*/ + + +static void primaryexp (LexState *ls, expdesc *v) { + /* primaryexp -> NAME | '(' expr ')' */ + switch (ls->t.token) { + case '(': { + int line = ls->linenumber; + luaX_next(ls); + expr(ls, v); + check_match(ls, ')', '(', line); + luaK_dischargevars(ls->fs, v); + return; + } + case TK_NAME: { + singlevar(ls, v); + return; + } + default: { + luaX_syntaxerror(ls, "unexpected symbol"); + } + } +} + + +static void suffixedexp (LexState *ls, expdesc *v) { + /* suffixedexp -> + primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */ + FuncState *fs = ls->fs; + int line = ls->linenumber; + primaryexp(ls, v); + for (;;) { + switch (ls->t.token) { + case '.': { /* fieldsel */ + fieldsel(ls, v); + break; + } + case '[': { /* '[' exp1 ']' */ + expdesc key; + luaK_exp2anyregup(fs, v); + yindex(ls, &key); + luaK_indexed(fs, v, &key); + break; + } + case ':': { /* ':' NAME funcargs */ + expdesc key; + luaX_next(ls); + checkname(ls, &key); + luaK_self(fs, v, &key); + funcargs(ls, v, line); + break; + } + case '(': case TK_STRING: case '{': { /* funcargs */ + luaK_exp2nextreg(fs, v); + funcargs(ls, v, line); + break; + } + default: return; + } + } +} + + +static void simpleexp (LexState *ls, expdesc *v) { + /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... | + constructor | FUNCTION body | suffixedexp */ + switch (ls->t.token) { + case TK_FLT: { + init_exp(v, VKFLT, 0); + v->u.nval = ls->t.seminfo.r; + break; + } + case TK_INT: { + init_exp(v, VKINT, 0); + v->u.ival = ls->t.seminfo.i; + break; + } + case TK_STRING: { + codestring(ls, v, ls->t.seminfo.ts); + break; + } + case TK_NIL: { + init_exp(v, VNIL, 0); + break; + } + case TK_TRUE: { + init_exp(v, VTRUE, 0); + break; + } + case TK_FALSE: { + init_exp(v, VFALSE, 0); + break; + } + case TK_DOTS: { /* vararg */ + FuncState *fs = ls->fs; + check_condition(ls, fs->f->is_vararg, + "cannot use '...' outside a vararg function"); + init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0)); + break; + } + case '{': { /* constructor */ + constructor(ls, v); + return; + } + case TK_FUNCTION: { + luaX_next(ls); + body(ls, v, 0, ls->linenumber); + return; + } + default: { + suffixedexp(ls, v); + return; + } + } + luaX_next(ls); +} + + +static UnOpr getunopr (int op) { + switch (op) { + case TK_NOT: return OPR_NOT; + case '-': return OPR_MINUS; + case '~': return OPR_BNOT; + case '#': return OPR_LEN; + default: return OPR_NOUNOPR; + } +} + + +static BinOpr getbinopr (int op) { + switch (op) { + case '+': return OPR_ADD; + case '-': return OPR_SUB; + case '*': return OPR_MUL; + case '%': return OPR_MOD; + case '^': return OPR_POW; + case '/': return OPR_DIV; + case TK_IDIV: return OPR_IDIV; + case '&': return OPR_BAND; + case '|': return OPR_BOR; + case '~': return OPR_BXOR; + case TK_SHL: return OPR_SHL; + case TK_SHR: return OPR_SHR; + case TK_CONCAT: return OPR_CONCAT; + case TK_NE: return OPR_NE; + case TK_EQ: return OPR_EQ; + case '<': return OPR_LT; + case TK_LE: return OPR_LE; + case '>': return OPR_GT; + case TK_GE: return OPR_GE; + case TK_AND: return OPR_AND; + case TK_OR: return OPR_OR; + default: return OPR_NOBINOPR; + } +} + + +static const struct { + lu_byte left; /* left priority for each binary operator */ + lu_byte right; /* right priority */ +} priority[] = { /* ORDER OPR */ + {10, 10}, {10, 10}, /* '+' '-' */ + {11, 11}, {11, 11}, /* '*' '%' */ + {14, 13}, /* '^' (right associative) */ + {11, 11}, {11, 11}, /* '/' '//' */ + {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */ + {7, 7}, {7, 7}, /* '<<' '>>' */ + {9, 8}, /* '..' (right associative) */ + {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ + {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ + {2, 2}, {1, 1} /* and, or */ +}; + +#define UNARY_PRIORITY 12 /* priority for unary operators */ + + +/* +** subexpr -> (simpleexp | unop subexpr) { binop subexpr } +** where 'binop' is any binary operator with a priority higher than 'limit' +*/ +static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { + BinOpr op; + UnOpr uop; + enterlevel(ls); + uop = getunopr(ls->t.token); + if (uop != OPR_NOUNOPR) { + int line = ls->linenumber; + luaX_next(ls); + subexpr(ls, v, UNARY_PRIORITY); + luaK_prefix(ls->fs, uop, v, line); + } + else simpleexp(ls, v); + /* expand while operators have priorities higher than 'limit' */ + op = getbinopr(ls->t.token); + while (op != OPR_NOBINOPR && priority[op].left > limit) { + expdesc v2; + BinOpr nextop; + int line = ls->linenumber; + luaX_next(ls); + luaK_infix(ls->fs, op, v); + /* read sub-expression with higher priority */ + nextop = subexpr(ls, &v2, priority[op].right); + luaK_posfix(ls->fs, op, v, &v2, line); + op = nextop; + } + leavelevel(ls); + return op; /* return first untreated operator */ +} + + +static void expr (LexState *ls, expdesc *v) { + subexpr(ls, v, 0); +} + +/* }==================================================================== */ + + + +/* +** {====================================================================== +** Rules for Statements +** ======================================================================= +*/ + + +static void block (LexState *ls) { + /* block -> statlist */ + FuncState *fs = ls->fs; + BlockCnt bl; + enterblock(fs, &bl, 0); + statlist(ls); + leaveblock(fs); +} + + +/* +** structure to chain all variables in the left-hand side of an +** assignment +*/ +struct LHS_assign { + struct LHS_assign *prev; + expdesc v; /* variable (global, local, upvalue, or indexed) */ +}; + + +/* +** check whether, in an assignment to an upvalue/local variable, the +** upvalue/local variable is begin used in a previous assignment to a +** table. If so, save original upvalue/local value in a safe place and +** use this safe copy in the previous assignment. +*/ +static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { + FuncState *fs = ls->fs; + int extra = fs->freereg; /* eventual position to save local variable */ + int conflict = 0; + for (; lh; lh = lh->prev) { /* check all previous assignments */ + if (lh->v.k == VINDEXED) { /* assigning to a table? */ + /* table is the upvalue/local being assigned now? */ + if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) { + conflict = 1; + lh->v.u.ind.vt = VLOCAL; + lh->v.u.ind.t = extra; /* previous assignment will use safe copy */ + } + /* index is the local being assigned? (index cannot be upvalue) */ + if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) { + conflict = 1; + lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ + } + } + } + if (conflict) { + /* copy upvalue/local value to a temporary (in position 'extra') */ + OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL; + luaK_codeABC(fs, op, extra, v->u.info, 0); + luaK_reserveregs(fs, 1); + } +} + + +static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) { + expdesc e; + check_condition(ls, vkisvar(lh->v.k), "syntax error"); + if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */ + struct LHS_assign nv; + nv.prev = lh; + suffixedexp(ls, &nv.v); + if (nv.v.k != VINDEXED) + check_conflict(ls, lh, &nv.v); + checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS, + "C levels"); + assignment(ls, &nv, nvars+1); + } + else { /* assignment -> '=' explist */ + int nexps; + checknext(ls, '='); + nexps = explist(ls, &e); + if (nexps != nvars) + adjust_assign(ls, nvars, nexps, &e); + else { + luaK_setoneret(ls->fs, &e); /* close last expression */ + luaK_storevar(ls->fs, &lh->v, &e); + return; /* avoid default */ + } + } + init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */ + luaK_storevar(ls->fs, &lh->v, &e); +} + + +static int cond (LexState *ls) { + /* cond -> exp */ + expdesc v; + expr(ls, &v); /* read condition */ + if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */ + luaK_goiftrue(ls->fs, &v); + return v.f; +} + + +static void gotostat (LexState *ls, int pc) { + int line = ls->linenumber; + TString *label; + int g; + if (testnext(ls, TK_GOTO)) + label = str_checkname(ls); + else { + luaX_next(ls); /* skip break */ + label = luaS_new(ls->L, "break"); + } + g = newlabelentry(ls, &ls->dyd->gt, label, line, pc); + findlabel(ls, g); /* close it if label already defined */ +} + + +/* check for repeated labels on the same block */ +static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) { + int i; + for (i = fs->bl->firstlabel; i < ll->n; i++) { + if (eqstr(label, ll->arr[i].name)) { + const char *msg = luaO_pushfstring(fs->ls->L, + "label '%s' already defined on line %d", + getstr(label), ll->arr[i].line); + semerror(fs->ls, msg); + } + } +} + + +/* skip no-op statements */ +static void skipnoopstat (LexState *ls) { + while (ls->t.token == ';' || ls->t.token == TK_DBCOLON) + statement(ls); +} + + +static void labelstat (LexState *ls, TString *label, int line) { + /* label -> '::' NAME '::' */ + FuncState *fs = ls->fs; + Labellist *ll = &ls->dyd->label; + int l; /* index of new label being created */ + checkrepeated(fs, ll, label); /* check for repeated labels */ + checknext(ls, TK_DBCOLON); /* skip double colon */ + /* create new entry for this label */ + l = newlabelentry(ls, ll, label, line, luaK_getlabel(fs)); + skipnoopstat(ls); /* skip other no-op statements */ + if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */ + /* assume that locals are already out of scope */ + ll->arr[l].nactvar = fs->bl->nactvar; + } + findgotos(ls, &ll->arr[l]); +} + + +static void whilestat (LexState *ls, int line) { + /* whilestat -> WHILE cond DO block END */ + FuncState *fs = ls->fs; + int whileinit; + int condexit; + BlockCnt bl; + luaX_next(ls); /* skip WHILE */ + whileinit = luaK_getlabel(fs); + condexit = cond(ls); + enterblock(fs, &bl, 1); + checknext(ls, TK_DO); + block(ls); + luaK_jumpto(fs, whileinit); + check_match(ls, TK_END, TK_WHILE, line); + leaveblock(fs); + luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ +} + + +static void repeatstat (LexState *ls, int line) { + /* repeatstat -> REPEAT block UNTIL cond */ + int condexit; + FuncState *fs = ls->fs; + int repeat_init = luaK_getlabel(fs); + BlockCnt bl1, bl2; + enterblock(fs, &bl1, 1); /* loop block */ + enterblock(fs, &bl2, 0); /* scope block */ + luaX_next(ls); /* skip REPEAT */ + statlist(ls); + check_match(ls, TK_UNTIL, TK_REPEAT, line); + condexit = cond(ls); /* read condition (inside scope block) */ + if (bl2.upval) /* upvalues? */ + luaK_patchclose(fs, condexit, bl2.nactvar); + leaveblock(fs); /* finish scope */ + luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ + leaveblock(fs); /* finish loop */ +} + + +static int exp1 (LexState *ls) { + expdesc e; + int reg; + expr(ls, &e); + luaK_exp2nextreg(ls->fs, &e); + lua_assert(e.k == VNONRELOC); + reg = e.u.info; + return reg; +} + + +static void forbody (LexState *ls, int base, int line, int nvars, int isnum) { + /* forbody -> DO block */ + BlockCnt bl; + FuncState *fs = ls->fs; + int prep, endfor; + adjustlocalvars(ls, 3); /* control variables */ + checknext(ls, TK_DO); + prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs); + enterblock(fs, &bl, 0); /* scope for declared variables */ + adjustlocalvars(ls, nvars); + luaK_reserveregs(fs, nvars); + block(ls); + leaveblock(fs); /* end of scope for declared variables */ + luaK_patchtohere(fs, prep); + if (isnum) /* numeric for? */ + endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP); + else { /* generic for */ + luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars); + luaK_addlineinfo(fs, fs->pc - 1, line); + endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP); + } + luaK_patchlist(fs, endfor, prep + 1); + luaK_addlineinfo(fs, fs->pc - 1, line); +} + + +static void fornum (LexState *ls, TString *varname, int line) { + /* fornum -> NAME = exp1,exp1[,exp1] forbody */ + FuncState *fs = ls->fs; + int base = fs->freereg; + new_localvarliteral(ls, "(for index)"); + new_localvarliteral(ls, "(for limit)"); + new_localvarliteral(ls, "(for step)"); + new_localvar(ls, varname); + checknext(ls, '='); + exp1(ls); /* initial value */ + checknext(ls, ','); + exp1(ls); /* limit */ + if (testnext(ls, ',')) + exp1(ls); /* optional step */ + else { /* default step = 1 */ + luaK_codek(fs, fs->freereg, luaK_intK(fs, 1)); + luaK_reserveregs(fs, 1); + } + forbody(ls, base, line, 1, 1); +} + + +static void forlist (LexState *ls, TString *indexname) { + /* forlist -> NAME {,NAME} IN explist forbody */ + FuncState *fs = ls->fs; + expdesc e; + int nvars = 4; /* gen, state, control, plus at least one declared var */ + int line; + int base = fs->freereg; + /* create control variables */ + new_localvarliteral(ls, "(for generator)"); + new_localvarliteral(ls, "(for state)"); + new_localvarliteral(ls, "(for control)"); + /* create declared variables */ + new_localvar(ls, indexname); + while (testnext(ls, ',')) { + new_localvar(ls, str_checkname(ls)); + nvars++; + } + checknext(ls, TK_IN); + line = ls->linenumber; + adjust_assign(ls, 3, explist(ls, &e), &e); + luaK_checkstack(fs, 3); /* extra space to call generator */ + forbody(ls, base, line, nvars - 3, 0); +} + + +static void forstat (LexState *ls, int line) { + /* forstat -> FOR (fornum | forlist) END */ + FuncState *fs = ls->fs; + TString *varname; + BlockCnt bl; + enterblock(fs, &bl, 1); /* scope for loop and control variables */ + luaX_next(ls); /* skip 'for' */ + varname = str_checkname(ls); /* first variable name */ + switch (ls->t.token) { + case '=': fornum(ls, varname, line); break; + case ',': case TK_IN: forlist(ls, varname); break; + default: luaX_syntaxerror(ls, "'=' or 'in' expected"); + } + check_match(ls, TK_END, TK_FOR, line); + leaveblock(fs); /* loop scope ('break' jumps to this point) */ +} + + +static void test_then_block (LexState *ls, int *escapelist) { + /* test_then_block -> [IF | ELSEIF] cond THEN block */ + BlockCnt bl; + FuncState *fs = ls->fs; + expdesc v; + int jf; /* instruction to skip 'then' code (if condition is false) */ + luaX_next(ls); /* skip IF or ELSEIF */ + expr(ls, &v); /* read condition */ + checknext(ls, TK_THEN); + if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) { + luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */ + enterblock(fs, &bl, 0); /* must enter block before 'goto' */ + gotostat(ls, v.t); /* handle goto/break */ + while (testnext(ls, ';')) {} /* skip colons */ + if (block_follow(ls, 0)) { /* 'goto' is the entire block? */ + leaveblock(fs); + return; /* and that is it */ + } + else /* must skip over 'then' part if condition is false */ + jf = luaK_jump(fs); + } + else { /* regular case (not goto/break) */ + luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */ + enterblock(fs, &bl, 0); + jf = v.f; + } + statlist(ls); /* 'then' part */ + leaveblock(fs); + if (ls->t.token == TK_ELSE || + ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ + luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */ + luaK_patchtohere(fs, jf); +} + + +static void ifstat (LexState *ls, int line) { + /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ + FuncState *fs = ls->fs; + int escapelist = NO_JUMP; /* exit list for finished parts */ + test_then_block(ls, &escapelist); /* IF cond THEN block */ + while (ls->t.token == TK_ELSEIF) + test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ + if (testnext(ls, TK_ELSE)) + block(ls); /* 'else' part */ + check_match(ls, TK_END, TK_IF, line); + luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ +} + + +static void localfunc (LexState *ls) { + expdesc b; + FuncState *fs = ls->fs; + new_localvar(ls, str_checkname(ls)); /* new local variable */ + adjustlocalvars(ls, 1); /* enter its scope */ + body(ls, &b, 0, ls->linenumber); /* function created in next register */ + /* debug information will only see the variable after this point! */ + getlocvar(fs, b.u.info)->startpc = fs->pc; +} + + +static void localstat (LexState *ls) { + /* stat -> LOCAL NAME {',' NAME} ['=' explist] */ + int nvars = 0; + int nexps; + expdesc e; + do { + new_localvar(ls, str_checkname(ls)); + nvars++; + } while (testnext(ls, ',')); + if (testnext(ls, '=')) + nexps = explist(ls, &e); + else { + e.k = VVOID; + nexps = 0; + } + adjust_assign(ls, nvars, nexps, &e); + adjustlocalvars(ls, nvars); +} + + +static int funcname (LexState *ls, expdesc *v) { + /* funcname -> NAME {fieldsel} [':' NAME] */ + int ismethod = 0; + singlevar(ls, v); + while (ls->t.token == '.') + fieldsel(ls, v); + if (ls->t.token == ':') { + ismethod = 1; + fieldsel(ls, v); + } + return ismethod; +} + + +static void funcstat (LexState *ls, int line) { + /* funcstat -> FUNCTION funcname body */ + int ismethod; + expdesc v, b; + luaX_next(ls); /* skip FUNCTION */ + ismethod = funcname(ls, &v); + body(ls, &b, ismethod, line); + luaK_storevar(ls->fs, &v, &b); + luaK_addlineinfo(ls->fs, ls->fs->pc - 1, line); /* definition "happens" in the first line */ +} + + +static void exprstat (LexState *ls) { + /* stat -> func | assignment */ + FuncState *fs = ls->fs; + struct LHS_assign v; + suffixedexp(ls, &v.v); + if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */ + v.prev = NULL; + assignment(ls, &v, 1); + } + else { /* stat -> func */ + check_condition(ls, v.v.k == VCALL, "syntax error"); + SETARG_C(getinstruction(fs, &v.v), 1); /* call statement uses no results */ + } +} + + +static void retstat (LexState *ls) { + /* stat -> RETURN [explist] [';'] */ + FuncState *fs = ls->fs; + expdesc e; + int first, nret; /* registers with returned values */ + if (block_follow(ls, 1) || ls->t.token == ';') + first = nret = 0; /* return no values */ + else { + nret = explist(ls, &e); /* optional return values */ + if (hasmultret(e.k)) { + luaK_setmultret(fs, &e); + if (e.k == VCALL && nret == 1) { /* tail call? */ + SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL); + lua_assert(GETARG_A(getinstruction(fs,&e)) == fs->nactvar); + } + first = fs->nactvar; + nret = LUA_MULTRET; /* return all values */ + } + else { + if (nret == 1) /* only one single value? */ + first = luaK_exp2anyreg(fs, &e); + else { + luaK_exp2nextreg(fs, &e); /* values must go to the stack */ + first = fs->nactvar; /* return all active values */ + lua_assert(nret == fs->freereg - first); + } + } + } + luaK_ret(fs, first, nret); + testnext(ls, ';'); /* skip optional semicolon */ +} + + +static void statement (LexState *ls) { + int line = ls->linenumber; /* may be needed for error messages */ + enterlevel(ls); + switch (ls->t.token) { + case ';': { /* stat -> ';' (empty statement) */ + luaX_next(ls); /* skip ';' */ + break; + } + case TK_IF: { /* stat -> ifstat */ + ifstat(ls, line); + break; + } + case TK_WHILE: { /* stat -> whilestat */ + whilestat(ls, line); + break; + } + case TK_DO: { /* stat -> DO block END */ + luaX_next(ls); /* skip DO */ + block(ls); + check_match(ls, TK_END, TK_DO, line); + break; + } + case TK_FOR: { /* stat -> forstat */ + forstat(ls, line); + break; + } + case TK_REPEAT: { /* stat -> repeatstat */ + repeatstat(ls, line); + break; + } + case TK_FUNCTION: { /* stat -> funcstat */ + funcstat(ls, line); + break; + } + case TK_LOCAL: { /* stat -> localstat */ + luaX_next(ls); /* skip LOCAL */ + if (testnext(ls, TK_FUNCTION)) /* local function? */ + localfunc(ls); + else + localstat(ls); + break; + } + case TK_DBCOLON: { /* stat -> label */ + luaX_next(ls); /* skip double colon */ + labelstat(ls, str_checkname(ls), line); + break; + } + case TK_RETURN: { /* stat -> retstat */ + luaX_next(ls); /* skip RETURN */ + retstat(ls); + break; + } + case TK_BREAK: /* stat -> breakstat */ + case TK_GOTO: { /* stat -> 'goto' NAME */ + gotostat(ls, luaK_jump(ls->fs)); + break; + } + default: { /* stat -> func | assignment */ + exprstat(ls); + break; + } + } + lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && + ls->fs->freereg >= ls->fs->nactvar); + ls->fs->freereg = ls->fs->nactvar; /* free registers */ + leavelevel(ls); +} + +/* }====================================================================== */ + + +/* +** compiles the main function, which is a regular vararg function with an +** upvalue named LUA_ENV +*/ +static void mainfunc (LexState *ls, FuncState *fs) { + BlockCnt bl; + expdesc v; + open_func(ls, fs, &bl); + fs->f->is_vararg = 1; /* main function is always declared vararg */ + init_exp(&v, VLOCAL, 0); /* create and... */ + newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */ + luaX_next(ls); /* read first token */ + statlist(ls); /* parse main body */ + check(ls, TK_EOS); + close_func(ls); +} + + +static void compile_stripdebug(lua_State *L, Proto *f) { + int level = G(L)->stripdefault; + if (level > 0) + luaU_stripdebug(L, f, level, 1); +} + + +LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, + Dyndata *dyd, const char *name, int firstchar) { + LexState lexstate; + FuncState funcstate; + LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */ + setclLvalue(L, L->top, cl); /* anchor it (to avoid being collected) */ + luaD_inctop(L); + lexstate.h = luaH_new(L); /* create table for scanner */ + sethvalue(L, L->top, lexstate.h); /* anchor it */ + luaD_inctop(L); + funcstate.f = cl->p = luaF_newproto(L); + funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ + lua_assert(iswhite(funcstate.f)); /* do not need barrier here */ + lexstate.buff = buff; + lexstate.dyd = dyd; + dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; + luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); + mainfunc(&lexstate, &funcstate); + lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); + /* all scopes should be correctly finished */ + lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); + compile_stripdebug(L, funcstate.f); + L->top--; /* remove scanner's table */ + return cl; /* closure is on the stack, too */ +} + diff --git a/components/lua/lua-5.3/lparser.h b/components/lua/lua-5.3/lparser.h new file mode 100644 index 00000000..2868d8d5 --- /dev/null +++ b/components/lua/lua-5.3/lparser.h @@ -0,0 +1,136 @@ +/* +** $Id: lparser.h,v 1.76.1.1 2017/04/19 17:20:42 roberto Exp $ +** Lua Parser +** See Copyright Notice in lua.h +*/ + +#ifndef lparser_h +#define lparser_h + +#include "llimits.h" +#include "lobject.h" +#include "lzio.h" + + +/* +** Expression and variable descriptor. +** Code generation for variables and expressions can be delayed to allow +** optimizations; An 'expdesc' structure describes a potentially-delayed +** variable/expression. It has a description of its "main" value plus a +** list of conditional jumps that can also produce its value (generated +** by short-circuit operators 'and'/'or'). +*/ + +/* kinds of variables/expressions */ +typedef enum { + VVOID, /* when 'expdesc' describes the last expression a list, + this kind means an empty list (so, no expression) */ + VNIL, /* constant nil */ + VTRUE, /* constant true */ + VFALSE, /* constant false */ + VK, /* constant in 'k'; info = index of constant in 'k' */ + VKFLT, /* floating constant; nval = numerical float value */ + VKINT, /* integer constant; nval = numerical integer value */ + VNONRELOC, /* expression has its value in a fixed register; + info = result register */ + VLOCAL, /* local variable; info = local register */ + VUPVAL, /* upvalue variable; info = index of upvalue in 'upvalues' */ + VINDEXED, /* indexed variable; + ind.vt = whether 't' is register or upvalue; + ind.t = table register or upvalue; + ind.idx = key's R/K index */ + VJMP, /* expression is a test/comparison; + info = pc of corresponding jump instruction */ + VRELOCABLE, /* expression can put result in any register; + info = instruction pc */ + VCALL, /* expression is a function call; info = instruction pc */ + VVARARG /* vararg expression; info = instruction pc */ +} expkind; + + +#define vkisvar(k) (VLOCAL <= (k) && (k) <= VINDEXED) +#define vkisinreg(k) ((k) == VNONRELOC || (k) == VLOCAL) + +typedef struct expdesc { + expkind k; + union { + lua_Integer ival; /* for VKINT */ + lua_Number nval; /* for VKFLT */ + int info; /* for generic use */ + struct { /* for indexed variables (VINDEXED) */ + short idx; /* index (R/K) */ + lu_byte t; /* table (register or upvalue) */ + lu_byte vt; /* whether 't' is register (VLOCAL) or upvalue (VUPVAL) */ + } ind; + } u; + int t; /* patch list of 'exit when true' */ + int f; /* patch list of 'exit when false' */ +} expdesc; + + +/* description of active local variable */ +typedef struct Vardesc { + short idx; /* variable index in stack */ +} Vardesc; + + +/* description of pending goto statements and label statements */ +typedef struct Labeldesc { + TString *name; /* label identifier */ + int pc; /* position in code */ + int line; /* line where it appeared */ + lu_byte nactvar; /* local level where it appears in current block */ +} Labeldesc; + + +/* list of labels or gotos */ +typedef struct Labellist { + Labeldesc *arr; /* array */ + int n; /* number of entries in use */ + int size; /* array size */ +} Labellist; + + +/* dynamic structures used by the parser */ +typedef struct Dyndata { + struct { /* list of active local variables */ + Vardesc *arr; + int n; + int size; + } actvar; + Labellist gt; /* list of pending gotos */ + Labellist label; /* list of active labels */ +} Dyndata; + + +/* control of blocks */ +struct BlockCnt; /* defined in lparser.c */ + + +/* state needed to generate code for a given function */ +typedef struct FuncState { + Proto *f; /* current function header */ + struct FuncState *prev; /* enclosing function */ + struct LexState *ls; /* lexical state */ + struct BlockCnt *bl; /* chain of current blocks */ + int pc; /* next position to code (equivalent to 'ncode') */ + int lasttarget; /* 'label' of last 'jump label' */ + int jpc; /* list of pending jumps to 'pc' */ + int nk; /* number of elements in 'k' */ + int np; /* number of elements in 'p' */ + int firstlocal; /* index of first local var (in Dyndata array) */ + short nlocvars; /* number of elements in 'f->locvars' */ + lu_byte nactvar; /* number of active local variables */ + lu_byte nups; /* number of upvalues */ + lu_byte freereg; /* first free register */ + int sizelineinfo; /* only used during compilation for line info */ + int lastline; /* ditto */ + int lastpc; /* ditto */ +} FuncState; + + +LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, + Dyndata *dyd, const char *name, int firstchar); + + +#endif diff --git a/components/lua/lua-5.3/lprefix.h b/components/lua/lua-5.3/lprefix.h new file mode 100644 index 00000000..9a749a3f --- /dev/null +++ b/components/lua/lua-5.3/lprefix.h @@ -0,0 +1,45 @@ +/* +** $Id: lprefix.h,v 1.2.1.1 2017/04/19 17:20:42 roberto Exp $ +** Definitions for Lua code that must come before any other header file +** See Copyright Notice in lua.h +*/ + +#ifndef lprefix_h +#define lprefix_h + + +/* +** Allows POSIX/XSI stuff +*/ +#if !defined(LUA_USE_C89) /* { */ + +#if !defined(_XOPEN_SOURCE) +#define _XOPEN_SOURCE 600 +#elif _XOPEN_SOURCE == 0 +#undef _XOPEN_SOURCE /* use -D_XOPEN_SOURCE=0 to undefine it */ +#endif + +/* +** Allows manipulation of large files in gcc and some other compilers +*/ +#if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS) +#define _LARGEFILE_SOURCE 1 +#define _FILE_OFFSET_BITS 64 +#endif + +#endif /* } */ + + +/* +** Windows stuff +*/ +#if defined(_WIN32) /* { */ + +#if !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */ +#endif + +#endif /* } */ + +#endif + diff --git a/components/lua/lua-5.3/lrotable.h b/components/lua/lua-5.3/lrotable.h new file mode 100644 index 00000000..b67dae0b --- /dev/null +++ b/components/lua/lua-5.3/lrotable.h @@ -0,0 +1,2 @@ +// 5.1/5.3 compatibility shim +#include "lnodemcu.h" diff --git a/components/lua/lua-5.3/lstate.c b/components/lua/lua-5.3/lstate.c new file mode 100644 index 00000000..4a0df02e --- /dev/null +++ b/components/lua/lua-5.3/lstate.c @@ -0,0 +1,388 @@ +/* +** $Id: lstate.c,v 2.133.1.1 2017/04/19 17:39:34 roberto Exp $ +** Global State +** See Copyright Notice in lua.h +*/ + +#define lstate_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include + +#include "lua.h" + +#include "lapi.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "llex.h" +#include "lmem.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" + + +#if !defined(LUAI_GCPAUSE) +#define LUAI_GCPAUSE 200 /* 200% */ +#endif + +#if !defined(LUAI_GCMUL) +#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */ +#endif + + +/* +** a macro to help the creation of a unique random seed when a state is +** created; the seed is used to randomize hashes. +*/ +#if !defined(luai_makeseed) +#if defined(LUA_USE_ESP8266) +static inline unsigned int luai_makeseed(void) { + unsigned int r; + asm volatile("rsr %0, ccount" : "=r"(r)); + return r; +} +#elif defined(LUA_USE_ESP) +# include "esp_random.h" +# define luai_makeseed() esp_random() +#else +#include +#define luai_makeseed() cast(unsigned int, time(NULL)) +#endif +#endif + + + +/* +** thread state + extra space +*/ +typedef struct LX { + lu_byte extra_[LUA_EXTRASPACE]; + lua_State l; +} LX; + + +/* +** Main thread combines a thread state and the global state +*/ +typedef struct LG { + LX l; + global_State g; +} LG; + + + +#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l))) + + +/* +** Compute an initial seed as random as possible. Rely on Address Space +** Layout Randomization (if present) to increase randomness.. +*/ +#define addbuff(b,p,e) \ + { size_t t = cast(size_t, e); \ + memcpy(b + p, &t, sizeof(t)); p += sizeof(t); } + +static unsigned int makeseed (lua_State *L) { + char buff[4 * sizeof(size_t)]; + unsigned int h = luai_makeseed(); + int p = 0; + addbuff(buff, p, L); /* heap variable */ + addbuff(buff, p, &h); /* local variable */ + addbuff(buff, p, luaO_nilobject); /* global variable */ + addbuff(buff, p, &lua_newstate); /* public function */ + lua_assert(p == sizeof(buff)); + return luaS_hash(buff, p, h); +} + + +/* +** set GCdebt to a new value keeping the value (totalbytes + GCdebt) +** invariant (and avoiding underflows in 'totalbytes') +*/ +void luaE_setdebt (global_State *g, l_mem debt) { + l_mem tb = gettotalbytes(g); + lua_assert(tb > 0); + if (debt < tb - MAX_LMEM) + debt = tb - MAX_LMEM; /* will make 'totalbytes == MAX_LMEM' */ + g->totalbytes = tb - debt; + g->GCdebt = debt; +} + + +CallInfo *luaE_extendCI (lua_State *L) { + CallInfo *ci = luaM_new(L, CallInfo); + lua_assert(L->ci->next == NULL); + L->ci->next = ci; + ci->previous = L->ci; + ci->next = NULL; + L->nci++; + return ci; +} + + +/* +** free all CallInfo structures not in use by a thread +*/ +void luaE_freeCI (lua_State *L) { + CallInfo *ci = L->ci; + CallInfo *next = ci->next; + ci->next = NULL; + while ((ci = next) != NULL) { + next = ci->next; + luaM_free(L, ci); + L->nci--; + } +} + + +/* +** free half of the CallInfo structures not in use by a thread +*/ +void luaE_shrinkCI (lua_State *L) { + CallInfo *ci = L->ci; + CallInfo *next2; /* next's next */ + /* while there are two nexts */ + while (ci->next != NULL && (next2 = ci->next->next) != NULL) { + luaM_free(L, ci->next); /* free next */ + L->nci--; + ci->next = next2; /* remove 'next' from the list */ + next2->previous = ci; + ci = next2; /* keep next's next */ + } +} + + +static void stack_init (lua_State *L1, lua_State *L) { + int i; CallInfo *ci; + /* initialize stack array */ + L1->stack = luaM_newvector(L, BASIC_STACK_SIZE, TValue); + L1->stacksize = BASIC_STACK_SIZE; + for (i = 0; i < BASIC_STACK_SIZE; i++) + setnilvalue(L1->stack + i); /* erase new stack */ + L1->top = L1->stack; + L1->stack_last = L1->stack + L1->stacksize - EXTRA_STACK; + /* initialize first ci */ + ci = &L1->base_ci; + ci->next = ci->previous = NULL; + ci->callstatus = 0; + ci->func = L1->top; + setnilvalue(L1->top++); /* 'function' entry for this 'ci' */ + ci->top = L1->top + LUA_MINSTACK; + L1->ci = ci; +} + + +static void freestack (lua_State *L) { + if (L->stack == NULL) + return; /* stack not completely built yet */ + L->ci = &L->base_ci; /* free the entire 'ci' list */ + luaE_freeCI(L); + lua_assert(L->nci == 0); + luaM_freearray(L, L->stack, L->stacksize); /* free stack array */ +} + + +/* +** Create registry table and its predefined values +*/ +static void init_registry (lua_State *L, global_State *g) { + TValue temp; + /* create registry */ + Table *registry = luaH_new(L); + sethvalue(L, &g->l_registry, registry); + luaH_resize(L, registry, LUA_RIDX_LAST, 0); + /* registry[LUA_RIDX_MAINTHREAD] = L */ + setthvalue(L, &temp, L); /* temp = L */ + luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &temp); + /* registry[LUA_RIDX_GLOBALS] = table of globals */ + sethvalue(L, &temp, luaH_new(L)); /* temp = new table (global table) */ + luaH_setint(L, registry, LUA_RIDX_GLOBALS, &temp); +} + + +LUAI_FUNC int luaN_init (lua_State *L); +/* +** open parts of the state that may cause memory-allocation errors. +** ('g->version' != NULL flags that the state was completely build) +*/ +static void f_luaopen (lua_State *L, void *ud) { + global_State *g = G(L); + UNUSED(ud); + stack_init(L, L); /* init stack */ + init_registry(L, g); + luaN_init(L); /* optionally map RO string table */ + luaS_init(L); + luaT_init(L); + luaX_init(L); + g->gcrunning = 1; /* allow gc */ + g->version = lua_version(NULL); + luai_userstateopen(L); +} + + +/* +** preinitialize a thread with consistent values without allocating +** any memory (to avoid errors) +*/ +static void preinit_thread (lua_State *L, global_State *g) { + G(L) = g; + L->stack = NULL; + L->ci = NULL; + L->nci = 0; + L->stacksize = 0; + L->twups = L; /* thread has no upvalues */ + L->errorJmp = NULL; + L->nCcalls = 0; + L->hook = NULL; + L->hookmask = 0; + L->basehookcount = 0; + L->allowhook = 1; + resethookcount(L); + L->openupval = NULL; + L->nny = 1; + L->status = LUA_OK; + L->errfunc = 0; +} + + +static lua_State *L0 = NULL; + +static void close_state (lua_State *L) { + global_State *g = G(L); + luaF_close(L, L->stack); /* close all upvalues for this thread */ + luaC_freeallobjects(L); /* collect all objects */ + if (g->version) /* closing a fully built state? */ + luai_userstateclose(L); + luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size); + freestack(L); + if (L == L0) { + (*g->frealloc)(g->ud, g->cache, KEYCACHE_N * sizeof(KeyCacheLine), 0); + L0 = NULL; /* so reopening state initialises properly */ + } + lua_assert(gettotalbytes(g) == sizeof(LG)); + (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */ +} + + +LUA_API lua_State *lua_newthread (lua_State *L) { + global_State *g = G(L); + lua_State *L1; + lua_lock(L); + luaC_checkGC(L); + /* create new thread */ + L1 = &cast(LX *, luaM_newobject(L, LUA_TTHREAD, sizeof(LX)))->l; + L1->marked = luaC_white(g); + L1->tt = LUA_TTHREAD; + /* link it on list 'allgc' */ + L1->next = g->allgc; + g->allgc = obj2gco(L1); + /* anchor it on L stack */ + setthvalue(L, L->top, L1); + api_incr_top(L); + preinit_thread(L1, g); + L1->hookmask = L->hookmask; + L1->basehookcount = L->basehookcount; + L1->hook = L->hook; + resethookcount(L1); + /* initialize L1 extra space */ + memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread), + LUA_EXTRASPACE); + luai_userstatethread(L, L1); + stack_init(L1, L); /* init stack */ + lua_unlock(L); + return L1; +} + + +void luaE_freethread (lua_State *L, lua_State *L1) { + LX *l = fromstate(L1); + luaF_close(L1, L1->stack); /* close all upvalues for this thread */ + lua_assert(L1->openupval == NULL); + luai_userstatefree(L, L1); + freestack(L1); + luaM_free(L, l); +} + +LUAI_FUNC KeyCache *luaE_getcache (int lineno) { + return &G(L0)->cache[lineno][0]; +} + +LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { + int i; + lua_State *L; + global_State *g; + LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG))); + if (l == NULL) return NULL; + L = &l->l.l; + g = &l->g; + L->next = NULL; + L->tt = LUA_TTHREAD; + g->currentwhite = bitmask(WHITE0BIT); + L->marked = luaC_white(g); + preinit_thread(L, g); + g->frealloc = f; + g->ud = ud; + g->mainthread = L; + g->seed = makeseed(L); /* overwritten by LFS value if LFS loaded */ + g->gcrunning = 0; /* no GC while building state */ + g->GCestimate = 0; + g->strt.size = g->strt.nuse = 0; + g->strt.hash = NULL; + setnilvalue(&g->l_registry); + g->panic = NULL; + g->version = NULL; + g->gcstate = GCSpause; + g->gckind = KGC_NORMAL; + g->allgc = g->finobj = g->tobefnz = g->fixedgc = NULL; + g->sweepgc = NULL; + g->gray = g->grayagain = NULL; + g->weak = g->ephemeron = g->allweak = NULL; + g->twups = NULL; + g->totalbytes = sizeof(LG); + g->GCdebt = 0; + g->gcfinnum = 0; + g->gcpause = LUAI_GCPAUSE; + g->gcstepmul = LUAI_GCMUL; + g->stripdefault = CONFIG_LUA_OPTIMIZE_DEBUG; + g->ROstrt.size = 0; + g->ROstrt.nuse = 0; + g->ROstrt.hash = NULL; + g->LFSsize = 0; + setnilvalue(&g->LFStable); + g->l_LFS = NULL; +#ifdef LUA_ENABLE_TEST + if (L0) { /* This is a second state */ + g->cache=G(L0)->cache; + } else { +#endif + L0 = L; + g->cache = cast(KeyCacheLine *, + (*f)(ud, NULL, 0, KEYCACHE_N * sizeof(KeyCacheLine))); + memset(g->cache, 0, KEYCACHE_N * sizeof(KeyCacheLine)); +#ifdef LUA_ENABLE_TEST + } +#endif + for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL; + if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) { + /* memory allocation error: free partial state */ + close_state(L); + L = NULL; + } + return L; +} + + +LUA_API void lua_close (lua_State *L) { + L = G(L)->mainthread; /* only the main thread can be closed */ + lua_lock(L); + close_state(L); +} + + diff --git a/components/lua/lua-5.3/lstate.h b/components/lua/lua-5.3/lstate.h new file mode 100644 index 00000000..40297446 --- /dev/null +++ b/components/lua/lua-5.3/lstate.h @@ -0,0 +1,271 @@ +/* +** $Id: lstate.h,v 2.133.1.1 2017/04/19 17:39:34 roberto Exp $ +** Global State +** See Copyright Notice in lua.h +*/ + +#ifndef lstate_h +#define lstate_h + +#include "lua.h" + +#include "lobject.h" +#include "ltm.h" +#include "lzio.h" + + +/* + +** Some notes about garbage-collected objects: All objects in Lua must +** be kept somehow accessible until being freed, so all objects always +** belong to one (and only one) of these lists, using field 'next' of +** the 'CommonHeader' for the link: +** +** 'allgc': all objects not marked for finalization; +** 'finobj': all objects marked for finalization; +** 'tobefnz': all objects ready to be finalized; +** 'fixedgc': all objects that are not to be collected (currently +** only small strings, such as reserved words). +** +** Moreover, there is another set of lists that control gray objects. +** These lists are linked by fields 'gclist'. (All objects that +** can become gray have such a field. The field is not the same +** in all objects, but it always has this name.) Any gray object +** must belong to one of these lists, and all objects in these lists +** must be gray: +** +** 'gray': regular gray objects, still waiting to be visited. +** 'grayagain': objects that must be revisited at the atomic phase. +** That includes +** - black objects got in a write barrier; +** - all kinds of weak tables during propagation phase; +** - all threads. +** 'weak': tables with weak values to be cleared; +** 'ephemeron': ephemeron tables with white->white entries; +** 'allweak': tables with weak keys and/or weak values to be cleared. +** The last three lists are used only during the atomic phase. + +*/ + + +struct lua_longjmp; /* defined in ldo.c */ + + +/* +** Atomic type (relative to signals) to better ensure that 'lua_sethook' +** is thread safe +*/ +#ifdef LUA_USE_ESP8266 +# define l_define l_signal_t size_t +#endif +#if !defined(l_signalT) +#include +#define l_signalT sig_atomic_t +#endif + + +/* extra stack space to handle TM calls and some other extras */ +#define EXTRA_STACK 5 + + +#define BASIC_STACK_SIZE (2*LUA_MINSTACK) + + +/* kinds of Garbage Collection */ +#define KGC_NORMAL 0 +#define KGC_EMERGENCY 1 /* gc was forced by an allocation failure */ + + +typedef struct stringtable { + TString **hash; + int nuse; /* number of elements */ + int size; +} stringtable; + + +/* +** Information about a call. +** When a thread yields, 'func' is adjusted to pretend that the +** top function has only the yielded values in its stack; in that +** case, the actual 'func' value is saved in field 'extra'. +** When a function calls another with a continuation, 'extra' keeps +** the function index so that, in case of errors, the continuation +** function can be called with the correct top. +*/ +typedef struct CallInfo { + StkId func; /* function index in the stack */ + StkId top; /* top for this function */ + struct CallInfo *previous, *next; /* dynamic call link */ + union { + struct { /* only for Lua functions */ + StkId base; /* base for this function */ + const Instruction *savedpc; + } l; + struct { /* only for C functions */ + lua_KFunction k; /* continuation in case of yields */ + ptrdiff_t old_errfunc; + lua_KContext ctx; /* context info. in case of yields */ + } c; + } u; + ptrdiff_t extra; + short nresults; /* expected number of results from this function */ + unsigned short callstatus; +} CallInfo; + + +/* +** Bits in CallInfo status +*/ +#define CIST_OAH (1<<0) /* original value of 'allowhook' */ +#define CIST_LUA (1<<1) /* call is running a Lua function */ +#define CIST_HOOKED (1<<2) /* call is running a debug hook */ +#define CIST_FRESH (1<<3) /* call is running on a fresh invocation + of luaV_execute */ +#define CIST_YPCALL (1<<4) /* call is a yieldable protected call */ +#define CIST_TAIL (1<<5) /* call was tail called */ +#define CIST_HOOKYIELD (1<<6) /* last hook called yielded */ +#define CIST_LEQ (1<<7) /* using __lt for __le */ +#define CIST_FIN (1<<8) /* call is running a finalizer */ + +#define isLua(ci) ((ci)->callstatus & CIST_LUA) + +/* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */ +#define setoah(st,v) ((st) = ((st) & ~CIST_OAH) | (v)) +#define getoah(st) ((st) & CIST_OAH) + +/* +** KeyCache used for resolution of ROTable entries and Cstrings +*/ +typedef size_t KeyCache; +typedef KeyCache KeyCacheLine[KEYCACHE_M]; + +/* +** 'global state', shared by all threads of this state +*/ + +typedef struct FlashHeader LFSHeader; + +typedef struct global_State { + lua_Alloc frealloc; /* function to reallocate memory */ + void *ud; /* auxiliary data to 'frealloc' */ + l_mem totalbytes; /* number of bytes currently allocated - GCdebt */ + l_mem GCdebt; /* bytes allocated not yet compensated by the collector */ + lu_mem GCmemtrav; /* memory traversed by the GC */ + lu_mem GCestimate; /* an estimate of the non-garbage memory in use */ + stringtable strt; /* hash table for strings */ + TValue l_registry; + unsigned int seed; /* randomized seed for hashes */ + lu_byte currentwhite; + lu_byte gcstate; /* state of garbage collector */ + lu_byte gckind; /* kind of GC running */ + lu_byte gcrunning; /* true if GC is running */ + GCObject *allgc; /* list of all collectable objects */ + GCObject **sweepgc; /* current position of sweep in list */ + GCObject *finobj; /* list of collectable objects with finalizers */ + GCObject *gray; /* list of gray objects */ + GCObject *grayagain; /* list of objects to be traversed atomically */ + GCObject *weak; /* list of tables with weak values */ + GCObject *ephemeron; /* list of ephemeron tables (weak keys) */ + GCObject *allweak; /* list of all-weak tables */ + GCObject *tobefnz; /* list of userdata to be GC */ + GCObject *fixedgc; /* list of objects not to be collected */ + struct lua_State *twups; /* list of threads with open upvalues */ + unsigned int gcfinnum; /* number of finalizers to call in each GC step */ + int gcpause; /* size of pause between successive GCs */ + int gcstepmul; /* GC 'granularity' */ + int stripdefault; /* default stripping level for compilation */ + l_mem gcmemfreeboard; /* Free board which triggers EGC */ + lua_CFunction panic; /* to be called in unprotected errors */ + struct lua_State *mainthread; + const lua_Number *version; /* pointer to version number */ + TString *memerrmsg; /* memory-error message */ + TString *tmname[TM_N]; /* array with tag-method names */ + struct Table *mt[LUA_NUMTAGS]; /* metatables for basic types */ + stringtable ROstrt; /* Flash-based hash table for RO strings */ + TValue LFStable; /* Flash-based Proto main */ + LFSHeader *l_LFS; /* Lua Flash Store header */ + unsigned int LFSsize; /* size of LFS partition */ + KeyCacheLine *cache; /* cache for strings in API */ +} global_State; + + +/* +** 'per thread' state +*/ +struct lua_State { + CommonHeader; + unsigned short nci; /* number of items in 'ci' list */ + lu_byte status; + StkId top; /* first free slot in the stack */ + global_State *l_G; + CallInfo *ci; /* call info for current function */ + const Instruction *oldpc; /* last pc traced */ + StkId stack_last; /* last free slot in the stack */ + StkId stack; /* stack base */ + UpVal *openupval; /* list of open upvalues in this stack */ + GCObject *gclist; + struct lua_State *twups; /* list of threads with open upvalues */ + struct lua_longjmp *errorJmp; /* current error recover point */ + CallInfo base_ci; /* CallInfo for first level (C calling Lua) */ + volatile lua_Hook hook; + ptrdiff_t errfunc; /* current error handling function (stack index) */ + int stacksize; + int basehookcount; + int hookcount; + unsigned short nny; /* number of non-yieldable calls in stack */ + unsigned short nCcalls; /* number of nested C calls */ + l_signalT hookmask; + lu_byte allowhook; +}; + + +#define G(L) (L->l_G) + + +/* +** Union of all collectable objects (only for conversions) +*/ +union GCUnion { + GCObject gc; /* common header */ + struct TString ts; + struct Udata u; + union Closure cl; + struct Table h; + struct ROTable roh; + struct Proto p; + struct lua_State th; /* thread */ +}; +#define cast_u(o) cast(union GCUnion *, (o)) + +/* macros to convert a GCObject into a specific value */ +#define gco2ts(o) \ + check_exp(novariant((gettt(o))) == LUA_TSTRING, &((cast_u(o))->ts)) +#define gco2u(o) check_exp((gettt(o)) == LUA_TUSERDATA, &((cast_u(o))->u)) +#define gco2lcl(o) check_exp((gettt(o)) == LUA_TLCL, &((cast_u(o))->cl.l)) +#define gco2ccl(o) check_exp((gettt(o)) == LUA_TCCL, &((cast_u(o))->cl.c)) +#define gco2cl(o) \ + check_exp(novariant((gettt(o))) == LUA_TFUNCTION, &((cast_u(o))->cl)) +#define gco2t(o) \ + check_exp(novariant((gettt(o))) == LUA_TTABLE, &((cast_u(o))->h)) +#define gco2rwt(o) check_exp((gettt(o)) == LUA_TTBLRAM, &((cast_u(o))->h)) +#define gco2rot(o) check_exp((gettt(o)) == LUA_TTBLROF, &((cast_u(o))->roh)) +#define gco2p(o) check_exp((gettt(o)) == LUA_TPROTO, &((cast_u(o))->p)) +#define gco2th(o) check_exp((gettt(o)) == LUA_TTHREAD, &((cast_u(o))->th)) + + +/* macro to convert a Lua object into a GCObject */ +#define obj2gco(v) \ + check_exp(novariant((v)->tt) < LUA_TDEADKEY, (&(cast_u(v)->gc))) + + +/* actual number of total bytes allocated */ +#define gettotalbytes(g) cast(lu_mem, (g)->totalbytes + (g)->GCdebt) + +LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt); +LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); +LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L); +LUAI_FUNC void luaE_freeCI (lua_State *L); +LUAI_FUNC void luaE_shrinkCI (lua_State *L); +LUAI_FUNC KeyCache *luaE_getcache (int cl); + +#endif diff --git a/components/lua/lua-5.3/lstring.c b/components/lua/lua-5.3/lstring.c new file mode 100644 index 00000000..b9500670 --- /dev/null +++ b/components/lua/lua-5.3/lstring.c @@ -0,0 +1,288 @@ +/* +** $Id: lstring.c,v 2.56.1.1 2017/04/19 17:20:42 roberto Exp $ +** String table (keeps all strings handled by Lua) +** See Copyright Notice in lua.h +*/ + +#define lstring_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" + + +#define MEMERRMSG "not enough memory" + +/* +** Lua will use at most ~(2^LUAI_HASHLIMIT) bytes from a string to +** compute its hash +*/ +#if !defined(LUAI_HASHLIMIT) +#define LUAI_HASHLIMIT 5 +#endif + + +/* +** equality for long strings +*/ +int luaS_eqlngstr (TString *a, TString *b) { + size_t len = a->u.lnglen; + lua_assert(gettt(a) == LUA_TLNGSTR && gettt(b) == LUA_TLNGSTR); + return (a == b) || /* same instance or... */ + ((len == b->u.lnglen) && /* equal length and ... */ + (memcmp(getstr(a), getstr(b), len) == 0)); /* equal contents */ +} + + +unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) { + unsigned int h = seed ^ cast(unsigned int, l); + size_t step = (l >> LUAI_HASHLIMIT) + 1; + for (; l >= step; l -= step) + h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1])); + return h; +} + + +unsigned int luaS_hashlongstr (TString *ts) { + lua_assert(ts->tt == LUA_TLNGSTR); + if (getextra(ts) == 0) { /* no hash? */ + ts->hash = luaS_hash(getstr(ts), ts->u.lnglen, ts->hash); + ts->extra = 1; /* now it has its hash */ + } + return ts->hash; +} + + +/* +** resizes the string table +*/ +void luaS_resize (lua_State *L, int newsize) { + int i; +//***FIX*** rentrancy guard during GC + stringtable *tb = &G(L)->strt; + if (newsize > tb->size) { /* grow table if needed */ + luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *); + for (i = tb->size; i < newsize; i++) + tb->hash[i] = NULL; + } + for (i = 0; i < tb->size; i++) { /* rehash */ + TString *p = tb->hash[i]; + tb->hash[i] = NULL; + while (p) { /* for each node in the list */ + TString *hnext = p->u.hnext; /* save next */ + unsigned int h = lmod(p->hash, newsize); /* new position */ + p->u.hnext = tb->hash[h]; /* chain it */ + tb->hash[h] = p; + p = hnext; + } + } + if (newsize < tb->size) { /* shrink table if needed */ + /* vanishing slice should be empty */ + lua_assert(tb->hash[newsize] == NULL && tb->hash[tb->size - 1] == NULL); + luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *); + } + tb->size = newsize; +} + + +#define STRING_ENTRY(e) (cast(KeyCache,((size_t)(e)) & 1)); +/* +** Initialize the string table and the key cache +*/ +void luaS_init (lua_State *L) { + global_State *g = G(L); + int i, j; + luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */ + /* pre-create memory-error message */ + g->memerrmsg = luaS_newliteral(L, MEMERRMSG); + luaC_fix(L, obj2gco(g->memerrmsg)); /* it should never be collected */ + + /* Initialise the global cache to dummy string entries */ + for (i = 0; i < KEYCACHE_N; i++) { + KeyCache *p = g->cache[i]; + for (j = 0;j < KEYCACHE_M; j++) + p[j] = STRING_ENTRY(g->memerrmsg); + } +} + + + +/* +** creates a new string object +*/ +static TString *createstrobj (lua_State *L, size_t l, int tag, unsigned int h) { + TString *ts; + GCObject *o; + size_t totalsize; /* total size of TString object */ + totalsize = sizelstring(l); + o = luaC_newobj(L, tag, totalsize); + ts = gco2ts(o); + ts->hash = h; + ts->extra = 0; + getstr(ts)[l] = '\0'; /* ending 0 */ + return ts; +} + + +TString *luaS_createlngstrobj (lua_State *L, size_t l) { + TString *ts = createstrobj(L, l, LUA_TLNGSTR, G(L)->seed); + ts->u.lnglen = l; + return ts; +} + + +void luaS_remove (lua_State *L, TString *ts) { + stringtable *tb = &G(L)->strt; + TString **p = &tb->hash[lmod(ts->hash, tb->size)]; + while (*p != ts) /* find previous element */ + p = &(*p)->u.hnext; + *p = (*p)->u.hnext; /* remove element from its list */ + tb->nuse--; +} + + +/* +** checks whether short string exists and reuses it or creates a new one +*/ +static TString *internshrstr (lua_State *L, const char *str, size_t l) { + TString *ts; + global_State *g = G(L); + unsigned int h = luaS_hash(str, l, g->seed); + TString **list = &g->strt.hash[lmod(h, g->strt.size)]; + lua_assert(str != NULL); /* otherwise 'memcmp'/'memcpy' are undefined */ + for (ts = *list; ts != NULL; ts = ts->u.hnext) { + if (l == getshrlen(ts) && + (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) { + /* found! */ + if (isdead(g, ts)) /* dead (but not collected yet)? */ + changewhite(ts); /* resurrect it */ + return ts; + } + } + /* + * The RAM strt is searched first since RAM access is faster than flash + * access. If a miss, then search the RO string table. + */ + if (g->ROstrt.hash) { + for (ts = g->ROstrt.hash[lmod(h, g->ROstrt.size)]; + ts != NULL; + ts = ts->u.hnext) { + if (l == getshrlen(ts) && + memcmp(str, getstr(ts), l * sizeof(char)) == 0) { + /* found in ROstrt! */ + return ts; + } + } + } + if (g->strt.nuse >= g->strt.size && g->strt.size <= MAX_INT/2) { + luaS_resize(L, g->strt.size * 2); + list = &g->strt.hash[lmod(h, g->strt.size)]; /* recompute with new size */ + } + ts = createstrobj(L, l, LUA_TSHRSTR, h); + memcpy(getstr(ts), str, l * sizeof(char)); + ts->shrlen = cast_byte(l); + ts->u.hnext = *list; + *list = ts; + g->strt.nuse++; + return ts; +} + + +/* +** new string (with explicit length) +*/ +TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { + if (l <= LUAI_MAXSHORTLEN) /* short string? */ + return internshrstr(L, str, l); + else { + TString *ts; + if (l >= (MAX_SIZE - sizeof(TString))/sizeof(char)) + luaM_toobig(L); + ts = luaS_createlngstrobj(L, l); + memcpy(getstr(ts), str, l * sizeof(char)); + return ts; + } +} + + +/* +** Create or reuse a zero-terminated string, If the null terminated +** length > sizeof (unisigned) then first check the cache (using the +** string address as a key). The cache can contain only zero- +** terminated strings, so it is safe to use 'strcmp' to check hits. +** +** Note that the cache contains both TStrings and Tables entries but +** both of these addresses word are always aligned, so the address is +** a mulitple of size_t. The lowbit of the address in the cache is +** overwritten with a boolean to tag TString entries +*/ + +#define IS_STRING_ENTRY(e) (e & 1) +#define TSTRING(e) cast(TString *, ((size_t) e) & (~1u)) + +TString *luaS_new (lua_State *L, const char *str) { + unsigned int i = point2uint(str) % KEYCACHE_N; /* hash */ + int j; + TString *ps; + KeyCache *p = G(L)->cache[i]; + + for (j = 0; j < KEYCACHE_M; j++) { + ps = TSTRING(p[j]); + /* string cache entries always point to a valid TString */ + if (IS_STRING_ENTRY(p[j]) && strcmp(str, getstr(ps)) == 0) /* hit? */ + return ps; /* that is it */ + } + /* normal route, move out last element inserting new string at fist slot */ + for (j = KEYCACHE_M - 1; j > 0; j--) { + p[j] = p[j-1]; + } + ps = luaS_newlstr(L, str, strlen(str)); + p[0] = STRING_ENTRY(ps); + return ps; +} + +/* +** Clear API cache of dirty string entries. +*/ +void luaS_clearcache (global_State *g) { + int i, j, k; + TString *ps; + for (i = 0; i < KEYCACHE_N; i++) { + KeyCache *p = g->cache[i]; + for (j = 0, k = 0; j < KEYCACHE_M; j++) { + ps = TSTRING(p[j]); + if (!IS_STRING_ENTRY(p[j]) || !iswhite(cast(GCObject *,ps))) { /* keep entry? */ + if (k < j) + p[k] = p[j]; /* shift down element */ + k++; + } + } + for (;k < KEYCACHE_M; k++) + p[k] = STRING_ENTRY(g->memerrmsg); + } +} + +Udata *luaS_newudata (lua_State *L, size_t s) { + Udata *u; + GCObject *o; + if (s > MAX_SIZE - sizeof(Udata)) + luaM_toobig(L); + o = luaC_newobj(L, LUA_TUSERDATA, sizeludata(s)); + u = gco2u(o); + u->len = s; + u->metatable = NULL; + setuservalue(L, u, luaO_nilobject); + return u; +} + diff --git a/components/lua/lua-5.3/lstring.h b/components/lua/lua-5.3/lstring.h new file mode 100644 index 00000000..b878b645 --- /dev/null +++ b/components/lua/lua-5.3/lstring.h @@ -0,0 +1,49 @@ +/* +** $Id: lstring.h,v 1.61.1.1 2017/04/19 17:20:42 roberto Exp $ +** String table (keep all strings handled by Lua) +** See Copyright Notice in lua.h +*/ + +#ifndef lstring_h +#define lstring_h + +#include "lgc.h" +#include "lobject.h" +#include "lstate.h" + + +#define sizelstring(l) (sizeof(union UTString) + ((l) + 1) * sizeof(char)) + +#define sizeludata(l) (sizeof(union UUdata) + (l)) +#define sizeudata(u) sizeludata((u)->len) + +#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \ + (sizeof(s)/sizeof(char))-1)) + + +/* +** test whether a string is a reserved word +*/ +#define isreserved(s) (gettt(s) == LUA_TSHRSTR && getextra(s) > 0) + + +/* +** equality for short strings, which are always internalized +*/ +#define eqshrstr(a,b) check_exp(gettt(a) == LUA_TSHRSTR, (a) == (b)) + + +LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed); +LUAI_FUNC unsigned int luaS_hashlongstr (TString *ts); +LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b); +LUAI_FUNC void luaS_resize (lua_State *L, int newsize); +LUAI_FUNC void luaS_clearcache (global_State *g); +LUAI_FUNC void luaS_init (lua_State *L); +LUAI_FUNC void luaS_remove (lua_State *L, TString *ts); +LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s); +LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); +LUAI_FUNC TString *luaS_new (lua_State *L, const char *str); +LUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l); + + +#endif diff --git a/components/lua/lua-5.3/lstrlib.c b/components/lua/lua-5.3/lstrlib.c new file mode 100644 index 00000000..0166150f --- /dev/null +++ b/components/lua/lua-5.3/lstrlib.c @@ -0,0 +1,1590 @@ +/* +** $Id: lstrlib.c,v 1.254.1.1 2017/04/19 17:29:57 roberto Exp $ +** Standard library for string operations and pattern-matching +** See Copyright Notice in lua.h +*/ + +#define lstrlib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* +** maximum number of captures that a pattern can do during +** pattern-matching. This limit is arbitrary, but must fit in +** an unsigned char. +*/ +#if !defined(LUA_MAXCAPTURES) +#define LUA_MAXCAPTURES 32 +#endif + + +/* macro to 'unsign' a character */ +#define uchar(c) ((unsigned char)(c)) + + +/* +** Some sizes are better limited to fit in 'int', but must also fit in +** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.) +*/ +#define MAX_SIZET ((size_t)(~(size_t)0)) + +#define MAXSIZE \ + (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX)) + + + + +static int str_len (lua_State *L) { + size_t l; + luaL_checklstring(L, 1, &l); + lua_pushinteger(L, (lua_Integer)l); + return 1; +} + + +/* translate a relative string position: negative means back from end */ +static lua_Integer posrelat (lua_Integer pos, size_t len) { + if (pos >= 0) return pos; + else if (0u - (size_t)pos > len) return 0; + else return (lua_Integer)len + pos + 1; +} + + +static int str_sub (lua_State *L) { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + lua_Integer start = posrelat(luaL_checkinteger(L, 2), l); + lua_Integer end = posrelat(luaL_optinteger(L, 3, -1), l); + if (start < 1) start = 1; + if (end > (lua_Integer)l) end = l; + if (start <= end) + lua_pushlstring(L, s + start - 1, (size_t)(end - start) + 1); + else lua_pushliteral(L, ""); + return 1; +} + + +static int str_reverse (lua_State *L) { + size_t l, i; + luaL_Buffer b; + const char *s = luaL_checklstring(L, 1, &l); + char *p = luaL_buffinitsize(L, &b, l); + for (i = 0; i < l; i++) + p[i] = s[l - i - 1]; + luaL_pushresultsize(&b, l); + return 1; +} + + +static int str_lower (lua_State *L) { + size_t l; + size_t i; + luaL_Buffer b; + const char *s = luaL_checklstring(L, 1, &l); + char *p = luaL_buffinitsize(L, &b, l); + for (i=0; i MAXSIZE / n) /* may overflow? */ + return luaL_error(L, "resulting string too large"); + else { + size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep; + luaL_Buffer b; + char *p = luaL_buffinitsize(L, &b, totallen); + while (n-- > 1) { /* first n-1 copies (followed by separator) */ + memcpy(p, s, l * sizeof(char)); p += l; + if (lsep > 0) { /* empty 'memcpy' is not that cheap */ + memcpy(p, sep, lsep * sizeof(char)); + p += lsep; + } + } + memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */ + luaL_pushresultsize(&b, totallen); + } + return 1; +} + + +static int str_byte (lua_State *L) { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + lua_Integer posi = posrelat(luaL_optinteger(L, 2, 1), l); + lua_Integer pose = posrelat(luaL_optinteger(L, 3, posi), l); + int n, i; + if (posi < 1) posi = 1; + if (pose > (lua_Integer)l) pose = l; + if (posi > pose) return 0; /* empty interval; return no values */ + if (pose - posi >= INT_MAX) /* arithmetic overflow? */ + return luaL_error(L, "string slice too long"); + n = (int)(pose - posi) + 1; + luaL_checkstack(L, n, "string slice too long"); + for (i=0; i= ms->level || ms->capture[l].len == CAP_UNFINISHED) + return luaL_error(ms->L, "invalid capture index %%%d", l + 1); + return l; +} + + +static int capture_to_close (MatchState *ms) { + int level = ms->level; + for (level--; level>=0; level--) + if (ms->capture[level].len == CAP_UNFINISHED) return level; + return luaL_error(ms->L, "invalid pattern capture"); +} + + +static const char *classend (MatchState *ms, const char *p) { + switch (*p++) { + case L_ESC: { + if (p == ms->p_end) + luaL_error(ms->L, "malformed pattern (ends with '%%')"); + return p+1; + } + case '[': { + if (*p == '^') p++; + do { /* look for a ']' */ + if (p == ms->p_end) + luaL_error(ms->L, "malformed pattern (missing ']')"); + if (*(p++) == L_ESC && p < ms->p_end) + p++; /* skip escapes (e.g. '%]') */ + } while (*p != ']'); + return p+1; + } + default: { + return p; + } + } +} + + +static int match_class (int c, int cl) { + int res; + switch (tolower(cl)) { + case 'a' : res = isalpha(c); break; + case 'c' : res = iscntrl(c); break; + case 'd' : res = isdigit(c); break; + case 'g' : res = isgraph(c); break; + case 'l' : res = islower(c); break; + case 'p' : res = ispunct(c); break; + case 's' : res = isspace(c); break; + case 'u' : res = isupper(c); break; + case 'w' : res = isalnum(c); break; + case 'x' : res = isxdigit(c); break; + case 'z' : res = (c == 0); break; /* deprecated option */ + default: return (cl == c); + } + return (islower(cl) ? res : !res); +} + + +static int matchbracketclass (int c, const char *p, const char *ec) { + int sig = 1; + if (*(p+1) == '^') { + sig = 0; + p++; /* skip the '^' */ + } + while (++p < ec) { + if (*p == L_ESC) { + p++; + if (match_class(c, uchar(*p))) + return sig; + } + else if ((*(p+1) == '-') && (p+2 < ec)) { + p+=2; + if (uchar(*(p-2)) <= c && c <= uchar(*p)) + return sig; + } + else if (uchar(*p) == c) return sig; + } + return !sig; +} + + +static int singlematch (MatchState *ms, const char *s, const char *p, + const char *ep) { + if (s >= ms->src_end) + return 0; + else { + int c = uchar(*s); + switch (*p) { + case '.': return 1; /* matches any char */ + case L_ESC: return match_class(c, uchar(*(p+1))); + case '[': return matchbracketclass(c, p, ep-1); + default: return (uchar(*p) == c); + } + } +} + + +static const char *matchbalance (MatchState *ms, const char *s, + const char *p) { + if (p >= ms->p_end - 1) + luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')"); + if (*s != *p) return NULL; + else { + int b = *p; + int e = *(p+1); + int cont = 1; + while (++s < ms->src_end) { + if (*s == e) { + if (--cont == 0) return s+1; + } + else if (*s == b) cont++; + } + } + return NULL; /* string ends out of balance */ +} + + +static const char *max_expand (MatchState *ms, const char *s, + const char *p, const char *ep) { + ptrdiff_t i = 0; /* counts maximum expand for item */ + while (singlematch(ms, s + i, p, ep)) + i++; + /* keeps trying to match with the maximum repetitions */ + while (i>=0) { + const char *res = match(ms, (s+i), ep+1); + if (res) return res; + i--; /* else didn't match; reduce 1 repetition to try again */ + } + return NULL; +} + + +static const char *min_expand (MatchState *ms, const char *s, + const char *p, const char *ep) { + for (;;) { + const char *res = match(ms, s, ep+1); + if (res != NULL) + return res; + else if (singlematch(ms, s, p, ep)) + s++; /* try with one more repetition */ + else return NULL; + } +} + + +static const char *start_capture (MatchState *ms, const char *s, + const char *p, int what) { + const char *res; + int level = ms->level; + if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); + ms->capture[level].init = s; + ms->capture[level].len = what; + ms->level = level+1; + if ((res=match(ms, s, p)) == NULL) /* match failed? */ + ms->level--; /* undo capture */ + return res; +} + + +static const char *end_capture (MatchState *ms, const char *s, + const char *p) { + int l = capture_to_close(ms); + const char *res; + ms->capture[l].len = s - ms->capture[l].init; /* close capture */ + if ((res = match(ms, s, p)) == NULL) /* match failed? */ + ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ + return res; +} + + +static const char *match_capture (MatchState *ms, const char *s, int l) { + size_t len; + l = check_capture(ms, l); + len = ms->capture[l].len; + if ((size_t)(ms->src_end-s) >= len && + memcmp(ms->capture[l].init, s, len) == 0) + return s+len; + else return NULL; +} + + +static const char *match (MatchState *ms, const char *s, const char *p) { + if (ms->matchdepth-- == 0) + luaL_error(ms->L, "pattern too complex"); + init: /* using goto's to optimize tail recursion */ + if (p != ms->p_end) { /* end of pattern? */ + switch (*p) { + case '(': { /* start capture */ + if (*(p + 1) == ')') /* position capture? */ + s = start_capture(ms, s, p + 2, CAP_POSITION); + else + s = start_capture(ms, s, p + 1, CAP_UNFINISHED); + break; + } + case ')': { /* end capture */ + s = end_capture(ms, s, p + 1); + break; + } + case '$': { + if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */ + goto dflt; /* no; go to default */ + s = (s == ms->src_end) ? s : NULL; /* check end of string */ + break; + } + case L_ESC: { /* escaped sequences not in the format class[*+?-]? */ + switch (*(p + 1)) { + case 'b': { /* balanced string? */ + s = matchbalance(ms, s, p + 2); + if (s != NULL) { + p += 4; goto init; /* return match(ms, s, p + 4); */ + } /* else fail (s == NULL) */ + break; + } + case 'f': { /* frontier? */ + const char *ep; char previous; + p += 2; + if (*p != '[') + luaL_error(ms->L, "missing '[' after '%%f' in pattern"); + ep = classend(ms, p); /* points to what is next */ + previous = (s == ms->src_init) ? '\0' : *(s - 1); + if (!matchbracketclass(uchar(previous), p, ep - 1) && + matchbracketclass(uchar(*s), p, ep - 1)) { + p = ep; goto init; /* return match(ms, s, ep); */ + } + s = NULL; /* match failed */ + break; + } + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + case '8': case '9': { /* capture results (%0-%9)? */ + s = match_capture(ms, s, uchar(*(p + 1))); + if (s != NULL) { + p += 2; goto init; /* return match(ms, s, p + 2) */ + } + break; + } + default: goto dflt; + } + break; + } + default: dflt: { /* pattern class plus optional suffix */ + const char *ep = classend(ms, p); /* points to optional suffix */ + /* does not match at least once? */ + if (!singlematch(ms, s, p, ep)) { + if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */ + p = ep + 1; goto init; /* return match(ms, s, ep + 1); */ + } + else /* '+' or no suffix */ + s = NULL; /* fail */ + } + else { /* matched once */ + switch (*ep) { /* handle optional suffix */ + case '?': { /* optional */ + const char *res; + if ((res = match(ms, s + 1, ep + 1)) != NULL) + s = res; + else { + p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */ + } + break; + } + case '+': /* 1 or more repetitions */ + s++; /* 1 match already done */ + /* FALLTHROUGH */ + case '*': /* 0 or more repetitions */ + s = max_expand(ms, s, p, ep); + break; + case '-': /* 0 or more repetitions (minimum) */ + s = min_expand(ms, s, p, ep); + break; + default: /* no suffix */ + s++; p = ep; goto init; /* return match(ms, s + 1, ep); */ + } + } + break; + } + } + } + ms->matchdepth++; + return s; +} + + + +static const char *lmemfind (const char *s1, size_t l1, + const char *s2, size_t l2) { + if (l2 == 0) return s1; /* empty strings are everywhere */ + else if (l2 > l1) return NULL; /* avoids a negative 'l1' */ + else { + const char *init; /* to search for a '*s2' inside 's1' */ + l2--; /* 1st char will be checked by 'memchr' */ + l1 = l1-l2; /* 's2' cannot be found after that */ + while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { + init++; /* 1st char is already checked */ + if (memcmp(init, s2+1, l2) == 0) + return init-1; + else { /* correct 'l1' and 's1' to try again */ + l1 -= init-s1; + s1 = init; + } + } + return NULL; /* not found */ + } +} + + +static void push_onecapture (MatchState *ms, int i, const char *s, + const char *e) { + if (i >= ms->level) { + if (i == 0) /* ms->level == 0, too */ + lua_pushlstring(ms->L, s, e - s); /* add whole match */ + else + luaL_error(ms->L, "invalid capture index %%%d", i + 1); + } + else { + ptrdiff_t l = ms->capture[i].len; + if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture"); + if (l == CAP_POSITION) + lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1); + else + lua_pushlstring(ms->L, ms->capture[i].init, l); + } +} + + +static int push_captures (MatchState *ms, const char *s, const char *e) { + int i; + int nlevels = (ms->level == 0 && s) ? 1 : ms->level; + luaL_checkstack(ms->L, nlevels, "too many captures"); + for (i = 0; i < nlevels; i++) + push_onecapture(ms, i, s, e); + return nlevels; /* number of strings pushed */ +} + + +/* check whether pattern has no special characters */ +static int nospecials (const char *p, size_t l) { + size_t upto = 0; + do { + if (strpbrk(p + upto, SPECIALS)) + return 0; /* pattern has a special character */ + upto += strlen(p + upto) + 1; /* may have more after \0 */ + } while (upto <= l); + return 1; /* no special chars found */ +} + + +static void prepstate (MatchState *ms, lua_State *L, + const char *s, size_t ls, const char *p, size_t lp) { + ms->L = L; + ms->matchdepth = MAXCCALLS; + ms->src_init = s; + ms->src_end = s + ls; + ms->p_end = p + lp; +} + + +static void reprepstate (MatchState *ms) { + ms->level = 0; + lua_assert(ms->matchdepth == MAXCCALLS); +} + + +static int str_find_aux (lua_State *L, int find) { + size_t ls, lp; + const char *s = luaL_checklstring(L, 1, &ls); + const char *p = luaL_checklstring(L, 2, &lp); + lua_Integer init = posrelat(luaL_optinteger(L, 3, 1), ls); + if (init < 1) init = 1; + else if (init > (lua_Integer)ls + 1) { /* start after string's end? */ + lua_pushnil(L); /* cannot find anything */ + return 1; + } + /* explicit request or no special characters? */ + if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) { + /* do a plain search */ + const char *s2 = lmemfind(s + init - 1, ls - (size_t)init + 1, p, lp); + if (s2) { + lua_pushinteger(L, (s2 - s) + 1); + lua_pushinteger(L, (s2 - s) + lp); + return 2; + } + } + else { + MatchState ms; + const char *s1 = s + init - 1; + int anchor = (*p == '^'); + if (anchor) { + p++; lp--; /* skip anchor character */ + } + prepstate(&ms, L, s, ls, p, lp); + do { + const char *res; + reprepstate(&ms); + if ((res=match(&ms, s1, p)) != NULL) { + if (find) { + lua_pushinteger(L, (s1 - s) + 1); /* start */ + lua_pushinteger(L, res - s); /* end */ + return push_captures(&ms, NULL, 0) + 2; + } + else + return push_captures(&ms, s1, res); + } + } while (s1++ < ms.src_end && !anchor); + } + lua_pushnil(L); /* not found */ + return 1; +} + + +static int str_find (lua_State *L) { + return str_find_aux(L, 1); +} + + +static int str_match (lua_State *L) { + return str_find_aux(L, 0); +} + + +/* state for 'gmatch' */ +typedef struct GMatchState { + const char *src; /* current position */ + const char *p; /* pattern */ + const char *lastmatch; /* end of last match */ + MatchState ms; /* match state */ +} GMatchState; + + +static int gmatch_aux (lua_State *L) { + GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3)); + const char *src; + gm->ms.L = L; + for (src = gm->src; src <= gm->ms.src_end; src++) { + const char *e; + reprepstate(&gm->ms); + if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) { + gm->src = gm->lastmatch = e; + return push_captures(&gm->ms, src, e); + } + } + return 0; /* not found */ +} + + +static int gmatch (lua_State *L) { + size_t ls, lp; + const char *s = luaL_checklstring(L, 1, &ls); + const char *p = luaL_checklstring(L, 2, &lp); + GMatchState *gm; + lua_settop(L, 2); /* keep them on closure to avoid being collected */ + gm = (GMatchState *)lua_newuserdata(L, sizeof(GMatchState)); + prepstate(&gm->ms, L, s, ls, p, lp); + gm->src = s; gm->p = p; gm->lastmatch = NULL; + lua_pushcclosure(L, gmatch_aux, 3); + return 1; +} + + +static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, + const char *e) { + size_t l, i; + lua_State *L = ms->L; + const char *news = lua_tolstring(L, 3, &l); + for (i = 0; i < l; i++) { + if (news[i] != L_ESC) + luaL_addchar(b, news[i]); + else { + i++; /* skip ESC */ + if (!isdigit(uchar(news[i]))) { + if (news[i] != L_ESC) + luaL_error(L, "invalid use of '%c' in replacement string", L_ESC); + luaL_addchar(b, news[i]); + } + else if (news[i] == '0') + luaL_addlstring(b, s, e - s); + else { + push_onecapture(ms, news[i] - '1', s, e); + luaL_tolstring(L, -1, NULL); /* if number, convert it to string */ + lua_remove(L, -2); /* remove original value */ + luaL_addvalue(b); /* add capture to accumulated result */ + } + } + } +} + + +static void add_value (MatchState *ms, luaL_Buffer *b, const char *s, + const char *e, int tr) { + lua_State *L = ms->L; + switch (tr) { + case LUA_TFUNCTION: { + int n; + lua_pushvalue(L, 3); + n = push_captures(ms, s, e); + lua_call(L, n, 1); + break; + } + case LUA_TTABLE: { + push_onecapture(ms, 0, s, e); + lua_gettable(L, 3); + break; + } + default: { /* LUA_TNUMBER or LUA_TSTRING */ + add_s(ms, b, s, e); + return; + } + } + if (!lua_toboolean(L, -1)) { /* nil or false? */ + lua_pop(L, 1); + lua_pushlstring(L, s, e - s); /* keep original text */ + } + else if (!lua_isstring(L, -1)) + luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); + luaL_addvalue(b); /* add result to accumulator */ +} + + +static int str_gsub (lua_State *L) { + size_t srcl, lp; + const char *src = luaL_checklstring(L, 1, &srcl); /* subject */ + const char *p = luaL_checklstring(L, 2, &lp); /* pattern */ + const char *lastmatch = NULL; /* end of last match */ + int tr = lua_type(L, 3); /* replacement type */ + lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1); /* max replacements */ + int anchor = (*p == '^'); + lua_Integer n = 0; /* replacement count */ + MatchState ms; + luaL_Buffer b; + luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || + tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, + "string/function/table expected"); + luaL_buffinit(L, &b); + if (anchor) { + p++; lp--; /* skip anchor character */ + } + prepstate(&ms, L, src, srcl, p, lp); + while (n < max_s) { + const char *e; + reprepstate(&ms); /* (re)prepare state for new match */ + if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */ + n++; + add_value(&ms, &b, src, e, tr); /* add replacement to buffer */ + src = lastmatch = e; + } + else if (src < ms.src_end) /* otherwise, skip one character */ + luaL_addchar(&b, *src++); + else break; /* end of subject */ + if (anchor) break; + } + luaL_addlstring(&b, src, ms.src_end-src); + luaL_pushresult(&b); + lua_pushinteger(L, n); /* number of substitutions */ + return 2; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** STRING FORMAT +** ======================================================= +*/ + +#if !defined(lua_number2strx) /* { */ + +/* +** Hexadecimal floating-point formatter +*/ + +#include + +#define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char)) + + +/* +** Number of bits that goes into the first digit. It can be any value +** between 1 and 4; the following definition tries to align the number +** to nibble boundaries by making what is left after that first digit a +** multiple of 4. +*/ +#define L_NBFD ((l_mathlim(MANT_DIG) - 1) % 4 + 1) + + +/* +** Add integer part of 'x' to buffer and return new 'x' +*/ +static lua_Number adddigit (char *buff, int n, lua_Number x) { + lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */ + int d = (int)dd; + buff[n] = (d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */ + return x - dd; /* return what is left */ +} + + +static int num2straux (char *buff, int sz, lua_Number x) { + /* if 'inf' or 'NaN', format it like '%g' */ + if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL) + return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x); + else if (x == 0) { /* can be -0... */ + /* create "0" or "-0" followed by exponent */ + return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x); + } + else { + int e; + lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */ + int n = 0; /* character count */ + if (m < 0) { /* is number negative? */ + buff[n++] = '-'; /* add signal */ + m = -m; /* make it positive */ + } + buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */ + m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */ + e -= L_NBFD; /* this digit goes before the radix point */ + if (m > 0) { /* more digits? */ + buff[n++] = lua_getlocaledecpoint(); /* add radix point */ + do { /* add as many digits as needed */ + m = adddigit(buff, n++, m * 16); + } while (m > 0); + } + n += l_sprintf(buff + n, sz - n, "p%+d", e); /* add exponent */ + lua_assert(n < sz); + return n; + } +} + + +static int lua_number2strx (lua_State *L, char *buff, int sz, + const char *fmt, lua_Number x) { + int n = num2straux(buff, sz, x); + if (fmt[SIZELENMOD] == 'A') { + int i; + for (i = 0; i < n; i++) + buff[i] = toupper(uchar(buff[i])); + } + else if (fmt[SIZELENMOD] != 'a') + return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented"); + return n; +} + +#endif /* } */ + + +/* +** Maximum size of each formatted item. Unlike standard Lua which is +** based on the maximum size is produceD by format('%.99f', -maxfloat), +** NodeMCU just limits this to 128. +*/ +#define MAX_ITEM 128 + + +/* valid flags in a format specification */ +#define FLAGS "-+ #0" + +/* +** maximum size of each format specification (such as "%-099.99d") +*/ +#define MAX_FORMAT 32 + + +static void addquoted (luaL_Buffer *b, const char *s, size_t len) { + luaL_addchar(b, '"'); + while (len--) { + if (*s == '"' || *s == '\\' || *s == '\n') { + luaL_addchar(b, '\\'); + luaL_addchar(b, *s); + } + else if (iscntrl(uchar(*s))) { + char buff[10]; + if (!isdigit(uchar(*(s+1)))) + l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s)); + else + l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s)); + luaL_addstring(b, buff); + } + else + luaL_addchar(b, *s); + s++; + } + luaL_addchar(b, '"'); +} + + +/* +** Ensures the 'buff' string uses a dot as the radix character. +*/ +static void checkdp (char *buff, int nb) { + if (memchr(buff, '.', nb) == NULL) { /* no dot? */ + char point = lua_getlocaledecpoint(); /* try locale point */ + char *ppoint = (char *)memchr(buff, point, nb); + if (ppoint) *ppoint = '.'; /* change it to a dot */ + } +} + + +static void addliteral (lua_State *L, luaL_Buffer *b, int arg) { + switch (lua_type(L, arg)) { + case LUA_TSTRING: { + size_t len; + const char *s = lua_tolstring(L, arg, &len); + addquoted(b, s, len); + break; + } + case LUA_TNUMBER: { + char *buff = luaL_prepbuffsize(b, MAX_ITEM); + int nb; + if (!lua_isinteger(L, arg)) { /* float? */ + lua_Number n = lua_tonumber(L, arg); /* write as hexa ('%a') */ + nb = lua_number2strx(L, buff, MAX_ITEM, "%" LUA_NUMBER_FRMLEN "a", n); + checkdp(buff, nb); /* ensure it uses a dot */ + } + else { /* integers */ + lua_Integer n = lua_tointeger(L, arg); + const char *format = (n == LUA_MININTEGER) /* corner case? */ + ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hexa */ + : LUA_INTEGER_FMT; /* else use default format */ + nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n); + } + luaL_addsize(b, nb); + break; + } + case LUA_TNIL: case LUA_TBOOLEAN: { + luaL_tolstring(L, arg, NULL); + luaL_addvalue(b); + break; + } + default: { + luaL_argerror(L, arg, "value has no literal form"); + } + } +} + + +static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { + const char *p = strfrmt; + while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */ + if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char)) + luaL_error(L, "invalid format (repeated flags)"); + if (isdigit(uchar(*p))) p++; /* skip width */ + if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ + if (*p == '.') { + p++; + if (isdigit(uchar(*p))) p++; /* skip precision */ + if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ + } + if (isdigit(uchar(*p))) + luaL_error(L, "invalid format (width or precision too long)"); + *(form++) = '%'; + memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char)); + form += (p - strfrmt) + 1; + *form = '\0'; + return p; +} + + +/* +** add length modifier into formats +*/ +static void addlenmod (char *form, const char *lenmod) { + size_t l = strlen(form); + size_t lm = strlen(lenmod); + char spec = form[l - 1]; + strcpy(form + l - 1, lenmod); + form[l + lm - 1] = spec; + form[l + lm] = '\0'; +} + + +static int str_format (lua_State *L) { + int top = lua_gettop(L); + int arg = 1; + size_t sfl; + const char *strfrmt = luaL_checklstring(L, arg, &sfl); + const char *strfrmt_end = strfrmt+sfl; + luaL_Buffer b; + luaL_buffinit(L, &b); + while (strfrmt < strfrmt_end) { + if (*strfrmt != L_ESC) + luaL_addchar(&b, *strfrmt++); + else if (*++strfrmt == L_ESC) + luaL_addchar(&b, *strfrmt++); /* %% */ + else { /* format item */ + char form[MAX_FORMAT]; /* to store the format ('%...') */ + char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */ + int nb = 0; /* number of bytes in added item */ + if (++arg > top) + luaL_argerror(L, arg, "no value"); + strfrmt = scanformat(L, strfrmt, form); + switch (*strfrmt++) { + case 'c': { + nb = l_sprintf(buff, MAX_ITEM, form, (int)luaL_checkinteger(L, arg)); + break; + } + case 'd': case 'i': + case 'o': case 'u': case 'x': case 'X': { + lua_Integer n = luaL_checkinteger(L, arg); + addlenmod(form, LUA_INTEGER_FRMLEN); + nb = l_sprintf(buff, MAX_ITEM, form, (LUAI_UACINT)n); + break; + } + case 'a': case 'A': + addlenmod(form, LUA_NUMBER_FRMLEN); + nb = lua_number2strx(L, buff, MAX_ITEM, form, + luaL_checknumber(L, arg)); + break; + case 'e': case 'E': case 'f': + case 'g': case 'G': { + lua_Number n = luaL_checknumber(L, arg); + addlenmod(form, LUA_NUMBER_FRMLEN); + nb = l_sprintf(buff, MAX_ITEM, form, (LUAI_UACNUMBER)n); + break; + } + case 'q': { + addliteral(L, &b, arg); + break; + } + case 's': { + size_t l; + const char *s = luaL_tolstring(L, arg, &l); + if (form[2] == '\0') /* no modifiers? */ + luaL_addvalue(&b); /* keep entire string */ + else { + luaL_argcheck(L, l == strlen(s), arg, "string contains zeros"); + if (!strchr(form, '.') && l >= 100) { + /* no precision and string is too long to be formatted */ + luaL_addvalue(&b); /* keep entire string */ + } + else { /* format the string into 'buff' */ + nb = l_sprintf(buff, MAX_ITEM, form, s); + lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ + } + } + break; + } + default: { /* also treat cases 'pnLlh' */ + return luaL_error(L, "invalid option '%%%c' to 'format'", + *(strfrmt - 1)); + } + } + lua_assert(nb < MAX_ITEM); + luaL_addsize(&b, nb); + } + } + luaL_pushresult(&b); + return 1; +} + +static int str_format2 (lua_State *L) { + if (lua_type(L, 2) == LUA_TTABLE) { + int i,n=lua_rawlen(L,2); + lua_settop(L,2); + for (i = 1; i <= n; i++) + lua_rawgeti(L, 2, i); + lua_remove(L, 2); + } + return str_format(L); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** PACK/UNPACK +** ======================================================= +*/ + + +/* value used for padding */ +#if !defined(LUAL_PACKPADBYTE) +#define LUAL_PACKPADBYTE 0x00 +#endif + +/* maximum size for the binary representation of an integer */ +#define MAXINTSIZE 16 + +/* number of bits in a character */ +#define NB CHAR_BIT + +/* mask for one character (NB 1's) */ +#define MC ((1 << NB) - 1) + +/* size of a lua_Integer */ +#define SZINT ((int)sizeof(lua_Integer)) + + +/* dummy union to get native endianness */ +static const union { + int dummy; + char little; /* true iff machine is little endian */ +} nativeendian = {1}; + + +/* dummy structure to get native alignment requirements */ +struct cD { + char c; + union { double d; void *p; lua_Integer i; lua_Number n; } u; +}; + +#define MAXALIGN (offsetof(struct cD, u)) + + +/* +** Union for serializing floats +*/ +typedef union Ftypes { + float f; + double d; + lua_Number n; + char buff[5 * sizeof(lua_Number)]; /* enough for any float type */ +} Ftypes; + + +/* +** information to pack/unpack stuff +*/ +typedef struct Header { + lua_State *L; + int islittle; + int maxalign; +} Header; + + +/* +** options for pack/unpack +*/ +typedef enum KOption { + Kint, /* signed integers */ + Kuint, /* unsigned integers */ + Kfloat, /* floating-point numbers */ + Kchar, /* fixed-length strings */ + Kstring, /* strings with prefixed length */ + Kzstr, /* zero-terminated strings */ + Kpadding, /* padding */ + Kpaddalign, /* padding for alignment */ + Knop /* no-op (configuration or spaces) */ +} KOption; + + +/* +** Read an integer numeral from string 'fmt' or return 'df' if +** there is no numeral +*/ +static int digit (int c) { return '0' <= c && c <= '9'; } + +static int getnum (const char **fmt, int df) { + if (!digit(**fmt)) /* no number? */ + return df; /* return default value */ + else { + int a = 0; + do { + a = a*10 + (*((*fmt)++) - '0'); + } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10); + return a; + } +} + + +/* +** Read an integer numeral and raises an error if it is larger +** than the maximum size for integers. +*/ +static int getnumlimit (Header *h, const char **fmt, int df) { + int sz = getnum(fmt, df); + if (sz > MAXINTSIZE || sz <= 0) + return luaL_error(h->L, "integral size (%d) out of limits [1,%d]", + sz, MAXINTSIZE); + return sz; +} + + +/* +** Initialize Header +*/ +static void initheader (lua_State *L, Header *h) { + h->L = L; + h->islittle = nativeendian.little; + h->maxalign = 1; +} + + +/* +** Read and classify next option. 'size' is filled with option's size. +*/ +static KOption getoption (Header *h, const char **fmt, int *size) { + int opt = *((*fmt)++); + *size = 0; /* default */ + switch (opt) { + case 'b': *size = sizeof(char); return Kint; + case 'B': *size = sizeof(char); return Kuint; + case 'h': *size = sizeof(short); return Kint; + case 'H': *size = sizeof(short); return Kuint; + case 'l': *size = sizeof(long); return Kint; + case 'L': *size = sizeof(long); return Kuint; + case 'j': *size = sizeof(lua_Integer); return Kint; + case 'J': *size = sizeof(lua_Integer); return Kuint; + case 'T': *size = sizeof(size_t); return Kuint; + case 'f': *size = sizeof(float); return Kfloat; + case 'd': *size = sizeof(double); return Kfloat; + case 'n': *size = sizeof(lua_Number); return Kfloat; + case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint; + case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint; + case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring; + case 'c': + *size = getnum(fmt, -1); + if (*size == -1) + luaL_error(h->L, "missing size for format option 'c'"); + return Kchar; + case 'z': return Kzstr; + case 'x': *size = 1; return Kpadding; + case 'X': return Kpaddalign; + case ' ': break; + case '<': h->islittle = 1; break; + case '>': h->islittle = 0; break; + case '=': h->islittle = nativeendian.little; break; + case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break; + default: luaL_error(h->L, "invalid format option '%c'", opt); + } + return Knop; +} + + +/* +** Read, classify, and fill other details about the next option. +** 'psize' is filled with option's size, 'notoalign' with its +** alignment requirements. +** Local variable 'size' gets the size to be aligned. (Kpadal option +** always gets its full alignment, other options are limited by +** the maximum alignment ('maxalign'). Kchar option needs no alignment +** despite its size. +*/ +static KOption getdetails (Header *h, size_t totalsize, + const char **fmt, int *psize, int *ntoalign) { + KOption opt = getoption(h, fmt, psize); + int align = *psize; /* usually, alignment follows size */ + if (opt == Kpaddalign) { /* 'X' gets alignment from following option */ + if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0) + luaL_argerror(h->L, 1, "invalid next option for option 'X'"); + } + if (align <= 1 || opt == Kchar) /* need no alignment? */ + *ntoalign = 0; + else { + if (align > h->maxalign) /* enforce maximum alignment */ + align = h->maxalign; + if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */ + luaL_argerror(h->L, 1, "format asks for alignment not power of 2"); + *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1); + } + return opt; +} + + +/* +** Pack integer 'n' with 'size' bytes and 'islittle' endianness. +** The final 'if' handles the case when 'size' is larger than +** the size of a Lua integer, correcting the extra sign-extension +** bytes if necessary (by default they would be zeros). +*/ +static void packint (luaL_Buffer *b, lua_Unsigned n, + int islittle, int size, int neg) { + char *buff = luaL_prepbuffsize(b, size); + int i; + buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */ + for (i = 1; i < size; i++) { + n >>= NB; + buff[islittle ? i : size - 1 - i] = (char)(n & MC); + } + if (neg && size > SZINT) { /* negative number need sign extension? */ + for (i = SZINT; i < size; i++) /* correct extra bytes */ + buff[islittle ? i : size - 1 - i] = (char)MC; + } + luaL_addsize(b, size); /* add result to buffer */ +} + + +/* +** Copy 'size' bytes from 'src' to 'dest', correcting endianness if +** given 'islittle' is different from native endianness. +*/ +static void copywithendian (volatile char *dest, volatile const char *src, + int size, int islittle) { + if (islittle == nativeendian.little) { + while (size-- != 0) + *(dest++) = *(src++); + } + else { + dest += size - 1; + while (size-- != 0) + *(dest--) = *(src++); + } +} + + +static int str_pack (lua_State *L) { + luaL_Buffer b; + Header h; + const char *fmt = luaL_checkstring(L, 1); /* format string */ + int arg = 1; /* current argument to pack */ + size_t totalsize = 0; /* accumulate total size of result */ + initheader(L, &h); + lua_pushnil(L); /* mark to separate arguments from string buffer */ + luaL_buffinit(L, &b); + while (*fmt != '\0') { + int size, ntoalign; + KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); + totalsize += ntoalign + size; + while (ntoalign-- > 0) + luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */ + arg++; + switch (opt) { + case Kint: { /* signed integers */ + lua_Integer n = luaL_checkinteger(L, arg); + if (size < SZINT) { /* need overflow check? */ + lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1); + luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow"); + } + packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0)); + break; + } + case Kuint: { /* unsigned integers */ + lua_Integer n = luaL_checkinteger(L, arg); + if (size < SZINT) /* need overflow check? */ + luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)), + arg, "unsigned overflow"); + packint(&b, (lua_Unsigned)n, h.islittle, size, 0); + break; + } + case Kfloat: { /* floating-point options */ + volatile Ftypes u; + char *buff = luaL_prepbuffsize(&b, size); + lua_Number n = luaL_checknumber(L, arg); /* get argument */ + if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */ + else if (size == sizeof(u.d)) u.d = (double)n; + else u.n = n; + /* move 'u' to final result, correcting endianness if needed */ + copywithendian(buff, u.buff, size, h.islittle); + luaL_addsize(&b, size); + break; + } + case Kchar: { /* fixed-size string */ + size_t len; + const char *s = luaL_checklstring(L, arg, &len); + luaL_argcheck(L, len <= (size_t)size, arg, + "string longer than given size"); + luaL_addlstring(&b, s, len); /* add string */ + while (len++ < (size_t)size) /* pad extra space */ + luaL_addchar(&b, LUAL_PACKPADBYTE); + break; + } + case Kstring: { /* strings with length count */ + size_t len; + const char *s = luaL_checklstring(L, arg, &len); + luaL_argcheck(L, size >= (int)sizeof(size_t) || + len < ((size_t)1 << (size * NB)), + arg, "string length does not fit in given size"); + packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */ + luaL_addlstring(&b, s, len); + totalsize += len; + break; + } + case Kzstr: { /* zero-terminated string */ + size_t len; + const char *s = luaL_checklstring(L, arg, &len); + luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros"); + luaL_addlstring(&b, s, len); + luaL_addchar(&b, '\0'); /* add zero at the end */ + totalsize += len + 1; + break; + } + case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */ + case Kpaddalign: case Knop: + arg--; /* undo increment */ + break; + } + } + luaL_pushresult(&b); + return 1; +} + + +static int str_packsize (lua_State *L) { + Header h; + const char *fmt = luaL_checkstring(L, 1); /* format string */ + size_t totalsize = 0; /* accumulate total size of result */ + initheader(L, &h); + while (*fmt != '\0') { + int size, ntoalign; + KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); + size += ntoalign; /* total space used by option */ + luaL_argcheck(L, totalsize <= MAXSIZE - size, 1, + "format result too large"); + totalsize += size; + switch (opt) { + case Kstring: /* strings with length count */ + case Kzstr: /* zero-terminated string */ + luaL_argerror(L, 1, "variable-length format"); + /* call never return, but to avoid warnings: *//* FALLTHROUGH */ + default: break; + } + } + lua_pushinteger(L, (lua_Integer)totalsize); + return 1; +} + + +/* +** Unpack an integer with 'size' bytes and 'islittle' endianness. +** If size is smaller than the size of a Lua integer and integer +** is signed, must do sign extension (propagating the sign to the +** higher bits); if size is larger than the size of a Lua integer, +** it must check the unread bytes to see whether they do not cause an +** overflow. +*/ +static lua_Integer unpackint (lua_State *L, const char *str, + int islittle, int size, int issigned) { + lua_Unsigned res = 0; + int i; + int limit = (size <= SZINT) ? size : SZINT; + for (i = limit - 1; i >= 0; i--) { + res <<= NB; + res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i]; + } + if (size < SZINT) { /* real size smaller than lua_Integer? */ + if (issigned) { /* needs sign extension? */ + lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1); + res = ((res ^ mask) - mask); /* do sign extension */ + } + } + else if (size > SZINT) { /* must check unread bytes */ + int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC; + for (i = limit; i < size; i++) { + if ((unsigned char)str[islittle ? i : size - 1 - i] != mask) + luaL_error(L, "%d-byte integer does not fit into Lua Integer", size); + } + } + return (lua_Integer)res; +} + + +static int str_unpack (lua_State *L) { + Header h; + const char *fmt = luaL_checkstring(L, 1); + size_t ld; + const char *data = luaL_checklstring(L, 2, &ld); + size_t pos = (size_t)posrelat(luaL_optinteger(L, 3, 1), ld) - 1; + int n = 0; /* number of results */ + luaL_argcheck(L, pos <= ld, 3, "initial position out of string"); + initheader(L, &h); + while (*fmt != '\0') { + int size, ntoalign; + KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign); + if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld) + luaL_argerror(L, 2, "data string too short"); + pos += ntoalign; /* skip alignment */ + /* stack space for item + next position */ + luaL_checkstack(L, 2, "too many results"); + n++; + switch (opt) { + case Kint: + case Kuint: { + lua_Integer res = unpackint(L, data + pos, h.islittle, size, + (opt == Kint)); + lua_pushinteger(L, res); + break; + } + case Kfloat: { + volatile Ftypes u; + lua_Number num; + copywithendian(u.buff, data + pos, size, h.islittle); + if (size == sizeof(u.f)) num = (lua_Number)u.f; + else if (size == sizeof(u.d)) num = (lua_Number)u.d; + else num = u.n; + lua_pushnumber(L, num); + break; + } + case Kchar: { + lua_pushlstring(L, data + pos, size); + break; + } + case Kstring: { + size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0); + luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short"); + lua_pushlstring(L, data + pos + size, len); + pos += len; /* skip string */ + break; + } + case Kzstr: { + size_t len = (int)strlen(data + pos); + lua_pushlstring(L, data + pos, len); + pos += len + 1; /* skip string plus final '\0' */ + break; + } + case Kpaddalign: case Kpadding: case Knop: + n--; /* undo increment */ + break; + } + pos += size; + } + lua_pushinteger(L, pos + 1); /* next position */ + return n + 1; +} + +/* }====================================================== */ + +LROT_BEGIN(strlib, NULL, LROT_MASK_INDEX) + LROT_TABENTRY( __index, strlib ) + LROT_FUNCENTRY( __mod, str_format2 ) + LROT_FUNCENTRY( byte, str_byte ) + LROT_FUNCENTRY( char, str_char ) + LROT_FUNCENTRY( dump, str_dump ) + LROT_FUNCENTRY( find, str_find ) + LROT_FUNCENTRY( format, str_format ) + LROT_FUNCENTRY( gmatch, gmatch ) + LROT_FUNCENTRY( gsub, str_gsub ) + LROT_FUNCENTRY( len, str_len ) + LROT_FUNCENTRY( lower, str_lower ) + LROT_FUNCENTRY( match, str_match ) + LROT_FUNCENTRY( rep, str_rep ) + LROT_FUNCENTRY( reverse, str_reverse ) + LROT_FUNCENTRY( sub, str_sub ) + LROT_FUNCENTRY( upper, str_upper ) + LROT_FUNCENTRY( pack, str_pack ) + LROT_FUNCENTRY( packsize, str_packsize ) + LROT_FUNCENTRY( unpack, str_unpack ) +LROT_END(strlib, NULL, LROT_MASK_INDEX) + + +/* +** Open string library +*/ +LUAMOD_API int luaopen_string (lua_State *L) { + lua_pushliteral(L, ""); /* dummy string */ + lua_pushrotable(L, LROT_TABLEREF(strlib)); + lua_setmetatable(L, -2); /* set table as metatable for strings */ + lua_pop(L, 1); /* pop dummy string */ + return 0; +} + diff --git a/components/lua/lua-5.3/ltable.c b/components/lua/lua-5.3/ltable.c new file mode 100644 index 00000000..58041b57 --- /dev/null +++ b/components/lua/lua-5.3/ltable.c @@ -0,0 +1,841 @@ +/* +** $Id: ltable.c,v 2.118.1.4 2018/06/08 16:22:51 roberto Exp $ +** Lua tables (hash) +** See Copyright Notice in lua.h +*/ + +#define ltable_c +#define LUA_CORE + +#include "lprefix.h" + + +/* +** Implementation of tables (aka arrays, objects, or hash tables). +** Tables keep its elements in two parts: an array part and a hash part. +** Non-negative integer keys are all candidates to be kept in the array +** part. The actual size of the array is the largest 'n' such that +** more than half the slots between 1 and n are in use. +** Hash uses a mix of chained scatter table with Brent's variation. +** A main invariant of these tables is that, if an element is not +** in its main position (i.e. the 'original' position that its hash gives +** to it), then the colliding element is in its own main position. +** Hence even when the load factor reaches 100%, performance remains good. +*/ + +#include +#include +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "lvm.h" + + +/* +** Maximum size of array part (MAXASIZE) is 2^MAXABITS. MAXABITS is +** the largest integer such that MAXASIZE fits in an unsigned int. +*/ +#define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1) +#define MAXASIZE (1u << MAXABITS) + +/* +** Maximum size of hash part is 2^MAXHBITS. MAXHBITS is the largest +** integer such that 2^MAXHBITS fits in a signed int. (Note that the +** maximum number of elements in a table, 2^MAXABITS + 2^MAXHBITS, still +** fits comfortably in an unsigned int.) +*/ +#define MAXHBITS (MAXABITS - 1) + + +#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) + +#define hashstr(t,str) hashpow2(t, (str)->hash) +#define hashboolean(t,p) hashpow2(t, p) +#define hashint(t,i) hashpow2(t, i) + + +/* +** for some types, it is better to avoid modulus by power of 2, as +** they tend to have many 2 factors. +*/ +#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) + + +#define hashpointer(t,p) hashmod(t, point2uint(p)) + + +#define dummynode (&dummynode_) + +static const Node dummynode_ = { + {NILCONSTANT}, /* value */ + {{NILCONSTANT, 0}} /* key */ +}; + + +/* +** Hash for floating-point numbers. +** The main computation should be just +** n = frexp(n, &i); return (n * INT_MAX) + i +** but there are some numerical subtleties. +** In a two-complement representation, INT_MAX does not has an exact +** representation as a float, but INT_MIN does; because the absolute +** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the +** absolute value of the product 'frexp * -INT_MIN' is smaller or equal +** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when +** adding 'i'; the use of '~u' (instead of '-u') avoids problems with +** INT_MIN. +*/ +#if !defined(l_hashfloat) +static int l_hashfloat (lua_Number n) { + int i; + lua_Integer ni; + n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN); + if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */ + lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL)); + return 0; + } + else { /* normal case */ + unsigned int u = cast(unsigned int, i) + cast(unsigned int, ni); + return cast_int(u <= cast(unsigned int, INT_MAX) ? u : ~u); + } +} +#endif + + +/* +** returns the 'main' position of an element in a table (that is, the index +** of its hash value) +*/ +static Node *mainposition (const Table *t, const TValue *key) { + switch (ttype(key)) { + case LUA_TNUMINT: + return hashint(t, ivalue(key)); + case LUA_TNUMFLT: + return hashmod(t, l_hashfloat(fltvalue(key))); + case LUA_TSHRSTR: + return hashstr(t, tsvalue(key)); + case LUA_TLNGSTR: + return hashpow2(t, luaS_hashlongstr(tsvalue(key))); + case LUA_TBOOLEAN: + return hashboolean(t, bvalue(key)); + case LUA_TLIGHTUSERDATA: + return hashpointer(t, pvalue(key)); + case LUA_TLCF: + return hashpointer(t, fvalue(key)); + default: + lua_assert(!ttisdeadkey(key)); + return hashpointer(t, gcvalue(key)); + } +} + + +/* +** returns the index for 'key' if 'key' is an appropriate key to live in +** the array part of the table, 0 otherwise. +*/ +static unsigned int arrayindex (const TValue *key) { + if (ttisinteger(key)) { + lua_Integer k = ivalue(key); + if (0 < k && (lua_Unsigned)k <= MAXASIZE) + return cast(unsigned int, k); /* 'key' is an appropriate array index */ + } + return 0; /* 'key' did not match some condition */ +} + + +/* +** returns the index of a 'key' for table traversals. First goes all +** elements in the array part, then elements in the hash part. The +** beginning of a traversal is signaled by 0. +*/ +static unsigned int findindex (lua_State *L, Table *t, StkId key) { + unsigned int i; + if (ttisnil(key)) return 0; /* first iteration */ + i = arrayindex(key); + if (i != 0 && i <= t->sizearray) /* is 'key' inside array part? */ + return i; /* yes; that's the index */ + else { + int nx; + Node *n = mainposition(t, key); + for (;;) { /* check whether 'key' is somewhere in the chain */ + /* key may be dead already, but it is ok to use it in 'next' */ + if (luaV_rawequalobj(gkey(n), key) || + (ttisdeadkey(gkey(n)) && iscollectable(key) && + deadvalue(gkey(n)) == gcvalue(key))) { + i = cast_int(n - gnode(t, 0)); /* key index in hash table */ + /* hash elements are numbered after array ones */ + return (i + 1) + t->sizearray; + } + nx = gnext(n); + if (nx == 0) + luaG_runerror(L, "invalid key to 'next'"); /* key not found */ + else n += nx; + } + } +} + +static void rotable_next(lua_State *L, ROTable *t, TValue *key, TValue *val); + +int luaH_next (lua_State *L, Table *t, StkId key) { + unsigned int i; + if (isrotable(t)) { + rotable_next(L, (ROTable *) t, key, key+1); + return ttisnil(key) ? 0 : 1; + } + i = findindex(L, t, key); /* find original element */ + for (; i < t->sizearray; i++) { /* try first array part */ + if (!ttisnil(&t->array[i])) { /* a non-nil value? */ + setivalue(key, i + 1); + setobj2s(L, key+1, &t->array[i]); + return 1; + } + } + for (i -= t->sizearray; cast_int(i) < sizenode(t); i++) { /* hash part */ + if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ + setobj2s(L, key, gkey(gnode(t, i))); + setobj2s(L, key+1, gval(gnode(t, i))); + return 1; + } + } + return 0; /* no more elements */ +} + + +/* +** {============================================================= +** Rehash +** ============================================================== +*/ + +/* +** Compute the optimal size for the array part of table 't'. 'nums' is a +** "count array" where 'nums[i]' is the number of integers in the table +** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of +** integer keys in the table and leaves with the number of keys that +** will go to the array part; return the optimal size. +*/ +static unsigned int computesizes (unsigned int nums[], unsigned int *pna) { + int i; + unsigned int twotoi; /* 2^i (candidate for optimal size) */ + unsigned int a = 0; /* number of elements smaller than 2^i */ + unsigned int na = 0; /* number of elements to go to array part */ + unsigned int optimal = 0; /* optimal size for array part */ + /* loop while keys can fill more than half of total size */ + for (i = 0, twotoi = 1; + twotoi > 0 && *pna > twotoi / 2; + i++, twotoi *= 2) { + if (nums[i] > 0) { + a += nums[i]; + if (a > twotoi/2) { /* more than half elements present? */ + optimal = twotoi; /* optimal size (till now) */ + na = a; /* all elements up to 'optimal' will go to array part */ + } + } + } + lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal); + *pna = na; + return optimal; +} + + +static int countint (const TValue *key, unsigned int *nums) { + unsigned int k = arrayindex(key); + if (k != 0) { /* is 'key' an appropriate array index? */ + nums[luaO_ceillog2(k)]++; /* count as such */ + return 1; + } + else + return 0; +} + + +/* +** Count keys in array part of table 't': Fill 'nums[i]' with +** number of keys that will go into corresponding slice and return +** total number of non-nil keys. +*/ +static unsigned int numusearray (const Table *t, unsigned int *nums) { + int lg; + unsigned int ttlg; /* 2^lg */ + unsigned int ause = 0; /* summation of 'nums' */ + unsigned int i = 1; /* count to traverse all array keys */ + /* traverse each slice */ + for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) { + unsigned int lc = 0; /* counter */ + unsigned int lim = ttlg; + if (lim > t->sizearray) { + lim = t->sizearray; /* adjust upper limit */ + if (i > lim) + break; /* no more elements to count */ + } + /* count elements in range (2^(lg - 1), 2^lg] */ + for (; i <= lim; i++) { + if (!ttisnil(&t->array[i-1])) + lc++; + } + nums[lg] += lc; + ause += lc; + } + return ause; +} + + +static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) { + int totaluse = 0; /* total number of elements */ + int ause = 0; /* elements added to 'nums' (can go to array part) */ + int i = sizenode(t); + while (i--) { + Node *n = &t->node[i]; + if (!ttisnil(gval(n))) { + ause += countint(gkey(n), nums); + totaluse++; + } + } + *pna += ause; + return totaluse; +} + + +static void setarrayvector (lua_State *L, Table *t, unsigned int size) { + unsigned int i; + luaM_reallocvector(L, t->array, t->sizearray, size, TValue); + for (i=t->sizearray; iarray[i]); + t->sizearray = size; +} + + +static void setnodevector (lua_State *L, Table *t, unsigned int size) { + if (size == 0) { /* no elements to hash part? */ + t->node = cast(Node *, dummynode); /* use common 'dummynode' */ + t->lsizenode = 0; + t->lastfree = NULL; /* signal that it is using dummy node */ + } + else { + int i; + int lsize = luaO_ceillog2(size); + if (lsize > MAXHBITS) + luaG_runerror(L, "table overflow"); + size = twoto(lsize); + t->node = luaM_newvector(L, size, Node); + for (i = 0; i < (int)size; i++) { + Node *n = gnode(t, i); + gnext(n) = 0; + setnilvalue(wgkey(n)); + setnilvalue(gval(n)); + } + t->lsizenode = cast_byte(lsize); + t->lastfree = gnode(t, size); /* all positions are free */ + } +} + + +typedef struct { + Table *t; + unsigned int nhsize; +} AuxsetnodeT; + + +static void auxsetnode (lua_State *L, void *ud) { + AuxsetnodeT *asn = cast(AuxsetnodeT *, ud); + setnodevector(L, asn->t, asn->nhsize); +} + + +void luaH_resize (lua_State *L, Table *t, unsigned int nasize, + unsigned int nhsize) { + unsigned int i; + int j; + AuxsetnodeT asn; + unsigned int oldasize = t->sizearray; + int oldhsize = allocsizenode(t); + Node *nold = t->node; /* save old hash ... */ + if (nasize > oldasize) /* array part must grow? */ + setarrayvector(L, t, nasize); + /* create new hash part with appropriate size */ + asn.t = t; asn.nhsize = nhsize; + if (luaD_rawrunprotected(L, auxsetnode, &asn) != LUA_OK) { /* mem. error? */ + setarrayvector(L, t, oldasize); /* array back to its original size */ + luaD_throw(L, LUA_ERRMEM); /* rethrow memory error */ + } + if (nasize < oldasize) { /* array part must shrink? */ + t->sizearray = nasize; + /* re-insert elements from vanishing slice */ + for (i=nasize; iarray[i])) + luaH_setint(L, t, i + 1, &t->array[i]); + } + /* shrink array */ + luaM_reallocvector(L, t->array, oldasize, nasize, TValue); + } + /* re-insert elements from hash part */ + for (j = oldhsize - 1; j >= 0; j--) { + Node *old = nold + j; + if (!ttisnil(gval(old))) { + /* doesn't need barrier/invalidate cache, as entry was + already present in the table */ + setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old)); + } + } + if (oldhsize > 0) /* not the dummy node? */ + luaM_freearray(L, nold, cast(size_t, oldhsize)); /* free old hash */ +} + + +void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) { + int nsize = allocsizenode(t); + luaH_resize(L, t, nasize, nsize); +} + +/* +** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i +*/ +static void rehash (lua_State *L, Table *t, const TValue *ek) { + unsigned int asize; /* optimal size for array part */ + unsigned int na; /* number of keys in the array part */ + unsigned int nums[MAXABITS + 1]; + int i; + int totaluse; + for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */ + na = numusearray(t, nums); /* count keys in array part */ + totaluse = na; /* all those keys are integer keys */ + totaluse += numusehash(t, nums, &na); /* count keys in hash part */ + /* count extra key */ + na += countint(ek, nums); + totaluse++; + /* compute new size for array part */ + asize = computesizes(nums, &na); + /* resize the table to new computed sizes */ + luaH_resize(L, t, asize, totaluse - na); +} + + + +/* +** }============================================================= +*/ + + +Table *luaH_new (lua_State *L) { + GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table)); + Table *t = gco2t(o); + t->metatable = NULL; + t->flags = cast_byte(~0); + t->array = NULL; + t->sizearray = 0; + setnodevector(L, t, 0); + return t; +} + + +void luaH_free (lua_State *L, Table *t) { + if (!isdummy(t)) + luaM_freearray(L, t->node, cast(size_t, sizenode(t))); + luaM_freearray(L, t->array, t->sizearray); + luaM_free(L, t); +} + + +static Node *getfreepos (Table *t) { + if (!isdummy(t)) { + while (t->lastfree > t->node) { + t->lastfree--; + if (ttisnil(gkey(t->lastfree))) + return t->lastfree; + } + } + return NULL; /* could not find a free place */ +} + + + +/* +** inserts a new key into a hash table; first, check whether key's main +** position is free. If not, check whether colliding node is in its main +** position or not: if it is not, move colliding node to an empty place and +** put new key in its main position; otherwise (colliding node is in its main +** position), new key goes to an empty position. +*/ +TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) { + Node *mp; + TValue aux; + if(!isrwtable(t)) luaG_runerror(L, "table is Readonly"); + if (ttisnil(key)) luaG_runerror(L, "table index is nil"); + else if (ttisfloat(key)) { + lua_Integer k; + if (luaV_tointeger(key, &k, 0)) { /* does index fit in an integer? */ + setivalue(&aux, k); + key = &aux; /* insert it as an integer */ + } + else if (luai_numisnan(fltvalue(key))) + luaG_runerror(L, "table index is NaN"); + } + mp = mainposition(t, key); + if (!ttisnil(gval(mp)) || isdummy(t)) { /* main position is taken? */ + Node *othern; + Node *f = getfreepos(t); /* get a free place */ + if (f == NULL) { /* cannot find a free place? */ + rehash(L, t, key); /* grow table */ + /* whatever called 'newkey' takes care of TM cache */ + return luaH_set(L, t, key); /* insert key into grown table */ + } + lua_assert(!isdummy(t)); + othern = mainposition(t, gkey(mp)); + if (othern != mp) { /* is colliding node out of its main position? */ + /* yes; move colliding node into free position */ + while (othern + gnext(othern) != mp) /* find previous */ + othern += gnext(othern); + gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */ + *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */ + if (gnext(mp) != 0) { + gnext(f) += cast_int(mp - f); /* correct 'next' */ + gnext(mp) = 0; /* now 'mp' is free */ + } + setnilvalue(gval(mp)); + } + else { /* colliding node is in its own main position */ + /* new node will go into free position */ + if (gnext(mp) != 0) + gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */ + else lua_assert(gnext(f) == 0); + gnext(mp) = cast_int(f - mp); + mp = f; + } + } + setnodekey(L, &mp->i_key, key); + luaC_barrierback(L, t, key); + lua_assert(ttisnil(gval(mp))); + return gval(mp); +} + + +/* +** search function for integers +*/ +const TValue *luaH_getint (Table *t, lua_Integer key) { + if (isrotable(t)) + return luaO_nilobject; + /* (1 <= key && key <= t->sizearray) */ + if (l_castS2U(key) - 1 < t->sizearray) + return &t->array[key - 1]; + else { + Node *n = hashint(t, key); + for (;;) { /* check whether 'key' is somewhere in the chain */ + if (ttisinteger(gkey(n)) && ivalue(gkey(n)) == key) + return gval(n); /* that's it */ + else { + int nx = gnext(n); + if (nx == 0) break; + n += nx; + } + } + return luaO_nilobject; + } +} + + +/* +** search function for short strings +*/ + +static const TValue* rotable_findentry(ROTable *rotable, TString *key, unsigned *ppos); + +const TValue *luaH_getshortstr (Table *t, TString *key) { + Node *n; + if (isrotable(t)) + return rotable_findentry((ROTable*) t, key, NULL); + n = hashstr(t, key); + lua_assert(gettt(key) == LUA_TSHRSTR); + for (;;) { /* check whether 'key' is somewhere in the chain */ + const TValue *k = gkey(n); + if (ttisshrstring(k) && eqshrstr(tsvalue(k), key)) + return gval(n); /* that's it */ + else { + int nx = gnext(n); + if (nx == 0) + return luaO_nilobject; /* not found */ + n += nx; + } + } +} + + +/* +** "Generic" get version. (Not that generic: not valid for integers, +** which may be in array part, nor for floats with integral values.) +*/ +static const TValue *getgeneric (Table *t, const TValue *key) { + Node *n; + if (isrotable(t)) + return luaO_nilobject; + n = mainposition(t, key); + for (;;) { /* check whether 'key' is somewhere in the chain */ + if (luaV_rawequalobj(gkey(n), key)) + return gval(n); /* that's it */ + else { + int nx = gnext(n); + if (nx == 0) + return luaO_nilobject; /* not found */ + n += nx; + } + } +} + + +const TValue *luaH_getstr (Table *t, TString *key) { + if (gettt(key) == LUA_TSHRSTR) + return luaH_getshortstr(t, key); + else { /* for long strings, use generic case */ + TValue ko; + setsvalue(cast(lua_State *, NULL), &ko, key); + return getgeneric(t, &ko); + } +} + + +/* +** main search function +*/ +const TValue *luaH_get (Table *t, const TValue *key) { + switch (ttype(key)) { + case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key)); + case LUA_TNUMINT: return luaH_getint(t, ivalue(key)); + case LUA_TNIL: return luaO_nilobject; + case LUA_TNUMFLT: { + lua_Integer k; + if (luaV_tointeger(key, &k, 0)) /* index is int? */ + return luaH_getint(t, k); /* use specialized version */ + /* else... */ + } /* FALLTHROUGH */ + default: + return getgeneric(t, key); + } +} + + +/* +** beware: when using this function you probably need to check a GC +** barrier and invalidate the TM cache. +*/ +TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { + const TValue *p; + if (isrotable(t)) + luaG_runerror(L, "table is readonly"); + p = luaH_get(t, key); + if (p != luaO_nilobject) + return cast(TValue *, p); + else return luaH_newkey(L, t, key); +} + + +void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) { + const TValue *p; + if (isrotable(t)) + luaG_runerror(L, "table is readonly"); + p = luaH_getint(t, key); + TValue *cell; + if (p != luaO_nilobject) + cell = cast(TValue *, p); + else { + TValue k; + setivalue(&k, key); + cell = luaH_newkey(L, t, &k); + } + setobj2t(L, cell, value); +} + + +static lua_Unsigned unbound_search (Table *t, lua_Unsigned j) { + lua_Unsigned i = j; /* i is zero or a present index */ + j++; + /* find 'i' and 'j' such that i is present and j is not */ + while (!ttisnil(luaH_getint(t, j))) { + i = j; + if (j > l_castS2U(LUA_MAXINTEGER) / 2) { /* overflow? */ + /* table was built with bad purposes: resort to linear search */ + i = 1; + while (!ttisnil(luaH_getint(t, i))) i++; + return i - 1; + } + j *= 2; + } + /* now do a binary search between them */ + while (j - i > 1) { + lua_Unsigned m = (i+j)/2; + if (ttisnil(luaH_getint(t, m))) j = m; + else i = m; + } + return i; +} + + +/* +** Try to find a boundary in table 't'. A 'boundary' is an integer index +** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil). +*/ +lua_Unsigned luaH_getn (Table *t) { + unsigned int j; + if (isrotable(t)) + return 0; + j = t->sizearray; + if (j > 0 && ttisnil(&t->array[j - 1])) { + /* there is a boundary in the array part: (binary) search for it */ + unsigned int i = 0; + while (j - i > 1) { + unsigned int m = (i+j)/2; + if (ttisnil(&t->array[m - 1])) j = m; + else i = m; + } + return i; + } + /* else must find a boundary in hash part */ + else if (isdummy(t)) /* hash part is empty? */ + return j; /* that is easy... */ + else return unbound_search(t, j); +} + + +int luaH_isdummy (const Table *t) { return isdummy(t); } + + +/* +** All keyed ROTable access passes through rotable_findentry(). ROTables +** are simply a list of pairs. +** +** The global KeyCache is used to avoid a relatively expensive Flash memory +** vector scan. A simple hash on the key's TString addr and the ROTable +** addr selects the cache line. The line's slots are then scanned for a +** hit. +** +** Unlike the standard hash which uses a prime line count therefore requires +** the use of modulus operation which is expensive on an IoT processor +** without H/W divide. This hash is power of 2 based which might not be quite +** so uniform but can be calculated without using H/W-based instructions. +** +** If a match is found and the table addresses match, then this entry is +** probed first. In practice the hit-rate here is over 99% so the code +** rarely fails back to doing the linear scan in ROM. +** Note that this hash does a couple of prime multiples and a modulus 2^X +** with is all evaluated in H/W, and adequately randomizes the lookup. +*/ +#define HASH(a,b) ((((29*(size_t)(a)) ^ (37*((b)->hash)))>>4)&(KEYCACHE_N-1)) +#define NDX_SHFT 24 +#define ADDR_MASK (((size_t) 1<<24)-1) + +/* + * Find a string key entry in a rotable and return it. + */ +static const TValue* rotable_findentry(ROTable *t, TString *key, unsigned *ppos) { + const ROTable_entry *e = cast(const ROTable_entry *, t->entry); + const int tl = getlsizenode(t); + const char *strkey = getstr(key); + const int hash = HASH(t, key); + KeyCache *cl = luaE_getcache(hash); + int i, j = 1, l; + + if (!e || gettt(key) != LUA_TSHRSTR) + return luaO_nilobject; + + l = getshrlen(key); + /* scan the ROTable key cache and return if hit found */ + for (i = 0; i < KEYCACHE_M; i++) { + int cl_ndx = cl[i] >> NDX_SHFT; + if ((((size_t)t - cl[i]) & ADDR_MASK) == 0 && cl_ndx < tl && + strcmp(e[cl_ndx].key, strkey) == 0) { + if (ppos) + *ppos = cl_ndx; + return &e[cl_ndx].value; + } + } + /* + * In practice most table scans are from a table miss due to the key cache + * short-circuiting almost all table hits. ROTable keys can be unsorted + * because of legacy compatibility, so the search must use a sequential + * equality match. + * + * The masked name4 comparison is a safe 4-byte comparison for all supported + * NodeMCU hosts and targets; It generate fast efficient access that avoids + * unaligned exceptions and costly strcmp() except for a last hit validation. + * However, this is ENDIAN SENSITIVE which is validate during initialisation. + * + * The majority of search misses are for metavalues (keys starting with __), + * so all metavalues if any must be at the front of each entry list. + */ + lu_int32 name4 = *(lu_int32 *)strkey; + lu_int32 mask4 = l > 2 ? (~0u) : (~0u)>>((3-l)*8); + lua_assert(*(int*)"abcd" == 0x64636261); +#define eq4(s) (((*(lu_int32 *)s ^ name4) & mask4) == 0) +#define ismeta(s) ((*(lu_int32 *)s & 0xffff) == *(lu_int32 *)"__\0") + + if (ismeta(&name4)) { + for(i = 0; i < tl && ismeta(e[i].key); i++) { + if (eq4(e[i].key) && !strcmp(e[i].key, strkey)) { + j = 0; break; + } + } + } else { + for(i = 0; i < tl; i++) { + if (eq4(e[i].key) && !strcmp(e[i].key, strkey)) { + j = 0; break; + } + } + } + if (j) + return luaO_nilobject; + if (ppos) + *ppos = i; + /* In the case of a hit, update the lookaside cache */ + for (j = KEYCACHE_M-1; j>0; j--) + cl[j] = cl[j-1]; + cl[0] = ((size_t)t & ADDR_MASK) + (i << NDX_SHFT); + return &e[i].value; +} + + +static void rotable_next_helper(lua_State *L, ROTable *t, int pos, + TValue *key, TValue *val) { + const ROTable_entry *e = cast(const ROTable_entry *, t->entry); + if (pos < getlsizenode(t)) { + /* Found an entry */ + setsvalue(L, key, luaS_new(L, e[pos].key)); + setobj2s(L, val, &e[pos].value); + } else { + setnilvalue(key); + setnilvalue(val); + } +} + + +/* next (used for iteration) */ +static void rotable_next(lua_State *L, ROTable *t, TValue *key, TValue *val) { + unsigned keypos = getlsizenode(t); + + /* Special case: if key is nil, return the first element of the rotable */ + if (ttisnil(key)) + rotable_next_helper(L, t, 0, key, val); + else if (ttisstring(key)) { + /* Find the previous key again */ + if (ttisstring(key)) { + rotable_findentry(t, tsvalue(key), &keypos); + } + /* Advance to next key */ + rotable_next_helper(L, t, ++keypos, key, val); + } +} + + + +#if defined(LUA_DEBUG) +Node *luaH_mainposition (const Table *t, const TValue *key) { + return mainposition(t, key); +} +#endif diff --git a/components/lua/lua-5.3/ltable.h b/components/lua/lua-5.3/ltable.h new file mode 100644 index 00000000..0ca0dbfc --- /dev/null +++ b/components/lua/lua-5.3/ltable.h @@ -0,0 +1,70 @@ +/* +** $Id: ltable.h,v 2.23.1.2 2018/05/24 19:39:05 roberto Exp $ +** Lua tables (hash) +** See Copyright Notice in lua.h +*/ + +#ifndef ltable_h +#define ltable_h + +#include "lobject.h" + + +#define gnode(t,i) (&(t)->node[i]) +#define gval(n) (&(n)->i_val) +#define gnext(n) ((n)->i_key.nk.next) + + +/* 'const' to avoid wrong writings that can mess up field 'next' */ +#define gkey(n) cast(const TValue*, (&(n)->i_key.tvk)) + +/* +** writable version of 'gkey'; allows updates to individual fields, +** but not to the whole (which has incompatible type) +*/ +#define wgkey(n) (&(n)->i_key.nk) + +#define invalidateTMcache(t) ((t)->flags = 0) + + +/* true when 't' is using 'dummynode' as its hash part */ +#define isdummy(t) ((t)->lastfree == NULL) + + +/* allocated size for hash nodes */ +#define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t)) + + +/* returns the key, given the value of a table entry */ +#define keyfromval(v) \ + (gkey(cast(Node *, cast(char *, (v)) - offsetof(Node, i_val)))) + +/* test Table to determine if it is a RW or RO table */ +#define isrotable(t) (gettt(t)==LUA_TTBLROF) +#define isrwtable(t) (gettt(t)==LUA_TTBLRAM) + + +LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key); +LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key, + TValue *value); +LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key); +LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); +LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); +LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key); +LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key); +LUAI_FUNC Table *luaH_new (lua_State *L); +LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize, + unsigned int nhsize); +LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize); +LUAI_FUNC void luaH_free (lua_State *L, Table *t); +LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); +LUAI_FUNC lua_Unsigned luaH_getn (Table *t); + + +#if defined(LUA_DEBUG) +LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); +LUAI_FUNC int luaH_isdummy (const Table *t); +#endif + + +#endif diff --git a/components/lua/lua-5.3/ltablib.c b/components/lua/lua-5.3/ltablib.c new file mode 100644 index 00000000..77715598 --- /dev/null +++ b/components/lua/lua-5.3/ltablib.c @@ -0,0 +1,444 @@ +/* +** $Id: ltablib.c,v 1.93.1.1 2017/04/19 17:20:42 roberto Exp $ +** Library for Table Manipulation +** See Copyright Notice in lua.h +*/ + +#define ltablib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* +** Operations that an object must define to mimic a table +** (some functions only need some of them) +*/ +#define TAB_R 1 /* read */ +#define TAB_W 2 /* write */ +#define TAB_L 4 /* length */ +#define TAB_RW (TAB_R | TAB_W) /* read/write */ + + +#define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n)) + + +static int checkfield (lua_State *L, const char *key, int n) { + lua_pushstring(L, key); + return (lua_rawget(L, -n) != LUA_TNIL); +} + + +/* +** Check that 'arg' either is a table or can behave like one (that is, +** has a metatable with the required metamethods) +*/ +static void checktab (lua_State *L, int arg, int what) { + if (lua_type(L, arg) != LUA_TTABLE) { /* is it not a table? */ + int n = 1; /* number of elements to pop */ + if (lua_getmetatable(L, arg) && /* must have metatable */ + (!(what & TAB_R) || checkfield(L, "__index", ++n)) && + (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) && + (!(what & TAB_L) || checkfield(L, "__len", ++n))) { + lua_pop(L, n); /* pop metatable and tested metamethods */ + } + else + luaL_checktype(L, arg, LUA_TTABLE); /* force an error */ + } +} + + +#if defined(LUA_COMPAT_MAXN) +static int maxn (lua_State *L) { + lua_Number max = 0; + luaL_checktype(L, 1, LUA_TTABLE); + lua_pushnil(L); /* first key */ + while (lua_next(L, 1)) { + lua_pop(L, 1); /* remove value */ + if (lua_type(L, -1) == LUA_TNUMBER) { + lua_Number v = lua_tonumber(L, -1); + if (v > max) max = v; + } + } + lua_pushnumber(L, max); + return 1; +} +#endif + + +static int tinsert (lua_State *L) { + lua_Integer e = aux_getn(L, 1, TAB_RW) + 1; /* first empty element */ + lua_Integer pos; /* where to insert new element */ + switch (lua_gettop(L)) { + case 2: { /* called with only 2 arguments */ + pos = e; /* insert new element at the end */ + break; + } + case 3: { + lua_Integer i; + pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */ + luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds"); + for (i = e; i > pos; i--) { /* move up elements */ + lua_geti(L, 1, i - 1); + lua_seti(L, 1, i); /* t[i] = t[i - 1] */ + } + break; + } + default: { + return luaL_error(L, "wrong number of arguments to 'insert'"); + } + } + lua_seti(L, 1, pos); /* t[pos] = v */ + return 0; +} + + +static int tremove (lua_State *L) { + lua_Integer size = aux_getn(L, 1, TAB_RW); + lua_Integer pos = luaL_optinteger(L, 2, size); + if (pos != size) /* validate 'pos' if given */ + luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds"); + lua_geti(L, 1, pos); /* result = t[pos] */ + for ( ; pos < size; pos++) { + lua_geti(L, 1, pos + 1); + lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */ + } + lua_pushnil(L); + lua_seti(L, 1, pos); /* t[pos] = nil */ + return 1; +} + + +/* +** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever +** possible, copy in increasing order, which is better for rehashing. +** "possible" means destination after original range, or smaller +** than origin, or copying to another table. +*/ +static int tmove (lua_State *L) { + lua_Integer f = luaL_checkinteger(L, 2); + lua_Integer e = luaL_checkinteger(L, 3); + lua_Integer t = luaL_checkinteger(L, 4); + int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */ + checktab(L, 1, TAB_R); + checktab(L, tt, TAB_W); + if (e >= f) { /* otherwise, nothing to move */ + lua_Integer n, i; + luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3, + "too many elements to move"); + n = e - f + 1; /* number of elements to move */ + luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4, + "destination wrap around"); + if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) { + for (i = 0; i < n; i++) { + lua_geti(L, 1, f + i); + lua_seti(L, tt, t + i); + } + } + else { + for (i = n - 1; i >= 0; i--) { + lua_geti(L, 1, f + i); + lua_seti(L, tt, t + i); + } + } + } + lua_pushvalue(L, tt); /* return destination table */ + return 1; +} + + +static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) { + lua_geti(L, 1, i); + if (!lua_isstring(L, -1)) + luaL_error(L, "invalid value (%s) at index %d in table for 'concat'", + luaL_typename(L, -1), i); + luaL_addvalue(b); +} + + +static int tconcat (lua_State *L) { + luaL_Buffer b; + lua_Integer last = aux_getn(L, 1, TAB_R); + size_t lsep; + const char *sep = luaL_optlstring(L, 2, "", &lsep); + lua_Integer i = luaL_optinteger(L, 3, 1); + last = luaL_optinteger(L, 4, last); + luaL_buffinit(L, &b); + for (; i < last; i++) { + addfield(L, &b, i); + luaL_addlstring(&b, sep, lsep); + } + if (i == last) /* add last value (if interval was not empty) */ + addfield(L, &b, i); + luaL_pushresult(&b); + return 1; +} + + +/* +** {====================================================== +** Pack/unpack +** ======================================================= +*/ + +static int pack (lua_State *L) { + int i; + int n = lua_gettop(L); /* number of elements to pack */ + lua_createtable(L, n, 1); /* create result table */ + lua_insert(L, 1); /* put it at index 1 */ + for (i = n; i >= 1; i--) /* assign elements */ + lua_seti(L, 1, i); + lua_pushinteger(L, n); + lua_setfield(L, 1, "n"); /* t.n = number of elements */ + return 1; /* return table */ +} + + +static int unpack (lua_State *L) { + lua_Unsigned n; + lua_Integer i = luaL_optinteger(L, 2, 1); + lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1)); + if (i > e) return 0; /* empty range */ + n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */ + if (n >= (unsigned int)INT_MAX || !lua_checkstack(L, (int)(++n))) + return luaL_error(L, "too many results to unpack"); + for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */ + lua_geti(L, 1, i); + } + lua_geti(L, 1, e); /* push last element */ + return (int)n; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** Quicksort +** (based on 'Algorithms in MODULA-3', Robert Sedgewick; +** Addison-Wesley, 1993.) +** ======================================================= +*/ + + +/* type for array indices */ +typedef unsigned int IdxT; + + +/* +** Produce a "random" 'unsigned int' to randomize pivot choice. This +** macro is used only when 'sort' detects a big imbalance in the result +** of a partition. (If you don't want/need this "randomness", ~0 is a +** good choice.) +*/ +#define l_randomizePivot() (~0); + +#if !defined(l_randomizePivot) /* { */ + +#include + +/* size of 'e' measured in number of 'unsigned int's */ +#define sof(e) (sizeof(e) / sizeof(unsigned int)) + +/* +** Use 'time' and 'clock' as sources of "randomness". Because we don't +** know the types 'clock_t' and 'time_t', we cannot cast them to +** anything without risking overflows. A safe way to use their values +** is to copy them to an array of a known type and use the array values. +*/ +static unsigned int l_randomizePivot (void) { + clock_t c = clock(); + time_t t = time(NULL); + unsigned int buff[sof(c) + sof(t)]; + unsigned int i, rnd = 0; + memcpy(buff, &c, sof(c) * sizeof(unsigned int)); + memcpy(buff + sof(c), &t, sof(t) * sizeof(unsigned int)); + for (i = 0; i < sof(buff); i++) + rnd += buff[i]; + return rnd; +} + +#endif /* } */ + + +/* arrays larger than 'RANLIMIT' may use randomized pivots */ +#define RANLIMIT 100u + + +static void set2 (lua_State *L, IdxT i, IdxT j) { + lua_seti(L, 1, i); + lua_seti(L, 1, j); +} + + +/* +** Return true iff value at stack index 'a' is less than the value at +** index 'b' (according to the order of the sort). +*/ +static int sort_comp (lua_State *L, int a, int b) { + if (lua_isnil(L, 2)) /* no function? */ + return lua_compare(L, a, b, LUA_OPLT); /* a < b */ + else { /* function */ + int res; + lua_pushvalue(L, 2); /* push function */ + lua_pushvalue(L, a-1); /* -1 to compensate function */ + lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */ + lua_call(L, 2, 1); /* call function */ + res = lua_toboolean(L, -1); /* get result */ + lua_pop(L, 1); /* pop result */ + return res; + } +} + + +/* +** Does the partition: Pivot P is at the top of the stack. +** precondition: a[lo] <= P == a[up-1] <= a[up], +** so it only needs to do the partition from lo + 1 to up - 2. +** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up] +** returns 'i'. +*/ +static IdxT partition (lua_State *L, IdxT lo, IdxT up) { + IdxT i = lo; /* will be incremented before first use */ + IdxT j = up - 1; /* will be decremented before first use */ + /* loop invariant: a[lo .. i] <= P <= a[j .. up] */ + for (;;) { + /* next loop: repeat ++i while a[i] < P */ + while (lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) { + if (i == up - 1) /* a[i] < P but a[up - 1] == P ?? */ + luaL_error(L, "invalid order function for sorting"); + lua_pop(L, 1); /* remove a[i] */ + } + /* after the loop, a[i] >= P and a[lo .. i - 1] < P */ + /* next loop: repeat --j while P < a[j] */ + while (lua_geti(L, 1, --j), sort_comp(L, -3, -1)) { + if (j < i) /* j < i but a[j] > P ?? */ + luaL_error(L, "invalid order function for sorting"); + lua_pop(L, 1); /* remove a[j] */ + } + /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */ + if (j < i) { /* no elements out of place? */ + /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */ + lua_pop(L, 1); /* pop a[j] */ + /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */ + set2(L, up - 1, i); + return i; + } + /* otherwise, swap a[i] - a[j] to restore invariant and repeat */ + set2(L, i, j); + } +} + + +/* +** Choose an element in the middle (2nd-3th quarters) of [lo,up] +** "randomized" by 'rnd' +*/ +static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) { + IdxT r4 = (up - lo) / 4; /* range/4 */ + IdxT p = rnd % (r4 * 2) + (lo + r4); + lua_assert(lo + r4 <= p && p <= up - r4); + return p; +} + + +/* +** QuickSort algorithm (recursive function) +*/ +static void auxsort (lua_State *L, IdxT lo, IdxT up, + unsigned int rnd) { + while (lo < up) { /* loop for tail recursion */ + IdxT p; /* Pivot index */ + IdxT n; /* to be used later */ + /* sort elements 'lo', 'p', and 'up' */ + lua_geti(L, 1, lo); + lua_geti(L, 1, up); + if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */ + set2(L, lo, up); /* swap a[lo] - a[up] */ + else + lua_pop(L, 2); /* remove both values */ + if (up - lo == 1) /* only 2 elements? */ + return; /* already sorted */ + if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */ + p = (lo + up)/2; /* middle element is a good pivot */ + else /* for larger intervals, it is worth a random pivot */ + p = choosePivot(lo, up, rnd); + lua_geti(L, 1, p); + lua_geti(L, 1, lo); + if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */ + set2(L, p, lo); /* swap a[p] - a[lo] */ + else { + lua_pop(L, 1); /* remove a[lo] */ + lua_geti(L, 1, up); + if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */ + set2(L, p, up); /* swap a[up] - a[p] */ + else + lua_pop(L, 2); + } + if (up - lo == 2) /* only 3 elements? */ + return; /* already sorted */ + lua_geti(L, 1, p); /* get middle element (Pivot) */ + lua_pushvalue(L, -1); /* push Pivot */ + lua_geti(L, 1, up - 1); /* push a[up - 1] */ + set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */ + p = partition(L, lo, up); + /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */ + if (p - lo < up - p) { /* lower interval is smaller? */ + auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */ + n = p - lo; /* size of smaller interval */ + lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */ + } + else { + auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */ + n = up - p; /* size of smaller interval */ + up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */ + } + if ((up - lo) / 128 > n) /* partition too imbalanced? */ + rnd = l_randomizePivot(); /* try a new randomization */ + } /* tail call auxsort(L, lo, up, rnd) */ +} + + +static int sort (lua_State *L) { + lua_Integer n = aux_getn(L, 1, TAB_RW); + if (n > 1) { /* non-trivial interval? */ + luaL_argcheck(L, n < INT_MAX, 1, "array too big"); + if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */ + luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */ + lua_settop(L, 2); /* make sure there are two arguments */ + auxsort(L, 1, (IdxT)n, 0); + } + return 0; +} + +/* }====================================================== */ + +LROT_BEGIN(tab_funcs, NULL, 0) + LROT_FUNCENTRY( concat, tconcat ) +#if defined(LUA_COMPAT_MAXN) + LROT_FUNCENTRY( maxn, maxn ) +#endif + LROT_FUNCENTRY( insert, tinsert ) + LROT_FUNCENTRY( pack, pack ) + LROT_FUNCENTRY( unpack, unpack) + LROT_FUNCENTRY( move, tmove ) + LROT_FUNCENTRY( remove, tremove ) + LROT_FUNCENTRY( sort, sort ) +LROT_END(tab_funcs, NULL, 0) + +LUAMOD_API int luaopen_table (lua_State *L) { + (void)L; + return 0; +} + diff --git a/components/lua/lua-5.3/ltm.c b/components/lua/lua-5.3/ltm.c new file mode 100644 index 00000000..6b202530 --- /dev/null +++ b/components/lua/lua-5.3/ltm.c @@ -0,0 +1,179 @@ +/* +** $Id: ltm.c,v 2.38.1.1 2017/04/19 17:39:34 roberto Exp $ +** Tag methods +** See Copyright Notice in lua.h +*/ + +#define ltm_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lvm.h" + + +static const char udatatypename[] = "userdata"; + +LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTAGS] = { + "no value", + "nil", "boolean", udatatypename, "number", + "string", "table", "function", udatatypename, "thread", + "proto" /* this last case is used for tests only */ +}; + + +static const char *const luaT_eventname[] = { /* ORDER TM */ + "__index", "__newindex", + "__gc", "__mode", "__len", "__eq", + "__add", "__sub", "__mul", "__mod", "__pow", + "__div", "__idiv", + "__band", "__bor", "__bxor", "__shl", "__shr", + "__unm", "__bnot", "__lt", "__le", + "__concat", "__call" +}; + + +void luaT_init (lua_State *L) { + int i; + for (i=0; itmname[i] = luaS_new(L, luaT_eventname[i]); + luaC_fix(L, obj2gco(G(L)->tmname[i])); /* never collect these names */ + } +} + +#define N_EVENTS sizeof(luaT_eventname)/sizeof(*luaT_eventname) +#define N_TYPES sizeof(luaT_typenames_)/sizeof(*luaT_typenames_) + +/* Access method to expose luaT_fixed strings */ +const char *luaT_getstr (unsigned int i) { + if (i < N_EVENTS) + return luaT_eventname[i]; + if (i < N_EVENTS + N_TYPES) + return luaT_typenames_[i - N_EVENTS]; + return NULL; +} + + +/* +** function to be used with macro "fasttm": optimized for absence of +** tag methods +*/ +const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { + const TValue *tm = luaH_getshortstr(events, ename); + lua_assert(event <= TM_EQ); + if (ttisnil(tm)) { /* no tag method? */ + events->flags |= cast_byte(1u<metatable; + break; + case LUA_TUSERDATA: + mt = uvalue(o)->metatable; + break; + default: + mt = G(L)->mt[ttnov(o)]; + } + return (mt ? luaH_getshortstr(mt, G(L)->tmname[event]) : luaO_nilobject); +} + + +/* +** Return the name of the type of an object. For tables and userdata +** with metatable, use their '__name' metafield, if present. +*/ +const char *luaT_objtypename (lua_State *L, const TValue *o) { + Table *mt; + if ((ttistable(o) && (mt = hvalue(o)->metatable) != NULL) || + (ttisfulluserdata(o) && (mt = uvalue(o)->metatable) != NULL)) { + const TValue *name = luaH_getshortstr(mt, luaS_new(L, "__name")); + if (ttisstring(name)) /* is '__name' a string? */ + return getstr(tsvalue(name)); /* use it as type name */ + } + return ttypename(ttnov(o)); /* else use standard type name */ +} + + +void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, + const TValue *p2, TValue *p3, int hasres) { + ptrdiff_t result = savestack(L, p3); + StkId func = L->top; + setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ + setobj2s(L, func + 1, p1); /* 1st argument */ + setobj2s(L, func + 2, p2); /* 2nd argument */ + L->top += 3; + if (!hasres) /* no result? 'p3' is third argument */ + setobj2s(L, L->top++, p3); /* 3rd argument */ + /* metamethod may yield only when called from Lua code */ + if (isLua(L->ci)) + luaD_call(L, func, hasres); + else + luaD_callnoyield(L, func, hasres); + if (hasres) { /* if has result, move it to its place */ + p3 = restorestack(L, result); + setobjs2s(L, p3, --L->top); + } +} + + +int luaT_callbinTM (lua_State *L, const TValue *p1, const TValue *p2, + StkId res, TMS event) { + const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ + if (ttisnil(tm)) + tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ + if (ttisnil(tm)) return 0; + luaT_callTM(L, tm, p1, p2, res, 1); + return 1; +} + + +void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, + StkId res, TMS event) { + if (!luaT_callbinTM(L, p1, p2, res, event)) { + switch (event) { + case TM_CONCAT: + luaG_concaterror(L, p1, p2); + /* call never returns, but to avoid warnings: *//* FALLTHROUGH */ + case TM_BAND: case TM_BOR: case TM_BXOR: + case TM_SHL: case TM_SHR: case TM_BNOT: { + lua_Number dummy; + if (tonumber(p1, &dummy) && tonumber(p2, &dummy)) + luaG_tointerror(L, p1, p2); + else + luaG_opinterror(L, p1, p2, "perform bitwise operation on"); + } + /* calls never return, but to avoid warnings: *//* FALLTHROUGH */ + default: + luaG_opinterror(L, p1, p2, "perform arithmetic on"); + } + } +} + + +int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2, + TMS event) { + if (!luaT_callbinTM(L, p1, p2, L->top, event)) + return -1; /* no metamethod */ + else + return !l_isfalse(L->top); +} + diff --git a/components/lua/lua-5.3/ltm.h b/components/lua/lua-5.3/ltm.h new file mode 100644 index 00000000..baa03a61 --- /dev/null +++ b/components/lua/lua-5.3/ltm.h @@ -0,0 +1,77 @@ +/* +** $Id: ltm.h,v 2.22.1.1 2017/04/19 17:20:42 roberto Exp $ +** Tag methods +** See Copyright Notice in lua.h +*/ + +#ifndef ltm_h +#define ltm_h + + +#include "lobject.h" + + +/* +* WARNING: if you change the order of this enumeration, +* grep "ORDER TM" and "ORDER OP" +*/ +typedef enum { + TM_INDEX, + TM_NEWINDEX, + TM_GC, + TM_MODE, + TM_LEN, + TM_EQ, /* last tag method with fast access */ + TM_ADD, + TM_SUB, + TM_MUL, + TM_MOD, + TM_POW, + TM_DIV, + TM_IDIV, + TM_BAND, + TM_BOR, + TM_BXOR, + TM_SHL, + TM_SHR, + TM_UNM, + TM_BNOT, + TM_LT, + TM_LE, + TM_CONCAT, + TM_CALL, + TM_N /* number of elements in the enum */ +} TMS; + + + +#define gfasttm(g,et,e) ((et) == NULL ? NULL : \ + (getflags(et) & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e])) + +#define fasttm(l,et,e) gfasttm(G(l), et, e) + +#define ttypename(x) luaT_typenames_[(x) + 1] + +LUAI_DDEC const char *const luaT_typenames_[LUA_TOTALTAGS]; + + +LUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o); + +LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename); +LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, + TMS event); +LUAI_FUNC void luaT_init (lua_State *L); +LUAI_FUNC const char *luaT_getstr (unsigned int i); + +LUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, + const TValue *p2, TValue *p3, int hasres); +LUAI_FUNC int luaT_callbinTM (lua_State *L, const TValue *p1, const TValue *p2, + StkId res, TMS event); +LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, + StkId res, TMS event); +LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1, + const TValue *p2, TMS event); + + + +#endif diff --git a/components/lua/lua-5.3/lua.c b/components/lua/lua-5.3/lua.c new file mode 100644 index 00000000..f1eb1687 --- /dev/null +++ b/components/lua/lua-5.3/lua.c @@ -0,0 +1,384 @@ +/* +** NodeMCU Lua 5.1 and 5.3 main initiator and comand interpreter +** See Copyright Notice in lua.h +*/ + +#include +#include +#include +#include "user_version.h" +#include "linput.h" + +#define lua_c +#define LUA_CORE + +#ifndef LUA_VERSION_51 /* LUA_VERSION_NUM == 503 */ +#define LUA_VERSION_53 +#include "lua.h" +#include "lauxlib.h" +#include "lualib.h" +#include "lprefix.h" +#include "lgc.h" +#include "lnodemcu.h" +#endif + +#include "platform.h" + +#if !defined(LUA_PROMPT) +#define LUA_PROMPT "> " +#define LUA_PROMPT2 ">> " +#endif + +#ifndef LUA_INIT_STRING +#define LUA_INIT_STRING "@init.lua" +#endif + +#if !defined(STARTUP_COUNT) +# define STARTUP_COUNT +#endif + +/* +** The NodeMCU version of lua.c is structurally different for standard lua.c +** as a result of architectural drivers arising from its context and being +** initiated within the startup sequence of an IoT SoC embedded runtime. +** +** 1) Processing is based on a single threaded event loop model (somewhat akin +** to Node.js), so access to most system services is asyncronous and uses +** a callback mechanism. The Lua interactive mode processes input lines +** that are provided by the firmware on a line by line basis and indeed +** other Lua tasks might interleave any multiline processing, so the +** standard doREPL approach won't work. +** +** 2) Most OS services and enviroment processing are supported so much of the +** standard functionality is irrelevant and is stripped out for simplicity. +** +** 3) stderr and stdout redirection aren't offered as an OS service, so this +** is handled in the baselib print function and errors are sent to print. +*/ +lua_State *globalL = NULL; + +static int pmain (lua_State *L); +void lua_input_string (const char *line, int len); + +/* +** Prints (calling the Lua 'print' function) to print n values on the stack +*/ +static void l_print (lua_State *L, int n) { + if (n > 0) { /* any result to be printed? */ + luaL_checkstack(L, LUA_MINSTACK, "too many results to print"); + lua_getglobal(L, "print"); + lua_insert(L, -n-1); + if (lua_pcall(L, n, 0, 0) != LUA_OK) { + lua_writestringerror("error calling 'print' (%s)\n", lua_tostring(L, -1)); + lua_settop(L, -n-1); + } + } +} + + +/* +** Message handler is used with all chunks calls. Returns the traceback on ToS +*/ +static int msghandler (lua_State *L) { + lua_getglobal(L, "debug"); + lua_getfield(L, -1, "traceback"); + if (lua_isfunction(L, -1)) { + lua_insert(L, 1); /* insert tracback function above error */ + lua_pop(L, 1); /* dump the debug table entry */ + lua_pushinteger(L, 2); /* skip this function and traceback */ + lua_call(L, 2, 1); /* call debug.traceback and return it as a string */ + } + return 1; /* return the traceback */ +} + + +/* +** Interface to 'lua_pcall', which sets appropriate message function and error +** handler. Used to run all chunks. Results or error traceback left on stack. +** This function is interactive so unlike lua_pcallx(), the error is sent direct +** to the print function and erroring does not trigger an on error restart. +*/ +static int docall (lua_State *L, int narg) { + int status; + int base = lua_gettop(L) - narg; /* function index */ + lua_pushcfunction(L, msghandler); /* push message handler */ + lua_insert(L, base); /* put it under chunk and args */ + status = lua_pcall(L, narg, LUA_MULTRET, base); + lua_remove(L, base); /* remove message handler from the stack */ + /* force a complete garbage collection in case of errors */ + if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0); + return status; +} + + +#if !defined(DISABLE_STARTUP_BANNER) && defined(ESP8266) +static void print_version (lua_State *L) { + lua_writestringerror( "\n" NODE_VERSION " build " BUILD_DATE + " powered by " LUA_RELEASE " on SDK %s\n", SDK_VERSION); +} +#endif + +/* +** Returns the string to be used as a prompt by the interpreter. +*/ +static const char *get_prompt (lua_State *L, int firstline) { + const char *p; + lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2"); + p = lua_tostring(L, -1); + if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2); + lua_pop(L, 1); /* remove global */ + return p; +} + + +/* +** Check whether 'status' signals a syntax error and the error +** message at the top of the stack ends with the above mark for +** incomplete statements. +*/ +#ifdef LUA_VERSION_51 +#define EOFMARK LUA_QL("") +#else +#define EOFMARK "" +#endif +#define MARKLEN (sizeof(EOFMARK)/sizeof(char) - 1) +static int incomplete (lua_State *L, int status) { + if (status == LUA_ERRSYNTAX) { + size_t lmsg; + const char *msg = lua_tolstring(L, -1, &lmsg); + if (lmsg >= MARKLEN && !strcmp(msg + lmsg - MARKLEN, EOFMARK)) { + lua_pop(L, 1); + return 1; + } + } + return 0; +} + +static void l_create_stdin (lua_State *L); +/* +** Note that the Lua stack can't be used to stash part-line components as +** other C API and Lua functions might be executed as tasks between lines in +** a multiline, so a standard luaL_ref() registry entry is used instead. +*/ +static void dojob (lua_State *L) { + static int MLref = LUA_NOREF; /* Lua Reg entry for cached multi-line */ + int status; + const char *prompt; + size_t l; + const char *b = lua_tostring(L, -1); /* ToS contains next input line */ + + if (MLref != LUA_NOREF) { + /* processing multiline */ + lua_rawgeti(L, LUA_REGISTRYINDEX, MLref); /* insert prev lines(s) */ + lua_pushliteral(L, "\n"); /* insert CR */ + lua_pushvalue(L, -3); /* dup new line */ + lua_concat(L, 3); /* concat all 3 */ + lua_remove(L,-2); /* and shift down to ToS */ + } else if (b[0] == '=') { /* If firstline and of the format = */ + lua_pushfstring(L, "return %s", b+1); + lua_remove(L, -2); + } + /* + * ToS is at S[2] which contains the putative chunk to be compiled + */ + b = lua_tolstring(L, -1, &l); + status = luaL_loadbuffer(L, b, l, "=stdin"); + if (incomplete(L, status)) { + /* Store line back in the Reg mlref sot */ + if (MLref == LUA_NOREF) { + MLref = luaL_ref(L, LUA_REGISTRYINDEX); + } else { + lua_rawseti(L, LUA_REGISTRYINDEX, MLref); + } + } else { + /* compile finished OK or with hard error */ + lua_remove(L, -2); /* remove line because now redundant */ + if (MLref != LUA_NOREF) { /* also remove multiline if it exists */ + luaL_unref(L, LUA_REGISTRYINDEX, MLref); + MLref = LUA_NOREF; + } + /* Execute the compiled chunk of successful */ + if (status == 0) + status = docall(L, 0); + /* print any returned results or error message */ + if (status && !lua_isnil(L, -1)) { + lua_pushliteral(L, "Lua error: "); + lua_insert(L , -2); + } + l_print(L, lua_gettop(L) - 1); /* print error or results one stack */ + } + + prompt = get_prompt(L, MLref!= LUA_NOREF ? 0 : 1); + input_setprompt(prompt); + lua_writestring(prompt,strlen(prompt)); +} + + +/* +** Main body of standalone interpreter. +*/ +static int pmain (lua_State *L) { + const char *init = LUA_INIT_STRING; + int status; + STARTUP_COUNT; + + lua_gc(L, LUA_GCSTOP, 0); /* stop GC during initialization */ + luaL_openlibs(L); /* Nodemcu open will throw to signal an LFS reload */ +#ifdef LUA_VERSION_51 + lua_setegcmode( L, EGC_ALWAYS, 4096 ); +#else + lua_gc( L, LUA_GCSETMEMLIMIT, 4096 ); +#endif + lua_gc(L, LUA_GCRESTART, 0); /* restart GC and set EGC mode */ + lua_settop(L, 0); + l_create_stdin(L); + input_setup(LUA_MAXINPUT, get_prompt(L, 1)); + lua_input_string(" \n", 2); /* queue CR to issue first prompt */ + +#if defined(LUA_USE_ESP8266) && !defined(DISABLE_STARTUP_BANNER) + if ((platform_rcr_get_startup_option() & STARTUP_OPTION_NO_BANNER) == 0) { + print_version(L); + } +#else + printf("\n%s build %s powered by %s on IDF %s\n", + NODE_VERSION, BUILD_DATE, LUA_RELEASE, IDF_VER); +#endif + /* + * And last of all, kick off application initialisation. Note that if + * LUA_INIT_STRING is a file reference and the file system is uninitialised + * then attempting the open will trigger a file system format. + */ +#if defined(LUA_USE_ESP8266) + platform_rcr_read(PLATFORM_RCR_INITSTR, (void**) &init); +#endif + STARTUP_COUNT; + if (init[0] == '!') { /* !module is a compile-free way of executing LFS module */ + luaL_pushlfsmodule(L); + lua_pushstring(L, init+1); + lua_call(L, 1, 1); /* return LFS.module or nil */ + status = LUA_OK; + if (!lua_isfunction(L, -1)) { + lua_pushfstring(L, "cannot load LFS.%s", init+1); + status = LUA_ERRRUN; + } + } else { + status = (init[0] == '@') ? + luaL_loadfile(L, init+1) : + luaL_loadbuffer(L, init, strlen(init), "=INIT"); + } + STARTUP_COUNT; + if (status == LUA_OK) + status = docall(L, 0); + if (status != LUA_OK) + l_print (L, 1); + STARTUP_COUNT; + return 0; +} + + +/* +** The system initialisation CB nodemcu_init() calls lua_main() to startup the +** Lua environment by calling luaL_newstate() which initiates the core Lua VM. +** The initialisation of the libraries, etc. can potentially throw errors and +** so is wrapped in a protected call which also kicks off the user application +** through the LUA_INIT_STRING hook. +*/ +int lua_main (void) { + lua_State *L = luaL_newstate(); + if (L == NULL) { + lua_writestringerror( "cannot create state: %s", "not enough memory"); + return 0; + } + globalL = L; + lua_pushcfunction(L, pmain); + if (docall(L, 0) != LUA_OK) { + if (strstr(lua_tostring(L, -1),"!LFSrestart!")) { + lua_close(L); + return 1; /* non-zero return to flag LFS reload */ + } + l_print(L, 1); + } + return 0; +} + + +lua_State *lua_getstate(void) { + return globalL; +} + +/* +** The Lua interpreter is event-driven and task-oriented in NodeMCU rather than +** based on a readline poll loop as in the standard implementation. Input lines +** can come from one of two sources: the application can "push" lines for the +** interpreter to compile and execute, or they can come from the UART. To +** minimise application blocking, the lines are queued in a pipe when received, +** with the Lua interpreter task attached to the pipe as its reader task. This +** CB processes one line of input per task execution. +** +** Even though lines can be emitted from independent sources (the UART and the +** node API), and they could in theory get interleaved, the strategy here is +** "let the programmer beware": interactive input will normally only occur in +** development and injected input occur in telnet type applications. If there +** is a need for interlocks, then the application should handle this. +*/ + +void lua_input_string (const char *line, int len) { + lua_State *L = globalL; + lua_getfield(L, LUA_REGISTRYINDEX, "stdin"); + lua_rawgeti(L, -1, 1); /* get the pipe_write from stdin[1] */ + lua_insert(L, -2); /* stick above the pipe */ + lua_pushlstring(L, line, len); + lua_call(L, 2, 0); /* stdin:write(line) */ +} + +/* +** CB reader for the stdin pipe, and follows the calling conventions for a +** pipe readers; it has one argument, the stdin pipe that it is reading. +*/ +static int l_read_stdin (lua_State *L) { + size_t l; + lua_settop(L, 1); /* pipe obj at S[1] */ + lua_getfield(L, 1, "read"); /* pobj:read at S[2] */ + lua_pushvalue(L, 1); /* dup pobj to S[3] */ + lua_pushliteral(L, "\n+"); /* S[4] = "\n+" */ + lua_call(L, 2, 1); /* S[2] = pobj:read("\n+") */ + const char* b = lua_tolstring(L, 2, &l); /* b = NULL if S[2] is nil */ + /* + * If the pipe is empty, or the line not CR terminated, return false to + * suppress automatic reposting + */ + lua_pushboolean(L, false); + if ((lua_isnil(L, 2) || l == 0)) + return 1; /* return false if pipe empty */ + if (b[l-1] != '\n') { + /* likewise if not CR terminated, then unread and ditto */ + lua_insert(L, 1); /* insert false return above the pipe */ + lua_getfield(L, 2, "unread"); + lua_insert(L, 2); /* insert pipe.unread above the pipe */ + lua_call(L, 2, 0); /* pobj:unread(line) */ + return 1; /* return false */ + } + lua_pop(L, 1); /* dump false value at ToS */ + /* + * Now we can process a proper CR terminated line + */ + lua_pushlstring(L, b, --l); /* remove end CR */ + lua_remove(L, 2); + dojob(L); + return 0; +} + + +/* +** Create and initialise the stdin pipe +*/ +static void l_create_stdin (lua_State *L) { + lua_pushliteral(L, "stdin"); + lua_getglobal(L, "pipe"); + lua_getfield(L, -1, "create"); + lua_remove(L, -2); + lua_pushcfunction(L, l_read_stdin); + lua_pushinteger(L, LUA_TASK_LOW); + lua_call(L, 2, 1); /* ToS = pipe.create(dojob, low_priority) */ + lua_rawset(L, LUA_REGISTRYINDEX); /* and stash input pipe in Reg["stdin"] */ +} diff --git a/components/lua/lua-5.3/lua.h b/components/lua/lua-5.3/lua.h new file mode 100644 index 00000000..6f395dc9 --- /dev/null +++ b/components/lua/lua-5.3/lua.h @@ -0,0 +1,533 @@ +/* +** $Id: lua.h,v 1.332.1.2 2018/06/13 16:58:17 roberto Exp $ +** Lua - A Scripting Language +** Lua.org, PUC-Rio, Brazil (http://www.lua.org) +** See Copyright Notice at the end of this file +*/ + + +#ifndef lua_h +#define lua_h + +#include +#include + + +#include "luaconf.h" + + +#define LUA_VERSION_MAJOR "5" +#define LUA_VERSION_MINOR "3" +#define LUA_VERSION_NUM 503 +#define LUA_VERSION_RELEASE "5" + +#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR +#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE +#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2018 Lua.org, PUC-Rio" +#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" + + +/* mark for precompiled code ('Lua') */ +#define LUA_SIGNATURE "\x1bLua" + +/* option for multiple returns in 'lua_pcall' and 'lua_call' */ +#define LUA_MULTRET (-1) + + +/* +** Pseudo-indices +** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty +** space after that to help overflow detection) +*/ +#define LUA_REGISTRYINDEX (-LUAI_MAXSTACK - 1000) +#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) + + +/* thread status */ +#define LUA_OK 0 +#define LUA_YIELD 1 +#define LUA_ERRRUN 2 +#define LUA_ERRSYNTAX 3 +#define LUA_ERRMEM 4 +#define LUA_ERRGCMM 5 +#define LUA_ERRERR 6 + + +typedef struct lua_State lua_State; + + +/* +** basic types +*/ +#define LUA_TNONE (-1) + +#define LUA_TNIL 0 +#define LUA_TBOOLEAN 1 +#define LUA_TLIGHTUSERDATA 2 +#define LUA_TNUMBER 3 +#define LUA_TSTRING 4 +#define LUA_TTABLE 5 +#define LUA_TFUNCTION 6 +#define LUA_TUSERDATA 7 +#define LUA_TTHREAD 8 + +#define LUA_NUMTAGS 9 + + + +/* minimum Lua stack available to a C function */ +#define LUA_MINSTACK 20 + + +/* predefined values in the registry */ +#define LUA_RIDX_MAINTHREAD 1 +#define LUA_RIDX_GLOBALS 2 +#define LUA_RIDX_LAST LUA_RIDX_GLOBALS + + +/* type of numbers in Lua */ +typedef LUA_NUMBER lua_Number; +typedef LUA_FLOAT lua_Float; + + +/* type for integer functions */ +typedef LUA_INTEGER lua_Integer; + +/* unsigned integer type */ +typedef LUA_UNSIGNED lua_Unsigned; + +/* type for continuation-function contexts */ +typedef LUA_KCONTEXT lua_KContext; + + +/* +** Type for C functions registered with Lua +*/ +typedef int (*lua_CFunction) (lua_State *L); + +/* +** Type for continuation functions +*/ +typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); + + +/* +** Type for functions that read/write blocks when loading/dumping Lua chunks +*/ +typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); + +typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud); + + +/* +** Type for memory-allocation functions +*/ +typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); + + +/* +** generic extra include file +*/ +#if defined(LUA_USER_H) +#include LUA_USER_H +#endif + +#if defined(LUA_ENABLE_TEST) && defined(LUA_USE_HOST) +#include "ltests.h" +#endif + +/* +** RCS ident string +*/ +extern const char lua_ident[]; + + +/* +** state manipulation +*/ +LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); +LUA_API void (lua_close) (lua_State *L); +LUA_API lua_State *(lua_newthread) (lua_State *L); + +LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); + + +LUA_API const lua_Number *(lua_version) (lua_State *L); + + +/* +** basic stack manipulation +*/ +LUA_API int (lua_absindex) (lua_State *L, int idx); +LUA_API int (lua_gettop) (lua_State *L); +LUA_API void (lua_settop) (lua_State *L, int idx); +LUA_API void (lua_pushvalue) (lua_State *L, int idx); +LUA_API void (lua_rotate) (lua_State *L, int idx, int n); +LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx); +LUA_API int (lua_checkstack) (lua_State *L, int n); + +LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); + + +/* +** access functions (stack -> C) +*/ + +LUA_API int (lua_isnumber) (lua_State *L, int idx); +LUA_API int (lua_isstring) (lua_State *L, int idx); +LUA_API int (lua_iscfunction) (lua_State *L, int idx); +LUA_API int (lua_isinteger) (lua_State *L, int idx); +LUA_API int (lua_isuserdata) (lua_State *L, int idx); +LUA_API int (lua_type) (lua_State *L, int idx); +LUA_API const char *(lua_typename) (lua_State *L, int tp); + +LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum); +LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum); +LUA_API int (lua_toboolean) (lua_State *L, int idx); +LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); +LUA_API size_t (lua_rawlen) (lua_State *L, int idx); +LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); +LUA_API void *(lua_touserdata) (lua_State *L, int idx); +LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); +LUA_API const void *(lua_topointer) (lua_State *L, int idx); + + +/* +** Comparison and arithmetic functions +*/ + +#define LUA_OPADD 0 /* ORDER TM, ORDER OP */ +#define LUA_OPSUB 1 +#define LUA_OPMUL 2 +#define LUA_OPMOD 3 +#define LUA_OPPOW 4 +#define LUA_OPDIV 5 +#define LUA_OPIDIV 6 +#define LUA_OPBAND 7 +#define LUA_OPBOR 8 +#define LUA_OPBXOR 9 +#define LUA_OPSHL 10 +#define LUA_OPSHR 11 +#define LUA_OPUNM 12 +#define LUA_OPBNOT 13 + +LUA_API void (lua_arith) (lua_State *L, int op); + +#define LUA_OPEQ 0 +#define LUA_OPLT 1 +#define LUA_OPLE 2 + +LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); +LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op); + + +/* +** push functions (C -> stack) +*/ +LUA_API void (lua_pushnil) (lua_State *L); +LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); +LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); +LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len); +LUA_API const char *(lua_pushstring) (lua_State *L, const char *s); +LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, + va_list argp); +LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); +LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); +LUA_API void (lua_pushboolean) (lua_State *L, int b); +LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); +LUA_API int (lua_pushthread) (lua_State *L); + + +/* +** get functions (Lua -> stack) +*/ +LUA_API int (lua_getglobal) (lua_State *L, const char *name); +LUA_API int (lua_gettable) (lua_State *L, int idx); +LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k); +LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n); +LUA_API int (lua_rawget) (lua_State *L, int idx); +LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n); +LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p); + +LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); +LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); +LUA_API int (lua_getmetatable) (lua_State *L, int objindex); +LUA_API int (lua_getuservalue) (lua_State *L, int idx); + + +/* +** set functions (stack -> Lua) +*/ +LUA_API void (lua_setglobal) (lua_State *L, const char *name); +LUA_API void (lua_settable) (lua_State *L, int idx); +LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); +LUA_API void (lua_seti) (lua_State *L, int idx, lua_Integer n); +LUA_API void (lua_rawset) (lua_State *L, int idx); +LUA_API void (lua_rawseti) (lua_State *L, int idx, lua_Integer n); +LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p); +LUA_API int (lua_setmetatable) (lua_State *L, int objindex); +LUA_API void (lua_setuservalue) (lua_State *L, int idx); + + +/* +** 'load' and 'call' functions (load and run Lua code) +*/ +LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults, + lua_KContext ctx, lua_KFunction k); +#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) + +LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc, + lua_KContext ctx, lua_KFunction k); +#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) + +LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, + const char *chunkname, const char *mode); + +LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip); +LUA_API int (lua_stripdebug) (lua_State *L, int stripping); + + +/* +** coroutine functions +*/ +LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx, + lua_KFunction k); +LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg); +LUA_API int (lua_status) (lua_State *L); +LUA_API int (lua_isyieldable) (lua_State *L); + +#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) + + +/* +** garbage-collection function and options +*/ + +#define LUA_GCSTOP 0 +#define LUA_GCRESTART 1 +#define LUA_GCCOLLECT 2 +#define LUA_GCCOUNT 3 +#define LUA_GCCOUNTB 4 +#define LUA_GCSTEP 5 +#define LUA_GCSETPAUSE 6 +#define LUA_GCSETSTEPMUL 7 +#define LUA_GCSETMEMLIMIT 8 +#define LUA_GCISRUNNING 9 + +LUA_API int (lua_gc) (lua_State *L, int what, int data); + + +/* +** miscellaneous functions +*/ + +LUA_API int (lua_error) (lua_State *L); + +LUA_API int (lua_next) (lua_State *L, int idx); + +LUA_API void (lua_concat) (lua_State *L, int n); +LUA_API void (lua_len) (lua_State *L, int idx); + +LUA_API size_t (lua_stringtonumber) (lua_State *L, const char *s); + +LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); +LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud); + + + +/* +** {============================================================== +** some useful macros +** =============================================================== +*/ + +#define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE)) + +#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL) +#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL) + +#define lua_pop(L,n) lua_settop(L, -(n)-1) + +#define lua_newtable(L) lua_createtable(L, 0, 0) + +#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) + +#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) + +#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) +#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) +#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) +#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) +#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) +#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) +#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) +#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) + +#define lua_pushliteral(L, s) lua_pushstring(L, "" s) + +#define lua_pushglobaltable(L) \ + ((void)lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS)) + +#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) + + +#define lua_insert(L,idx) lua_rotate(L, (idx), 1) + +#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1)) + +#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1)) + +/* }============================================================== */ + + +/* +** {============================================================== +** compatibility macros for unsigned conversions +** =============================================================== +*/ +#if defined(LUA_COMPAT_APIINTCASTS) + +#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) +#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is)) +#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL) + +#endif +/* }============================================================== */ + +/* +** {====================================================================== +** Debug API +** ======================================================================= +*/ + + +/* +** Event codes +*/ +#define LUA_HOOKCALL 0 +#define LUA_HOOKRET 1 +#define LUA_HOOKLINE 2 +#define LUA_HOOKCOUNT 3 +#define LUA_HOOKTAILCALL 4 + + +/* +** Event masks +*/ +#define LUA_MASKCALL (1 << LUA_HOOKCALL) +#define LUA_MASKRET (1 << LUA_HOOKRET) +#define LUA_MASKLINE (1 << LUA_HOOKLINE) +#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) + +typedef struct lua_Debug lua_Debug; /* activation record */ + + +/* Functions to be called by the debugger in specific events */ +typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); + + +LUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar); +LUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar); +LUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n); +LUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n); +LUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n); +LUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n); + +LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n); +LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1, + int fidx2, int n2); + +LUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count); +LUA_API lua_Hook (lua_gethook) (lua_State *L); +LUA_API int (lua_gethookmask) (lua_State *L); +LUA_API int (lua_gethookcount) (lua_State *L); + + +struct lua_Debug { + int event; + const char *name; /* (n) */ + const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */ + const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */ + const char *source; /* (S) */ + int currentline; /* (l) */ + int linedefined; /* (S) */ + int lastlinedefined; /* (S) */ + unsigned char nups; /* (u) number of upvalues */ + unsigned char nparams;/* (u) number of parameters */ + char isvararg; /* (u) */ + char istailcall; /* (t) */ + char short_src[LUA_IDSIZE]; /* (S) */ + /* private part */ + struct CallInfo *i_ci; /* active function */ +}; + +int lua_main(void); +void lua_input_string (const char *line, int len); + +/* }====================================================================== */ + +/* NodeMCU extensions to the standard API */ + +typedef struct ROTable ROTable; +typedef const struct ROTable_entry ROTable_entry; + +LUA_API void (lua_pushrotable) (lua_State *L, const ROTable *p); +LUA_API void (lua_createrotable) (lua_State *L, ROTable *t, const ROTable_entry *e, ROTable *mt); +LUA_API lua_State *(lua_getstate) (void); +LUA_API int (lua_pushstringsarray) (lua_State *L, int opt); +LUA_API int (lua_freeheap) (void); + +LUA_API void (lua_getlfsconfig) (lua_State *L, intptr_t *); +LUA_API int (lua_pushlfsindex) (lua_State *L); +LUA_API int (lua_pushlfsfunc) (lua_State *L); + + +#define luaN_freearray(L,a,l) luaM_freearray(L,a,l) + +// LUA_MAXINPUT is the maximum length for an input line in the +#define LUA_MAXINPUT 256 +#define LUAI_MAXINT32 INT_MAX + +typedef struct Proto Proto; + +#ifdef DEVELOPMENT_USE_GDB +LUALIB_API void (lua_debugbreak)(void); +#define ASSERT(s) ((s) ? (void)0 : lua_debugbreak()) +#else +#define lua_debugbreak() (void)(0) +#define ASSERT(s) (void)(0) +#endif + + +// from undump.c +#define LUA_ERR_CC_INTOVERFLOW 101 +#define LUA_ERR_CC_NOTINTEGER 102 + + +/* }====================================================================== */ + +/****************************************************************************** +* Copyright (C) 1994-2018 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. +******************************************************************************/ + + +#endif diff --git a/components/lua/lua-5.3/luaconf.h b/components/lua/lua-5.3/luaconf.h new file mode 100644 index 00000000..a7089da2 --- /dev/null +++ b/components/lua/lua-5.3/luaconf.h @@ -0,0 +1,444 @@ +/* +** $Id: luaconf.h,v 1.259.1.1 2017/04/19 17:29:57 roberto Exp $ +** Configuration file for Lua +** See Copyright Notice in lua.h +*/ + + +#ifndef luaconf_h +#define luaconf_h + +#include +#include +#include +#include +#include "sdkconfig.h" + +/* +** =================================================================== +** The NodeMCU Lua environment support 2 compilation targets: +** +** * The ESP8266 ans ESP32 embedded runtimes which are compiled using +** the GCC XTENSA cross-compiler toolchain. +** +** * An extend version of the luac build for cross-compiling Lua +** sources for downloading to the ESP hardware. This is command +** line only and does not support any interactive dialogue or +** dynamically loaded libraries. +** +** Note that we've removd the "how to fill this in comments so you +** can now see the actual content more easily. Also the two big +** boilerplate conditional sections "Configuration for Numbers" and +** "Dependencies with C99 and other C details" have been moved to +** the end of the include file to keep the information dense content +** at the front. +** =================================================================== +*/ +#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE) +# define LUA_USE_WINDOWS /* enable goodies for regular Windows */ +//# define LUA_USE_C89 /* We only support the VS2013 C or later */ +#elif defined(__APPLE__) +# define LUA_USE_MACOSX +# define LUA_USE_POSIX +#else +# define LUA_USE_LINUX +//# define LUA_USE_POSIX +#endif + +#define LUA_NODEMCU_NOCLOADERS + +//#define LUA_C89_NUMBERS + +#define LUAI_BITSINT 32 + +/* predefined options for LUA_INT_TYPE */ +#define LUA_INT_INT 1 +#define LUA_INT_LONG 2 +#define LUA_INT_LONGLONG 3L + +/* predefined options for LUA_FLOAT_TYPE */ +#define LUA_FLOAT_FLOAT 1 +#define LUA_FLOAT_DOUBLE 2 +#define LUA_FLOAT_LONGDOUBLE 3 + +/* 32 vs 64 bit decisions controlled via Kconfig options */ +#if defined(CONFIG_LUA_NUMBER_INT64) +# define LUA_INT_TYPE LUA_INT_LONGLONG +#else +# define LUA_INT_TYPE LUA_INT_INT +#endif + +#if defined(CONFIG_LUA_NUMBER_DOUBLE) +# define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE +#else +# define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT +#endif + +/* +** Configuration for Paths. +** +** LUA_CPATH_DEFAULT is the default path that Lua uses to look for +** Dynamic C libraries are not used and ditto LUA_CPATH_DEFAULT +*/ +#define LUA_PATH_SEP ";" +#define LUA_PATH_MARK "?" +#define LUA_EXEC_DIR "!" +#define LUA_PATH_DEFAULT "?.lc;?.lua" + +#if defined(_WIN32) +#define LUA_DIRSEP "\\" +#else +#define LUA_DIRSEP "/" +#endif + +/* +** {================================================================== +** Marks for exported symbols in the C code +** =================================================================== +** +@@ LUA_API is a mark for all core API functions. +@@ LUALIB_API is a mark for all auxiliary library functions. +@@ LUAMOD_API is a mark for all standard library opening functions. +*/ +#define LUA_API extern +#define LUALIB_API LUA_API +#define LUAMOD_API LUALIB_API + + +/* +@@ LUAI_FUNC, LUAI_DDEF and LUAI_DDEC are used to mark visibilty when +** building lua as a shared library. Used to tag private inter-module +** Lua internal functions. +*/ +//#define LUAI_FUNC __attribute__((visibility("hidden"))) extern +#define LUAI_FUNC extern +#define LUAI_DDEC LUAI_FUNC +#define LUAI_DDEF + +/* +** {================================================================== +** Compatibility with previous versions +** =================================================================== +*/ + +//#define LUA_COMPAT_MATHLIB // retains several deprecated functions in math. +//#define LUA_COMPAT_BITLIB // bit32 is separately implemented as a NodeMCU lib +//#define LUA_COMPAT_IPAIRS // enables __ipairs meta which isn't used in NodeMCU + +#define LUA_NODEMCU_COMPAT_MATHLIB /* retains NodeMCU subset of mathlib */ +#define LUA_COMPAT_APIINTCASTS /* needed to enable NodeMCU modules to work on */ + /* both Lua 5.1 and Lua 5.3 */ +#define LUA_COMPAT_UNPACK /* needed to support a global 'unpack' */ +#define LUA_COMPAT_LOADERS /* keeps 'package.loaders' as a synonym for */ + /* 'package.searchers'. Used in our libraries */ +#define LUA_COMPAT_LOADSTRING /* keeps loadstring(s) as synonym for load(s) */ + +#if 0 +#define lua_cpcall(L,f,u) \ // Not used in our module code + (lua_pushcfunction(L, (f)), \ + lua_pushlightuserdata(L,(u)), \ + lua_pcall(L,1,0,0)) +#endif + +//#define LUA_COMPAT_LOG10 // math.log10 not used in NodeMCU +//#define LUA_COMPAT_MAXN // math.maxn not used + +/* Compatbililty for some API calls withdrawn in Lua53 */ + +#define lua_strlen(L,i) lua_rawlen(L, (i)) +#define lua_objlen(L,i) lua_rawlen(L, (i)) +#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) +#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) + +// #define LUA_COMPAT_MODULE // drop support for legacy module() format not used in our modules + +/**** May need to revisit this one *****/ +// #define LUA_COMPAT_FLOATSTRING // makes Lua format integral floats without a float mark + +#define LUA_KCONTEXT ptrdiff_t + +#define lua_getlocaledecpoint() '.' + +// #define LUA_NOCVTN2S // enable automatic coercion between +// #define LUA_NOCVTS2N // strings and numbers + +#if defined(LUA_USE_APICHECK) +#include +#define luai_apicheck(l,e) assert(e) +#endif + +#define LUA_EXTRASPACE (sizeof(void *)) // raw memory area associated with a Lua state +#define LUAI_MAXSTACK 12000 // Maximum Lua stack size +#define LUA_IDSIZE 60 // Maximum size for the description of the source + +/* +@@ lua_getlocaledecpoint gets the locale "radix character" (decimal point). +** Change that if you do not want to use C locales. (Code using this +** macro must include header 'locale.h'.) +*/ + // of a function in debug information. +#define LUAL_BUFFERSIZE 256 // NodeMCU setting because of stack limits +#define LUA_QL(x) "'" x "'" // No longer used in lua53, but still used +#define LUA_QS LUA_QL("%s") // in some of our apllication modules + +/* +** {================================================================== +** Other NodeMCU configuration. +** =================================================================== +*/ + +#ifdef LUA_USE_ESP +#define LUAI_USER_ALIGNMENT_T size_t +#endif + +#define LUAI_GCPAUSE 110 /* 110% (wait memory to grow 10% before next gc) */ + +/* }================================================================== */ + +/* +** {================================================================== +** Configuration for Numbers. +** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_* +** satisfy your needs. +** =================================================================== +** +@@ LUA_NUMBER is the floating-point type used by Lua. +@@ LUAI_UACNUMBER is the result of a 'default argument promotion' over a floating number. +@@ l_mathlim(x) corrects limit name 'x' to the proper float type by prefixing it with one of FLT/DBL/LDBL. +@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats. +@@ LUA_NUMBER_FMT is the format for writing floats. +@@ lua_number2str converts a float to a string. +@@ l_mathop allows the addition of an 'l' or 'f' to all math operations. +@@ l_floor takes the floor of a float. +@@ lua_str2number converts a decimal numeric string to a number. +*/ + +/* The following definitions are good for most cases here */ + +#define l_floor(x) (l_mathop(floor)(x)) + +#define lua_number2str(s,sz,n) \ + l_sprintf((s), sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)(n)) + +/* +@@ lua_numbertointeger converts a float number to an integer, or +** returns 0 if float is not within the range of a lua_Integer. +** (The range comparisons are tricky because of rounding. The tests +** here assume a two-complement representation, where MININTEGER always +** has an exact representation as a float; MAXINTEGER may not have one, +** and therefore its conversion to float may have an ill-defined value.) +*/ +#define lua_numbertointeger(n,p) \ + ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ + (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ + (*(p) = (LUA_INTEGER)(n), 1)) + + +/* now the variable definitions */ + +#if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */ + +#define LUA_NUMBER float + +#define l_mathlim(n) (FLT_##n) + +#define LUAI_UACNUMBER double + +#define LUA_NUMBER_FRMLEN "" +#define LUA_NUMBER_FMT "%.7g" + +#define l_mathop(op) op##f + +#define lua_str2number(s,p) strtof((s), (p)) + + +#elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE /* }{ long double */ + +#define LUA_NUMBER long double + +#define l_mathlim(n) (LDBL_##n) + +#define LUAI_UACNUMBER long double + +#define LUA_NUMBER_FRMLEN "L" +#define LUA_NUMBER_FMT "%.19Lg" + +#define l_mathop(op) op##l + +#define lua_str2number(s,p) strtold((s), (p)) + +#elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE /* }{ double */ + +#define LUA_NUMBER double + +#define l_mathlim(n) (DBL_##n) + +#define LUAI_UACNUMBER double + +#define LUA_NUMBER_FRMLEN "" +#define LUA_NUMBER_FMT "%.14g" + +#define l_mathop(op) op + +#define lua_str2number(s,p) strtod((s), (p)) + +#else /* }{ */ + +#error "numeric float type not defined" + +#endif /* } */ +#define LUA_FLOAT LUA_NUMBER + + +/* +@@ LUA_INTEGER is the integer type used by Lua. +** +@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER. +** +@@ LUAI_UACINT is the result of a 'default argument promotion' +@@ over a lUA_INTEGER. +@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers. +@@ LUA_INTEGER_FMT is the format for writing integers. +@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER. +@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER. +@@ lua_integer2str converts an integer to a string. +*/ + + +/* The following definitions are good for most cases here */ + +#define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d" + +#define LUAI_UACINT LUA_INTEGER + +#define lua_integer2str(s,sz,n) \ + l_sprintf((s), sz, LUA_INTEGER_FMT, (LUAI_UACINT)(n)) + +/* +** use LUAI_UACINT here to avoid problems with promotions (which +** can turn a comparison between unsigneds into a signed comparison) +*/ +#define LUA_UNSIGNED unsigned LUAI_UACINT + + +/* now the variable definitions */ + +#if LUA_INT_TYPE == LUA_INT_INT /* { int */ + +#define LUA_INTEGER int +#define LUA_INTEGER_FRMLEN "" + +#define LUA_MAXINTEGER INT_MAX +#define LUA_MININTEGER INT_MIN + +#elif LUA_INT_TYPE == LUA_INT_LONG /* }{ long */ + +#define LUA_INTEGER long +#define LUA_INTEGER_FRMLEN "l" + +#define LUA_MAXINTEGER LONG_MAX +#define LUA_MININTEGER LONG_MIN + +#elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */ + +/* use presence of macro LLONG_MAX as proxy for C99 compliance */ +#if defined(LLONG_MAX) /* { */ +/* use ISO C99 stuff */ + +#define LUA_INTEGER long long +#define LUA_INTEGER_FRMLEN "ll" + +#define LUA_MAXINTEGER LLONG_MAX +#define LUA_MININTEGER LLONG_MIN + +#elif defined(LUA_USE_WINDOWS) /* }{ */ +/* in Windows, can use specific Windows types */ + +#define LUA_INTEGER __int64 +#define LUA_INTEGER_FRMLEN "I64" + +#define LUA_MAXINTEGER _I64_MAX +#define LUA_MININTEGER _I64_MIN + +#else /* }{ */ + +#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \ + or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)" + +#endif /* } */ + +#else /* }{ */ + +#error "numeric integer type not defined" + +#endif /* } */ + +/* }================================================================== */ + + +/* +** {================================================================== +** Dependencies with C99 and other C details +** =================================================================== +*/ + +/* +@@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89. +** (All uses in Lua have only one format item.) +*/ +#if !defined(LUA_USE_C89) +#define l_sprintf(s,sz,f,i) snprintf(s,sz,f,i) +#else +#define l_sprintf(s,sz,f,i) ((void)(sz), sprintf(s,f,i)) +#endif + + +/* +@@ lua_strx2number converts an hexadecimal numeric string to a number. +** In C99, 'strtod' does that conversion. Otherwise, you can +** leave 'lua_strx2number' undefined and Lua will provide its own +** implementation. +*/ +#if !defined(LUA_USE_C89) +#define lua_strx2number(s,p) lua_str2number(s,p) +#endif + + +/* +@@ lua_pointer2str converts a pointer to a readable string in a +** non-specified way. +*/ +#define lua_pointer2str(buff,sz,p) l_sprintf(buff,sz,"%p",p) + + +/* +@@ lua_number2strx converts a float to an hexadecimal numeric string. +** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that. +** Otherwise, you can leave 'lua_number2strx' undefined and Lua will +** provide its own implementation. +*/ +#if !defined(LUA_USE_C89) +#define lua_number2strx(L,b,sz,f,n) \ + ((void)L, l_sprintf(b,sz,f,(LUAI_UACNUMBER)(n))) +#endif + + +/* +** 'strtof' and 'opf' variants for math functions are not valid in +** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the +** availability of these variants. ('math.h' is already included in +** all files that use these macros.) +*/ +#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF)) +#undef l_mathop /* variants not available */ +#undef lua_str2number +#define l_mathop(op) (lua_Number)op /* no variant */ +#define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) +#endif + +#undef lua_str2number +#define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) + +#define LUA_DEBUG_HOOK lua_debugbreak + +#endif diff --git a/components/lua/lua-5.3/lualib.h b/components/lua/lua-5.3/lualib.h new file mode 100644 index 00000000..f5304aa0 --- /dev/null +++ b/components/lua/lua-5.3/lualib.h @@ -0,0 +1,61 @@ +/* +** $Id: lualib.h,v 1.45.1.1 2017/04/19 17:20:42 roberto Exp $ +** Lua standard libraries +** See Copyright Notice in lua.h +*/ + + +#ifndef lualib_h +#define lualib_h + +#include "lua.h" + + +/* version suffix for environment variable names */ +#define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR + + +LUAMOD_API int (luaopen_base) (lua_State *L); + +#define LUA_COLIBNAME "coroutine" +LUAMOD_API int (luaopen_coroutine) (lua_State *L); + +#define LUA_TABLIBNAME "table" +LUAMOD_API int (luaopen_table) (lua_State *L); + +#define LUA_IOLIBNAME "io" +LUAMOD_API int (luaopen_io) (lua_State *L); + +#define LUA_OSLIBNAME "os" +LUAMOD_API int (luaopen_os) (lua_State *L); + +#define LUA_STRLIBNAME "string" +LUAMOD_API int (luaopen_string) (lua_State *L); + +#define LUA_UTF8LIBNAME "utf8" +LUAMOD_API int (luaopen_utf8) (lua_State *L); + +#define LUA_BITLIBNAME "bit32" +LUAMOD_API int (luaopen_bit32) (lua_State *L); + +#define LUA_MATHLIBNAME "math" +LUAMOD_API int (luaopen_math) (lua_State *L); + +#define LUA_DBLIBNAME "debug" +LUAMOD_API int (luaopen_debug) (lua_State *L); + +#define LUA_LOADLIBNAME "package" +LUAMOD_API int (luaopen_package) (lua_State *L); + + +/* open all previous libraries */ +LUALIB_API void (luaL_openlibs) (lua_State *L); + + + +#if !defined(lua_assert) +#define lua_assert(x) ((void)0) +#endif + + +#endif diff --git a/components/lua/lua-5.3/lundump.c b/components/lua/lua-5.3/lundump.c new file mode 100644 index 00000000..578e2d29 --- /dev/null +++ b/components/lua/lua-5.3/lundump.c @@ -0,0 +1,637 @@ +/*--- +** $Id: lundump.c,v 2.44.1.1 2017/04/19 17:20:42 roberto Exp $ +** load precompiled Lua chunks +** See Copyright Notice in lua.h +*/ +#define lundump_c +#define LUA_CORE +#include "lprefix.h" +#include +#include "lua.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "llex.h" +#include "lmem.h" +#include "lnodemcu.h" +#include "lobject.h" +#include "lstring.h" +#include "lundump.h" +#include "lzio.h" +/* +** Unlike the standard Lua version of lundump.c, this NodeMCU version must be +** able to store the dumped Protos into one of two targets: +** +** (A) RAM-based heap. This in the same way as standard Lua, where the +** Proto data structures can be created by direct in memory addressing, +** with any references complying with Lua GC assumptions, so that all +** storage can be collected in the case of a thrown error. +** +** (B) Flash programmable ROM memory. This can only be written to serially, +** using a write API, it can be subsequently but accessed and directly +** addressable through a memory-mapped address window after cache flush. +** +** Mode (B) also know as LFS (Lua FLash Store) enables running Lua apps +** on small-memory IoT devices which support programmable flash storage such +** as the ESP8266 SoC. In the case of this chip, the usable RAM heap is +** roughly 45Kb, so the ability to store an extra 128Kb, say, of program into +** LFS can materially increase the size of application that can be executed +** and leave most of the heap for true R/W application data. +** +** The changes to this source file enable the addition of LFS mode. In mode B, +** the resources aren't allocated in RAM but are written to Flash using the +** write API which returns the corresponding Flash read address is returned; +** also data can't be immediately read back using these addresses because of +** cache staleness. +** +** Handling the Proto record has been reordered to avoid interleaved resource +** writes in mode (B), with the f->k being cached in RAM and the Proto +** hierarchies walked bottom-up in a way that still maintains GC compliance +** conformance for mode (A). This no-interleave constraint also complicates +** the writing of TString resources into flash, so the flashing process +** circumvents this issue for LFS loads by header by taking two passes to dump +** the hierarchy. The first dumps all strings that needed to load the Protos, +** with the subsequent Proto loads use an index to any TString references. +** This enables all strings to be loaded into an LFS-based ROstrt before +** starting to load the Protos. +** +** Note that this module and ldump.c are compiled into both the ESP firmware +** and a host-based luac cross compiler. LFS dump is currently only supported +** in the compiler, but both the LFS and standard loads are supported in both +** the target (lua.c) and the host (luac.cross -e)environments. Both +** environments are built with the same integer and float formats (e.g. 32 bit, +** 32-bit IEEE). +** +** Dumps can either be loaded into RAM or LFS depending on the load format. An +** extra complication is that luac.cross supports two LFS modes, with the +** first loading into an host process address space and using host 32 or 64 +** bit address references. The second uses shadow ESP 32 bit addresses to +** create an absolute binary image for direct provisioning of ESP images. +*/ +#define MODE_RAM 0 /* Loading into RAM */ +#define MODE_LFS 1 /* Loading into a locally executable LFS */ +#define MODE_LFSA 2 /* (Host only) Loading into a shadow ESP image */ +typedef struct { + lua_State *L; /* cache L to drop parameter list */ + ZIO *Z; /* ZIO context */ + const char *name; /* Filename of the LFS image being loaded */ + LFSHeader *fh; /* LFS flash header block */ + void *startLFS; /* Start address of LFS region */ + TString **TS; /* List of TStrings being used in the image */ + lu_int32 TSlen; /* Length of the same */ + lu_int32 TSndx; /* Index into the same */ + lu_int32 TSnFixed; /* Number of "fixed" TS */ + char *buff; /* Working buffer for assembling a TString */ + lu_int32 buffLen; /* Maximum length of TS used in the image */ + TString **list; /* TS list used to index the ROstrt */ + lu_int32 listLen; /* Length of the same */ + Proto **pv; /* List of Protos in LFS */ + lu_int32 pvLen; /* Length of the same */ + GCObject *protogc; /* LFS proto linked list */ + lu_byte useStrRefs; /* Flag if set then TStings are a index into TS */ + lu_byte mode; /* Either LFS or RAM */ +} LoadState; +static l_noret error(LoadState *S, const char *why) { + luaO_pushfstring(S->L, "%s: %s precompiled chunk", S->name, why); + luaD_throw(S->L, LUA_ERRSYNTAX); +} +#define wordptr(p) cast(lu_int32 *, p) +#define byteptr(p) cast(lu_byte *, p) +#define wordoffset(p,q) (wordptr(p) - wordptr(q)) +#define FHaddr(S,t,f) cast(t, wordptr(S->startLFS) + (f)) +#define FHoffset(S,o) wordoffset((o), S->startLFS) +#define NewVector(S, n, t) cast(t *,NewVector_(S, n, sizeof(t))) +#define StoreGetPos(S) luaN_writeFlash((S)->Z->data, NULL, 0) +static void *NewVector_(LoadState *S, int n, size_t s) { + void *v; + if (S->mode == MODE_RAM) { + v = luaM_reallocv(S->L, NULL, 0, n, s); + memset (v, 0, n*s); + } else { + v = StoreGetPos(S); + } + return v; +} +static void *Store_(LoadState *S, void *a, int ndx, const void *e, size_t s +#ifdef LUA_USE_HOST + , const char *format +#endif + ) { + if (S->mode == MODE_RAM) { + lu_byte *p = byteptr(a) + ndx*s; + if (p != byteptr(e)) + memcpy(p, e, s); + return p; + } +#ifdef LUA_USE_HOST + else if (S->mode == MODE_LFSA && format) { /* do a repack move */ + void *p = StoreGetPos(S); + const char *f = format; + int o; + for (o = 0; *f; o++, f++ ) { + luaN_writeFlash(S->Z->data, wordptr(e)+o, sizeof(lu_int32)); + if (*f == 'A' || *f == 'W') /* Addr or word followed by alignment fill */ + o++; + } + lua_assert(o*sizeof(lu_int32) == s); + return p; + } +#endif + /* mode == LFS or 32bit build */ + return luaN_writeFlash(S->Z->data, e, s); +} +#ifdef LUA_USE_HOST +#include +/* These compression maps must match the definitions in lobject.h etc. */ +# define OFFSET_TSTRING (2*(sizeof(lu_int32)-sizeof(size_t))) +# define FMT_TSTRING "AwwA" +# define FMT_TVALUE "WA" +# define FMT_PROTO "AwwwwwwwwwwAAAAAAAA" +# define FMT_UPVALUE "AW" +# define FMT_LOCVAR "Aww" +# define FMT_ROTENTRY "AWA" +# define FMT_ROTABLE "AWAA" +# define StoreR(S,a, i, v, f) Store_(S, (a), i, &(v), sizeof(v), f) +# define Store(S, a, i, v) StoreR(S, (a), i, v, NULL) +# define StoreN(S, v, n) Store_(S, NULL, 0, (v), (n)*sizeof(*(v)), NULL) +static void *StoreAV (LoadState *S, void *a, int n) { + void **av = cast(void**, a); + if (S->mode == MODE_LFSA) { + void *p = StoreGetPos(S); + int i; for (i = 0; i < n; i ++) + luaN_writeFlash(S->Z->data, wordptr(av++), sizeof(lu_int32)); + return p; + } else { + return Store_(S, NULL, 0, av, n*sizeof(*av), NULL); + } +} +#else // LUA_USE_ESP +# define OFFSET_TSTRING (0) +# define Store(S, a, i, v) Store_(S, (a), i, &(v), sizeof(v)) +# define StoreN(S, v, n) Store_(S, NULL, 0, (v), (n)*sizeof(*(v))) + # define StoreR(S, a, i, v, f) Store(S, a, i, v) +# define StoreAV(S, p, n) StoreN(S, p, n) +# define OPT_FMT +#endif +#define StoreFlush(S) luaN_flushFlash((S)->Z->data); +#define LoadVector(S,b,n) LoadBlock(S,b,(n)*sizeof((b)[0])) +static void LoadBlock (LoadState *S, void *b, size_t size) { + lu_int32 left = luaZ_read(S->Z, b, size); + if ( left != 0) + error(S, "truncated"); +} +#define LoadVar(S,x) LoadVector(S,&x,1) +static lu_byte LoadByte (LoadState *S) { + lu_byte x; + LoadVar(S, x); + return x; +} +static lua_Integer LoadInt (LoadState *S) { + lu_byte b; + lua_Integer x = 0; + do { b = LoadByte(S); x = (x<<7) + (b & 0x7f); } while (b & 0x80); + return x; +} +static lua_Number LoadNumber (LoadState *S) { + lua_Number x; + LoadVar(S, x); + return x; +} +static lua_Integer LoadInteger (LoadState *S, lu_byte tt_data) { + lu_byte b; + lua_Integer x = tt_data & LUAU_DMASK; + if (tt_data & 0x80) { + do { b = LoadByte(S); x = (x<<7) + (b & 0x7f); } while (b & 0x80); + } + return (tt_data & LUAU_TMASK) == LUAU_TNUMNINT ? -x-1 : x; +} +static TString *LoadString_ (LoadState *S, int prelen) { + TString *ts; + char buff[LUAI_MAXSHORTLEN]; + int n = LoadInteger(S, (prelen < 0 ? LoadByte(S) : prelen)) - 1; + if (n < 0) + return NULL; + if (S->useStrRefs) + ts = S->TS[n]; + else if (n <= LUAI_MAXSHORTLEN) { /* short string? */ + LoadVector(S, buff, n); + ts = luaS_newlstr(S->L, buff, n); + } else { /* long string */ + ts = luaS_createlngstrobj(S->L, n); + LoadVector(S, getstr(ts), n); /* load directly in final place */ + } + return ts; +} +#define LoadString(S) LoadString_(S,-1) +#define LoadString2(S,pl) LoadString_(S,(pl)) +static void LoadCode (LoadState *S, Proto *f) { + Instruction *p; + f->sizecode = LoadInt(S); + f->code = luaM_newvector(S->L, f->sizecode, Instruction); + LoadVector(S, f->code, f->sizecode); + if (S->mode != MODE_RAM) { + p = StoreN(S, f->code, f->sizecode); + luaM_freearray(S->L, f->code, f->sizecode); + f->code = p; + } +} +static void *LoadFunction(LoadState *S, Proto *f, TString *psource); +static void LoadConstants (LoadState *S, Proto *f) { + int i; + f->sizek = LoadInt(S); + f->k = NewVector(S, f->sizek, TValue); + for (i = 0; i < f->sizek; i++) { + TValue o; + /* + * tt is formatted 0bFTTTDDDD where TTT is the type; the F and the DDDD + * fields are used by the integer decoder as this often saves a byte in + * the endcoding. + */ + lu_byte tt = LoadByte(S); + switch (tt & LUAU_TMASK) { + case LUAU_TNIL: + setnilvalue(&o); + break; + case LUAU_TBOOLEAN: + setbvalue(&o, !(tt == LUAU_TBOOLEAN)); + break; + case LUAU_TNUMFLT: + setfltvalue(&o, LoadNumber(S)); + break; + case LUAU_TNUMPINT: + case LUAU_TNUMNINT: + setivalue(&o, LoadInteger(S, tt)); + break; + case LUAU_TSSTRING: + o.value_.gc = cast(GCObject *, LoadString2(S, tt)); + o.tt_ = ctb(LUA_TSHRSTR); + break; + case LUAU_TLSTRING: + o.value_.gc = cast(GCObject *, LoadString2(S, tt)); + o.tt_ = ctb(LUA_TLNGSTR); + break; + default: + lua_assert(0); + } + StoreR(S, f->k, i, o, FMT_TVALUE); + } +} +/* +** The handling of Protos has support both modes, and in the case of flash +** mode, this requires some care as any writes to a Proto f must be deferred +** until after all of the writes to its sub Protos have been completed; so +** the Proto record and its p vector must be retained in RAM until stored to +** flash. +** +** Recovery of dead resources on error handled by the Lua GC as standard in +** the case of RAM loading. In the case of loading an LFS image into flash, +** the error recovery could be done through the S->protogc list, but given +** that the immediate action is to restart the CPU, there is little point +** in adding the extra functionality to recover these dangling resources. +*/ +static void LoadProtos (LoadState *S, Proto *f) { + int i, n = LoadInt(S); + Proto **p = luaM_newvector(S->L, n, Proto *); + f->p = p; + f->sizep = n; + memset (p, 0, n * sizeof(*p)); + for (i = 0; i < n; i++) + p[i] = LoadFunction(S, luaF_newproto(S->L), f->source); + if (S->mode != MODE_RAM) { + f->p = StoreAV(S, cast(void **, p), n); + luaM_freearray(S->L, p, n); + } +} +static void LoadUpvalues (LoadState *S, Proto *f) { + int i, nostripnames = LoadByte(S); + f->sizeupvalues = LoadInt(S); + if (f->sizeupvalues) { + f->upvalues = NewVector(S, f->sizeupvalues, Upvaldesc); + for (i = 0; i < f->sizeupvalues ; i++) { + TString *name = nostripnames ? LoadString(S) : NULL; + Upvaldesc uv = {name, LoadByte(S), LoadByte(S)}; + StoreR(S, f->upvalues, i, uv, FMT_UPVALUE); + } + } +} +static void LoadDebug (LoadState *S, Proto *f) { + int i; + f->sizelineinfo = LoadInt(S); + if (f->sizelineinfo) { + lu_byte *li = luaM_newvector(S->L, f->sizelineinfo, lu_byte); + LoadVector(S, li, f->sizelineinfo); + if (S->mode == MODE_RAM) { + f->lineinfo = li; + } else { + f->lineinfo = StoreN(S, li, f->sizelineinfo); + luaM_freearray(S->L, li, f->sizelineinfo); + } + } + f->sizelocvars = LoadInt(S); + f->locvars = NewVector(S, f->sizelocvars, LocVar); + for (i = 0; i < f->sizelocvars; i++) { + LocVar lv = {LoadString(S), LoadInt(S), LoadInt(S)}; + StoreR(S, f->locvars, i, lv, FMT_LOCVAR); + } +} +static void *LoadFunction (LoadState *S, Proto *f, TString *psource) { + /* + * Main protos have f->source naming the file used to create the hierarchy; + * subordinate protos set f->source != NULL to inherit this name from the + * parent. In LFS mode, the Protos are moved from the GC to a local list + * in S, but no error GC is attempted as discussed in LoadProtos. + */ + Proto *p; + global_State *g = G(S->L); + if (S->mode != MODE_RAM) { + lua_assert(g->allgc == obj2gco(f)); + g->allgc = f->next; /* remove object from 'allgc' list */ + f->next = S->protogc; /* push f into the head of the protogc list */ + S->protogc = obj2gco(f); + } + f->source = LoadString(S); + if (f->source == NULL) /* no source in dump? */ + f->source = psource; /* reuse parent's source */ + f->linedefined = LoadInt(S); + f->lastlinedefined = LoadInt(S); + f->numparams = LoadByte(S); + f->is_vararg = LoadByte(S); + f->maxstacksize = LoadByte(S); + LoadProtos(S, f); + LoadCode(S, f); + LoadConstants(S, f); + LoadUpvalues(S, f); + LoadDebug(S, f); + if (S->mode != MODE_RAM) { + GCObject *save = f->next; + if (f->source != NULL) { + setLFSbit(f); + /* cache the RAM next and set up the next for the LFS proto chain */ + f->next = FHaddr(S, GCObject *, S->fh->protoHead); + p = StoreR(S, NULL, 0, *f, FMT_PROTO); + S->fh->protoHead = FHoffset(S, p); + } else { + p = StoreR(S, NULL, 0, *f, FMT_PROTO); + } + S->protogc = save; /* pop f from the head of the protogc list */ + luaM_free(S->L, f); /* and collect the dead resource */ + f = p; + } + return f; +} +static void checkliteral (LoadState *S, const char *s, const char *msg) { + char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */ + size_t len = strlen(s); + LoadVector(S, buff, len); + if (memcmp(s, buff, len) != 0) + error(S, msg); +} +static void fchecksize (LoadState *S, size_t size, const char *tname) { + if (LoadByte(S) != size) + error(S, luaO_pushfstring(S->L, "%s size mismatch in", tname)); +} +#define checksize(S,t) fchecksize(S,sizeof(t),#t) +static void checkHeader (LoadState *S, int format) { + checkliteral(S, LUA_SIGNATURE + 1, "not a"); /* 1st char already checked */ + if (LoadByte(S) != LUAC_VERSION) + error(S, "version mismatch in"); + if (LoadByte(S) != format) + error(S, "format mismatch in"); + checkliteral(S, LUAC_DATA, "corrupted"); + checksize(S, int); + /* + * The standard Lua VM does a check on the sizeof size_t and endian check on + * integer; both are dropped as the former prevents dump files being shared + * across 32 and 64 bit machines, and we use multi-byte coding of ints. + */ + checksize(S, Instruction); + checksize(S, lua_Integer); + checksize(S, lua_Number); + LoadByte(S); /* skip number tt field */ + if (LoadNumber(S) != LUAC_NUM) + error(S, "float format mismatch in"); +} +/* +** Load precompiled chunk to support standard LUA_API load functions. The +** extra LFS functionality is effectively NO-OPed out on this MODE_RAM path. +*/ +LClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) { + LoadState S = {0}; + LClosure *cl; + if (*name == '@' || *name == '=') + S.name = name + 1; + else if (*name == LUA_SIGNATURE[0]) + S.name = "binary string"; + else + S.name = name; + S.L = L; + S.Z = Z; + S.mode = MODE_RAM; + S.fh = NULL; + S.useStrRefs = 0; + checkHeader(&S, LUAC_FORMAT); + cl = luaF_newLclosure(L, LoadByte(&S)); + setclLvalue(L, L->top, cl); + luaD_inctop(L); + cl->p = luaF_newproto(L); + LoadFunction(&S, cl->p, NULL); + lua_assert(cl->nupvalues == cl->p->sizeupvalues); + return cl; +} +/*============================================================================** +** NodeMCU extensions for LFS support and Loading. Note that this funtionality +** is called from a hook in the lua startup within a lua_lock() (as with +** LuaU_undump), so luaU_undumpLFS() cannot use the external Lua API. It does +** uses the Lua stack, but staying within LUA_MINSTACK limits. +** +** The in-RAM Protos used to assemble proto content prior to writing to LFS +** need special treatment since these hold LFS references rather than RAM ones +** and will cause the Lua GC to error if swept. Rather than adding complexity +** to lgc.c for this one-off process, these Protos are removed from the allgc +** list and fixed in a local one, and collected inline. +**============================================================================*/ +/* +** Write a TString to the LFS. This parallels the lstring.c algo but writes +** directly to the LFS buffer and also append the LFS address in S->TS. Seeding +** is based on the seed defined in the LFS image, rather than g->seed. +*/ +static void addTS(LoadState *S, int l, int extra) { + LFSHeader *fh = S->fh; + TString *ts = cast(TString *, S->buff); + char *s = getstr(ts); + lua_assert (sizelstring(l) <= S->buffLen); + s[l] = '\0'; + /* The collectable and LFS bits must be set; all others inc the whitebits clear */ + ts->marked = bitmask(LFSBIT) | BIT_ISCOLLECTABLE; + ts->extra = extra; + if (l <= LUAI_MAXSHORTLEN) { /* short string */ + TString **p; + ts->tt = LUA_TSHRSTR; + ts->shrlen = cast_byte(l); + ts->hash = luaS_hash(s, l, fh->seed); + p = S->list + lmod(ts->hash, S->listLen); + ts->u.hnext = *p; + ts->next = FHaddr(S, GCObject *, fh->shortTShead); + S->TS[S->TSndx] = *p = StoreR(S, NULL, 0, *ts, FMT_TSTRING); + fh->shortTShead = FHoffset(S, *p); + } else { /* long string */ + TString *p; + ts->tt = LUA_TLNGSTR; + ts->shrlen = 0; + ts->u.lnglen = l; + ts->hash = fh->seed; + luaS_hashlongstr(ts); /* sets hash and extra fields */ + ts->next = FHaddr(S, GCObject *, fh->longTShead); + S->TS[S->TSndx] = p = StoreR(S, NULL, 0, *ts, FMT_TSTRING); + fh->longTShead = FHoffset(S, p); + } +// printf("%04u(%u): %s\n", S->TSndx, l, S->buff + sizeof(union UTString)); + StoreN(S,S->buff + sizeof(union UTString), l+1); + S->TSndx++; +} +/* +** The runtime (in ltm.c and llex.c) declares ~100 fixed strings and so these +** are moved into LFS to free up an extra ~2Kb RAM. Extra get token access +** functions have been added to these modules. These tokens aren't unique as +** ("nil" and "function" are both tokens and typenames), hardwiring this +** duplication debounce as a wrapper around addTS() is the simplest way of +** voiding the need for extra lookup resources. +*/ +static void addTSnodup(LoadState *S, const char *s, int extra) { + int i, l = strlen(s); + static struct {const char *k; int found; } t[] = {{"nil", 0},{"function", 0}}; + for (i = 0; i < sizeof(t)/sizeof(*t); i++) { + if (!strcmp(t[i].k, s)) { + if (t[i].found) return; /* ignore the duplicate copy */ + t[i].found = 1; /* flag that this constant is already loaded */ + break; + } + } + memcpy(getstr(cast(TString *, S->buff)), s, l); + addTS(S, l, extra); +} +/* +** Load TStrings in dump format. ALl TStrings used in an LFS image excepting +** any fixed strings are dumped as a unique collated set. Any strings in the +** following Proto streams use an index reference into this list rather than an +** inline copy. This function loads and stores them into LFS, constructing the +** ROstrt for the shorter interned strings. +*/ +static void LoadAllStrings (LoadState *S) { + lua_State *L = S->L; + global_State *g = G(L); + int nb = sizelstring(LoadInt(S)); + int ns = LoadInt(S); + int nl = LoadInt(S); + int nstrings = LoadInt(S); + int n = ns + nl; + int nlist = 1<TS = luaM_newvector(L, n+1, TString *); + S->TSlen = n+1; + S->buff = luaM_newvector(L, nb, char); + S->buffLen = nb; + S->list = luaM_newvector(L, nlist, TString *); + S->listLen = nlist; + memset (S->list, 0, nlist*sizeof(TString *)); + /* add the strings in the image file to LFS */ + for (i = 1; i <= nstrings; i++) { + int tt = LoadByte(S); + lua_assert((tt&LUAU_TMASK)==LUAU_TSSTRING || (tt&LUAU_TMASK)==LUAU_TLSTRING); + int l = LoadInteger(S, tt) - 1; /* No NULL entry in list of TSs */ + LoadVector(S, getstr(cast(TString *, S->buff)), l); + addTS(S, l, 0); + } + /* add the fixed strings to LFS */ + for (i = 0; (p = luaX_getstr(i, &extra))!=NULL; i++) { + addTSnodup(S, p, extra); + } + addTSnodup(S, getstr(g->memerrmsg), 0); + addTSnodup(S, LUA_ENV, 0); + for (i = 0; (p = luaT_getstr(i))!=NULL; i++) { + addTSnodup(S, p, 0); + } + /* check that the actual size is the same as the predicted */ + lua_assert(n == S->TSndx-1); + S->fh->oROhash = FHoffset(S, StoreAV(S, S->list, nlist)); + S->fh->nROuse = ns; + S->fh->nROsize = nlist; + StoreFlush(S); + S->buff = luaM_freearray(L, S->buff, nb); + S->buffLen = 0; + S->list = luaM_freearray(L, S->list, nlist); + S->listLen = 0; +} +static void LoadAllProtos (LoadState *S) { + lua_State *L = S->L; + ROTable_entry eol = {NULL, LRO_NILVAL}; + int i, n = LoadInt(S); + S->pv = luaM_newvector(L, n, Proto *); + S->pvLen = n; + /* Load Protos and store addresses in the Proto vector */ + for (i = 0; i < n; i++) { + S->pv[i] = LoadFunction(S, luaF_newproto(L), NULL); + } + /* generate the ROTable entries from first N constants; the last is a timestamp */ + lua_assert(n+1 == LoadInt(S)); + ROTable_entry *entry_list = cast(ROTable_entry *, StoreGetPos(S)); + for (i = 0; i < n; i++) { + lu_byte tt_data = LoadByte(S); + TString *Tname = LoadString2(S, tt_data); + const char *name = getstr(Tname) + OFFSET_TSTRING; + lua_assert((tt_data & LUAU_TMASK) == LUAU_TSSTRING); + ROTable_entry me = {name, LRO_LUDATA(S->pv[i])}; + StoreR(S, NULL, 0, me, FMT_ROTENTRY); + } + StoreR(S, NULL, 0, eol, FMT_ROTENTRY); + /* terminate the ROTable entry list and store the ROTable header */ + ROTable ev = { (GCObject *)1, LUA_TTBLROF, LROT_MARKED, + (lu_byte) ~0, n, NULL, entry_list}; + S->fh->protoROTable = FHoffset(S, StoreR(S, NULL, 0, ev, FMT_ROTABLE)); + /* last const is timestamp */ + S->fh->timestamp = LoadInteger(S, LoadByte(S)); +} +static void undumpLFS(lua_State *L, void *ud) { + LoadState *S = cast(LoadState *, ud); + void *F = S->Z->data; + S->startLFS = StoreGetPos(S); + luaN_setFlash(F, sizeof(LFSHeader)); + S->fh->flash_sig = FLASH_SIG; + if (LoadByte(S) != LUA_SIGNATURE[0]) + error(S, "invalid header in"); + checkHeader(S, LUAC_LFS_IMAGE_FORMAT); + S->fh->seed = LoadInteger(S, LoadByte(S)); + checkliteral(S, LUA_STRING_SIG,"no string vector"); + LoadAllStrings (S); + checkliteral(S, LUA_PROTO_SIG,"no Proto vector"); + LoadAllProtos(S); + S->fh->flash_size = byteptr(StoreGetPos(S)) - byteptr(S->startLFS); + luaN_setFlash(F, 0); + StoreN(S, S->fh, 1); + luaN_setFlash(F, 0); + S->TS = luaM_freearray(L, S->TS, S->TSlen); +} +/* +** Load precompiled LFS image. This is called from a hook in the firmware +** startup if LFS reload is required. +*/ +LUAI_FUNC int luaU_undumpLFS(lua_State *L, ZIO *Z, int isabs) { + LFSHeader fh = {0}; + LoadState S = {0}; + int status; + S.L = L; + S.Z = Z; + S.mode = isabs && sizeof(size_t) != sizeof(lu_int32) ? MODE_LFSA : MODE_LFS; + S.useStrRefs = 1; + S.fh = &fh; + L->nny++; /* do not yield during undump LFS */ + status = luaD_pcall(L, undumpLFS, &S, savestack(L, L->top), L->errfunc); + luaM_freearray(L, S.TS, S.TSlen); + luaM_freearray(L, S.buff, S.buffLen); + luaM_freearray(L, S.list, S.listLen); + luaM_freearray(L, S.pv, S.pvLen); + L->nny--; + return status; +} diff --git a/components/lua/lua-5.3/lundump.h b/components/lua/lua-5.3/lundump.h new file mode 100644 index 00000000..26eff4fe --- /dev/null +++ b/components/lua/lua-5.3/lundump.h @@ -0,0 +1,94 @@ +/* +** $Id: lundump.h,v 1.45.1.1 2017/04/19 17:20:42 roberto Exp $ +** load precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#ifndef lundump_h +#define lundump_h + +#include "llimits.h" +#include "lobject.h" +#include "lzio.h" + +/* These allow a multi=byte flag:1,type:3,data:4 packing in the tt byte */ +#define LUAU_TNIL (0<<4) +#define LUAU_TBOOLEAN (1<<4) +#define LUAU_TNUMFLT (2<<4) +#define LUAU_TNUMPINT (3<<4) +#define LUAU_TNUMNINT (4<<4) +#define LUAU_TSSTRING (5<<4) +#define LUAU_TLSTRING (6<<4) +#define LUAU_TMASK (7<<4) +#define LUAU_DMASK 0x0f + + +/* data to catch conversion errors */ +#define LUAC_DATA "\x19\x93\r\n\x1a\n" + +#define LUAC_INT 0x5678 +#define LUAC_NUM cast_num(370.5) +#define LUAC_FUNC_MARKER 0xFE +#define LUA_TNUMNINT (LUA_TNUMBER | (2 << 4)) /* negative integer numbers */ + +#define MYINT(s) (s[0]-'0') +#define LUAC_VERSION (MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR)) +#define LUAC_FORMAT 10 /* this is the NodeMCU format */ +#define LUAC_LFS_IMAGE_FORMAT 11 +#define LUA_STRING_SIG "\x19ss" +#define LUA_PROTO_SIG "\x19pr" +#define LUA_HDR_BYTE '\x19' +/* load one chunk; from lundump.c */ +LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, const char* name); + +/* dump one chunk; from ldump.c */ +LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, + void* data, int strip); +LUAI_FUNC int luaU_DumpAllProtos(lua_State *L, const Proto *m, lua_Writer w, + void *data, int strip); + +LUAI_FUNC int luaU_undumpLFS(lua_State *L, ZIO *Z, int isabs); +LUAI_FUNC int luaU_stripdebug (lua_State *L, Proto *f, int level, int recv); + +typedef struct FlashHeader LFSHeader; +/* +** The LFSHeader uses offsets rather than pointers to avoid 32 vs 64 bit issues +** during host compilation. The offsets are in units of lu_int32's and NOT +** size_t, though clearly any internal pointers are of the size_t for the +** executing architectures: 4 or 8 byte. Likewise recources are size_t aligned +** so LFS regions built for 64-bit execution will have 4-byte alignment packing +** between resources. +*/ +struct FlashHeader{ + lu_int32 flash_sig; /* a standard fingerprint identifying an LFS image */ + lu_int32 flash_size; /* Size of LFS image in bytes */ + lu_int32 seed; /* random number seed used in LFS */ + lu_int32 timestamp; /* timestamp of LFS build */ + lu_int32 nROuse; /* number of elements in ROstrt */ + lu_int32 nROsize; /* size of ROstrt */ + lu_int32 oROhash; /* offset of TString ** ROstrt hash */ + lu_int32 protoROTable; /* offset of master ROTable for proto lookup */ + lu_int32 protoHead; /* offset of linked list of Protos in LFS */ + lu_int32 shortTShead; /* offset of linked list of short TStrings in LFS */ + lu_int32 longTShead; /* offset of linked list of long TStrings in LFS */ + lu_int32 reserved; +}; + +#ifdef LUA_USE_HOST +extern void *LFSregion; +LUAI_FUNC void luaN_setabsolute(lu_int32 addr); +#endif + +#define FLASH_FORMAT_VERSION ( 2 << 8) +#define FLASH_SIG_B1 0x06 +#define FLASH_SIG_B2 0x02 +#define FLASH_SIG_PASS2 0x0F +#define FLASH_FORMAT_MASK 0xF00 +#define FLASH_SIG_B2_MASK 0x04 +#define FLASH_SIG_ABSOLUTE 0x01 +#define FLASH_SIG_IN_PROGRESS 0x08 +#define FLASH_SIG (0xfafaa050 | FLASH_FORMAT_VERSION) + +#define FLASH_FORMAT_MASK 0xF00 + +#endif diff --git a/components/lua/lua-5.3/lutf8lib.c b/components/lua/lua-5.3/lutf8lib.c new file mode 100644 index 00000000..4fff0f2d --- /dev/null +++ b/components/lua/lua-5.3/lutf8lib.c @@ -0,0 +1,264 @@ +/* +** $Id: lutf8lib.c,v 1.16.1.1 2017/04/19 17:29:57 roberto Exp $ +** Standard library for UTF-8 manipulation +** See Copyright Notice in lua.h +*/ + +#define lutf8lib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + +#define MAXUNICODE 0x10FFFF + +#define iscont(p) ((*(p) & 0xC0) == 0x80) + + +/* from strlib */ +/* translate a relative string position: negative means back from end */ +static lua_Integer u_posrelat (lua_Integer pos, size_t len) { + if (pos >= 0) return pos; + else if (0u - (size_t)pos > len) return 0; + else return (lua_Integer)len + pos + 1; +} + + +/* +** Decode one UTF-8 sequence, returning NULL if byte sequence is invalid. +*/ +static const char *utf8_decode (const char *o, int *val) { + static const unsigned int limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFF}; + const unsigned char *s = (const unsigned char *)o; + unsigned int c = s[0]; + unsigned int res = 0; /* final result */ + if (c < 0x80) /* ascii? */ + res = c; + else { + int count = 0; /* to count number of continuation bytes */ + while (c & 0x40) { /* still have continuation bytes? */ + int cc = s[++count]; /* read next byte */ + if ((cc & 0xC0) != 0x80) /* not a continuation byte? */ + return NULL; /* invalid byte sequence */ + res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */ + c <<= 1; /* to test next bit */ + } + res |= ((c & 0x7F) << (count * 5)); /* add first byte */ + if (count > 3 || res > MAXUNICODE || res <= limits[count]) + return NULL; /* invalid byte sequence */ + s += count; /* skip continuation bytes read */ + } + if (val) *val = res; + return (const char *)s + 1; /* +1 to include first byte */ +} + + +/* +** utf8len(s [, i [, j]]) --> number of characters that start in the +** range [i,j], or nil + current position if 's' is not well formed in +** that interval +*/ +static int utflen (lua_State *L) { + int n = 0; + size_t len; + const char *s = luaL_checklstring(L, 1, &len); + lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len); + lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len); + luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2, + "initial position out of string"); + luaL_argcheck(L, --posj < (lua_Integer)len, 3, + "final position out of string"); + while (posi <= posj) { + const char *s1 = utf8_decode(s + posi, NULL); + if (s1 == NULL) { /* conversion error? */ + lua_pushnil(L); /* return nil ... */ + lua_pushinteger(L, posi + 1); /* ... and current position */ + return 2; + } + posi = s1 - s; + n++; + } + lua_pushinteger(L, n); + return 1; +} + + +/* +** codepoint(s, [i, [j]]) -> returns codepoints for all characters +** that start in the range [i,j] +*/ +static int codepoint (lua_State *L) { + size_t len; + const char *s = luaL_checklstring(L, 1, &len); + lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len); + lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len); + int n; + const char *se; + luaL_argcheck(L, posi >= 1, 2, "out of range"); + luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of range"); + if (posi > pose) return 0; /* empty interval; return no values */ + if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */ + return luaL_error(L, "string slice too long"); + n = (int)(pose - posi) + 1; + luaL_checkstack(L, n, "string slice too long"); + n = 0; + se = s + pose; + for (s += posi - 1; s < se;) { + int code; + s = utf8_decode(s, &code); + if (s == NULL) + return luaL_error(L, "invalid UTF-8 code"); + lua_pushinteger(L, code); + n++; + } + return n; +} + + +static void pushutfchar (lua_State *L, int arg) { + lua_Integer code = luaL_checkinteger(L, arg); + luaL_argcheck(L, 0 <= code && code <= MAXUNICODE, arg, "value out of range"); + lua_pushfstring(L, "%U", (long)code); +} + + +/* +** utfchar(n1, n2, ...) -> char(n1)..char(n2)... +*/ +static int utfchar (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + if (n == 1) /* optimize common case of single char */ + pushutfchar(L, 1); + else { + int i; + luaL_Buffer b; + luaL_buffinit(L, &b); + for (i = 1; i <= n; i++) { + pushutfchar(L, i); + luaL_addvalue(&b); + } + luaL_pushresult(&b); + } + return 1; +} + + +/* +** offset(s, n, [i]) -> index where n-th character counting from +** position 'i' starts; 0 means character at 'i'. +*/ +static int byteoffset (lua_State *L) { + size_t len; + const char *s = luaL_checklstring(L, 1, &len); + lua_Integer n = luaL_checkinteger(L, 2); + lua_Integer posi = (n >= 0) ? 1 : len + 1; + posi = u_posrelat(luaL_optinteger(L, 3, posi), len); + luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3, + "position out of range"); + if (n == 0) { + /* find beginning of current byte sequence */ + while (posi > 0 && iscont(s + posi)) posi--; + } + else { + if (iscont(s + posi)) + return luaL_error(L, "initial position is a continuation byte"); + if (n < 0) { + while (n < 0 && posi > 0) { /* move back */ + do { /* find beginning of previous character */ + posi--; + } while (posi > 0 && iscont(s + posi)); + n++; + } + } + else { + n--; /* do not move for 1st character */ + while (n > 0 && posi < (lua_Integer)len) { + do { /* find beginning of next character */ + posi++; + } while (iscont(s + posi)); /* (cannot pass final '\0') */ + n--; + } + } + } + if (n == 0) /* did it find given character? */ + lua_pushinteger(L, posi + 1); + else /* no such character */ + lua_pushnil(L); + return 1; +} + + +static int iter_aux (lua_State *L) { + size_t len; + const char *s = luaL_checklstring(L, 1, &len); + lua_Integer n = lua_tointeger(L, 2) - 1; + if (n < 0) /* first iteration? */ + n = 0; /* start from here */ + else if (n < (lua_Integer)len) { + n++; /* skip current byte */ + while (iscont(s + n)) n++; /* and its continuations */ + } + if (n >= (lua_Integer)len) + return 0; /* no more codepoints */ + else { + int code; + const char *next = utf8_decode(s + n, &code); + if (next == NULL || iscont(next)) + return luaL_error(L, "invalid UTF-8 code"); + lua_pushinteger(L, n + 1); + lua_pushinteger(L, code); + return 2; + } +} + + +static int iter_codes (lua_State *L) { + luaL_checkstring(L, 1); + lua_pushcfunction(L, iter_aux); + lua_pushvalue(L, 1); + lua_pushinteger(L, 0); + return 3; +} + + +/* pattern to match a single UTF-8 character */ + +#define UTF8PATT "[\0-\x7F\xC2-\xF4][\x80-\xBF]*" +static int utf8_lookup (lua_State *L) { + const char *key = lua_tostring(L,2); + if (strcmp(key,"charpattern")) + lua_pushnil(L); + else + lua_pushlstring(L, UTF8PATT, sizeof(UTF8PATT)/sizeof(char) - 1); + return 1; +} + +LROT_BEGIN(utf8_meta, NULL, LROT_MASK_INDEX) + LROT_FUNCENTRY( __index, utf8_lookup ) +LROT_END(utf8_meta, NULL, LROT_MASK_INDEX) + + +LROT_BEGIN(utf8, LROT_TABLEREF(utf8_meta), 0) + LROT_FUNCENTRY( offset, byteoffset ) + LROT_FUNCENTRY( codepoint, codepoint ) + LROT_FUNCENTRY( char, utfchar ) + LROT_FUNCENTRY( len, utflen ) + LROT_FUNCENTRY( codes, iter_codes ) +LROT_END(utf8, LROT_TABLEREF(utf8_meta), 0) + + +LUAMOD_API int luaopen_utf8 (lua_State *L) { + (void)L; + return 0; +} + diff --git a/components/lua/lua-5.3/lvm.c b/components/lua/lua-5.3/lvm.c new file mode 100644 index 00000000..c186e5e7 --- /dev/null +++ b/components/lua/lua-5.3/lvm.c @@ -0,0 +1,1286 @@ +/* +** $Id: lvm.c,v 2.268.1.1 2017/04/19 17:39:34 roberto Exp $ +** Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#define lvm_c +#define LUA_CORE + +#include "lprefix.h" + +#include +#include +#include +#include +#include +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lvm.h" + + +/* limit for table tag-method chains (to avoid loops) */ +#define MAXTAGLOOP 2000 + + + +/* +** 'l_intfitsf' checks whether a given integer can be converted to a +** float without rounding. Used in comparisons. Left undefined if +** all integers fit in a float precisely. +*/ +#if !defined(l_intfitsf) + +/* number of bits in the mantissa of a float */ +#define NBM (l_mathlim(MANT_DIG)) + +/* +** Check whether some integers may not fit in a float, that is, whether +** (maxinteger >> NBM) > 0 (that implies (1 << NBM) <= maxinteger). +** (The shifts are done in parts to avoid shifting by more than the size +** of an integer. In a worst case, NBM == 113 for long double and +** sizeof(integer) == 32.) +*/ +#if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \ + >> (NBM - (3 * (NBM / 4)))) > 0 + +#define l_intfitsf(i) \ + (-((lua_Integer)1 << NBM) <= (i) && (i) <= ((lua_Integer)1 << NBM)) + +#endif + +#endif + + + +/* +** Try to convert a value to a float. The float case is already handled +** by the macro 'tonumber'. +*/ +int luaV_tonumber_ (const TValue *obj, lua_Number *n) { + TValue v; + if (ttisinteger(obj)) { + *n = cast_num(ivalue(obj)); + return 1; + } + else if (cvt2num(obj) && /* string convertible to number? */ + luaO_str2num(svalue(obj), &v) == vslen(obj) + 1) { + *n = nvalue(&v); /* convert result of 'luaO_str2num' to a float */ + return 1; + } + else + return 0; /* conversion failed */ +} + + +/* +** try to convert a value to an integer, rounding according to 'mode': +** mode == 0: accepts only integral values +** mode == 1: takes the floor of the number +** mode == 2: takes the ceil of the number +*/ +int luaV_tointeger (const TValue *obj, lua_Integer *p, int mode) { + TValue v; + again: + if (ttisfloat(obj)) { + lua_Number n = fltvalue(obj); + lua_Number f = l_floor(n); + if (n != f) { /* not an integral value? */ + if (mode == 0) return 0; /* fails if mode demands integral value */ + else if (mode > 1) /* needs ceil? */ + f += 1; /* convert floor to ceil (remember: n != f) */ + } + return lua_numbertointeger(f, p); + } + else if (ttisinteger(obj)) { + *p = ivalue(obj); + return 1; + } + else if (cvt2num(obj) && + luaO_str2num(svalue(obj), &v) == vslen(obj) + 1) { + obj = &v; + goto again; /* convert result from 'luaO_str2num' to an integer */ + } + return 0; /* conversion failed */ +} + + +/* +** Try to convert a 'for' limit to an integer, preserving the +** semantics of the loop. +** (The following explanation assumes a non-negative step; it is valid +** for negative steps mutatis mutandis.) +** If the limit can be converted to an integer, rounding down, that is +** it. +** Otherwise, check whether the limit can be converted to a number. If +** the number is too large, it is OK to set the limit as LUA_MAXINTEGER, +** which means no limit. If the number is too negative, the loop +** should not run, because any initial integer value is larger than the +** limit. So, it sets the limit to LUA_MININTEGER. 'stopnow' corrects +** the extreme case when the initial value is LUA_MININTEGER, in which +** case the LUA_MININTEGER limit would still run the loop once. +*/ +static int forlimit (const TValue *obj, lua_Integer *p, lua_Integer step, + int *stopnow) { + *stopnow = 0; /* usually, let loops run */ + if (!luaV_tointeger(obj, p, (step < 0 ? 2 : 1))) { /* not fit in integer? */ + lua_Number n; /* try to convert to float */ + if (!tonumber(obj, &n)) /* cannot convert to float? */ + return 0; /* not a number */ + if (luai_numlt(0, n)) { /* if true, float is larger than max integer */ + *p = LUA_MAXINTEGER; + if (step < 0) *stopnow = 1; + } + else { /* float is smaller than min integer */ + *p = LUA_MININTEGER; + if (step >= 0) *stopnow = 1; + } + } + return 1; +} + + +/* +** Finish the table access 'val = t[key]'. +** if 'slot' is NULL, 't' is not a table; otherwise, 'slot' points to +** t[k] entry (which must be nil). +*/ +void luaV_finishget (lua_State *L, const TValue *t, TValue *key, StkId val, + const TValue *slot) { + int loop; /* counter to avoid infinite loops */ + const TValue *tm; /* metamethod */ + for (loop = 0; loop < MAXTAGLOOP; loop++) { + if (slot == NULL) { /* 't' is not a table? */ + lua_assert(!ttistable(t)); + tm = luaT_gettmbyobj(L, t, TM_INDEX); + if (ttisnil(tm)) + luaG_typeerror(L, t, "index"); /* no metamethod */ + /* else will try the metamethod */ + } + else { /* 't' is a table */ + lua_assert(ttisnil(slot)); + tm = fasttm(L, hvalue(t)->metatable, TM_INDEX); /* table's metamethod */ + if (tm == NULL) { /* no metamethod? */ + setnilvalue(val); /* result is nil */ + return; + } + /* else will try the metamethod */ + } + if (ttisfunction(tm)) { /* is metamethod a function? */ + luaT_callTM(L, tm, t, key, val, 1); /* call it */ + return; + } + t = tm; /* else try to access 'tm[key]' */ + if (luaV_fastget(L,t,key,slot,luaH_get)) { /* fast track? */ + setobj2s(L, val, slot); /* done */ + return; + } + /* else repeat (tail call 'luaV_finishget') */ + } + luaG_runerror(L, "'__index' chain too long; possible loop"); +} + + +/* +** Finish a table assignment 't[key] = val'. +** If 'slot' is NULL, 't' is not a table. Otherwise, 'slot' points +** to the entry 't[key]', or to 'luaO_nilobject' if there is no such +** entry. (The value at 'slot' must be nil, otherwise 'luaV_fastset' +** would have done the job.) +*/ +void luaV_finishset (lua_State *L, const TValue *t, TValue *key, + StkId val, const TValue *slot) { + int loop; /* counter to avoid infinite loops */ + for (loop = 0; loop < MAXTAGLOOP; loop++) { + const TValue *tm; /* '__newindex' metamethod */ + if (slot != NULL) { /* is 't' a table? */ + Table *h = hvalue(t); /* save 't' table */ + lua_assert(ttisnil(slot)); /* old value must be nil */ + tm = fasttm(L, h->metatable, TM_NEWINDEX); /* get metamethod */ + if (tm == NULL) { /* no metamethod? */ + if (slot == luaO_nilobject) /* no previous entry? */ + slot = luaH_newkey(L, h, key); /* create one */ + /* no metamethod and (now) there is an entry with given key */ + setobj2t(L, cast(TValue *, slot), val); /* set its new value */ + invalidateTMcache(h); + luaC_barrierback(L, h, val); + return; + } + /* else will try the metamethod */ + } + else { /* not a table; check metamethod */ + if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) + luaG_typeerror(L, t, "index"); + } + /* try the metamethod */ + if (ttisfunction(tm)) { + luaT_callTM(L, tm, t, key, val, 0); + return; + } + t = tm; /* else repeat assignment over 'tm' */ + if (luaV_fastset(L, t, key, slot, luaH_get, val)) + return; /* done */ + /* else loop */ + } + luaG_runerror(L, "'__newindex' chain too long; possible loop"); +} + + +/* +** Compare two strings 'ls' x 'rs', returning an integer smaller-equal- +** -larger than zero if 'ls' is smaller-equal-larger than 'rs'. +** Stripped down version for NodeMCU without locales support +*/ +static int l_strcmp (const TString *ls, const TString *rs) { + const char *l = getstr(ls); + const char *r = getstr(rs); + if (l == r) { + return 0; + } else { + size_t ll = tsslen(ls); + size_t lr = tsslen(rs); + size_t lm = ll= -cast_num(LUA_MININTEGER)) /* -minint == maxint + 1 */ + return 1; /* f >= maxint + 1 > i */ + else if (f > cast_num(LUA_MININTEGER)) /* minint < f <= maxint ? */ + return (i < cast(lua_Integer, f)); /* compare them as integers */ + else /* f <= minint <= i (or 'f' is NaN) --> not(i < f) */ + return 0; + } +#endif + return luai_numlt(cast_num(i), f); /* compare them as floats */ +} + + +/* +** Check whether integer 'i' is less than or equal to float 'f'. +** See comments on previous function. +*/ +static int LEintfloat (lua_Integer i, lua_Number f) { +#if defined(l_intfitsf) + if (!l_intfitsf(i)) { + if (f >= -cast_num(LUA_MININTEGER)) /* -minint == maxint + 1 */ + return 1; /* f >= maxint + 1 > i */ + else if (f >= cast_num(LUA_MININTEGER)) /* minint <= f <= maxint ? */ + return (i <= cast(lua_Integer, f)); /* compare them as integers */ + else /* f < minint <= i (or 'f' is NaN) --> not(i <= f) */ + return 0; + } +#endif + return luai_numle(cast_num(i), f); /* compare them as floats */ +} + + +/* +** Return 'l < r', for numbers. +*/ +static int LTnum (const TValue *l, const TValue *r) { + if (ttisinteger(l)) { + lua_Integer li = ivalue(l); + if (ttisinteger(r)) + return li < ivalue(r); /* both are integers */ + else /* 'l' is int and 'r' is float */ + return LTintfloat(li, fltvalue(r)); /* l < r ? */ + } + else { + lua_Number lf = fltvalue(l); /* 'l' must be float */ + if (ttisfloat(r)) + return luai_numlt(lf, fltvalue(r)); /* both are float */ + else if (luai_numisnan(lf)) /* 'r' is int and 'l' is float */ + return 0; /* NaN < i is always false */ + else /* without NaN, (l < r) <--> not(r <= l) */ + return !LEintfloat(ivalue(r), lf); /* not (r <= l) ? */ + } +} + + +/* +** Return 'l <= r', for numbers. +*/ +static int LEnum (const TValue *l, const TValue *r) { + if (ttisinteger(l)) { + lua_Integer li = ivalue(l); + if (ttisinteger(r)) + return li <= ivalue(r); /* both are integers */ + else /* 'l' is int and 'r' is float */ + return LEintfloat(li, fltvalue(r)); /* l <= r ? */ + } + else { + lua_Number lf = fltvalue(l); /* 'l' must be float */ + if (ttisfloat(r)) + return luai_numle(lf, fltvalue(r)); /* both are float */ + else if (luai_numisnan(lf)) /* 'r' is int and 'l' is float */ + return 0; /* NaN <= i is always false */ + else /* without NaN, (l <= r) <--> not(r < l) */ + return !LTintfloat(ivalue(r), lf); /* not (r < l) ? */ + } +} + + +/* +** Main operation less than; return 'l < r'. +*/ +int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { + int res; + if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */ + return LTnum(l, r); + else if (ttisstring(l) && ttisstring(r)) /* both are strings? */ + return l_strcmp(tsvalue(l), tsvalue(r)) < 0; + else if ((res = luaT_callorderTM(L, l, r, TM_LT)) < 0) /* no metamethod? */ + luaG_ordererror(L, l, r); /* error */ + return res; +} + + +/* +** Main operation less than or equal to; return 'l <= r'. If it needs +** a metamethod and there is no '__le', try '__lt', based on +** l <= r iff !(r < l) (assuming a total order). If the metamethod +** yields during this substitution, the continuation has to know +** about it (to negate the result of r= 0) /* try 'le' */ + return res; + else { /* try 'lt': */ + L->ci->callstatus |= CIST_LEQ; /* mark it is doing 'lt' for 'le' */ + res = luaT_callorderTM(L, r, l, TM_LT); + L->ci->callstatus ^= CIST_LEQ; /* clear mark */ + if (res < 0) + luaG_ordererror(L, l, r); + return !res; /* result is negated */ + } +} + + +/* +** Main operation for equality of Lua values; return 't1 == t2'. +** L == NULL means raw equality (no metamethods) +*/ +int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) { + const TValue *tm; + if (ttype(t1) != ttype(t2)) { /* not the same variant? */ + if (ttnov(t1) != ttnov(t2) || ttnov(t1) != LUA_TNUMBER) + return 0; /* only numbers can be equal with different variants */ + else { /* two numbers with different variants */ + lua_Integer i1, i2; /* compare them as integers */ + return (tointeger(t1, &i1) && tointeger(t2, &i2) && i1 == i2); + } + } + /* values have same type and same variant */ + switch (ttype(t1)) { + case LUA_TNIL: return 1; + case LUA_TNUMINT: return (ivalue(t1) == ivalue(t2)); + case LUA_TNUMFLT: return luai_numeq(fltvalue(t1), fltvalue(t2)); + case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */ + case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); + case LUA_TLCF: return fvalue(t1) == fvalue(t2); + case LUA_TSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2)); + case LUA_TLNGSTR: return luaS_eqlngstr(tsvalue(t1), tsvalue(t2)); + case LUA_TUSERDATA: { + if (uvalue(t1) == uvalue(t2)) return 1; + else if (L == NULL) return 0; + tm = fasttm(L, uvalue(t1)->metatable, TM_EQ); + if (tm == NULL) + tm = fasttm(L, uvalue(t2)->metatable, TM_EQ); + break; /* will try TM */ + } + case LUA_TTBLRAM: + case LUA_TTBLROF: { + if (hvalue(t1) == hvalue(t2)) return 1; + else if (L == NULL) return 0; + tm = fasttm(L, hvalue(t1)->metatable, TM_EQ); + if (tm == NULL) + tm = fasttm(L, hvalue(t2)->metatable, TM_EQ); + break; /* will try TM */ + } + default: + return gcvalue(t1) == gcvalue(t2); + } + if (tm == NULL) /* no TM? */ + return 0; /* objects are different */ + luaT_callTM(L, tm, t1, t2, L->top, 1); /* call TM */ + return !l_isfalse(L->top); +} + + +/* macro used by 'luaV_concat' to ensure that element at 'o' is a string */ +#define tostring(L,o) \ + (ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1))) + +#define isemptystr(o) (ttisshrstring(o) && getshrlen(tsvalue(o)) == 0) + +/* copy strings in stack from top - n up to top - 1 to buffer */ +static void copy2buff (StkId top, int n, char *buff) { + size_t tl = 0; /* size already copied */ + do { + size_t l = vslen(top - n); /* length of string being copied */ + memcpy(buff + tl, svalue(top - n), l * sizeof(char)); + tl += l; + } while (--n > 0); +} + + +/* +** Main operation for concatenation: concat 'total' values in the stack, +** from 'L->top - total' up to 'L->top - 1'. +*/ +void luaV_concat (lua_State *L, int total) { + lua_assert(total >= 2); + do { + StkId top = L->top; + int n = 2; /* number of elements handled in this pass (at least 2) */ + if (!(ttisstring(top-2) || cvt2str(top-2)) || !tostring(L, top-1)) + luaT_trybinTM(L, top-2, top-1, top-2, TM_CONCAT); + else if (isemptystr(top - 1)) /* second operand is empty? */ + cast_void(tostring(L, top - 2)); /* result is first operand */ + else if (isemptystr(top - 2)) { /* first operand is an empty string? */ + setobjs2s(L, top - 2, top - 1); /* result is second op. */ + } + else { + /* at least two non-empty string values; get as many as possible */ + size_t tl = vslen(top - 1); + TString *ts; + /* collect total length and number of strings */ + for (n = 1; n < total && tostring(L, top - n - 1); n++) { + size_t l = vslen(top - n - 1); + if (l >= (MAX_SIZE/sizeof(char)) - tl) + luaG_runerror(L, "string length overflow"); + tl += l; + } + if (tl <= LUAI_MAXSHORTLEN) { /* is result a short string? */ + char buff[LUAI_MAXSHORTLEN]; + copy2buff(top, n, buff); /* copy strings to buffer */ + ts = luaS_newlstr(L, buff, tl); + } + else { /* long string; copy strings directly to final result */ + ts = luaS_createlngstrobj(L, tl); + copy2buff(top, n, getstr(ts)); + } + setsvalue2s(L, top - n, ts); /* create result */ + } + total -= n-1; /* got 'n' strings to create 1 new */ + L->top -= n-1; /* popped 'n' strings and pushed one */ + } while (total > 1); /* repeat until only 1 result left */ +} + + +/* +** Main operation 'ra' = #rb'. +*/ +void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) { + const TValue *tm; + switch (ttype(rb)) { + case LUA_TTABLE: { + Table *h = hvalue(rb); + tm = fasttm(L, h->metatable, TM_LEN); + if (tm) break; /* metamethod? break switch to call it */ + setivalue(ra, luaH_getn(h)); /* else primitive len */ + return; + } + case LUA_TSHRSTR: { + setivalue(ra, getshrlen(tsvalue(rb))); + return; + } + case LUA_TLNGSTR: { + setivalue(ra, tsvalue(rb)->u.lnglen); + return; + } + default: { /* try metamethod */ + tm = luaT_gettmbyobj(L, rb, TM_LEN); + if (ttisnil(tm)) /* no metamethod? */ + luaG_typeerror(L, rb, "get length of"); + break; + } + } + luaT_callTM(L, tm, rb, rb, ra, 1); +} + + +/* +** Integer division; return 'm // n', that is, floor(m/n). +** C division truncates its result (rounds towards zero). +** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer, +** otherwise 'floor(q) == trunc(q) - 1'. +*/ +lua_Integer luaV_div (lua_State *L, lua_Integer m, lua_Integer n) { + if (l_castS2U(n) + 1u <= 1u) { /* special cases: -1 or 0 */ + if (n == 0) + luaG_runerror(L, "attempt to divide by zero"); + return intop(-, 0, m); /* n==-1; avoid overflow with 0x80000...//-1 */ + } + else { + lua_Integer q = m / n; /* perform C division */ + if ((m ^ n) < 0 && m % n != 0) /* 'm/n' would be negative non-integer? */ + q -= 1; /* correct result for different rounding */ + return q; + } +} + + +/* +** Integer modulus; return 'm % n'. (Assume that C '%' with +** negative operands follows C99 behavior. See previous comment +** about luaV_div.) +*/ +lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) { + if (l_castS2U(n) + 1u <= 1u) { /* special cases: -1 or 0 */ + if (n == 0) + luaG_runerror(L, "attempt to perform 'n%%0'"); + return 0; /* m % -1 == 0; avoid overflow with 0x80000...%-1 */ + } + else { + lua_Integer r = m % n; + if (r != 0 && (m ^ n) < 0) /* 'm/n' would be non-integer negative? */ + r += n; /* correct result for different rounding */ + return r; + } +} + + +/* number of bits in an integer */ +#define NBITS cast_int(sizeof(lua_Integer) * CHAR_BIT) + +/* +** Shift left operation. (Shift right just negates 'y'.) +*/ +lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) { + if (y < 0) { /* shift right? */ + if (y <= -NBITS) return 0; + else return intop(>>, x, -y); + } + else { /* shift left */ + if (y >= NBITS) return 0; + else return intop(<<, x, y); + } +} + + +/* +** create a new Lua closure, push it in the stack, and initialize +** its upvalues. Note that the closure is not cached if prototype is +** already black (which means that 'cache' was already cleared by the +** GC). +*/ +static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base, + StkId ra) { + int nup = p->sizeupvalues; + Upvaldesc *uv = p->upvalues; + int i; + LClosure *ncl = luaF_newLclosure(L, nup); + ncl->p = p; + setclLvalue(L, ra, ncl); /* anchor new closure in stack */ + for (i = 0; i < nup; i++) { /* fill in its upvalues */ + if (uv[i].instack) /* upvalue refers to local variable? */ + ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx); + else /* get upvalue from enclosing function */ + ncl->upvals[i] = encup[uv[i].idx]; + ncl->upvals[i]->refcount++; + /* new closure is white, so we do not need a barrier here */ + } +} + + +/* +** finish execution of an opcode interrupted by an yield +*/ +void luaV_finishOp (lua_State *L) { + CallInfo *ci = L->ci; + StkId base = ci->u.l.base; + Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */ + OpCode op = GET_OPCODE(inst); + switch (op) { /* finish its execution */ + case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_IDIV: + case OP_BAND: case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: + case OP_MOD: case OP_POW: + case OP_UNM: case OP_BNOT: case OP_LEN: + case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: { + setobjs2s(L, base + GETARG_A(inst), --L->top); + break; + } + case OP_LE: case OP_LT: case OP_EQ: { + int res = !l_isfalse(L->top - 1); + L->top--; + if (ci->callstatus & CIST_LEQ) { /* "<=" using "<" instead? */ + lua_assert(op == OP_LE); + ci->callstatus ^= CIST_LEQ; /* clear mark */ + res = !res; /* negate result */ + } + lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP); + if (res != GETARG_A(inst)) /* condition failed? */ + ci->u.l.savedpc++; /* skip jump instruction */ + break; + } + case OP_CONCAT: { + StkId top = L->top - 1; /* top when 'luaT_trybinTM' was called */ + int b = GETARG_B(inst); /* first element to concatenate */ + int total = cast_int(top - 1 - (base + b)); /* yet to concatenate */ + setobj2s(L, top - 2, top); /* put TM result in proper position */ + if (total > 1) { /* are there elements to concat? */ + L->top = top - 1; /* top is one after last element (at top-2) */ + luaV_concat(L, total); /* concat them (may yield again) */ + } + /* move final result to final position */ + setobj2s(L, ci->u.l.base + GETARG_A(inst), L->top - 1); + L->top = ci->top; /* restore top */ + break; + } + case OP_TFORCALL: { + lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_TFORLOOP); + L->top = ci->top; /* correct top */ + break; + } + case OP_CALL: { + if (GETARG_C(inst) - 1 >= 0) /* nresults >= 0? */ + L->top = ci->top; /* adjust results */ + break; + } + case OP_TAILCALL: case OP_SETTABUP: case OP_SETTABLE: + break; + default: lua_assert(0); + } +} + + + + +/* +** {================================================================== +** Function 'luaV_execute': main interpreter loop +** =================================================================== +*/ + + +/* +** some macros for common tasks in 'luaV_execute' +*/ + + +#define RA(i) (base+GETARG_A(i)) +#define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i)) +#define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i)) +#define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \ + ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i)) +#define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \ + ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i)) + + +/* execute a jump instruction */ +#define dojump(ci,i,e) \ + { int a = GETARG_A(i); \ + if (a != 0) luaF_close(L, ci->u.l.base + a - 1); \ + ci->u.l.savedpc += GETARG_sBx(i) + e; } + +/* for test instructions, execute the jump instruction that follows it */ +#define donextjump(ci) { i = *ci->u.l.savedpc; dojump(ci, i, 1); } + + +#define Protect(x) { {x;}; base = ci->u.l.base; } + +#define checkGC(L,c) \ + { luaC_condGC(L, L->top = (c), /* limit of live values */ \ + Protect(L->top = ci->top)); /* restore top */ \ + luai_threadyield(L); } + + +/* fetch an instruction and prepare its execution */ +#define vmfetch() { \ + i = *(ci->u.l.savedpc++); \ + if (L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) \ + Protect(luaG_traceexec(L)); \ + ra = RA(i); /* WARNING: any stack reallocation invalidates 'ra' */ \ + lua_assert(base == ci->u.l.base); \ + lua_assert(base <= L->top && L->top < L->stack + L->stacksize); \ +} + +#define vmdispatch(o) switch(o) +#define vmcase(l) case l: +#define vmbreak break + + +/* +** copy of 'luaV_gettable', but protecting the call to potential +** metamethod (which can reallocate the stack) +*/ +#define gettableProtected(L,t,k,v) { const TValue *slot; \ + if (luaV_fastget(L,t,k,slot,luaH_get)) { setobj2s(L, v, slot); } \ + else Protect(luaV_finishget(L,t,k,v,slot)); } + + +/* same for 'luaV_settable' */ +#define settableProtected(L,t,k,v) { const TValue *slot; \ + if (!luaV_fastset(L,t,k,slot,luaH_get,v)) \ + Protect(luaV_finishset(L,t,k,v,slot)); } + + + +void luaV_execute (lua_State *L) { + CallInfo *ci = L->ci; + LClosure *cl; + TValue *k; + StkId base; + ci->callstatus |= CIST_FRESH; /* fresh invocation of 'luaV_execute" */ + newframe: /* reentry point when frame changes (call/return) */ + lua_assert(ci == L->ci); + cl = clLvalue(ci->func); /* local reference to function's closure */ + k = cl->p->k; /* local reference to function's constant table */ + base = ci->u.l.base; /* local copy of function's base */ + /* main loop of interpreter */ + for (;;) { + Instruction i; + StkId ra; + vmfetch(); + vmdispatch (GET_OPCODE(i)) { + vmcase(OP_MOVE) { + setobjs2s(L, ra, RB(i)); + vmbreak; + } + vmcase(OP_LOADK) { + TValue *rb = k + GETARG_Bx(i); + setobj2s(L, ra, rb); + vmbreak; + } + vmcase(OP_LOADKX) { + TValue *rb; + lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG); + rb = k + GETARG_Ax(*ci->u.l.savedpc++); + setobj2s(L, ra, rb); + vmbreak; + } + vmcase(OP_LOADBOOL) { + setbvalue(ra, GETARG_B(i)); + if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */ + vmbreak; + } + vmcase(OP_LOADNIL) { + int b = GETARG_B(i); + do { + setnilvalue(ra++); + } while (b--); + vmbreak; + } + vmcase(OP_GETUPVAL) { + int b = GETARG_B(i); + setobj2s(L, ra, cl->upvals[b]->v); + vmbreak; + } + vmcase(OP_GETTABUP) { + TValue *upval = cl->upvals[GETARG_B(i)]->v; + TValue *rc = RKC(i); + gettableProtected(L, upval, rc, ra); + vmbreak; + } + vmcase(OP_GETTABLE) { + StkId rb = RB(i); + TValue *rc = RKC(i); + gettableProtected(L, rb, rc, ra); + vmbreak; + } + vmcase(OP_SETTABUP) { + TValue *upval = cl->upvals[GETARG_A(i)]->v; + TValue *rb = RKB(i); + TValue *rc = RKC(i); + settableProtected(L, upval, rb, rc); + vmbreak; + } + vmcase(OP_SETUPVAL) { + UpVal *uv = cl->upvals[GETARG_B(i)]; + setobj(L, uv->v, ra); + luaC_upvalbarrier(L, uv); + vmbreak; + } + vmcase(OP_SETTABLE) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + settableProtected(L, ra, rb, rc); + vmbreak; + } + vmcase(OP_NEWTABLE) { + int b = GETARG_B(i); + int c = GETARG_C(i); + Table *t = luaH_new(L); + sethvalue(L, ra, t); + if (b != 0 || c != 0) + luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c)); + checkGC(L, ra + 1); + vmbreak; + } + vmcase(OP_SELF) { + const TValue *aux; + StkId rb = RB(i); + TValue *rc = RKC(i); + TString *key = tsvalue(rc); /* key must be a string */ + setobjs2s(L, ra + 1, rb); + if (luaV_fastget(L, rb, key, aux, luaH_getstr)) { + setobj2s(L, ra, aux); + } + else Protect(luaV_finishget(L, rb, rc, ra, aux)); + vmbreak; + } + vmcase(OP_ADD) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Number nb; lua_Number nc; + if (ttisinteger(rb) && ttisinteger(rc)) { + lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc); + setivalue(ra, intop(+, ib, ic)); + } + else if (tonumber(rb, &nb) && tonumber(rc, &nc)) { + setfltvalue(ra, luai_numadd(L, nb, nc)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_ADD)); } + vmbreak; + } + vmcase(OP_SUB) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Number nb; lua_Number nc; + if (ttisinteger(rb) && ttisinteger(rc)) { + lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc); + setivalue(ra, intop(-, ib, ic)); + } + else if (tonumber(rb, &nb) && tonumber(rc, &nc)) { + setfltvalue(ra, luai_numsub(L, nb, nc)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SUB)); } + vmbreak; + } + vmcase(OP_MUL) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Number nb; lua_Number nc; + if (ttisinteger(rb) && ttisinteger(rc)) { + lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc); + setivalue(ra, intop(*, ib, ic)); + } + else if (tonumber(rb, &nb) && tonumber(rc, &nc)) { + setfltvalue(ra, luai_nummul(L, nb, nc)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MUL)); } + vmbreak; + } + vmcase(OP_DIV) { /* float division (always with floats) */ + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Number nb; lua_Number nc; + if (tonumber(rb, &nb) && tonumber(rc, &nc)) { + setfltvalue(ra, luai_numdiv(L, nb, nc)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_DIV)); } + vmbreak; + } + vmcase(OP_BAND) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Integer ib; lua_Integer ic; + if (tointeger(rb, &ib) && tointeger(rc, &ic)) { + setivalue(ra, intop(&, ib, ic)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BAND)); } + vmbreak; + } + vmcase(OP_BOR) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Integer ib; lua_Integer ic; + if (tointeger(rb, &ib) && tointeger(rc, &ic)) { + setivalue(ra, intop(|, ib, ic)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BOR)); } + vmbreak; + } + vmcase(OP_BXOR) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Integer ib; lua_Integer ic; + if (tointeger(rb, &ib) && tointeger(rc, &ic)) { + setivalue(ra, intop(^, ib, ic)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BXOR)); } + vmbreak; + } + vmcase(OP_SHL) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Integer ib; lua_Integer ic; + if (tointeger(rb, &ib) && tointeger(rc, &ic)) { + setivalue(ra, luaV_shiftl(ib, ic)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHL)); } + vmbreak; + } + vmcase(OP_SHR) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Integer ib; lua_Integer ic; + if (tointeger(rb, &ib) && tointeger(rc, &ic)) { + setivalue(ra, luaV_shiftl(ib, -ic)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHR)); } + vmbreak; + } + vmcase(OP_MOD) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Number nb; lua_Number nc; + if (ttisinteger(rb) && ttisinteger(rc)) { + lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc); + setivalue(ra, luaV_mod(L, ib, ic)); + } + else if (tonumber(rb, &nb) && tonumber(rc, &nc)) { + lua_Number m; + luai_nummod(L, nb, nc, m); + setfltvalue(ra, m); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MOD)); } + vmbreak; + } + vmcase(OP_IDIV) { /* floor division */ + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Number nb; lua_Number nc; + if (ttisinteger(rb) && ttisinteger(rc)) { + lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc); + setivalue(ra, luaV_div(L, ib, ic)); + } + else if (tonumber(rb, &nb) && tonumber(rc, &nc)) { + setfltvalue(ra, luai_numidiv(L, nb, nc)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_IDIV)); } + vmbreak; + } + vmcase(OP_POW) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Number nb; lua_Number nc; + if (tonumber(rb, &nb) && tonumber(rc, &nc)) { + setfltvalue(ra, luai_numpow(L, nb, nc)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_POW)); } + vmbreak; + } + vmcase(OP_UNM) { + TValue *rb = RB(i); + lua_Number nb; + if (ttisinteger(rb)) { + lua_Integer ib = ivalue(rb); + setivalue(ra, intop(-, 0, ib)); + } + else if (tonumber(rb, &nb)) { + setfltvalue(ra, luai_numunm(L, nb)); + } + else { + Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM)); + } + vmbreak; + } + vmcase(OP_BNOT) { + TValue *rb = RB(i); + lua_Integer ib; + if (tointeger(rb, &ib)) { + setivalue(ra, intop(^, ~l_castS2U(0), ib)); + } + else { + Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT)); + } + vmbreak; + } + vmcase(OP_NOT) { + TValue *rb = RB(i); + int res = l_isfalse(rb); /* next assignment may change this value */ + setbvalue(ra, res); + vmbreak; + } + vmcase(OP_LEN) { + Protect(luaV_objlen(L, ra, RB(i))); + vmbreak; + } + vmcase(OP_CONCAT) { + int b = GETARG_B(i); + int c = GETARG_C(i); + StkId rb; + L->top = base + c + 1; /* mark the end of concat operands */ + Protect(luaV_concat(L, c - b + 1)); + ra = RA(i); /* 'luaV_concat' may invoke TMs and move the stack */ + rb = base + b; + setobjs2s(L, ra, rb); + checkGC(L, (ra >= rb ? ra + 1 : rb)); + L->top = ci->top; /* restore top */ + vmbreak; + } + vmcase(OP_JMP) { + dojump(ci, i, 0); + vmbreak; + } + vmcase(OP_EQ) { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + Protect( + if (luaV_equalobj(L, rb, rc) != GETARG_A(i)) + ci->u.l.savedpc++; + else + donextjump(ci); + ) + vmbreak; + } + vmcase(OP_LT) { + Protect( + if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i)) + ci->u.l.savedpc++; + else + donextjump(ci); + ) + vmbreak; + } + vmcase(OP_LE) { + Protect( + if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i)) + ci->u.l.savedpc++; + else + donextjump(ci); + ) + vmbreak; + } + vmcase(OP_TEST) { + if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra)) + ci->u.l.savedpc++; + else + donextjump(ci); + vmbreak; + } + vmcase(OP_TESTSET) { + TValue *rb = RB(i); + if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb)) + ci->u.l.savedpc++; + else { + setobjs2s(L, ra, rb); + donextjump(ci); + } + vmbreak; + } + vmcase(OP_CALL) { + int b = GETARG_B(i); + int nresults = GETARG_C(i) - 1; + if (b != 0) L->top = ra+b; /* else previous instruction set top */ + if (luaD_precall(L, ra, nresults)) { /* C function? */ + if (nresults >= 0) + L->top = ci->top; /* adjust results */ + Protect((void)0); /* update 'base' */ + } + else { /* Lua function */ + ci = L->ci; + goto newframe; /* restart luaV_execute over new Lua function */ + } + vmbreak; + } + vmcase(OP_TAILCALL) { + int b = GETARG_B(i); + if (b != 0) L->top = ra+b; /* else previous instruction set top */ + lua_assert(GETARG_C(i) - 1 == LUA_MULTRET); + if (luaD_precall(L, ra, LUA_MULTRET)) { /* C function? */ + Protect((void)0); /* update 'base' */ + } + else { + /* tail call: put called frame (n) in place of caller one (o) */ + CallInfo *nci = L->ci; /* called frame */ + CallInfo *oci = nci->previous; /* caller frame */ + StkId nfunc = nci->func; /* called function */ + StkId ofunc = oci->func; /* caller function */ + /* last stack slot filled by 'precall' */ + StkId lim = nci->u.l.base + getnumparams(getproto(nfunc)); + int aux; + /* close all upvalues from previous call */ + if (cl->p->sizep > 0) luaF_close(L, oci->u.l.base); + /* move new frame into old one */ + for (aux = 0; nfunc + aux < lim; aux++) + setobjs2s(L, ofunc + aux, nfunc + aux); + oci->u.l.base = ofunc + (nci->u.l.base - nfunc); /* correct base */ + oci->top = L->top = ofunc + (L->top - nfunc); /* correct top */ + oci->u.l.savedpc = nci->u.l.savedpc; + oci->callstatus |= CIST_TAIL; /* function was tail called */ + ci = L->ci = oci; /* remove new frame */ + lua_assert(L->top == oci->u.l.base + getmaxstacksize(getproto(ofunc))); + goto newframe; /* restart luaV_execute over new Lua function */ + } + vmbreak; + } + vmcase(OP_RETURN) { + int b = GETARG_B(i); + if (cl->p->sizep > 0) luaF_close(L, base); + b = luaD_poscall(L, ci, ra, (b != 0 ? b - 1 : cast_int(L->top - ra))); + if (ci->callstatus & CIST_FRESH) /* local 'ci' still from callee */ + return; /* external invocation: return */ + else { /* invocation via reentry: continue execution */ + ci = L->ci; + if (b) L->top = ci->top; + lua_assert(isLua(ci)); + lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL); + goto newframe; /* restart luaV_execute over new Lua function */ + } + } + vmcase(OP_FORLOOP) { + if (ttisinteger(ra)) { /* integer loop? */ + lua_Integer step = ivalue(ra + 2); + lua_Integer idx = intop(+, ivalue(ra), step); /* increment index */ + lua_Integer limit = ivalue(ra + 1); + if ((0 < step) ? (idx <= limit) : (limit <= idx)) { + ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ + chgivalue(ra, idx); /* update internal index... */ + setivalue(ra + 3, idx); /* ...and external index */ + } + } + else { /* floating loop */ + lua_Number step = fltvalue(ra + 2); + lua_Number idx = luai_numadd(L, fltvalue(ra), step); /* inc. index */ + lua_Number limit = fltvalue(ra + 1); + if (luai_numlt(0, step) ? luai_numle(idx, limit) + : luai_numle(limit, idx)) { + ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ + chgfltvalue(ra, idx); /* update internal index... */ + setfltvalue(ra + 3, idx); /* ...and external index */ + } + } + vmbreak; + } + vmcase(OP_FORPREP) { + TValue *init = ra; + TValue *plimit = ra + 1; + TValue *pstep = ra + 2; + lua_Integer ilimit; + int stopnow; + if (ttisinteger(init) && ttisinteger(pstep) && + forlimit(plimit, &ilimit, ivalue(pstep), &stopnow)) { + /* all values are integer */ + lua_Integer initv = (stopnow ? 0 : ivalue(init)); + setivalue(plimit, ilimit); + setivalue(init, intop(-, initv, ivalue(pstep))); + } + else { /* try making all values floats */ + lua_Number ninit; lua_Number nlimit; lua_Number nstep; + if (!tonumber(plimit, &nlimit)) + luaG_runerror(L, "'for' limit must be a number"); + setfltvalue(plimit, nlimit); + if (!tonumber(pstep, &nstep)) + luaG_runerror(L, "'for' step must be a number"); + setfltvalue(pstep, nstep); + if (!tonumber(init, &ninit)) + luaG_runerror(L, "'for' initial value must be a number"); + setfltvalue(init, luai_numsub(L, ninit, nstep)); + } + ci->u.l.savedpc += GETARG_sBx(i); + vmbreak; + } + vmcase(OP_TFORCALL) { + StkId cb = ra + 3; /* call base */ + setobjs2s(L, cb+2, ra+2); + setobjs2s(L, cb+1, ra+1); + setobjs2s(L, cb, ra); + L->top = cb + 3; /* func. + 2 args (state and index) */ + Protect(luaD_call(L, cb, GETARG_C(i))); + L->top = ci->top; + i = *(ci->u.l.savedpc++); /* go to next instruction */ + ra = RA(i); + lua_assert(GET_OPCODE(i) == OP_TFORLOOP); + goto l_tforloop; + } + vmcase(OP_TFORLOOP) { + l_tforloop: + if (!ttisnil(ra + 1)) { /* continue loop? */ + setobjs2s(L, ra, ra + 1); /* save control variable */ + ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ + } + vmbreak; + } + vmcase(OP_SETLIST) { + int n = GETARG_B(i); + int c = GETARG_C(i); + unsigned int last; + Table *h; + if (n == 0) n = cast_int(L->top - ra) - 1; + if (c == 0) { + lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG); + c = GETARG_Ax(*ci->u.l.savedpc++); + } + h = hvalue(ra); + last = ((c-1)*LFIELDS_PER_FLUSH) + n; + if (last > h->sizearray) /* needs more space? */ + luaH_resizearray(L, h, last); /* preallocate it at once */ + for (; n > 0; n--) { + TValue *val = ra+n; + luaH_setint(L, h, last--, val); + luaC_barrierback(L, h, val); + } + L->top = ci->top; /* correct top (in case of previous open call) */ + vmbreak; + } + vmcase(OP_CLOSURE) { + Proto *p = cl->p->p[GETARG_Bx(i)]; + pushclosure(L, p, cl->upvals, base, ra); /* create a new Closure */ + checkGC(L, ra + 1); + vmbreak; + } + vmcase(OP_VARARG) { + int b = GETARG_B(i) - 1; /* required results */ + int j; + int n = cast_int(base - ci->func) - getnumparams(cl->p) - 1; + if (n < 0) /* less arguments than parameters? */ + n = 0; /* no vararg arguments */ + if (b < 0) { /* B == 0? */ + b = n; /* get all var. arguments */ + Protect(luaD_checkstack(L, n)); + ra = RA(i); /* previous call may change the stack */ + L->top = ra + n; + } + for (j = 0; j < b && j < n; j++) + setobjs2s(L, ra + j, base - n + j); + for (; j < b; j++) /* complete required results with nil */ + setnilvalue(ra + j); + vmbreak; + } + vmcase(OP_EXTRAARG) { + lua_assert(0); + vmbreak; + } + } + } +} + +/* }================================================================== */ + diff --git a/components/lua/lua-5.3/lvm.h b/components/lua/lua-5.3/lvm.h new file mode 100644 index 00000000..a8f954f0 --- /dev/null +++ b/components/lua/lua-5.3/lvm.h @@ -0,0 +1,113 @@ +/* +** $Id: lvm.h,v 2.41.1.1 2017/04/19 17:20:42 roberto Exp $ +** Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#ifndef lvm_h +#define lvm_h + + +#include "ldo.h" +#include "lobject.h" +#include "ltm.h" + + +#if !defined(LUA_NOCVTN2S) +#define cvt2str(o) ttisnumber(o) +#else +#define cvt2str(o) 0 /* no conversion from numbers to strings */ +#endif + + +#if !defined(LUA_NOCVTS2N) +#define cvt2num(o) ttisstring(o) +#else +#define cvt2num(o) 0 /* no conversion from strings to numbers */ +#endif + + +/* +** You can define LUA_FLOORN2I if you want to convert floats to integers +** by flooring them (instead of raising an error if they are not +** integral values) +*/ +#if !defined(LUA_FLOORN2I) +#define LUA_FLOORN2I 0 +#endif + + +#define tonumber(o,n) \ + (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n)) + +#define tointeger(o,i) \ + (ttisinteger(o) ? (*(i) = ivalue(o), 1) : luaV_tointeger(o,i,LUA_FLOORN2I)) + +#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2)) + +#define luaV_rawequalobj(t1,t2) luaV_equalobj(NULL,t1,t2) + + +/* +** fast track for 'gettable': if 't' is a table and 't[k]' is not nil, +** return 1 with 'slot' pointing to 't[k]' (final result). Otherwise, +** return 0 (meaning it will have to check metamethod) with 'slot' +** pointing to a nil 't[k]' (if 't' is a table) or NULL (otherwise). +** 'f' is the raw get function to use. +*/ +#define luaV_fastget(L,t,k,slot,f) \ + (!ttistable(t) \ + ? (slot = NULL, 0) /* not a table; 'slot' is NULL and result is 0 */ \ + : (slot = f(hvalue(t), k), /* else, do raw access */ \ + !ttisnil(slot))) /* result not nil? */ + +/* +** standard implementation for 'gettable' +*/ +#define luaV_gettable(L,t,k,v) { const TValue *slot; \ + if (luaV_fastget(L,t,k,slot,luaH_get)) { setobj2s(L, v, slot); } \ + else luaV_finishget(L,t,k,v,slot); } + + +/* +** Fast track for set table. If 't' is a table and 't[k]' is not nil, +** call GC barrier, do a raw 't[k]=v', and return true; otherwise, +** return false with 'slot' equal to NULL (if 't' is not a table) or +** 'nil'. (This is needed by 'luaV_finishget'.) Note that, if the macro +** returns true, there is no need to 'invalidateTMcache', because the +** call is not creating a new entry. +*/ +#define luaV_fastset(L,t,k,slot,f,v) \ + (!ttistable(t) \ + ? (slot = NULL, 0) \ + : (slot = f(hvalue(t), k), \ + ttisnil(slot) ? 0 \ + : (luaC_barrierback(L, hvalue(t), v), \ + setobj2t(L, cast(TValue *,slot), v), \ + 1))) + + +#define luaV_settable(L,t,k,v) { const TValue *slot; \ + if (!luaV_fastset(L,t,k,slot,luaH_get,v)) \ + luaV_finishset(L,t,k,v,slot); } + + + +LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2); +LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); +LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r); +LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n); +LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, int mode); +LUAI_FUNC void luaV_finishget (lua_State *L, const TValue *t, TValue *key, + StkId val, const TValue *slot); +LUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key, + StkId val, const TValue *slot); +LUAI_FUNC void luaV_finishOp (lua_State *L); +LUAI_FUNC void luaV_execute (lua_State *L); +LUAI_FUNC void luaV_concat (lua_State *L, int total); +LUAI_FUNC lua_Integer luaV_div (lua_State *L, lua_Integer x, lua_Integer y); +LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y); +LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y); +LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb); + +#endif diff --git a/components/lua/lua-5.3/lzio.c b/components/lua/lua-5.3/lzio.c new file mode 100644 index 00000000..6f790944 --- /dev/null +++ b/components/lua/lua-5.3/lzio.c @@ -0,0 +1,68 @@ +/* +** $Id: lzio.c,v 1.37.1.1 2017/04/19 17:20:42 roberto Exp $ +** Buffered streams +** See Copyright Notice in lua.h +*/ + +#define lzio_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "llimits.h" +#include "lmem.h" +#include "lstate.h" +#include "lzio.h" + + +int luaZ_fill (ZIO *z) { + size_t size; + lua_State *L = z->L; + const char *buff; + lua_unlock(L); + buff = z->reader(L, z->data, &size); + lua_lock(L); + if (buff == NULL || size == 0) + return EOZ; + z->n = size - 1; /* discount char being returned */ + z->p = buff; + return cast_uchar(*(z->p++)); +} + + +void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { + z->L = L; + z->reader = reader; + z->data = data; + z->n = 0; + z->p = NULL; +} + + +/* --------------------------------------------------------------- read --- */ +size_t luaZ_read (ZIO *z, void *b, size_t n) { + while (n) { + size_t m; + if (z->n == 0) { /* no bytes in buffer? */ + if (luaZ_fill(z) == EOZ) /* try to read more */ + return n; /* no more input; return number of missing bytes */ + else { + z->n++; /* luaZ_fill consumed first byte; put it back */ + z->p--; + } + } + m = (n <= z->n) ? n : z->n; /* min. between n and z->n */ + memcpy(b, z->p, m); + z->n -= m; + z->p += m; + b = (char *)b + m; + n -= m; + } + return 0; +} + diff --git a/components/lua/lua-5.3/lzio.h b/components/lua/lua-5.3/lzio.h new file mode 100644 index 00000000..d8978708 --- /dev/null +++ b/components/lua/lua-5.3/lzio.h @@ -0,0 +1,66 @@ +/* +** $Id: lzio.h,v 1.31.1.1 2017/04/19 17:20:42 roberto Exp $ +** Buffered streams +** See Copyright Notice in lua.h +*/ + + +#ifndef lzio_h +#define lzio_h + +#include "lua.h" + +#include "lmem.h" + + +#define EOZ (-1) /* end of stream */ + +typedef struct Zio ZIO; + +#define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z)) + + +typedef struct Mbuffer { + char *buffer; + size_t n; + size_t buffsize; +} Mbuffer; + +#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0) + +#define luaZ_buffer(buff) ((buff)->buffer) +#define luaZ_sizebuffer(buff) ((buff)->buffsize) +#define luaZ_bufflen(buff) ((buff)->n) + +#define luaZ_buffremove(buff,i) ((buff)->n -= (i)) +#define luaZ_resetbuffer(buff) ((buff)->n = 0) + + +#define luaZ_resizebuffer(L, buff, size) \ + ((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \ + (buff)->buffsize, size), \ + (buff)->buffsize = size) + +#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) + + +LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, + void *data); +LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n); /* read next n bytes */ + + + +/* --------- Private Part ------------------ */ + +struct Zio { + size_t n; /* bytes still unread */ + const char *p; /* current position in buffer */ + lua_Reader reader; /* reader function */ + void *data; /* additional data */ + lua_State *L; /* Lua state (for reader) */ +}; + + +LUAI_FUNC int luaZ_fill (ZIO *z); + +#endif diff --git a/components/lua/lua.c b/components/lua/lua.c deleted file mode 100644 index e23a3ffd..00000000 --- a/components/lua/lua.c +++ /dev/null @@ -1,544 +0,0 @@ -/* -** $Id: lua.c,v 1.160.1.2 2007/12/28 15:32:23 roberto Exp $ -** Lua stand-alone interpreter -** See Copyright Notice in lua.h -*/ - - -// #include -#include -#include -#include -#include "user_version.h" -#include "driver/console.h" -#include "esp_system.h" -#include "platform.h" - -#define lua_c - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" -#include "legc.h" -#include "lflash.h" - -lua_State *globalL = NULL; - -lua_Load gLoad; -static const char *progname = LUA_PROGNAME; - -static void l_message (const char *pname, const char *msg) { -#if defined(LUA_USE_STDIO) - if (pname) fprintf(stderr, "%s: ", pname); - fprintf(stderr, "%s\n", msg); - fflush(stderr); -#else - if (pname) luai_writestringerror("%s: ", pname); - luai_writestringerror("%s\n", msg); -#endif -} - - -static int report (lua_State *L, int status) { - if (status && !lua_isnil(L, -1)) { - const char *msg = lua_tostring(L, -1); - if (msg == NULL) msg = "(error object is not a string)"; - l_message(progname, msg); - lua_pop(L, 1); - } - return status; -} - - -static int traceback (lua_State *L) { - if (!lua_isstring(L, 1)) /* 'message' not a string? */ - return 1; /* keep it intact */ - lua_getfield(L, LUA_GLOBALSINDEX, "debug"); - if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) { - lua_pop(L, 1); - return 1; - } - lua_getfield(L, -1, "traceback"); - if (!lua_isfunction(L, -1) && !lua_islightfunction(L, -1)) { - lua_pop(L, 2); - return 1; - } - lua_pushvalue(L, 1); /* pass error message */ - lua_pushinteger(L, 2); /* skip this function and traceback */ - lua_call(L, 2, 1); /* call debug.traceback */ - return 1; -} - - -static int docall (lua_State *L, int narg, int clear) { - int status; - int base = lua_gettop(L) - narg; /* function index */ - lua_pushcfunction(L, traceback); /* push traceback function */ - lua_insert(L, base); /* put it under chunk and args */ - // signal(SIGINT, laction); - status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base); - // signal(SIGINT, SIG_DFL); - lua_remove(L, base); /* remove traceback function */ - /* force a complete garbage collection in case of errors */ - if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0); - return status; -} - - -static void print_version (lua_State *L) { - lua_pushliteral (L, "\n" NODE_VERSION " build " BUILD_DATE " powered by " LUA_RELEASE " on SDK "); - lua_pushstring (L, SDK_VERSION); - lua_concat (L, 2); - const char *msg = lua_tostring (L, -1); - l_message (NULL, msg); - lua_pop (L, 1); -} - - -#if 0 -static int getargs (lua_State *L, char **argv, int n) { - int narg; - int i; - int argc = 0; - while (argv[argc]) argc++; /* count total number of arguments */ - narg = argc - (n + 1); /* number of arguments to the script */ - luaL_checkstack(L, narg + 3, "too many arguments to script"); - for (i=n+1; i < argc; i++) - lua_pushstring(L, argv[i]); - lua_createtable(L, narg, n + 1); - for (i=0; i < argc; i++) { - lua_pushstring(L, argv[i]); - lua_rawseti(L, -2, i - n); - } - return narg; -} -#endif - -static int dofsfile (lua_State *L, const char *name) { - int status = luaL_loadfsfile(L, name) || docall(L, 0, 1); - return report(L, status); -} - -static int dolfsfile (lua_State *L, const char *name) { - int status = 1; - const char *code_fmt = "if node.flashindex('%s') then node.flashindex('%s')() end"; - char *module_name = strdup(name); - unsigned name_len = strlen(name); - unsigned code_length = strlen(code_fmt) + name_len*2 + 1; - char *code_buf = malloc(code_length); - - if (code_buf && module_name) { - char *dot = strrchr(module_name, '.'); - if (dot) { - if (strstr(module_name, ".lua") == dot) - *dot = 0; - } - snprintf(code_buf, code_length, code_fmt, module_name, module_name); - status = luaL_dostring(L, code_buf); - if (status) - lua_pushfstring(L, "Failed to load %s from LFS", module_name); - } else { - lua_pushstring(L, "Failed to allocate memory"); - } - - if (module_name) - free(module_name); - if (code_buf) - free(code_buf); - return report(L, status); -} - -static int dostring (lua_State *L, const char *s, const char *name) { - int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1); - return report(L, status); -} - - -static int dolibrary (lua_State *L, const char *name) { - lua_getglobal(L, "require"); - lua_pushstring(L, name); - return report(L, docall(L, 1, 1)); -} - -static const char *get_prompt (lua_State *L, int firstline) { - const char *p; - lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2"); - p = lua_tostring(L, -1); - if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2); - lua_pop(L, 1); /* remove global */ - return p; -} - - -static int incomplete (lua_State *L, int status) { - if (status == LUA_ERRSYNTAX) { - size_t lmsg; - const char *msg = lua_tolstring(L, -1, &lmsg); - const char *tp = msg + lmsg - (sizeof(LUA_QL("")) - 1); - if (strstr(msg, LUA_QL("")) == tp) { - lua_pop(L, 1); - return 1; - } - } - return 0; /* else... */ -} - - -/* check that argument has no extra characters at the end */ -#define notail(x) {if ((x)[2] != '\0') return -1;} - - -static int collectargs (char **argv, int *pi, int *pv, int *pe) { - int i; - for (i = 1; argv[i] != NULL; i++) { - if (argv[i][0] != '-') /* not an option? */ - return i; - switch (argv[i][1]) { /* option */ - case '-': - notail(argv[i]); - return (argv[i+1] != NULL ? i+1 : 0); - case '\0': - return i; - case 'i': - notail(argv[i]); - *pi = 1; /* fall-through */ - case 'v': - notail(argv[i]); - *pv = 1; - break; - case 'e': - *pe = 1; /* fall-through */ - case 'm': /* fall-through */ - case 'l': - if (argv[i][2] == '\0') { - i++; - if (argv[i] == NULL) return -1; - } - break; - default: return -1; /* invalid option */ - } - } - return 0; -} - - -static int runargs (lua_State *L, char **argv, int n) { - int i; - for (i = 1; i < n; i++) { - if (argv[i] == NULL) continue; - lua_assert(argv[i][0] == '-'); - switch (argv[i][1]) { /* option */ - case 'e': { - const char *chunk = argv[i] + 2; - if (*chunk == '\0') chunk = argv[++i]; - lua_assert(chunk != NULL); - if (dostring(L, chunk, "=(command line)") != 0) - return 1; - break; - } - case 'm': { - const char *limit = argv[i] + 2; - int memlimit=0; - if (*limit == '\0') limit = argv[++i]; - lua_assert(limit != NULL); - memlimit = atoi(limit); - lua_gc(L, LUA_GCSETMEMLIMIT, memlimit); - break; - } - case 'l': { - const char *filename = argv[i] + 2; - if (*filename == '\0') filename = argv[++i]; - lua_assert(filename != NULL); - if (dolibrary(L, filename)) - return 1; /* stop if file fails */ - break; - } - default: break; - } - } - return 0; -} - - -#ifndef LUA_INIT_STRING -#define LUA_INIT_STRING "@init.lua" -#endif - -static int handle_luainit (lua_State *L) { - (void)dolfsfile; // silence warning about potentially unused function - const char *init = LUA_INIT_STRING; - if (init[0] == '@') { - #if CONFIG_NODEMCU_EMBEDDED_LFS_SIZE > 0 - int status = dolfsfile(L, init+1); - if (status == 0) - return status; - #endif - return dofsfile(L, init+1); - } else - return dostring(L, init, LUA_INIT); -} - - -struct Smain { - int argc; - char **argv; - int status; -}; - - -static int pmain (lua_State *L) { - struct Smain *s = (struct Smain *)lua_touserdata(L, 1); - char **argv = s->argv; - int script; - int has_i = 0, has_v = 0, has_e = 0; - globalL = L; - if (argv[0] && argv[0][0]) progname = argv[0]; - lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ - luaL_openlibs(L); /* open libraries */ - lua_gc(L, LUA_GCRESTART, 0); - print_version(L); - s->status = handle_luainit(L); - script = collectargs(argv, &has_i, &has_v, &has_e); - if (script < 0) { /* invalid args? */ - s->status = 1; - return 0; - } - s->status = runargs(L, argv, (script > 0) ? script : s->argc); - if (s->status != 0) return 0; - return 0; -} - -static void dojob(lua_Load *load); -static bool readline(lua_Load *load); - -#ifdef LUA_RPC -int main (int argc, char **argv) { -#else -int lua_main (int argc, char **argv) { -#endif - int status; - struct Smain s; - lua_State *L = lua_open(); /* create state */ - if (L == NULL) { - l_message(argv[0], "cannot create state: not enough memory"); - return EXIT_FAILURE; - } - s.argc = argc; - s.argv = argv; - - status = lua_cpcall(L, &pmain, &s); - - report(L, status); - - gLoad.L = L; - gLoad.firstline = 1; - gLoad.done = 0; - gLoad.line = malloc(LUA_MAXINPUT); - gLoad.len = LUA_MAXINPUT; - gLoad.line_position = 0; - gLoad.prmt = get_prompt(L, 1); - - dojob(&gLoad); - - NODE_DBG("Heap size:%d.\n",system_get_free_heap_size()); - legc_set_mode( L, EGC_ALWAYS, 4096 ); - // legc_set_mode( L, EGC_ON_MEM_LIMIT, 4096 ); - // lua_close(L); - return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS; -} - -int lua_put_line(const char *s, size_t l) { - if (s == NULL || ++l > LUA_MAXINPUT || gLoad.line_position > 0) - return 0; - memcpy(gLoad.line, s, l); - gLoad.line[l] = '\0'; - gLoad.line_position = l; - gLoad.done = 1; - NODE_DBG("Get command: %s\n", gLoad.line); - return 1; -} - -void lua_handle_input (bool force) -{ - while (gLoad.L && (force || readline (&gLoad))) { - NODE_DBG("Handle Input: first=%u, pos=%u, len=%u, actual=%u, line=%s\n", gLoad.firstline, - gLoad.line_position, gLoad.len, strlen(gLoad.line), gLoad.line); - dojob (&gLoad); - force = false; - } -} - -void donejob(lua_Load *load){ - lua_close(load->L); -} - -static void dojob(lua_Load *load){ - size_t l; - int status; - char *b = load->line; - lua_State *L = load->L; - - const char *oldprogname = progname; - progname = NULL; - - do{ - if(load->done == 1){ - l = strlen(b); - if (l > 0 && b[l-1] == '\n') /* line ends with newline? */ - b[l-1] = '\0'; /* remove it */ - if (load->firstline && b[0] == '=') /* first line starts with `=' ? */ - lua_pushfstring(L, "return %s", b+1); /* change it to `return' */ - else - lua_pushstring(L, b); - if(load->firstline != 1){ - lua_pushliteral(L, "\n"); /* add a new line... */ - lua_insert(L, -2); /* ...between the two lines */ - lua_concat(L, 3); /* join them */ - } - - status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin"); - if (!incomplete(L, status)) { /* cannot try to add lines? */ - lua_remove(L, 1); /* remove line */ - if (status == 0) { - status = docall(L, 0, 0); - } - report(L, status); - if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */ - lua_getglobal(L, "print"); - lua_insert(L, 1); - if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) - l_message(progname, lua_pushfstring(L, - "error calling " LUA_QL("print") " (%s)", - lua_tostring(L, -1))); - } - load->firstline = 1; - load->prmt = get_prompt(L, 1); - lua_settop(L, 0); - /* force a complete garbage collection in case of errors */ - if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0); - } else { - load->firstline = 0; - load->prmt = get_prompt(L, 0); - } - } - }while(0); - - progname = oldprogname; - - load->done = 0; - load->line_position = 0; - memset(load->line, 0, load->len); - printf(load->prmt); - fflush (stdout); -} - -extern bool uart_on_data_cb(unsigned id, const char *buf, size_t len); -extern bool uart0_echo; -extern bool run_input; -extern uart_status_t uart_status[]; -static char last_nl_char = '\0'; -static bool readline(lua_Load *load){ - // NODE_DBG("readline() is called.\n"); - bool need_dojob = false; - char ch; - uart_status_t *us = & uart_status[CONSOLE_UART]; - while (console_getc(&ch)) - { - if(run_input) - { - char tmp_last_nl_char = last_nl_char; - // reset marker, will be finally set below when newline is processed - last_nl_char = '\0'; - - /* handle CR & LF characters - filters second char of LF&CR (\n\r) or CR&LF (\r\n) sequences */ - if ((ch == '\r' && tmp_last_nl_char == '\n') || // \n\r sequence -> skip \r - (ch == '\n' && tmp_last_nl_char == '\r')) // \r\n sequence -> skip \n - { - continue; - } - - /* backspace key */ - else if (ch == 0x7f || ch == 0x08) - { - if (load->line_position > 0) - { - if(uart0_echo) putchar(0x08); - if(uart0_echo) putchar(' '); - if(uart0_echo) putchar(0x08); - load->line_position--; - } - load->line[load->line_position] = 0; - continue; - } - /* EOT(ctrl+d) */ - // else if (ch == 0x04) - // { - // if (load->line_position == 0) - // // No input which makes lua interpreter close - // donejob(load); - // else - // continue; - // } - - /* end of line */ - if (ch == '\r' || ch == '\n') - { - last_nl_char = ch; - - load->line[load->line_position] = 0; - if(uart0_echo) putchar('\n'); - uart_on_data_cb(CONSOLE_UART, load->line, load->line_position); - if (load->line_position == 0) - { - /* Get a empty line, then go to get a new line */ - printf(load->prmt); - fflush (stdout); - } else { - load->done = 1; - need_dojob = true; - } - continue; - } - - /* other control character or not an acsii character */ - // if (ch < 0x20 || ch >= 0x80) - // { - // continue; - // } - - /* echo */ - if(uart0_echo) putchar(ch); - - /* it's a large line, discard it */ - if ( load->line_position + 1 >= load->len ){ - load->line_position = 0; - } - } - - load->line[load->line_position] = ch; - load->line_position++; - - if(!run_input) - { - if( ((us->need_len!=0) && (load->line_position >= us->need_len)) || \ - (load->line_position >= load->len) || \ - ((us->end_char>=0) && ((unsigned char)ch==(unsigned char)us->end_char)) ) - { - uart_on_data_cb(CONSOLE_UART, load->line, load->line_position); - load->line_position = 0; - } - } - - ch = 0; - } - - if( (load->line_position > 0) && (!run_input) && (us->need_len==0) && (us->end_char<0) ) - { - uart_on_data_cb(CONSOLE_UART, load->line, load->line_position); - load->line_position = 0; - } - - return need_dojob; -} diff --git a/components/lua/luac_cross.h b/components/lua/luac_cross.h deleted file mode 100644 index 02a82a3d..00000000 --- a/components/lua/luac_cross.h +++ /dev/null @@ -1,23 +0,0 @@ -/* -** Header to allow luac.cross compile within NodeMCU -** See Copyright Notice in lua.h -*/ -#ifndef luac_cross_h -#define luac_cross_h - -#define C_HEADER_ASSERT -#define C_HEADER_CTYPE -#define C_HEADER_ERRNO -#define C_HEADER_FCNTL -#define C_HEADER_LOCALE -#define C_HEADER_MATH -#define C_HEADER_STDIO -#define C_HEADER_STDLIB -#define C_HEADER_STRING -#define C_HEADER_TIME - -#ifdef LUA_CROSS_COMPILER -#define ICACHE_RODATA_ATTR -#endif - -#endif /* luac_cross_h */ diff --git a/components/lua/project_include.cmake b/components/lua/project_include.cmake index 0ab5d01a..5e88c9e2 100644 --- a/components/lua/project_include.cmake +++ b/components/lua/project_include.cmake @@ -1,11 +1 @@ -foreach(def - "-DLUA_OPTIMIZE_MEMORY=2" - "-DMIN_OPT_LEVEL=2" - "-DLUA_OPTIMIZE_DEBUG=${CONFIG_LUA_OPTIMIZE_DEBUG}" -) - idf_build_set_property(COMPILE_DEFINITIONS ${def} APPEND) -endforeach() - -if(CONFIG_LUA_NUMBER_INTEGRAL) - idf_build_set_property(COMPILE_DEFINITIONS -DLUA_NUMBER_INTEGRAL APPEND) -endif() +idf_build_set_property(COMPILE_DEFINITIONS -DLUA_USE_ESP APPEND) diff --git a/components/luac_cross/CMakeLists.txt b/components/luac_cross/CMakeLists.txt deleted file mode 100644 index e26024f5..00000000 --- a/components/luac_cross/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -idf_component_register(luac_cross) - -# Not sure why we can't directly depend on ${SDKCONFIG_HEADER} in our -# externalproject_add(), but them's the brakes... - -add_custom_command( - OUTPUT sdkconfig.h - COMMAND cp ${SDKCONFIG_HEADER} sdkconfig.h - DEPENDS ${SDKCONFIG_HEADER} - VERBATIM -) -add_custom_target(sdkconfig_h DEPENDS sdkconfig.h) - -externalproject_add(luac_cross_build - PREFIX ${BUILD_DIR}/luac_cross - SOURCE_DIR ${COMPONENT_DIR} - CONFIGURE_COMMAND "" - BUILD_COMMAND make -f ${COMPONENT_DIR}/Makefile BUILD_DIR_BASE=${BUILD_DIR} COMPONENT_PATH=${COMPONENT_DIR} CONFIG_LUA_OPTIMIZE_DEBUG=${CONFIG_LUA_OPTIMIZE_DEBUG} PYTHON=${PYTHON} - INSTALL_COMMAND "" - BUILD_ALWAYS 1 - DEPENDS sdkconfig_h -) diff --git a/components/luac_cross/Makefile b/components/luac_cross/Makefile deleted file mode 100644 index 7b5e3eb8..00000000 --- a/components/luac_cross/Makefile +++ /dev/null @@ -1,80 +0,0 @@ -all: build - -HOSTCC?=$(PYTHON) -m ziglang cc - -# zig cc (0.8.0 at least) seems to get itself all confused with its cache -# when we're running a separate path for dependencies, so we skip them for -# now as for most people they're not needed anyway. -ifeq ($(findstring zig,$(HOSTCC)),zig) - WITHOUT_DEPS:=1 -endif - -ifeq ($V,) - Q:=@ -endif - -LUAC_CFLAGS:= -I$(COMPONENT_PATH)/../uzlib -I$(COMPONENT_PATH)/../lua -I$(BUILD_DIR_BASE)/config -I$(COMPONENT_PATH)/../base_nodemcu/include -O2 -g -Wall -Wextra -LUAC_LDFLAGS:= -ldl -lm - -LUAC_DEFINES += -DLUA_CROSS_COMPILER -DLUA_USE_STDIO -ifneq ($(CONFIG_LUA_OPTIMIZE_DEBUG),) -LUAC_DEFINES += -DLUA_OPTIMIZE_DEBUG=$(CONFIG_LUA_OPTIMIZE_DEBUG) -endif - -vpath %.c $(COMPONENT_PATH) $(COMPONENT_PATH)/../lua $(COMPONENT_PATH)/../uzlib $(COMPONENT_PATH)/../base_nodemcu - -LUAC_LUACSRC:= \ - luac.c lflashimg.c loslib.c print.c liolib.c - -LUAC_LUASRC:= $(addprefix $(COMPONENT_PATH)/../lua/, \ - lapi.c lauxlib.c lbaselib.c lcode.c ldblib.c ldebug.c \ - ldo.c ldump.c lfunc.c lgc.c llex.c \ - lmathlib.c lmem.c loadlib.c lobject.c lopcodes.c lparser.c \ - lrotable.c lstate.c lstring.c lstrlib.c ltable.c ltablib.c \ - ltm.c lundump.c lvm.c lzio.c \ -) - -LUAC_UZSRC:= $(addprefix $(COMPONENT_PATH)/../uzlib/, \ - uzlib_deflate.c crc32.c \ -) - -LUAC_NODEMCUSRC:= $(addprefix $(COMPONENT_PATH)/../base_nodemcu/, \ - linit.c \ -) - -LUAC_BUILD_DIR:=$(BUILD_DIR_BASE)/luac_cross - -LUAC_OBJS:=$(LUAC_LUACSRC:%.c=$(LUAC_BUILD_DIR)/%.o) -LUAC_OBJS+=$(LUAC_LUASRC:$(COMPONENT_PATH)/../lua/%.c=$(LUAC_BUILD_DIR)/%.o) -LUAC_OBJS+=$(LUAC_UZSRC:$(COMPONENT_PATH)/../uzlib/%.c=$(LUAC_BUILD_DIR)/%.o) -LUAC_OBJS+=$(LUAC_NODEMCUSRC:$(COMPONENT_PATH)/../base_nodemcu/%.c=$(LUAC_BUILD_DIR)/%.o) - - -ifneq ($(WITHOUT_DEPS),1) -LUAC_DEPS:=$(LUAC_OBJS:%.o=%.d) -endif - -LUAC_CROSS:=$(LUAC_BUILD_DIR)/luac.cross - -$(LUAC_BUILD_DIR): - @mkdir -p "$@" - -$(LUAC_BUILD_DIR)/%.o: %.c | $(LUAC_BUILD_DIR) - @echo '[hostcc] $(notdir $@)' - $Q$(HOSTCC) $(LUAC_DEFINES) $(LUAC_CFLAGS) "$<" -c -o "$@" - -$(LUAC_BUILD_DIR)/%.d: SHELL=/bin/bash -$(LUAC_BUILD_DIR)/%.d: %.c | $(LUAC_BUILD_DIR) - @echo '[ dep] $<' - @rm -f "$@" - $Qset -eo pipefail; $(HOSTCC) $(LUAC_DEFINES) $(LUAC_CFLAGS) -M "$<" | sed 's,\($*\.o\)[ :]*,$(LUAC_BUILD_DIR)/\1 $@ : ,g' > "$@.tmp"; mv "$@.tmp" "$@" - -build: $(LUAC_DEPS) $(LUAC_CROSS) - -$(LUAC_CROSS): $(LUAC_OBJS) - @echo '[ link] $(notdir $@)' - $Q$(HOSTCC) $(LUAC_CFLAGS) $^ $(LUAC_LDFLAGS) -o "$@" - -ifneq ($(MAKECMDGOALS),clean) --include $(LUAC_DEPS) -endif diff --git a/components/modules-esp32/CMakeLists.txt b/components/modules-esp32/CMakeLists.txt deleted file mode 100644 index 10126238..00000000 --- a/components/modules-esp32/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ -if(NOT "${IDF_TARGET}" STREQUAL "esp32c3") - -# Globbing isn't recommended, but I dislike it less than having to edit -# this file whenever a new module source file springs into existence. -# Just remember to "idf.py reconfigure" (or do a clean build) to get -# cmake to pick up on the new (or removed) files. -file( - GLOB module_srcs - LIST_DIRECTORIES false - RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} - *.c -) - -idf_component_register( - SRCS ${module_srcs} - PRIV_INCLUDE_DIRS "." "${CMAKE_CURRENT_BINARY_DIR}" - PRIV_REQUIRES - "base_nodemcu" - "driver" - "driver_can" - "sdmmc" - "esp_eth" - "lua" - "modules" - "platform" - "soc" -) - -# Match up all the module source files with their corresponding Kconfig -# option in the form NODEMCU_CMODULE_ and if enabled, add a -# "-u _module_selected1" option to force the linker to include -# the module. See components/core/include/module.h for further details on -# how this works. -set(modules_enabled) -foreach(module_src ${module_srcs}) - string(REPLACE ".c" "" module_name ${module_src}) - string(TOUPPER ${module_name} module_ucase) - set(mod_opt "CONFIG_NODEMCU_CMODULE_${module_ucase}") - if (${${mod_opt}}) - list(APPEND modules_enabled ${module_ucase}) - endif() -endforeach() -message("Including the following modules: ${modules_enabled}") - -foreach(mod ${modules_enabled}) - target_link_libraries(${COMPONENT_LIB} "-u ${mod}_module_selected1") -endforeach() - -endif() diff --git a/components/modules-esp32/Kconfig b/components/modules-esp32/Kconfig deleted file mode 100644 index b8716f8d..00000000 --- a/components/modules-esp32/Kconfig +++ /dev/null @@ -1,49 +0,0 @@ -menu "NodeMCU modules (ESP32/ESP32-S specific)" -depends on IDF_TARGET != "ESP32C3" - - config NODEMCU_CMODULE_CAN - bool "CAN module" - default "n" - help - Includes the can module. - - config NODEMCU_CMODULE_DAC - bool "DAC module" - default "n" - help - Includes the dac module. - - config NODEMCU_CMODULE_ETH - select ETH_USE_ESP32_EMAC - bool "Ethernet module" - default "n" - help - Includes the ethernet module. - - config NODEMCU_CMODULE_I2S - bool "I2S module" - default "n" - help - Includes the I2S module. - - config NODEMCU_CMODULE_PULSECNT - bool "Pulse counter module" - default "n" - help - Includes the pulse counter module to use ESP32's built-in pulse - counting hardware. - - config NODEMCU_CMODULE_SDMMC - bool "SD-MMC module" - default "n" - help - Includes the sdmmc module. - - config NODEMCU_CMODULE_TOUCH - bool "Touch module" - default "n" - help - Includes the touch module to use ESP32's built-in touch sensor - hardware. - -endmenu diff --git a/components/modules/CMakeLists.txt b/components/modules/CMakeLists.txt index fabc549c..4aaf296e 100644 --- a/components/modules/CMakeLists.txt +++ b/components/modules/CMakeLists.txt @@ -1,14 +1,68 @@ -# Globbing isn't recommended, but I dislike it less than having to edit -# this file whenever a new module source file springs into existence. -# Just remember to "idf.py reconfigure" (or do a clean build) to get -# cmake to pick up on the new (or removed) files. -file( - GLOB module_srcs - LIST_DIRECTORIES false - RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} - *.c +# Modules common to all chips +set(module_srcs + "adc.c" + "bit.c" + "bthci.c" + "common.c" + "crypto.c" + "dht.c" + "encoder.c" + "file.c" + "gpio.c" + "http.c" + "i2c.c" + "i2c_hw_master.c" + "i2c_hw_slave.c" + "ledc.c" + "mqtt.c" + "net.c" + "node.c" + "otaupgrade.c" + "ow.c" + "pipe.c" + "qrcodegen.c" + "sigma_delta.c" + "sjson.c" + "sodium.c" + "spi.c" + "spi_master.c" + "struct.c" + "time.c" + "tmr.c" + "u8g2.c" + "uart.c" + "ucg.c" + "wifi.c" + "wifi_ap.c" + "wifi_common.c" + "wifi_sta.c" + "ws2812.c" ) +# Chip specific modules, per module. +# List source files for each applicable chip. +if(IDF_TARGET STREQUAL "esp32") + list(APPEND module_srcs + "can.c" + "dac.c" + "eth.c" + "i2s.c" + "pulsecnt.c" + "sdmmc.c" + "touch.c" + ) +elseif(IDF_TARGET STREQUAL "esp32s2") + list(APPEND module_srcs + "dac.c" + ) +elseif(IDF_TARGET STREQUAL "esp32s3") + list(APPEND module_srcs + ) +elseif(IDF_TARGET STREQUAL "esp32c3") + list(APPEND module_srcs + ) +endif() + idf_component_register( SRCS ${module_srcs} INCLUDE_DIRS "." "${CMAKE_CURRENT_BINARY_DIR}" diff --git a/components/modules/Kconfig b/components/modules/Kconfig index c949d2a8..1d0098d4 100644 --- a/components/modules/Kconfig +++ b/components/modules/Kconfig @@ -21,12 +21,26 @@ menu "NodeMCU modules" help Includes the simple BlueTooth HCI module. + config NODEMCU_CMODULE_CAN + depends on CONFIG_IDF_TARGET_ESP32 + bool "CAN module" + default "n" + help + Includes the can module. + config NODEMCU_CMODULE_CRYPTO bool "Crypto module" default "n" help Includes the crypto module. + config NODEMCU_CMODULE_DAC + depends on IDF_TARGET_ESP32 || IDF_TARGET_ESP32S2 + bool "DAC module" + default "n" + help + Includes the dac module. + config NODEMCU_CMODULE_DHT bool "DHT11/21/22/AM2301/AM2302 module" default "n" @@ -40,6 +54,14 @@ menu "NodeMCU modules" Includes the encoder module. This provides hex and base64 encoding and decoding functionality. + config NODEMCU_CMODULE_ETH + depends on IDF_TARGET_ESP32 + select ETH_USE_ESP32_EMAC + bool "Ethernet module" + default "n" + help + Includes the ethernet module. + config NODEMCU_CMODULE_FILE bool "File module" default "y" @@ -64,6 +86,13 @@ menu "NodeMCU modules" help Includes the I2C module (recommended). + config NODEMCU_CMODULE_I2S + depends on IDF_TARGET_ESP32 + bool "I2S module" + default "n" + help + Includes the I2S module. + config NODEMCU_CMODULE_LEDC bool "LEDC module" default "n" @@ -102,6 +131,20 @@ menu "NodeMCU modules" requires a partition table with at least two OTA partitions, plus the OTA data partition. See the IDF documentation for details. + config NODEMCU_CMODULE_PIPE + bool "Pipe module" + default "y" + help + Includes the pipe module (required by our Lua VM). + + config NODEMCU_CMODULE_PULSECNT + depends on IDF_TARGET_ESP32 + bool "Pulse counter module" + default "n" + help + Includes the pulse counter module to use ESP32's built-in pulse + counting hardware. + config NODEMCU_CMODULE_QRCODEGEN bool "QR Code Generator module" default "n" @@ -109,6 +152,13 @@ menu "NodeMCU modules" Includes the QR Code Generator from https://www.nayuki.io/page/qr-code-generator-library + config NODEMCU_CMODULE_SDMMC + depends on IDF_TARGET_ESP32 + bool "SD-MMC module" + default "n" + help + Includes the sdmmc module. + config NODEMCU_CMODULE_SIGMA_DELTA bool "Sigma-Delta module" default "n" @@ -147,6 +197,14 @@ menu "NodeMCU modules" help Includes the timer module (recommended). + config NODEMCU_CMODULE_TOUCH + depends on IDF_TARGET_ESP32 + bool "Touch module" + default "n" + help + Includes the touch module to use ESP32's built-in touch sensor + hardware. + config NODEMCU_CMODULE_U8G2 bool "U8G2 module" default "n" @@ -182,4 +240,10 @@ menu "NodeMCU modules" help Includes the time module. + config NODEMCU_CMODULE_UART + bool "UART module" + default y + help + Includes the UART module (required by our Lua VM). + endmenu diff --git a/components/modules/adc.c b/components/modules/adc.c index d0c60c49..86af249c 100644 --- a/components/modules/adc.c +++ b/components/modules/adc.c @@ -60,7 +60,7 @@ static int read_hall_sensor( lua_State *L ) } // Module function map -LROT_BEGIN(adc) +LROT_BEGIN(adc, NULL, 0) LROT_FUNCENTRY( setwidth, adc_set_width ) LROT_FUNCENTRY( setup, adc_setup ) LROT_FUNCENTRY( read, adc_read ) diff --git a/components/modules/bit.c b/components/modules/bit.c index b7b62cc0..c5dafd69 100644 --- a/components/modules/bit.c +++ b/components/modules/bit.c @@ -119,7 +119,7 @@ static int bit_clear( lua_State* L ) return 1; } -LROT_BEGIN(bit) +LROT_BEGIN(bit, NULL, 0) LROT_FUNCENTRY( bnot, bit_bnot ) LROT_FUNCENTRY( band, bit_band ) LROT_FUNCENTRY( bor, bit_bor ) diff --git a/components/modules/bthci.c b/components/modules/bthci.c index 9fde97e4..ae3aa3bd 100644 --- a/components/modules/bthci.c +++ b/components/modules/bthci.c @@ -216,7 +216,7 @@ static int send_hci_command (lua_State *L, uint8_t *data, unsigned len) if (lua_gettop (L) > 0 && !lua_isnil (L, -1)) { cmd_q[i].cmd = cmd; - luaL_checkanyfunction (L, -1); + luaL_checkfunction (L, -1); lua_pushvalue (L, -1); cmd_q[i].cb_ref = luaL_ref (L, LUA_REGISTRYINDEX); } @@ -271,7 +271,7 @@ static void invoke_cmd_q_callback ( else lua_pushnil (L); // no error lua_pushlstring (L, (const char *)data, len ); // extra bytes, if any - lua_call (L, 2, 0); + luaL_pcallx (L, 2, 0); } } @@ -316,7 +316,7 @@ static void handle_hci_event (task_param_t arg, task_prio_t prio) uint8_t *report = &hci_event[5]; lua_rawgeti (L, LUA_REGISTRYINDEX, adv_rep_cb_ref); lua_pushlstring (L, (const char *)report, len - 2); - lua_call (L, 1, 0); + luaL_pcallx (L, 1, 0); } } } @@ -424,7 +424,7 @@ static int lbthci_adv_setparams (lua_State *L) uint8_t adv_chan_map = ADV_CHAN_ALL; uint8_t adv_filter_pol = ADV_FILTER_NONE; - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); lua_settop (L, 2); // Pad a nil into the function slot if necessary get_opt_field_int (1, adv_interval_min, "interval_min"); @@ -501,7 +501,7 @@ static int lbthci_scan_setparams (lua_State *L) uint8_t own_addr_type = 0; uint8_t filter_policy = 0; - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); lua_settop (L, 2); // Pad a nil into the function slot if necessary get_opt_field_int (1, scan_mode, "mode"); @@ -557,7 +557,7 @@ static int lbthci_rawhci (lua_State *L) } -LROT_BEGIN(bthci_adv) +LROT_BEGIN(bthci_adv, NULL, 0) LROT_FUNCENTRY( enable, lbthci_adv_enable ) LROT_FUNCENTRY( setdata, lbthci_adv_setdata ) LROT_FUNCENTRY( setparams, lbthci_adv_setparams ) @@ -576,14 +576,14 @@ LROT_BEGIN(bthci_adv) LROT_END(bthci_adv, NULL, 0) -LROT_BEGIN(bthci_scan) +LROT_BEGIN(bthci_scan, NULL, 0) LROT_FUNCENTRY( enable, lbthci_scan ) LROT_FUNCENTRY( setparams, lbthci_scan_setparams ) LROT_FUNCENTRY( on, lbthci_scan_on ) LROT_END(bthci_scan, NULL, 0) -LROT_BEGIN(bthci) +LROT_BEGIN(bthci, NULL, 0) LROT_FUNCENTRY( rawhci, lbthci_rawhci ) LROT_FUNCENTRY( reset, lbthci_reset ) LROT_TABENTRY ( adv, bthci_adv ) diff --git a/components/modules-esp32/can.c b/components/modules/can.c similarity index 97% rename from components/modules-esp32/can.c rename to components/modules/can.c index e9576a75..6f748057 100644 --- a/components/modules-esp32/can.c +++ b/components/modules/can.c @@ -46,7 +46,7 @@ static void can_data_task( task_param_t param, task_prio_t prio ) { lua_pushinteger(L, frame->MsgID); lua_pushlstring(L, (char *)frame->data.u8, frame->DLC); free( frame ); - lua_call(L, 3, 0); + luaL_pcallx(L, 3, 0); } // RTOS @@ -77,9 +77,9 @@ static int can_setup( lua_State *L ) { if(xCanTaskHandle != NULL) luaL_error( L, "Stop CAN before setup" ); - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); - luaL_checkanyfunction (L, 2); + luaL_checkfunction (L, 2); lua_settop (L, 2); if(can_on_received != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, can_on_received); can_on_received = luaL_ref(L, LUA_REGISTRYINDEX); @@ -148,7 +148,7 @@ static int can_send( lua_State *L ) } // Module function map -LROT_BEGIN(can) +LROT_BEGIN(can, NULL, 0) LROT_FUNCENTRY( setup, can_setup ) LROT_FUNCENTRY( start, can_start ) LROT_FUNCENTRY( stop, can_stop ) diff --git a/components/modules/common.h b/components/modules/common.h index 1de9df6c..f324cb71 100644 --- a/components/modules/common.h +++ b/components/modules/common.h @@ -2,6 +2,9 @@ #define modules_common_h #include "lua.h" +#include +#include +#include /* Some common code shared between modules */ diff --git a/components/modules/crypto.c b/components/modules/crypto.c index 42d96fa3..524d6b56 100644 --- a/components/modules/crypto.c +++ b/components/modules/crypto.c @@ -153,22 +153,22 @@ static int crypto_hash_gc(lua_State* L) { } // The following table defines methods of the hasher object -LROT_BEGIN(crypto_hasher) - LROT_FUNCENTRY(update, crypto_hash_update) - LROT_FUNCENTRY(finalize, crypto_hash_finalize) +LROT_BEGIN(crypto_hasher, NULL, 0) LROT_FUNCENTRY(__gc, crypto_hash_gc) LROT_TABENTRY(__index, crypto_hasher) + LROT_FUNCENTRY(update, crypto_hash_update) + LROT_FUNCENTRY(finalize, crypto_hash_finalize) LROT_END(crypto_hasher, NULL, 0) // This table defines the functions of the crypto module: -LROT_BEGIN(crypto) +LROT_BEGIN(crypto, NULL, 0) LROT_FUNCENTRY(new_hash, crypto_new_hash) LROT_FUNCENTRY(new_hmac, crypto_new_hmac) LROT_END(crypto, NULL, 0) // luaopen_crypto is the crypto module initialization function int luaopen_crypto(lua_State* L) { - luaL_rometatable(L, HASH_METATABLE, (void*)crypto_hasher_map); // create metatable for crypto.hash + luaL_rometatable(L, HASH_METATABLE, LROT_TABLEREF(crypto_hasher)); // create metatable for crypto.hash return 0; } diff --git a/components/modules-esp32/dac.c b/components/modules/dac.c similarity index 98% rename from components/modules-esp32/dac.c rename to components/modules/dac.c index 449a4d62..769c9975 100644 --- a/components/modules-esp32/dac.c +++ b/components/modules/dac.c @@ -52,7 +52,7 @@ static int ldac_write( lua_State *L ) // Module function map -LROT_BEGIN(dac) +LROT_BEGIN(dac, NULL, 0) LROT_FUNCENTRY( enable, ldac_enable ) LROT_FUNCENTRY( disable, ldac_disable ) LROT_FUNCENTRY( write, ldac_write ) diff --git a/components/modules/dht.c b/components/modules/dht.c index c348ad00..73e00daa 100644 --- a/components/modules/dht.c +++ b/components/modules/dht.c @@ -91,7 +91,7 @@ static int ldht_read2x( lua_State *L ) } -LROT_BEGIN(dht) +LROT_BEGIN(dht, NULL, 0) LROT_FUNCENTRY( read11, ldht_read11 ) LROT_FUNCENTRY( read2x, ldht_read2x ) LROT_NUMENTRY ( OK, LDHT_OK ) diff --git a/components/modules/encoder.c b/components/modules/encoder.c index 53c2fae5..8ebb3f9c 100644 --- a/components/modules/encoder.c +++ b/components/modules/encoder.c @@ -116,7 +116,7 @@ static uint8_t *fromHex ( lua_State* L, const uint8_t *msg, size_t *len){ } else if (*p >= 'A' && *p <= 'F') { b = *p++ - ('A' - 10); } else { - luaM_freearray(L, out, *len, uint8_t); + luaN_freearray(L, out, *len); luaL_error (L, "Invalid hex string"); __builtin_unreachable (); } @@ -140,7 +140,7 @@ static int do_func (lua_State *L, uint8_t * (*conv_func)(lua_State *, const uint if (output) { lua_pushlstring(L, (char *)output, len); - luaM_freearray(L, output, len, uint8_t); + luaN_freearray(L, output, len); } else { lua_pushstring(L, ""); } @@ -156,7 +156,7 @@ static int do_func (lua_State *L, uint8_t * (*conv_func)(lua_State *, const uint DECLARE_FUNCTION(toHex); // Module function map -LROT_BEGIN(encoder) +LROT_BEGIN(encoder, NULL, 0) LROT_FUNCENTRY(fromBase64, encoder_fromBase64) LROT_FUNCENTRY(toBase64, encoder_toBase64) LROT_FUNCENTRY(fromHex, encoder_fromHex) diff --git a/components/modules-esp32/eth.c b/components/modules/eth.c similarity index 98% rename from components/modules-esp32/eth.c rename to components/modules/eth.c index 50e7cbd4..d9f0ff49 100644 --- a/components/modules-esp32/eth.c +++ b/components/modules/eth.c @@ -119,7 +119,7 @@ static void on_event(esp_event_base_t base, int32_t id, const void *data) lua_pushstring( L, events[idx].name ); lua_createtable( L, 0, 5 ); events[idx].fill_cb_arg( L, data ); - lua_pcall( L, 2, 0, 0 ); + luaL_pcallx( L, 2, 0 ); lua_settop( L, top ); } @@ -184,7 +184,7 @@ static int leth_on( lua_State *L ) { const char *event_name = luaL_checkstring( L, 1 ); if (!lua_isnoneornil( L, 2 )) { - luaL_checkanyfunction( L, 2 ); + luaL_checkfunction( L, 2 ); } lua_settop( L, 2 ); @@ -274,7 +274,7 @@ cleanup_mac_phy: } -LROT_BEGIN(eth) +LROT_BEGIN(eth, NULL, 0) LROT_FUNCENTRY( init, leth_init ) LROT_FUNCENTRY( on, leth_on ) LROT_FUNCENTRY( get_speed, leth_get_speed ) diff --git a/components/modules/file.c b/components/modules/file.c index b96a7e5d..658bada9 100644 --- a/components/modules/file.c +++ b/components/modules/file.c @@ -58,7 +58,7 @@ static int32_t file_rtc_cb( vfs_time *tm ) lua_State *L = lua_getstate(); lua_rawgeti( L, LUA_REGISTRYINDEX, rtc_cb_ref ); - lua_call( L, 0, 1 ); + luaL_pcallx( L, 0, 1 ); if (lua_type( L, lua_gettop( L ) ) == LUA_TTABLE) { table2tm( L, tm ); @@ -86,8 +86,7 @@ static int file_on(lua_State *L) case ON_RTC: luaL_unref(L, LUA_REGISTRYINDEX, rtc_cb_ref); - if ((lua_type(L, 2) == LUA_TFUNCTION) || - (lua_type(L, 2) == LUA_TLIGHTFUNCTION)) { + if (lua_isfunction(L, 2)) { lua_pushvalue(L, 2); // copy argument (func) to the top of stack rtc_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX); vfs_register_rtc_cb(file_rtc_cb); @@ -430,7 +429,7 @@ static int file_g_read( lua_State* L, int n, int16_t end_char, int fd ) } if (heap_mem) { - luaM_freearray(L, heap_mem, bufsize, char); + luaN_freearray(L, heap_mem, bufsize); } if (err){ @@ -550,7 +549,9 @@ static int file_chdir( lua_State *L ) } #endif -LROT_BEGIN(file_obj) +LROT_BEGIN(file_obj, NULL, 0) + LROT_FUNCENTRY( __gc, file_obj_free ) + LROT_TABENTRY ( __index, file_obj ) LROT_FUNCENTRY( close, file_close ) LROT_FUNCENTRY( read, file_read ) LROT_FUNCENTRY( readline, file_readline ) @@ -558,12 +559,10 @@ LROT_BEGIN(file_obj) LROT_FUNCENTRY( writeline, file_writeline ) LROT_FUNCENTRY( seek, file_seek ) LROT_FUNCENTRY( flush, file_flush ) - LROT_FUNCENTRY( __gc, file_obj_free ) - LROT_TABENTRY ( __index, file_obj ) LROT_END(file_obj, NULL, 0) // Module function map -LROT_BEGIN(file) +LROT_BEGIN(file, NULL, 0) LROT_FUNCENTRY( list, file_list ) LROT_FUNCENTRY( open, file_open ) LROT_FUNCENTRY( close, file_close ) @@ -589,7 +588,7 @@ LROT_BEGIN(file) LROT_END(file, NULL, 0) int luaopen_file( lua_State *L ) { - luaL_rometatable( L, "file.obj", (void *)file_obj_map ); + luaL_rometatable( L, "file.obj", LROT_TABLEREF(file_obj)); return 0; } diff --git a/components/modules/gpio.c b/components/modules/gpio.c index b1035ec9..2c487a04 100644 --- a/components/modules/gpio.c +++ b/components/modules/gpio.c @@ -79,7 +79,7 @@ static int lgpio_config (lua_State *L) luaL_checkstack (L, 5, "out of mem"); for (int i = 1; i <= n; ++i) { - luaL_checkanytable (L, i); + luaL_checktable (L, i); gpio_config_t cfg; cfg.intr_type = GPIO_INTR_DISABLE; @@ -141,7 +141,7 @@ static int lgpio_trig (lua_State *L) int gpio = luaL_checkint (L, 1); int intr_type = luaL_optint (L, 2, GPIO_INTR_DISABLE); if (!lua_isnoneornil (L, 3)) - luaL_checkanyfunction (L, 3); + luaL_checkfunction (L, 3); lua_settop (L, 3); @@ -235,7 +235,7 @@ static void nodemcu_gpio_callback_task (task_param_t param, task_prio_t prio) lua_rawgeti (L, LUA_REGISTRYINDEX, gpio_cb_refs[gpio]); lua_pushinteger (L, gpio); lua_pushinteger (L, level); - lua_call (L, 2, 0); + luaL_pcallx (L, 2, 0); gpio_intr_enable (gpio); } } @@ -250,7 +250,7 @@ static int nodemcu_gpio_init (lua_State *L) } -LROT_BEGIN(lgpio) +LROT_BEGIN(lgpio, NULL, 0) LROT_FUNCENTRY( config, lgpio_config ) LROT_FUNCENTRY( read, lgpio_read ) LROT_FUNCENTRY( trig, lgpio_trig ) diff --git a/components/modules/http.c b/components/modules/http.c index 310d0dd4..e6f80753 100644 --- a/components/modules/http.c +++ b/components/modules/http.c @@ -335,7 +335,7 @@ static int make_callback(lhttp_context_t *context, int id, void *data, size_t da // Lowercase all header names luaL_getmetafield(L, -1, "lower"); lua_insert(L, -2); - lua_call(L, 1, 1); + luaL_pcallx(L, 1, 1); char *val = item->data + item->len + 1; lua_pushstring(L, val); lua_settable(L, -3); @@ -366,7 +366,7 @@ static int make_callback(lhttp_context_t *context, int id, void *data, size_t da if (id != HTTP_REQUEST_COMPLETE) { context_setflag(context, InCallback); } - int err = lua_pcall(L, lua_gettop(L) - 1, 1, 0); + int err = luaL_pcallx(L, lua_gettop(L) - 1, 1); context_clearflag(context, InCallback); if (err) { const char *msg = lua_type(L, -1) == LUA_TSTRING ? lua_tostring(L, -1) : ""; @@ -657,7 +657,7 @@ static int http_accumulate_complete(lua_State *L) context_setref(L, context, HeadersCallback); } else { lua_rawgeti(L, cache_table, 2); // headers - lua_call(L, 3, 0); + luaL_pcallx(L, 3, 0); } // unset this since it contains a reference to the context and would prevent the context to be garbage collected context_unsetref(L, context,CompleteCallback); @@ -692,7 +692,7 @@ static int make_oneshot_request(lua_State *L, int callback_idx) // Finally, call request lua_pushcfunction(L, http_lapi_request); lua_pushvalue(L, -2); // context - lua_call(L, 1, 0); + luaL_pcallx(L, 1, 0); if (async) { return 0; @@ -736,7 +736,7 @@ static int http_lapi_get(lua_State *L) lua_pushinteger(L, HTTP_METHOD_GET); lua_pushvalue(L, 2); // options - lua_call(L, 3, 1); // returns context + luaL_pcallx(L, 3, 1); // returns context return make_oneshot_request(L, 3); } @@ -768,17 +768,17 @@ static int http_lapi_post(lua_State *L) lua_pushinteger(L, HTTP_METHOD_POST); lua_pushvalue(L, 2); // options - lua_call(L, 3, 1); // returns context + luaL_pcallx(L, 3, 1); // returns context lua_pushcfunction(L, http_lapi_setpostdata); lua_pushvalue(L, -2); // context lua_pushvalue(L, 3); // body - lua_call(L, 2, 0); + luaL_pcallx(L, 2, 0); return make_oneshot_request(L, 4); // 4 = callback idx } -LROT_BEGIN(http) +LROT_BEGIN(http, NULL, 0) LROT_FUNCENTRY(createConnection, http_lapi_createConnection) LROT_NUMENTRY (GET, HTTP_METHOD_GET) LROT_NUMENTRY (POST, HTTP_METHOD_POST) @@ -790,7 +790,9 @@ LROT_BEGIN(http) LROT_FUNCENTRY(post, http_lapi_post) LROT_END(http, NULL, 0) -LROT_BEGIN(http_context) +LROT_BEGIN(http_context, NULL, 0) + LROT_FUNCENTRY(__gc, context_gc) + LROT_TABENTRY (__index, http_context) LROT_FUNCENTRY(on, http_lapi_on) LROT_FUNCENTRY(request, http_lapi_request) LROT_FUNCENTRY(setmethod, http_lapi_setmethod) @@ -799,13 +801,11 @@ LROT_BEGIN(http_context) LROT_FUNCENTRY(setpostdata, http_lapi_setpostdata) LROT_FUNCENTRY(close, context_close) LROT_FUNCENTRY(ack, http_lapi_ack) - LROT_FUNCENTRY(__gc, context_gc) - LROT_TABENTRY (__index, http_context) LROT_END(http_context, NULL, 0) static int luaopen_http(lua_State *L) { - luaL_rometatable(L, http_context_mt, (void *)http_context_map); + luaL_rometatable(L, http_context_mt, LROT_TABLEREF(http_context)); lhttp_request_task_id = task_get_id(lhttp_request_task); lhttp_event_task_id = task_get_id(lhttp_event_task); return 0; diff --git a/components/modules/i2c.c b/components/modules/i2c.c index a07a7643..95f0e004 100644 --- a/components/modules/i2c.c +++ b/components/modules/i2c.c @@ -210,7 +210,7 @@ static int i2c_read( lua_State *L ) } } -LROT_BEGIN(i2c) +LROT_BEGIN(i2c, NULL, 0) LROT_FUNCENTRY( setup, i2c_setup ) LROT_FUNCENTRY( start, i2c_start ) LROT_FUNCENTRY( stop, i2c_stop ) diff --git a/components/modules/i2c_common.h b/components/modules/i2c_common.h index 14cf241b..3a3958da 100644 --- a/components/modules/i2c_common.h +++ b/components/modules/i2c_common.h @@ -29,7 +29,7 @@ int li2c_hw_master_transfer( lua_State *L ); // *************************************************************************** // Hardware slave prototypes // -LROT_EXTERN(li2c_slave); +extern LROT_TABLE(li2c_slave); void li2c_hw_slave_init( lua_State *L ); diff --git a/components/modules/i2c_hw_master.c b/components/modules/i2c_hw_master.c index b9bb9c60..f0709292 100644 --- a/components/modules/i2c_hw_master.c +++ b/components/modules/i2c_hw_master.c @@ -4,6 +4,7 @@ #include "lmem.h" #include "driver/i2c.h" #include "soc/i2c_reg.h" +#include "hal/i2c_ll.h" #include "i2c_common.h" @@ -110,7 +111,7 @@ static void i2c_transfer_task( task_param_t param, task_prio_t prio ) lua_pushnil( L ); } lua_pushboolean( L, job->err == ESP_OK ); - lua_call(L, 2, 0); + luaL_pcallx(L, 2, 0); } // free all memory @@ -219,7 +220,7 @@ int li2c_hw_master_setup( lua_State *L, unsigned id, unsigned sda, unsigned scl, int timeoutcycles; i2c_lua_checkerr( L, i2c_get_timeout( port, &timeoutcycles) ); timeoutcycles = timeoutcycles * stretchfactor; - luaL_argcheck( L, timeoutcycles * stretchfactor <= I2C_TIME_OUT_REG_V, 5, "excessive stretch factor" ); + luaL_argcheck( L, timeoutcycles * stretchfactor <= I2C_LL_MAX_TIMEOUT, 5, "excessive stretch factor" ); i2c_lua_checkerr( L, i2c_set_timeout( port, timeoutcycles) ); i2c_lua_checkerr( L, i2c_driver_install( port, cfg.mode, 0, 0, 0 )); @@ -319,7 +320,7 @@ int li2c_hw_master_transfer( lua_State *L ) luaL_error( L, "no commands scheduled" ); stack++; - if (lua_isfunction( L, stack ) || lua_islightfunction( L, stack )) { + if (lua_isfunction( L, stack )) { lua_pushvalue( L, stack ); // copy argument (func) to the top of stack luaL_unref( L, LUA_REGISTRYINDEX, job->cb_ref ); job->cb_ref = luaL_ref(L, LUA_REGISTRYINDEX); diff --git a/components/modules/i2c_hw_slave.c b/components/modules/i2c_hw_slave.c index 1564de9a..c5790f70 100644 --- a/components/modules/i2c_hw_slave.c +++ b/components/modules/i2c_hw_slave.c @@ -109,7 +109,7 @@ static void i2c_receive_task( task_param_t param, task_prio_t prio ) } else { lua_pushnil( L ); } - lua_call(L, 2, 0); + luaL_pcallx(L, 2, 0); } // free all memory @@ -173,7 +173,7 @@ static int li2c_slave_setup( lua_State *L ) ud->port = port; int stack = 1; - luaL_checkanytable( L, ++stack ); + luaL_checktable( L, ++stack ); lua_settop( L, stack ); i2c_config_t cfg; @@ -305,7 +305,7 @@ static int li2c_slave_on( lua_State *L ) luaL_unref( L, LUA_REGISTRYINDEX, ud->receivedcb_ref ); ++stack; - if (lua_isfunction( L, stack ) || lua_islightfunction( L, stack )) { + if (lua_isfunction( L, stack )) { lua_pushvalue( L, stack ); // copy argument (func) to the top of stack ud->receivedcb_ref = luaL_ref( L, LUA_REGISTRYINDEX ); } @@ -318,7 +318,7 @@ static int li2c_slave_on( lua_State *L ) } -LROT_PUBLIC_BEGIN(li2c_slave) +LROT_BEGIN(li2c_slave, NULL, 0) LROT_FUNCENTRY( on, li2c_slave_on ) LROT_FUNCENTRY( setup, li2c_slave_setup ) LROT_FUNCENTRY( send, li2c_slave_send ) diff --git a/components/modules-esp32/i2s.c b/components/modules/i2s.c similarity index 99% rename from components/modules-esp32/i2s.c rename to components/modules/i2s.c index 7fd9720d..88fab401 100644 --- a/components/modules-esp32/i2s.c +++ b/components/modules/i2s.c @@ -55,7 +55,7 @@ static void i2s_tx_task( task_param_t param, task_prio_t prio ) { lua_rawgeti(L, LUA_REGISTRYINDEX, is->cb); lua_pushinteger( L, i2s_id ); lua_pushstring( L, "tx" ); - lua_call( L, 2, 0 ); + luaL_pcallx( L, 2, 0 ); } } @@ -68,7 +68,7 @@ static void i2s_rx_task( task_param_t param, task_prio_t prio ) { lua_rawgeti(L, LUA_REGISTRYINDEX, is->cb); lua_pushinteger( L, i2s_id ); lua_pushstring( L, "rx" ); - lua_call( L, 2, 0 ); + luaL_pcallx( L, 2, 0 ); } } @@ -134,7 +134,7 @@ static int node_i2s_start( lua_State *L ) int top = lua_gettop( L ); - luaL_checkanytable (L, 2); + luaL_checktable (L, 2); i2s_config_t i2s_config; memset( &i2s_config, 0, sizeof( i2s_config ) ); @@ -309,7 +309,7 @@ static int node_i2s_mute( lua_State *L ) // Module function map -LROT_BEGIN(i2s) +LROT_BEGIN(i2s, NULL, 0) LROT_FUNCENTRY( start, node_i2s_start ) LROT_FUNCENTRY( stop, node_i2s_stop ) LROT_FUNCENTRY( read, node_i2s_read ) diff --git a/components/modules/ledc.c b/components/modules/ledc.c index 1dab60c4..515580be 100644 --- a/components/modules/ledc.c +++ b/components/modules/ledc.c @@ -17,7 +17,7 @@ typedef struct { static int lledc_new_channel( lua_State *L ) { const int top = lua_gettop(L); - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); /* Setup timer */ ledc_timer_config_t ledc_timer; @@ -231,7 +231,8 @@ static int lledc_set_fade( lua_State *L ) { } // Module function map -LROT_BEGIN(ledc_channel) +LROT_BEGIN(ledc_channel, NULL, 0) + LROT_TABENTRY ( __index, ledc_channel ) LROT_FUNCENTRY( getduty, lledc_get_duty ) LROT_FUNCENTRY( setduty, lledc_set_duty ) LROT_FUNCENTRY( getfreq, lledc_get_freq ) @@ -245,11 +246,9 @@ LROT_BEGIN(ledc_channel) LROT_FUNCENTRY( fadewithtime, lledc_set_fade_with_time ) LROT_FUNCENTRY( fadewithstep, lledc_set_fade_with_step ) LROT_FUNCENTRY( fade, lledc_set_fade ) - - LROT_TABENTRY ( __index, ledc_channel ) LROT_END(ledc_channel, NULL, 0) -LROT_BEGIN(ledc) +LROT_BEGIN(ledc, NULL, 0) LROT_FUNCENTRY( newChannel, lledc_new_channel ) #if SOC_LEDC_SUPPORT_HS_MODE @@ -295,7 +294,7 @@ LROT_BEGIN(ledc) LROT_END(ledc, NULL, 0) int luaopen_ledc(lua_State *L) { - luaL_rometatable(L, "ledc.channel", (void *)ledc_channel_map); // create metatable for ledc.channel + luaL_rometatable(L, "ledc.channel", LROT_TABLEREF(ledc_channel)); // create metatable for ledc.channel return 0; } diff --git a/components/modules/mqtt.c b/components/modules/mqtt.c index 43bb9d23..9b92f22f 100644 --- a/components/modules/mqtt.c +++ b/components/modules/mqtt.c @@ -119,7 +119,7 @@ static void event_connected(lua_State* L, mqtt_context_t* mqtt_context, esp_mqtt luaX_push_weak_ref(L, mqtt_context->self); // push a reference to the client (first parameter) ESP_LOGD(TAG, "CB:connect: calling registered one-shot connect callback"); - int res = lua_pcall(L, 1, 0, 0); //call the connect callback: function(client) + int res = luaL_pcallx(L, 1, 0); //call the connect callback: function(client) if (res != 0) ESP_LOGD(TAG, "CB:connect: Error when calling one-shot connect callback - (%d) %s", res, luaL_checkstring(L, -1)); @@ -133,7 +133,7 @@ static void event_connected(lua_State* L, mqtt_context_t* mqtt_context, esp_mqtt ESP_LOGD(TAG, "CB:connect: calling registered standard connect callback"); lua_rawgeti(L, LUA_REGISTRYINDEX, mqtt_context->on_connect_cb); // push the callback function reference to the stack luaX_push_weak_ref(L, mqtt_context->self); // push a reference to the client (first parameter) - int res = lua_pcall(L, 1, 0, 0); //call the connect callback: function(client) + int res = luaL_pcallx(L, 1, 0); //call the connect callback: function(client) if (res != 0) ESP_LOGD(TAG, "CB:connect: Error when calling connect callback - (%d) %s", res, luaL_checkstring(L, -1)); } @@ -156,7 +156,7 @@ static void event_disconnected(lua_State* L, mqtt_context_t* mqtt_context, esp_m lua_pushinteger(L, -6); // esp sdk mqtt lib does not provide reason codes. Push "-6" to be backward compatible with ESP8266 API ESP_LOGD(TAG, "CB:disconnect: calling registered one-shot disconnect callback"); - int res = lua_pcall(L, 2, 0, 0); //call the disconnect callback with 2 parameters: function(client, reason) + int res = luaL_pcallx(L, 2, 0); //call the disconnect callback with 2 parameters: function(client, reason) if (res != 0) ESP_LOGD(TAG, "CB:disconnect: Error when calling one-shot disconnect callback - (%d) %s", res, luaL_checkstring(L, -1)); @@ -170,7 +170,7 @@ static void event_disconnected(lua_State* L, mqtt_context_t* mqtt_context, esp_m ESP_LOGD(TAG, "CB:disconnect: calling registered standard on_offline_cb callback"); lua_rawgeti(L, LUA_REGISTRYINDEX, mqtt_context->on_offline_cb); // push the callback function reference to the stack luaX_push_weak_ref(L, mqtt_context->self); // push a reference to the client (first parameter) - int res = lua_pcall(L, 1, 0, 0); //call the offline callback: function(client) + int res = luaL_pcallx(L, 1, 0); //call the offline callback: function(client) if (res != 0) ESP_LOGD(TAG, "CB:disconnect: Error when calling offline callback - (%d) %s", res, luaL_checkstring(L, -1)); } @@ -184,7 +184,7 @@ static void event_subscribed(lua_State* L, mqtt_context_t* mqtt_context, esp_mqt lua_rawgeti(L, LUA_REGISTRYINDEX, mqtt_context->subscribed_ok_cb); // push the function reference on the stack luaX_push_weak_ref(L, mqtt_context->self); // push the client object on the stack luaX_unset_ref(L, &mqtt_context->subscribed_ok_cb); // forget the callback since it is one-shot - int res = lua_pcall(L, 1, 0, 0); //call the connect callback with one parameter: function(client) + int res = luaL_pcallx(L, 1, 0); //call the connect callback with one parameter: function(client) if (res != 0) ESP_LOGD(TAG, "CB:subscribe: Error when calling one-shot subscribe callback - (%d) %s", res, luaL_checkstring(L, -1)); } @@ -197,7 +197,7 @@ static void event_published(lua_State* L, mqtt_context_t* mqtt_context, esp_mqtt lua_rawgeti(L, LUA_REGISTRYINDEX, mqtt_context->published_ok_cb); // push the callback function reference to the stack luaX_push_weak_ref(L, mqtt_context->self); // push the client reference to the stack luaX_unset_ref(L, &mqtt_context->published_ok_cb); // forget this callback since it is one-shot - int res = lua_pcall(L, 1, 0, 0); //call the connect callback with 1 parameter: function(client) + int res = luaL_pcallx(L, 1, 0); //call the connect callback with 1 parameter: function(client) if (res != 0) ESP_LOGD(TAG, "CB:publish: Error when calling one-shot publish callback - (%d) %s", res, luaL_checkstring(L, -1)); } @@ -210,7 +210,7 @@ static void event_unsubscribed(lua_State* L, mqtt_context_t* mqtt_context, esp_m lua_rawgeti(L, LUA_REGISTRYINDEX, mqtt_context->unsubscribed_ok_cb); // push callback function reference on the stack luaX_push_weak_ref(L, mqtt_context->self); // push a reference to the client luaX_unset_ref(L, &mqtt_context->unsubscribed_ok_cb); // forget callback as it is one-shot - int res = lua_pcall(L, 1, 0, 0); //call the connect callback with one parameter: function(client) + int res = luaL_pcallx(L, 1, 0); //call the connect callback with one parameter: function(client) if (res != 0) ESP_LOGD(TAG, "CB:unsubscribe: Error when calling one-shot unsubscribe callback - (%d) %s", res, luaL_checkstring(L, -1)); } @@ -227,7 +227,7 @@ static void event_data_received(lua_State* L, mqtt_context_t* mqtt_context, esp_ lua_pushlstring(L, event->data, event->data_len); numArg++; } - int res = lua_pcall(L, numArg, 0, 0); //call the messagecallback + int res = luaL_pcallx(L, numArg, 0); //call the messagecallback if (res != 0) ESP_LOGD(TAG, "CB:data: Error when calling message callback - (%d) %s", res, luaL_checkstring(L, -1)); } @@ -635,7 +635,9 @@ static int mqtt_new(lua_State* L) { } // map client methods to functions: -LROT_BEGIN(mqtt_metatable) +LROT_BEGIN(mqtt_metatable, NULL, 0) + LROT_FUNCENTRY(__gc, mqtt_delete) + LROT_TABENTRY(__index, mqtt_metatable) LROT_FUNCENTRY(connect, mqtt_connect) LROT_FUNCENTRY(close, mqtt_close) LROT_FUNCENTRY(lwt, mqtt_lwt) @@ -643,17 +645,15 @@ LROT_BEGIN(mqtt_metatable) LROT_FUNCENTRY(subscribe, mqtt_subscribe) LROT_FUNCENTRY(unsubscribe, mqtt_unsubscribe) LROT_FUNCENTRY(on, mqtt_on) - LROT_FUNCENTRY(__gc, mqtt_delete) - LROT_TABENTRY(__index, mqtt_metatable) LROT_END(mqtt_metatable, NULL, 0) // Module function map -LROT_BEGIN(mqtt) +LROT_BEGIN(mqtt, NULL, 0) LROT_FUNCENTRY(Client, mqtt_new) LROT_END(mqtt, NULL, 0) int luaopen_mqtt(lua_State* L) { - luaL_rometatable(L, MQTT_METATABLE, (void*)mqtt_metatable_map); // create metatable for mqtt + luaL_rometatable(L, MQTT_METATABLE, LROT_TABLEREF(mqtt_metatable)); // create metatable for mqtt return 0; } diff --git a/components/modules/net.c b/components/modules/net.c index a078fc60..bb7074e7 100644 --- a/components/modules/net.c +++ b/components/modules/net.c @@ -479,7 +479,7 @@ static int net_listen( lua_State *L ) { if (!ipaddr_aton(domain, &addr)) return luaL_error(L, "invalid IP address"); if (ud->type == TYPE_TCP_SERVER) { - if (lua_isfunction(L, stack) || lua_islightfunction(L, stack)) { + if (lua_isfunction(L, stack)) { lua_pushvalue(L, stack++); luaL_unref(L, LUA_REGISTRYINDEX, ud->server.cb_accept_ref); ud->server.cb_accept_ref = luaL_ref(L, LUA_REGISTRYINDEX); @@ -586,7 +586,7 @@ static int net_on( lua_State *L ) { } if (refptr == NULL) return luaL_error(L, "invalid callback name"); - if (lua_isfunction(L, 3) || lua_islightfunction(L, 3)) { + if (lua_isfunction(L, 3)) { lua_pushvalue(L, 3); luaL_unref(L, LUA_REGISTRYINDEX, *refptr); *refptr = luaL_ref(L, LUA_REGISTRYINDEX); @@ -620,7 +620,7 @@ static int net_send( lua_State *L ) { data = luaL_checklstring(L, stack++, &datalen); if (!data || datalen == 0) return luaL_error(L, "no data to send"); ud->client.num_send = datalen; - if (lua_isfunction(L, stack) || lua_islightfunction(L, stack)) { + if (lua_isfunction(L, stack)) { lua_pushvalue(L, stack++); luaL_unref(L, LUA_REGISTRYINDEX, ud->client.cb_sent_ref); ud->client.cb_sent_ref = luaL_ref(L, LUA_REGISTRYINDEX); @@ -684,7 +684,7 @@ static int net_dns( lua_State *L ) { const char *domain = luaL_checklstring(L, 2, &dl); if (!domain) return luaL_error(L, "no domain specified"); - if (lua_isfunction(L, 3) || lua_islightfunction(L, 3)) { + if (lua_isfunction(L, 3)) { luaL_unref(L, LUA_REGISTRYINDEX, ud->client.cb_dns_ref); lua_pushvalue(L, 3); ud->client.cb_dns_ref = luaL_ref(L, LUA_REGISTRYINDEX); @@ -890,7 +890,7 @@ static int net_dns_static( lua_State* L ) { return luaL_error(L, "domain name too long"); } - luaL_checkanyfunction(L, 2); + luaL_checkfunction(L, 2); lua_settop(L, 2); dns_event_t *ev = luaM_new(L, dns_event_t); @@ -968,7 +968,7 @@ static void ldnsfound_cb (lua_State *L, lnet_userdata *ud, ip_addr_t *addr) { } else { lua_pushnil(L); } - lua_call(L, 2, 0); + luaL_pcallx(L, 2, 0); } ud->client.wait_dns --; if (ud->netconn && ud->type == TYPE_TCP_CLIENT && !ud->client.connecting) { @@ -997,7 +997,7 @@ static void ldnsstatic_cb (lua_State *L, int cb_ref, ip_addr_t *addr) { } else { lua_pushnil(L); } - lua_call(L, 1, 0); + luaL_pcallx(L, 1, 0); } @@ -1005,7 +1005,7 @@ static void lconnected_cb (lua_State *L, lnet_userdata *ud) { if (ud->self_ref != LUA_NOREF && ud->client.cb_connect_ref != LUA_NOREF) { lua_rawgeti(L, LUA_REGISTRYINDEX, ud->client.cb_connect_ref); lua_rawgeti(L, LUA_REGISTRYINDEX, ud->self_ref); - lua_call(L, 1, 0); + luaL_pcallx(L, 1, 0); } } @@ -1041,7 +1041,7 @@ static void lrecv_cb (lua_State *L, lnet_userdata *ud) { lua_pushinteger(L, port); lua_pushstring(L, iptmp); } - lua_call(L, num_args, 0); + luaL_pcallx(L, num_args, 0); } } while (netbuf_next(p) != -1); @@ -1069,7 +1069,7 @@ static void laccept_cb (lua_State *L, lnet_userdata *ud) { nud->netconn->pcb.tcp->keep_cnt = 1; } else luaL_error(L, "cannot accept new server socket connection"); - lua_call(L, 1, 0); + luaL_pcallx(L, 1, 0); } @@ -1077,7 +1077,7 @@ static void lsent_cb (lua_State *L, lnet_userdata *ud) { if (ud->client.cb_sent_ref != LUA_NOREF) { lua_rawgeti(L, LUA_REGISTRYINDEX, ud->client.cb_sent_ref); lua_rawgeti(L, LUA_REGISTRYINDEX, ud->self_ref); - lua_call(L, 1, 0); + luaL_pcallx(L, 1, 0); } } @@ -1094,7 +1094,7 @@ static void lerr_cb (lua_State *L, lnet_userdata *ud, err_t err) lua_rawgeti(L, LUA_REGISTRYINDEX, ref); lua_rawgeti(L, LUA_REGISTRYINDEX, ud->self_ref); lua_pushinteger(L, err); - lua_call(L, 2, 0); + luaL_pcallx(L, 2, 0); } if (ud->client.wait_dns == 0) { lua_gc(L, LUA_GCSTOP, 0); @@ -1108,15 +1108,17 @@ static void lerr_cb (lua_State *L, lnet_userdata *ud, err_t err) // --- Tables // Module function map -LROT_BEGIN(net_tcpserver) +LROT_BEGIN(net_tcpserver, NULL, 0) + LROT_FUNCENTRY( __gc, net_delete ) + LROT_TABENTRY ( __index, net_tcpserver ) LROT_FUNCENTRY( listen, net_listen ) LROT_FUNCENTRY( getaddr, net_getaddr ) LROT_FUNCENTRY( close, net_close ) - LROT_FUNCENTRY( __gc, net_delete ) - LROT_TABENTRY ( __index, net_tcpserver ) LROT_END(net_tcpserver, NULL, 0) -LROT_BEGIN(net_tcpsocket) +LROT_BEGIN(net_tcpsocket, NULL, 0) + LROT_FUNCENTRY( __gc, net_delete ) + LROT_TABENTRY ( __index, net_tcpsocket ) LROT_FUNCENTRY( connect, net_connect ) LROT_FUNCENTRY( close, net_close ) LROT_FUNCENTRY( on, net_on ) @@ -1124,28 +1126,27 @@ LROT_BEGIN(net_tcpsocket) LROT_FUNCENTRY( dns, net_dns ) LROT_FUNCENTRY( getpeer, net_getpeer ) LROT_FUNCENTRY( getaddr, net_getaddr ) - LROT_FUNCENTRY( __gc, net_delete ) - LROT_TABENTRY ( __index, net_tcpsocket ) LROT_END(net_tcpsocket, NULL, 0) -LROT_BEGIN(net_udpsocket) +LROT_BEGIN(net_udpsocket, NULL, 0) + LROT_FUNCENTRY( __gc, net_delete ) + LROT_TABENTRY ( __index, net_udpsocket ) LROT_FUNCENTRY( listen, net_listen ) LROT_FUNCENTRY( close, net_close ) LROT_FUNCENTRY( on, net_on ) LROT_FUNCENTRY( send, net_send ) LROT_FUNCENTRY( dns, net_dns ) LROT_FUNCENTRY( getaddr, net_getaddr ) - LROT_FUNCENTRY( __gc, net_delete ) - LROT_TABENTRY ( __index, net_udpsocket ) LROT_END(net_udpsocket, NULL, 0) -LROT_BEGIN(net_dns) +LROT_BEGIN(net_dns, NULL, 0) LROT_FUNCENTRY( setdnsserver, net_setdnsserver ) LROT_FUNCENTRY( getdnsserver, net_getdnsserver ) LROT_FUNCENTRY( resolve, net_dns_static ) LROT_END(net_dns, NULL, 0) -LROT_BEGIN(net) +LROT_BEGIN(net, NULL, 0) + LROT_TABENTRY ( __metatable, net ) LROT_FUNCENTRY( createServer, net_createServer ) LROT_FUNCENTRY( createConnection, net_createConnection ) LROT_FUNCENTRY( createUDPSocket, net_createUDPSocket ) @@ -1154,15 +1155,14 @@ LROT_BEGIN(net) LROT_TABENTRY ( dns, net_dns ) LROT_NUMENTRY ( TCP, TYPE_TCP ) LROT_NUMENTRY ( UDP, TYPE_UDP ) - LROT_TABENTRY ( __metatable, net ) LROT_END(net, NULL, 0) int luaopen_net( lua_State *L ) { igmp_init(); - luaL_rometatable(L, NET_TABLE_TCP_SERVER, (void *)net_tcpserver_map); - luaL_rometatable(L, NET_TABLE_TCP_CLIENT, (void *)net_tcpsocket_map); - luaL_rometatable(L, NET_TABLE_UDP_SOCKET, (void *)net_udpsocket_map); + luaL_rometatable(L, NET_TABLE_TCP_SERVER, LROT_TABLEREF(net_tcpserver)); + luaL_rometatable(L, NET_TABLE_TCP_CLIENT, LROT_TABLEREF(net_tcpsocket)); + luaL_rometatable(L, NET_TABLE_UDP_SOCKET, LROT_TABLEREF(net_udpsocket)); net_handler = task_get_id(handle_net_event); dns_handler = task_get_id(handle_dns_event); diff --git a/components/modules/node.c b/components/modules/node.c index f08344bd..a39afcab 100644 --- a/components/modules/node.c +++ b/components/modules/node.c @@ -1,7 +1,6 @@ #include "module.h" #include "lauxlib.h" #include "common.h" -#include "legc.h" #include "lundump.h" #include "platform.h" #include "task/task.h" @@ -14,7 +13,7 @@ #include "ldebug.h" #include "esp_vfs.h" #include "lnodeaux.h" -#include "lflash.h" +#include "lpanic.h" #include "rom/rtc.h" // Lua: node.bootreason() @@ -57,7 +56,7 @@ static int node_bootreason( lua_State *L) // 21: EXT_CPU_RESET = 14, /**<14, for APP CPU, reseted by PRO CPU*/ // 22: RTCWDT_BROWN_OUT_RESET = 15, /**<15, Reset when the vdd voltage is not stable*/ // 23: RTCWDT_RTC_RESET = 16 /**<16, RTC Watch dog reset digital core and rtc module*/` -#if defined(CONFIG_IDF_TARGET_ESP32C3) +#if !defined(CONFIG_IDF_TARGET_ESP32) # define SW_CPU_RESET RTC_SW_CPU_RESET # define SW_RESET RTC_SW_SYS_RESET #endif @@ -68,24 +67,32 @@ static int node_bootreason( lua_State *L) case SW_RESET: rawinfo = 2; break; case NO_MEAN: -#if !defined(CONFIG_IDF_TARGET_ESP32C3) +#if defined(CONFIG_IDF_TARGET_ESP32) case EXT_CPU_RESET: #endif case DEEPSLEEP_RESET: +#if defined(CONFIG_IDF_TARGET_ESP32) || defined(CONFIG_IDF_TARGET_ESP32C3) case SDIO_RESET: +#endif +#if defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) + case GLITCH_RTC_RESET: +#endif +#if defined(CONFIG_IDF_TARGET_ESP32S3) + case EFUSE_RESET: +#endif case TG0WDT_SYS_RESET: case TG1WDT_SYS_RESET: case INTRUSION_RESET: case RTCWDT_BROWN_OUT_RESET: case RTCWDT_RTC_RESET: rawinfo = 3; break; -#if defined(CONFIG_IDF_TARGET_ESP32C3) +#if defined(CONFIG_IDF_TARGET_ESP32) + case OWDT_RESET: + case TGWDT_CPU_RESET: +#else case TG0WDT_CPU_RESET: case TG1WDT_CPU_RESET: case SUPER_WDT_RESET: -#else - case OWDT_RESET: - case TGWDT_CPU_RESET: #endif case RTCWDT_CPU_RESET: case RTCWDT_SYS_RESET: @@ -100,7 +107,7 @@ static int node_bootreason( lua_State *L) return 2; } -#if !defined(CONFIG_IDF_TARGET_ESP32C3) +#if defined(CONFIG_IDF_TARGET_ESP32) // Lua: node.chipid() static int node_chipid( lua_State *L ) { @@ -169,7 +176,7 @@ static void node_sleep_disable_wakeup_sources (lua_State *L) static int node_sleep (lua_State *L) { lua_settop(L, 1); - luaL_checkanytable(L, 1); + luaL_checktable(L, 1); node_sleep_disable_wakeup_sources(L); // uart options: uart = num|{num, num, ...} @@ -342,24 +349,13 @@ static int node_dsleep (lua_State *L) } -extern lua_Load gLoad; -extern bool user_process_input(bool force); // Lua: input("string") static int node_input( lua_State* L ) { size_t l = 0; const char *s = luaL_checklstring(L, 1, &l); - if (s != NULL && l > 0 && l < LUA_MAXINPUT - 1) - { - lua_Load *load = &gLoad; - if (load->line_position == 0) { - memcpy(load->line, s, l); - load->line[l + 1] = '\0'; - load->line_position = strlen(load->line) + 1; - load->done = 1; - user_process_input(true); - } - } + if (l > 0 && l < LUA_MAXINPUT - 1) + lua_input_string(s, l); return 0; } @@ -383,7 +379,7 @@ ssize_t redir_write(int fd, const void *data, size_t size) { lua_State *L = lua_getstate(); lua_rawgeti(L, LUA_REGISTRYINDEX, output_redir); // push function reference lua_pushlstring(L, (char *)data, size); // push data - lua_pcall(L, 1, 0, 0); // invoke callback + luaL_pcallx(L, 1, 0); // invoke callback } return size; } @@ -395,7 +391,7 @@ int redir_open(const char *path, int flags, int mode) { // Lua: node.output(func, serial_debug) static int node_output(lua_State *L) { - if (lua_type(L, 1) == LUA_TFUNCTION || lua_type(L, 1) == LUA_TLIGHTFUNCTION) { + if (lua_isfunction(L, 1)) { if (output_redir == LUA_NOREF) { // create an instance of a virtual filesystem so we can use fopen esp_vfs_t redir_fs = { @@ -451,7 +447,7 @@ int redir_vprintf(const char *fmt, va_list ap) lua_State *L = lua_getstate(); lua_rawgeti(L, LUA_REGISTRYINDEX, os_output_redir); // push function reference lua_pushlstring(L, (char *)data, size); // push data - lua_pcall(L, 1, 0, 0); // invoke callback + luaL_pcallx(L, 1, 0); // invoke callback } return size; } @@ -459,7 +455,7 @@ int redir_vprintf(const char *fmt, va_list ap) // Lua: node.output(func, serial_debug) static int node_osoutput(lua_State *L) { - if (lua_type(L, 1) == LUA_TFUNCTION || lua_type(L, 1) == LUA_TLIGHTFUNCTION) { + if (lua_isfunction(L, 1)) { if (os_output_redir == LUA_NOREF) { // register our log redirect first time this is invoked oldvprintf = esp_log_set_vprintf(redir_vprintf); @@ -477,6 +473,7 @@ static int node_osoutput(lua_State *L) { return 0; } + /* node.stripdebug([level[, function]]).  * level: 1 don't discard debug * 2 discard Local and Upvalue debug info @@ -487,58 +484,38 @@ static int node_osoutput(lua_State *L) { * The function returns an estimated integer count of the bytes stripped. */ static int node_stripdebug (lua_State *L) { - int level; - if (L->top == L->base) { - lua_pushlightuserdata(L, &luaG_stripdebug ); - lua_gettable(L, LUA_REGISTRYINDEX); - if (lua_isnil(L, -1)) { - lua_pop(L, 1); - lua_pushinteger(L, CONFIG_LUA_OPTIMIZE_DEBUG); - } - return 1; + int n = lua_gettop(L); + int strip = 0; + + lua_settop(L, 2); + if (!lua_isnil(L, 1)) { + strip = lua_tointeger(L, 1); + luaL_argcheck(L, strip > 0 && strip < 4, 1, "Invalid strip level"); } - level = luaL_checkint(L, 1); - if ((level <= 0) || (level > 3)) luaL_argerror(L, 1, "must in range 1-3"); - - if (L->top == L->base + 1) { - /* Store the default level in the registry if no function parameter */ - lua_pushlightuserdata(L, &luaG_stripdebug); - lua_pushinteger(L, level); - lua_settable(L, LUA_REGISTRYINDEX); - lua_settop(L,0); - return 0; - } - - if (level == 1) { - lua_settop(L,0); - lua_pushinteger(L, 0); - return 1; - } - - if (!lua_isfunction(L, 2)) { - int scope = luaL_checkint(L, 2); + if (lua_isnumber(L, 2)) { + /* Use debug interface to replace stack level by corresponding function */ + int scope = luaL_checkinteger(L, 2); if (scope > 0) { - /* if the function parameter is a +ve integer then climb to find function */ lua_Debug ar; - lua_pop(L, 1); /* pop level as getinfo will replace it by the function */ + lua_pop(L, 1); if (lua_getstack(L, scope, &ar)) { - lua_getinfo(L, "f", &ar); + lua_getinfo(L, "f", &ar); /* put function at [2] (ToS) */ } } } - if(!lua_isfunction(L, 2) || lua_iscfunction(L, -1)) luaL_argerror(L, 2, "must be a Lua Function"); - // lua_lock(L); - Proto *f = clvalue(L->base + 1)->l.p; - // lua_unlock(L); - lua_settop(L,0); - lua_pushinteger(L, luaG_stripdebug(L, f, level, 1)); + int isfunc = lua_isfunction(L, 2); + luaL_argcheck(L, n < 2 || isfunc, 2, "not a valid function"); + + /* return result of lua_stripdebug, adding 1 if this is get/set level) */ + lua_pushinteger(L, lua_stripdebug(L, strip - 1) + (isfunc ? 0 : 1)); return 1; } +#if defined(CONFIG_LUA_VERSION_51) // Lua: node.egc.setmode( mode, [param]) // where the mode is one of the node.egc constants NOT_ACTIVE , ON_ALLOC_FAILURE, // ON_MEM_LIMIT, ALWAYS. In the case of ON_MEM_LIMIT an integer parameter is reqired @@ -550,9 +527,10 @@ static int node_egc_setmode(lua_State* L) { luaL_argcheck(L, mode <= (EGC_ON_ALLOC_FAILURE | EGC_ON_MEM_LIMIT | EGC_ALWAYS), 1, "invalid mode"); luaL_argcheck(L, !(mode & EGC_ON_MEM_LIMIT) || limit>0, 1, "limit must be non-zero"); - legc_set_mode( L, mode, limit ); + lua_setegcmode( L, mode, limit ); return 0; } +#endif static int writer(lua_State* L, const void* p, size_t size, void* u) @@ -593,7 +571,7 @@ static int node_compile( lua_State* L ) output[strlen(output) - 1] = '\0'; NODE_DBG(output); NODE_DBG("\n"); - if (luaL_loadfsfile(L, fname) != 0) { + if (luaL_loadfile(L, fname) != 0) { luaM_free( L, output ); return luaL_error(L, lua_tostring(L, -1)); } @@ -643,7 +621,7 @@ static void do_node_task (task_param_t task_fn_ref, task_prio_t prio) lua_rawgeti(L, LUA_REGISTRYINDEX, (int)task_fn_ref); luaL_unref(L, LUA_REGISTRYINDEX, (int)task_fn_ref); lua_pushinteger(L, prio); - lua_call(L, 1, 0); + luaL_pcallx(L, 1, 0); } // Lua: node.task.post([priority],task_cb) -- schedule a task for execution next @@ -656,7 +634,7 @@ static int node_task_post( lua_State* L ) luaL_argcheck(L, priority <= TASK_PRIORITY_HIGH, 1, "invalid priority"); Ltype = lua_type(L, ++n); } - luaL_argcheck(L, Ltype == LUA_TFUNCTION || Ltype == LUA_TLIGHTFUNCTION, n, "invalid function"); + luaL_argcheck(L, Ltype == LUA_TFUNCTION, n, "invalid function"); lua_pushvalue(L, n); int task_fn_ref = luaL_ref(L, LUA_REGISTRYINDEX); @@ -699,16 +677,102 @@ static int node_uptime(lua_State *L) } -LROT_BEGIN(node_egc) +// Lua: n = node.LFS.reload(lfsimage) +static int node_lfsreload (lua_State *L) { + lua_settop(L, 1); + luaL_lfsreload(L); + return 1; +} + +// Lua: n = node.flashreload(lfsimage) +static int node_lfsreload_deprecated (lua_State *L) { + platform_print_deprecation_note("node.flashreload", "soon. Use node.LFS interface instead"); + return node_lfsreload (L); +} + +// Lua: n = node.flashindex(module) +// Lua: n = node.LFS.get(module) +static int node_lfsindex (lua_State *L) { + lua_settop(L, 1); + luaL_pushlfsmodule(L); + return 1; +} + +// Lua: n = node.LFS.list([option]) +// Note that option is ignored in this release +static int node_lfslist (lua_State *L) { + lua_settop(L, 1); + luaL_pushlfsmodules(L); + if (lua_istable(L, -1) && lua_getglobal(L, "table") == LUA_TTABLE) { + lua_getfield(L, -1, "sort"); + lua_remove(L, -2); /* remove table table */ + lua_pushvalue(L, -2); /* dup array of modules ref to ToS */ + lua_call(L, 1, 0); + } + return 1; +} + + +//== node.LFS Table emulator ==============================================// + + +static void add_int_field( lua_State* L, lua_Integer i, const char *name){ + lua_pushinteger(L, i); + lua_setfield(L, -2, name); +} + +static void get_lfs_config ( lua_State* L ){ + int config[5]; + lua_getlfsconfig(L, config); + lua_createtable(L, 0, 4); + add_int_field(L, config[0], "lfs_mapped"); + add_int_field(L, config[1], "lfs_base"); + add_int_field(L, config[2], "lfs_size"); + add_int_field(L, config[3], "lfs_used"); +} + +static int node_lfs_func (lua_State* L) { /*T[1] = LFS, T[2] = fieldname */ + lua_remove(L, 1); + lua_settop(L, 1); + const char *name = lua_tostring(L, 1); + if (!name) { + lua_pushnil(L); + } else if (!strcmp(name, "config")) { + get_lfs_config(L); + } else if (!strcmp(name, "time")) { + luaL_pushlfsdts(L); + } else { + luaL_pushlfsmodule(L); + } + return 1; +} + +LROT_BEGIN(node_lfs_meta, NULL, LROT_MASK_INDEX) + LROT_FUNCENTRY( __index, node_lfs_func) +LROT_END(node_lfs_meta, NULL, LROT_MASK_INDEX) + +LROT_BEGIN(node_lfs, LROT_TABLEREF(node_lfs_meta), 0) + LROT_FUNCENTRY( list, node_lfslist) + LROT_FUNCENTRY( get, node_lfsindex) + LROT_FUNCENTRY( reload, node_lfsreload ) +LROT_END(node_lfs, LROT_TABLEREF(node_lfs_meta), 0) + + + + + +#if defined(CONFIG_LUA_VERSION_51) +LROT_BEGIN(node_egc, NULL, 0) LROT_FUNCENTRY( setmode, node_egc_setmode ) LROT_NUMENTRY ( NOT_ACTIVE, EGC_NOT_ACTIVE ) LROT_NUMENTRY ( ON_ALLOC_FAILURE, EGC_ON_ALLOC_FAILURE ) LROT_NUMENTRY ( ON_MEM_LIMIT, EGC_ON_MEM_LIMIT ) LROT_NUMENTRY ( ALWAYS, EGC_ALWAYS ) LROT_END(node_egc, NULL, 0) +#endif -LROT_BEGIN(node_task) +LROT_BEGIN(node_task, NULL, 0) LROT_FUNCENTRY( post, node_task_post ) LROT_NUMENTRY ( LOW_PRIORITY, TASK_PRIORITY_LOW ) LROT_NUMENTRY ( MEDIUM_PRIORITY, TASK_PRIORITY_MEDIUM ) @@ -717,7 +781,7 @@ LROT_END(node_task, NULL, 0) // Wakup reasons -LROT_BEGIN(node_wakeup) +LROT_BEGIN(node_wakeup, NULL, 0) LROT_NUMENTRY ( GPIO, ESP_SLEEP_WAKEUP_GPIO ) LROT_NUMENTRY ( TIMER, ESP_SLEEP_WAKEUP_TIMER ) LROT_NUMENTRY ( TOUCHPAD, ESP_SLEEP_WAKEUP_TOUCHPAD ) @@ -725,16 +789,19 @@ LROT_BEGIN(node_wakeup) LROT_NUMENTRY ( ULP, ESP_SLEEP_WAKEUP_ULP ) LROT_END(node_wakeup, NULL, 0) -LROT_BEGIN(node) +LROT_BEGIN(node, NULL, 0) LROT_FUNCENTRY( bootreason, node_bootreason ) -#if !defined(CONFIG_IDF_TARGET_ESP32C3) +#if defined(CONFIG_IDF_TARGET_ESP32) LROT_FUNCENTRY( chipid, node_chipid ) #endif LROT_FUNCENTRY( compile, node_compile ) LROT_FUNCENTRY( dsleep, node_dsleep ) +#if defined(CONFIG_LUA_VERSION_51) LROT_TABENTRY ( egc, node_egc ) - LROT_FUNCENTRY( flashreload,luaN_reload_reboot ) - LROT_FUNCENTRY( flashindex, luaN_index ) +#endif + LROT_FUNCENTRY( flashreload,node_lfsreload_deprecated ) + LROT_FUNCENTRY( flashindex, node_lfsindex ) + LROT_TABENTRY( LFS, node_lfs ) LROT_FUNCENTRY( heap, node_heap ) LROT_FUNCENTRY( input, node_input ) LROT_FUNCENTRY( output, node_output ) diff --git a/components/modules/otaupgrade.c b/components/modules/otaupgrade.c index 4f41ccd1..2444ebcf 100644 --- a/components/modules/otaupgrade.c +++ b/components/modules/otaupgrade.c @@ -239,13 +239,13 @@ next: } -LROT_BEGIN(otaupgrade) +LROT_BEGIN(otaupgrade, NULL, 0) LROT_FUNCENTRY( commence, lotaupgrade_commence ) LROT_FUNCENTRY( write, lotaupgrade_write ) LROT_FUNCENTRY( complete, lotaupgrade_complete ) LROT_FUNCENTRY( accept, lotaupgrade_accept ) LROT_FUNCENTRY( rollback, lotaupgrade_rollback ) LROT_FUNCENTRY( info, lotaupgrade_info ) -LROT_END(otaupgrade, 0, NULL) +LROT_END(otaupgrade, NULL, 0) NODEMCU_MODULE(OTAUPGRADE, "otaupgrade", otaupgrade, NULL); diff --git a/components/modules/ow.c b/components/modules/ow.c index 40060905..123a2920 100644 --- a/components/modules/ow.c +++ b/components/modules/ow.c @@ -326,7 +326,7 @@ static int ow_crc16( lua_State *L ) return 1; } -LROT_BEGIN(ow) +LROT_BEGIN(ow, NULL, 0) LROT_FUNCENTRY( setup, ow_setup ) LROT_FUNCENTRY( reset, ow_reset ) LROT_FUNCENTRY( skip, ow_skip ) diff --git a/components/modules/pipe.c b/components/modules/pipe.c new file mode 100644 index 00000000..688137db --- /dev/null +++ b/components/modules/pipe.c @@ -0,0 +1,477 @@ +/* +** The pipe algo is somewhat similar to the luaL_Buffer algo, except that it +** uses table to store the LUAL_BUFFERSIZE byte array chunks instead of the +** stack. Writing is always to the last UD in the table and overflow pushes a +** new UD to the end of the table. Reading is always from the first UD in the +** table and underrun removes the first UD to shift a new one into slot 2. (Slot +** 1 of the table is reserved for the pipe reader function with 0 denoting no +** reader.) +** +** Reads and writes may span multiple UD buffers and if the read spans multiple +** UDs then the parts are collected as strings on the Lua stack and then +** concatenated with a lua_concat(). +** +** Note that pipe tables also support the undocumented length and tostring +** operators for debugging puposes, so if p is a pipe then #p[i] gives the +** effective length of pipe slot i and printing p[i] gives its contents. +** +** The pipe library also supports the automatic scheduling of a reader task. +** This is declared by including a Lua CB function and an optional prioirty for +** it to execute at in the pipe.create() call. The reader task may or may not +** empty the FIFO (and there is also nothing to stop the task also writing to +** the FIFO. The reader automatically reschedules itself if the pipe contains +** unread content. +** +** The reader tasks may be interleaved with other tasks that write to the pipe +** and others that don't. Any task writing to the pipe will also trigger the +** posting of a read task if one is not already pending. In this way at most +** only one pending reader task is pending, and this prevents overrun of the +** task queueing system. +** +** Implementation Notes: +** +** - The Pipe slot 1 is used to store the Lua CB function reference of the +** reader task. Note that is actually an auxiliary wrapper around the +** supplied Lua CB function, and this wrapper also uses upvals to store +** internal pipe state. The remaining slots are the Userdata buffer chunks. +** +** - This internal state needs to be shared with the pipe_write function, but a +** limitation of Lua 5.1 is that C functions cannot share upvals; to avoid +** this constraint, this function is also denormalised to act as the +** pipe_write function: if Arg1 is the pipe then its a pipe:write() otherwise +** its a CB wrapper. +** +** Also note that the pipe module is used by the Lua VM and therefore the create +** read, and unread methods are exposed as directly callable C functions. (Write +** is available through pipe[1].) +** +** Read the docs/modules/pipe.md documentation for a functional description. +*/ + +#include "module.h" +#include "lauxlib.h" +#include +#include "platform.h" +#include "task/task.h" + +#define INVALID_LEN ((unsigned)-1) + +typedef struct buffer { + int start, end; + char buf[LUAL_BUFFERSIZE]; +} buffer_t; + + +#define AT_TAIL 0x00 +#define AT_HEAD 0x01 +#define WRITING 0x02 + +static buffer_t *checkPipeUD (lua_State *L, int ndx); +static buffer_t *newPipeUD(lua_State *L, int ndx, int n); +static int pipe_write_aux(lua_State *L); +LROT_TABLE(pipe_meta); + +/* Validation and utility functions */ + // [-0, +0, v] +static buffer_t *checkPipeTable (lua_State *L, int tbl, int flags) { + int m = lua_gettop(L), n = lua_objlen(L, tbl); + if (lua_istable(L, tbl) && lua_getmetatable(L, tbl)) { + lua_pushrotable(L, LROT_TABLEREF(pipe_meta));/* push comparison metatable */ + if (lua_rawequal(L, -1, -2)) { /* check these match */ + buffer_t *ud; + if (n == 1) { + ud = (flags & WRITING) ? newPipeUD(L, tbl, 2) : NULL; + } else { + int i = flags & AT_HEAD ? 2 : n; /* point to head or tail of T */ + lua_rawgeti(L, tbl, i); /* and fetch UD */ + ud = checkPipeUD(L, -1); + } + lua_settop(L, m); + return ud; /* and return ptr to buffer_t rec */ + } + } + luaL_argerror(L, tbl, "pipe table"); + return NULL; /* NORETURN avoid compiler error */ +} + +static buffer_t *checkPipeUD (lua_State *L, int ndx) { // [-0, +0, v] + luaL_checktype(L, ndx, LUA_TUSERDATA); /* NORETURN on error */ + buffer_t *ud = lua_touserdata(L, ndx); + if (ud && lua_getmetatable(L, ndx)) { /* Get UD and its metatable? */ + lua_pushrotable(L, LROT_TABLEREF(pipe_meta)); /* push correct metatable */ + if (lua_rawequal(L, -1, -2)) { /* Do these match? */ + lua_pop(L, 2); /* remove both metatables */ + return ud; /* and return ptr to buffer_t rec */ + } + } + return NULL; +} + +/* Create new buffer chunk at `n` in the table which is at stack `ndx` */ +static buffer_t *newPipeUD(lua_State *L, int ndx, int n) { // [-0,+0,-] + buffer_t *ud = (buffer_t *) lua_newuserdata(L, sizeof(buffer_t)); + lua_pushrotable(L, LROT_TABLEREF(pipe_meta)); /* push the metatable */ + lua_setmetatable(L, -2); /* set UD's metabtable to pipe_meta */ + ud->start = ud->end = 0; + lua_rawseti(L, ndx, n); /* T[n] = new UD */ + return ud; /* ud points to new T[n] */ +} + +#define CHAR_DELIM -1 +#define CHAR_DELIM_KEEP -2 +static char getsize_delim (lua_State *L, int ndx, int *len) { // [-0, +0, v] + char delim; + int n; + if( lua_type( L, ndx ) == LUA_TNUMBER ) { + n = luaL_checkinteger( L, ndx ); + luaL_argcheck(L, n > 0, ndx, "invalid chunk size"); + delim = '\0'; + } else if (lua_isnil(L, ndx)) { + n = CHAR_DELIM; + delim = '\n'; + } else { + size_t ldelim; + const char *s = lua_tolstring( L, 2, &ldelim); + n = ldelim == 2 && s[1] == '+' ? CHAR_DELIM_KEEP : CHAR_DELIM ; + luaL_argcheck(L, ldelim + n == 0, ndx, "invalid delimiter"); + delim = s[0]; + } + if (len) + *len = n; + return delim; +} + +/* +** Read CB Initiator AND pipe_write. If arg1 == the pipe, then this is a pipe +** write(); otherwise it is the Lua CB wapper for the task post. This botch +** allows these two functions to share Upvals within the Lua 5.1 VM: +*/ +#define UVpipe lua_upvalueindex(1) // The pipe table object +#define UVfunc lua_upvalueindex(2) // The CB's Lua function +#define UVprio lua_upvalueindex(3) // The task priority +#define UVstate lua_upvalueindex(4) // Pipe state; +#define CB_NOT_USED 0 +#define CB_ACTIVE 1 +#define CB_WRITE_UPDATED 2 +#define CB_QUIESCENT 4 +/* +** Note that nothing precludes the Lua CB function from itself writing to the +** pipe and in this case this routine will call itself recursively. +** +** The Lua CB itself takes the pipe object as a parameter and returns an +** optional boolean to force or to suppress automatic retasking if needed. If +** omitted, then the default is to repost if the pipe is not empty, otherwise +** the task chain is left to lapse. +*/ +static int pipe_write_and_read_poster (lua_State *L) { + int state = lua_tointeger(L, UVstate); + if (lua_rawequal(L, 1, UVpipe)) { + /* arg1 == the pipe, so this was invoked as a pipe_write() */ + if (pipe_write_aux(L) && state && !(state & CB_WRITE_UPDATED)) { + /* + * if this resulted in a write and not already in a CB and not already + * toggled the write update then post the task + */ + state |= CB_WRITE_UPDATED; + lua_pushinteger(L, state); + lua_replace(L, UVstate); /* Set CB state write updated flag */ + if (state == (CB_QUIESCENT | CB_WRITE_UPDATED)) { + lua_rawgeti(L, 1, 1); /* Get CB ref from pipe[1] */ + luaL_posttask(L, (int) lua_tointeger(L, UVprio)); /* and repost task */ + } + } + + } else if (state != CB_NOT_USED) { + /* invoked by the luaN_taskpost() so call the Lua CB */ + int repost; /* can take the values CB_WRITE_UPDATED or 0 */ + lua_pushinteger(L, CB_ACTIVE); /* CB state set to active only */ + lua_replace(L, UVstate); + lua_pushvalue(L, UVfunc); /* Lua CB function */ + lua_pushvalue(L, UVpipe); /* pipe table */ + lua_call(L, 1, 1); /* Errors are thrown back to caller */ + /* + * On return from the Lua CB, the task is never reposted if the pipe is empty. + * If it is not empty then the Lua CB return status determines when reposting + * occurs: + * - true = repost + * - false = don't repost + * - nil = only repost if there has been a write update. + */ + if (lua_isboolean(L,-1)) { + repost = (lua_toboolean(L, -1) == true && + lua_objlen(L, UVpipe) > 1) ? CB_WRITE_UPDATED : 0; + } else { + repost = state & CB_WRITE_UPDATED; + } + state = CB_QUIESCENT | repost; + lua_pushinteger(L, state); /* Update the CB state */ + lua_replace(L, UVstate); + + if (repost) { + lua_rawgeti(L, UVpipe, 1); /* Get CB ref from pipe[1] */ + luaL_posttask(L, (int) lua_tointeger(L, UVprio)); /* and repost task */ + } + } + return 0; +} + +/* Lua callable methods. Since the metatable is linked to both the pipe table */ +/* and the userdata entries the __len & __tostring functions must handle both */ + +// Lua: buf = pipe.create() +int pipe_create(lua_State *L) { + int prio = -1; + lua_settop(L, 2); /* fix stack sze as 2 */ + + if (!lua_isnil(L, 1)) { + luaL_checktype(L, 1, LUA_TFUNCTION); /* non-nil arg1 must be a function */ + if (lua_isnil(L, 2)) { + prio = TASK_PRIORITY_MEDIUM; + } else { + prio = (int) lua_tointeger(L, 2); + luaL_argcheck(L, prio >= TASK_PRIORITY_LOW && + prio <= TASK_PRIORITY_HIGH, 2, + "invalid priority"); + } + } + + lua_createtable (L, 1, 0); /* create pipe table */ + lua_pushrotable(L, LROT_TABLEREF(pipe_meta)); + lua_setmetatable(L, -2); /* set pipe table's metabtable to pipe_meta */ + + lua_pushvalue(L, -1); /* UV1: pipe object */ + lua_pushvalue(L, 1); /* UV2: CB function */ + lua_pushinteger(L, prio); /* UV3: task priority */ + lua_pushinteger(L, prio == -1 ? CB_NOT_USED : CB_QUIESCENT); + lua_pushcclosure(L, pipe_write_and_read_poster, 4); /* aux func for C task */ + lua_rawseti(L, -2, 1); /* and write to T[1] */ + return 1; /* return the table */ +} + +// len = #pipeobj[i] +static int pipe__len (lua_State *L) { + if (lua_istable(L, 1)) { + lua_pushinteger(L, lua_objlen(L, 1)); + } else { + buffer_t *ud = checkPipeUD(L, 1); + lua_pushinteger(L, ud->end - ud->start); + } + return 1; +} + +//Lua s = pipeUD:tostring() +static int pipe__tostring (lua_State *L) { + if (lua_istable(L, 1)) { + lua_pushfstring(L, "Pipe: %p", lua_topointer(L, 1)); + } else { + buffer_t *ud = checkPipeUD(L, 1); + lua_pushlstring(L, ud->buf + ud->start, ud->end - ud->start); + } + return 1; +} + +// Lua: rec = p:read(end_or_delim) // also [-2, +1,- ] +int pipe_read(lua_State *L) { + buffer_t *ud = checkPipeTable(L, 1, AT_HEAD); + int i, k=0, n; + lua_settop(L,2); + const char delim = getsize_delim(L, 2, &n); + lua_pop(L,1); + + while (ud && n) { + int want, used, avail = ud->end - ud->start; + + if (n < 0 /* one of the CHAR_DELIM flags */) { + /* getting a delimited chunk so scan for delimiter */ + for (i = ud->start; i < ud->end && ud->buf[i] != delim; i++) {} + /* Can't have i = ud->end and ud->buf[i] == delim so either */ + /* we've scanned full buffer avail OR we've hit a delim char */ + if (i == ud->end) { + want = used = avail; /* case where we've scanned without a hit */ + } else { + want = used = i + 1 - ud->start; /* case where we've hit a delim */ + if (n == CHAR_DELIM) + want--; + n = 0; /* force loop exit because delim found */ + } + } else { + want = used = (n < avail) ? n : avail; + n -= used; + } + lua_pushlstring(L, ud->buf + ud->start, want); /* part we want */ + k++; + ud->start += used; + if (ud->start == ud->end) { + /* shift the pipe array down overwriting T[1] */ + int nUD = lua_objlen(L, 1); + for (i = 2; i < nUD; i++) { /* for i = 2, nUD-1 */ + lua_rawgeti(L, 1, i+1); lua_rawseti(L, 1, i); /* T[i] = T[i+1] */ + } + lua_pushnil(L); lua_rawseti(L, 1, nUD--); /* T[n] = nil */ + if (nUD>1) { + lua_rawgeti(L, 1, 2); + ud = checkPipeUD(L, -1); + lua_pop(L, 1); + } else { + ud = NULL; + } + } + } + if (k) + lua_concat(L, k); + else + lua_pushnil(L); + return 1; +} + +// Lua: buf:unread(some_string) +int pipe_unread(lua_State *L) { + size_t l = INVALID_LEN; + const char *s = lua_tolstring(L, 2, &l); + if (l==0) + return 0; + luaL_argcheck(L, l != INVALID_LEN, 2, "must be a string"); + buffer_t *ud = checkPipeTable(L, 1, AT_HEAD | WRITING); + + do { + int used = ud->end - ud->start; + int lrem = LUAL_BUFFERSIZE-used; + + if (used == LUAL_BUFFERSIZE) { + /* If the current UD is full insert a new UD at T[2] */ + int i, nUD = lua_objlen(L, 1); + for (i = nUD; i > 1; i--) { /* for i = nUD,1,-1 */ + lua_rawgeti(L, 1, i); lua_rawseti(L, 1, i+1); /* T[i+1] = T[i] */ + } + ud = newPipeUD(L, 1, 2); + used = 0; lrem = LUAL_BUFFERSIZE; + + /* Filling leftwards; make this chunk "empty but at the right end" */ + ud->start = ud->end = LUAL_BUFFERSIZE; + } else if (ud->start < l) { + /* If the unread can't fit it before the start, shift content to end */ + memmove(ud->buf + lrem, + ud->buf + ud->start, used); /* must be memmove not cpy */ + ud->start = lrem; ud->end = LUAL_BUFFERSIZE; + } + + if (l <= (unsigned )lrem) + break; + + /* If we're here then the remaining string is strictly longer than the */ + /* remaining buffer space; top off the buffer before looping around again */ + l -= lrem; + memcpy(ud->buf, s + l, lrem); + ud->start = 0; + + } while(1); + + /* Copy any residual tail to the UD buffer. + * Here, ud != NULL and 0 <= l <= ud->start */ + + ud->start -= l; + memcpy(ud->buf + ud->start, s, l); + return 0; +} + +// Lua: buf:write(some_string) +static int pipe_write_aux(lua_State *L) { + size_t l = INVALID_LEN; + const char *s = lua_tolstring(L, 2, &l); +//dbg_printf("pipe write(%u): %s", l, s); + if (l==0) + return false; + luaL_argcheck(L, l != INVALID_LEN, 2, "must be a string"); + buffer_t *ud = checkPipeTable(L, 1, AT_TAIL | WRITING); + + do { + int used = ud->end - ud->start; + + if (used == LUAL_BUFFERSIZE) { + /* If the current UD is full insert a new UD at T[end] */ + ud = newPipeUD(L, 1, lua_objlen(L, 1)+1); + used = 0; + } else if (LUAL_BUFFERSIZE - ud->end < l) { + /* If the write can't fit it at the end then shift content to the start */ + memmove(ud->buf, ud->buf + ud->start, used); /* must be memmove not cpy */ + ud->start = 0; ud->end = used; + } + + int lrem = LUAL_BUFFERSIZE-used; + if (l <= (unsigned )lrem) + break; + + /* If we've got here then the remaining string is longer than the buffer */ + /* space left, so top off the buffer before looping around again */ + memcpy(ud->buf + ud->end, s, lrem); + ud->end += lrem; + l -= lrem; + s += lrem; + + } while(1); + + /* Copy any residual tail to the UD buffer. Note that this is l>0 and */ + memcpy(ud->buf + ud->end, s, l); + ud->end += l; + return true; +} + +// Lua: fread = pobj:reader(1400) -- or other number +// fread = pobj:reader('\n') -- or other delimiter (delim is stripped) +// fread = pobj:reader('\n+') -- or other delimiter (delim is retained) +#define TBL lua_upvalueindex(1) +#define N lua_upvalueindex(2) +static int pipe_read_aux(lua_State *L) { + lua_settop(L, 0); /* ignore args since we use upvals instead */ + lua_pushvalue(L, TBL); + lua_pushvalue(L, N); + return pipe_read(L); +} +static int pipe_reader(lua_State *L) { + lua_settop(L,2); + checkPipeTable (L, 1,AT_HEAD); + getsize_delim(L, 2, NULL); + lua_pushcclosure(L, pipe_read_aux, 2); /* return (closure, nil, table) */ + return 1; +} + +// return number of records +static int pipe_nrec (lua_State *L) { + lua_pushinteger(L, lua_objlen(L, 1) - 1); + return 1; +} + +LROT_BEGIN(pipe_funcs, NULL, 0) + LROT_FUNCENTRY( __len, pipe__len ) + LROT_FUNCENTRY( __tostring, pipe__tostring ) + LROT_FUNCENTRY( read, pipe_read ) + LROT_FUNCENTRY( reader, pipe_reader ) + LROT_FUNCENTRY( unread, pipe_unread ) + LROT_FUNCENTRY( nrec, pipe_nrec ) +LROT_END(pipe_funcs, NULL, 0) + +/* Using a index func is needed because the write method is at pipe[1] */ +static int pipe__index(lua_State *L) { + lua_settop(L,2); + const char *k=lua_tostring(L,2); + if(!strcmp(k,"write")){ + lua_rawgeti(L, 1, 1); + } else { + lua_pushrotable(L, LROT_TABLEREF(pipe_funcs)); + lua_replace(L, 1); + lua_rawget(L, 1); + } + return 1; +} + +LROT_BEGIN(pipe_meta, NULL, LROT_MASK_INDEX) + LROT_FUNCENTRY( __index, pipe__index) + LROT_FUNCENTRY( __len, pipe__len ) + LROT_FUNCENTRY( __tostring, pipe__tostring ) +LROT_END(pipe_meta, NULL, LROT_MASK_INDEX) + +LROT_BEGIN(pipe, NULL, 0) + LROT_FUNCENTRY( create, pipe_create ) +LROT_END(pipe, NULL, 0) + +NODEMCU_MODULE(PIPE, "pipe", pipe, NULL); diff --git a/components/modules-esp32/pulsecnt.c b/components/modules/pulsecnt.c similarity index 98% rename from components/modules-esp32/pulsecnt.c rename to components/modules/pulsecnt.c index df031df6..83e11d5c 100644 --- a/components/modules-esp32/pulsecnt.c +++ b/components/modules/pulsecnt.c @@ -214,7 +214,7 @@ static void pulsecnt_task(task_param_t param, task_prio_t prio) lua_pushboolean (L, zero); // lua_pushinteger (L, moving_to); // lua_pushinteger (L, status); - lua_call (L, 6, 0); + luaL_pcallx (L, 6, 0); } else { if (pc->is_debug) ESP_LOGI("pulsecnt", "Could not find cb for unit %d with ptr %d", unit, pc->cb_ref); } @@ -539,12 +539,12 @@ static int pulsecnt_channel_config( lua_State *L, uint8_t channel ) { // Lua: pc:chan0Config(pulse_gpio_num, ctrl_gpio_num, pos_mode, neg_mode, lctrl_mode, hctrl_mode, counter_l_lim, counter_h_lim) // Example: pc:chan0Config(2, 4, pulsecnt.PCNT_COUNT_INC, pulsecnt.PCNT_COUNT_DIS, pulsecnt.PCNT_MODE_REVERSE, pulsecnt.PCNT_MODE_KEEP, -100, 100) -static int pulsecnt_channel0_config( lua_State *L, uint8_t channel ) { +static int pulsecnt_channel0_config( lua_State *L ) { return pulsecnt_channel_config(L, 0); } // Lua: pc:chan1Config(pulse_gpio_num, ctrl_gpio_num, pos_mode, neg_mode, lctrl_mode, hctrl_mode, counter_l_lim, counter_h_lim) // Example: pc:chan1Config(2, 4, pulsecnt.PCNT_COUNT_INC, pulsecnt.PCNT_COUNT_DIS, pulsecnt.PCNT_MODE_REVERSE, pulsecnt.PCNT_MODE_KEEP, -100, 100) -static int pulsecnt_channel1_config( lua_State *L, uint8_t channel ) { +static int pulsecnt_channel1_config( lua_State *L ) { return pulsecnt_channel_config(L, 1); } @@ -565,7 +565,7 @@ static int pulsecnt_create( lua_State *L ) { // user did not provide a callback. that's ok. just don't give them one. isCallback = false; } else { - luaL_argcheck(L, lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION, stack, "Must be function"); + luaL_checkfunction(L, stack); } // ok, we have our unit number which is required. good. now create our object @@ -678,7 +678,10 @@ static int pulsecnt_unregister(lua_State* L){ return 0; } -LROT_BEGIN(pulsecnt_dyn) +LROT_BEGIN(pulsecnt_dyn, NULL, 0) + LROT_FUNCENTRY( __gc, pulsecnt_unregister ) + LROT_TABENTRY ( __index, pulsecnt_dyn ) + // LROT_FUNCENTRY( __tostring, pulsecnt_tostring ) LROT_FUNCENTRY( getCnt, pulsecnt_getCnt ) LROT_FUNCENTRY( clear, pulsecnt_clear ) LROT_FUNCENTRY( testCb, pulsecnt_testCb ) @@ -690,13 +693,9 @@ LROT_BEGIN(pulsecnt_dyn) LROT_FUNCENTRY( setFilter, pulsecnt_set_filter ) LROT_FUNCENTRY( rawSetEventVal, pulsecnt_set_event_value ) LROT_FUNCENTRY( rawGetEventVal, pulsecnt_get_event_value ) - - // LROT_FUNCENTRY( __tostring, pulsecnt_tostring ) - LROT_FUNCENTRY( __gc, pulsecnt_unregister ) - LROT_TABENTRY ( __index, pulsecnt_dyn ) LROT_END(pulsecnt_dyn, NULL, 0) -LROT_BEGIN(pulsecnt) +LROT_BEGIN(pulsecnt, NULL, 0) LROT_FUNCENTRY( create, pulsecnt_create ) LROT_NUMENTRY ( PCNT_MODE_KEEP, 0 ) /*pcnt_ctrl_mode_t.PCNT_MODE_KEEP*/ LROT_NUMENTRY ( PCNT_MODE_REVERSE, 1 ) /*pcnt_ctrl_mode_t.PCNT_MODE_REVERSE*/ @@ -717,7 +716,7 @@ LROT_END(pulsecnt, NULL, 0) int luaopen_pulsecnt(lua_State *L) { - luaL_rometatable(L, "pulsecnt.pctr", (void *)pulsecnt_dyn_map); + luaL_rometatable(L, "pulsecnt.pctr", LROT_TABLEREF(pulsecnt_dyn)); pulsecnt_task_id = task_get_id(pulsecnt_task); diff --git a/components/modules/qrcodegen.c b/components/modules/qrcodegen.c index 0a3a1fa1..e698ea64 100644 --- a/components/modules/qrcodegen.c +++ b/components/modules/qrcodegen.c @@ -56,7 +56,7 @@ static int getPixel(lua_State *L) return 1; } -LROT_BEGIN(qrcodegen) +LROT_BEGIN(qrcodegen, NULL, 0) LROT_FUNCENTRY(encodeText, encodeText) LROT_FUNCENTRY(getSize, getSize) LROT_FUNCENTRY(getPixel, getPixel) diff --git a/components/modules-esp32/sdmmc.c b/components/modules/sdmmc.c similarity index 97% rename from components/modules-esp32/sdmmc.c rename to components/modules/sdmmc.c index 94f8f83b..ad94f76d 100644 --- a/components/modules-esp32/sdmmc.c +++ b/components/modules/sdmmc.c @@ -187,7 +187,7 @@ static int lsdmmc_read( lua_State * L) luaL_addlstring( &b, rbuf, num_sec * 512 ); luaL_pushresult( &b ); - luaM_freearray( L, rbuf, rbuf_size, uint8_t ); + luaN_freearray( L, rbuf, rbuf_size ); // all ok return 1; @@ -195,7 +195,7 @@ static int lsdmmc_read( lua_State * L) } else err_msg = "card access failed"; - luaM_freearray( L, rbuf, rbuf_size, uint8_t ); + luaN_freearray( L, rbuf, rbuf_size ); return luaL_error( L, err_msg ); } @@ -327,16 +327,16 @@ static int lsdmmc_umount( lua_State *L ) return luaL_error( L, err_msg ); } -LROT_BEGIN(sdmmc_card) +LROT_BEGIN(sdmmc_card, NULL, 0) + LROT_TABENTRY( __index, sdmmc_card ) LROT_FUNCENTRY( read, lsdmmc_read ) LROT_FUNCENTRY( write, lsdmmc_write ) LROT_FUNCENTRY( get_info, lsdmmc_get_info ) LROT_FUNCENTRY( mount, lsdmmc_mount ) LROT_FUNCENTRY( umount, lsdmmc_umount ) - LROT_TABENTRY( __index, sdmmc_card ) LROT_END(sdmmc_card, NULL, 0) -LROT_BEGIN(sdmmc) +LROT_BEGIN(sdmmc, NULL, 0) LROT_FUNCENTRY( init, lsdmmc_init ) LROT_NUMENTRY( HS1, SDMMC_HOST_SLOT_0 ) LROT_NUMENTRY( HS2, SDMMC_HOST_SLOT_1 ) @@ -352,7 +352,7 @@ LROT_END(sdmmc, NULL, 0) static int luaopen_sdmmc( lua_State *L ) { - luaL_rometatable(L, "sdmmc.card", (void *)sdmmc_card_map); + luaL_rometatable(L, "sdmmc.card", LROT_TABLEREF(sdmmc_card)); // initialize cards for (int i = 0; i < NUM_CARDS; i++ ) { diff --git a/components/modules/sigma_delta.c b/components/modules/sigma_delta.c index 551cda10..250df2ad 100644 --- a/components/modules/sigma_delta.c +++ b/components/modules/sigma_delta.c @@ -77,7 +77,7 @@ static int sigma_delta_setduty( lua_State *L ) // Module function map -LROT_BEGIN(sigma_delta) +LROT_BEGIN(sigma_delta, NULL, 0) LROT_FUNCENTRY( setup, sigma_delta_setup ) LROT_FUNCENTRY( close, sigma_delta_close ) //LROT_FUNCENTRY( setpwmduty, sigma_delta_setpwmduty ) diff --git a/components/modules/sjson.c b/components/modules/sjson.c index 567d4a0c..8ed7ce1a 100644 --- a/components/modules/sjson.c +++ b/components/modules/sjson.c @@ -1,8 +1,6 @@ #define LUA_LIB -#include "lua.h" #include "lauxlib.h" -#include "lstring.h" #ifndef LOCAL_LUA #include "module.h" @@ -18,7 +16,9 @@ #define DEFAULT_DEPTH 20 -#define DBG_PRINTF(...) +#define DBG_PRINTF(...) + +#define SJSON_FLOAT_FMT ((sizeof(lua_Float) == 8) ? "%.19g" : "%.9g") typedef struct { jsonsl_t jsn; @@ -86,31 +86,31 @@ create_new_element(jsonsl_t jsn, switch(state->type) { case JSONSL_T_SPECIAL: - case JSONSL_T_STRING: - case JSONSL_T_HKEY: + case JSONSL_T_STRING: + case JSONSL_T_HKEY: break; - case JSONSL_T_LIST: - case JSONSL_T_OBJECT: + case JSONSL_T_LIST: + case JSONSL_T_OBJECT: create_table(data); - state->lua_object_ref = lua_ref(data->L, 1); + state->lua_object_ref = luaL_ref(data->L, LUA_REGISTRYINDEX); state->used_count = 0; lua_rawgeti(data->L, LUA_REGISTRYINDEX, get_parent_object_ref()); if (data->hkey_ref == LUA_NOREF) { // list, so append - lua_pushnumber(data->L, get_parent_object_used_count_pre_inc()); + lua_pushinteger(data->L, get_parent_object_used_count_pre_inc()); DBG_PRINTF("Adding array element\n"); } else { - // object, so + // object, so lua_rawgeti(data->L, LUA_REGISTRYINDEX, data->hkey_ref); - lua_unref(data->L, data->hkey_ref); + luaL_unref(data->L, LUA_REGISTRYINDEX, data->hkey_ref); data->hkey_ref = LUA_NOREF; DBG_PRINTF("Adding hash element\n"); } if (data->pos_ref != LUA_NOREF && state->level > 1) { lua_rawgeti(data->L, LUA_REGISTRYINDEX, data->pos_ref); - lua_pushnumber(data->L, state->level - 1); + lua_pushinteger(data->L, state->level - 1); lua_pushvalue(data->L, -3); // get the key lua_settable(data->L, -3); lua_pop(data->L, 1); @@ -118,17 +118,17 @@ create_new_element(jsonsl_t jsn, // At this point, the stack: // top: index/hash key // : table - + int want_value = 1; // Invoke the checkpath method if possible if (data->pos_ref != LUA_NOREF) { lua_rawgeti(data->L, LUA_REGISTRYINDEX, data->metatable); lua_getfield(data->L, -1, "checkpath"); - if (lua_type(data->L, -1) != LUA_TNIL) { + if (!lua_isnil(data->L, -1)) { // Call with the new table and the path as arguments lua_rawgeti(data->L, LUA_REGISTRYINDEX, state->lua_object_ref); lua_rawgeti(data->L, LUA_REGISTRYINDEX, data->pos_ref); - lua_call(data->L, 2, 1); + luaL_pcallx(data->L, 2, 1); want_value = lua_toboolean(data->L, -1); } lua_pop(data->L, 2); // Discard the metatable and either the getfield result or retval @@ -155,9 +155,15 @@ create_new_element(jsonsl_t jsn, static void push_number(JSN_DATA *data, struct jsonsl_state_st *state) { lua_pushlstring(data->L, get_state_buffer(data, state), state->pos_cur - state->pos_begin); - LUA_NUMBER r = lua_tonumber(data->L, -1); - lua_pop(data->L, 1); - lua_pushnumber(data->L, r); +#if LUA_VERSION_NUM == 501 + lua_pushnumber(data->L, lua_tonumber(data->L, -1)); +#else + if (!lua_stringtonumber(data->L, lua_tostring(data->L, -1))) { + // In this case stringtonumber does not push a value + luaL_error(data->L, "Invalid number"); + } +#endif + lua_remove(data->L, -2); } static int fromhex(char c) { @@ -217,7 +223,7 @@ static void push_string(JSN_DATA *data, struct jsonsl_state_st *state) { continue; } } - luaL_putchar(&b, nc); + luaL_addchar(&b, nc); } luaL_pushresult(&b); } @@ -236,18 +242,18 @@ cleanup_closing_element(jsonsl_t jsn, switch (state->type) { case JSONSL_T_HKEY: push_string(data, state); - data->hkey_ref = lua_ref(data->L, 1); + data->hkey_ref = luaL_ref(data->L, LUA_REGISTRYINDEX); break; case JSONSL_T_STRING: lua_rawgeti(data->L, LUA_REGISTRYINDEX, get_parent_object_ref()); if (data->hkey_ref == LUA_NOREF) { // list, so append - lua_pushnumber(data->L, get_parent_object_used_count_pre_inc()); + lua_pushinteger(data->L, get_parent_object_used_count_pre_inc()); } else { - // object, so + // object, so lua_rawgeti(data->L, LUA_REGISTRYINDEX, data->hkey_ref); - lua_unref(data->L, data->hkey_ref); + luaL_unref(data->L, LUA_REGISTRYINDEX, data->hkey_ref); data->hkey_ref = LUA_NOREF; } push_string(data, state); @@ -274,11 +280,11 @@ cleanup_closing_element(jsonsl_t jsn, lua_rawgeti(data->L, LUA_REGISTRYINDEX, get_parent_object_ref()); if (data->hkey_ref == LUA_NOREF) { // list, so append - lua_pushnumber(data->L, get_parent_object_used_count_pre_inc()); + lua_pushinteger(data->L, get_parent_object_used_count_pre_inc()); } else { - // object, so + // object, so lua_rawgeti(data->L, LUA_REGISTRYINDEX, data->hkey_ref); - lua_unref(data->L, data->hkey_ref); + luaL_unref(data->L, LUA_REGISTRYINDEX, data->hkey_ref); data->hkey_ref = LUA_NOREF; } lua_pushvalue(data->L, -3); @@ -289,11 +295,11 @@ cleanup_closing_element(jsonsl_t jsn, break; case JSONSL_T_OBJECT: case JSONSL_T_LIST: - lua_unref(data->L, state->lua_object_ref); + luaL_unref(data->L, LUA_REGISTRYINDEX, state->lua_object_ref); state->lua_object_ref = LUA_NOREF; if (data->pos_ref != LUA_NOREF) { lua_rawgeti(data->L, LUA_REGISTRYINDEX, data->pos_ref); - lua_pushnumber(data->L, state->level); + lua_pushinteger(data->L, state->level); lua_pushnil(data->L); lua_settable(data->L, -3); lua_pop(data->L, 1); @@ -347,11 +353,11 @@ static int sjson_decoder_int(lua_State *L, int argno) { data->error = NULL; data->L = L; data->buffer_len = 0; - + data->min_needed = data->min_available = jsn->pos; lua_pushlightuserdata(L, 0); - data->null_ref = lua_ref(L, 1); + data->null_ref = luaL_ref(L, LUA_REGISTRYINDEX); // This may throw... lua_newtable(L); @@ -361,25 +367,25 @@ static int sjson_decoder_int(lua_State *L, int argno) { luaL_unref(L, LUA_REGISTRYINDEX, data->null_ref); data->null_ref = LUA_NOREF; lua_getfield(L, argno, "null"); - data->null_ref = lua_ref(L, 1); + data->null_ref = luaL_ref(L, LUA_REGISTRYINDEX); lua_getfield(L, argno, "metatable"); lua_pushvalue(L, -1); - data->metatable = lua_ref(L, 1); + data->metatable = luaL_ref(L, LUA_REGISTRYINDEX); - if (lua_type(L, -1) != LUA_TNIL) { + if (!lua_isnil(L, -1)) { lua_getfield(L, -1, "checkpath"); - if (lua_type(L, -1) != LUA_TNIL) { + if (!lua_isnil(L, -1)) { lua_newtable(L); - data->pos_ref = lua_ref(L, 1); + data->pos_ref = luaL_ref(L, LUA_REGISTRYINDEX); } - lua_pop(L, 1); // Throw away the checkpath value + lua_pop(L, 1); // Throw away the checkpath value } lua_pop(L, 1); // Throw away the metatable } jsonsl_enable_all_callbacks(data->jsn); - + jsn->action_callback = NULL; jsn->action_callback_PUSH = create_new_element; jsn->action_callback_POP = cleanup_closing_element; @@ -477,7 +483,7 @@ static int sjson_decoder_write_int(lua_State *L, int udata_pos, int string_pos) size_t blen; data->buffer = luaL_checklstring(L, -1, &blen); data->buffer_len = blen; - data->buffer_ref = lua_ref(L, 1); + data->buffer_ref = luaL_ref(L, LUA_REGISTRYINDEX); jsonsl_feed(data->jsn, str, len); @@ -611,9 +617,9 @@ static void enc_pop_stack(lua_State *L, ENC_DATA *data) { } ENC_DATA_STATE *state = &data->stack[data->level]; - lua_unref(L, state->lua_object_ref); + luaL_unref(L, LUA_REGISTRYINDEX, state->lua_object_ref); state->lua_object_ref = LUA_NOREF; - lua_unref(L, state->lua_key_ref); + luaL_unref(L, LUA_REGISTRYINDEX, state->lua_key_ref); state->lua_key_ref = LUA_REFNIL; data->level--; } @@ -624,7 +630,7 @@ static void enc_push_stack(lua_State *L, ENC_DATA *data, int argno) { } lua_pushvalue(L, argno); ENC_DATA_STATE *state = &data->stack[data->level]; - state->lua_object_ref = lua_ref(L, 1); + state->lua_object_ref = luaL_ref(L, LUA_REGISTRYINDEX); state->size = sjson_encoder_get_table_size(L, argno); state->offset = 0; // We haven't started on this one yet } @@ -674,7 +680,7 @@ static int sjson_encoder(lua_State *L) { luaL_unref(L, LUA_REGISTRYINDEX, data->null_ref); data->null_ref = LUA_NOREF; lua_getfield(L, argno, "null"); - data->null_ref = lua_ref(L, 1); + data->null_ref = luaL_ref(L, LUA_REGISTRYINDEX); } return 1; @@ -694,7 +700,7 @@ static void encode_lua_object(lua_State *L, ENC_DATA *data, int argno, const cha lua_rawgeti(L, LUA_REGISTRYINDEX, data->null_ref); if (lua_equal(L, -1, -2)) { type = LUA_TNIL; - } + } lua_pop(L, 1); } } @@ -716,12 +722,27 @@ static void encode_lua_object(lua_State *L, ENC_DATA *data, int argno, const cha case LUA_TNUMBER: { lua_pushvalue(L, argno); - size_t len; - const char *str = lua_tolstring(L, -1, &len); - char value[len + 1]; - strcpy(value, str); + char value[50]; + +#if LUA_VERSION_NUM == 501 +#ifdef LUA_NUMBER_INTEGRAL + snprintf(value, sizeof(value), "%d", lua_tointeger(L, -1)); +#else + snprintf(value, sizeof(value), SJSON_FLOAT_FMT, lua_tonumber(L, -1)); +#endif +#else + if (lua_isinteger(L, -1)) { + snprintf(value, sizeof(value), LUA_INTEGER_FMT, lua_tointeger(L, -1)); + } else { + snprintf(value, sizeof(value), SJSON_FLOAT_FMT, lua_tonumber(L, -1)); + } +#endif lua_pop(L, 1); - luaL_addstring(&b, value); + if (strcmp(value, "-inf") == 0 || strcmp(value, "nan") == 0 || strcmp(value, "inf") == 0) { + luaL_addstring(&b, "null"); // According to ECMA-262 section 24.5.2 Note 4 + } else { + luaL_addstring(&b, value); + } break; } @@ -785,10 +806,7 @@ static void encode_lua_object(lua_State *L, ENC_DATA *data, int argno, const cha static int sjson_encoder_next_value_is_table(lua_State *L) { int count = 10; - while ((lua_type(L, -1) == LUA_TFUNCTION -#ifdef LUA_TLIGHTFUNCTION - || lua_type(L, -1) == LUA_TLIGHTFUNCTION -#endif + while ((lua_isfunction(L, -1) ) && count-- > 0) { // call it and use the return value lua_call(L, 0, 1); // Expecting replacement value @@ -806,7 +824,7 @@ static void sjson_encoder_make_next_chunk(lua_State *L, ENC_DATA *data) { luaL_buffinit(L, &b); // Ending condition - while (data->level >= 0 && !b.lvl) { + while (data->level >= 0 /* && !b.lvl */) { ENC_DATA_STATE *state = &data->stack[data->level]; int finished = 0; @@ -815,7 +833,7 @@ static void sjson_encoder_make_next_chunk(lua_State *L, ENC_DATA *data) { if (state->offset == 0) { // start of object or whatever luaL_addchar(&b, '['); - } + } if (state->offset == state->size << 1) { luaL_addchar(&b, ']'); finished = 1; @@ -849,11 +867,11 @@ static void sjson_encoder_make_next_chunk(lua_State *L, ENC_DATA *data) { if (lua_next(L, -2)) { // save the key if (state->offset & 1) { - lua_unref(L, state->lua_key_ref); + luaL_unref(L, LUA_REGISTRYINDEX, state->lua_key_ref); state->lua_key_ref = LUA_NOREF; // Duplicate the key lua_pushvalue(L, -2); - state->lua_key_ref = lua_ref(L, 1); + state->lua_key_ref = luaL_ref(L, LUA_REGISTRYINDEX); } if ((state->offset & 1) == 0) { @@ -895,7 +913,7 @@ static void sjson_encoder_make_next_chunk(lua_State *L, ENC_DATA *data) { } } luaL_pushresult(&b); - data->current_str_ref = lua_ref(L, 1); + data->current_str_ref = luaL_ref(L, LUA_REGISTRYINDEX); data->offset = 0; } @@ -923,7 +941,7 @@ static int sjson_encoder_read_int(lua_State *L, ENC_DATA *data, int readsize) { readsize -= amnt; if (data->offset == len) { - lua_unref(L, data->current_str_ref); + luaL_unref(L, LUA_REGISTRYINDEX, data->current_str_ref); data->current_str_ref = LUA_NOREF; } } @@ -992,71 +1010,34 @@ static int sjson_encoder_destructor(lua_State *L) { return 0; } -#ifdef LOCAL_LUA -static const luaL_Reg sjson_encoder_map[] = { - { "read", sjson_encoder_read }, - { "__gc", sjson_encoder_destructor }, - { NULL, NULL } -}; -static const luaL_Reg sjson_decoder_map[] = { - { "write", sjson_decoder_write }, - { "result", sjson_decoder_result }, - { "__gc", sjson_decoder_destructor }, - { NULL, NULL } -}; +LROT_BEGIN(sjson_encoder_map, NULL, LROT_MASK_GC_INDEX) + LROT_FUNCENTRY( __gc, sjson_encoder_destructor ) + LROT_TABENTRY( __index, sjson_encoder_map ) + LROT_FUNCENTRY( read, sjson_encoder_read ) +LROT_END(sjson_encoder_map, NULL, LROT_MASK_GC_INDEX) -static const luaL_Reg sjsonlib[] = { - { "decode", sjson_decode }, - { "decoder", sjson_decoder }, - { "encode", sjson_encode }, - { "encoder", sjson_encoder }, - {NULL, NULL} -}; -#else -LROT_BEGIN(sjson_encoder) - LROT_FUNCENTRY( read, sjson_encoder_read ) - LROT_FUNCENTRY( __gc, sjson_encoder_destructor ) - LROT_TABENTRY ( __index, sjson_encoder ) -LROT_END(sjson_encoder, NULL, 0) -LROT_BEGIN(sjson_decoder) - LROT_FUNCENTRY( write, sjson_decoder_write ) - LROT_FUNCENTRY( result, sjson_decoder_result ) - LROT_FUNCENTRY( __gc, sjson_decoder_destructor ) - LROT_TABENTRY ( __index, sjson_decoder ) -LROT_END(sjson_decoder, NULL, 0) -LROT_BEGIN(sjson) - LROT_FUNCENTRY( encode, sjson_encode ) - LROT_FUNCENTRY( decode, sjson_decode ) - LROT_FUNCENTRY( encoder, sjson_encoder ) - LROT_FUNCENTRY( decoder, sjson_decoder ) - LROT_LUDENTRY ( NULL, 0 ) +LROT_BEGIN(sjson_decoder_map, NULL, LROT_MASK_GC_INDEX) + LROT_FUNCENTRY( __gc, sjson_decoder_destructor ) + LROT_TABENTRY( __index, sjson_decoder_map ) + LROT_FUNCENTRY( write, sjson_decoder_write ) + LROT_FUNCENTRY( result, sjson_decoder_result ) +LROT_END(sjson_decoder_map, NULL, LROT_MASK_GC_INDEX) + + +LROT_BEGIN(sjson, NULL, 0) + LROT_FUNCENTRY( encode, sjson_encode ) + LROT_FUNCENTRY( decode, sjson_decode ) + LROT_FUNCENTRY( encoder, sjson_encoder ) + LROT_FUNCENTRY( decoder, sjson_decoder ) LROT_END(sjson, NULL, 0) -#endif LUALIB_API int luaopen_sjson (lua_State *L) { -#ifdef LOCAL_LUA - luaL_register(L, LUA_SJSONLIBNAME, sjsonlib); - lua_getglobal(L, LUA_SJSONLIBNAME); - lua_pushstring(L, "NULL"); - lua_pushlightuserdata(L, 0); - lua_settable(L, -3); - lua_pop(L, 1); - luaL_newmetatable(L, "sjson.encoder"); - luaL_register(L, NULL, sjson_encoder_map); - lua_setfield(L, -1, "__index"); - luaL_newmetatable(L, "sjson.decoder"); - luaL_register(L, NULL, sjson_decoder_map); - lua_setfield(L, -1, "__index"); -#else - luaL_rometatable(L, "sjson.decoder", (void *)sjson_decoder_map); - luaL_rometatable(L, "sjson.encoder", (void *)sjson_encoder_map); -#endif + luaL_rometatable(L, "sjson.decoder", LROT_TABLEREF(sjson_decoder_map)); + luaL_rometatable(L, "sjson.encoder", LROT_TABLEREF(sjson_encoder_map)); return 1; } -#ifndef LOCAL_LUA NODEMCU_MODULE(SJSON, "sjson", sjson, luaopen_sjson); -#endif diff --git a/components/modules/sodium.c b/components/modules/sodium.c index 1431849a..878bd6ef 100644 --- a/components/modules/sodium.c +++ b/components/modules/sodium.c @@ -129,19 +129,19 @@ static int l_crypto_box_seal_open(lua_State *L) return 1; } -LROT_BEGIN(random) +LROT_BEGIN(random, NULL, 0) LROT_FUNCENTRY(random, l_randombytes_random) LROT_FUNCENTRY(uniform, l_randombytes_uniform) LROT_FUNCENTRY(buf, l_randombytes_buf) LROT_END(random, NULL, 0) -LROT_BEGIN(crypto_box) +LROT_BEGIN(crypto_box, NULL, 0) LROT_FUNCENTRY(keypair, l_crypto_box_keypair) LROT_FUNCENTRY(seal, l_crypto_box_seal) LROT_FUNCENTRY(seal_open, l_crypto_box_seal_open) LROT_END(crypto_box, NULL, 0) -LROT_BEGIN(sodium) +LROT_BEGIN(sodium, NULL, 0) LROT_TABENTRY(random, random) LROT_TABENTRY(crypto_box, crypto_box) LROT_END(sodium, NULL, 0) diff --git a/components/modules/spi.c b/components/modules/spi.c index 91d167da..3424e173 100644 --- a/components/modules/spi.c +++ b/components/modules/spi.c @@ -7,7 +7,7 @@ #include "driver/spi_common.h" -LROT_BEGIN(lspi) +LROT_BEGIN(lspi, NULL, 0) LROT_FUNCENTRY( master, lspi_master ) // LROT_FUNCENTRY( slave, lspi_slave ) #if defined(CONFIG_IDF_TARGET_ESP32) diff --git a/components/modules/spi_master.c b/components/modules/spi_master.c index 97b58c26..0642a8c6 100644 --- a/components/modules/spi_master.c +++ b/components/modules/spi_master.c @@ -177,11 +177,11 @@ free_mem: } -LROT_BEGIN(lspi_device) - LROT_FUNCENTRY( transfer, lspi_device_transfer ) - LROT_FUNCENTRY( remove, lspi_device_free ) +LROT_BEGIN(lspi_device, NULL, 0) LROT_FUNCENTRY( __gc, lspi_device_free ) LROT_TABENTRY( __index, lspi_device ) + LROT_FUNCENTRY( transfer, lspi_device_transfer ) + LROT_FUNCENTRY( remove, lspi_device_free ) LROT_END(lspi_device, NULL, 0) @@ -320,11 +320,11 @@ static int lspi_host_device( lua_State *L ) } -LROT_BEGIN(lspi_master) - LROT_FUNCENTRY( device, lspi_host_device ) - LROT_FUNCENTRY( close, lspi_host_free ) +LROT_BEGIN(lspi_master, NULL, 0) LROT_FUNCENTRY( __gc, lspi_host_free ) LROT_TABENTRY( __index, lspi_master ) + LROT_FUNCENTRY( device, lspi_host_device ) + LROT_FUNCENTRY( close, lspi_host_free ) LROT_END(lspi_master, NULL, 0) @@ -332,7 +332,7 @@ LROT_END(lspi_master, NULL, 0) // Generic // int luaopen_spi_master( lua_State *L ) { - luaL_rometatable(L, UD_HOST_STR, (void *)lspi_master_map); - luaL_rometatable(L, UD_DEVICE_STR, (void *)lspi_device_map); + luaL_rometatable(L, UD_HOST_STR, LROT_TABLEREF(lspi_master)); + luaL_rometatable(L, UD_DEVICE_STR, LROT_TABLEREF(lspi_device)); return 0; } diff --git a/components/modules/struct.c b/components/modules/struct.c index ac6ccda5..7a6ebb7c 100644 --- a/components/modules/struct.c +++ b/components/modules/struct.c @@ -392,7 +392,7 @@ static int b_size (lua_State *L) { -LROT_BEGIN(thislib) +LROT_BEGIN(thislib, NULL, 0) LROT_FUNCENTRY(pack, b_pack) LROT_FUNCENTRY(unpack, b_unpack) LROT_FUNCENTRY(size, b_size) diff --git a/components/modules/time.c b/components/modules/time.c index cc7acd4d..155fb409 100644 --- a/components/modules/time.c +++ b/components/modules/time.c @@ -118,7 +118,7 @@ static int time_epoch2cal(lua_State *L) static int time_cal2epoc(lua_State *L) { struct tm date; - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); lua_getfield (L, 1, "year"); date.tm_year = luaL_optinteger(L, -1, 1900) - 1900; @@ -143,7 +143,7 @@ static int time_cal2epoc(lua_State *L) return 1; } -LROT_BEGIN(time) +LROT_BEGIN(time, NULL, 0) LROT_FUNCENTRY(set, time_set) LROT_FUNCENTRY(get, time_get) LROT_FUNCENTRY(getlocal, time_getLocal) diff --git a/components/modules/tmr.c b/components/modules/tmr.c index 644c763b..85a3cea0 100755 --- a/components/modules/tmr.c +++ b/components/modules/tmr.c @@ -59,7 +59,7 @@ static void alarm_timer_task(task_param_t param, task_prio_t prio) luaL_unref(L, LUA_REGISTRYINDEX, tmr->self_ref); tmr->self_ref = LUA_NOREF; } - lua_call(L, 1, 0); + luaL_pcallx(L, 1, 0); } static tmr_t tmr_get( lua_State *L, int stack ) @@ -81,7 +81,7 @@ static int tmr_register(lua_State* L) luaL_argcheck(L, mode == TIMER_MODE_SINGLE || mode == TIMER_MODE_SEMI || mode == TIMER_MODE_AUTO, stack, "Invalid mode"); ++stack; - luaL_argcheck(L, lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION, stack, "Must be function"); + luaL_checkfunction(L, stack); if (tmr->timer) { // delete previous timer since mode change could be requested here @@ -235,7 +235,9 @@ static int tmr_create( lua_State *L ) { // Module function map -LROT_BEGIN(tmr_dyn) +LROT_BEGIN(tmr_dyn, NULL, 0) + LROT_FUNCENTRY( __gc, tmr_unregister ) + LROT_TABENTRY ( __index, tmr_dyn ) LROT_FUNCENTRY( register, tmr_register ) LROT_FUNCENTRY( alarm, tmr_alarm ) LROT_FUNCENTRY( start, tmr_start ) @@ -243,11 +245,9 @@ LROT_BEGIN(tmr_dyn) LROT_FUNCENTRY( unregister, tmr_unregister ) LROT_FUNCENTRY( interval, tmr_interval) LROT_FUNCENTRY( state, tmr_state ) - LROT_FUNCENTRY( __gc, tmr_unregister ) - LROT_TABENTRY ( __index, tmr_dyn ) LROT_END(tmr_dyn, NULL, 0) -LROT_BEGIN(tmr) +LROT_BEGIN(tmr, NULL, 0) LROT_FUNCENTRY( create, tmr_create ) LROT_NUMENTRY ( ALARM_SINGLE, TIMER_MODE_SINGLE ) LROT_NUMENTRY ( ALARM_SEMI, TIMER_MODE_SEMI ) @@ -255,7 +255,7 @@ LROT_BEGIN(tmr) LROT_END(tmr, NULL, 0) static int luaopen_tmr( lua_State *L ){ - luaL_rometatable(L, "tmr.timer", (void *)tmr_dyn_map); + luaL_rometatable(L, "tmr.timer", LROT_TABLEREF(tmr_dyn)); alarm_task_id = task_get_id(alarm_timer_task); diff --git a/components/modules-esp32/touch.c b/components/modules/touch.c similarity index 98% rename from components/modules-esp32/touch.c rename to components/modules/touch.c index f429fa0e..367fcb8a 100644 --- a/components/modules-esp32/touch.c +++ b/components/modules/touch.c @@ -141,7 +141,7 @@ static void touch_task(task_param_t param, task_prio_t prio) // call the cb_ref with one argument /* do the call (1 argument, 0 results) */ - if (lua_pcall(L, 1, 0, 0) != 0) { + if (luaL_pcallx(L, 1, 0) != 0) { ESP_LOGI(TAG, "error running callback function `f': %s", funcName); } } @@ -179,7 +179,7 @@ static int touch_create( lua_State *L ) { touch_t tp = &tpObj; // const int top = lua_gettop(L); - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); tp->is_debug = opt_checkbool(L, "isDebug", false); tp->filterMs = opt_checkint(L, "filterMs", 0); @@ -227,8 +227,8 @@ static int touch_create( lua_State *L ) { isCallback = false; if (tp->is_debug) ESP_LOGI(TAG, "No callback provided. Not turning on interrupt." ); } else { - luaL_argcheck(L, lua_type(L, -1) == LUA_TFUNCTION || lua_type(L, -1) == LUA_TLIGHTFUNCTION, -1, "Cb must be function"); - + luaL_checkfunction(L, -1); + //get the lua function reference luaL_unref(L, LUA_REGISTRYINDEX, tp->cb_ref); lua_pushvalue(L, -1); @@ -589,19 +589,18 @@ static int touch_unregister(lua_State* L) { return 0; } -LROT_BEGIN(touch_dyn) +LROT_BEGIN(touch_dyn, NULL, 0) + LROT_FUNCENTRY( __gc, touch_unregister ) + LROT_TABENTRY ( __index, touch_dyn ) + // LROT_FUNCENTRY( __tostring, touch_tostring ) LROT_FUNCENTRY( read, touch_read ) LROT_FUNCENTRY( intrEnable, touch_intrEnable ) LROT_FUNCENTRY( intrDisable, touch_intrDisable ) LROT_FUNCENTRY( setThres, touch_setThres ) LROT_FUNCENTRY( setTriggerMode, touch_setTriggerMode ) - - // LROT_FUNCENTRY( __tostring, touch_tostring ) - LROT_FUNCENTRY( __gc, touch_unregister ) - LROT_TABENTRY ( __index, touch_dyn ) LROT_END(touch_dyn, NULL, 0) -LROT_BEGIN(touch) +LROT_BEGIN(touch, NULL, 0) LROT_FUNCENTRY( create, touch_create ) LROT_NUMENTRY ( TOUCH_HVOLT_KEEP, TOUCH_HVOLT_KEEP ) LROT_NUMENTRY ( TOUCH_HVOLT_2V4, TOUCH_HVOLT_2V4 ) @@ -626,7 +625,7 @@ LROT_END(touch, NULL, 0) int luaopen_touch(lua_State *L) { - luaL_rometatable(L, "touch.pctr", (void *)touch_dyn_map); + luaL_rometatable(L, "touch.pctr", LROT_TABLEREF(touch_dyn)); touch_task_id = task_get_id(touch_task); diff --git a/components/modules/u8g2.c b/components/modules/u8g2.c index 3e171cc5..0ec828a2 100644 --- a/components/modules/u8g2.c +++ b/components/modules/u8g2.c @@ -558,7 +558,9 @@ static int lu8g2_updateDisplayArea( lua_State *L ) } -LROT_BEGIN(lu8g2_display) +LROT_BEGIN(lu8g2_display, NULL, 0) + //LROT_FUNCENTRY( __gc, lu8g2_display_free ) + LROT_TABENTRY( __index, lu8g2_display ) LROT_FUNCENTRY( clearBuffer, lu8g2_clearBuffer ) LROT_FUNCENTRY( drawBox, lu8g2_drawBox ) LROT_FUNCENTRY( drawCircle, lu8g2_drawCircle ) @@ -600,8 +602,6 @@ LROT_BEGIN(lu8g2_display) LROT_FUNCENTRY( setPowerSave, lu8g2_setPowerSave ) LROT_FUNCENTRY( updateDispla, lu8g2_updateDisplay ) LROT_FUNCENTRY( updateDisplayArea, lu8g2_updateDisplayArea ) - //LROT_FUNCENTRY( __gc, lu8g2_display_free ) - LROT_TABENTRY( __index, lu8g2_display ) LROT_END(lu8g2_display, NULL, 0) @@ -802,7 +802,7 @@ U8G2_DISPLAY_TABLE_SPI #define U8G2_DISPLAY_TABLE_ENTRY(function, binding) \ LROT_FUNCENTRY( binding, l ## binding ) -LROT_BEGIN(lu8g2) +LROT_BEGIN(lu8g2, NULL, 0) U8G2_DISPLAY_TABLE_I2C U8G2_DISPLAY_TABLE_SPI // @@ -824,7 +824,7 @@ LROT_BEGIN(lu8g2) LROT_END(lu8g2, NULL, 0) int luaopen_u8g2( lua_State *L ) { - luaL_rometatable(L, "u8g2.display", (void *)lu8g2_display_map); + luaL_rometatable(L, "u8g2.display", LROT_TABLEREF(lu8g2_display)); return 0; } diff --git a/components/base_nodemcu/uart.c b/components/modules/uart.c similarity index 93% rename from components/base_nodemcu/uart.c rename to components/modules/uart.c index 26fe5071..118be37d 100644 --- a/components/base_nodemcu/uart.c +++ b/components/modules/uart.c @@ -3,15 +3,13 @@ #include "module.h" #include "lauxlib.h" #include "platform.h" -#include "driver/console.h" +#include "linput.h" #include #include -extern uart_status_t uart_status[NUM_UART]; - static lua_State *gL = NULL; -bool run_input = true; + bool uart_on_data_cb(unsigned id, const char *buf, size_t len){ if(!buf || len==0) return false; @@ -23,7 +21,7 @@ bool uart_on_data_cb(unsigned id, const char *buf, size_t len){ int top = lua_gettop(gL); lua_rawgeti(gL, LUA_REGISTRYINDEX, uart_status[id].receive_rf); lua_pushlstring(gL, buf, len); - lua_pcall(gL, 1, 0, 0); + luaL_pcallx(gL, 1, 0); lua_settop(gL, top); return !run_input; } @@ -39,7 +37,7 @@ bool uart_on_error_cb(unsigned id, const char *buf, size_t len){ int top = lua_gettop(gL); lua_rawgeti(gL, LUA_REGISTRYINDEX, uart_status[id].error_rf); lua_pushlstring(gL, buf, len); - lua_pcall(gL, 1, 0, 0); + luaL_pcallx(gL, 1, 0); lua_settop(gL, top); return true; } @@ -47,7 +45,7 @@ bool uart_on_error_cb(unsigned id, const char *buf, size_t len){ // Lua: uart.on([id], "method", [number/char], function, [run_input]) static int uart_on( lua_State* L ) { - unsigned id = CONSOLE_UART; + unsigned id = CONFIG_ESP_CONSOLE_UART_NUM; size_t sl, el; int32_t run = 1; uint8_t stack = 1; @@ -86,8 +84,7 @@ static int uart_on( lua_State* L ) us->need_len = 0; } - // luaL_checkanyfunction(L, stack); - if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){ + if (lua_isfunction(L, stack)) { if ( lua_isnumber(L, stack+1) ){ run = lua_tointeger(L, stack+1); } @@ -96,7 +93,7 @@ static int uart_on( lua_State* L ) lua_pushnil(L); } if(sl == 4 && strcmp(method, "data") == 0){ - if(id == CONSOLE_UART) + if(id == CONFIG_ESP_CONSOLE_UART_NUM) run_input = true; if(us->receive_rf != LUA_NOREF){ luaL_unref(L, LUA_REGISTRYINDEX, us->receive_rf); @@ -105,7 +102,7 @@ static int uart_on( lua_State* L ) if(!lua_isnil(L, -1)){ us->receive_rf = luaL_ref(L, LUA_REGISTRYINDEX); gL = L; - if(id == CONSOLE_UART && run==0) + if(id == CONFIG_ESP_CONSOLE_UART_NUM && run==0) run_input = false; } else { lua_pop(L, 1); @@ -128,7 +125,6 @@ static int uart_on( lua_State* L ) return 0; } -bool uart0_echo = true; // Lua: actualbaud = setup( id, baud, databits, parity, stopbits, echo ) static int uart_setup( lua_State* L ) { @@ -142,13 +138,13 @@ static int uart_setup( lua_State* L ) databits = luaL_checkinteger( L, 3 ); parity = luaL_checkinteger( L, 4 ); stopbits = luaL_checkinteger( L, 5 ); - if(id == CONSOLE_UART && lua_isnumber(L,6)){ + if(id == CONFIG_ESP_CONSOLE_UART_NUM && lua_isnumber(L,6)){ echo = lua_tointeger(L,6); if(echo!=0) - uart0_echo = true; + input_echo = true; else - uart0_echo = false; - } else if(id != CONSOLE_UART && lua_istable( L, 6 )) { + input_echo = false; + } else if(id != CONFIG_ESP_CONSOLE_UART_NUM && lua_istable( L, 6 )) { lua_getfield (L, 6, "tx"); pins.tx_pin = luaL_checkint(L, -1); lua_getfield (L, 6, "rx"); @@ -280,7 +276,7 @@ static int luart_tx_flush (lua_State *L) } // Module function map -LROT_BEGIN(uart) +LROT_BEGIN(uart, NULL, 0) LROT_FUNCENTRY( setup, uart_setup ) LROT_FUNCENTRY( write, uart_write ) LROT_FUNCENTRY( start, uart_start ) diff --git a/components/modules/ucg.c b/components/modules/ucg.c index e05d18a5..8f5df8a4 100644 --- a/components/modules/ucg.c +++ b/components/modules/ucg.c @@ -678,7 +678,9 @@ UCG_DISPLAY_TABLE // Module function map -LROT_BEGIN(lucg_display) +LROT_BEGIN(lucg_display, NULL, 0) + LROT_FUNCENTRY( __gc, lucg_close_display ) + LROT_TABENTRY( __index, lucg_display ) LROT_FUNCENTRY( begin, lucg_begin ) LROT_FUNCENTRY( clearScreen, lucg_clearScreen ) LROT_FUNCENTRY( draw90Line, lucg_draw90Line ) @@ -722,11 +724,10 @@ LROT_BEGIN(lucg_display) LROT_FUNCENTRY( undoClipRange, lucg_setMaxClipRange ) LROT_FUNCENTRY( undoRotate, lucg_undoRotate ) LROT_FUNCENTRY( undoScale, lucg_undoScale ) - LROT_FUNCENTRY( __gc, lucg_close_display ) - LROT_TABENTRY( __index, lucg_display ) LROT_END(lucg_display, NULL, 0) -LROT_BEGIN(lucg) +LROT_BEGIN(lucg, NULL, 0) + LROT_TABENTRY( __metatable, lucg ) #undef UCG_DISPLAY_TABLE_ENTRY #define UCG_DISPLAY_TABLE_ENTRY(binding, device, extension) LROT_FUNCENTRY( binding, l ## binding ) UCG_DISPLAY_TABLE @@ -746,13 +747,11 @@ LROT_BEGIN(lucg) LROT_NUMENTRY( DRAW_LOWER_RIGHT, UCG_DRAW_LOWER_RIGHT ) LROT_NUMENTRY( DRAW_LOWER_LEFT, UCG_DRAW_LOWER_LEFT ) LROT_NUMENTRY( DRAW_ALL, UCG_DRAW_ALL ) - - LROT_TABENTRY( __metatable, lucg ) LROT_END(lucg, NULL, 0) int luaopen_ucg( lua_State *L ) { - luaL_rometatable(L, "ucg.display", (void *)lucg_display_map); // create metatable + luaL_rometatable(L, "ucg.display", LROT_TABLEREF(lucg_display)); // create metatable return 0; } diff --git a/components/modules/wifi.c b/components/modules/wifi.c index 343b1884..489c804a 100644 --- a/components/modules/wifi.c +++ b/components/modules/wifi.c @@ -108,10 +108,10 @@ static int wifi_init (lua_State *L) } -LROT_EXTERN(wifi_sta); -LROT_EXTERN(wifi_ap); +extern LROT_TABLE(wifi_sta); +extern LROT_TABLE(wifi_ap); -LROT_BEGIN(wifi) +LROT_BEGIN(wifi, NULL, 0) LROT_FUNCENTRY( getchannel, wifi_getchannel ) LROT_FUNCENTRY( getmode, wifi_getmode ) LROT_FUNCENTRY( mode, wifi_mode ) diff --git a/components/modules/wifi_ap.c b/components/modules/wifi_ap.c index 5bccc712..e9cb4012 100644 --- a/components/modules/wifi_ap.c +++ b/components/modules/wifi_ap.c @@ -115,7 +115,7 @@ static void on_event (esp_event_base_t base, int32_t id, const void *data) lua_pushstring (L, events[idx].name); lua_createtable (L, 0, 5); events[idx].fill_cb_arg (L, data); - lua_call (L, 2, 0); + luaL_pcallx (L, 2, 0); } NODEMCU_ESP_EVENT(WIFI_EVENT, WIFI_EVENT_AP_START, on_event); @@ -136,7 +136,7 @@ void wifi_ap_init (void) static int wifi_ap_setip(lua_State *L) { - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); size_t len = 0; const char *str = NULL; @@ -202,7 +202,7 @@ static int wifi_ap_sethostname(lua_State *L) static int wifi_ap_config (lua_State *L) { - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); bool save = luaL_optbool (L, 2, DEFAULT_SAVE); wifi_config_t cfg; @@ -257,7 +257,7 @@ static int wifi_ap_on (lua_State *L) } -LROT_PUBLIC_BEGIN(wifi_ap) +LROT_BEGIN(wifi_ap, NULL, 0) LROT_FUNCENTRY( setip, wifi_ap_setip ) LROT_FUNCENTRY( sethostname, wifi_ap_sethostname ) LROT_FUNCENTRY( config, wifi_ap_config ) diff --git a/components/modules/wifi_common.c b/components/modules/wifi_common.c index 03dd0790..0aa9d266 100644 --- a/components/modules/wifi_common.c +++ b/components/modules/wifi_common.c @@ -63,7 +63,7 @@ int wifi_on (lua_State *L, const event_desc_t *table, unsigned n, int *event_cb) { const char *event_name = luaL_checkstring (L, 1); if (!lua_isnoneornil (L, 2)) - luaL_checkanyfunction (L, 2); + luaL_checkfunction (L, 2); lua_settop (L, 2); int idx = wifi_event_idx_by_name (table, n, event_name); diff --git a/components/modules/wifi_sta.c b/components/modules/wifi_sta.c index b207a76f..acf40b76 100644 --- a/components/modules/wifi_sta.c +++ b/components/modules/wifi_sta.c @@ -141,7 +141,7 @@ static void on_event (esp_event_base_t base, int32_t id, const void *data) lua_pushstring (L, events[idx].name); lua_createtable (L, 0, 5); events[idx].fill_cb_arg (L, data); - lua_call (L, 2, 0); + luaL_pcallx (L, 2, 0); } NODEMCU_ESP_EVENT(WIFI_EVENT, WIFI_EVENT_STA_START, on_event); @@ -164,7 +164,7 @@ void wifi_sta_init (void) // --- Lua API functions ---------------------------------------------------- static int wifi_sta_setip(lua_State *L) { - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); size_t len = 0; const char *str = NULL; @@ -224,7 +224,7 @@ static int wifi_sta_sethostname(lua_State *L) static int wifi_sta_config (lua_State *L) { - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); bool save = luaL_optbool (L, 2, DEFAULT_SAVE); lua_settop (L, 1); @@ -390,7 +390,7 @@ static void on_scan_done(esp_event_base_t base, int32_t id, const void *data) else lua_pushfstring (L, "failure on scan done"); luaM_free (L, aps); - lua_call (L, nargs, 0); + luaL_pcallx (L, nargs, 0); } } @@ -405,9 +405,9 @@ static int wifi_sta_scan (lua_State *L) if (scan_cb_ref != LUA_NOREF) return luaL_error (L, "scan already in progress"); - luaL_checkanytable (L, 1); + luaL_checktable (L, 1); - luaL_checkanyfunction (L, 2); + luaL_checkfunction (L, 2); lua_settop (L, 2); scan_cb_ref = luaL_ref (L, LUA_REGISTRYINDEX); @@ -438,7 +438,7 @@ static int wifi_sta_scan (lua_State *L) } -LROT_PUBLIC_BEGIN(wifi_sta) +LROT_BEGIN(wifi_sta, NULL, 0) LROT_FUNCENTRY( setip, wifi_sta_setip ) LROT_FUNCENTRY( sethostname, wifi_sta_sethostname ) LROT_FUNCENTRY( config, wifi_sta_config ) diff --git a/components/modules/ws2812.c b/components/modules/ws2812.c index 681878c6..2021dc1b 100644 --- a/components/modules/ws2812.c +++ b/components/modules/ws2812.c @@ -497,7 +497,10 @@ static int ws2812_buffer_tostring(lua_State* L) { return 1; } -LROT_BEGIN(ws2812_buffer) +LROT_BEGIN(ws2812_buffer, NULL, 0) + LROT_FUNCENTRY( __concat, ws2812_buffer_concat ) + LROT_TABENTRY ( __index, ws2812_buffer ) + LROT_FUNCENTRY( __tostring, ws2812_buffer_tostring ) LROT_FUNCENTRY( dump, ws2812_buffer_dump ) LROT_FUNCENTRY( fade, ws2812_buffer_fade ) LROT_FUNCENTRY( fill, ws2812_buffer_fill ) @@ -509,12 +512,9 @@ LROT_BEGIN(ws2812_buffer) LROT_FUNCENTRY( shift, ws2812_buffer_shift ) LROT_FUNCENTRY( size, ws2812_buffer_size ) LROT_FUNCENTRY( sub, ws2812_buffer_sub ) - LROT_FUNCENTRY( __concat, ws2812_buffer_concat ) - LROT_TABENTRY ( __index, ws2812_buffer ) - LROT_FUNCENTRY( __tostring, ws2812_buffer_tostring ) LROT_END(ws2812_buffer, NULL, 0) -LROT_BEGIN(ws2812) +LROT_BEGIN(ws2812, NULL, 0) LROT_FUNCENTRY( newBuffer, ws2812_new_buffer ) LROT_FUNCENTRY( write, ws2812_write ) LROT_NUMENTRY ( FADE_IN, FADE_IN ) @@ -525,7 +525,7 @@ LROT_END(ws2812, NULL, 0) int luaopen_ws2812(lua_State *L) { // TODO: Make sure that the GPIO system is initialized - luaL_rometatable(L, "ws2812.buffer", (void *)ws2812_buffer_map); // create metatable for ws2812.buffer + luaL_rometatable(L, "ws2812.buffer", LROT_TABLEREF(ws2812_buffer)); // create metatable for ws2812.buffer return 0; } diff --git a/components/platform/CMakeLists.txt b/components/platform/CMakeLists.txt index f25d8043..f8c285d0 100644 --- a/components/platform/CMakeLists.txt +++ b/components/platform/CMakeLists.txt @@ -3,6 +3,6 @@ idf_component_register( "platform_flash.c" "platform_partition.c" "platform_rmt.c" "u8x8_nodemcu_hal.c" "ucg_nodemcu_hal.c" "vfs.c" "wdt.c" "ws2812.c" INCLUDE_DIRS "include" - REQUIRES "spiffs" "u8g2" "ucg" "driver_i2c" - PRIV_REQUIRES "bootloader_support" "driver_console" "lua" "esp32" + REQUIRES "spiffs" "u8g2" "ucg" "driver_i2c" "task" + PRIV_REQUIRES "bootloader_support" "lua" "esp32" ) diff --git a/components/platform/Kconfig b/components/platform/Kconfig index 103fd527..1c174384 100644 --- a/components/platform/Kconfig +++ b/components/platform/Kconfig @@ -1,79 +1,5 @@ menu "NodeMCU platform config" - choice NODEMCU_CONSOLE_BIT_RATE - prompt "UART console default bit rate" - default NODEMCU_CONSOLE_BIT_RATE_115200 - help - Configure the default bit rate for the UART console. - - The resulting UART setting will be xxx-8N1, where xxx represents - the chosen bit rate. - config NODEMCU_CONSOLE_BIT_RATE_300 - bool "300" - config NODEMCU_CONSOLE_BIT_RATE_600 - bool "600" - config NODEMCU_CONSOLE_BIT_RATE_1200 - bool "1200" - config NODEMCU_CONSOLE_BIT_RATE_2400 - bool "2400" - config NODEMCU_CONSOLE_BIT_RATE_4800 - bool "4800" - config NODEMCU_CONSOLE_BIT_RATE_9600 - bool "9600" - config NODEMCU_CONSOLE_BIT_RATE_19200 - bool "19200" - config NODEMCU_CONSOLE_BIT_RATE_38400 - bool "38400" - config NODEMCU_CONSOLE_BIT_RATE_57600 - bool "57600" - config NODEMCU_CONSOLE_BIT_RATE_74880 - bool "74880" - config NODEMCU_CONSOLE_BIT_RATE_115200 - bool "115200" - config NODEMCU_CONSOLE_BIT_RATE_230400 - bool "230400" - config NODEMCU_CONSOLE_BIT_RATE_460800 - bool "460800" - config NODEMCU_CONSOLE_BIT_RATE_921600 - bool "921600" - config NODEMCU_CONSOLE_BIT_RATE_1843200 - bool "1843200" - config NODEMCU_CONSOLE_BIT_RATE_3683400 - bool "3683400" - endchoice - - config NODEMCU_CONSOLE_BIT_RATE - int - default 300 if NODEMCU_CONSOLE_BIT_RATE_300 - default 600 if NODEMCU_CONSOLE_BIT_RATE_600 - default 1200 if NODEMCU_CONSOLE_BIT_RATE_1200 - default 2400 if NODEMCU_CONSOLE_BIT_RATE_2400 - default 4800 if NODEMCU_CONSOLE_BIT_RATE_4800 - default 9600 if NODEMCU_CONSOLE_BIT_RATE_9600 - default 19200 if NODEMCU_CONSOLE_BIT_RATE_19200 - default 38400 if NODEMCU_CONSOLE_BIT_RATE_38400 - default 57600 if NODEMCU_CONSOLE_BIT_RATE_57600 - default 74880 if NODEMCU_CONSOLE_BIT_RATE_74880 - default 115200 if NODEMCU_CONSOLE_BIT_RATE_115200 - default 230400 if NODEMCU_CONSOLE_BIT_RATE_230400 - default 460800 if NODEMCU_CONSOLE_BIT_RATE_460800 - default 921600 if NODEMCU_CONSOLE_BIT_RATE_921600 - default 1843200 if NODEMCU_CONSOLE_BIT_RATE_1843200 - default 3683400 if NODEMCU_CONSOLE_BIT_RATE_3683400 - - config NODEMCU_CONSOLE_BIT_RATE_AUTO - bool "UART console auto-baud detection" - default "y" - help - Enables auto-baud detection for the UART console. - - By typing a few characters into the console shortly after boot, - NodeMCU can automatically detect your terminal settings and - adjust accordingly. - - If you are doing advanced things with the console, you may want - to disable this feature. - config NODEMCU_NODE_DEBUG bool "Enable NODE_DBG() output" default "n" diff --git a/components/platform/include/platform.h b/components/platform/include/platform.h index 1f345874..9a1cd71e 100644 --- a/components/platform/include/platform.h +++ b/components/platform/include/platform.h @@ -101,12 +101,7 @@ typedef struct { int16_t end_char; } uart_status_t; -typedef struct { - unsigned id; - int type; - size_t size; - char* data; -} uart_event_post_t; +extern uart_status_t uart_status[NUM_UART]; // Flow control types (this is a bit mask, one can specify PLATFORM_UART_FLOW_RTS | PLATFORM_UART_FLOW_CTS ) #define PLATFORM_UART_FLOW_NONE 0 @@ -266,14 +261,6 @@ typedef struct { */ bool platform_partition_info (uint8_t idx, platform_partition_t *info); -/** - * Appends a partition entry to the partition table, if possible. - * Intended for auto-creation of a SPIFFS partition. - * @param info The partition definition to append. - * @returns True if the partition could be added, false if not. - */ -bool platform_partition_add (const platform_partition_t *info); - // ***************************************************************************** // Helper macros @@ -293,4 +280,6 @@ bool platform_partition_add (const platform_partition_t *info); +void platform_print_deprecation_note( const char *msg, const char *time_frame); + #endif diff --git a/components/platform/include/user_version.h b/components/platform/include/user_version.h index 18b89487..82d47f4f 100644 --- a/components/platform/include/user_version.h +++ b/components/platform/include/user_version.h @@ -11,7 +11,7 @@ #define BUILD_DATE "unspecified" #endif -#define SDK_VERSION "IDF" +#define SDK_VERSION IDF_VER #endif /* __USER_VERSION_H__ */ diff --git a/components/platform/platform.c b/components/platform/platform.c index 88e5e70f..d0178ea9 100644 --- a/components/platform/platform.c +++ b/components/platform/platform.c @@ -1,5 +1,4 @@ #include "platform.h" -#include "driver/console.h" #include "driver/sigmadelta.h" #include "driver/adc.h" #include "driver/uart.h" @@ -10,6 +9,8 @@ #include "lua.h" #include "rom/uart.h" #include "esp_log.h" +#include "task/task.h" +#include "linput.h" int platform_init (void) { @@ -33,42 +34,52 @@ int platform_gpio_output_exists( unsigned gpio ) { return GPIO_IS_VALID_OUTPUT_G #define PLATFORM_UART_EVENT_RX (UART_EVENT_MAX + 3) #define PLATFORM_UART_EVENT_BREAK (UART_EVENT_MAX + 4) +typedef struct { + unsigned id; + int type; + size_t size; + char* data; +} uart_event_post_t; + static const char *UART_TAG = "uart"; uart_status_t uart_status[NUM_UART]; - +task_handle_t uart_event_task_id = 0; SemaphoreHandle_t sem = NULL; extern bool uart_on_data_cb(unsigned id, const char *buf, size_t len); extern bool uart_on_error_cb(unsigned id, const char *buf, size_t len); -task_handle_t uart_event_task_id = 0; void uart_event_task( task_param_t param, task_prio_t prio ) { - uint16_t need_len; - int16_t end_char; - char ch; - unsigned id; - uart_status_t *us; uart_event_post_t *post = (uart_event_post_t *)param; - id = post->id; - us = & uart_status[id]; + unsigned id = post->id; + uart_status_t *us = &uart_status[id]; xSemaphoreGive(sem); if(post->type == PLATFORM_UART_EVENT_DATA) { - for(size_t p = 0; p < post->size; p++) { - ch = post->data[p]; - us->line_buffer[us->line_position] = ch; - us->line_position++; + size_t i = 0; + while (i < post->size) + { + if (id == CONFIG_ESP_CONSOLE_UART_NUM && run_input) { + unsigned used = feed_lua_input(post->data + i, post->size - i); + i += used; + } + else { + char ch = post->data[i]; + us->line_buffer[us->line_position] = ch; + us->line_position++; - need_len = us->need_len; - end_char = us->end_char; - size_t max_wanted = - (end_char >= 0 && need_len == 0) ? LUA_MAXINPUT : need_len; - bool at_end = (us->line_position >= max_wanted); - bool end_char_found = - (end_char >= 0 && (uint8_t)ch == (uint8_t)end_char); - if (at_end || end_char_found) { - uart_on_data_cb(id, us->line_buffer, us->line_position); - us->line_position = 0; + uint16_t need_len = us->need_len; + int16_t end_char = us->end_char; + size_t max_wanted = + (end_char >= 0 && need_len == 0) ? LUA_MAXINPUT : need_len; + bool at_end = (us->line_position >= max_wanted); + bool end_char_found = + (end_char >= 0 && (uint8_t)ch == (uint8_t)end_char); + if (at_end || end_char_found) { + uart_on_data_cb(id, us->line_buffer, us->line_position); + us->line_position = 0; + } + ++i; } } free(post->data); @@ -177,88 +188,53 @@ static void task_uart( void *pvParameters ){ // pins must not be null for non-console uart uint32_t platform_uart_setup( unsigned id, uint32_t baud, int databits, int parity, int stopbits, uart_pins_t* pins ) { - if (id == CONSOLE_UART) + int flow_control = UART_HW_FLOWCTRL_DISABLE; + if(pins->flow_control & PLATFORM_UART_FLOW_CTS) flow_control |= UART_HW_FLOWCTRL_CTS; + if(pins->flow_control & PLATFORM_UART_FLOW_RTS) flow_control |= UART_HW_FLOWCTRL_RTS; + + uart_config_t cfg = { + .baud_rate = baud, + .flow_ctrl = flow_control, + .rx_flow_ctrl_thresh = UART_FIFO_LEN - 16, + }; + + switch (databits) { - ConsoleSetup_t cfg; - cfg.bit_rate = baud; - switch (databits) - { - case 5: cfg.data_bits = CONSOLE_NUM_BITS_5; break; - case 6: cfg.data_bits = CONSOLE_NUM_BITS_6; break; - case 7: cfg.data_bits = CONSOLE_NUM_BITS_7; break; - case 8: // fall-through - default: cfg.data_bits = CONSOLE_NUM_BITS_8; break; - } - switch (parity) - { - case PLATFORM_UART_PARITY_EVEN: cfg.parity = CONSOLE_PARITY_EVEN; break; - case PLATFORM_UART_PARITY_ODD: cfg.parity = CONSOLE_PARITY_ODD; break; - default: // fall-through - case PLATFORM_UART_PARITY_NONE: cfg.parity = CONSOLE_PARITY_NONE; break; - } - switch (stopbits) - { - default: // fall-through - case PLATFORM_UART_STOPBITS_1: - cfg.stop_bits = CONSOLE_STOP_BITS_1; break; - case PLATFORM_UART_STOPBITS_1_5: - cfg.stop_bits = CONSOLE_STOP_BITS_1_5; break; - case PLATFORM_UART_STOPBITS_2: - cfg.stop_bits = CONSOLE_STOP_BITS_2; break; - } - cfg.auto_baud = false; - console_setup (&cfg); - return baud; + case 5: cfg.data_bits = UART_DATA_5_BITS; break; + case 6: cfg.data_bits = UART_DATA_6_BITS; break; + case 7: cfg.data_bits = UART_DATA_7_BITS; break; + case 8: // fall-through + default: cfg.data_bits = UART_DATA_8_BITS; break; } - else + switch (parity) { - int flow_control = UART_HW_FLOWCTRL_DISABLE; - if(pins->flow_control & PLATFORM_UART_FLOW_CTS) flow_control |= UART_HW_FLOWCTRL_CTS; - if(pins->flow_control & PLATFORM_UART_FLOW_RTS) flow_control |= UART_HW_FLOWCTRL_RTS; - - uart_config_t cfg = { - .baud_rate = baud, - .flow_ctrl = flow_control, - .rx_flow_ctrl_thresh = UART_FIFO_LEN - 16, - }; - - switch (databits) - { - case 5: cfg.data_bits = UART_DATA_5_BITS; break; - case 6: cfg.data_bits = UART_DATA_6_BITS; break; - case 7: cfg.data_bits = UART_DATA_7_BITS; break; - case 8: // fall-through - default: cfg.data_bits = UART_DATA_8_BITS; break; - } - switch (parity) - { - case PLATFORM_UART_PARITY_EVEN: cfg.parity = UART_PARITY_EVEN; break; - case PLATFORM_UART_PARITY_ODD: cfg.parity = UART_PARITY_ODD; break; - default: // fall-through - case PLATFORM_UART_PARITY_NONE: cfg.parity = UART_PARITY_DISABLE; break; - } - switch (stopbits) - { - default: // fall-through - case PLATFORM_UART_STOPBITS_1: - cfg.stop_bits = UART_STOP_BITS_1; break; - case PLATFORM_UART_STOPBITS_1_5: - cfg.stop_bits = UART_STOP_BITS_1_5; break; - case PLATFORM_UART_STOPBITS_2: - cfg.stop_bits = UART_STOP_BITS_2; break; - } - uart_param_config(id, &cfg); + case PLATFORM_UART_PARITY_EVEN: cfg.parity = UART_PARITY_EVEN; break; + case PLATFORM_UART_PARITY_ODD: cfg.parity = UART_PARITY_ODD; break; + default: // fall-through + case PLATFORM_UART_PARITY_NONE: cfg.parity = UART_PARITY_DISABLE; break; + } + switch (stopbits) + { + default: // fall-through + case PLATFORM_UART_STOPBITS_1: + cfg.stop_bits = UART_STOP_BITS_1; break; + case PLATFORM_UART_STOPBITS_1_5: + cfg.stop_bits = UART_STOP_BITS_1_5; break; + case PLATFORM_UART_STOPBITS_2: + cfg.stop_bits = UART_STOP_BITS_2; break; + } + uart_param_config(id, &cfg); + + if (pins != NULL) { uart_set_pin(id, pins->tx_pin, pins->rx_pin, pins->rts_pin, pins->cts_pin); uart_set_line_inverse(id, (pins->tx_inverse? UART_TXD_INV_M : 0) | (pins->rx_inverse? UART_RXD_INV_M : 0) | (pins->rts_inverse? UART_RTS_INV_M : 0) | (pins->cts_inverse? UART_CTS_INV_M : 0) ); - - if(uart_event_task_id == 0) uart_event_task_id = task_get_id( uart_event_task ); - - return baud; } + + return baud; } void platform_uart_setmode(unsigned id, unsigned mode) @@ -285,7 +261,7 @@ void platform_uart_setmode(unsigned id, unsigned mode) void platform_uart_send_multi( unsigned id, const char *data, size_t len ) { size_t i; - if (id == CONSOLE_UART) { + if (id == CONFIG_ESP_CONSOLE_UART_NUM) { for( i = 0; i < len; i ++ ) { putchar (data[ i ]); } @@ -296,7 +272,7 @@ void platform_uart_send_multi( unsigned id, const char *data, size_t len ) void platform_uart_send( unsigned id, uint8_t data ) { - if (id == CONSOLE_UART) + if (id == CONFIG_ESP_CONSOLE_UART_NUM) putchar (data); else uart_write_bytes(id, (const char *)&data, 1); @@ -304,7 +280,7 @@ void platform_uart_send( unsigned id, uint8_t data ) void platform_uart_flush( unsigned id ) { - if (id == CONSOLE_UART) + if (id == CONFIG_ESP_CONSOLE_UART_NUM) fflush (stdout); else uart_tx_flush(id); @@ -313,38 +289,38 @@ void platform_uart_flush( unsigned id ) int platform_uart_start( unsigned id ) { - if (id == CONSOLE_UART) - return 0; - else { - uart_status_t *us = & uart_status[id]; - - esp_err_t ret = uart_driver_install(id, UART_BUFFER_SIZE, UART_BUFFER_SIZE, 3, & us->queue, 0); - if(ret != ESP_OK) { - return -1; - } - us->line_buffer = malloc(LUA_MAXINPUT); - us->line_position = 0; - if(us->line_buffer == NULL) { - uart_driver_delete(id); - return -1; - } + if(uart_event_task_id == 0) + uart_event_task_id = task_get_id( uart_event_task ); - char pcName[6]; - snprintf( pcName, 6, "uart%d", id ); - pcName[5] = '\0'; - if(xTaskCreate(task_uart, pcName, 2048, (void*)id, ESP_TASK_MAIN_PRIO + 1, & us->taskHandle) != pdPASS) { - uart_driver_delete(id); - free(us->line_buffer); - us->line_buffer = NULL; - return -1; - } - return 0; + uart_status_t *us = & uart_status[id]; + + esp_err_t ret = uart_driver_install(id, UART_BUFFER_SIZE, UART_BUFFER_SIZE, 3, & us->queue, 0); + if(ret != ESP_OK) { + return -1; } + us->line_buffer = malloc(LUA_MAXINPUT); + us->line_position = 0; + if(us->line_buffer == NULL) { + uart_driver_delete(id); + return -1; + } + + char pcName[6]; + snprintf( pcName, 6, "uart%d", id ); + pcName[5] = '\0'; + if(xTaskCreate(task_uart, pcName, 2048, (void*)id, ESP_TASK_MAIN_PRIO + 1, & us->taskHandle) != pdPASS) { + uart_driver_delete(id); + free(us->line_buffer); + us->line_buffer = NULL; + return -1; + } + + return 0; } void platform_uart_stop( unsigned id ) { - if (id == CONSOLE_UART) + if (id == CONFIG_ESP_CONSOLE_UART_NUM) ; else { uart_status_t *us = & uart_status[id]; @@ -501,15 +477,7 @@ int platform_adc_channel_exists( uint8_t adc, uint8_t channel ) { uint8_t platform_adc_set_width( uint8_t adc, int bits ) { (void)adc; -#if defined(CONFIG_IDF_TARGET_ESP32C3) - if (bits != SOC_ADC_MAX_BITWIDTH) - return 0; - bits = SOC_ADC_MAX_BITWIDTH; -#else bits = bits - 9; - if (bits < ADC_WIDTH_9Bit || bits > ADC_WIDTH_12Bit) - return 0; -#endif if (ESP_OK != adc1_config_width( bits )) return 0; @@ -530,7 +498,7 @@ int platform_adc_read( uint8_t adc, uint8_t channel ) { } int platform_adc_read_hall_sensor( ) { -#if !defined(CONFIG_IDF_TARGET_ESP32C3) +#if defined(CONFIG_IDF_TARGET_ESP32) int value = hall_sensor_read( ); return value; #else @@ -682,3 +650,10 @@ int platform_i2c_recv_byte( unsigned id, int ack ){ #endif int platform_i2c_exists( unsigned id ) { return id < I2C_NUM_MAX; } + + +void platform_print_deprecation_note( const char *msg, const char *time_frame) +{ + printf( "Warning, deprecated API! %s. It will be removed %s. See documentation for details.\n", msg, time_frame ); +} + diff --git a/components/platform/ws2812.c b/components/platform/ws2812.c index 68403ed3..6b1b9ddc 100644 --- a/components/platform/ws2812.c +++ b/components/platform/ws2812.c @@ -104,10 +104,12 @@ static void ws2812_isr(void *arg) RMT.int_clr.val = BIT(channel+24); ws2812_chain_t *chain = &(ws2812_chains[channel]); -#if defined(CONFIG_IDF_TARGET_ESP32C3) - uint32_t data_sub_len = RMT.tx_lim[channel].limit/8; -#else +#if defined(CONFIG_IDF_TARGET_ESP32) || defined(CONFIG_IDF_TARGET_ESP32S2) uint32_t data_sub_len = RMT.tx_lim_ch[channel].limit/8; +#elif defined(CONFIG_IDF_TARGET_ESP32S3) + uint32_t data_sub_len = RMT.chn_tx_lim[channel].tx_lim_chn/8; +#else + uint32_t data_sub_len = RMT.tx_lim[channel].limit/8; #endif if (chain->len >= data_sub_len) { diff --git a/components/spiffs/spiffs.c b/components/spiffs/spiffs.c index 4d7a2b74..5b4462f5 100644 --- a/components/spiffs/spiffs.c +++ b/components/spiffs/spiffs.c @@ -56,7 +56,6 @@ The small 4KB sectors allow for greater flexibility in applications th static bool get_spiffs_partition (spiffs_config *cfg) { platform_partition_t info; - uint32_t next_free_offs = 0; uint8_t i = 0; while (platform_partition_info (i, &info)) { @@ -68,34 +67,9 @@ static bool get_spiffs_partition (spiffs_config *cfg) return true; } else - { ++i; - if ((info.offs + info.size) > next_free_offs) - next_free_offs = info.offs + info.size; - } - } - // Attempt to append a spiffs partition - NODE_ERR("No filesystem partition found, attempting to create it...\n"); - info.type = PLATFORM_PARTITION_TYPE_NODEMCU; - info.subtype = PLATFORM_PARTITION_SUBTYPE_NODEMCU_SPIFFS; - strcpy ((char *)info.label, "spiffs"); - info.offs = cfg->phys_addr = next_free_offs; - info.size = cfg->phys_size = flash_safe_get_size_byte () - info.offs; - if (info.size <= 0) - { - NODE_ERR("No space available at end of flash, can't add fs partition!\n"); - return false; - } - if (platform_partition_add (&info)) - { - NODE_ERR("Ok.\n"); - return true; - } - else - { - NODE_ERR("Error rewriting partition table!\n"); - return false; } + return false; } diff --git a/components/uzlib/uzlib_deflate.c b/components/uzlib/uzlib_deflate.c index 77ddf32e..9327176d 100644 --- a/components/uzlib/uzlib_deflate.c +++ b/components/uzlib/uzlib_deflate.c @@ -113,7 +113,7 @@ jmp_buf unwindAddr; #ifdef __XTENSA__ #define RAM_COPY_BYTE_ARRAY(c,s,sl) uint8_t *c = alloca(sl); memcpy(c,s,(sl)) #else -#define RAM_COPY_BYTE_ARRAY(c,s,sl) uint8_t *c = s; +#define RAM_COPY_BYTE_ARRAY(c,s,sl) uint8_t *c = s; (void)sl #endif #define FREE(v) if (v) uz_free(v) @@ -200,7 +200,8 @@ static void genCodeRecs (const codeRecord *rec, uint16_t len, if (*c == 0xFF) b++, c++; m += (*c & 0x80) ? 2 << (*c & 0x1F) : *c; - *p++ = (codeRecord) {i, b, last + 1, (last = m)}; + *p++ = (codeRecord) {i, b, last + 1, m}; + last = m; } } diff --git a/docs/lfs.md b/docs/lfs.md new file mode 100644 index 00000000..a55057b6 --- /dev/null +++ b/docs/lfs.md @@ -0,0 +1,195 @@ +# Lua Flash Store (LFS) + +## Some Acronym Definitions + +Before I begin, I think it useful to define some acronyms in the context used in this paper. There are others like [IoT](https://en.wikipedia.org/wiki/Internet_of_things) which you might know and on first use are hyperlinked to an external (typically Wikipedia) definition. + +Acronym | What it means in this paper +-----|-------- +**LFS** | _Lua Flash Store_, and if you want to understand more then read on. +**RTS** | The Lua environment on the ESP chipset include a core [Runtime System](https://en.wikipedia.org/wiki/Runtime_system) includes a [VM](https://en.wikipedia.org/wiki/Virtual_machine) that executes compiled Lua code, handle resource management, and provides and [API](https://en.wikipedia.org/wiki/Application_programming_interface) for the integration of library modules. +**ESP** | [Espressif](https://www.espressif.com/) Systems Processor. A range of [SoC](https://en.wikipedia.org/wiki/System_on_a_chip) devices based on an [Xtensa core](https://en.wikipedia.org/wiki/Tensilica#Xtensa_configurable_cores). NodeMCU currently offers Lua firmware builds for its ESP8266 and ESP32 families. +**RAM** | [Random Access Memory](https://en.wikipedia.org/wiki/Random-access_memory) that can be directly read or written by the [CPU](https://en.wikipedia.org/wiki/Central_processing_unit) and can be used to hold both data and machine code. +**ROM** | [Read Only Memory](https://en.wikipedia.org/wiki/Read-only_memory), though for the purposes of this paper, this also includes a region of [Flash memory](https://en.wikipedia.org/wiki/Flash_memory). +**GC** | [Garbage Collection](https://www.lua.org/manual/5.3/manual.html#2.5) refers to the automatic management resources to collect dead objects and make any associated memory available for reuse. + +## Background + +Lua was originally designed as a general purpose embedded extension language for use in applications run on a conventional computer such as a PC, where the processor is mounted on a motherboard together with multiple Gb of RAM and a lot of other chips providing CPU and I/O support to connect to other devices. + +An ESP8266 module is on a very different scale: it costs a few dollars; it is postage stamp-sized and only mounts two main components, an ESP SoC and a flash memory chip. The SoC includes on-chip RAM and also provides hardware support to map part of the external flash memory into a ROM addressable region so that the [firmware](https://en.wikipedia.org/wiki/Firmware) code can be executed via an [L1 cache](https://en.wikipedia.org/wiki/CPU_cache) out of this memory. + +ESP SoCs also adopt a type of [modified Harvard architecture](https://en.wikipedia.org/wiki/Modified_Harvard_architecture) found on many IoT devices where separate address regions are used for RAM code and RAM data and ROM code. ESPs also allow data constants to be loaded from code memory. The ESP8266 has 96 Kb of data RAM, but half of this is used by the operating system, for stack and for device drivers such as for WiFi support; typically **44 Kb** RAM is available as heap space for embedded applications. By contrast, the mapped flash ROM region can be up to **960 Kb**, that is over twenty times larger. Even though flash ROM is read-only for normal execution, there is also a "back-door" file-like API for erasing flash pages and overwriting them (though some care has to be taken to ensure cache integrity after update). + +Lua's design goals of speed, portability, small kernel size, extensibility and ease-of-use make it a good choice for embedded use on an IoT platform, but with one major limitation: the standard Lua RTS assumes that both Lua data _and_ code are stored in RAM, and this is a material constraint on a device with perhaps 44Kb free RAM and 512Kb free program ROM. + +The LFS feature modifies the Lua RTS to support a modified Harvard architecture by allowing the Lua code and its associated constant data to be executed directly out of flash ROM (just as the NoceMCU firmware is itself executed). This enables NodeMCU Lua developers to create Lua applications with a region of flash ROM allocated to Lua code and read-only constants. The entire RAM heap is then available for Lua read-write variables and data for applications where all Lua is executed from LFS. + +The ESP architecture provides very restricted write operations to flash memory: any updates use [NAND flash rules](https://en.wikipedia.org/wiki/Flash_memory#Writing_and_erasing), so any updates typically first require bulk erasing of complete 4Kb memory pages. This makes it impractical to modify Lua code pages on the fly safely, and hence LFS uses a "reflash and restart" paradigm for reloading the LFS region. + +If you are just interested in learning how to quickly get started with LFS, then please read the chapters referenced in the [Getting Started](getting-started.md) overview. The remainder of this paper is for those who want to understand a little of how this magic happens, and gives more details on the technical issues that were addressed in order to implement this feature in the following sections: + +- [Configuring LFS](#configuring-lfs) +- [An Overview of LFS Internals](#an-overview-of-lfs-internals) +- [Programming Techniques](#programming-techniques) +- [Compiling and Loading LFS Images](#compiling-and-loading-lfs-images) + +## Configuring LFS + +The LFS region can be allocated during firmware build: + +- For Lua developers that prefer the convenience of our [Cloud Build Service](https://nodemcu-build.com/), the menu dialogue offers a range of drop down options to select the size of LFS region required. + +- Some advanced developers might want to use [Docker](https://www.docker.com/) or their own build environment as per our [Building the firmware](build.md) documentation, and in this case the file [`app/include/user_config.h`](../app/include/user_config.h) is used and includes inline documentation on how to select the configuration options to make an LFS firmware build. + +## An Overview of LFS Internals + +### LFS Internal Structure + +Whilst memory capacity isn't a material constraint on most conventional machines, the Lua RTS still includes some features to minimise overall memory usage. In particular: + +- The more resource intensive data types are know as _collectable objects_, and the RTS includes a GC which regularly scans these collectable resources to determine which are no longer in use, so that their associated memory can be reclaimed and reused. + +- The Lua RTS also treats strings and compiled function code as collectable objects, so that these can also be GCed when no longer referenced + +The compiled Lua code which is executed by the RTS internally comprises one or more function prototypes (which use a `Proto` structure type) plus their associated vectors (constants, instructions and meta data for debug). Most of these compiled constant types are basic (e.g. numbers); strings are the only collectable constant data type. Other collectable types such as arrays are actually created at runtime by executing Lua compiled code to build each resource dynamically. + +Overlay techniques can be used ensure that active functions are loaded into RAM on a just-in time basis and thus mitigate RAM limitations. Moving Lua "program" resources into flash ROM typically at least doubles the effective RAM available, and typically removes any need to complicate applications code by implementing overlaying. + +When any Lua file is loaded (without LFS) into an ESP application, the RTS loads the corresponding compiled version into RAM. Each compiled function has an associated own Proto structure hierarchy, but this hierarchy is not exposed directly to the running application; instead the compiler generates `CLOSURE` instruction which is executed at runtime to bind the Proto to a Lua function value thus creating a [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming)). Since this occurs at runtime, any Proto can be bound to multiple closures. A Lua closure can also have multiple [Upvalues](https://www.lua.org/manual/5.3/manual.html#3.5) bound to it, and so function value is an updatable object in that it is referring to something that can contain writeable state, even though the Proto hierarchy itself is intrinsically read-only. + +As read-only resources that are store in flash ROM clearly cannot be collected by the GC, such ROM based resources cannot reference any volatile RAM-based data elements, though the converse can apply: updatable resources in RAM can reference read-only ones in ROM. + +All strings are stored internally in Lua with a header structure known as a `TString`, In Lua 5.1, all TStrings were [interned](https://en.wikipedia.org/wiki/String_interning), so that only one copy of any string is kept in memory, and most string manipulation uses the address of this single copy as a unique reference. Lua 5.3 divides strings into **Short** and **Long** subtypes with short strings being handled in the same way as Lua 5.1. In contrast, long strings are created and copied by reference, but are _not_ guaranteed to be stored uniquely. Guaranteeing uniqueness requires the string to be hashed and this can have a large runtime overhead for long strings, yet identical long strings are rarely generated by other than by copy-reference; hence the general runtime savings for not hashing long strings exceed the small chance of storage duplication. + +All of this complexity is hidden from running Lua applications, but does impact our LFS implementation. The Lua global state links to two (short) string tables: `ROstrt` in LFS for short strings stored in LFS; and `strt` for short strings in RAM. Maintaining integrity across these two string tables at runtime is simple and low-cost, with LFS resolution process extended across both the RAM and ROM string tables. Hence any strings already in the ROM string table can be reused and this avoids the need to add an additional entry in the RAM table. This significantly reduces the size of the RAM string table, and also removes a lot of strings from the LCG scanning. + +Lua GC of both types is essentially the same (and skipped for LFS strings) except that collection of long strings does not need to update the `strt`. + +LFS internal layouts are different for our Lua 5.1 and Lua 5.3 version execution environments, with the Lua 5.3 version: + +- Reflecting the changes to the Lua core that support the new Lua 5.2 and 5.3 language features (such the two string subtypes); +- Facilitating the additions of a second LFS region to allow separate System and Application LFS regions; this will also add a second `RO2strt`; +- Facilitates the on-ESP building of LFS regions at runtime, thus optionally removing the need for host-based code compilation; +- Improving the scalability of LFS function resolution. + +Any Lua file compiled into the LFS image includes its main function prototype and all the child resources that are linked in its `Proto` structure, so all of these resources are compiled into the LFS image with this entire hierarchy self-consistently within the flash memory: + +- A TString reference to the name of the function +- The vector of Lua VM instructions used to execute the function codes +- (optional) A packed map of instruction offset -> line number used for error tracebacks +- A vector of constants used by the function +- (optional) metadata on local variables +- metadata on local variables (some fields optional) +- a vector of references to other Protos compiled within the current one. + +The optional fields are include or not depending on the [stripdebug](modules/node.md#nodestripdebug) setting at the time of compilation. + +Lua 5.1 LFS images include a (hidden) Lua index function which has an `if n == "moduleN" then return moduleN end` chain to resolve functions within the LFS. This as been replaced by a [ROTable](nodemcu-lrm.md#values-and-types) in Lua 5.3 significantly reducing lookup times for larger LFS images. + +Lua uses a binary tokenised format for dumping compiled Lua code into a file based "compiled" format. Unlike the loading of Lua source which involves on-demand compilation at runtime, "undumping" compiled Lua code is the reverse operation to "dump" and is 5-10× faster. + +With Lua 5.3 LFS image file formats are a minor extension to the dump format and loading the image file into an LFS is a variant of the "undump" process (which shares the same internal functions). + +### Impact on the Lua Garbage Collector + +The GC applies to what the Lua VM classifies as collectable objects (strings, tables, functions, userdata, threads -- known collectively as `GCObjects`). A simple two "colour" GC was used in previous Lua versions, but Lua 5.1 introduced the Dijkstra's 3-colour (*white*, *grey*, *black*) variant that enabled the GC to operate in an incremental mode. This permits smaller GC steps interspersed by pauses, and this is very useful for larger scale Lua implementations. Even though this incremental mode is less useful for small RAM IoT devices, NodeMCU retains this standard Lua implementation. + +In fact, two *white* flavours are used to support incremental working (so this 3-colour algorithm really uses 4). All newly allocated collectable objects are marked as the current *white*, and a link in `GCObject` header enables scanning through all such Lua objects. Collectable objects can be referenced directly or indirectly via one of the Lua application's *roots*: . + +The standard GC algorithm is quite complex and assumes that all GCObjects are in RAM and updatable. It operates in two broad phases: **mark** and **sweep** where the mark phase does a recursive walk starting at the GC _roots_ (the global environment, the Lua registry and the stack) and marks the collectable objects in use. This process is complicated by the fact that the collector is incremental, that is its processing can be broken into packets of collection that can be interleaved within normal memory allocation actions. Once a mark phase has been completed, the sweep phase chains down the linked list of GCobjects to detect unmarked objects and reclaim them. Because LFS ROM GCObjects are treated as immutable, GC processing can still maintain overall object integrity, with the LFS modifications preventing the marking updates to ROM GCObjects (since any attempt to update any ROM-base structure during GC will result in the firmware crashing with a memory exception). + +There are all sorts of nuances needed because of the incremental nature and to allow Lua finalizers to take an active role in collection, and these finalizers can themselves trigger allocation actions. Not for the faint hearted. However, ROM GCOjects can still be handled robustly within this scheme because: +- Whilst a RAM object can refer to a ROM object, the converse in _not_true: a ROM object can never refer to a RAM one. Hence the recursive mark phase can safe abort its recursive walk at any node when a ROM object is detected. +- ROM objects are in a separate linked list to that used by the sweep process on RAM objects and so are never swept. + +Lastly note that the cost of GC is directly related to the size of the GC sweep lists. Therefore moving resources into LFS ROM removes them from the GC scope, and therefore reduces GC runtime accordingly. + + +### Programming Techniques + +A number of developers have commented that moving applications into LFS simplifies coding style, as you need to be far less concerned about dynamic loading of code just-in-time to mitigate RAM use, and source modules can be larger if that suits application structure. This makes it easier to adopt a clearer coding style, so ESP Lua code can now looks more similar to host-based Lua development. Also Lua code can still be loaded from SPIFFS, so you still have the option to keep test code in SPIFFS, and only move modules into LFS once they are stable. + +#### Accessing LFS functions and loading LFS modules + +The main interface to LFS is encapsulated in the `node.LFS` table. +See [`lua_examples/lfs/_init.lua`](../lua_examples/lfs/_init.lua) for the code that I use in my `_init` module to do create a simple access API for LFS. There are two parts to this. + +The first sets up a table in the global variable `LFS` with the `__index` and `__newindex` metamethods. The main purpose of the `__index()` is to resolve any names against the LFS using a `node.flashindex()` call, so that `LFS.someFunc(params)` does exactly what you would expect it to do: this will call `someFunc` with the specified parameters, if it exists in in the LFS. The LFS properties `_time`, `_config` and `_list` can be used to access the other LFS metadata that you need. See the code to understand what they do, but `LFS._list` is the array of all module names in the LFS. The `__newindex` method makes `LFS` readonly. + +The second part uses standard Lua functionality to add the LFS to the require [package.loaders](http://pgl.yoyo.org/luai/i/package.loaders) list. (Read the link if you want more detail). There are four standard loaders, which the require loader searches in turn. NodeMCU only uses the second of these (the Lua loader from the file system), and since loaders 1,3 and 4 aren't used, we can simply replace the 1st or the 3rd by code to use `node.flashindex()` to return the LFS module. The supplied `_init` puts the LFS loader at entry 3, so if the module is in both SPIFFS and LFS, then the SPIFFS version will be loaded. One result of this has burnt me during development: if there is an out of date version in SPIFFS, then it will still get loaded instead of the one if LFS. + +If you want to swap this search order so that the LFS is searched first, then SET `package.loaders[1] = loader_flash` in your `_init` code. If you need to swap the search order temporarily for development or debugging, then do this after you've run the `_init` code: + +```Lua +do local pl = package.loaders; pl[1],pl[3] = pl[3],pl[1]; end +``` + +#### Moving common string constants into LFS + +LFS is mainly used to store compiled modules, but it also includes its own string table and any strings loaded into this can be used in your Lua application without taking any space in RAM. Hence, you might also want to preload any other frequently used strings into LFS as this will both save RAM use and reduced the Lua Garbage Collector (**GC**) overheads. + +The new debug function `debug.getstrings()` can help you determine what strings are worth adding to LFS. It takes an optional string argument `'RAM'` (the default) or `'ROM'`, and returns a list of the strings in the corresponding table. So the following example can be used to get a listing of the strings in RAM. +```Lua +do + local a=debug.getstrings'RAM' + for i =1, #a do a[i] = ('%q'):format(a[i]) end + print ('local preload='..table.concat(a,',')) +end +``` + +You can do this at the interactive prompt or call it as a debug function during a running application in order to generate this string list, (but note that calling this still creates the overhead of an array in RAM, so you do need to have enough "head room" to do the call). + +You can then create a file, say `LFS_dummy_strings.lua`, and insert these `local preload` lines into it. By including this file in your `luac.cross` compile, then the cross compiler will also include all strings referenced in this dummy module in the generated ROM string table. Note that you don''t need to call this module; it's inclusion in the LFS build is enough to add the strings to the ROM table. Once in the ROM table, then you can use them subsequently in your application without incurring any RAM or GC overhead. + +A useful starting point may be found in [lua_examples/lfs/dummy_strings.lua](../lua_examples/lfs/dummy_strings.lua); this saves about 4Kb of RAM by moving a lot of common compiler and Lua VM strings into ROM. + +Another good use of this technique is when you have resources such as CSS, HTML and JS fragments that you want to output over the internet. Instead of having lots of small resource files, you can just use string assignments in an LFS module and this will keep these constants in LFS instead. + + +### Choosing your development life-cycle + + The build environment for generating the firmware images is Linux-based, but you can still develop NodeMCU applications on pretty much any platform including Windows and MacOS, as you can use our cloud build service to generate these images. Unfortunately LFS images must be built off-ESP on a host platform, so you must be able to run the `luac.cross` cross compiler on your development machine to build LFS images. + +- For Windows 10 developers, one method of achieving this is to install the [Windows Subsystem for Linux](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux). The default installation uses the GNU `bash` shell and includes the core GNU utilities. WSL extends the NT kernel to support the direct execution of Linux ELF images, and it can directly run the `luac.cross` and `spiffsimg` that are build as part of the firmware. You will also need the `esptool.py` tool but `python.org` already provides Python releases for Windows. Of course all Windows developers can use the Cygwin environment as this runs on all Windows versions and it also takes up less than ½Gb HDD (WSL takes up around 5Gb). + +- Linux users can just use these tools natively. Windows users can also to do this in a linux VM or use our standard Docker image. Another alternative is to get yourself a Raspberry Pi or equivalent SBC and use a package like [DietPi](http://www.dietpi.com/) which makes it easy to install the OS, a Webserver and Samba and make the RPi look like a NAS to your PC. It is also straightforward to write a script to automatically recompile a Samba folder after updates and to make the LFS image available on the webservice so that your ESP modules can update themselves OTA using the new `HTTP_OTA.lua` example. + +- In principle, only the environment component needed to support application development is `luac.cross`, built by the `app/lua/lua_cross` make. (Some developers might also use the `spiffsimg` exectable, made in the `tools/spifsimg` subdirectory). Both of these components use the host toolchain (that is the compiler and associated utilities), rather than the Xtensa cross-compiler toolchain, so it is therefore straightforward to make under any environment which provides POSIX runtime support, including WSL, MacOS and Cygwin. + +Most Lua developers seem to start with the [ESPlorer](https://github.com/4refr0nt/ESPlorer) tool, a 'simple to use' IDE that enables beginning Lua developers to get started. ESPlorer can be slow cumbersome for larger ESP application, and it requires a direct UART connection. So many experienced Lua developers switch to a rapid development cycle where they use a development machine to maintain your master Lua source. Going this route will allow you use your favourite program editor and source control, with one of various techniques for compiling the lua on-host and downloading the compiled code to the ESP: + +- If you use a fixed SPIFFS image (I find 128Kb is enough for most of my applications) and are developing on a UART-attached ESP module, then you can also recompile any LC files and LFS image, then rebuild a SPIFFS file system image before loading it onto the ESP using `esptool.py`; if you script this you will find that this cycle takes less than a minute. You can either embed the LFS.img in the SPIFFS. You can also use the `luac.cross -a` option to build an absolute address format image that you can directly flash into the LFS region within the firmware. + +- If you only need to update the Lua components, then you can work over-the-air (OTA). For example see my +[HTTP_OTA.lua](../lua_examples/lfs/HTTP_OTA.lua), which pulls a new LFS image from a webservice and reloads it into the LFS region. This only takes seconds, so I often use this in preference to UART-attached loading. + +- Another option would be to include the FTP and Telnet modules in the base LFS image and to use telnet and FTP to update your system. (Given that a 64Kb LFS can store thousands of lines of Lua, doing this isn't much of an issue.) + +My current practice is to use a small bootstrap `init.lua` file in SPIFFS to connect to WiFi, and also load the `_init` module from LFS to do all of the actual application initialisation. There is a few sec delay whilst connecting to the Wifi, and this delay also acts as a "just in case" when I am developing, as it is enough to allow me to paste a `file.remove('init.lua')` into the UART if my test application is stuck into a panic loop, or set up a different development path for debugging. + +Under rare circumstances, for example a power fail during the flashing process, the flash can be left in a part-written state following a `flashreload()`. The Lua RTS start-up sequence will detect this and take the failsafe option of resetting the LFS to empty, and if this happens then the LFS `_init` function will be unavailable. Your `init.lua` should therefore not assume that the LFS contains any modules (such as `_init`), and should contain logic to detect if LFS reset has occurred and if necessary reload the LFS again. Calling `node.flashindex("_init")()` directly will result in a panic loop in these circumstances. Therefore first check that `node.flashindex("_init")` returns a function or protect the call, `pcall(node.flashindex("_init"))`, and decode the error status to validate that initialisation was successful. + +No doubt some standard usecase / templates will be developed by the community over the next six months. + +A LFS image can be loaded in the LFS store by either during provisioning of the initial firmware image or programmatically at runtime as discussed further in [Compiling and Loading LFS Images](#compiling-and-loading-lfs-images) below. +one of two mechanisms: + +- The image can be build on the host and then copied into SPIFFS. Calling the `node.flashreload()` API with this filename will load the image, and then schedule a restart to leave the ESP in normal application mode, but with an updated flash block. This sequence is essentially atomic. Once called, and the format of the LFS image has been valiated, then the only exit is the reboot. + +- The second option is to build the LFS image using the `-a` option to base it at the correct absolute address of the LFS store for a given firmware image. The LFS can then be flashed to the ESP along with the firmware image. + +The LFS store is a fixed size for any given firmware build (configurable by the application developer through `user_config.h`) and is at a build-specific base address within the `ICACHE_FLASH` address space. This is used to store the ROM string table and the set of `Proto` hierarchies corresponding to a list of Lua files in the loaded image. + +A separate `node.flashindex()` function creates a new Lua closure based on a module loaded into LFS and more specfically its flash-based prototype; whilst this access function is not transparent at a coding level, this is no different functionally than already having to handle `lua` and `lc` files and the existing range of load functions (`load`,`loadfile`, `loadstring`). Either way, creating a closure on flash-based prototype is _fast_ in terms of runtime. (It is basically a single instruction rather than a compile, and it has minimal RAM impact.) + +### General comments + +- **Reboot implementation**. Whilst the application initiated LFS reload might seem an overhead, it typically only adds a few seconds per reboot. + +- **Typical Usecase**. The rebuilding of a store is an occasional step in the development cycle. (Say up to 10-20 times a day in a typical intensive development process). Modules and source files under development can also be executed from SPIFFS in `.lua` format. The developer is free to reorder the `package.loaders` and load any SPIFFS files in preference to Flash ones. And if stable code is moved into Flash, then there is little to be gained in storing development Lua code in SPIFFS in `lc` compiled format. + +- **Flash caching coherency**. The ESP chipset employs hardware enabled caching of the `ICACHE_FLASH` address space, and writing to the flash does not flush this cache. However, in this restart model, the CPU is always restarted before any updates are read programmatically, so this (lack of) coherence isn't an issue. + +- **Failsafe reversion**. Since the entire image is precompiled and validated before loading into LFS, the chances of failure during reload are small. The loader uses the Flash NAND rules to write the flash header flag in two parts: one at start of the load and again at the end. If on reboot, the flag in on incostent state, then the LFS is cleared and disabled until the next reload. + diff --git a/docs/lua53.md b/docs/lua53.md new file mode 100644 index 00000000..e22ad10e --- /dev/null +++ b/docs/lua53.md @@ -0,0 +1,261 @@ +## Background and Objectives + +The NodeMCU firmware was historically based on the Lua 5.1.4 core with the `eLua` patch and other NodeMCU specific enhancements and optimisations ("**Lua51**"). This paper discusses the rebaselining of NodeMCU to the latest production Lua version 5.3.5 ("**Lua53**"). Our goals in this upgrade were: + +- NodeMCU now offers a current Lua version, 5.3.5 which is as functionally complete as practical. + +- Lua53 adopts a minimum change strategy against the standard Lua source code base, that is changes to the VM and runtime system will only be made where there is a compelling reasons for any change, for example Lua53 preserves some valuable NodeMCU enhancements previously introduced to Lua51, for example the addition of Lua VM support for constant Lua program and data being executable directly from Flash ROM in order to free up RAM for application use to mitigate the RAM limitations of ESP-class IoT devices + +- NodeMCU provides a clear and stable migration path for both existing hardware libraries and ESP Lua applications being migrated from Lua51 to Lua53. + +- The Lua53 implementation provides a common code base for ESP8266 and ESP32 architectures. (The Lua51 implementation was forked with variant code bases for the two architectures.) + +## Specific Design Decisions + +- The NodeMCU C module API is built on the standard Lua C API that is common across the Lua51 and Lua53 build environments but with limited changes needs to reflect our IoT changes. Note that standard Lua 5.3 introduced some core functional and C API changes v.v 5.1; however, the use the standard Lua 5.3 compatibility modes largely hides these changes, though modules can make use of the `LUA_VERSION_NUM` define should version-specific code variants be needed. + +- The historic NodeMCU C module API (following `eLua` precedent and) added some extensions that somewhat compromised the orthogonal design principles of the standard Lua API; these are that modules should only access the Lua runtime via the `lua_XXX` macros and and calls exported through the `lua.h` header (or the wrapped helper `luaL_XXXX` versions exported through the `lauxlib.h` header). Such inconsistencies will be removed from the existing NodeMCU API and modules, so that all modules can be compiled and executed within either the Lua51 or the Lua53 environment. + +- Lua publishes a [Lua Reference Manual](https://www.lua.org/manual/5.3/)(**LRM**) for the Language specification, core libraries and C APIs for each Lua version. The Lua53 implementation includes a supplemental [NodeMCU Reference Manual](nodemcu-lrm.md)(**NRM**) to document the NodeMCU extensions to the core libraries and C APIs. As this API is unified across Lua51 and Lua53, this also provides a common reference that can also be used for developing both Lua51 and Lua53 modules. + +- The two Lua code bases are maintained within a common Git branch (in parallel NodeMCU sub-directories `app/lua` and `app/lua53`). An optional make parameter `LUA=53` selects a Lua53 build based on `app/lua53`, thus generating a Lua 5.3 firmware image. (At a later stage once Lua53 is proven and stable, we will swap the default to Lua53 and move the Lua51 tree into frozen support.) + +- Many of the important features of the `eLua` changes to Lua51 used by NodeMCU have now been incorporated into core Lua53 and can continue to be used 'out of the box'. Other NodeMCU **LFS**, **ROTable** and **LCD** functionality has been rewritten for NodeMCU, so the Lua53 code base no longer uses the `eLua` patch. + +- Lua53 will ultimately support three build targets that correspond to the ESP8266, ESP32 and native host targets using a _common Lua53 source directory_. The ESP build targets generate a firmware image for the corresponding ESP chip class, and the host target generates a host based `luac.cross` executable. This last can either be built standalone or as a sub-make of the ESP builds. + +- The Lua53 host build `luac.cross` executable will continue to extend the standard functionality by adding support for LFS image compilation and include a Lua runtime execution environment that can be invoked with the `-e` option. An optional make target also adds the [Lua Test Suite](https://www.lua.org/tests/) to this environment to enable use of this test suite. + +- Lua 5.3 introduces the concept of **subtypes** which are used for Numbers and Functions, and Lua53 follows this model adding an additional ROTables subtype for Tables. + + - **Lua numbers** have separate **Integer** and **Floating point** subtypes. There is therefore no advantage in having separate Integer and Floating point build variants. Lua53 therefore ignores the `LUA_NUMBER_INTEGRAL` build option. However it will provide option to use 32 or 64 bit numeric values with floating point numbers being stored as single or double precision respectively as well as the current hybrid where integers are 32-bit and `double` for floating point. Hence 32-bit integer only applications will have similar memory use and runtime performance as existing Lua51 Integer builds. + + - **Lua tables** have separate **Table** and **ROTable** subtypes. The Lua53 implementation of this subtyping has been backported to Lua51 where these were previously separate types, so that the table access API is the same for both Lua51 and Lua53. + + - **Lua Functions** have separate **Lua**, **C** and **lightweight C** subtypes, with this last being a special case where the C function has no upvals and so it doesn't need an associated `Closure` structure. It is also the same TValue type as our lightweight functions. + +- Lua 5.3 also introduces another small number of other but significant Lua language and core library / API changes. Our Lua53 implementation does not limit these, though we have enabled the appropriate compatibility modes to limit the impact at a Lua developer level. These are discussed in further detail in the following compatibility sections. + +- Many standard OS services aren't available on a embedded IoT device, so Lua53 follows the Lua51 precedent by omitting the `os` library for target builds as the relevant functionally is largely replaced by the `node` library. + +- Flash based code execution can incur runtime performance impacts if not mitigated. Some small code changes were required as the current GCC toolchain for the Xtensa processors doesn't handle all of these flash access mitigations during code generation. For example, the ESP CPU only supports aligned word access to flash memory, so 'hot' byte constant accesses have been encapsulated in an inline assembler macro to remove non-aligned exceptions at a cost of one extra Xtensa instruction per access; the remaining byte accesses to flash use a software exception handler. + +- NodeMCU employs a single threaded event loop model (somewhat akin to Node.js), and this is supported by some task extensions to the C API that facilitate use of a callback mechanism. + +## Detailed Implementation Notes + +We follow two broad principles (1) everything other than the Lua source directory is common, and (2) only change the Lua core when there is a compelling reason. The following sub-sections describe these issues / changes in detail. + +### Build variants and includes + +Lua53 supports three build targets which correspond to: + +- The ESP8266 (and derivative ESP8385) architectures use the Espressif non-OS SDK and its GCC Xtensa tool-chain. The macros `LUA_USE_ESP8266` and `LUA_USE_ESP` are defined for this target. + +- The ESP32 architecture using the Espressif IDF and its GCC Xtensa toolchain. The macros `LUA_USE_ESP32` and `LUA_USE_ESP` are defined for this target. + +- A host architecture using the standard host C toolchain. The macro `LUA_USE_HOST` is defined for this target. We currently support any POSIX environment that supports the GCC toolchain and Windows builds using native MSVC, WSL, Cygwin and MinGW. + +`LUA_USE_HOST` and `LUA_USE_ESP` are in effect mutually exclusive: `LUA_USE_ESP` is defined for a target firmware build, and `LUA_USE_HOST` for a build of the host-based `luac.cross` executable for the host environment. Note that `LUA_USE_HOST` also defines `LUA_CROSS_COMPILER` as used in Lua51. + +Our Lua51 source has been migrated to use `newlib` conformant headers and C runtime calls. An example of this is that the standard SDK headers supplied by Espressif include `"c_string.h"` and use `c_strcmp()` as the string comparison function. NodeMCU source files use `` and `strcmp()`. + +_**Caution**: The NodeMCU source is _compliant_ rather than fully _conformant_ with the standard headers such as ``; that is the current subset of these APIs used by the code will successfully compile, link and execute as an image, but code additions which attempt to use extra functions defined in the APIs might not; this at least minimises the need to change standard source code to compile and run on the ESP8266._ + +As with Lua51, Lua53 heavily customises the `linit.c`, `lua.c` and `luac.c` files because of the demands of an embedded runtime environment. Given the amount of change, these files are stripped of the functionally dead code. + +### TString types and implementation + +The Lua 5.3 version includes a significant modification to the treatment of strings, by dividing them into two separate subtypes based on the string length (at `LUAI_MAXSHORTLEN`, 40 in the current implementation). This decision reflects two empirical observations based on a broad range of practical Lua applications: the longer the string, the less likely the application is to recreate it independently; and the cost of ensuring uniqueness increases linearly with the length of the string. Hence Lua53 now treats the string type differently: + +- **Short Strings** are stored uniquely using the `strt` and `ROstrt` string table as discussed below. Two short TStrings are identical if and only if their addresses are the same. + +- **Long Strings** are created and copied by reference, but are not guaranteed to be stored uniquely. + +Since short strings are stored uniquely, identity comparison is based comparing their TString address. For long TStrings identify comparison is a little more complex: + +- They are identical if their addresses are the same +- They are different if their lengths are different. +- Failing these short circuits, a full `memcmp()` must be carried out. + +Lua GC of both types is essentially the same, except that collection of long strings does not need to update the `strt`. + +Note that for real applications, identical long strings are rarely generated by other than by copy-reference and hence in general the runtime savings benefits exceed the small chance of storage duplication. Also note that this and other sub-typing is hidden at the Lua C API level and is handled privately inside the Lua VM implementation. + +Whilst running Lua applications make heavy use of TStrings, the Lua VM itself makes little use of TStrings and typically pushes any string literals as CStrings. The Lua53 VM introduced a key cache to avoid the runtime cost of hashing string and doing the `strt` lookup for this type of CString constant. The NodeMCU implementation shares this key cache with ROTable field resolution. + +Short strings in the standard Lua VM are bound at runtime into the the RAM-based `strt` string table. The LFS implementation adds a second LFS-based readonly `ROstrt` string table that is created during LFS image load and then referenced on subsequent CPU restarts. The Lua VM and C API resolves each new short string first against the `strt`, then the `ROstrt` string table, before adding any unresolved strings into the `strt`. Hence short strings are interned across these two `strt` and `ROstrt` string tables. Any runtime reference to strings already in the LFS `ROstrt` therefore do not create additional entries in RAM. So applications are free include dummy resource functions (such as `dummy_strings.lua` in `lua_examples/lfs`) to preload additional strings into `ROstrt` and avoid needing RAM for these string constants. Such dummy functions don't need to called; simply inclusion in the LFS build is sufficient. + +An LFS section below discusses further implementation details. + +### ROTables + +The ROTables concept was introduced in `eLua`, with the ROTable format designed to be compiled by being declarable with C source and so statically included in the firmware at built-time, rather taking up RAM. This essential functionality has been preserved across both Lua51 and Lua53. At an API level ROTables are handled as a table subtype within the Lua VM except that: +- ROTables are declared statically in C code. +- Only a subset of key and value types is supported for ROTables. +- Attempting to write to a ROTable field will raise an error. +- The C API provides a method to push a ROTable reference direct to the Lua stack, but other than this, the Lua API to read ROTables and Tables is the same. + +We have now completely replaced the `eLua` implementation for Lua53, and this implementation has been back-ported to Lua51. Tables are now declared using `LROT` macros with the `LROT_END()` macro also generating a `ROTable` structure, which is a variant of the standard `Table` header and linking to the `luaR_entry` vector declared using the various `LROT_XXXXENTRY()` macros. This has new implementation has some major advantages: + +- ROTables are a separate subtype of Table, and so only minor code changes are needed within `ltable.c` to implement this, with the implementation now effectively hidden from the rest of the runtime and any library modules; this has enabled the removal of most of the ROTable code patches introduced by `eLua` into Lua51. + +- The `luaR_entry` vector is a linear list, so (unlike a standard RAM Table) any ROTable has no associate hash table for fast key lookup. However we have introduced a unified ROTable key cache to provide direct access into ROTable entries with a typical hit rate over 99% (key cache misses still require a linear key scan), and so average ROTable access is perhaps 30% slower than RAM Table access, unlike the `eLua` implementation which was 30-50 times slower. + +- The `ROTable` structure variants are not GC collectable and so one of its fields is tagged to allow the Lua GC to short-circuit GC sweeps across such RO nodes. The `ROTable` structure variant also drops unused fields to save space, and again this is handled internally within `ltable.c`. + +- As all tables have a header record that includes a valid `flags` field, the `fasttm()` optimisations for common metamethods now work for both `ROTables` and `Tables`. + +The same Lua51 ROTable functionality and limitations also apply to Lua53 in order to minimise migration impact for C module libraries: + +- ROTables can only have string keys and a limited set of Lua value types (Numeric, Light CFunc, Light UserData, ROTable, string and Nil). In Lua 5.3 `Integer` and `Float` are now separate numeric subtypes, so `LROT_INTENTRY()` takes an integer value. The new `LROT_FLOATENTRY()` is used for a non-integer values. This isn't a migration issue as none of the current NodeMCU modules use floating point constants in ROTables declared in them. (There is the only one currently used and that is `math.PI`.) + + - For 5.1 builds, `LROT_FLOATENTRY()` is a synonym of `LROT_NUMENTRY()`. + - For 5.3 builds, `LROT_NUMENTRY()` is a synonym of `LROT_INTENTRY()`. + +- Some ordering limitations apply: `luaR_entry` vectors can be unordered _except for any metafields_: Any entry with a key name starting in "_" _must_ must be ordered and placed at the start of the vector. + +- The `LROT_BEGIN()` and `LROT_END()` take the same three parameters. (These are ignored in the case of the `LROT_BEGIN()` macro, but by convention these are the same to facilitate the begin / end pairing). + - The first field is the table name. + - The second field is used to reference the ROTable's metatable (or `NULL` if it doesn't have one). + - The third field is 0 unless the table is a metatable, in which case it is a bit mask used to define the `fasttm()` `flags` field. This must match any metafield entries for metafield lookup to work correctly. + +### Proto Structures + +Standard Lua 5.3 contains a new peep hole optimisation relating to closures: the Proto structure now contains one RW field pointing to the last closure created, and the GC adopts a lazy approach to recovering these closures. When a new closure is created, if the old one exists _and the upvals are the same_ then it is reused instead of creating a new one. This allows peephole optimisation of a usecase where a function closure is embedded in a do loop, so the higher cost closure creation is done once rather than `n` times. + +This reduces runtime at the cost of RAM overhead. However for RAM limited IoTs this change introduced two major issues: first, LFS relies on Protos being read-only and this RW `cache` field breaks this assumption; second closures can now exist past their lifetime, and this delays their GC. Memory constrained NodeMCU applications rely on the fact that dead closed upvals can be GCed once the closure is complete. This optimisation changes this behaviour. Not good. + +Lua53 **_removes_** this optimisation for all prototypes. + +### Locale support + +Standard Lua 5.3 introduces localisation support. NodeMCU Lua53 disables this because IoT implementation doesn't have the appropriate OS support. + +### Memory Optimisations + +Some Lua structures have `double` fields which are align(8) by default. There is no reason or performance benefit for doing align(8) on ESPs so `#pragma pack(4)` is used for the value struct. + +Lua53 also reimplements the Lua51 LCD (Lua Compact Debug) patch. This replaces the `sizecode` `ìnt` vector giving line info with a packed byte array that is typically 15-30× smaller. See the [LCD whitepaper](lcd.md) for more information on this algorithm. + +### Unaligned exception avoidance + +By default the GCC compiler emits a `l8ui` instruction to access byte fields on the ESP8266 and ESP32 Xtensa processors. This instruction will generate an unaligned fetch exception when this byte field is in Flash memory (as will accessing short fields). These exceptions are handled by emulating the instruction in software using an unaligned access handler; this allows execution to continue albeit with the runtime cost of handling the exception in software. We wish to avoid the performance hit of executing this handler for such exceptions. + +`lobject.h` now defines a `GET_BYTE_FN(name,t,wo,bo)` macro. In the case of host targets this macro generates the normal field access, but in the case of Xtensa targets uses of this macro define an `static inline` access function for each field. These functions at the default `-O2` optimisation level cause the code generator to emit a pair of `l32i.n` + `extui` instructions replacing the single `l8ui` instruction. This has the cost of an extra instruction execution for accessing RAM data, but also removes the 200+ clock overhead of the software exception handler in the case of flash memory accesses. + +There are 9 byte fields in the `GCObject`,`TString`, `Proto`, `ROTable` structures that can either be statically compiled as `const struct` into library code space or generated by the Lua cross compiler and loaded into the LFS region; the `GET_BYTE_FN` macro is used to create inline access functions for these fields, and read references of the form `(o)->tt` (for example) have been recoded using the access macro form `gettt(o)`. There are 44 such changed access references in the source which together represent perhaps 99% of potential sources of this software exception within the Lua VM. + +The access macro hasn't been used where access is guarded by a conditional that implies the field in a RAM structure and therefore the `l8ui` instruction is executed correctly in hardware. Another exclusion is in modules such as `lcode.c` which are only used in compilation, and where the addition runtime penalty is acceptable. + +A wider review of `const char` initialisers and `-S` asm output from the compiler confirms that there are few other cases of character loads of constant data, largely because inline character constants such as '@' are loaded into a register as an immediate parameter to a `movi.n` instruction. Ditto use of short fields. + +### Modulus and division operation avoidance + +The Lua runtime uses the modulus (`%`) and divide (`/`) operators in a number of computations. This isn't an issue for most uses where the divisor is an integer power of 2 since the **gcc** optimiser substitutes a fast machine code equivalent which typically executes 1-4 inline Xtensa instructions (ditto for many constant multiplies). The compiler will also fold any used in constant expressions to avoid runtime evaluation. However the ESP Xtensa CPU doesn't implement modulus and divide operations in hardware, so these generate a call to a subroutine such as `_udivsi3()` which typically involves 500 instructions or so to evaluate. A couple of frequent uses have been replaced. (I have ensured that such uses are space delimited, so searching for " % " will locate these. `grep -P " (%|/) (?!(2|4|8|16))" app/lua53/*.[hc]` will list them off.) + +### Key cache + +Standard Lua 5.3 introduced a string key cache for constant CString to TString lookup. In NodeMCU we also introduced a lookaside cache for ROTable fields access, and in practice this provides single probe access for over 99% of key hit accesses to ROTable entries. + +In Lua53 these two caching functions (for CString and ROTable key lookup) have been unified into a common key cache to provide both caching functions with the runtime overhead of a single cache table in RAM. Folding these two lookups into a single key cache isn't ideal, but given our limited RAM this allows the cache use to be rebalanced at runtime reflecting the relative use of CString and ROTable key lookups. + +### Flash image generation and loading + +The current Lua51 `app/lua` implementation has two variants for dumping and loading Lua bytecode: (1) `ldump.c` + `lundump.c`; (2) `lflashimg.c` + `lflash.c`. These have been unified into a single load / unload mechanism in Lua53. However, this mechanism must facilitate sequential loading into flash storage, which is straight forward _if_ with some small changes to the standard internal ordering of the LC file format. The reason for this is that any `Proto` can embed other Proto definitions internally, creating a Proto hierarchy. The standard Lua dump algorithm dumps some Proto header components, then recurses into any sub-Protos before completing the wrapping Proto dump. As a result each Proto's resources get interleaved with those of its subordinate Proto hierarchy. This means that resources get to written to RAM non-serially, which is bad news for writing serially to the LFS region. + +The NodeMCU Lua53 dump reorders the proto hierarchy tree walk, so that resources of the lowest protos in the hierarchy are loaded first: +``` +dump_proto(p) + foreach subp in p + dump_proto(subp) + dump proto content +end +``` +This results in Proto references now being backwards references to Protos that have already been loaded, and this in turn enables the Proto resources to be allocated as a sequential contiguous allocation units, so the same code can be used for loading compiled Lua code into RAM and into LFS. + +The standard Lua 5.3 dump format embeds string constants in each proto as a `len`+`byte string` definition. NodeMCU needs to separate the collection of strings into an `ROstrt` for LFS loading, and this requires an extra processing pass either on dump or load. By doing a preliminary Proto scan to collect tracking the strings used then dumping these as a prologue makes the load process on the ESP a single pass and avoids any need for string resolution tables in the ESP's RAM. The extra memory resources needed for this two-pass dump aren't a material issue in a PC environment. + +Changes to `lundump.c` facilitate the addition of LFS mode. Writing to flash uses a record oriented write-once API. Once the flash cache has been flushed when updating the LFS region, this data can be directly accesses using the memory-mapped RO flash window, the resources are written directly to Flash without any allocation in RAM. + +Both the `dump.c` and `lundump.c` are compiled into both the ESP firmware and the host-based luac cross compiler. Both the host and ESP targets use the same integer and float formats (e.g. 32 bit, 32-bit IEEE) which simplifies loading and unloading. However one complication is that the host `luac.cross` application might be compiled on either a 32 or 64 bit environment and must therefore accommodate either 4 or 8 byte address constants. This is not an issue with the compiled Lua format since this uses the grammatical structure of the file format to derive resource relationships, rather than offsets or pointers. + +We also have a requirement to generate binary compatible absolute LFS images for linking into firmware builds. The host mode is tweaked to achieve this. In this case the write buffer function returns the correct absolute ESP address which are 32-bit; this doesn't cause any execution issue in luac since these addressed are never used for access within `luac.cross`. On 64-bit execution environments, it also repacks the Proto and other record formats on copy by discarding the top 32-bits of any address reference. + +#### Handling embedded integers in the dump format + +A typical dump contains a lot of integer fields, not only for Integer constants, but also for repeat count and lengths. Most of these integers are small, so rather than using a fixed 4-byte field in the file stream all integers are unsigned and represented by a big-endian multi-byte encoding, 7 bits per byte, with the high-bit used as a continuation flag. This means that integers 0..127 encode in 1 byte, 128..32,767 in 2 etc. This multi-byte scheme has minimal overhead but reduces the size of typical `.lc` and `.img` by 10% with minimal extra processing and less than the cost of reading that extra 10% of bytes from the file system. + +A separate dump type is used for negative integer constants where the constant `-x` is stored as `-(x+1)`. Note that endianness isn't an issue since the stream is processed byte-wise, but using big-endian simplifies the load algorithm. + +#### Handling LFS-based strings + +The dump function for a individual Protos hierarchy for loading as an `.lc` file follows the standard convention of embedding strings inline as a `\\`. Any LFS image contains a dump of all of the strings used in the LFS image Protos as an "all-strings" prologue; the Protos are then dumped into the image with string references using an index into the all-strings header. This approach enables a fast one-pass algorithm for loading the LFS image; it is also a compact encoding strategy as string references typically use 1 or 2 byte integer offset in the image file. + +One complication here is that in the standard Lua runtime start-up adds a set of special fixed strings to the `strt` that are also tagged to prevent GC. This could cause problems with the LFS image if any of these constants is used in the code. To remove this conflict the LFS image loader _always_ automatically includes these fixed strings in the `ROstrt`. (This also moves an extra ~2Kb string constants from RAM to Flash as a side-effect.) These fixed strings are omitted from the "all-strings prologue", even though the code itself can still use them. The `llex.c` and `ltm.c` initialisers loop over internal `char *` lists to register these fixed strings. NodeMCU adds a couple of access methods to `llex.c` and `ltm.c` to enable the dump and load functions to process these lists and resolve strings against them. + +#### Handling LFS top level functions + +Lua functions in standard Lua 5.1 are represented by two variant Closure headers (for C and Lua functions). In the case of Lua functions with upvals, the internal Protos can validly be bound to multiple function instances. `eLua` and Lua 5.3 introduced the concept of lightweight C functions as a separate function subtype that doesn't require a Closure record. Note that a function variable in a Lua exists as a TValue referencing either the C function address or a Closure record; this Closure is not the same as the CallInfo records which are chained to track the current call chain and stack usage. + +Whilst lightweight C functions can be declared statically as TValues in ROTables, there isn't a corresponding mechanism for declaring a ROTable containing LFS functions. This is because a Lua function TValue can only be created at runtime by executing a `CLOSURE` opcode within the Lua VM. The Lua51 implementation avoids this issue by generating a top level Lua dispatch function that does the equivalent of emitting `if name == "moduleN" then return moduleN end` for each entry, and this takes 4 Lua opcodes per module entry. This lookup has an O(N) cost which becomes non-trivial as N grows large, and so Lua51 has a somewhat arbitrary limit of 50 for the maximum number modules in a LFS image. + +In the Lua53 LFS implementation, the undump loader appends a `ROTable` to the LFS region which contains a set of entries `"module name"= Proto_address`. These table values are store as lightweight userdata pointer and as such are not directly accessible via Lua but the NodeMCU C function that does LFS lookup can still retrieve the required Proto address, execute the `CLOSURE` and return the corresponding TValue. Since this approach uses the standard table access API, which is a lot more efficient than the 4×N opcode `if` chain implementation. + +### Garbage collection + +Lua51 includes the eLua emergency GC, plus the various EGC tuning parameters that seem to be rarely used. The default setting (which most users use) is `node.egc.ALWAYS` which triggers a full GC before every memory allocation so the VM spends maybe 90% of its time doing full GC sweeps. + +Standard Lua 5.3 has adopted the eLua EGC but without the EGC tuning parameters. (I have raised a separate GitHub issue to discuss this.) We extend the EGC with the functional equivalent of the `ON_MEM_LIMIT` setting with a negative parameter, that is only trigger the EGC with less than a preset free heap left. The runtime spends far less time in the GC and code typically runs perhaps 5× faster. + +### Panic Handling + +Standard Lua includes a throw / catch framework for handling errors. (This has been slightly modified to enable yielding to work across C API calls, but this can be modification can ignored for the discussion of Panic handling.) All calls to Lua execution are handled by `ldo.c` through one of two mechanisms: + +- All protected calls are handled via `luaD_rawrunprotected()` which links its C stack frame into the `struct lua_longjmp` chain updating the head pointer at `L->errorJmp`. Any `luaD_throw()` will `longjmp` up to this entry in the C stack, hence as long as there is at least one protected call in the call chain, the C call stack can be properly unrolled to the correct frame. + +- If no protected calls are on the Lua call stack, then `L->errorJmp` will be null and there is no established C stack level to unroll to. In this case the `luaD_throw()` will directly call the `at_panic()` handler. Since there is no valid stack frame to unroll to and execution cannot safely continue, so the only safe next step is to abort, which in our case restarts the processor. + +Any Lua calls directly initiated through `lua.c` interpreter loop or through `luac.cross` are protected. However NodeMCU applications can also establish C callbacks that are called directly by the SDK / event dispatcher. The current practice is that these invoke their associated Lua CB using an unprotected call and hence the only safe option is to restart the processor on error. With Lua53 we have introduced a new `luaL_pcallx()` call variant as a NodeMCU extension; this is new call is designed to be used within library CBs that execute Lua CB functions, and it is argument compatible with `lua_call()`, except that in the case of caught errors it will also return a negative call status. This function establishes an error handler to protect the called function, and this is invoked on error at the error's stack level to provide a stack trace. + +This error handler posts a task to a panic error handler (with the error string as an upval) before returning control to the invoking routine. If the Lua registry entry `onerror` exists and is set to a function, then the handler calls this with the error string as an argument otherwise it calls standard `print` function by default. This function can return `false` in which case the handler exits, otherwise it restarts the processor. The application can use `node.setonerror()` to override the default "always restart" action if wanted (for example to write an error to a logfile or to a network syslog before restarting). Note that `print` returns `nil` and this has the effect of printing the full error traceback before restarting the processor. + +Currently all (bar 1) of the cases of such Lua callbacks within the NodeMCU C modules used a simple `lua_call()`, with the result that any runtime error executed a panic on error and reboots the processor. These call have all been replaced by the `luaL_pcallx()` variant, so control is always returned to the C routine, and a later post task report the error and restarts the processor. Note that substituting library uses of `lua_call()` by `luaL_pcallx()` does changes processing paths in the case of thrown errors. If the library CB function immediately returns control to the SDK/event scheduler after the call, then this is the correct behaviour. However, in a few cases, the routine performs post-call clean-up and this adapt the logic depending on the return status. + +### The `luac.cross` execution environment + +As with Lua51, the Lua53 host-build `luac.cross` executable extends the standard functionality by adding support for LFS image compilation and also includes a Lua runtime execution environment that can be invoked with the `-e` option. This environment was added primarily to facilitate in host testing (albeit with some limitations) of the NodeMCU. + +This execution environment also emulates LFS loading and execution using the `-F` option to load an LFS image before running the `-e` script. On POSIX environments this allocates the LFS region using a kernel extension, a page-aligned allocator and it also uses the kernel API to turn off write access to this region except during the simulated write to flash operations. In this way unintended writes to the LFS region throw a H/W exception in a manner parallel to the ESP environment. + +### API Compatibility for NodeMCU modules + +The Lua public API has largely been preserved across both Lua versions. Having done a difference analysis of the two API and in particular the standard `lua.h` and `lauxlib.h` headers which contain the public API as documented in the LRM 5.1 and 5.3, these differences are grouped into the following categories: + +- NodeMCU features that were in Lua51 and have also been added to Lua53 as part of this migration. +- Differences (additions / removals / API changes) that we are not using in our modules and which can therefore be effectively ignored for the purposes of migration. +- Some very nice feature enhancements in Lua53, for example the table access functions are now type `int` instead of type `void` and return the type of the accessed TValue. These features have been back-ported to Lua51 so that modules can be coded using Lua53 best practice and still work in a Lua51 runtime environment. +- Source differences which can be encapsulated through common macros will be removed by updating module code to use this common macro set. In a very small number of cases module functionality will be recoded to employ this common API base. + +Both the LRM and PiL make quite clear that the public API for C modules is as documented in `lua.h` and all its definitions start with `lua_`. This API strives for economy and orthogonality. The supplementary functions provided by the auxiliary library (`lauxlib.c`) access Lua services and functions through the `lua.h` interface and without other reference to the internals of Lua; this is exposed through `lauxlib.h` and all its definitions start with `luaL_`. All Lua library modules (such as `lstrlib.c` which implements `string`) conform to this policy and only access the Lua runtime via the `lua.h` and `lauxlib.h` interfaces. + +There are significant changes to internal APIs between Lua51 and Lua53 and as exposed in the other "private" headers within the Lua source directory, and so any code using these APIs may fail to work across the two versions. + +Both Lua51 and Lua53 have a concept of Lua core files, and these set the `LUA_CORE` define. In order to enforce limited access to the 'private' internal APIs, `#ifdef LUA_CORE` guards have been added to all private Lua headers effectively hiding them from application library and other non-core access. + +One thing that this analysis has underline is that the project has been lax in the past about how we allow our modules to be implemented. All existing modules have now been updated to use only the public API. If any new or changed module required any of the 'internal' Lua headers to compile, then it is implemented incorrectly. + + +### Lua Language and Libary Compatibility for NodeMCU Lua modules + +For the immediate future we will be supporting both builds based on both language variants, so Lua module writers either: + - Avoid using Lua 5.3 language features and implement their module in the common subset (this is currently our preferred approach); + - Or explicitly state any language constraints and include a test for `_VERSION=='Lua.5.3'` (or 5.1) in the module startup and explicitly error if incompatible. + +### Other Implementation Notes + +- **Use of Linker Magic**. Lua51 introduced a set of linker-aware macros to allow NodeMCU C library modules to be marshalled by the GNU linker for firmware builds; Lua53 target builds maintain these to ensuring cross-version compatibility. However, the lua53 `luac.cross` build does all library marshalling in `linit.c` and this removes the need to try to emulate this strategy on the diverse host toolchains that we support for compiling `luac.cross`. + +- **Host / ESP interoperability**. Our strategy is to build the firmware for the ESP target and `luac.cross` in the same make process. This requires the host to use a little endian ANSI floating point host architecture such as x68, AMD64 or ARM, so that the LC binary formats are compatible. This ain't a material constraint in practice. + +- **Emergency GC.** The Lua VM takes a more aggressive stance than the standard Lua version on triggering a GC sweep on heap exhaustion. This is because we run in a small RAM size environment. This means that any resource allocation within the Lua API can trigger a GC sweep which can call __GC metamethods which in turn can require to stack to be resized. diff --git a/docs/modules/node.md b/docs/modules/node.md index acaefc83..4286c914 100644 --- a/docs/modules/node.md +++ b/docs/modules/node.md @@ -166,6 +166,18 @@ none #### Returns flash ID (number) + +## node.flashindex() --deprecated + +Deprecated synonym for [`node.LFS.get()`](#nodelfsget) to return an LFS function reference. + +Note that this returns `nil` if the function does not exist in LFS. + +## node.flashreload() --deprecated + +Deprecated synonym for [`node.LFS.reload()`](#nodelfsreload) to reload [LFS (Lua Flash Store)](../lfs.md) with the named flash image provided. + + ## node.heap() Returns the current available heap size in bytes. Note that due to fragmentation, actual allocations of this size may not be possible. @@ -230,6 +242,65 @@ sk:on("receive", function(conn, payload) node.input(payload) end) #### See also [`node.output()`](#nodeoutput) + +## node.LFS + +Sub-table containing the API for [Lua Flash Store](../lfs.md)(**LFS**) access. Programmers might prefer to map this to a global or local variable for convenience for example: +```lua +local LFS = node.LFS +``` +This table contains the following methods and properties: + +Property/Method | Description +-------|--------- +`config` | A synonym for [`node.info('lfs')`](#nodeinfo). Returns the properties `lfs_base`, `lfs_mapped`, `lfs_size`, `lfs_used`. +`get()` | See [node.LFS.get()](#nodelfsget). +`list()` | See [node.LFS.list()](#nodelfslist). +`reload()` |See [node.LFS.reload()](#nodelfsreload). +`time` | Returns the Unix timestamp at time of image creation. + + +## node.LFS.get() + +Returns the function reference for a function in LFS. + +Note that unused `node.LFS` properties map onto the equialent `get()` call so for example: `node.LFS.mySub1` is a synonym for `node.LFS.get('mySub1')`. + +#### Syntax +`node.LFS.get(modulename)` + +#### Parameters +`modulename` The name of the module to be loaded. + +#### Returns +- If the LFS is loaded and the `modulename` is a string that is the name of a valid module in the LFS, then the function is returned in the same way the `load()` and the other Lua load functions do +- Otherwise `nil` is returned. + + +## node.LFS.list() + +List the modules in LFS. + + +#### Returns +- If no LFS image IS LOADED then `nil` is returned. +- Otherwise an sorted array of the name of modules in LFS is returned. + +## node.LFS.reload() + +Reload LFS with the flash image provided. Flash images can be generated on the host machine using the `luac.cross`command. + +#### Syntax +`node.LFS.reload(imageName)` + +#### Parameters +`imageName` The name of a image file in the filesystem to be loaded into the LFS. + +#### Returns +- In the case when the `imagename` is a valid LFS image, this is expanded and loaded into flash, and the ESP is then immediately rebooted, _so control is not returned to the calling Lua application_ in the case of a successful reload. +- The reload process internally makes multiple passes through the LFS image file. The first pass validates the file and header formats and detects many errors. If any is detected then an error string is returned. + + ## node.key() --deprecated Defines action to take on button press (on the old devkit 0.9), button connected to GPIO 16. diff --git a/docs/modules/pipe.md b/docs/modules/pipe.md new file mode 100644 index 00000000..0b717d54 --- /dev/null +++ b/docs/modules/pipe.md @@ -0,0 +1,139 @@ +# pipe Module +| Since | Origin / Contributor | Maintainer | Source | +| :----- | :-------------------- | :---------- | :------ | +| 2019-07-18 | [Terry Ellison](https://github.com/TerryE) | [Terry Ellison](https://github.com/TerryE) | [pipe.c](../../app/modules/pipe.c)| + +The pipe module provides a RAM-efficient means of passing character stream of records from one Lua +task to another. + +## pipe.create() + +Create a pipe. + +#### Syntax +`pobj = pipe.create([CB_function],[task_priority])` + +#### Parameters +- `CB_function` optional reader callback which is called through the `node.task.post()` when the pipe is written to. If the CB returns a boolean, then the reposting action is forced: it is reposted if true and not if false. If the return is nil or omitted then the deault is to repost if a pipe write has occured since the last call. +- `task_priority` See `ǹode.task.post()` + +#### Returns +A pipe resource. + +## pobj:read() + +Read a record from a pipe object. + +Note that the recommended method of reading from a pipe is to use a reader function as described below. + +#### Syntax +`pobj:read([size/end_char])` + +#### Parameters +- `size/end_char` + - If numeric then a string of `size` length will be returned from the pipe. + - If a string then this is a single character delimiter, followed by an optional "+" flag. The delimiter is used as an end-of-record to split the character stream into separate records. If the flag "+" is specified then the delimiter is also returned at the end of the record, otherwise it is discarded. + - If omitted, then this defaults to `"\n+"` + +Note that if the last record in the pipe is missing a delimiter or is too short, then it is still returned, emptying the pipe. + +#### Returns +A string or `nil` if the pipe is empty + +#### Example +```lua +line = pobj:read('\n') +line = pobj:read(50) +``` + +## pobj:reader() + +Returns a Lua **iterator** function for a pipe object. This is as described in the +[Lua Language: For Statement](http://www.lua.org/manual/5.1/manual.html#2.4.5). \(Note that the +`state` and `object` variables mentioned in 2.5.4 are optional and default to `nil`, so this +conforms to the`for` iterator syntax and works in a for because it maintains the state and `pobj` +internally as upvalues. + +An emptied pipe takes up minimal RAM resources (an empty Lua array), and just like any other array +this is reclaimed if all variables referencing it go out of scope or are over-written. Note +that any reader iterators that you have created also refer to the pipe as an upval, so you will +need to discard these to descope the pipe array. + +#### Syntax +`myFunc = pobj:reader([size/end_char])` + +#### Parameters +- `size/end_char` as for `pobj:read()` + +#### Returns +- `myFunc` iterator function + +#### Examples + +- used in `for` loop: +```lua +for rec in p:reader() do print(rec) end +-- or +fp = p:reader() +-- ... +for rec in fp do print(rec) end +``` + +- used in callback task: +```Lua +do + local pipe_reader = p:reader(1400) + local function flush(sk) -- Upvals flush, pipe_reader + local next = pipe_reader() + if next then + sk:send(next, flush) + else + sk:on('sent') -- dereference to allow GC + flush = nil + end + end + flush() +end +``` + +## pobj:unread() + +Write a string to the head of a pipe object. This can be used to back-out a previous read. + +#### Syntax +`pobj:unread(s)` + +#### Parameters +`s` Any input string. Note that with all Lua strings, these may contain all character values including "\0". + +#### Returns +Nothing + +#### Example + +```Lua +a=p:read() +p:unread(a) -- restores pipe to state before the read +``` + +## pobj:write() + +Write a string to a pipe object. + +#### Syntax +`pobj:write(s)` + +#### Parameters +`s` Any input string. Note that with all Lua strings, these may contain all character values including "\0". + +#### Returns +Nothing + + +## pobj:nrec() + +Return the number of internal records in the pipe. Each record ranges from 1 +to 256 bytes in length, with full chunks being the most common case. As +extracting from a pipe only to `unread` if too few bytes are available, it may +be useful to have a quickly estimated upper bound on the length of the string +that would be returned. diff --git a/docs/nodemcu-lrm.md b/docs/nodemcu-lrm.md new file mode 100644 index 00000000..1cc5557e --- /dev/null +++ b/docs/nodemcu-lrm.md @@ -0,0 +1,330 @@ +# NodeMCU Reference Manual + +## Introduction + +NodeMCU firmware is an IoT project ("the Project") which implements a Lua-based runtime for SoC modules based on the Espressif ESP8266 and ESP32 architectures. This NodeMCU Reference Manual (**NRM**) specifically addresses how the NodeMCU Lua implementation relates to standard Lua as described in the two versions of the Lua language that we currently support: + +- The [Lua 5.1 Reference Manual](https://www.lua.org/manual/5.1/) and +- The [Lua 5.3 Reference Manual](https://www.lua.org/manual/5.3/) (**LRM**) + +Developers using the NodeMCU environment should familiarise themselves with the 5.3 LRM. + +The Project provides a wide range of standard library modules written in both C and Lua to support many ESP hardware modules and chips, and these are documented in separate sections in our [online documentation](index.md). + +The NRM supplements LRM content and module documentation by focusing on a complete description of the _differences_ between NodeMCU Lua and standard Lua 5.3 in use. It adopts the same structure and style as the LRM. As NodeMCU provides a full implementation of the Lua language there is little content herein relating to Lua itself. However, what NodeMCU does is to offer a number of enhancements that enable resources to be allocated in constant program memory — resources in standard Lua that are allocated in RAM; where this does impact is in the coding of C library modules and the APIs used to do this. Hence the bulk of the differences relate to these APIs. + +One of our goals in introducing Lua 5.3 support was to maintain the continuity of our existing C modules by ensuring that they can be successfully compiled and executed in both the Lua 5.1 and 5.3 environments. This goal was achieved by a combination of: +- enabling relevant compatibility options for standard Lua libraries; +- back porting some Lua 5.3 API enhancements back into our Lua 5.1 implementation, and +- making some small changes to the module source to ensure that incompatible API use is avoided. + +Further details are given in the [Lua compatibility](#lua-compatibility) section below. Notwithstanding this, the Project has now deprecated Lua 5.1 and will soon be moving this version into frozen support. + +As well as providing the ability to building runtime firmware environments for ESP chipsets, the Project also offers a `luac.cross` cross compiler that can be built for common platforms such as Windows 10 and Linux, and this enables developers to compile source modules into a binary file format for download to ESP targets and loading from those targets. + +## Basic Concepts + +The NodeNCU runtime offers a full implementation of the [LRM §2](https://www.lua.org/manual/5.3/manual.html#2) core concepts, with the following adjustments: + +### Values and Types + +- The firmware is compiled to use 32-bit integers and single-precision (32-bit) floats by default. Address pointers are also 32-bit, and this allows all Lua variables to be encoded in RAM as an 8-byte "`TValue`" (compared to the 12-byte `TValue` used in Lua 5.1). +- C modules can statically declare read-only variant of the `Table` structure type known as a "`ROTable`". There are some limitations to the types for ROTable keys and value, in order to ensure that these are consistent with static declaration. ROTables are stored in code space (in flash memory on the ESPs), and hence do not take up RAM resources. However these are still represented by the Lua type _table_ and a Lua application can treat them during execution the same as any other read-only table. Any attempt to write to a `ROTable` or to set its metatable will throw an error. +- NodeMCU also introduces a concept known as **Lua Flash Store (LFS)**. This enables Lua code (and any string constants used in this code) to be compiled and stored in code space, and hence without using RAM resources. Such LFS functions are still represented by the type _function_ and can be executed just like any other Lua function. + +### Environments and the Global Environment + +These are implemented as per the LRM. Note that the Lua 5.1 and Lua 5.3 language implementations are different and can introduce breaking incompatibilities when moving between versions, but this is a Lua issue rather than a NodeMCU one. + +### Garbage Collection + +All LFS functions, any string constants used in these functions, and any ROTables are stored in static code space. These are ignored by the Lua Garbage collector (LGC). The LGC only scans RAM-based resources and recovers unused ones. The NodeMCU LGC has slightly modified configuration settings that increase its aggressiveness as heap usage approaches RAM capacity. + +### Coroutines + +The firmware includes the full coroutine implementation, but note that there are some slight differences between the standard Lua 5.1 and Lua 5.3 C API implementations. (See [Feature breaks](#feature-breaks) below.) + +## Lua Language + +The NodeNCU runtime offers a full implementation of the Lua language as defined in [LRM §3](https://www.lua.org/manual/5.3/manual.html#3) and its subsections. + +## The Application Program Interface + +[LRM §4](https://www.lua.org/manual/5.3/manual.html#4) describes the C API for Lua. This is used by NodeMCU modules written in the C source language to interface to the the Lua runtime. The header file `lua.h` is used to define all API functions, together with their related types and constants. This section 4 forms the primary reference, though the NodeMCU makes minor changes as detailed below to support LFS and ROTable resources. + +### Error Handling in C + +[LRM §4.6](https://www.lua.org/manual/5.3/manual.html#4.6) describes how errors are handled within the runtime. + +The normal practice within the runtime and C modules is to throw any detected errors -- that is to unroll the call stack until the error is acquired by a routine that has declared an error handler. Such an environment can be established by [lua_pcall](https://www.lua.org/manual/5.3/manual.html#lua_pcall) and related API functions within C and by the Lua function [pcall](https://www.lua.org/manual/5.3/manual.html#pdf-pcall); this is known as a _protected environment_. Errors which occur outside any protected environment are not caught by the Lua application and by default trigger a "panic". By default NodeMCU captures the error traceback and posts a new SDK task to print the error before restarting the processor. + +The NodeMCU runtime implements a non-blocking threaded model that is similar to that of `node.js`, and hence most Lua execution is initiated from event-triggered callback (CB) routines within C library modules. NodeMCU enables full recovery of error diagnostics from otherwise unprotected Lua execution by adding an additional auxiliary library function [`luaL_pcallx`](#luaL_pcallx). All event-driven Lua callbacks within our library modules use `luaL_pcallx` instead of `lua_call`. This has the same behaviour if no uncaught error occurs. However, in the case of an error that would have previously resulted in a panic, a new SDK task is posted with the error traceback as an upvalue to process this error information. + +The default action is to print a full traceback and then trigger processor restart, that is a similar outcome as before but with recovery of the full error traceback. However the `node.onerror()` library function is available to override this default action; for example developers might wish to print the error without restarting the processor, so that the circumstances which triggered the error can be investigated. + +### Additional API Functions and Types + +These are available for developers coding new library modules in C. Note that if you compare the standard and NodeMCU versions of `lua.h` you will find a small number of entries not listed below. This is because the Lua 5.1 and Lua 5.3 variants are incompatible owing to architectural differences. However, `laubxlib.h` includes equivalent wrapper version-compatible functions that may be used safely for both versions. + +#### ROTable and ROTable_entry + +Extra structure types used in `LROT` macros to declare static RO tables. See detailed section below. + +#### lua_createrotable + +` void (lua_createrotable) (lua_State *L, ROTable *t, const ROTable_entry *e, ROTable *mt);`         [-0, +1, -] + +Create a RAM based `ROTable` pointing to the `ROTable_entry` vector `e`, and metatable `mt`. + +#### lua_debugbreak and ASSERT + +` void (lua_debugbreak)(void);` + +`lua_debugbreak()` and `ASSERT(condition)` are available for development debugging. If `DEVELOPMENT_USE_GDB` is defined then these will respectively trigger a debugger break and evaluate a conditional assert prologue on the same. If not, then these are effectively ignored and generate no executable code. + +#### lua_dump + +` int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip);`         [-0, +0, –] + +Dumps function at the top of the stack function as a binary chunk as per LRM. However the last argument `strip` is now an integer is in the range -1..2, rather a boolean as per standard Lua: + +- -1, use the current default strip level (which can be set by [`lua_stripdebug`](#lua_stripdebug)) +- 0, keep all debug info +- 1, discard Local and Upvalue debug info; keep line number info +- 2, discard Local, Upvalue and line number debug info + +The internal NodeMCU `Proto` encoding of debug line number information is typically 15× more compact than in standard Lua; the intermediate `strip=1` argument allows the removal of most of the debug information whilst retaining the ability to produce a proper line number traceback on error. + +#### lua_freeheap + +` int lua_freeheap (void);`         [-0, +0, –] + +returns the amount of free heap available to the Lua memory allocator. + +#### lua_gc + +` int lua_gc (lua_State *L, int what, int data);`         [-0, +0, m] + +provides an option for +- `what`: + - `LUA_GCSETMEMLIMIT` sets the available heap threshold (in bytes) at which aggressive sweeping starts. + +#### lua_getlfsconfig + +` void lua_getlfsconfig (lua_State *L, int *conf);`         [-0, +0, -] + +if `conf` is not `NULL`, then this returns an int[5] summary of the LFS configuration. The first 3 items are the mapped and flash address of the LFS region, and its allocated size. If the LFS is loaded then the 4th is the current size used and the 5th (for Lua 5.3 only) the date-timestamp of loaded LFS image. + +#### lua_getstate + +` lua_State * lua_getstate();`         [-0, +0, -] + +returns the main thread `lua_State` record. Used in CBs to initialise `L` for subsequent API call use. + +#### lua_pushrotable +` void lua_pushrotable (lua_State *L, ROTable *p);`         [-0, +1, -] + +Pushes a ROTable onto the stack. + +#### lua_stripdebug +` int lua_stripdebug (lua_State *L, int level);`         [-1, +0, e] + +This function has two modes. A value is popped off the stack. +- If this value is `nil`, then the default strip level is set to given `level` if this is in the range 0 to 2. Returns the current default level. +- If this value is a Lua function (in RAM rather than in LFS), then the prototype hierarchy within the function is stripped of debug information to the specified level. Returns an _approximate_ estimate of the heap freed (this can be a lot higher if some strings can be garbage collected). + +#### lua_writestring + +` void lua_writestring(const char *s, size_t l); /* macro */` + +Writes a string `s` of length `l` to `stdout`. Note that any output redirection will be applied to the string. + +#### lua_writestringerror + +` void lua_writestringerror(const char *s, void *p). /* macro */` + +Writes an error with CString format specifier `s` and parameter `p` to `stderr`. Note on the ESP devices this error will always be sent to `UART0`; output redirection will not be applied. + +### The Debug Interface + +#### lua_pushstringsarray +` int lua_pushstringsarray (lua_State *L, int opt);`         [-0, +1, m] + +Pushes an array onto the stack containing all strings in the specified strings table. If `opt` = 0 then the RAM table is used, else if `opt` = 1 and LFS is loaded then the LFS table is used, else `nil` is pushed onto the stack. + +Returns a status boolean; true if a table has been pushed. + +### Auxiliary Library Functions and Types + +Note that the LRM defines an auxiliary library which contains a set of functions that assist in coding convenience and economy. These are strictly built on top of the basic API, and are defined in `lauxlib.h`. By convention all auxiliary functions have the prefix `luaL_` so module code should only contain `lua_XXXX()` and `luaL_XXXX()` data declarations and functions. And since the `lauxlib.h` itself incudes `lua.h`, all C modules should only need to `#include "lauxlib.h"` in their include preambles. + +NodeMCU adds some extra auxiliary functions above those defined in the LRM. + +#### luaL_lfsreload + +` int lua_lfsreload (lua_State *L);`         [-1, +1, -] + +This function pops the LFS image name from the stack, and if it exists and contains the correct image header then it reloads LFS with the specified image file, and immediately restarts with the new LFS image loaded, so control it not returned to the calling function. If the image is missing or the header is invalid then an error message is pushed onto the stack and control is returned. Note that if the image has a valid header but its contents are invalid then the result is undetermined. + +#### luaL_pcallx + +` int luaL_pcallx (lua_State *L, int narg, int nresults);`         [-(nargs + 1), +(nresults|1), –] + +Calls a function in protected mode and providing a full traceback on error. + +Both `nargs` and `nresults` have the same meaning as in [lua_call](https://www.lua.org/manual/5.3/manual.html#lua_call). If there are no errors during the call, then `luaL_pcallx` behaves exactly like `lua_call`. However, if there is any error, `lua_pcallx` has already established an traceback error handler for the call that catches the error. It cleans up the stack and returns the negative error code. + +Any caught error is posted to a separate NodeMCU task which which calls the error reporter as defined in the registry entry `onerror` with the traceback text as its argument. The default action is to print the error and then set a 1 sec one-shot timer to restart the CPU. (One second is enough time to allow the error to be sent over the network if redirection to a telnet session is in place.) If the `onerror` entry is set to `print` for example, then the error is simply printed without restarting the CPU. + +Note that the Lua runtime does not call the error handler if the error is an out-of memory one, so in this case the out-of-memory error is posted to the error reporter without a traceback. + +#### luaL_posttask + +` int luaL_posttask (lua_State* L, int prio);`         [-1, +0, e] + +Posts a task to execute the function popped from the stack at the specified user task priority +- `prio` one of: + - `LUA_TASK_LOW` + - `LUA_TASK_MEDIUM` + - `LUA_TASK_HIGH` + +Note that the function is invoked with the priority as its parameter. + +#### luaL_pushlfsmodule + +` int luaL_pushlfsmodule ((lua_State *L);`         [-1, +1, -] + +This function pops a module name from the stack. If this is a string, LFS is loaded and it contains the named module then its closure is pushed onto the stack as a function value, otherwise `nil` is pushed. + +Returns the type of the pushed value. + +#### luaL_pushlfsmodules + +` int luaL_pushlfsmodules (lua_State *L);`         [-0, +1, m] + +If LFS is loaded then an array of the names of all of the modules in LFS is pushed onto the stack as a function value, otherwise `nil` is pushed. + +Returns the type of the pushed value. + +#### luaL_pushlfsdts + +` int luaL_pushlfsdts (lua_State *L);`         [-0, +1, m-] + +If LFS is loaded then the Unix-style date-timestamp for the compile time of the image is pushed onto the stack as a integer value, otherwise `nil` is pushed. Note that the primary use of this stamp is to act as a unique identifier for the image version. + +Returns the type of the pushed value. + +#### luaL_reref +` void (luaL_reref) (lua_State *L, int t, int *ref);`         [-1, +0, m] + +Variant of [luaL_ref](https://www.lua.org/manual/5.3/manual.html#luaL_ref). If `*ref` is a valid reference in the table at index t, then this is replaced by the object at the top of the stack (and pops the object), otherwise it creates and returns a new reference using the `luaL_ref` algorithm. + +#### luaL_rometatable + +` int (luaL_rometatable) (lua_State *L, const char* tname, const ROTable *p);`         [-0, +1, e] + +Equivalent to `luaL_newmetatable()` for ROTable metatables. Adds key / ROTable entry to the registry `[tname] = p`, rather than using a new RAM table. + +#### luaL_unref2 + +` luaL_unref2(l,t,r)` + +This macro executes `luaL_unref(L, t, r)` and then assigns `r = LUA_NOREF`. + +### Declaring modules and ROTables in NodeMCU + +All NodeMCU C library modules should include the standard header "`module.h`". This internally includes `lnodemcu.h` and these together provide the macros to enable declaration of NodeMCU modules and ROTables within them. All ROtable support macros are either prefixed by `LRO_` (Lua Read Only) or in the case of table entries `LROT_`. + +#### NODEMCU_MODULE + +` NODEMCU_MODULE(sectionname, libraryname, map, initfunc)` + +This macro enables the module to be statically declared and linked in the `ROM` ROTable. The global environment's metafield `__index` is set to the ROTable `ROM` hence any entries in the ROM table are resolved as read-only entries in the global environment. +- `sectionname`. This is the linker section for the module and by convention this is the uppercased library name (e.g. `FILE`). Behind the scenes `_module_selected` is appended to this section name if corresponding "use module" macro (e.g. `LUA_USE_MODULES_FILE`) is defined in the configuration. Only the modules sections `*_module_selected` are linked into the firmware image and those not selected are ignored. +- `libraryname`. This is the name of the module (e.g. `file`) and is the key for the entry in the `ROM` ROTable. +- `map`. This is the ROTable defining the functions and constants for the module, and this is the corresponding value for the entry in the `ROM` ROTable. +- `initfunc`. If this is not NULL, it should be a valid C function and is call during Lua initialisation to carry out one-time initialisation of the module. + +#### LROT_BEGIN and LROT_END + +` LROT_BEGIN(rt,mt,flags)` +` LROT_END(rt,mt,flags)` +These macros start and end a ROTable definition. The three parameters must be the same in both declarations. +- `rt`. ROTable name. +- `mt`. ROTable's metatable. This should be of the form `LROT_TABLEREF(tablename)` if the metatable is used and `NULL` otherwise. +- `flags`. The Lua VM table access routines use a `flags` field to short-circuit where the access needs to honour metamethods during access. In the case of a static ROTable this flag bit mask must be declared statically during compile rather than cached dynamically at runtime. Hence if the table is a metatable and it includes the metamethods `__index`, `__newindex`, `__gc`, `__mode`, `__len` or `__eq`, then the mask field should or-in the corresponding mask for example if `__index` is used then the flags should include `LROT_MASK_INDEX`. Note that index and GC are a very common combination, so `LROT_MASK_GC_INDEX` is also defined to be `(LROT_MASK_GC | LROT_MASK_INDEX)`. + +#### LROT_xxxx_ENTRY + +ROTables only support static declaration of string keys and value types: C function, Lightweight userdata, Numeric, ROTable. These are entries are declared by means of the `LROT_FUNCENTRY`, `LROT_LUDENTRY`, `LROT_NUMENTRY`, `LROT_INTENTRY`, `LROT_FLOATENTRY` and `LROT_TABENTRY` macros. All take two parameters: the name of the key and the value. For Lua 5.1 builds `LROT_NUMENTRY` and `LROT_INTENTRY` both generate a numeric `TValue`, but in the case of Lua 5.3 these are separate numeric subtypes so these macros generate the appropriate subtype. + +Note that ROTable entries can be declared in any order except that keys starting with "`_`" must be declared at the head of the list. This is a pragmatic constraint for runtime efficiency. A lookaside cache is used to optimise key searches and results in a direct table probe in over 95% of ROTable accesses. A table miss (that is the key doesn't exist) still requires a full scan of the list, and the main source of table misses are scans for metafield values. Forcing these to be at the head of the ROTable allows the scan to abort on reading the first non-"`_`" key. + +ROTables can still support other key and value types by using an index metamethod to point at an C index access function. For example this technique is used in the `utf8` library to return `utf8.charpattern` + +```C +LROT_BEGIN(utf8_meta, NULL, LROT_MASK_INDEX) + LROT_FUNCENTRY( __index, utf8_lookup ) +LROT_END(utf8_meta, NULL, LROT_MASK_INDEX) + +LROT_BEGIN(utf8, LROT_TABLEREF(utf8_meta, 0) + LROT_FUNCENTRY( offset, byteoffset ) + LROT_FUNCENTRY( codepoint, codepoint ) + LROT_FUNCENTRY( char, utfchar ) + LROT_FUNCENTRY( len, utflen ) + LROT_FUNCENTRY( codes, iter_codes ) +LROT_END(utf8, LROT_TABLEREF(utf8_meta), 0) +``` + +Any reference to `utf8.charpattern` will call the `__index` method function (`utf8_lookup()`); this returns the UTF8 character pattern if the name equals `"charpattern"` and `nil` otherwise. Hence `utf8` works as standard even though ROTables don't natively support a string value type. + +### Standard Libraries + +- Basic Lua functions, coroutine support, Lua module support, string and table manipulation are as per the standard Lua implementation. However, note that there are some breaking changes in the standard Lua string implementation as discussed in the LRM, e.g. the `\z` end-of-line separator; no string functions exhibit a CString behaviour (that is treat `"\0"` as a special character). +- The modulus operator is implemented for string data types so `str % var` is a synonym for `string.format(str, var)` and `str % tbl` is a synonym for `string.format(str, table.unpack(tbl))`. This python-like formatting functionality is a very common extension to the string library, but is awkward to implement with `string` being a `ROTable`. +- The `string.dump()` `strip` parameter can take integer values 1,2,3 (the [`lua_stripdebug`](#lua_stripdebug) strip parameter + 1). `false` is synonymous to `1`, `true` to `3` and omitted takes the default strip level. +- The `string` library does not offer locale support. +- The 5.3 `math` library is expanded compared to the 5.1 one, and specifically: + - Included: ` abs`, ` acos`, ` asin`, ` atan`, ` ceil`, ` cos`, ` deg`, ` exp`, ` tointeger`, ` floor`, ` fmod`, ` ult`, ` log`, ` max`, ` min`, ` modf`, ` rad`, ` random`, ` randomseed`, ` sin`, ` sqrt`, ` tan` and ` type` + - Not implemented: ` atan2`, ` cosh`, ` sinh`, ` tanh`, ` pow`, ` frexp`, ` ldexp` and ` log10` + - Input, output OS Facilities (the `io` and `os` libraries) are not implement for firmware builds because of the minimal OS supported offered by the embedded run-time. The separately documented `file` and `node` libraries provide functionally similar analogues. The host execution environment implemented by `luac.cross` does support the `io` and `os` libraries. +- The full `debug` library is implemented less the `debug.debug()` function. + - An extra function `debug.getstrings(type)` has been added; `type` is one of `'ROM'`, or `'RAM'` (the default). Returns a sorted array of the strings returned from the [`lua_getstrings`](#lua_getstrings) function. + +## Lua compatibility + +Standard Lua has a number of breaking incompatibilities that require conditional code to enable modules using these features to be compiled against both Lua 5.1 and Lua 5.3. See [Lua 5.2 §8](https://www.lua.org/manual/5.2/manual.html#8) and [Lua 5.3 §8](https://www.lua.org/manual/5.3/manual.html#8) for incompatibilities with Lua 5.1. + +A key strategy in our NodeMCU migration to Lua 5.3 is that all NodeMCU application modules must be compilable and work under both Lua versions. This has been achieved by three mechanisms +- The standard Lua build has conditionals to enable improved compatibility with earlier versions. In general the Lua 5.1 compatibilities have been enabled in the Lua 5.3 builds. +- Regressing new Lua 5.3 features into the Lua 5.1 API. +- For a limited number of features the Project accepts that the two versions APIs are incompatible and hence modules should either avoid their use or use `#if LUA_VERSION_NUM == 501` conditional compilation. + +The following subsections detail how NodeMCU Lua versions deviate from standard Lua in order to achieve these objectives. + +### Enabling Compatibility modes + +The following Compatibility modes are enabled: +- `LUA_COMPAT_APIINTCASTS`. These `ìnt`cast are still used within NodeMCU modules. +- `LUA_COMPAT_UNPACK`. This retains `ROM.unpack` as a global synonym for `table.unpack` +- `LUA_COMPAT_LOADERS`. This keeps `package.loaders` as a synonym for `package.seachers` +- `LUA_COMPAT_LOADSTRING`. This keeps `loadstring(s)` as a synonym for `load(s)`. + +### New Lua 5.3 features back-ported into the Lua 5.1 API + +- Table access routines in Lua 5.3 are now type `int` rather than `void` and return the type of the value pushed onto the stack. The 5.1 routines `lua_getfield`, `lua_getglobal`, `lua_geti`, `lua_gettable`, `lua_rawget`, `lua_rawgeti`, `lua_rawgetp` and `luaL_getmetatable` have been updated to mirror this behaviour and return the type of the value pushed onto the stack. +- There is a general numeric comparison API function `lua_compare()` with macros for `lua_equal()` and `lua_lessthan()` whereas 5.1 only support the `==` and `<` tests through separate API calls. 5.1 has been update to mirror the 5.3. implementation. +- Lua 5.3 includes a `lua_absindex(L, idx)` which converts ToS relative (e.g. `-1`) indices to stack base relative and hence independent of further push/pop operations. This makes using down-stack indexes a lot simpler. 5.1 has been updated to mirror this 5.3 function. + +### Feature breaks + +- `\0` is now a valid pattern character in search patterns, and the `%z` pattern is no longer supported. We suggest that modules either limit searching to non-null strings or accept that the source will require version variants. + +- The stack pseudo-index `LUA_GLOBALSINDEX` has been removed. Modules must either get the global environment from the registry entry `LUA_RIDX_GLOBALS` or use the `lua_getglobal` API call. All current global references in the NodeMCU library modules now use `lua_getglobal` where necessary. + +- Shared userdata and table upvalues. Lua 5.3 now supports the sharing of GCObjects such as userdata and tables as upvalue between C functions using `lua_getupvalue` and `lua_setupvalue`. This has changed from 5.1 and we suggest that modules either avoid using these API calls or accept that the source will require version variants. + +- The environment support has changed from Lua 5.1 to 5.3. We suggest that modules either avoid using these API calls or accept that the source will require version variants. + + - The coroutine yield / resume API support has changed in Lua 5.3 to support yield and resume across C function calls. We suggest that modules either avoid using these API calls or accept that the source will require version variants. + diff --git a/docs/nodemcu-pil.md b/docs/nodemcu-pil.md new file mode 100644 index 00000000..2943284d --- /dev/null +++ b/docs/nodemcu-pil.md @@ -0,0 +1,42 @@ +# Programming in NodeMCU + +The standard Lua runtime offers support for both Lua modules that can define multiple Lua functions and properties in an encapsulating table as described in the [Lua 5.3 Reference Manual](https://www.lua.org/manual/5.3/) \("**LRM**") and specifically in [LRM Section 6.3](https://www.lua.org/manual/5.3/manual.html#6.3). Lua also provides a C API to allow developers to implement modules in compiled C. + +NodeMCU developers are also able to develop and incorporate their own C modules into their own firmware build using this standard API, although we encourage developers to download the standard [Lua Reference Manual](https://www.lua.org/manual/) and also buy of copy of Roberto Ierusalimschy's Programming in Lua edition 4 \("**PiL**"). The NodeMCU implementation extends standard Lua as documented in the [NodeMCU Reference Manual](nodemcu-lrm.md) \("**NRM**"). + +Those developers who wish to develop or to modify existing C modules should have access to the LRM, PiL and NRM and familiarise themselves with these references. These are the primary references; and this document does not repeat this content, but rather provide some NodeMCU-specific information to supplement it. + +From a perspective of developing C modules, there is very little difference from that of developing modules in standard Lua. All of the standard Lua library modules (`bit`, `coroutine`, `debug`, `math`, `string`, `table`, `utf8`) use the C API for Lua and the NodeMCU versions have been updated to use NRM extensions. so their source code is available for browsing and using as style template (see the corresponding `lXXXlib.c` file in GitHub [NodeMCU lua53](../app/lua53) folder). + +The main functional change is that NodeMCU supports a read-only subclass of the `Table` type, known as a **`ROTable`**, which can be statically declared within the module source using static `const` declarations. There are also limitations on the valid types for ROTable keys and value in order to ensure that these are consistent with static declaration; and hence ROTables are stored in code space (and therefore in flash memory on the IoT device). Hence unlike standard Lua tables, ROTables do not take up RAM resources. + +Also unlike standard Lua, two global ROTables are used for the registration of C modules. Again, static declaration macros plus linker "magic" (use of make filters plus linker _section_ directives) result in the marshalling of these ROTables during the make process, and because this is all ROTable based, the integration of modules into the firmware builds and their access from executing Lua applications depends on code space rather than RAM-based data structures. + +Note that dynamic loading of C modules is not supported within the ESP SDK, so any library registration must be compiled into the source used in the firmware build. Our approach is simple, flexible and avoids the RAM overheads of the standard Lua approach. The special ROTable **`ROM`** is core to this approach. The global environment table has an `__index` metamethod referencing this ROM table. Hence, any non-raw lookups against the global table will also resolve against ROM. All base Lua functions (such as `print`) and any C libraries (written to NodeMCU standards) have an entry in the ROM table and hence have global visibility. This approach does not prevent developers use of standard Lua mechanisms, but rather it offers a simple low RAM use alternative. + +The `NODEMCU_MODULE` macro is used in each module to register it in an entry in the **`ROM`** ROTable. It also adds a entry in the second (hidden) **`ROMentry`** ROTable. +- All `ROM` entries will resolve globally +- The Lua runtime scans the `ROMentry` ROTable during its start up, and it will execute any non-NULL `CFunction` values in this table. This enables C modules to hook in any one-time start-up functions if they are needed. + +Note that the standard `make` will include any modules found in the `app/modules` folder within a firmware build _if_ the corresponding `LUA_USE_MODULES_modname` macro has been defined. These defines are conventionally set in a common include file `user_modules.h`, and this practice is mandated for any user-submitted modules that are added to to the NodeMCU distribution. However, this does not prevent developers adding their own local modules to the `app/modules` folder and simply defining the corresponding `LUA_USE_MODULES_modname` inline. + +This macro + linker approach renders the need for `luaL_reg` declarations and use of `luaL_openlib()` unnecessary, and these are not permitted in project-adopted `app/modules` files. + +Hence a NodeMCU C library module typically has a standard layout that parallels that of the standard Lua library modules and uses the same C API to access the Lua runtime: + +- A `#ìnclude` block to resolve access to external resources. All modules will include entries for `"module.h"`, and `"lauxlib.h"`. They should _not_ reference any other `lXXX.h` includes from the Lua source directory as these are private to the Lua runtime. These may be followed by C standard runtime includes, external application libraries and any SDK resource headers needed. + +- The only external interface to a C module should be via the Lua runtime and its `NODEMCU_MODULE` hooks. Therefore all functions and resources should be declared `static` and be private to the module. These can be ordered as the developer wishes, subject of course to the need for appropriate forward declarations to comply with C scoping rules. + +- Module methods will typically employ a Lua standard `static int somefunc (lua_State *L) { ... }` template. +- ROTables are typically declared at the end of the module to minimise the need for forward references and use the `LROT` macros described in the NRM. Note that ROTables only support static declaration of string keys and the value types: C function, Lightweight userdata, Numeric, ROTable. ROTables can also have ROTable metatables. + - Whilst the ROTable search algorithm is a simply linear scan of the ROTable entries, the runtime also maintains a LRU cache of ROTable accesses, so typically over 95% of ROTable accesses bypass the linear scan and do a direct access to the appropriate entry. + - ROTables are also reasonable lightweight and well integrated into the Lua runtime, so the normal metamethod processing works well. This means that developers can use the `__index` method to implement other key and value typed entries through an index function. +- NodeMCU modules are intended to be compilable against both our Lua 5.1 and Lua 5.3 runtimes. The NRM discusses the implications and constraints here. However note that: + - We have back-ported many new Lua 5.3 features into the NodeMCU Lua 5.1 API, so in general you can use the 5.3 API to code your modules. Again the NRM notes the exceptions where you will either need variant code or to decide to limit yourself to the the 5.3 runtime. In this last case the simplest approach is to `#if LUA_VERSION_NUM != 503` to disable the 5.3 content so that 5.1 build can compile and link. Note that all modules currently in the `app/modules` folder will compile against and execute within both the Lua 5.1 and the 5.3 environments. + - Lua 5.3 uses a 32-bit representation for all numerics with separate subtypes for integer (stored as a 32 bit signed integer) and float (stored as 32bit single precision float). This achieves the same RAM storage density as Lua 5.1 integer builds without the loss of use of floating point when convenient. We have therefore decided that there is no benefit in having a separate Integer 5.3 build variant. + - We recommend that developers make use of the full set of `luaL_` API calls to minimise code verbosity. We have also added a couple of registry access optimisations that both simply and improve runtime performance when using the Lua registry for callback support. + - `luaL_reref()` replaces an existing registry reference in place (or creates a new one if needed). Less code and faster execution than a `luaL_unref()` plus `luaL_ref()` construct. + - `luaL_unref2()` does the unref and set the static int hook to `LUA_NOREF`. + +Rather than include simple examples of module templates, we suggest that you review the modules in our GitHub repository, such as the [`utf8`](../app/lua53/lutf8lib.c) library. Note that whilst all of the existing modules in `app/modules` folder compile and work, we plan to do a clean up of the core modules to ensure that they conform to best practice. diff --git a/mkdocs.yml b/mkdocs.yml index 3ca7334f..9a69550c 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -28,10 +28,15 @@ pages: - Uploading code: 'upload.md' - JTAG debugging: 'debug.md' - Support: 'support.md' + - Reference: + - NodeMCU Language Reference Manual: 'nodemcu-lrm.md' + - Programming in NodeMCU: 'nodemcu-pil.md' - FAQs: - Lua Developer FAQ: 'lua-developer-faq.md' - Extension Developer FAQ: 'extn-developer-faq.md' - Whitepapers: + - Lua 5.3 Support: 'lua53.md' + - Lua Flash Store (LFS): 'lfs.md' - Filesystem on SD card: 'sdcard.md' - Writing external C modules: 'modules/extmods.md' - C Modules: @@ -55,6 +60,7 @@ pages: - 'node': 'modules/node.md' - 'ota': 'modules/otaupgrade.md' - 'ow (1-Wire)': 'modules/ow.md' + - 'pipe': 'modules/pipe.md' - 'pulsecnt': 'modules/pulsecnt.md' - 'qrcodegen': 'modules/qrcodegen.md' - 'sdmmc': 'modules/sdmmc.md' diff --git a/sdk/esp32-esp-idf b/sdk/esp32-esp-idf index 8e3e65a4..a20df743 160000 --- a/sdk/esp32-esp-idf +++ b/sdk/esp32-esp-idf @@ -1 +1 @@ -Subproject commit 8e3e65a47b7d9b5dc4f52eb56660a748fda1884e +Subproject commit a20df743f1c51e6d65b021ed2ffd3081a2feec64 diff --git a/sdkconfig.defaults b/sdkconfig.defaults index dfff71f0..1f6f711f 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -21,13 +21,6 @@ CONFIG_MQTT_TRANSPORT_SSL=n CONFIG_MQTT_TRANSPORT_WEBSOCKET=n CONFIG_MQTT_USE_CUSTOM_CONFIG=n -# Allow writing to dangerous regions to avoid boot loops when creating filesystem -# Symptom: -# Mounting flash filesystem... -# No filesystem partition found, attempting to create it... -# abort() was called at PC 0x400ecddd on core 0 -CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED=y - # Enable address reuse for sockets in TIME_WAIT # see https://github.com/nodemcu/nodemcu-firmware/pull/1838 CONFIG_LWIP_SO_REUSE=y diff --git a/tools/embed_lfs.sh b/tools/embed_lfs.sh index 51fe29f5..d63f25c3 100755 --- a/tools/embed_lfs.sh +++ b/tools/embed_lfs.sh @@ -35,12 +35,27 @@ fi echo "LFS segment address ${LFS_ADDR}, length ${LFS_SIZE}" -${LUAC_CROSS} -a ${LFS_ADDR} -m ${LFS_SIZE} -o ${LUAC_OUTPUT} ${LUA_APP_SRC} +if ${LUAC_CROSS} -v | grep -q 'Lua 5.1' +then + echo "Generating Lua 5.1 LFS image..." + ${LUAC_CROSS} -a ${LFS_ADDR} -m ${LFS_SIZE} -o ${LUAC_OUTPUT} ${LUA_APP_SRC} +else + set -e + echo "Generating intermediate Lua 5.3 LFS image..." + ${LUAC_CROSS} -f -m ${LFS_SIZE} -o ${LUAC_OUTPUT}.tmp ${LUA_APP_SRC} + echo "Converting to absolute LFS image..." + ${LUAC_CROSS} -F ${LUAC_OUTPUT}.tmp -a ${LFS_ADDR} -o ${LUAC_OUTPUT} + rm ${LUAC_OUTPUT}.tmp +fi if [ $? != 0 ]; then echo "Error: luac.cross failed" exit 1 +else + echo "Generated $(ls -l ${LUAC_OUTPUT} | cut -f5 -d' ') bytes of LFS data" fi # cmake depencies don't seem to pick up the change to luac.out? rm -f build/lua.flash.store.reserved -make +echo "Re-linking nodemcu binary by invoking IDF build..." +make >/dev/null +echo "Done."