[
  {
    "path": ".github/ISSUE_TEMPLATE/readme-first.md",
    "content": "---\nname: Readme First\nabout: Issues is bug report only\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\nThe **Issues** is for bug report only.\n\nGoto **Discussions** for feature request , questions, etc.\n\n**Update to master branch HEAD first**, and\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior.\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/workflows/build-release.yml",
    "content": "name: Build and Release Skynet\n\non:\n  push:\n    branches: [ master ]\n    tags: [ 'v*' ]\n\npermissions:\n  contents: write\n  actions: read\n\njobs:\n  build:\n    name: Build ${{ matrix.platform }}\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - platform: windows\n            os: ubuntu-latest\n            container: debian:13\n            target: mingw\n            artifact: skynet-windows.zip\n          - platform: linux\n            os: ubuntu-latest\n            container: debian:13\n            target: linux\n            artifact: skynet-linux.zip\n          - platform: macosx\n            os: macos-latest\n            target: macosx\n            artifact: skynet-macosx.zip\n          - platform: freebsd\n            os: ubuntu-latest\n            container: debian:13\n            target: freebsd\n            artifact: skynet-freebsd.zip\n\n    container: ${{ matrix.container }}\n\n    steps:\n    - name: Install dependencies (Debian - Windows/Linux)\n      if: matrix.container == 'debian:13'\n      run: |\n        apt-get update\n        apt-get install -y --no-install-recommends \\\n          build-essential \\\n          make \\\n          pkg-config \\\n          mingw-w64 \\\n          mingw-w64-tools \\\n          mingw-w64-i686-dev \\\n          mingw-w64-x86-64-dev \\\n          autoconf \\\n          automake \\\n          libtool \\\n          git \\\n          zip \\\n          ca-certificates \\\n          curl \\\n          libreadline-dev \\\n          libedit-dev \\\n          rsync\n\n    - name: Install dependencies (macOS)\n      if: matrix.platform == 'macosx'\n      run: |\n        # macOS usually has most build tools pre-installed\n        # Install any additional dependencies if needed\n        brew install autoconf automake libtool || true\n\n    - name: Install dependencies (FreeBSD)\n      if: matrix.platform == 'freebsd'\n      run: |\n        # FreeBSD build using standard build tools (cross-compilation compatible)\n        apt-get update\n        apt-get install -y --no-install-recommends \\\n          build-essential \\\n          make \\\n          pkg-config \\\n          autoconf \\\n          automake \\\n          libtool \\\n          git \\\n          zip \\\n          ca-certificates \\\n          curl \\\n          libreadline-dev \\\n          libedit-dev \\\n          rsync\n\n    - name: Update CA certificates (Debian containers)\n      if: matrix.container == 'debian:13'\n      run: |\n        update-ca-certificates\n\n    - name: Configure Git SSL (Debian containers)\n      if: matrix.container == 'debian:13'\n      run: |\n        git config --global http.sslverify true\n        git config --global http.sslcainfo /etc/ssl/certs/ca-certificates.crt\n\n    - name: Checkout code\n      uses: actions/checkout@v6\n      with:\n        submodules: recursive\n        fetch-depth: 1\n\n    - name: Build ${{ matrix.platform }}\n      run: |\n        make cleanall\n        make ${{ matrix.target }}\n\n    - name: Prepare build files\n      run: |\n        mkdir -p build-output\n        # Copy all files except .git and .github with ignore-errors flag\n    - name: Clean and recreate directory\n      run: |\n        rm -rf build-output/\n        mkdir -p build-output/\n\n    - name: Sync files to build-output excluding specific directories\n      run: |\n        rsync -av --ignore-errors --exclude='.git*' --exclude='.github' --exclude='build-output' . build-output/\n\n    - name: Upload artifact\n      uses: actions/upload-artifact@v4\n      with:\n        name: ${{ matrix.artifact }}\n        path: build-output/\n        retention-days: 30\n\n  release:\n    name: Create Release\n    needs: build\n    runs-on: ubuntu-latest\n    if: startsWith(github.ref, 'refs/tags/v')\n    \n    steps:\n    - name: Download all artifacts\n      uses: actions/download-artifact@v4\n      with:\n        path: artifacts\n\n    - name: Prepare release assets\n      run: |\n        mkdir -p release-assets\n        # Copy zip files from artifact directories to release assets\n        for artifact in skynet-windows.zip skynet-linux.zip skynet-macosx.zip skynet-freebsd.zip; do\n          if [ -d \"artifacts/${artifact}\" ]; then\n            # The artifacts are already organized, just copy them\n            cp -r \"artifacts/${artifact}/\"* \"release-assets/\" 2>/dev/null || true\n            # Or if we want to create new zip files with consistent naming\n            platform=$(echo ${artifact} | sed 's/skynet-\\(.*\\)\\.zip/\\1/')\n            cd \"artifacts/${artifact}\"\n            zip -r \"../../release-assets/skynet-${platform}.zip\" .\n            cd ../..\n          fi\n        done\n        ls -la release-assets/\n\n    - name: Create Release\n      uses: softprops/action-gh-release@v1\n      with:\n        files: release-assets/*.zip\n        generate_release_notes: true\n        draft: false\n        prerelease: false\n      env:\n        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "*.o\n*.a\n/skynet\n/skynet.pid\n3rd/lua/lua\n3rd/lua/luac\n3rd/lua/all\n/cservice\n/luaclib\n*.so\n*.dSYM\n.DS_Store\n.vscode\n3rd/lua/lua.exe\n3rd/lua/luac.exe\n3rd/lua/lua54.dll\nskynet.exe\n*.dll\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"3rd/jemalloc\"]\n\tpath = 3rd/jemalloc\n\turl = https://github.com/jemalloc/jemalloc.git\n"
  },
  {
    "path": "3rd/compat-mingw/arpa/inet.h",
    "content": "#pragma once"
  },
  {
    "path": "3rd/compat-mingw/compat.c",
    "content": "#include \"compat.h\"\n\n#include \"dlfcn.c\"\n#include \"unistd.c\"\n#include \"wepoll.c\"\n"
  },
  {
    "path": "3rd/compat-mingw/compat.h",
    "content": "#pragma once\n\n#include \"unistd.h\"\n#include \"dlfcn.h\"\n"
  },
  {
    "path": "3rd/compat-mingw/dlfcn.c",
    "content": "#include \"dlfcn.h\"\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n\nvoid *dlopen(const char *path, int flag) {\n    return LoadLibraryA(path);\n}\n\nconst char *dlerror() {\n    DWORD err = GetLastError();\n    HLOCAL LocalAddress = NULL;\n    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,\n                  NULL, err, 0, (PTSTR)&LocalAddress, 0, NULL);\n    return (LPSTR)LocalAddress;\n}\n\nvoid *dlsym(void *dl, const char *sym) {\n    return GetProcAddress(dl, sym);\n}\n\n"
  },
  {
    "path": "3rd/compat-mingw/dlfcn.h",
    "content": "#pragma once\n\nenum { RTLD_NOW, RTLD_GLOBAL };\n\nvoid *dlopen(const char *path, int flag);\nconst char *dlerror();\nvoid *dlsym(void *dl, const char *sym);"
  },
  {
    "path": "3rd/compat-mingw/netdb.h",
    "content": "#pragma once\n\n#include <ws2tcpip.h>"
  },
  {
    "path": "3rd/compat-mingw/netinet/in.h",
    "content": "#pragma once\n"
  },
  {
    "path": "3rd/compat-mingw/netinet/tcp.h",
    "content": "#pragma once\n"
  },
  {
    "path": "3rd/compat-mingw/sys/epoll.h",
    "content": "#pragma once\n\n#include \"wepoll.h\""
  },
  {
    "path": "3rd/compat-mingw/sys/file.h",
    "content": "#pragma once"
  },
  {
    "path": "3rd/compat-mingw/sys/socket.h",
    "content": "#pragma once\n\n#define _WINSOCK_DEPRECATED_NO_WARNINGS\n#define WIN32_LEAN_AND_MEAN\n\n#undef FD_SETSIZE\n#define FD_SETSIZE 1024\n\n#include <winsock2.h>\n#include <windows.h>\n#include <conio.h>\n\n#include <ws2ipdef.h>\n#include <ws2tcpip.h>\n\n#include \"socket_poll.h\"\n#include \"socket_epoll.h\""
  },
  {
    "path": "3rd/compat-mingw/unistd.c",
    "content": "#include \"unistd.h\"\n\n#define _WINSOCK_DEPRECATED_NO_WARNINGS\n#define WIN32_LEAN_AND_MEAN\n#include <winsock2.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <windows.h>\n#include <conio.h>\n#include <errno.h>\n\n// WSA error to errno mapping function\nstatic void set_errno_from_wsa_error(int wsa_error) {\n    switch (wsa_error) {\n        case WSAECONNRESET:\n            errno = ECONNRESET;\n            break;\n        case WSAECONNABORTED:\n            errno = ECONNABORTED;\n            break;\n        case WSAECONNREFUSED:\n            errno = ECONNREFUSED;\n            break;\n        case WSAENETDOWN:\n            errno = ENETDOWN;\n            break;\n        case WSAENETUNREACH:\n            errno = ENETUNREACH;\n            break;\n        case WSAEHOSTDOWN:\n            errno = EHOSTDOWN;\n            break;\n        case WSAEHOSTUNREACH:\n            errno = EHOSTUNREACH;\n            break;\n        case WSAETIMEDOUT:\n            errno = ETIMEDOUT;\n            break;\n        case WSAENOTCONN:\n            errno = ENOTCONN;\n            break;\n        case WSAEWOULDBLOCK:\n            errno = EAGAIN;\n            break;\n        case WSAEINTR:\n            errno = EINTR;\n            break;\n        case WSAEINVAL:\n            errno = EINVAL;\n            break;\n        case WSAEACCES:\n            errno = EACCES;\n            break;\n        case WSAEADDRINUSE:\n            errno = EADDRINUSE;\n            break;\n        case WSAEADDRNOTAVAIL:\n            errno = EADDRNOTAVAIL;\n            break;\n        default:\n            errno = EIO;  // Generic I/O error for unknown cases\n            break;\n    }\n}\n\n// Windows Socket initialization\nstatic int winsock_initialized = 0;\n\nstatic int init_winsock(void) {\n    if (!winsock_initialized) {\n        WSADATA wsaData;\n        int result = WSAStartup(MAKEWORD(2, 2), &wsaData);\n        if (result != 0) {\n            return -1;\n        }\n        winsock_initialized = 1;\n    }\n    return 0;\n}\n\nstatic void cleanup_winsock(void) {\n    if (winsock_initialized) {\n        WSACleanup();\n        winsock_initialized = 0;\n    }\n}\n\n// Auto-initialize Winsock when the library is loaded\n__attribute__((constructor))\nstatic void auto_init_winsock(void) {\n    init_winsock();\n}\n\n// Auto-cleanup Winsock when the library is unloaded\n__attribute__((destructor))\nstatic void auto_cleanup_winsock(void) {\n    cleanup_winsock();\n}\n\nstatic LONGLONG get_cpu_freq() {\n    LARGE_INTEGER freq;\n    QueryPerformanceFrequency(&freq);\n    return freq.QuadPart;\n}\n\nint kill(pid_t pid, int exit_code) {\n    return TerminateProcess((HANDLE)(uintptr_t)pid, exit_code);\n}\n\n#define NANOSEC 1000000000\n#define MICROSEC 1000000\n\nvoid usleep(size_t us) {\n    if (us > 1000) {\n        Sleep(us / 1000);\n        return;\n    }\n    LONGLONG delta = get_cpu_freq() / MICROSEC * us;\n    LARGE_INTEGER counter;\n    QueryPerformanceCounter(&counter);\n    LONGLONG start = counter.QuadPart;\n    for (;;) {\n        QueryPerformanceCounter(&counter);\n        if (counter.QuadPart - start >= delta)\n            return;\n    }\n}\n\nvoid sleep(size_t sec) {\n    Sleep(sec * 1000UL);\n}\n\nint clock_gettime(int what, struct timespec* ti) {\n    switch (what) {\n    case CLOCK_MONOTONIC:\n        static __int64 Freq = 0;\n        static __int64 Start = 0;\n        static __int64 StartTime = 0;\n        if (Freq == 0) {\n            StartTime = time(NULL);\n            QueryPerformanceFrequency((LARGE_INTEGER*)&Freq);\n            QueryPerformanceCounter((LARGE_INTEGER*)&Start);\n        }\n        __int64 Count = 0;\n        QueryPerformanceCounter((LARGE_INTEGER*)&Count);\n\n        // 乘以1000，把秒化为毫秒\n        __int64 now = (__int64)((double)(Count - Start) / (double)Freq * 1000.0) + StartTime * 1000;\n        ti->tv_sec = now / 1000;\n        ti->tv_nsec = (now - now / 1000 * 1000) * 1000 * 1000;\n        return 0;\n    case CLOCK_REALTIME:\n        SYSTEMTIME st;\n        GetSystemTime(&st); // 获取 UTC 时间\n\n        // 将 SYSTEMTIME 转换为 UNIX 时间戳\n        FILETIME ft;\n        SystemTimeToFileTime(&st, &ft);\n        ULARGE_INTEGER u64;\n        u64.LowPart = ft.dwLowDateTime;\n        u64.HighPart = ft.dwHighDateTime;\n\n        ti->tv_sec = (uint32_t)((u64.QuadPart - 116444736000000000ULL) / 10000000); // 转换为秒\n        ti->tv_nsec = (uint32_t)((u64.QuadPart % 10000000) * 100); // 获取纳秒部分\n        return 0; // 响应成功\n    case CLOCK_THREAD_CPUTIME_ID:\n        // 获取当前线程的 CPU 时间\n        FILETIME creation_time, exit_time, kernel_time, user_time;\n        if (GetThreadTimes(GetCurrentThread(), &creation_time, &exit_time, &kernel_time, &user_time)) {\n            ULARGE_INTEGER u64;\n            u64.LowPart = user_time.dwLowDateTime;\n            u64.HighPart = user_time.dwHighDateTime;\n\n            ti->tv_sec = (uint32_t)((u64.QuadPart - 116444736000000000ULL) / 10000000); // 转换为秒\n            ti->tv_nsec = (uint32_t)((u64.QuadPart % 10000000) * 100); // 获取纳秒部分\n            return 0;\n        } else {\n            return -1; // 获取失败\n        }\n    }\n    return -1;\n}\n\nint flock(int fd, int flag) {\n    // Not implemented\n    return 3;\n}\n\nint fcntl(int fd, int cmd, long arg) {\n    if (cmd == F_GETFL)\n        return 0;\n\n    if (cmd == F_SETFL && arg == O_NONBLOCK) {\n        u_long ulOption = 1;\n        ioctlsocket(fd, FIONBIO, &ulOption);\n    }\n\n    return 1;\n}\n\nvoid sigfillset(int* flag) {\n    // Not implemented\n}\n\nint sigemptyset(int* set) {\n    /*Not implemented*/\n    return 0;\n}\n\nvoid sigaction(int flag, struct sigaction* action, void* param) {\n    // Not implemented\n}\n\nstatic void socket_keepalive(int fd) {\n    int keepalive = 1;\n    int ret = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void*)&keepalive,\n        sizeof(keepalive));\n\n    assert(ret != SOCKET_ERROR);\n}\n\nint pipe(int fd[2]) {\n    int listen_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n    if (listen_fd == INVALID_SOCKET) {\n        return -1;\n    }\n    \n    struct sockaddr_in sin;\n    sin.sin_family = AF_INET;\n    sin.sin_addr.S_un.S_addr = inet_addr(\"127.0.0.1\");\n\n    srand(time(NULL));\n    // use random port(range from 60000 to 60999) to simulate pipe()\n    int port;\n    for (;;) {\n        port = 60000 + rand() % 1000;\n        sin.sin_port = htons(port);\n        if (!bind(listen_fd, (struct sockaddr*)&sin, sizeof(sin)))\n            break;\n    }\n\n    if (listen(listen_fd, 5) == SOCKET_ERROR) {\n        closesocket(listen_fd);\n        return -1;\n    }\n\n    socket_keepalive(listen_fd);\n\n    int client_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n    if (client_fd == INVALID_SOCKET) {\n        closesocket(listen_fd);\n        return -1;\n    }\n    \n    if (connect(client_fd, (struct sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR) {\n        closesocket(listen_fd);\n        closesocket(client_fd);\n        return -1;\n    }\n\n    struct sockaddr_in client_addr;\n    size_t name_len = sizeof(client_addr);\n    int client_sock = accept(listen_fd, (struct sockaddr*)&client_addr, &name_len);\n    if (client_sock == INVALID_SOCKET) {\n        closesocket(listen_fd);\n        closesocket(client_fd);\n        return -1;\n    }\n\n    closesocket(listen_fd);  // Close listen socket as it's no longer needed\n\n    fd[0] = client_sock;\n    fd[1] = client_fd;\n\n    socket_keepalive(client_sock);\n    socket_keepalive(client_fd);\n\n    return 0;\n}\n\nint write(int fd, const void* ptr, unsigned int sz) {\n    WSABUF vecs[1];\n    vecs[0].buf = (char*)ptr;\n    vecs[0].len = sz;\n\n    DWORD bytesSent;\n    if (WSASend(fd, vecs, 1, &bytesSent, 0, NULL, NULL)) {\n        int wsa_error = WSAGetLastError();\n        set_errno_from_wsa_error(wsa_error);\n        return -1;\n    } else {\n        return bytesSent;\n    }\n}\n\nint read(int fd, void* buffer, unsigned int sz) {\n\n    WSABUF vecs[1];\n    vecs[0].buf = buffer;\n    vecs[0].len = sz;\n\n    DWORD bytesRecv = 0;\n    DWORD flags = 0;\n    if (WSARecv(fd, vecs, 1, &bytesRecv, &flags, NULL, NULL)) {\n        int wsa_error = WSAGetLastError();\n        \n        if (wsa_error == WSAECONNRESET) {\n            return 0;  // Connection closed by peer\n        }\n        \n        // Map WSA error to errno for better error reporting\n        set_errno_from_wsa_error(wsa_error);\n        return -1;\n    } else {\n        return bytesRecv;\n    }\n}\n\n// Wrapper for recv function with better error handling\nint compat_recv(SOCKET s, char *buf, int len, int flags) {\n    WSABUF vecs[1];\n    vecs[0].buf = buf;\n    vecs[0].len = len;\n\n    DWORD bytesRecv = 0;\n    DWORD wsaFlags = 0;\n    if (WSARecv(s, vecs, 1, &bytesRecv, &wsaFlags, NULL, NULL)) {\n        int wsa_error = WSAGetLastError();\n        \n        // Handle non-blocking operations - these are not real errors\n        if (wsa_error == WSAEWOULDBLOCK || wsa_error == WSAEINTR) {\n            // For non-blocking sockets, this is normal - no data available right now\n            set_errno_from_wsa_error(wsa_error);\n            return -1;  // Caller should check errno == EAGAIN\n        }\n        \n        if (wsa_error == WSAECONNRESET) {\n            return 0;  // Connection closed by peer\n        }\n        \n        // Map WSA error to errno for better error reporting\n        set_errno_from_wsa_error(wsa_error);\n        return -1;\n    } else {\n        return bytesRecv;\n    }\n}\n\nint close(int fd) {\n    shutdown(fd, SD_BOTH);\n    return closesocket(fd);\n}\n\nint daemon(int a, int b) {\n    // Not implemented\n    return 0;\n}\n\nchar* strsep(char** stringp, const char* delim) {\n    char* s;\n    const char* spanp;\n    int c, sc;\n    char* tok;\n    if ((s = *stringp) == NULL)\n        return (NULL);\n    for (tok = s;;) {\n        c = *s++;\n        spanp = delim;\n        do {\n            if ((sc = *spanp++) == c) {\n                if (c == 0)\n                    s = NULL;\n                else\n                    s[-1] = 0;\n                *stringp = s;\n                return (tok);\n            }\n        } while (sc != 0);\n    }\n    /* NOTREACHED */\n}\n"
  },
  {
    "path": "3rd/compat-mingw/unistd.h",
    "content": "#pragma once\n\n#include <assert.h>\n#include <stdio.h>\n#include <time.h>\n#include <process.h>\n#include <io.h>\n#include <assert.h>\n#include <stdlib.h>\n#include <errno.h>\n\n// Define missing errno values for network errors\n#ifndef ECONNRESET\n#define ECONNRESET 104\n#endif\n#ifndef ECONNABORTED\n#define ECONNABORTED 103\n#endif\n#ifndef ECONNREFUSED\n#define ECONNREFUSED 111\n#endif\n#ifndef ENETDOWN\n#define ENETDOWN 100\n#endif\n#ifndef ENETUNREACH\n#define ENETUNREACH 101\n#endif\n#ifndef EHOSTDOWN\n#define EHOSTDOWN 112\n#endif\n#ifndef EHOSTUNREACH\n#define EHOSTUNREACH 113\n#endif\n#ifndef ETIMEDOUT\n#define ETIMEDOUT 110\n#endif\n#ifndef ENOTCONN\n#define ENOTCONN 107\n#endif\n#ifndef EADDRINUSE\n#define EADDRINUSE 98\n#endif\n#ifndef EADDRNOTAVAIL\n#define EADDRNOTAVAIL 99\n#endif\n\n// Include winsock2.h for gethostname and other network functions\n#define _WINSOCK_DEPRECATED_NO_WARNINGS\n#define WIN32_LEAN_AND_MEAN\n#include <winsock2.h>\n#include <ws2tcpip.h>\n\n// Undefine Windows legacy keywords that conflict with variable names\n#ifdef near\n#undef near\n#endif\n#ifdef far\n#undef far\n#endif\n\n// Socket compatibility macros\n#define SHUT_RD SD_RECEIVE\n#define SHUT_WR SD_SEND\n#define SHUT_RDWR SD_BOTH\n\n#define ssize_t size_t\n\n#define random rand\n#define srandom srand\n#define snprintf _snprintf\n#define localtime_r _localtime64_s\n\n#define pid_t int\n\nint kill(pid_t pid, int exit_code);\n\nvoid usleep(size_t us);\nvoid sleep(size_t ms);\n\nint clock_gettime(int what, struct timespec *ti);\n\nenum { LOCK_EX, LOCK_NB };\nint flock(int fd, int flag);\n\nstruct sigaction {\n  void (*sa_handler)(int);\n  int sa_flags;\n  int sa_mask;\n};\nenum { SIGPIPE, SIGHUP, SA_RESTART };\nvoid sigfillset(int *flag);\nint sigemptyset(int* set);\nvoid sigaction(int flag, struct sigaction *action, void* param);\n\nint pipe(int fd[2]);\nint daemon(int a, int b);\n\n#define O_NONBLOCK 1\n#define F_SETFL 0\n#define F_GETFL 1\n\nint fcntl(int fd, int cmd, long arg);\n\nchar *strsep(char **stringp, const char *delim);\n\nint write(int fd, const void* ptr, unsigned int sz);\nint read(int fd, void* buffer, unsigned int sz);\n// Wrapper function for recv with better error handling\nint compat_recv(SOCKET s, char *buf, int len, int flags);\n\n// Macro to redirect recv calls to our wrapper\n#define recv compat_recv\nint close(int fd);\n\n#define getpid _getpid\n#define open _open\n#define dup2 _dup2\n"
  },
  {
    "path": "3rd/compat-mingw/wepoll.c",
    "content": "/*\n * wepoll - epoll for Windows\n * https://github.com/piscisaureus/wepoll\n *\n * Copyright 2012-2020, Bert Belder <bertbelder@gmail.com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *\n *   * Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef WEPOLL_EXPORT\n#define WEPOLL_EXPORT\n#endif\n\n#include <stdint.h>\n\nenum EPOLL_EVENTS {\n  EPOLLIN      = (int) (1U <<  0),\n  EPOLLPRI     = (int) (1U <<  1),\n  EPOLLOUT     = (int) (1U <<  2),\n  EPOLLERR     = (int) (1U <<  3),\n  EPOLLHUP     = (int) (1U <<  4),\n  EPOLLRDNORM  = (int) (1U <<  6),\n  EPOLLRDBAND  = (int) (1U <<  7),\n  EPOLLWRNORM  = (int) (1U <<  8),\n  EPOLLWRBAND  = (int) (1U <<  9),\n  EPOLLMSG     = (int) (1U << 10), /* Never reported. */\n  EPOLLRDHUP   = (int) (1U << 13),\n  EPOLLONESHOT = (int) (1U << 31)\n};\n\n#define EPOLLIN      (1U <<  0)\n#define EPOLLPRI     (1U <<  1)\n#define EPOLLOUT     (1U <<  2)\n#define EPOLLERR     (1U <<  3)\n#define EPOLLHUP     (1U <<  4)\n#define EPOLLRDNORM  (1U <<  6)\n#define EPOLLRDBAND  (1U <<  7)\n#define EPOLLWRNORM  (1U <<  8)\n#define EPOLLWRBAND  (1U <<  9)\n#define EPOLLMSG     (1U << 10)\n#define EPOLLRDHUP   (1U << 13)\n#define EPOLLONESHOT (1U << 31)\n\n#define EPOLL_CTL_ADD 1\n#define EPOLL_CTL_MOD 2\n#define EPOLL_CTL_DEL 3\n\ntypedef void* HANDLE;\ntypedef uintptr_t SOCKET;\n\ntypedef union epoll_data {\n  void* ptr;\n  int fd;\n  uint32_t u32;\n  uint64_t u64;\n  SOCKET sock; /* Windows specific */\n  HANDLE hnd;  /* Windows specific */\n} epoll_data_t;\n\nstruct epoll_event {\n  uint32_t events;   /* Epoll events and flags */\n  epoll_data_t data; /* User data variable */\n};\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nWEPOLL_EXPORT HANDLE epoll_create(int size);\nWEPOLL_EXPORT HANDLE epoll_create1(int flags);\n\nWEPOLL_EXPORT int epoll_close(HANDLE ephnd);\n\nWEPOLL_EXPORT int epoll_ctl(HANDLE ephnd,\n                            int op,\n                            SOCKET sock,\n                            struct epoll_event* event);\n\nWEPOLL_EXPORT int epoll_wait(HANDLE ephnd,\n                             struct epoll_event* events,\n                             int maxevents,\n                             int timeout);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#include <assert.h>\n\n#include <stdlib.h>\n\n#define WEPOLL_INTERNAL static\n#define WEPOLL_INTERNAL_EXTERN static\n\n#if defined(__clang__)\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wnonportable-system-include-path\"\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#elif defined(_MSC_VER)\n#pragma warning(push, 1)\n#endif\n\n#undef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN\n\n#undef _WIN32_WINNT\n#define _WIN32_WINNT 0x0600\n\n#include <winsock2.h>\n#include <ws2tcpip.h>\n#include <windows.h>\n\n#if defined(__clang__)\n#pragma clang diagnostic pop\n#elif defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n\nWEPOLL_INTERNAL int nt_global_init(void);\n\ntypedef LONG NTSTATUS;\ntypedef NTSTATUS* PNTSTATUS;\n\n#ifndef NT_SUCCESS\n#define NT_SUCCESS(status) (((NTSTATUS)(status)) >= 0)\n#endif\n\n#ifndef STATUS_SUCCESS\n#define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)\n#endif\n\n#ifndef STATUS_PENDING\n#define STATUS_PENDING ((NTSTATUS) 0x00000103L)\n#endif\n\n#ifndef STATUS_CANCELLED\n#define STATUS_CANCELLED ((NTSTATUS) 0xC0000120L)\n#endif\n\n#ifndef STATUS_NOT_FOUND\n#define STATUS_NOT_FOUND ((NTSTATUS) 0xC0000225L)\n#endif\n\ntypedef struct _IO_STATUS_BLOCK {\n  NTSTATUS Status;\n  ULONG_PTR Information;\n} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;\n\ntypedef VOID(NTAPI* PIO_APC_ROUTINE)(PVOID ApcContext,\n                                     PIO_STATUS_BLOCK IoStatusBlock,\n                                     ULONG Reserved);\n\ntypedef struct _UNICODE_STRING {\n  USHORT Length;\n  USHORT MaximumLength;\n  PWSTR Buffer;\n} UNICODE_STRING, *PUNICODE_STRING;\n\n#define RTL_CONSTANT_STRING(s) \\\n  { sizeof(s) - sizeof((s)[0]), sizeof(s), s }\n\ntypedef struct _OBJECT_ATTRIBUTES {\n  ULONG Length;\n  HANDLE RootDirectory;\n  PUNICODE_STRING ObjectName;\n  ULONG Attributes;\n  PVOID SecurityDescriptor;\n  PVOID SecurityQualityOfService;\n} OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES;\n\n#define RTL_CONSTANT_OBJECT_ATTRIBUTES(ObjectName, Attributes) \\\n  { sizeof(OBJECT_ATTRIBUTES), NULL, ObjectName, Attributes, NULL, NULL }\n\n#ifndef FILE_OPEN\n#define FILE_OPEN 0x00000001UL\n#endif\n\n#define KEYEDEVENT_WAIT 0x00000001UL\n#define KEYEDEVENT_WAKE 0x00000002UL\n#define KEYEDEVENT_ALL_ACCESS \\\n  (STANDARD_RIGHTS_REQUIRED | KEYEDEVENT_WAIT | KEYEDEVENT_WAKE)\n\n#define NT_NTDLL_IMPORT_LIST(X)           \\\n  X(NTSTATUS,                             \\\n    NTAPI,                                \\\n    NtCancelIoFileEx,                     \\\n    (HANDLE FileHandle,                   \\\n     PIO_STATUS_BLOCK IoRequestToCancel,  \\\n     PIO_STATUS_BLOCK IoStatusBlock))     \\\n                                          \\\n  X(NTSTATUS,                             \\\n    NTAPI,                                \\\n    NtCreateFile,                         \\\n    (PHANDLE FileHandle,                  \\\n     ACCESS_MASK DesiredAccess,           \\\n     POBJECT_ATTRIBUTES ObjectAttributes, \\\n     PIO_STATUS_BLOCK IoStatusBlock,      \\\n     PLARGE_INTEGER AllocationSize,       \\\n     ULONG FileAttributes,                \\\n     ULONG ShareAccess,                   \\\n     ULONG CreateDisposition,             \\\n     ULONG CreateOptions,                 \\\n     PVOID EaBuffer,                      \\\n     ULONG EaLength))                     \\\n                                          \\\n  X(NTSTATUS,                             \\\n    NTAPI,                                \\\n    NtCreateKeyedEvent,                   \\\n    (PHANDLE KeyedEventHandle,            \\\n     ACCESS_MASK DesiredAccess,           \\\n     POBJECT_ATTRIBUTES ObjectAttributes, \\\n     ULONG Flags))                        \\\n                                          \\\n  X(NTSTATUS,                             \\\n    NTAPI,                                \\\n    NtDeviceIoControlFile,                \\\n    (HANDLE FileHandle,                   \\\n     HANDLE Event,                        \\\n     PIO_APC_ROUTINE ApcRoutine,          \\\n     PVOID ApcContext,                    \\\n     PIO_STATUS_BLOCK IoStatusBlock,      \\\n     ULONG IoControlCode,                 \\\n     PVOID InputBuffer,                   \\\n     ULONG InputBufferLength,             \\\n     PVOID OutputBuffer,                  \\\n     ULONG OutputBufferLength))           \\\n                                          \\\n  X(NTSTATUS,                             \\\n    NTAPI,                                \\\n    NtReleaseKeyedEvent,                  \\\n    (HANDLE KeyedEventHandle,             \\\n     PVOID KeyValue,                      \\\n     BOOLEAN Alertable,                   \\\n     PLARGE_INTEGER Timeout))             \\\n                                          \\\n  X(NTSTATUS,                             \\\n    NTAPI,                                \\\n    NtWaitForKeyedEvent,                  \\\n    (HANDLE KeyedEventHandle,             \\\n     PVOID KeyValue,                      \\\n     BOOLEAN Alertable,                   \\\n     PLARGE_INTEGER Timeout))             \\\n                                          \\\n  X(ULONG, WINAPI, RtlNtStatusToDosError, (NTSTATUS Status))\n\n#define X(return_type, attributes, name, parameters) \\\n  WEPOLL_INTERNAL_EXTERN return_type(attributes* name) parameters;\nNT_NTDLL_IMPORT_LIST(X)\n#undef X\n\n#define AFD_POLL_RECEIVE           0x0001\n#define AFD_POLL_RECEIVE_EXPEDITED 0x0002\n#define AFD_POLL_SEND              0x0004\n#define AFD_POLL_DISCONNECT        0x0008\n#define AFD_POLL_ABORT             0x0010\n#define AFD_POLL_LOCAL_CLOSE       0x0020\n#define AFD_POLL_ACCEPT            0x0080\n#define AFD_POLL_CONNECT_FAIL      0x0100\n\ntypedef struct _AFD_POLL_HANDLE_INFO {\n  HANDLE Handle;\n  ULONG Events;\n  NTSTATUS Status;\n} AFD_POLL_HANDLE_INFO, *PAFD_POLL_HANDLE_INFO;\n\ntypedef struct _AFD_POLL_INFO {\n  LARGE_INTEGER Timeout;\n  ULONG NumberOfHandles;\n  ULONG Exclusive;\n  AFD_POLL_HANDLE_INFO Handles[1];\n} AFD_POLL_INFO, *PAFD_POLL_INFO;\n\nWEPOLL_INTERNAL int afd_create_device_handle(HANDLE iocp_handle,\n                                             HANDLE* afd_device_handle_out);\n\nWEPOLL_INTERNAL int afd_poll(HANDLE afd_device_handle,\n                             AFD_POLL_INFO* poll_info,\n                             IO_STATUS_BLOCK* io_status_block);\nWEPOLL_INTERNAL int afd_cancel_poll(HANDLE afd_device_handle,\n                                    IO_STATUS_BLOCK* io_status_block);\n\n#define return_map_error(value) \\\n  do {                          \\\n    err_map_win_error();        \\\n    return (value);             \\\n  } while (0)\n\n#define return_set_error(value, error) \\\n  do {                                 \\\n    err_set_win_error(error);          \\\n    return (value);                    \\\n  } while (0)\n\nWEPOLL_INTERNAL void err_map_win_error(void);\nWEPOLL_INTERNAL void err_set_win_error(DWORD error);\nWEPOLL_INTERNAL int err_check_handle(HANDLE handle);\n\n#define IOCTL_AFD_POLL 0x00012024\n\nstatic UNICODE_STRING afd__device_name =\n    RTL_CONSTANT_STRING(L\"\\\\Device\\\\Afd\\\\Wepoll\");\n\nstatic OBJECT_ATTRIBUTES afd__device_attributes =\n    RTL_CONSTANT_OBJECT_ATTRIBUTES(&afd__device_name, 0);\n\nint afd_create_device_handle(HANDLE iocp_handle,\n                             HANDLE* afd_device_handle_out) {\n  HANDLE afd_device_handle;\n  IO_STATUS_BLOCK iosb;\n  NTSTATUS status;\n\n  /* By opening \\Device\\Afd without specifying any extended attributes, we'll\n   * get a handle that lets us talk to the AFD driver, but that doesn't have an\n   * associated endpoint (so it's not a socket). */\n  status = NtCreateFile(&afd_device_handle,\n                        SYNCHRONIZE,\n                        &afd__device_attributes,\n                        &iosb,\n                        NULL,\n                        0,\n                        FILE_SHARE_READ | FILE_SHARE_WRITE,\n                        FILE_OPEN,\n                        0,\n                        NULL,\n                        0);\n  if (status != STATUS_SUCCESS)\n    return_set_error(-1, RtlNtStatusToDosError(status));\n\n  if (CreateIoCompletionPort(afd_device_handle, iocp_handle, 0, 0) == NULL)\n    goto error;\n\n  if (!SetFileCompletionNotificationModes(afd_device_handle,\n                                          FILE_SKIP_SET_EVENT_ON_HANDLE))\n    goto error;\n\n  *afd_device_handle_out = afd_device_handle;\n  return 0;\n\nerror:\n  CloseHandle(afd_device_handle);\n  return_map_error(-1);\n}\n\nint afd_poll(HANDLE afd_device_handle,\n             AFD_POLL_INFO* poll_info,\n             IO_STATUS_BLOCK* io_status_block) {\n  NTSTATUS status;\n\n  /* Blocking operation is not supported. */\n  assert(io_status_block != NULL);\n\n  io_status_block->Status = STATUS_PENDING;\n  status = NtDeviceIoControlFile(afd_device_handle,\n                                 NULL,\n                                 NULL,\n                                 io_status_block,\n                                 io_status_block,\n                                 IOCTL_AFD_POLL,\n                                 poll_info,\n                                 sizeof *poll_info,\n                                 poll_info,\n                                 sizeof *poll_info);\n\n  if (status == STATUS_SUCCESS)\n    return 0;\n  else if (status == STATUS_PENDING)\n    return_set_error(-1, ERROR_IO_PENDING);\n  else\n    return_set_error(-1, RtlNtStatusToDosError(status));\n}\n\nint afd_cancel_poll(HANDLE afd_device_handle,\n                    IO_STATUS_BLOCK* io_status_block) {\n  NTSTATUS cancel_status;\n  IO_STATUS_BLOCK cancel_iosb;\n\n  /* If the poll operation has already completed or has been cancelled earlier,\n   * there's nothing left for us to do. */\n  if (io_status_block->Status != STATUS_PENDING)\n    return 0;\n\n  cancel_status =\n      NtCancelIoFileEx(afd_device_handle, io_status_block, &cancel_iosb);\n\n  /* NtCancelIoFileEx() may return STATUS_NOT_FOUND if the operation completed\n   * just before calling NtCancelIoFileEx(). This is not an error. */\n  if (cancel_status == STATUS_SUCCESS || cancel_status == STATUS_NOT_FOUND)\n    return 0;\n  else\n    return_set_error(-1, RtlNtStatusToDosError(cancel_status));\n}\n\nWEPOLL_INTERNAL int epoll_global_init(void);\n\nWEPOLL_INTERNAL int init(void);\n\ntypedef struct port_state port_state_t;\ntypedef struct queue queue_t;\ntypedef struct sock_state sock_state_t;\ntypedef struct ts_tree_node ts_tree_node_t;\n\nWEPOLL_INTERNAL port_state_t* port_new(HANDLE* iocp_handle_out);\nWEPOLL_INTERNAL int port_close(port_state_t* port_state);\nWEPOLL_INTERNAL int port_delete(port_state_t* port_state);\n\nWEPOLL_INTERNAL int port_wait(port_state_t* port_state,\n                              struct epoll_event* events,\n                              int maxevents,\n                              int timeout);\n\nWEPOLL_INTERNAL int port_ctl(port_state_t* port_state,\n                             int op,\n                             SOCKET sock,\n                             struct epoll_event* ev);\n\nWEPOLL_INTERNAL int port_register_socket(port_state_t* port_state,\n                                         sock_state_t* sock_state,\n                                         SOCKET socket);\nWEPOLL_INTERNAL void port_unregister_socket(port_state_t* port_state,\n                                            sock_state_t* sock_state);\nWEPOLL_INTERNAL sock_state_t* port_find_socket(port_state_t* port_state,\n                                               SOCKET socket);\n\nWEPOLL_INTERNAL void port_request_socket_update(port_state_t* port_state,\n                                                sock_state_t* sock_state);\nWEPOLL_INTERNAL void port_cancel_socket_update(port_state_t* port_state,\n                                               sock_state_t* sock_state);\n\nWEPOLL_INTERNAL void port_add_deleted_socket(port_state_t* port_state,\n                                             sock_state_t* sock_state);\nWEPOLL_INTERNAL void port_remove_deleted_socket(port_state_t* port_state,\n                                                sock_state_t* sock_state);\n\nWEPOLL_INTERNAL HANDLE port_get_iocp_handle(port_state_t* port_state);\nWEPOLL_INTERNAL queue_t* port_get_poll_group_queue(port_state_t* port_state);\n\nWEPOLL_INTERNAL port_state_t* port_state_from_handle_tree_node(\n    ts_tree_node_t* tree_node);\nWEPOLL_INTERNAL ts_tree_node_t* port_state_to_handle_tree_node(\n    port_state_t* port_state);\n\n/* The reflock is a special kind of lock that normally prevents a chunk of\n * memory from being freed, but does allow the chunk of memory to eventually be\n * released in a coordinated fashion.\n *\n * Under normal operation, threads increase and decrease the reference count,\n * which are wait-free operations.\n *\n * Exactly once during the reflock's lifecycle, a thread holding a reference to\n * the lock may \"destroy\" the lock; this operation blocks until all other\n * threads holding a reference to the lock have dereferenced it. After\n * \"destroy\" returns, the calling thread may assume that no other threads have\n * a reference to the lock.\n *\n * Attemmpting to lock or destroy a lock after reflock_unref_and_destroy() has\n * been called is invalid and results in undefined behavior. Therefore the user\n * should use another lock to guarantee that this can't happen.\n */\n\ntypedef struct reflock {\n  volatile long state; /* 32-bit Interlocked APIs operate on `long` values. */\n} reflock_t;\n\nWEPOLL_INTERNAL int reflock_global_init(void);\n\nWEPOLL_INTERNAL void reflock_init(reflock_t* reflock);\nWEPOLL_INTERNAL void reflock_ref(reflock_t* reflock);\nWEPOLL_INTERNAL void reflock_unref(reflock_t* reflock);\nWEPOLL_INTERNAL void reflock_unref_and_destroy(reflock_t* reflock);\n\n#include <stdbool.h>\n\n/* N.b.: the tree functions do not set errno or LastError when they fail. Each\n * of the API functions has at most one failure mode. It is up to the caller to\n * set an appropriate error code when necessary. */\n\ntypedef struct tree tree_t;\ntypedef struct tree_node tree_node_t;\n\ntypedef struct tree {\n  tree_node_t* root;\n} tree_t;\n\ntypedef struct tree_node {\n  tree_node_t* left;\n  tree_node_t* right;\n  tree_node_t* parent;\n  uintptr_t key;\n  bool red;\n} tree_node_t;\n\nWEPOLL_INTERNAL void tree_init(tree_t* tree);\nWEPOLL_INTERNAL void tree_node_init(tree_node_t* node);\n\nWEPOLL_INTERNAL int tree_add(tree_t* tree, tree_node_t* node, uintptr_t key);\nWEPOLL_INTERNAL void tree_del(tree_t* tree, tree_node_t* node);\n\nWEPOLL_INTERNAL tree_node_t* tree_find(const tree_t* tree, uintptr_t key);\nWEPOLL_INTERNAL tree_node_t* tree_root(const tree_t* tree);\n\ntypedef struct ts_tree {\n  tree_t tree;\n  SRWLOCK lock;\n} ts_tree_t;\n\ntypedef struct ts_tree_node {\n  tree_node_t tree_node;\n  reflock_t reflock;\n} ts_tree_node_t;\n\nWEPOLL_INTERNAL void ts_tree_init(ts_tree_t* rtl);\nWEPOLL_INTERNAL void ts_tree_node_init(ts_tree_node_t* node);\n\nWEPOLL_INTERNAL int ts_tree_add(ts_tree_t* ts_tree,\n                                ts_tree_node_t* node,\n                                uintptr_t key);\n\nWEPOLL_INTERNAL ts_tree_node_t* ts_tree_del_and_ref(ts_tree_t* ts_tree,\n                                                    uintptr_t key);\nWEPOLL_INTERNAL ts_tree_node_t* ts_tree_find_and_ref(ts_tree_t* ts_tree,\n                                                     uintptr_t key);\n\nWEPOLL_INTERNAL void ts_tree_node_unref(ts_tree_node_t* node);\nWEPOLL_INTERNAL void ts_tree_node_unref_and_destroy(ts_tree_node_t* node);\n\nstatic ts_tree_t epoll__handle_tree;\n\nint epoll_global_init(void) {\n  ts_tree_init(&epoll__handle_tree);\n  return 0;\n}\n\nstatic HANDLE epoll__create(void) {\n  port_state_t* port_state;\n  HANDLE ephnd;\n  ts_tree_node_t* tree_node;\n\n  if (init() < 0)\n    return NULL;\n\n  port_state = port_new(&ephnd);\n  if (port_state == NULL)\n    return NULL;\n\n  tree_node = port_state_to_handle_tree_node(port_state);\n  if (ts_tree_add(&epoll__handle_tree, tree_node, (uintptr_t) ephnd) < 0) {\n    /* This should never happen. */\n    port_delete(port_state);\n    return_set_error(NULL, ERROR_ALREADY_EXISTS);\n  }\n\n  return ephnd;\n}\n\nHANDLE epoll_create(int size) {\n  if (size <= 0)\n    return_set_error(NULL, ERROR_INVALID_PARAMETER);\n\n  return epoll__create();\n}\n\nHANDLE epoll_create1(int flags) {\n  if (flags != 0)\n    return_set_error(NULL, ERROR_INVALID_PARAMETER);\n\n  return epoll__create();\n}\n\nint epoll_close(HANDLE ephnd) {\n  ts_tree_node_t* tree_node;\n  port_state_t* port_state;\n\n  if (init() < 0)\n    return -1;\n\n  tree_node = ts_tree_del_and_ref(&epoll__handle_tree, (uintptr_t) ephnd);\n  if (tree_node == NULL) {\n    err_set_win_error(ERROR_INVALID_PARAMETER);\n    goto err;\n  }\n\n  port_state = port_state_from_handle_tree_node(tree_node);\n  port_close(port_state);\n\n  ts_tree_node_unref_and_destroy(tree_node);\n\n  return port_delete(port_state);\n\nerr:\n  err_check_handle(ephnd);\n  return -1;\n}\n\nint epoll_ctl(HANDLE ephnd, int op, SOCKET sock, struct epoll_event* ev) {\n  ts_tree_node_t* tree_node;\n  port_state_t* port_state;\n  int r;\n\n  if (init() < 0)\n    return -1;\n\n  tree_node = ts_tree_find_and_ref(&epoll__handle_tree, (uintptr_t) ephnd);\n  if (tree_node == NULL) {\n    err_set_win_error(ERROR_INVALID_PARAMETER);\n    goto err;\n  }\n\n  port_state = port_state_from_handle_tree_node(tree_node);\n  r = port_ctl(port_state, op, sock, ev);\n\n  ts_tree_node_unref(tree_node);\n\n  if (r < 0)\n    goto err;\n\n  return 0;\n\nerr:\n  /* On Linux, in the case of epoll_ctl(), EBADF takes priority over other\n   * errors. Wepoll mimics this behavior. */\n  err_check_handle(ephnd);\n  err_check_handle((HANDLE) sock);\n  return -1;\n}\n\nint epoll_wait(HANDLE ephnd,\n               struct epoll_event* events,\n               int maxevents,\n               int timeout) {\n  ts_tree_node_t* tree_node;\n  port_state_t* port_state;\n  int num_events;\n\n  if (maxevents <= 0)\n    return_set_error(-1, ERROR_INVALID_PARAMETER);\n\n  if (init() < 0)\n    return -1;\n\n  tree_node = ts_tree_find_and_ref(&epoll__handle_tree, (uintptr_t) ephnd);\n  if (tree_node == NULL) {\n    err_set_win_error(ERROR_INVALID_PARAMETER);\n    goto err;\n  }\n\n  port_state = port_state_from_handle_tree_node(tree_node);\n  num_events = port_wait(port_state, events, maxevents, timeout);\n\n  ts_tree_node_unref(tree_node);\n\n  if (num_events < 0)\n    goto err;\n\n  return num_events;\n\nerr:\n  err_check_handle(ephnd);\n  return -1;\n}\n\n#include <errno.h>\n\n#define ERR__ERRNO_MAPPINGS(X)               \\\n  X(ERROR_ACCESS_DENIED, EACCES)             \\\n  X(ERROR_ALREADY_EXISTS, EEXIST)            \\\n  X(ERROR_BAD_COMMAND, EACCES)               \\\n  X(ERROR_BAD_EXE_FORMAT, ENOEXEC)           \\\n  X(ERROR_BAD_LENGTH, EACCES)                \\\n  X(ERROR_BAD_NETPATH, ENOENT)               \\\n  X(ERROR_BAD_NET_NAME, ENOENT)              \\\n  X(ERROR_BAD_NET_RESP, ENETDOWN)            \\\n  X(ERROR_BAD_PATHNAME, ENOENT)              \\\n  X(ERROR_BROKEN_PIPE, EPIPE)                \\\n  X(ERROR_CANNOT_MAKE, EACCES)               \\\n  X(ERROR_COMMITMENT_LIMIT, ENOMEM)          \\\n  X(ERROR_CONNECTION_ABORTED, ECONNABORTED)  \\\n  X(ERROR_CONNECTION_ACTIVE, EISCONN)        \\\n  X(ERROR_CONNECTION_REFUSED, ECONNREFUSED)  \\\n  X(ERROR_CRC, EACCES)                       \\\n  X(ERROR_DIR_NOT_EMPTY, ENOTEMPTY)          \\\n  X(ERROR_DISK_FULL, ENOSPC)                 \\\n  X(ERROR_DUP_NAME, EADDRINUSE)              \\\n  X(ERROR_FILENAME_EXCED_RANGE, ENOENT)      \\\n  X(ERROR_FILE_NOT_FOUND, ENOENT)            \\\n  X(ERROR_GEN_FAILURE, EACCES)               \\\n  X(ERROR_GRACEFUL_DISCONNECT, EPIPE)        \\\n  X(ERROR_HOST_DOWN, EHOSTUNREACH)           \\\n  X(ERROR_HOST_UNREACHABLE, EHOSTUNREACH)    \\\n  X(ERROR_INSUFFICIENT_BUFFER, EFAULT)       \\\n  X(ERROR_INVALID_ADDRESS, EADDRNOTAVAIL)    \\\n  X(ERROR_INVALID_FUNCTION, EINVAL)          \\\n  X(ERROR_INVALID_HANDLE, EBADF)             \\\n  X(ERROR_INVALID_NETNAME, EADDRNOTAVAIL)    \\\n  X(ERROR_INVALID_PARAMETER, EINVAL)         \\\n  X(ERROR_INVALID_USER_BUFFER, EMSGSIZE)     \\\n  X(ERROR_IO_PENDING, EINPROGRESS)           \\\n  X(ERROR_LOCK_VIOLATION, EACCES)            \\\n  X(ERROR_MORE_DATA, EMSGSIZE)               \\\n  X(ERROR_NETNAME_DELETED, ECONNABORTED)     \\\n  X(ERROR_NETWORK_ACCESS_DENIED, EACCES)     \\\n  X(ERROR_NETWORK_BUSY, ENETDOWN)            \\\n  X(ERROR_NETWORK_UNREACHABLE, ENETUNREACH)  \\\n  X(ERROR_NOACCESS, EFAULT)                  \\\n  X(ERROR_NONPAGED_SYSTEM_RESOURCES, ENOMEM) \\\n  X(ERROR_NOT_ENOUGH_MEMORY, ENOMEM)         \\\n  X(ERROR_NOT_ENOUGH_QUOTA, ENOMEM)          \\\n  X(ERROR_NOT_FOUND, ENOENT)                 \\\n  X(ERROR_NOT_LOCKED, EACCES)                \\\n  X(ERROR_NOT_READY, EACCES)                 \\\n  X(ERROR_NOT_SAME_DEVICE, EXDEV)            \\\n  X(ERROR_NOT_SUPPORTED, ENOTSUP)            \\\n  X(ERROR_NO_MORE_FILES, ENOENT)             \\\n  X(ERROR_NO_SYSTEM_RESOURCES, ENOMEM)       \\\n  X(ERROR_OPERATION_ABORTED, EINTR)          \\\n  X(ERROR_OUT_OF_PAPER, EACCES)              \\\n  X(ERROR_PAGED_SYSTEM_RESOURCES, ENOMEM)    \\\n  X(ERROR_PAGEFILE_QUOTA, ENOMEM)            \\\n  X(ERROR_PATH_NOT_FOUND, ENOENT)            \\\n  X(ERROR_PIPE_NOT_CONNECTED, EPIPE)         \\\n  X(ERROR_PORT_UNREACHABLE, ECONNRESET)      \\\n  X(ERROR_PROTOCOL_UNREACHABLE, ENETUNREACH) \\\n  X(ERROR_REM_NOT_LIST, ECONNREFUSED)        \\\n  X(ERROR_REQUEST_ABORTED, EINTR)            \\\n  X(ERROR_REQ_NOT_ACCEP, EWOULDBLOCK)        \\\n  X(ERROR_SECTOR_NOT_FOUND, EACCES)          \\\n  X(ERROR_SEM_TIMEOUT, ETIMEDOUT)            \\\n  X(ERROR_SHARING_VIOLATION, EACCES)         \\\n  X(ERROR_TOO_MANY_NAMES, ENOMEM)            \\\n  X(ERROR_TOO_MANY_OPEN_FILES, EMFILE)       \\\n  X(ERROR_UNEXP_NET_ERR, ECONNABORTED)       \\\n  X(ERROR_WAIT_NO_CHILDREN, ECHILD)          \\\n  X(ERROR_WORKING_SET_QUOTA, ENOMEM)         \\\n  X(ERROR_WRITE_PROTECT, EACCES)             \\\n  X(ERROR_WRONG_DISK, EACCES)                \\\n  X(WSAEACCES, EACCES)                       \\\n  X(WSAEADDRINUSE, EADDRINUSE)               \\\n  X(WSAEADDRNOTAVAIL, EADDRNOTAVAIL)         \\\n  X(WSAEAFNOSUPPORT, EAFNOSUPPORT)           \\\n  X(WSAECONNABORTED, ECONNABORTED)           \\\n  X(WSAECONNREFUSED, ECONNREFUSED)           \\\n  X(WSAECONNRESET, ECONNRESET)               \\\n  X(WSAEDISCON, EPIPE)                       \\\n  X(WSAEFAULT, EFAULT)                       \\\n  X(WSAEHOSTDOWN, EHOSTUNREACH)              \\\n  X(WSAEHOSTUNREACH, EHOSTUNREACH)           \\\n  X(WSAEINPROGRESS, EBUSY)                   \\\n  X(WSAEINTR, EINTR)                         \\\n  X(WSAEINVAL, EINVAL)                       \\\n  X(WSAEISCONN, EISCONN)                     \\\n  X(WSAEMSGSIZE, EMSGSIZE)                   \\\n  X(WSAENETDOWN, ENETDOWN)                   \\\n  X(WSAENETRESET, EHOSTUNREACH)              \\\n  X(WSAENETUNREACH, ENETUNREACH)             \\\n  X(WSAENOBUFS, ENOMEM)                      \\\n  X(WSAENOTCONN, ENOTCONN)                   \\\n  X(WSAENOTSOCK, ENOTSOCK)                   \\\n  X(WSAEOPNOTSUPP, EOPNOTSUPP)               \\\n  X(WSAEPROCLIM, ENOMEM)                     \\\n  X(WSAESHUTDOWN, EPIPE)                     \\\n  X(WSAETIMEDOUT, ETIMEDOUT)                 \\\n  X(WSAEWOULDBLOCK, EWOULDBLOCK)             \\\n  X(WSANOTINITIALISED, ENETDOWN)             \\\n  X(WSASYSNOTREADY, ENETDOWN)                \\\n  X(WSAVERNOTSUPPORTED, ENOSYS)\n\nstatic errno_t err__map_win_error_to_errno(DWORD error) {\n  switch (error) {\n#define X(error_sym, errno_sym) \\\n  case error_sym:               \\\n    return errno_sym;\n    ERR__ERRNO_MAPPINGS(X)\n#undef X\n  }\n  return EINVAL;\n}\n\nvoid err_map_win_error(void) {\n  errno = err__map_win_error_to_errno(GetLastError());\n}\n\nvoid err_set_win_error(DWORD error) {\n  SetLastError(error);\n  errno = err__map_win_error_to_errno(error);\n}\n\nint err_check_handle(HANDLE handle) {\n  DWORD flags;\n\n  /* GetHandleInformation() succeeds when passed INVALID_HANDLE_VALUE, so check\n   * for this condition explicitly. */\n  if (handle == INVALID_HANDLE_VALUE)\n    return_set_error(-1, ERROR_INVALID_HANDLE);\n\n  if (!GetHandleInformation(handle, &flags))\n    return_map_error(-1);\n\n  return 0;\n}\n\n#include <stddef.h>\n\n#define array_count(a) (sizeof(a) / (sizeof((a)[0])))\n\n#define container_of(ptr, type, member) \\\n  ((type*) ((uintptr_t) (ptr) - offsetof(type, member)))\n\n#define unused_var(v) ((void) (v))\n\n/* Polyfill `inline` for older versions of msvc (up to Visual Studio 2013) */\n#if defined(_MSC_VER) && _MSC_VER < 1900\n#define inline __inline\n#endif\n\nWEPOLL_INTERNAL int ws_global_init(void);\nWEPOLL_INTERNAL SOCKET ws_get_base_socket(SOCKET socket);\n\nstatic bool init__done = false;\nstatic INIT_ONCE init__once = INIT_ONCE_STATIC_INIT;\n\nstatic BOOL CALLBACK init__once_callback(INIT_ONCE* once,\n                                         void* parameter,\n                                         void** context) {\n  unused_var(once);\n  unused_var(parameter);\n  unused_var(context);\n\n  /* N.b. that initialization order matters here. */\n  if (ws_global_init() < 0 || nt_global_init() < 0 ||\n      reflock_global_init() < 0 || epoll_global_init() < 0)\n    return FALSE;\n\n  init__done = true;\n  return TRUE;\n}\n\nint init(void) {\n  if (!init__done &&\n      !InitOnceExecuteOnce(&init__once, init__once_callback, NULL, NULL))\n    /* `InitOnceExecuteOnce()` itself is infallible, and it doesn't set any\n     * error code when the once-callback returns FALSE. We return -1 here to\n     * indicate that global initialization failed; the failing init function is\n     * resposible for setting `errno` and calling `SetLastError()`. */\n    return -1;\n\n  return 0;\n}\n\n/* Set up a workaround for the following problem:\n *   FARPROC addr = GetProcAddress(...);\n *   MY_FUNC func = (MY_FUNC) addr;          <-- GCC 8 warning/error.\n *   MY_FUNC func = (MY_FUNC) (void*) addr;  <-- MSVC  warning/error.\n * To compile cleanly with either compiler, do casts with this \"bridge\" type:\n *   MY_FUNC func = (MY_FUNC) (nt__fn_ptr_cast_t) addr; */\n#ifdef __GNUC__\ntypedef void* nt__fn_ptr_cast_t;\n#else\ntypedef FARPROC nt__fn_ptr_cast_t;\n#endif\n\n#define X(return_type, attributes, name, parameters) \\\n  WEPOLL_INTERNAL return_type(attributes* name) parameters = NULL;\nNT_NTDLL_IMPORT_LIST(X)\n#undef X\n\nint nt_global_init(void) {\n  HMODULE ntdll;\n  FARPROC fn_ptr;\n\n  ntdll = GetModuleHandleW(L\"ntdll.dll\");\n  if (ntdll == NULL)\n    return -1;\n\n#define X(return_type, attributes, name, parameters) \\\n  fn_ptr = GetProcAddress(ntdll, #name);             \\\n  if (fn_ptr == NULL)                                \\\n    return -1;                                       \\\n  name = (return_type(attributes*) parameters)(nt__fn_ptr_cast_t) fn_ptr;\n  NT_NTDLL_IMPORT_LIST(X)\n#undef X\n\n  return 0;\n}\n\n#include <string.h>\n\ntypedef struct poll_group poll_group_t;\n\ntypedef struct queue_node queue_node_t;\n\nWEPOLL_INTERNAL poll_group_t* poll_group_acquire(port_state_t* port);\nWEPOLL_INTERNAL void poll_group_release(poll_group_t* poll_group);\n\nWEPOLL_INTERNAL void poll_group_delete(poll_group_t* poll_group);\n\nWEPOLL_INTERNAL poll_group_t* poll_group_from_queue_node(\n    queue_node_t* queue_node);\nWEPOLL_INTERNAL HANDLE\n    poll_group_get_afd_device_handle(poll_group_t* poll_group);\n\ntypedef struct queue_node {\n  queue_node_t* prev;\n  queue_node_t* next;\n} queue_node_t;\n\ntypedef struct queue {\n  queue_node_t head;\n} queue_t;\n\nWEPOLL_INTERNAL void queue_init(queue_t* queue);\nWEPOLL_INTERNAL void queue_node_init(queue_node_t* node);\n\nWEPOLL_INTERNAL queue_node_t* queue_first(const queue_t* queue);\nWEPOLL_INTERNAL queue_node_t* queue_last(const queue_t* queue);\n\nWEPOLL_INTERNAL void queue_prepend(queue_t* queue, queue_node_t* node);\nWEPOLL_INTERNAL void queue_append(queue_t* queue, queue_node_t* node);\nWEPOLL_INTERNAL void queue_move_to_start(queue_t* queue, queue_node_t* node);\nWEPOLL_INTERNAL void queue_move_to_end(queue_t* queue, queue_node_t* node);\nWEPOLL_INTERNAL void queue_remove(queue_node_t* node);\n\nWEPOLL_INTERNAL bool queue_is_empty(const queue_t* queue);\nWEPOLL_INTERNAL bool queue_is_enqueued(const queue_node_t* node);\n\n#define POLL_GROUP__MAX_GROUP_SIZE 32\n\ntypedef struct poll_group {\n  port_state_t* port_state;\n  queue_node_t queue_node;\n  HANDLE afd_device_handle;\n  size_t group_size;\n} poll_group_t;\n\nstatic poll_group_t* poll_group__new(port_state_t* port_state) {\n  HANDLE iocp_handle = port_get_iocp_handle(port_state);\n  queue_t* poll_group_queue = port_get_poll_group_queue(port_state);\n\n  poll_group_t* poll_group = malloc(sizeof *poll_group);\n  if (poll_group == NULL)\n    return_set_error(NULL, ERROR_NOT_ENOUGH_MEMORY);\n\n  memset(poll_group, 0, sizeof *poll_group);\n\n  queue_node_init(&poll_group->queue_node);\n  poll_group->port_state = port_state;\n\n  if (afd_create_device_handle(iocp_handle, &poll_group->afd_device_handle) <\n      0) {\n    free(poll_group);\n    return NULL;\n  }\n\n  queue_append(poll_group_queue, &poll_group->queue_node);\n\n  return poll_group;\n}\n\nvoid poll_group_delete(poll_group_t* poll_group) {\n  assert(poll_group->group_size == 0);\n  CloseHandle(poll_group->afd_device_handle);\n  queue_remove(&poll_group->queue_node);\n  free(poll_group);\n}\n\npoll_group_t* poll_group_from_queue_node(queue_node_t* queue_node) {\n  return container_of(queue_node, poll_group_t, queue_node);\n}\n\nHANDLE poll_group_get_afd_device_handle(poll_group_t* poll_group) {\n  return poll_group->afd_device_handle;\n}\n\npoll_group_t* poll_group_acquire(port_state_t* port_state) {\n  queue_t* poll_group_queue = port_get_poll_group_queue(port_state);\n  poll_group_t* poll_group =\n      !queue_is_empty(poll_group_queue)\n          ? container_of(\n                queue_last(poll_group_queue), poll_group_t, queue_node)\n          : NULL;\n\n  if (poll_group == NULL ||\n      poll_group->group_size >= POLL_GROUP__MAX_GROUP_SIZE)\n    poll_group = poll_group__new(port_state);\n  if (poll_group == NULL)\n    return NULL;\n\n  if (++poll_group->group_size == POLL_GROUP__MAX_GROUP_SIZE)\n    queue_move_to_start(poll_group_queue, &poll_group->queue_node);\n\n  return poll_group;\n}\n\nvoid poll_group_release(poll_group_t* poll_group) {\n  port_state_t* port_state = poll_group->port_state;\n  queue_t* poll_group_queue = port_get_poll_group_queue(port_state);\n\n  poll_group->group_size--;\n  assert(poll_group->group_size < POLL_GROUP__MAX_GROUP_SIZE);\n\n  queue_move_to_end(poll_group_queue, &poll_group->queue_node);\n\n  /* Poll groups are currently only freed when the epoll port is closed. */\n}\n\nWEPOLL_INTERNAL sock_state_t* sock_new(port_state_t* port_state,\n                                       SOCKET socket);\nWEPOLL_INTERNAL void sock_delete(port_state_t* port_state,\n                                 sock_state_t* sock_state);\nWEPOLL_INTERNAL void sock_force_delete(port_state_t* port_state,\n                                       sock_state_t* sock_state);\n\nWEPOLL_INTERNAL int sock_set_event(port_state_t* port_state,\n                                   sock_state_t* sock_state,\n                                   const struct epoll_event* ev);\n\nWEPOLL_INTERNAL int sock_update(port_state_t* port_state,\n                                sock_state_t* sock_state);\nWEPOLL_INTERNAL int sock_feed_event(port_state_t* port_state,\n                                    IO_STATUS_BLOCK* io_status_block,\n                                    struct epoll_event* ev);\n\nWEPOLL_INTERNAL sock_state_t* sock_state_from_queue_node(\n    queue_node_t* queue_node);\nWEPOLL_INTERNAL queue_node_t* sock_state_to_queue_node(\n    sock_state_t* sock_state);\nWEPOLL_INTERNAL sock_state_t* sock_state_from_tree_node(\n    tree_node_t* tree_node);\nWEPOLL_INTERNAL tree_node_t* sock_state_to_tree_node(sock_state_t* sock_state);\n\n#define PORT__MAX_ON_STACK_COMPLETIONS 256\n\ntypedef struct port_state {\n  HANDLE iocp_handle;\n  tree_t sock_tree;\n  queue_t sock_update_queue;\n  queue_t sock_deleted_queue;\n  queue_t poll_group_queue;\n  ts_tree_node_t handle_tree_node;\n  CRITICAL_SECTION lock;\n  size_t active_poll_count;\n} port_state_t;\n\nstatic inline port_state_t* port__alloc(void) {\n  port_state_t* port_state = malloc(sizeof *port_state);\n  if (port_state == NULL)\n    return_set_error(NULL, ERROR_NOT_ENOUGH_MEMORY);\n\n  return port_state;\n}\n\nstatic inline void port__free(port_state_t* port) {\n  assert(port != NULL);\n  free(port);\n}\n\nstatic inline HANDLE port__create_iocp(void) {\n  HANDLE iocp_handle =\n      CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);\n  if (iocp_handle == NULL)\n    return_map_error(NULL);\n\n  return iocp_handle;\n}\n\nport_state_t* port_new(HANDLE* iocp_handle_out) {\n  port_state_t* port_state;\n  HANDLE iocp_handle;\n\n  port_state = port__alloc();\n  if (port_state == NULL)\n    goto err1;\n\n  iocp_handle = port__create_iocp();\n  if (iocp_handle == NULL)\n    goto err2;\n\n  memset(port_state, 0, sizeof *port_state);\n\n  port_state->iocp_handle = iocp_handle;\n  tree_init(&port_state->sock_tree);\n  queue_init(&port_state->sock_update_queue);\n  queue_init(&port_state->sock_deleted_queue);\n  queue_init(&port_state->poll_group_queue);\n  ts_tree_node_init(&port_state->handle_tree_node);\n  InitializeCriticalSection(&port_state->lock);\n\n  *iocp_handle_out = iocp_handle;\n  return port_state;\n\nerr2:\n  port__free(port_state);\nerr1:\n  return NULL;\n}\n\nstatic inline int port__close_iocp(port_state_t* port_state) {\n  HANDLE iocp_handle = port_state->iocp_handle;\n  port_state->iocp_handle = NULL;\n\n  if (!CloseHandle(iocp_handle))\n    return_map_error(-1);\n\n  return 0;\n}\n\nint port_close(port_state_t* port_state) {\n  int result;\n\n  EnterCriticalSection(&port_state->lock);\n  result = port__close_iocp(port_state);\n  LeaveCriticalSection(&port_state->lock);\n\n  return result;\n}\n\nint port_delete(port_state_t* port_state) {\n  tree_node_t* tree_node;\n  queue_node_t* queue_node;\n\n  /* At this point the IOCP port should have been closed. */\n  assert(port_state->iocp_handle == NULL);\n\n  while ((tree_node = tree_root(&port_state->sock_tree)) != NULL) {\n    sock_state_t* sock_state = sock_state_from_tree_node(tree_node);\n    sock_force_delete(port_state, sock_state);\n  }\n\n  while ((queue_node = queue_first(&port_state->sock_deleted_queue)) != NULL) {\n    sock_state_t* sock_state = sock_state_from_queue_node(queue_node);\n    sock_force_delete(port_state, sock_state);\n  }\n\n  while ((queue_node = queue_first(&port_state->poll_group_queue)) != NULL) {\n    poll_group_t* poll_group = poll_group_from_queue_node(queue_node);\n    poll_group_delete(poll_group);\n  }\n\n  assert(queue_is_empty(&port_state->sock_update_queue));\n\n  DeleteCriticalSection(&port_state->lock);\n\n  port__free(port_state);\n\n  return 0;\n}\n\nstatic int port__update_events(port_state_t* port_state) {\n  queue_t* sock_update_queue = &port_state->sock_update_queue;\n\n  /* Walk the queue, submitting new poll requests for every socket that needs\n   * it. */\n  while (!queue_is_empty(sock_update_queue)) {\n    queue_node_t* queue_node = queue_first(sock_update_queue);\n    sock_state_t* sock_state = sock_state_from_queue_node(queue_node);\n\n    if (sock_update(port_state, sock_state) < 0)\n      return -1;\n\n    /* sock_update() removes the socket from the update queue. */\n  }\n\n  return 0;\n}\n\nstatic inline void port__update_events_if_polling(port_state_t* port_state) {\n  if (port_state->active_poll_count > 0)\n    port__update_events(port_state);\n}\n\nstatic inline int port__feed_events(port_state_t* port_state,\n                                    struct epoll_event* epoll_events,\n                                    OVERLAPPED_ENTRY* iocp_events,\n                                    DWORD iocp_event_count) {\n  int epoll_event_count = 0;\n  DWORD i;\n\n  for (i = 0; i < iocp_event_count; i++) {\n    IO_STATUS_BLOCK* io_status_block =\n        (IO_STATUS_BLOCK*) iocp_events[i].lpOverlapped;\n    struct epoll_event* ev = &epoll_events[epoll_event_count];\n\n    epoll_event_count += sock_feed_event(port_state, io_status_block, ev);\n  }\n\n  return epoll_event_count;\n}\n\nstatic inline int port__poll(port_state_t* port_state,\n                             struct epoll_event* epoll_events,\n                             OVERLAPPED_ENTRY* iocp_events,\n                             DWORD maxevents,\n                             DWORD timeout) {\n  DWORD completion_count;\n\n  if (port__update_events(port_state) < 0)\n    return -1;\n\n  port_state->active_poll_count++;\n\n  LeaveCriticalSection(&port_state->lock);\n\n  BOOL r = GetQueuedCompletionStatusEx(port_state->iocp_handle,\n                                       iocp_events,\n                                       maxevents,\n                                       &completion_count,\n                                       timeout,\n                                       FALSE);\n\n  EnterCriticalSection(&port_state->lock);\n\n  port_state->active_poll_count--;\n\n  if (!r)\n    return_map_error(-1);\n\n  return port__feed_events(\n      port_state, epoll_events, iocp_events, completion_count);\n}\n\nint port_wait(port_state_t* port_state,\n              struct epoll_event* events,\n              int maxevents,\n              int timeout) {\n  OVERLAPPED_ENTRY stack_iocp_events[PORT__MAX_ON_STACK_COMPLETIONS];\n  OVERLAPPED_ENTRY* iocp_events;\n  uint64_t due = 0;\n  DWORD gqcs_timeout;\n  int result;\n\n  /* Check whether `maxevents` is in range. */\n  if (maxevents <= 0)\n    return_set_error(-1, ERROR_INVALID_PARAMETER);\n\n  /* Decide whether the IOCP completion list can live on the stack, or allocate\n   * memory for it on the heap. */\n  if ((size_t) maxevents <= array_count(stack_iocp_events)) {\n    iocp_events = stack_iocp_events;\n  } else if ((iocp_events =\n                  malloc((size_t) maxevents * sizeof *iocp_events)) == NULL) {\n    iocp_events = stack_iocp_events;\n    maxevents = array_count(stack_iocp_events);\n  }\n\n  /* Compute the timeout for GetQueuedCompletionStatus, and the wait end\n   * time, if the user specified a timeout other than zero or infinite. */\n  if (timeout > 0) {\n    due = GetTickCount64() + (uint64_t) timeout;\n    gqcs_timeout = (DWORD) timeout;\n  } else if (timeout == 0) {\n    gqcs_timeout = 0;\n  } else {\n    gqcs_timeout = INFINITE;\n  }\n\n  EnterCriticalSection(&port_state->lock);\n\n  /* Dequeue completion packets until either at least one interesting event\n   * has been discovered, or the timeout is reached. */\n  for (;;) {\n    uint64_t now;\n\n    result = port__poll(\n        port_state, events, iocp_events, (DWORD) maxevents, gqcs_timeout);\n    if (result < 0 || result > 0)\n      break; /* Result, error, or time-out. */\n\n    if (timeout < 0)\n      continue; /* When timeout is negative, never time out. */\n\n    /* Update time. */\n    now = GetTickCount64();\n\n    /* Do not allow the due time to be in the past. */\n    if (now >= due) {\n      SetLastError(WAIT_TIMEOUT);\n      break;\n    }\n\n    /* Recompute time-out argument for GetQueuedCompletionStatus. */\n    gqcs_timeout = (DWORD)(due - now);\n  }\n\n  port__update_events_if_polling(port_state);\n\n  LeaveCriticalSection(&port_state->lock);\n\n  if (iocp_events != stack_iocp_events)\n    free(iocp_events);\n\n  if (result >= 0)\n    return result;\n  else if (GetLastError() == WAIT_TIMEOUT)\n    return 0;\n  else\n    return -1;\n}\n\nstatic inline int port__ctl_add(port_state_t* port_state,\n                                SOCKET sock,\n                                struct epoll_event* ev) {\n  sock_state_t* sock_state = sock_new(port_state, sock);\n  if (sock_state == NULL)\n    return -1;\n\n  if (sock_set_event(port_state, sock_state, ev) < 0) {\n    sock_delete(port_state, sock_state);\n    return -1;\n  }\n\n  port__update_events_if_polling(port_state);\n\n  return 0;\n}\n\nstatic inline int port__ctl_mod(port_state_t* port_state,\n                                SOCKET sock,\n                                struct epoll_event* ev) {\n  sock_state_t* sock_state = port_find_socket(port_state, sock);\n  if (sock_state == NULL)\n    return -1;\n\n  if (sock_set_event(port_state, sock_state, ev) < 0)\n    return -1;\n\n  port__update_events_if_polling(port_state);\n\n  return 0;\n}\n\nstatic inline int port__ctl_del(port_state_t* port_state, SOCKET sock) {\n  sock_state_t* sock_state = port_find_socket(port_state, sock);\n  if (sock_state == NULL)\n    return -1;\n\n  sock_delete(port_state, sock_state);\n\n  return 0;\n}\n\nstatic inline int port__ctl_op(port_state_t* port_state,\n                               int op,\n                               SOCKET sock,\n                               struct epoll_event* ev) {\n  switch (op) {\n    case EPOLL_CTL_ADD:\n      return port__ctl_add(port_state, sock, ev);\n    case EPOLL_CTL_MOD:\n      return port__ctl_mod(port_state, sock, ev);\n    case EPOLL_CTL_DEL:\n      return port__ctl_del(port_state, sock);\n    default:\n      return_set_error(-1, ERROR_INVALID_PARAMETER);\n  }\n}\n\nint port_ctl(port_state_t* port_state,\n             int op,\n             SOCKET sock,\n             struct epoll_event* ev) {\n  int result;\n\n  EnterCriticalSection(&port_state->lock);\n  result = port__ctl_op(port_state, op, sock, ev);\n  LeaveCriticalSection(&port_state->lock);\n\n  return result;\n}\n\nint port_register_socket(port_state_t* port_state,\n                         sock_state_t* sock_state,\n                         SOCKET socket) {\n  if (tree_add(&port_state->sock_tree,\n               sock_state_to_tree_node(sock_state),\n               socket) < 0)\n    return_set_error(-1, ERROR_ALREADY_EXISTS);\n  return 0;\n}\n\nvoid port_unregister_socket(port_state_t* port_state,\n                            sock_state_t* sock_state) {\n  tree_del(&port_state->sock_tree, sock_state_to_tree_node(sock_state));\n}\n\nsock_state_t* port_find_socket(port_state_t* port_state, SOCKET socket) {\n  tree_node_t* tree_node = tree_find(&port_state->sock_tree, socket);\n  if (tree_node == NULL)\n    return_set_error(NULL, ERROR_NOT_FOUND);\n  return sock_state_from_tree_node(tree_node);\n}\n\nvoid port_request_socket_update(port_state_t* port_state,\n                                sock_state_t* sock_state) {\n  if (queue_is_enqueued(sock_state_to_queue_node(sock_state)))\n    return;\n  queue_append(&port_state->sock_update_queue,\n               sock_state_to_queue_node(sock_state));\n}\n\nvoid port_cancel_socket_update(port_state_t* port_state,\n                               sock_state_t* sock_state) {\n  unused_var(port_state);\n  if (!queue_is_enqueued(sock_state_to_queue_node(sock_state)))\n    return;\n  queue_remove(sock_state_to_queue_node(sock_state));\n}\n\nvoid port_add_deleted_socket(port_state_t* port_state,\n                             sock_state_t* sock_state) {\n  if (queue_is_enqueued(sock_state_to_queue_node(sock_state)))\n    return;\n  queue_append(&port_state->sock_deleted_queue,\n               sock_state_to_queue_node(sock_state));\n}\n\nvoid port_remove_deleted_socket(port_state_t* port_state,\n                                sock_state_t* sock_state) {\n  unused_var(port_state);\n  if (!queue_is_enqueued(sock_state_to_queue_node(sock_state)))\n    return;\n  queue_remove(sock_state_to_queue_node(sock_state));\n}\n\nHANDLE port_get_iocp_handle(port_state_t* port_state) {\n  assert(port_state->iocp_handle != NULL);\n  return port_state->iocp_handle;\n}\n\nqueue_t* port_get_poll_group_queue(port_state_t* port_state) {\n  return &port_state->poll_group_queue;\n}\n\nport_state_t* port_state_from_handle_tree_node(ts_tree_node_t* tree_node) {\n  return container_of(tree_node, port_state_t, handle_tree_node);\n}\n\nts_tree_node_t* port_state_to_handle_tree_node(port_state_t* port_state) {\n  return &port_state->handle_tree_node;\n}\n\nvoid queue_init(queue_t* queue) {\n  queue_node_init(&queue->head);\n}\n\nvoid queue_node_init(queue_node_t* node) {\n  node->prev = node;\n  node->next = node;\n}\n\nstatic inline void queue__detach_node(queue_node_t* node) {\n  node->prev->next = node->next;\n  node->next->prev = node->prev;\n}\n\nqueue_node_t* queue_first(const queue_t* queue) {\n  return !queue_is_empty(queue) ? queue->head.next : NULL;\n}\n\nqueue_node_t* queue_last(const queue_t* queue) {\n  return !queue_is_empty(queue) ? queue->head.prev : NULL;\n}\n\nvoid queue_prepend(queue_t* queue, queue_node_t* node) {\n  node->next = queue->head.next;\n  node->prev = &queue->head;\n  node->next->prev = node;\n  queue->head.next = node;\n}\n\nvoid queue_append(queue_t* queue, queue_node_t* node) {\n  node->next = &queue->head;\n  node->prev = queue->head.prev;\n  node->prev->next = node;\n  queue->head.prev = node;\n}\n\nvoid queue_move_to_start(queue_t* queue, queue_node_t* node) {\n  queue__detach_node(node);\n  queue_prepend(queue, node);\n}\n\nvoid queue_move_to_end(queue_t* queue, queue_node_t* node) {\n  queue__detach_node(node);\n  queue_append(queue, node);\n}\n\nvoid queue_remove(queue_node_t* node) {\n  queue__detach_node(node);\n  queue_node_init(node);\n}\n\nbool queue_is_empty(const queue_t* queue) {\n  return !queue_is_enqueued(&queue->head);\n}\n\nbool queue_is_enqueued(const queue_node_t* node) {\n  return node->prev != node;\n}\n\n#define REFLOCK__REF          ((long) 0x00000001UL)\n#define REFLOCK__REF_MASK     ((long) 0x0fffffffUL)\n#define REFLOCK__DESTROY      ((long) 0x10000000UL)\n#define REFLOCK__DESTROY_MASK ((long) 0xf0000000UL)\n#define REFLOCK__POISON       ((long) 0x300dead0UL)\n\nstatic HANDLE reflock__keyed_event = NULL;\n\nint reflock_global_init(void) {\n  NTSTATUS status = NtCreateKeyedEvent(\n      &reflock__keyed_event, KEYEDEVENT_ALL_ACCESS, NULL, 0);\n  if (status != STATUS_SUCCESS)\n    return_set_error(-1, RtlNtStatusToDosError(status));\n  return 0;\n}\n\nvoid reflock_init(reflock_t* reflock) {\n  reflock->state = 0;\n}\n\nstatic void reflock__signal_event(void* address) {\n  NTSTATUS status =\n      NtReleaseKeyedEvent(reflock__keyed_event, address, FALSE, NULL);\n  if (status != STATUS_SUCCESS)\n    abort();\n}\n\nstatic void reflock__await_event(void* address) {\n  NTSTATUS status =\n      NtWaitForKeyedEvent(reflock__keyed_event, address, FALSE, NULL);\n  if (status != STATUS_SUCCESS)\n    abort();\n}\n\nvoid reflock_ref(reflock_t* reflock) {\n  long state = InterlockedAdd(&reflock->state, REFLOCK__REF);\n\n  /* Verify that the counter didn't overflow and the lock isn't destroyed. */\n  assert((state & REFLOCK__DESTROY_MASK) == 0);\n  unused_var(state);\n}\n\nvoid reflock_unref(reflock_t* reflock) {\n  long state = InterlockedAdd(&reflock->state, -REFLOCK__REF);\n\n  /* Verify that the lock was referenced and not already destroyed. */\n  assert((state & REFLOCK__DESTROY_MASK & ~REFLOCK__DESTROY) == 0);\n\n  if (state == REFLOCK__DESTROY)\n    reflock__signal_event(reflock);\n}\n\nvoid reflock_unref_and_destroy(reflock_t* reflock) {\n  long state =\n      InterlockedAdd(&reflock->state, REFLOCK__DESTROY - REFLOCK__REF);\n  long ref_count = state & REFLOCK__REF_MASK;\n\n  /* Verify that the lock was referenced and not already destroyed. */\n  assert((state & REFLOCK__DESTROY_MASK) == REFLOCK__DESTROY);\n\n  if (ref_count != 0)\n    reflock__await_event(reflock);\n\n  state = InterlockedExchange(&reflock->state, REFLOCK__POISON);\n  assert(state == REFLOCK__DESTROY);\n}\n\n#define SOCK__KNOWN_EPOLL_EVENTS                                       \\\n  (EPOLLIN | EPOLLPRI | EPOLLOUT | EPOLLERR | EPOLLHUP | EPOLLRDNORM | \\\n   EPOLLRDBAND | EPOLLWRNORM | EPOLLWRBAND | EPOLLMSG | EPOLLRDHUP)\n\ntypedef enum sock__poll_status {\n  SOCK__POLL_IDLE = 0,\n  SOCK__POLL_PENDING,\n  SOCK__POLL_CANCELLED\n} sock__poll_status_t;\n\ntypedef struct sock_state {\n  IO_STATUS_BLOCK io_status_block;\n  AFD_POLL_INFO poll_info;\n  queue_node_t queue_node;\n  tree_node_t tree_node;\n  poll_group_t* poll_group;\n  SOCKET base_socket;\n  epoll_data_t user_data;\n  uint32_t user_events;\n  uint32_t pending_events;\n  sock__poll_status_t poll_status;\n  bool delete_pending;\n} sock_state_t;\n\nstatic inline sock_state_t* sock__alloc(void) {\n  sock_state_t* sock_state = malloc(sizeof *sock_state);\n  if (sock_state == NULL)\n    return_set_error(NULL, ERROR_NOT_ENOUGH_MEMORY);\n  return sock_state;\n}\n\nstatic inline void sock__free(sock_state_t* sock_state) {\n  assert(sock_state != NULL);\n  free(sock_state);\n}\n\nstatic inline int sock__cancel_poll(sock_state_t* sock_state) {\n  assert(sock_state->poll_status == SOCK__POLL_PENDING);\n\n  if (afd_cancel_poll(poll_group_get_afd_device_handle(sock_state->poll_group),\n                      &sock_state->io_status_block) < 0)\n    return -1;\n\n  sock_state->poll_status = SOCK__POLL_CANCELLED;\n  sock_state->pending_events = 0;\n  return 0;\n}\n\nsock_state_t* sock_new(port_state_t* port_state, SOCKET socket) {\n  SOCKET base_socket;\n  poll_group_t* poll_group;\n  sock_state_t* sock_state;\n\n  if (socket == 0 || socket == INVALID_SOCKET)\n    return_set_error(NULL, ERROR_INVALID_HANDLE);\n\n  base_socket = ws_get_base_socket(socket);\n  if (base_socket == INVALID_SOCKET)\n    return NULL;\n\n  poll_group = poll_group_acquire(port_state);\n  if (poll_group == NULL)\n    return NULL;\n\n  sock_state = sock__alloc();\n  if (sock_state == NULL)\n    goto err1;\n\n  memset(sock_state, 0, sizeof *sock_state);\n\n  sock_state->base_socket = base_socket;\n  sock_state->poll_group = poll_group;\n\n  tree_node_init(&sock_state->tree_node);\n  queue_node_init(&sock_state->queue_node);\n\n  if (port_register_socket(port_state, sock_state, socket) < 0)\n    goto err2;\n\n  return sock_state;\n\nerr2:\n  sock__free(sock_state);\nerr1:\n  poll_group_release(poll_group);\n\n  return NULL;\n}\n\nstatic int sock__delete(port_state_t* port_state,\n                        sock_state_t* sock_state,\n                        bool force) {\n  if (!sock_state->delete_pending) {\n    if (sock_state->poll_status == SOCK__POLL_PENDING)\n      sock__cancel_poll(sock_state);\n\n    port_cancel_socket_update(port_state, sock_state);\n    port_unregister_socket(port_state, sock_state);\n\n    sock_state->delete_pending = true;\n  }\n\n  /* If the poll request still needs to complete, the sock_state object can't\n   * be free()d yet. `sock_feed_event()` or `port_close()` will take care\n   * of this later. */\n  if (force || sock_state->poll_status == SOCK__POLL_IDLE) {\n    /* Free the sock_state now. */\n    port_remove_deleted_socket(port_state, sock_state);\n    poll_group_release(sock_state->poll_group);\n    sock__free(sock_state);\n  } else {\n    /* Free the socket later. */\n    port_add_deleted_socket(port_state, sock_state);\n  }\n\n  return 0;\n}\n\nvoid sock_delete(port_state_t* port_state, sock_state_t* sock_state) {\n  sock__delete(port_state, sock_state, false);\n}\n\nvoid sock_force_delete(port_state_t* port_state, sock_state_t* sock_state) {\n  sock__delete(port_state, sock_state, true);\n}\n\nint sock_set_event(port_state_t* port_state,\n                   sock_state_t* sock_state,\n                   const struct epoll_event* ev) {\n  /* EPOLLERR and EPOLLHUP are always reported, even when not requested by the\n   * caller. However they are disabled after a event has been reported for a\n   * socket for which the EPOLLONESHOT flag was set. */\n  uint32_t events = ev->events | EPOLLERR | EPOLLHUP;\n\n  sock_state->user_events = events;\n  sock_state->user_data = ev->data;\n\n  if ((events & SOCK__KNOWN_EPOLL_EVENTS & ~sock_state->pending_events) != 0)\n    port_request_socket_update(port_state, sock_state);\n\n  return 0;\n}\n\nstatic inline DWORD sock__epoll_events_to_afd_events(uint32_t epoll_events) {\n  /* Always monitor for AFD_POLL_LOCAL_CLOSE, which is triggered when the\n   * socket is closed with closesocket() or CloseHandle(). */\n  DWORD afd_events = AFD_POLL_LOCAL_CLOSE;\n\n  if (epoll_events & (EPOLLIN | EPOLLRDNORM))\n    afd_events |= AFD_POLL_RECEIVE | AFD_POLL_ACCEPT;\n  if (epoll_events & (EPOLLPRI | EPOLLRDBAND))\n    afd_events |= AFD_POLL_RECEIVE_EXPEDITED;\n  if (epoll_events & (EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND))\n    afd_events |= AFD_POLL_SEND;\n  if (epoll_events & (EPOLLIN | EPOLLRDNORM | EPOLLRDHUP))\n    afd_events |= AFD_POLL_DISCONNECT;\n  if (epoll_events & EPOLLHUP)\n    afd_events |= AFD_POLL_ABORT;\n  if (epoll_events & EPOLLERR)\n    afd_events |= AFD_POLL_CONNECT_FAIL;\n\n  return afd_events;\n}\n\nstatic inline uint32_t sock__afd_events_to_epoll_events(DWORD afd_events) {\n  uint32_t epoll_events = 0;\n\n  if (afd_events & (AFD_POLL_RECEIVE | AFD_POLL_ACCEPT))\n    epoll_events |= EPOLLIN | EPOLLRDNORM;\n  if (afd_events & AFD_POLL_RECEIVE_EXPEDITED)\n    epoll_events |= EPOLLPRI | EPOLLRDBAND;\n  if (afd_events & AFD_POLL_SEND)\n    epoll_events |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;\n  if (afd_events & AFD_POLL_DISCONNECT)\n    epoll_events |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;\n  if (afd_events & AFD_POLL_ABORT)\n    epoll_events |= EPOLLHUP;\n  if (afd_events & AFD_POLL_CONNECT_FAIL)\n    /* Linux reports all these events after connect() has failed. */\n    epoll_events |=\n        EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLRDNORM | EPOLLWRNORM | EPOLLRDHUP;\n\n  return epoll_events;\n}\n\nint sock_update(port_state_t* port_state, sock_state_t* sock_state) {\n  assert(!sock_state->delete_pending);\n\n  if ((sock_state->poll_status == SOCK__POLL_PENDING) &&\n      (sock_state->user_events & SOCK__KNOWN_EPOLL_EVENTS &\n       ~sock_state->pending_events) == 0) {\n    /* All the events the user is interested in are already being monitored by\n     * the pending poll operation. It might spuriously complete because of an\n     * event that we're no longer interested in; when that happens we'll submit\n     * a new poll operation with the updated event mask. */\n\n  } else if (sock_state->poll_status == SOCK__POLL_PENDING) {\n    /* A poll operation is already pending, but it's not monitoring for all the\n     * events that the user is interested in. Therefore, cancel the pending\n     * poll operation; when we receive it's completion package, a new poll\n     * operation will be submitted with the correct event mask. */\n    if (sock__cancel_poll(sock_state) < 0)\n      return -1;\n\n  } else if (sock_state->poll_status == SOCK__POLL_CANCELLED) {\n    /* The poll operation has already been cancelled, we're still waiting for\n     * it to return. For now, there's nothing that needs to be done. */\n\n  } else if (sock_state->poll_status == SOCK__POLL_IDLE) {\n    /* No poll operation is pending; start one. */\n    sock_state->poll_info.Exclusive = FALSE;\n    sock_state->poll_info.NumberOfHandles = 1;\n    sock_state->poll_info.Timeout.QuadPart = INT64_MAX;\n    sock_state->poll_info.Handles[0].Handle = (HANDLE) sock_state->base_socket;\n    sock_state->poll_info.Handles[0].Status = 0;\n    sock_state->poll_info.Handles[0].Events =\n        sock__epoll_events_to_afd_events(sock_state->user_events);\n\n    if (afd_poll(poll_group_get_afd_device_handle(sock_state->poll_group),\n                 &sock_state->poll_info,\n                 &sock_state->io_status_block) < 0) {\n      switch (GetLastError()) {\n        case ERROR_IO_PENDING:\n          /* Overlapped poll operation in progress; this is expected. */\n          break;\n        case ERROR_INVALID_HANDLE:\n          /* Socket closed; it'll be dropped from the epoll set. */\n          return sock__delete(port_state, sock_state, false);\n        default:\n          /* Other errors are propagated to the caller. */\n          return_map_error(-1);\n      }\n    }\n\n    /* The poll request was successfully submitted. */\n    sock_state->poll_status = SOCK__POLL_PENDING;\n    sock_state->pending_events = sock_state->user_events;\n\n  } else {\n    /* Unreachable. */\n    assert(false);\n  }\n\n  port_cancel_socket_update(port_state, sock_state);\n  return 0;\n}\n\nint sock_feed_event(port_state_t* port_state,\n                    IO_STATUS_BLOCK* io_status_block,\n                    struct epoll_event* ev) {\n  sock_state_t* sock_state =\n      container_of(io_status_block, sock_state_t, io_status_block);\n  AFD_POLL_INFO* poll_info = &sock_state->poll_info;\n  uint32_t epoll_events = 0;\n\n  sock_state->poll_status = SOCK__POLL_IDLE;\n  sock_state->pending_events = 0;\n\n  if (sock_state->delete_pending) {\n    /* Socket has been deleted earlier and can now be freed. */\n    return sock__delete(port_state, sock_state, false);\n\n  } else if (io_status_block->Status == STATUS_CANCELLED) {\n    /* The poll request was cancelled by CancelIoEx. */\n\n  } else if (!NT_SUCCESS(io_status_block->Status)) {\n    /* The overlapped request itself failed in an unexpected way. */\n    epoll_events = EPOLLERR;\n\n  } else if (poll_info->NumberOfHandles < 1) {\n    /* This poll operation succeeded but didn't report any socket events. */\n\n  } else if (poll_info->Handles[0].Events & AFD_POLL_LOCAL_CLOSE) {\n    /* The poll operation reported that the socket was closed. */\n    return sock__delete(port_state, sock_state, false);\n\n  } else {\n    /* Events related to our socket were reported. */\n    epoll_events =\n        sock__afd_events_to_epoll_events(poll_info->Handles[0].Events);\n  }\n\n  /* Requeue the socket so a new poll request will be submitted. */\n  port_request_socket_update(port_state, sock_state);\n\n  /* Filter out events that the user didn't ask for. */\n  epoll_events &= sock_state->user_events;\n\n  /* Return if there are no epoll events to report. */\n  if (epoll_events == 0)\n    return 0;\n\n  /* If the the socket has the EPOLLONESHOT flag set, unmonitor all events,\n   * even EPOLLERR and EPOLLHUP. But always keep looking for closed sockets. */\n  if (sock_state->user_events & EPOLLONESHOT)\n    sock_state->user_events = 0;\n\n  ev->data = sock_state->user_data;\n  ev->events = epoll_events;\n  return 1;\n}\n\nsock_state_t* sock_state_from_queue_node(queue_node_t* queue_node) {\n  return container_of(queue_node, sock_state_t, queue_node);\n}\n\nqueue_node_t* sock_state_to_queue_node(sock_state_t* sock_state) {\n  return &sock_state->queue_node;\n}\n\nsock_state_t* sock_state_from_tree_node(tree_node_t* tree_node) {\n  return container_of(tree_node, sock_state_t, tree_node);\n}\n\ntree_node_t* sock_state_to_tree_node(sock_state_t* sock_state) {\n  return &sock_state->tree_node;\n}\n\nvoid ts_tree_init(ts_tree_t* ts_tree) {\n  tree_init(&ts_tree->tree);\n  InitializeSRWLock(&ts_tree->lock);\n}\n\nvoid ts_tree_node_init(ts_tree_node_t* node) {\n  tree_node_init(&node->tree_node);\n  reflock_init(&node->reflock);\n}\n\nint ts_tree_add(ts_tree_t* ts_tree, ts_tree_node_t* node, uintptr_t key) {\n  int r;\n\n  AcquireSRWLockExclusive(&ts_tree->lock);\n  r = tree_add(&ts_tree->tree, &node->tree_node, key);\n  ReleaseSRWLockExclusive(&ts_tree->lock);\n\n  return r;\n}\n\nstatic inline ts_tree_node_t* ts_tree__find_node(ts_tree_t* ts_tree,\n                                                 uintptr_t key) {\n  tree_node_t* tree_node = tree_find(&ts_tree->tree, key);\n  if (tree_node == NULL)\n    return NULL;\n\n  return container_of(tree_node, ts_tree_node_t, tree_node);\n}\n\nts_tree_node_t* ts_tree_del_and_ref(ts_tree_t* ts_tree, uintptr_t key) {\n  ts_tree_node_t* ts_tree_node;\n\n  AcquireSRWLockExclusive(&ts_tree->lock);\n\n  ts_tree_node = ts_tree__find_node(ts_tree, key);\n  if (ts_tree_node != NULL) {\n    tree_del(&ts_tree->tree, &ts_tree_node->tree_node);\n    reflock_ref(&ts_tree_node->reflock);\n  }\n\n  ReleaseSRWLockExclusive(&ts_tree->lock);\n\n  return ts_tree_node;\n}\n\nts_tree_node_t* ts_tree_find_and_ref(ts_tree_t* ts_tree, uintptr_t key) {\n  ts_tree_node_t* ts_tree_node;\n\n  AcquireSRWLockShared(&ts_tree->lock);\n\n  ts_tree_node = ts_tree__find_node(ts_tree, key);\n  if (ts_tree_node != NULL)\n    reflock_ref(&ts_tree_node->reflock);\n\n  ReleaseSRWLockShared(&ts_tree->lock);\n\n  return ts_tree_node;\n}\n\nvoid ts_tree_node_unref(ts_tree_node_t* node) {\n  reflock_unref(&node->reflock);\n}\n\nvoid ts_tree_node_unref_and_destroy(ts_tree_node_t* node) {\n  reflock_unref_and_destroy(&node->reflock);\n}\n\nvoid tree_init(tree_t* tree) {\n  memset(tree, 0, sizeof *tree);\n}\n\nvoid tree_node_init(tree_node_t* node) {\n  memset(node, 0, sizeof *node);\n}\n\n#define TREE__ROTATE(cis, trans)   \\\n  tree_node_t* p = node;           \\\n  tree_node_t* q = node->trans;    \\\n  tree_node_t* parent = p->parent; \\\n                                   \\\n  if (parent) {                    \\\n    if (parent->left == p)         \\\n      parent->left = q;            \\\n    else                           \\\n      parent->right = q;           \\\n  } else {                         \\\n    tree->root = q;                \\\n  }                                \\\n                                   \\\n  q->parent = parent;              \\\n  p->parent = q;                   \\\n  p->trans = q->cis;               \\\n  if (p->trans)                    \\\n    p->trans->parent = p;          \\\n  q->cis = p;\n\nstatic inline void tree__rotate_left(tree_t* tree, tree_node_t* node) {\n  TREE__ROTATE(left, right)\n}\n\nstatic inline void tree__rotate_right(tree_t* tree, tree_node_t* node) {\n  TREE__ROTATE(right, left)\n}\n\n#define TREE__INSERT_OR_DESCEND(side) \\\n  if (parent->side) {                 \\\n    parent = parent->side;            \\\n  } else {                            \\\n    parent->side = node;              \\\n    break;                            \\\n  }\n\n#define TREE__REBALANCE_AFTER_INSERT(cis, trans) \\\n  tree_node_t* grandparent = parent->parent;     \\\n  tree_node_t* uncle = grandparent->trans;       \\\n                                                 \\\n  if (uncle && uncle->red) {                     \\\n    parent->red = uncle->red = false;            \\\n    grandparent->red = true;                     \\\n    node = grandparent;                          \\\n  } else {                                       \\\n    if (node == parent->trans) {                 \\\n      tree__rotate_##cis(tree, parent);          \\\n      node = parent;                             \\\n      parent = node->parent;                     \\\n    }                                            \\\n    parent->red = false;                         \\\n    grandparent->red = true;                     \\\n    tree__rotate_##trans(tree, grandparent);     \\\n  }\n\nint tree_add(tree_t* tree, tree_node_t* node, uintptr_t key) {\n  tree_node_t* parent;\n\n  parent = tree->root;\n  if (parent) {\n    for (;;) {\n      if (key < parent->key) {\n        TREE__INSERT_OR_DESCEND(left)\n      } else if (key > parent->key) {\n        TREE__INSERT_OR_DESCEND(right)\n      } else {\n        return -1;\n      }\n    }\n  } else {\n    tree->root = node;\n  }\n\n  node->key = key;\n  node->left = node->right = NULL;\n  node->parent = parent;\n  node->red = true;\n\n  for (; parent && parent->red; parent = node->parent) {\n    if (parent == parent->parent->left) {\n      TREE__REBALANCE_AFTER_INSERT(left, right)\n    } else {\n      TREE__REBALANCE_AFTER_INSERT(right, left)\n    }\n  }\n  tree->root->red = false;\n\n  return 0;\n}\n\n#define TREE__REBALANCE_AFTER_REMOVE(cis, trans)   \\\n  tree_node_t* sibling = parent->trans;            \\\n                                                   \\\n  if (sibling->red) {                              \\\n    sibling->red = false;                          \\\n    parent->red = true;                            \\\n    tree__rotate_##cis(tree, parent);              \\\n    sibling = parent->trans;                       \\\n  }                                                \\\n  if ((sibling->left && sibling->left->red) ||     \\\n      (sibling->right && sibling->right->red)) {   \\\n    if (!sibling->trans || !sibling->trans->red) { \\\n      sibling->cis->red = false;                   \\\n      sibling->red = true;                         \\\n      tree__rotate_##trans(tree, sibling);         \\\n      sibling = parent->trans;                     \\\n    }                                              \\\n    sibling->red = parent->red;                    \\\n    parent->red = sibling->trans->red = false;     \\\n    tree__rotate_##cis(tree, parent);              \\\n    node = tree->root;                             \\\n    break;                                         \\\n  }                                                \\\n  sibling->red = true;\n\nvoid tree_del(tree_t* tree, tree_node_t* node) {\n  tree_node_t* parent = node->parent;\n  tree_node_t* left = node->left;\n  tree_node_t* right = node->right;\n  tree_node_t* next;\n  bool red;\n\n  if (!left) {\n    next = right;\n  } else if (!right) {\n    next = left;\n  } else {\n    next = right;\n    while (next->left)\n      next = next->left;\n  }\n\n  if (parent) {\n    if (parent->left == node)\n      parent->left = next;\n    else\n      parent->right = next;\n  } else {\n    tree->root = next;\n  }\n\n  if (left && right) {\n    red = next->red;\n    next->red = node->red;\n    next->left = left;\n    left->parent = next;\n    if (next != right) {\n      parent = next->parent;\n      next->parent = node->parent;\n      node = next->right;\n      parent->left = node;\n      next->right = right;\n      right->parent = next;\n    } else {\n      next->parent = parent;\n      parent = next;\n      node = next->right;\n    }\n  } else {\n    red = node->red;\n    node = next;\n  }\n\n  if (node)\n    node->parent = parent;\n  if (red)\n    return;\n  if (node && node->red) {\n    node->red = false;\n    return;\n  }\n\n  do {\n    if (node == tree->root)\n      break;\n    if (node == parent->left) {\n      TREE__REBALANCE_AFTER_REMOVE(left, right)\n    } else {\n      TREE__REBALANCE_AFTER_REMOVE(right, left)\n    }\n    node = parent;\n    parent = parent->parent;\n  } while (!node->red);\n\n  if (node)\n    node->red = false;\n}\n\ntree_node_t* tree_find(const tree_t* tree, uintptr_t key) {\n  tree_node_t* node = tree->root;\n  while (node) {\n    if (key < node->key)\n      node = node->left;\n    else if (key > node->key)\n      node = node->right;\n    else\n      return node;\n  }\n  return NULL;\n}\n\ntree_node_t* tree_root(const tree_t* tree) {\n  return tree->root;\n}\n\n#ifndef SIO_BSP_HANDLE_POLL\n#define SIO_BSP_HANDLE_POLL 0x4800001D\n#endif\n\n#ifndef SIO_BASE_HANDLE\n#define SIO_BASE_HANDLE 0x48000022\n#endif\n\nint ws_global_init(void) {\n  int r;\n  WSADATA wsa_data;\n\n  r = WSAStartup(MAKEWORD(2, 2), &wsa_data);\n  if (r != 0)\n    return_set_error(-1, (DWORD) r);\n\n  return 0;\n}\n\nstatic inline SOCKET ws__ioctl_get_bsp_socket(SOCKET socket, DWORD ioctl) {\n  SOCKET bsp_socket;\n  DWORD bytes;\n\n  if (WSAIoctl(socket,\n               ioctl,\n               NULL,\n               0,\n               &bsp_socket,\n               sizeof bsp_socket,\n               &bytes,\n               NULL,\n               NULL) != SOCKET_ERROR)\n    return bsp_socket;\n  else\n    return INVALID_SOCKET;\n}\n\nSOCKET ws_get_base_socket(SOCKET socket) {\n  SOCKET base_socket;\n  DWORD error;\n\n  for (;;) {\n    base_socket = ws__ioctl_get_bsp_socket(socket, SIO_BASE_HANDLE);\n    if (base_socket != INVALID_SOCKET)\n      return base_socket;\n\n    error = GetLastError();\n    if (error == WSAENOTSOCK)\n      return_set_error(INVALID_SOCKET, error);\n\n    /* Even though Microsoft documentation clearly states that LSPs should\n     * never intercept the `SIO_BASE_HANDLE` ioctl [1], Komodia based LSPs do\n     * so anyway, breaking it, with the apparent intention of preventing LSP\n     * bypass [2]. Fortunately they don't handle `SIO_BSP_HANDLE_POLL`, which\n     * will at least let us obtain the socket associated with the next winsock\n     * protocol chain entry. If this succeeds, loop around and call\n     * `SIO_BASE_HANDLE` again with the returned BSP socket, to make sure that\n     * we unwrap all layers and retrieve the actual base socket.\n     *  [1] https://docs.microsoft.com/en-us/windows/win32/winsock/winsock-ioctls\n     *  [2] https://www.komodia.com/newwiki/index.php?title=Komodia%27s_Redirector_bug_fixes#Version_2.2.2.6\n     */\n    base_socket = ws__ioctl_get_bsp_socket(socket, SIO_BSP_HANDLE_POLL);\n    if (base_socket != INVALID_SOCKET && base_socket != socket)\n      socket = base_socket;\n    else\n      return_set_error(INVALID_SOCKET, error);\n  }\n}\n"
  },
  {
    "path": "3rd/compat-mingw/wepoll.h",
    "content": "/*\n * wepoll - epoll for Windows\n * https://github.com/piscisaureus/wepoll\n *\n * Copyright 2012-2020, Bert Belder <bertbelder@gmail.com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *\n *   * Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef WEPOLL_H_\n#define WEPOLL_H_\n\n#ifndef WEPOLL_EXPORT\n#define WEPOLL_EXPORT\n#endif\n\n#include <stdint.h>\n\nenum EPOLL_EVENTS {\n  EPOLLIN      = (int) (1U <<  0),\n  EPOLLPRI     = (int) (1U <<  1),\n  EPOLLOUT     = (int) (1U <<  2),\n  EPOLLERR     = (int) (1U <<  3),\n  EPOLLHUP     = (int) (1U <<  4),\n  EPOLLRDNORM  = (int) (1U <<  6),\n  EPOLLRDBAND  = (int) (1U <<  7),\n  EPOLLWRNORM  = (int) (1U <<  8),\n  EPOLLWRBAND  = (int) (1U <<  9),\n  EPOLLMSG     = (int) (1U << 10), /* Never reported. */\n  EPOLLRDHUP   = (int) (1U << 13),\n  EPOLLONESHOT = (int) (1U << 31)\n};\n\n#define EPOLLIN      (1U <<  0)\n#define EPOLLPRI     (1U <<  1)\n#define EPOLLOUT     (1U <<  2)\n#define EPOLLERR     (1U <<  3)\n#define EPOLLHUP     (1U <<  4)\n#define EPOLLRDNORM  (1U <<  6)\n#define EPOLLRDBAND  (1U <<  7)\n#define EPOLLWRNORM  (1U <<  8)\n#define EPOLLWRBAND  (1U <<  9)\n#define EPOLLMSG     (1U << 10)\n#define EPOLLRDHUP   (1U << 13)\n#define EPOLLONESHOT (1U << 31)\n\n#define EPOLL_CTL_ADD 1\n#define EPOLL_CTL_MOD 2\n#define EPOLL_CTL_DEL 3\n\ntypedef void* HANDLE;\ntypedef uintptr_t SOCKET;\n\ntypedef union epoll_data {\n  void* ptr;\n  int fd;\n  uint32_t u32;\n  uint64_t u64;\n  SOCKET sock; /* Windows specific */\n  HANDLE hnd;  /* Windows specific */\n} epoll_data_t;\n\nstruct epoll_event {\n  uint32_t events;   /* Epoll events and flags */\n  epoll_data_t data; /* User data variable */\n};\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nWEPOLL_EXPORT HANDLE epoll_create(int size);\nWEPOLL_EXPORT HANDLE epoll_create1(int flags);\n\nWEPOLL_EXPORT int epoll_close(HANDLE ephnd);\n\nWEPOLL_EXPORT int epoll_ctl(HANDLE ephnd,\n                            int op,\n                            SOCKET sock,\n                            struct epoll_event* event);\n\nWEPOLL_EXPORT int epoll_wait(HANDLE ephnd,\n                             struct epoll_event* events,\n                             int maxevents,\n                             int timeout);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* WEPOLL_H_ */\n"
  },
  {
    "path": "3rd/lpeg/HISTORY",
    "content": "HISTORY for LPeg 1.1.0\n\n* Changes from version 1.0.2 to 1.1.0\n  ---------------------------------\n  + accumulator capture\n  + UTF-8 ranges\n  + Larger limit for number of rules in a grammar\n  + Larger limit for number of captures in a match\n  + bug fixes\n  + other small improvements\n\n* Changes from version 1.0.1 to 1.0.2\n  ---------------------------------\n  + some bugs fixed\n\n* Changes from version 0.12 to 1.0.1\n  ---------------------------------\n  + group \"names\" can be any Lua value\n  + some bugs fixed\n  + other small improvements\n\n* Changes from version 0.11 to 0.12\n  ---------------------------------\n  + no \"unsigned short\" limit for pattern sizes\n  + mathtime captures considered nullable\n  + some bugs fixed\n\n* Changes from version 0.10 to 0.11\n  -------------------------------\n  + complete reimplementation of the code generator\n  + new syntax for table captures\n  + new functions in module 're'\n  + other small improvements\n\n* Changes from version 0.9 to 0.10\n  -------------------------------\n  + backtrack stack has configurable size\n  + better error messages\n  + Notation for non-terminals in 're' back to A instead o <A>\n  + experimental look-behind pattern\n  + support for external extensions\n  + works with Lua 5.2\n  + consumes less C stack\n\n  - \"and\" predicates do not keep captures\n\n* Changes from version 0.8 to 0.9\n  -------------------------------\n  + The accumulator capture was replaced by a fold capture;\n    programs that used the old 'lpeg.Ca' will need small changes.\n  + Some support for character classes from old C locales.\n  + A new named-group capture.\n\n* Changes from version 0.7 to 0.8\n  -------------------------------\n  + New \"match-time\" capture.\n  + New \"argument capture\" that allows passing arguments into the pattern.\n  + Better documentation for 're'.\n  + Several small improvements for 're'.\n  + The 're' module has an incompatibility with previous versions:\n    now, any use of a non-terminal must be enclosed in angle brackets\n    (like <B>).\n\n* Changes from version 0.6 to 0.7\n  -------------------------------\n  + Several improvements in module 're':\n    - better documentation;\n    - support for most captures (all but accumulator);\n    - limited repetitions p{n,m}.\n  + Small improvements in efficiency.\n  + Several small bugs corrected (special thanks to Hans Hagen\n    and Taco Hoekwater).\n\n* Changes from version 0.5 to 0.6\n  -------------------------------\n  + Support for non-numeric indices in grammars.\n  + Some bug fixes (thanks to the luatex team).\n  + Some new optimizations; (thanks to Mike Pall).\n  + A new page layout (thanks to Andre Carregal).\n  + Minimal documentation for module 're'.\n\n* Changes from version 0.4 to 0.5\n  -------------------------------\n  + Several optimizations.\n  + lpeg.P now accepts booleans.\n  + Some new examples.\n  + A proper license.\n  + Several small improvements.\n\n* Changes from version 0.3 to 0.4\n  -------------------------------\n  + Static check for loops in repetitions and grammars.\n  + Removed label option in captures.\n  + The implementation of captures uses less memory.\n\n* Changes from version 0.2 to 0.3\n  -------------------------------\n  + User-defined patterns in Lua.\n  + Several new captures.\n\n* Changes from version 0.1 to 0.2\n  -------------------------------\n  + Several small corrections.\n  + Handles embedded zeros like any other character.\n  + Capture \"name\" can be any Lua value.\n  + Unlimited number of captures.\n  + Match gets an optional initial position.\n\n(end of HISTORY)\n"
  },
  {
    "path": "3rd/lpeg/README.md",
    "content": "# LPeg - Parsing Expression Grammars For Lua\n\nFor more information,\nsee [Lpeg](//www.inf.puc-rio.br/~roberto/lpeg/).\n"
  },
  {
    "path": "3rd/lpeg/lpcap.c",
    "content": "\n#include \"lua.h\"\n#include \"lauxlib.h\"\n\n#include \"lpcap.h\"\n#include \"lpprint.h\"\n#include \"lptypes.h\"\n\n\n#define getfromktable(cs,v)\tlua_rawgeti((cs)->L, ktableidx((cs)->ptop), v)\n\n#define pushluaval(cs)\t\tgetfromktable(cs, (cs)->cap->idx)\n\n\n\n#define skipclose(cs,head)  \\\n\tif (isopencap(head)) { assert(isclosecap(cs->cap)); cs->cap++; }\n\n\n/*\n** Return the size of capture 'cap'. If it is an open capture, 'close'\n** must be its corresponding close.\n*/\nstatic Index_t capsize (Capture *cap, Capture *close) {\n  if (isopencap(cap)) {\n    assert(isclosecap(close));\n    return close->index - cap->index;\n  }\n  else\n    return cap->siz - 1;\n}\n\n\nstatic Index_t closesize (CapState *cs, Capture *head) {\n  return capsize(head, cs->cap);\n}\n\n\n/*\n** Put at the cache for Lua values the value indexed by 'v' in ktable\n** of the running pattern (if it is not there yet); returns its index.\n*/\nstatic int updatecache (CapState *cs, int v) {\n  int idx = cs->ptop + 1;  /* stack index of cache for Lua values */\n  if (v != cs->valuecached) {  /* not there? */\n    getfromktable(cs, v);  /* get value from 'ktable' */\n    lua_replace(cs->L, idx);  /* put it at reserved stack position */\n    cs->valuecached = v;  /* keep track of what is there */\n  }\n  return idx;\n}\n\n\nstatic int pushcapture (CapState *cs);\n\n\n/*\n** Goes back in a list of captures looking for an open capture\n** corresponding to a close one.\n*/\nstatic Capture *findopen (Capture *cap) {\n  int n = 0;  /* number of closes waiting an open */\n  for (;;) {\n    cap--;\n    if (isclosecap(cap)) n++;  /* one more open to skip */\n    else if (isopencap(cap))\n      if (n-- == 0) return cap;\n  }\n}\n\n\n/*\n** Go to the next capture at the same level.\n*/\nstatic void nextcap (CapState *cs) {\n  Capture *cap = cs->cap;\n  if (isopencap(cap)) {  /* must look for a close? */\n    int n = 0;  /* number of opens waiting a close */\n    for (;;) {  /* look for corresponding close */\n      cap++;\n      if (isopencap(cap)) n++;\n      else if (isclosecap(cap))\n        if (n-- == 0) break;\n    }\n    cs->cap = cap + 1;  /* + 1 to skip last close */\n  }\n  else {\n    Capture *next;\n    for (next = cap + 1; capinside(cap, next); next++)\n      ;  /* skip captures inside current one */\n    cs->cap = next;\n  }\n}\n\n\n/*\n** Push on the Lua stack all values generated by nested captures inside\n** the current capture. Returns number of values pushed. 'addextra'\n** makes it push the entire match after all captured values. The\n** entire match is pushed also if there are no other nested values,\n** so the function never returns zero.\n*/\nstatic int pushnestedvalues (CapState *cs, int addextra) {\n  Capture *head = cs->cap++;  /* original capture */\n  int n = 0;  /* number of pushed subvalues */\n  /* repeat for all nested patterns */\n  while (capinside(head, cs->cap))\n    n += pushcapture(cs);\n  if (addextra || n == 0) {  /* need extra? */\n    lua_pushlstring(cs->L, cs->s + head->index, closesize(cs, head));\n    n++;\n  }\n  skipclose(cs, head);\n  return n;\n}\n\n\n/*\n** Push only the first value generated by nested captures\n*/\nstatic void pushonenestedvalue (CapState *cs) {\n  int n = pushnestedvalues(cs, 0);\n  if (n > 1)\n    lua_pop(cs->L, n - 1);  /* pop extra values */\n}\n\n\n/*\n** Checks whether group 'grp' is visible to 'ref', that is, 'grp' is\n** not nested inside a full capture that does not contain 'ref'.  (We\n** only need to care for full captures because the search at 'findback'\n** skips open-end blocks; so, if 'grp' is nested in a non-full capture,\n** 'ref' is also inside it.)  To check this, we search backward for the\n** inner full capture enclosing 'grp'.  A full capture cannot contain\n** non-full captures, so a close capture means we cannot be inside a\n** full capture anymore.\n*/\nstatic int capvisible (CapState *cs, Capture *grp, Capture *ref) {\n  Capture *cap = grp;\n  int i = MAXLOP;  /* maximum distance for an 'open' */\n  while (i-- > 0 && cap-- > cs->ocap) {\n    if (isclosecap(cap))\n      return 1;  /* can stop the search */\n    else if (grp->index - cap->index >= UCHAR_MAX)\n      return 1;  /* can stop the search */\n    else if (capinside(cap, grp))  /* is 'grp' inside cap? */\n      return capinside(cap, ref);  /* ok iff cap also contains 'ref' */\n  }\n  return 1;  /* 'grp' is not inside any capture */\n}\n\n\n/*\n** Try to find a named group capture with the name given at the top of\n** the stack; goes backward from 'ref'.\n*/\nstatic Capture *findback (CapState *cs, Capture *ref) {\n  lua_State *L = cs->L;\n  Capture *cap = ref;\n  while (cap-- > cs->ocap) {  /* repeat until end of list */\n    if (isclosecap(cap))\n      cap = findopen(cap);  /* skip nested captures */\n    else if (capinside(cap, ref))\n      continue;  /* enclosing captures are not visible to 'ref' */\n    if (captype(cap) == Cgroup && capvisible(cs, cap, ref)) {\n      getfromktable(cs, cap->idx);  /* get group name */\n      if (lp_equal(L, -2, -1)) {  /* right group? */\n        lua_pop(L, 2);  /* remove reference name and group name */\n        return cap;\n      }\n      else lua_pop(L, 1);  /* remove group name */\n    }\n  }\n  luaL_error(L, \"back reference '%s' not found\", lua_tostring(L, -1));\n  return NULL;  /* to avoid warnings */\n}\n\n\n/*\n** Back-reference capture. Return number of values pushed.\n*/\nstatic int backrefcap (CapState *cs) {\n  int n;\n  Capture *curr = cs->cap;\n  pushluaval(cs);  /* reference name */\n  cs->cap = findback(cs, curr);  /* find corresponding group */\n  n = pushnestedvalues(cs, 0);  /* push group's values */\n  cs->cap = curr + 1;\n  return n;\n}\n\n\n/*\n** Table capture: creates a new table and populates it with nested\n** captures.\n*/\nstatic int tablecap (CapState *cs) {\n  lua_State *L = cs->L;\n  Capture *head = cs->cap++;\n  int n = 0;\n  lua_newtable(L);\n  while (capinside(head, cs->cap)) {\n    if (captype(cs->cap) == Cgroup && cs->cap->idx != 0) {  /* named group? */\n      pushluaval(cs);  /* push group name */\n      pushonenestedvalue(cs);\n      lua_settable(L, -3);\n    }\n    else {  /* not a named group */\n      int i;\n      int k = pushcapture(cs);\n      for (i = k; i > 0; i--)  /* store all values into table */\n        lua_rawseti(L, -(i + 1), n + i);\n      n += k;\n    }\n  }\n  skipclose(cs, head);\n  return 1;  /* number of values pushed (only the table) */\n}\n\n\n/*\n** Table-query capture\n*/\nstatic int querycap (CapState *cs) {\n  int idx = cs->cap->idx;\n  pushonenestedvalue(cs);  /* get nested capture */\n  lua_gettable(cs->L, updatecache(cs, idx));  /* query cap. value at table */\n  if (!lua_isnil(cs->L, -1))\n    return 1;\n  else {  /* no value */\n    lua_pop(cs->L, 1);  /* remove nil */\n    return 0;\n  }\n}\n\n\n/*\n** Fold capture\n*/\nstatic int foldcap (CapState *cs) {\n  int n;\n  lua_State *L = cs->L;\n  Capture *head = cs->cap++;\n  int idx = head->idx;\n  if (isclosecap(cs->cap) ||  /* no nested captures (large subject)? */\n      (n = pushcapture(cs)) == 0)  /* nested captures with no values? */\n    return luaL_error(L, \"no initial value for fold capture\");\n  if (n > 1)\n    lua_pop(L, n - 1);  /* leave only one result for accumulator */\n  while (capinside(head, cs->cap)) {\n    lua_pushvalue(L, updatecache(cs, idx));  /* get folding function */\n    lua_insert(L, -2);  /* put it before accumulator */\n    n = pushcapture(cs);  /* get next capture's values */\n    lua_call(L, n + 1, 1);  /* call folding function */\n  }\n  skipclose(cs, head);\n  return 1;  /* only accumulator left on the stack */\n}\n\n\n/*\n** Function capture\n*/\nstatic int functioncap (CapState *cs) {\n  int n;\n  int top = lua_gettop(cs->L);\n  pushluaval(cs);  /* push function */\n  n = pushnestedvalues(cs, 0);  /* push nested captures */\n  lua_call(cs->L, n, LUA_MULTRET);  /* call function */\n  return lua_gettop(cs->L) - top;  /* return function's results */\n}\n\n\n/*\n** Accumulator capture\n*/\nstatic int accumulatorcap (CapState *cs) {\n  lua_State *L = cs->L;\n  int n;\n  if (lua_gettop(L) < cs->firstcap)\n    luaL_error(L, \"no previous value for accumulator capture\");\n  pushluaval(cs);  /* push function */\n  lua_insert(L, -2);  /* previous value becomes first argument */\n  n = pushnestedvalues(cs, 0);  /* push nested captures */\n  lua_call(L, n + 1, 1);  /* call function */\n  return 0;  /* did not add any extra value */\n}\n\n\n/*\n** Select capture\n*/\nstatic int numcap (CapState *cs) {\n  int idx = cs->cap->idx;  /* value to select */\n  if (idx == 0) {  /* no values? */\n    nextcap(cs);  /* skip entire capture */\n    return 0;  /* no value produced */\n  }\n  else {\n    int n = pushnestedvalues(cs, 0);\n    if (n < idx)  /* invalid index? */\n      return luaL_error(cs->L, \"no capture '%d'\", idx);\n    else {\n      lua_pushvalue(cs->L, -(n - idx + 1));  /* get selected capture */\n      lua_replace(cs->L, -(n + 1));  /* put it in place of 1st capture */\n      lua_pop(cs->L, n - 1);  /* remove other captures */\n      return 1;\n    }\n  }\n}\n\n\n/*\n** Return the stack index of the first runtime capture in the given\n** list of captures (or zero if no runtime captures)\n*/\nint finddyncap (Capture *cap, Capture *last) {\n  for (; cap < last; cap++) {\n    if (cap->kind == Cruntime)\n      return cap->idx;  /* stack position of first capture */\n  }\n  return 0;  /* no dynamic captures in this segment */\n}\n\n\n/*\n** Calls a runtime capture. Returns number of captures \"removed\" by the\n** call, that is, those inside the group capture. Captures to be added\n** are on the Lua stack.\n*/\nint runtimecap (CapState *cs, Capture *close, const char *s, int *rem) {\n  int n, id;\n  lua_State *L = cs->L;\n  int otop = lua_gettop(L);\n  Capture *open = findopen(close);  /* get open group capture */\n  assert(captype(open) == Cgroup);\n  id = finddyncap(open, close);  /* get first dynamic capture argument */\n  close->kind = Cclose;  /* closes the group */\n  close->index = s - cs->s;\n  cs->cap = open; cs->valuecached = 0;  /* prepare capture state */\n  luaL_checkstack(L, 4, \"too many runtime captures\");\n  pushluaval(cs);  /* push function to be called */\n  lua_pushvalue(L, SUBJIDX);  /* push original subject */\n  lua_pushinteger(L, s - cs->s + 1);  /* push current position */\n  n = pushnestedvalues(cs, 0);  /* push nested captures */\n  lua_call(L, n + 2, LUA_MULTRET);  /* call dynamic function */\n  if (id > 0) {  /* are there old dynamic captures to be removed? */\n    int i;\n    for (i = id; i <= otop; i++)\n      lua_remove(L, id);  /* remove old dynamic captures */\n    *rem = otop - id + 1;  /* total number of dynamic captures removed */\n  }\n  else\n    *rem = 0;  /* no dynamic captures removed */\n  return close - open - 1;  /* number of captures to be removed */\n}\n\n\n/*\n** Auxiliary structure for substitution and string captures: keep\n** information about nested captures for future use, avoiding to push\n** string results into Lua\n*/\ntypedef struct StrAux {\n  int isstring;  /* whether capture is a string */\n  union {\n    Capture *cp;  /* if not a string, respective capture */\n    struct {  /* if it is a string... */\n      Index_t idx;  /* starts here */\n      Index_t siz;  /* with this size */\n    } s;\n  } u;\n} StrAux;\n\n#define MAXSTRCAPS\t10\n\n/*\n** Collect values from current capture into array 'cps'. Current\n** capture must be Cstring (first call) or Csimple (recursive calls).\n** (In first call, fills %0 with whole match for Cstring.)\n** Returns number of elements in the array that were filled.\n*/\nstatic int getstrcaps (CapState *cs, StrAux *cps, int n) {\n  int k = n++;\n  Capture *head = cs->cap++;\n  cps[k].isstring = 1;  /* get string value */\n  cps[k].u.s.idx = head->index;  /* starts here */\n  while (capinside(head, cs->cap)) {\n    if (n >= MAXSTRCAPS)  /* too many captures? */\n      nextcap(cs);  /* skip extra captures (will not need them) */\n    else if (captype(cs->cap) == Csimple)  /* string? */\n      n = getstrcaps(cs, cps, n);  /* put info. into array */\n    else {\n      cps[n].isstring = 0;  /* not a string */\n      cps[n].u.cp = cs->cap;  /* keep original capture */\n      nextcap(cs);\n      n++;\n    }\n  }\n  cps[k].u.s.siz = closesize(cs, head);\n  skipclose(cs, head);\n  return n;\n}\n\n\n/*\n** add next capture value (which should be a string) to buffer 'b'\n*/\nstatic int addonestring (luaL_Buffer *b, CapState *cs, const char *what);\n\n\n/*\n** String capture: add result to buffer 'b' (instead of pushing\n** it into the stack)\n*/\nstatic void stringcap (luaL_Buffer *b, CapState *cs) {\n  StrAux cps[MAXSTRCAPS];\n  int n;\n  size_t len, i;\n  const char *fmt;  /* format string */\n  fmt = lua_tolstring(cs->L, updatecache(cs, cs->cap->idx), &len);\n  n = getstrcaps(cs, cps, 0) - 1;  /* collect nested captures */\n  for (i = 0; i < len; i++) {  /* traverse format string */\n    if (fmt[i] != '%')  /* not an escape? */\n      luaL_addchar(b, fmt[i]);  /* add it to buffer */\n    else if (fmt[++i] < '0' || fmt[i] > '9')  /* not followed by a digit? */\n      luaL_addchar(b, fmt[i]);  /* add to buffer */\n    else {\n      int l = fmt[i] - '0';  /* capture index */\n      if (l > n)\n        luaL_error(cs->L, \"invalid capture index (%d)\", l);\n      else if (cps[l].isstring)\n        luaL_addlstring(b, cs->s + cps[l].u.s.idx, cps[l].u.s.siz);\n      else {\n        Capture *curr = cs->cap;\n        cs->cap = cps[l].u.cp;  /* go back to evaluate that nested capture */\n        if (!addonestring(b, cs, \"capture\"))\n          luaL_error(cs->L, \"no values in capture index %d\", l);\n        cs->cap = curr;  /* continue from where it stopped */\n      }\n    }\n  }\n}\n\n\n/*\n** Substitution capture: add result to buffer 'b'\n*/\nstatic void substcap (luaL_Buffer *b, CapState *cs) {\n  const char *curr = cs->s + cs->cap->index;\n  Capture *head = cs->cap++;\n  while (capinside(head, cs->cap)) {\n    Capture *cap = cs->cap;\n    const char *caps = cs->s + cap->index;\n    luaL_addlstring(b, curr, caps - curr);  /* add text up to capture */\n    if (addonestring(b, cs, \"replacement\"))\n      curr = caps + capsize(cap, cs->cap - 1);  /* continue after match */\n    else  /* no capture value */\n      curr = caps;  /* keep original text in final result */\n  }\n  /* add last piece of text */\n  luaL_addlstring(b, curr, cs->s + head->index + closesize(cs, head) - curr);\n  skipclose(cs, head);\n}\n\n\n/*\n** Evaluates a capture and adds its first value to buffer 'b'; returns\n** whether there was a value\n*/\nstatic int addonestring (luaL_Buffer *b, CapState *cs, const char *what) {\n  switch (captype(cs->cap)) {\n    case Cstring:\n      stringcap(b, cs);  /* add capture directly to buffer */\n      return 1;\n    case Csubst:\n      substcap(b, cs);  /* add capture directly to buffer */\n      return 1;\n    case Cacc:  /* accumulator capture? */\n      return luaL_error(cs->L, \"invalid context for an accumulator capture\");\n    default: {\n      lua_State *L = cs->L;\n      int n = pushcapture(cs);\n      if (n > 0) {\n        if (n > 1) lua_pop(L, n - 1);  /* only one result */\n        if (!lua_isstring(L, -1))\n          return luaL_error(L, \"invalid %s value (a %s)\",\n                               what, luaL_typename(L, -1));\n        luaL_addvalue(b);\n      }\n      return n;\n    }\n  }\n}\n\n\n#if !defined(MAXRECLEVEL)\n#define MAXRECLEVEL\t200\n#endif\n\n\n/*\n** Push all values of the current capture into the stack; returns\n** number of values pushed\n*/\nstatic int pushcapture (CapState *cs) {\n  lua_State *L = cs->L;\n  int res;\n  luaL_checkstack(L, 4, \"too many captures\");\n  if (cs->reclevel++ > MAXRECLEVEL)\n    return luaL_error(L, \"subcapture nesting too deep\");\n  switch (captype(cs->cap)) {\n    case Cposition: {\n      lua_pushinteger(L, cs->cap->index + 1);\n      cs->cap++;\n      res = 1;\n      break;\n    }\n    case Cconst: {\n      pushluaval(cs);\n      cs->cap++;\n      res = 1;\n      break;\n    }\n    case Carg: {\n      int arg = (cs->cap++)->idx;\n      if (arg + FIXEDARGS > cs->ptop)\n        return luaL_error(L, \"reference to absent extra argument #%d\", arg);\n      lua_pushvalue(L, arg + FIXEDARGS);\n      res = 1;\n      break;\n    }\n    case Csimple: {\n      int k = pushnestedvalues(cs, 1);\n      lua_insert(L, -k);  /* make whole match be first result */\n      res = k;\n      break;\n    }\n    case Cruntime: {\n      lua_pushvalue(L, (cs->cap++)->idx);  /* value is in the stack */\n      res = 1;\n      break;\n    }\n    case Cstring: {\n      luaL_Buffer b;\n      luaL_buffinit(L, &b);\n      stringcap(&b, cs);\n      luaL_pushresult(&b);\n      res = 1;\n      break;\n    }\n    case Csubst: {\n      luaL_Buffer b;\n      luaL_buffinit(L, &b);\n      substcap(&b, cs);\n      luaL_pushresult(&b);\n      res = 1;\n      break;\n    }\n    case Cgroup: {\n      if (cs->cap->idx == 0)  /* anonymous group? */\n        res = pushnestedvalues(cs, 0);  /* add all nested values */\n      else {  /* named group: add no values */\n        nextcap(cs);  /* skip capture */\n        res = 0;\n      }\n      break;\n    }\n    case Cbackref: res = backrefcap(cs); break;\n    case Ctable: res = tablecap(cs); break;\n    case Cfunction: res = functioncap(cs); break;\n    case Cacc: res = accumulatorcap(cs); break;\n    case Cnum: res = numcap(cs); break;\n    case Cquery: res = querycap(cs); break;\n    case Cfold: res = foldcap(cs); break;\n    default: assert(0); res = 0;\n  }\n  cs->reclevel--;\n  return res;\n}\n\n\n/*\n** Prepare a CapState structure and traverse the entire list of\n** captures in the stack pushing its results. 's' is the subject\n** string, 'r' is the final position of the match, and 'ptop'\n** the index in the stack where some useful values were pushed.\n** Returns the number of results pushed. (If the list produces no\n** results, push the final position of the match.)\n*/\nint getcaptures (lua_State *L, const char *s, const char *r, int ptop) {\n  Capture *capture = (Capture *)lua_touserdata(L, caplistidx(ptop));\n  int n = 0;\n  /* printcaplist(capture); */\n  if (!isclosecap(capture)) {  /* is there any capture? */\n    CapState cs;\n    cs.ocap = cs.cap = capture; cs.L = L; cs.reclevel = 0;\n    cs.s = s; cs.valuecached = 0; cs.ptop = ptop;\n    cs.firstcap = lua_gettop(L) + 1;  /* where first value (if any) will go */\n    do {  /* collect their values */\n      n += pushcapture(&cs);\n    } while (!isclosecap(cs.cap));\n    assert(lua_gettop(L) - cs.firstcap == n - 1);\n  }\n  if (n == 0) {  /* no capture values? */\n    lua_pushinteger(L, r - s + 1);  /* return only end position */\n    n = 1;\n  }\n  return n;\n}\n\n\n"
  },
  {
    "path": "3rd/lpeg/lpcap.h",
    "content": "\n#if !defined(lpcap_h)\n#define lpcap_h\n\n\n#include \"lptypes.h\"\n\n\n/* kinds of captures */\ntypedef enum CapKind {\n  Cclose,  /* not used in trees */\n  Cposition,\n  Cconst,  /* ktable[key] is Lua constant */\n  Cbackref,  /* ktable[key] is \"name\" of group to get capture */\n  Carg,  /* 'key' is arg's number */\n  Csimple,  /* next node is pattern */\n  Ctable,  /* next node is pattern */\n  Cfunction,  /* ktable[key] is function; next node is pattern */\n  Cacc,  /* ktable[key] is function; next node is pattern */\n  Cquery,  /* ktable[key] is table; next node is pattern */\n  Cstring,  /* ktable[key] is string; next node is pattern */\n  Cnum,  /* numbered capture; 'key' is number of value to return */\n  Csubst,  /* substitution capture; next node is pattern */\n  Cfold,  /* ktable[key] is function; next node is pattern */\n  Cruntime,  /* not used in trees (is uses another type for tree) */\n  Cgroup  /* ktable[key] is group's \"name\" */\n} CapKind;\n\n\n/*\n** An unsigned integer large enough to index any subject entirely.\n** It can be size_t, but that will double the size of the array\n** of captures in a 64-bit machine.\n*/\n#if !defined(Index_t)\ntypedef uint Index_t;\n#endif\n\n#define MAXINDT\t\t(~(Index_t)0)\n\n\ntypedef struct Capture {\n  Index_t index;  /* subject position */\n  unsigned short idx;  /* extra info (group name, arg index, etc.) */\n  byte kind;  /* kind of capture */\n  byte siz;  /* size of full capture + 1 (0 = not a full capture) */\n} Capture;\n\n\ntypedef struct CapState {\n  Capture *cap;  /* current capture */\n  Capture *ocap;  /* (original) capture list */\n  lua_State *L;\n  int ptop;  /* stack index of last argument to 'match' */\n  int firstcap;  /* stack index of first capture pushed in the stack */\n  const char *s;  /* original string */\n  int valuecached;  /* value stored in cache slot */\n  int reclevel;  /* recursion level */\n} CapState;\n\n\n#define captype(cap)    ((cap)->kind)\n\n#define isclosecap(cap) (captype(cap) == Cclose)\n#define isopencap(cap)  ((cap)->siz == 0)\n\n/* true if c2 is (any number of levels) inside c1 */\n#define capinside(c1,c2)  \\\n\t(isopencap(c1) ? !isclosecap(c2) \\\n                       : (c2)->index < (c1)->index + (c1)->siz - 1)\n\n\n/**\n** Maximum number of captures to visit when looking for an 'open'.\n*/\n#define MAXLOP\t\t20\n\n\n\nint runtimecap (CapState *cs, Capture *close, const char *s, int *rem);\nint getcaptures (lua_State *L, const char *s, const char *r, int ptop);\nint finddyncap (Capture *cap, Capture *last);\n\n#endif\n\n\n"
  },
  {
    "path": "3rd/lpeg/lpcode.c",
    "content": "\n#include <limits.h>\n\n\n#include \"lua.h\"\n#include \"lauxlib.h\"\n\n#include \"lptypes.h\"\n#include \"lpcode.h\"\n#include \"lpcset.h\"\n\n\n/* signals a \"no-instruction */\n#define NOINST\t\t-1\n\n\n\nstatic const Charset fullset_ =\n  {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};\n\nstatic const Charset *fullset = &fullset_;\n\n\n/*\n** {======================================================\n** Analysis and some optimizations\n** =======================================================\n*/\n\n\n/*\n** A few basic operations on Charsets\n*/\nstatic void cs_complement (Charset *cs) {\n  loopset(i, cs->cs[i] = ~cs->cs[i]);\n}\n\nstatic int cs_disjoint (const Charset *cs1, const Charset *cs2) {\n  loopset(i, if ((cs1->cs[i] & cs2->cs[i]) != 0) return 0;)\n  return 1;\n}\n\n\n/*\n** Visit a TCall node taking care to stop recursion. If node not yet\n** visited, return 'f(sib2(tree))', otherwise return 'def' (default\n** value)\n*/\nstatic int callrecursive (TTree *tree, int f (TTree *t), int def) {\n  int key = tree->key;\n  assert(tree->tag == TCall);\n  assert(sib2(tree)->tag == TRule);\n  if (key == 0)  /* node already visited? */\n    return def;  /* return default value */\n  else {  /* first visit */\n    int result;\n    tree->key = 0;  /* mark call as already visited */\n    result = f(sib2(tree));  /* go to called rule */\n    tree->key = key;  /* restore tree */\n    return result;\n  }\n}\n\n\n/*\n** Check whether a pattern tree has captures\n*/\nint hascaptures (TTree *tree) {\n tailcall:\n  switch (tree->tag) {\n    case TCapture: case TRunTime:\n      return 1;\n    case TCall:\n      return callrecursive(tree, hascaptures, 0);\n    case TRule:  /* do not follow siblings */\n      tree = sib1(tree); goto tailcall;\n    case TOpenCall: assert(0);\n    default: {\n      switch (numsiblings[tree->tag]) {\n        case 1:  /* return hascaptures(sib1(tree)); */\n          tree = sib1(tree); goto tailcall;\n        case 2:\n          if (hascaptures(sib1(tree)))\n            return 1;\n          /* else return hascaptures(sib2(tree)); */\n          tree = sib2(tree); goto tailcall;\n        default: assert(numsiblings[tree->tag] == 0); return 0;\n      }\n    }\n  }\n}\n\n\n/*\n** Checks how a pattern behaves regarding the empty string,\n** in one of two different ways:\n** A pattern is *nullable* if it can match without consuming any character;\n** A pattern is *nofail* if it never fails for any string\n** (including the empty string).\n** The difference is only for predicates and run-time captures;\n** for other patterns, the two properties are equivalent.\n** (With predicates, &'a' is nullable but not nofail. Of course,\n** nofail => nullable.)\n** These functions are all convervative in the following way:\n**    p is nullable => nullable(p)\n**    nofail(p) => p cannot fail\n** The function assumes that TOpenCall is not nullable;\n** this will be checked again when the grammar is fixed.\n** Run-time captures can do whatever they want, so the result\n** is conservative.\n*/\nint checkaux (TTree *tree, int pred) {\n tailcall:\n  switch (tree->tag) {\n    case TChar: case TSet: case TAny: case TUTFR:\n    case TFalse: case TOpenCall:\n      return 0;  /* not nullable */\n    case TRep: case TTrue:\n      return 1;  /* no fail */\n    case TNot: case TBehind:  /* can match empty, but can fail */\n      if (pred == PEnofail) return 0;\n      else return 1;  /* PEnullable */\n    case TAnd:  /* can match empty; fail iff body does */\n      if (pred == PEnullable) return 1;\n      /* else return checkaux(sib1(tree), pred); */\n      tree = sib1(tree); goto tailcall;\n    case TRunTime:  /* can fail; match empty iff body does */\n      if (pred == PEnofail) return 0;\n      /* else return checkaux(sib1(tree), pred); */\n      tree = sib1(tree); goto tailcall;\n    case TSeq:\n      if (!checkaux(sib1(tree), pred)) return 0;\n      /* else return checkaux(sib2(tree), pred); */\n      tree = sib2(tree); goto tailcall;\n    case TChoice:\n      if (checkaux(sib2(tree), pred)) return 1;\n      /* else return checkaux(sib1(tree), pred); */\n      tree = sib1(tree); goto tailcall;\n    case TCapture: case TGrammar: case TRule: case TXInfo:\n      /* return checkaux(sib1(tree), pred); */\n      tree = sib1(tree); goto tailcall;\n    case TCall:  /* return checkaux(sib2(tree), pred); */\n      tree = sib2(tree); goto tailcall;\n    default: assert(0); return 0;\n  }\n}\n\n\n/*\n** number of characters to match a pattern (or -1 if variable)\n*/\nint fixedlen (TTree *tree) {\n  int len = 0;  /* to accumulate in tail calls */\n tailcall:\n  switch (tree->tag) {\n    case TChar: case TSet: case TAny:\n      return len + 1;\n    case TUTFR:\n      return (tree->cap == sib1(tree)->cap) ? len + tree->cap : -1;\n    case TFalse: case TTrue: case TNot: case TAnd: case TBehind:\n      return len;\n    case TRep: case TRunTime: case TOpenCall:\n      return -1;\n    case TCapture: case TRule: case TGrammar: case TXInfo:\n      /* return fixedlen(sib1(tree)); */\n      tree = sib1(tree); goto tailcall;\n    case TCall: {\n      int n1 = callrecursive(tree, fixedlen, -1);\n      if (n1 < 0)\n        return -1;\n      else\n        return len + n1;\n    }\n    case TSeq: {\n      int n1 = fixedlen(sib1(tree));\n      if (n1 < 0)\n        return -1;\n      /* else return fixedlen(sib2(tree)) + len; */\n      len += n1; tree = sib2(tree); goto tailcall;\n    }\n    case TChoice: {\n      int n1 = fixedlen(sib1(tree));\n      int n2 = fixedlen(sib2(tree));\n      if (n1 != n2 || n1 < 0)\n        return -1;\n      else\n        return len + n1;\n    }\n    default: assert(0); return 0;\n  };\n}\n\n\n/*\n** Computes the 'first set' of a pattern.\n** The result is a conservative aproximation:\n**   match p ax -> x (for some x) ==> a belongs to first(p)\n** or\n**   a not in first(p) ==> match p ax -> fail (for all x)\n**\n** The set 'follow' is the first set of what follows the\n** pattern (full set if nothing follows it).\n**\n** The function returns 0 when this resulting set can be used for\n** test instructions that avoid the pattern altogether.\n** A non-zero return can happen for two reasons:\n** 1) match p '' -> ''            ==> return has bit 1 set\n** (tests cannot be used because they would always fail for an empty input);\n** 2) there is a match-time capture ==> return has bit 2 set\n** (optimizations should not bypass match-time captures).\n*/\nstatic int getfirst (TTree *tree, const Charset *follow, Charset *firstset) {\n tailcall:\n  switch (tree->tag) {\n    case TChar: case TSet: case TAny: case TFalse: {\n      tocharset(tree, firstset);\n      return 0;\n    }\n    case TUTFR: {\n      int c;\n      clearset(firstset->cs);  /* erase all chars */\n      for (c = tree->key; c <= sib1(tree)->key; c++)\n        setchar(firstset->cs, c);\n      return 0;\n    }\n    case TTrue: {\n      loopset(i, firstset->cs[i] = follow->cs[i]);\n      return 1;  /* accepts the empty string */\n    }\n    case TChoice: {\n      Charset csaux;\n      int e1 = getfirst(sib1(tree), follow, firstset);\n      int e2 = getfirst(sib2(tree), follow, &csaux);\n      loopset(i, firstset->cs[i] |= csaux.cs[i]);\n      return e1 | e2;\n    }\n    case TSeq: {\n      if (!nullable(sib1(tree))) {\n        /* when p1 is not nullable, p2 has nothing to contribute;\n           return getfirst(sib1(tree), fullset, firstset); */\n        tree = sib1(tree); follow = fullset; goto tailcall;\n      }\n      else {  /* FIRST(p1 p2, fl) = FIRST(p1, FIRST(p2, fl)) */\n        Charset csaux;\n        int e2 = getfirst(sib2(tree), follow, &csaux);\n        int e1 = getfirst(sib1(tree), &csaux, firstset);\n        if (e1 == 0) return 0;  /* 'e1' ensures that first can be used */\n        else if ((e1 | e2) & 2)  /* one of the children has a matchtime? */\n          return 2;  /* pattern has a matchtime capture */\n        else return e2;  /* else depends on 'e2' */\n      }\n    }\n    case TRep: {\n      getfirst(sib1(tree), follow, firstset);\n      loopset(i, firstset->cs[i] |= follow->cs[i]);\n      return 1;  /* accept the empty string */\n    }\n    case TCapture: case TGrammar: case TRule: case TXInfo: {\n      /* return getfirst(sib1(tree), follow, firstset); */\n      tree = sib1(tree); goto tailcall;\n    }\n    case TRunTime: {  /* function invalidates any follow info. */\n      int e = getfirst(sib1(tree), fullset, firstset);\n      if (e) return 2;  /* function is not \"protected\"? */\n      else return 0;  /* pattern inside capture ensures first can be used */\n    }\n    case TCall: {\n      /* return getfirst(sib2(tree), follow, firstset); */\n      tree = sib2(tree); goto tailcall;\n    }\n    case TAnd: {\n      int e = getfirst(sib1(tree), follow, firstset);\n      loopset(i, firstset->cs[i] &= follow->cs[i]);\n      return e;\n    }\n    case TNot: {\n      if (tocharset(sib1(tree), firstset)) {\n        cs_complement(firstset);\n        return 1;\n      }  /* else */\n    }    /* FALLTHROUGH */\n    case TBehind: {  /* instruction gives no new information */\n      /* call 'getfirst' only to check for math-time captures */\n      int e = getfirst(sib1(tree), follow, firstset);\n      loopset(i, firstset->cs[i] = follow->cs[i]);  /* uses follow */\n      return e | 1;  /* always can accept the empty string */\n    }\n    default: assert(0); return 0;\n  }\n}\n\n\n/*\n** If 'headfail(tree)' true, then 'tree' can fail only depending on the\n** next character of the subject.\n*/\nstatic int headfail (TTree *tree) {\n tailcall:\n  switch (tree->tag) {\n    case TChar: case TSet: case TAny: case TFalse:\n      return 1;\n    case TTrue: case TRep: case TRunTime: case TNot:\n    case TBehind: case TUTFR:\n      return 0;\n    case TCapture: case TGrammar: case TRule: case TXInfo: case TAnd:\n      tree = sib1(tree); goto tailcall;  /* return headfail(sib1(tree)); */\n    case TCall:\n      tree = sib2(tree); goto tailcall;  /* return headfail(sib2(tree)); */\n    case TSeq:\n      if (!nofail(sib2(tree))) return 0;\n      /* else return headfail(sib1(tree)); */\n      tree = sib1(tree); goto tailcall;\n    case TChoice:\n      if (!headfail(sib1(tree))) return 0;\n      /* else return headfail(sib2(tree)); */\n      tree = sib2(tree); goto tailcall;\n    default: assert(0); return 0;\n  }\n}\n\n\n/*\n** Check whether the code generation for the given tree can benefit\n** from a follow set (to avoid computing the follow set when it is\n** not needed)\n*/\nstatic int needfollow (TTree *tree) {\n tailcall:\n  switch (tree->tag) {\n    case TChar: case TSet: case TAny: case TUTFR:\n    case TFalse: case TTrue: case TAnd: case TNot:\n    case TRunTime: case TGrammar: case TCall: case TBehind:\n      return 0;\n    case TChoice: case TRep:\n      return 1;\n    case TCapture:\n      tree = sib1(tree); goto tailcall;\n    case TSeq:\n      tree = sib2(tree); goto tailcall;\n    default: assert(0); return 0;\n  }\n}\n\n/* }====================================================== */\n\n\n\n/*\n** {======================================================\n** Code generation\n** =======================================================\n*/\n\n\n/*\n** size of an instruction\n*/\nint sizei (const Instruction *i) {\n  switch((Opcode)i->i.code) {\n    case ISet: case ISpan: return 1 + i->i.aux2.set.size;\n    case ITestSet: return 2 + i->i.aux2.set.size;\n    case ITestChar: case ITestAny: case IChoice: case IJmp: case ICall:\n    case IOpenCall: case ICommit: case IPartialCommit: case IBackCommit:\n    case IUTFR:\n      return 2;\n    default: return 1;\n  }\n}\n\n\n/*\n** state for the compiler\n*/\ntypedef struct CompileState {\n  Pattern *p;  /* pattern being compiled */\n  int ncode;  /* next position in p->code to be filled */\n  lua_State *L;\n} CompileState;\n\n\n/*\n** code generation is recursive; 'opt' indicates that the code is being\n** generated as the last thing inside an optional pattern (so, if that\n** code is optional too, it can reuse the 'IChoice' already in place for\n** the outer pattern). 'tt' points to a previous test protecting this\n** code (or NOINST). 'fl' is the follow set of the pattern.\n*/\nstatic void codegen (CompileState *compst, TTree *tree, int opt, int tt,\n                     const Charset *fl);\n\n\nstatic void finishrelcode (lua_State *L, Pattern *p, Instruction *block,\n                                         int size) {\n  if (block == NULL)\n    luaL_error(L, \"not enough memory\");\n  block->codesize = size;\n  p->code = (Instruction *)block + 1;\n}\n\n\n/*\n** Initialize array 'p->code'\n*/\nstatic void newcode (lua_State *L, Pattern *p, int size) {\n  void *ud;\n  Instruction *block;\n  lua_Alloc f = lua_getallocf(L, &ud);\n  size++;  /* slot for 'codesize' */\n  block = (Instruction*) f(ud, NULL, 0, size * sizeof(Instruction));\n  finishrelcode(L, p, block, size);\n}\n\n\nvoid freecode (lua_State *L, Pattern *p) {\n  if (p->code != NULL) {\n    void *ud;\n    lua_Alloc f = lua_getallocf(L, &ud);\n    uint osize = p->code[-1].codesize;\n    f(ud, p->code - 1, osize * sizeof(Instruction), 0);  /* free block */\n  }\n}\n\n\n/*\n** Assume that 'nsize' is not zero and that 'p->code' already exists.\n*/\nstatic void realloccode (lua_State *L, Pattern *p, int nsize) {\n  void *ud;\n  lua_Alloc f = lua_getallocf(L, &ud);\n  Instruction *block = p->code - 1;\n  uint osize = block->codesize;\n  nsize++;  /* add the 'codesize' slot to size */\n  block = (Instruction*) f(ud, block, osize * sizeof(Instruction),\n                                      nsize * sizeof(Instruction));\n  finishrelcode(L, p, block, nsize);\n}\n\n\n/*\n** Add space for an instruction with 'n' slots and return its index.\n*/\nstatic int nextinstruction (CompileState *compst, int n) {\n  int size = compst->p->code[-1].codesize - 1;\n  int ncode = compst->ncode;\n  if (ncode > size - n) {\n    uint nsize = size + (size >> 1) + n;\n    if (nsize >= INT_MAX)\n      luaL_error(compst->L, \"pattern code too large\");\n    realloccode(compst->L, compst->p, nsize);\n  }\n  compst->ncode = ncode + n;\n  return ncode;\n}\n\n\n#define getinstr(cs,i)\t\t((cs)->p->code[i])\n\n\nstatic int addinstruction (CompileState *compst, Opcode op, int aux) {\n  int i = nextinstruction(compst, 1);\n  getinstr(compst, i).i.code = op;\n  getinstr(compst, i).i.aux1 = aux;\n  return i;\n}\n\n\n/*\n** Add an instruction followed by space for an offset (to be set later)\n*/\nstatic int addoffsetinst (CompileState *compst, Opcode op) {\n  int i = addinstruction(compst, op, 0);  /* instruction */\n  addinstruction(compst, (Opcode)0, 0);  /* open space for offset */\n  assert(op == ITestSet || sizei(&getinstr(compst, i)) == 2);\n  return i;\n}\n\n\n/*\n** Set the offset of an instruction\n*/\nstatic void setoffset (CompileState *compst, int instruction, int offset) {\n  getinstr(compst, instruction + 1).offset = offset;\n}\n\n\nstatic void codeutfr (CompileState *compst, TTree *tree) {\n  int i = addoffsetinst(compst, IUTFR);\n  int to = sib1(tree)->u.n;\n  assert(sib1(tree)->tag == TXInfo);\n  getinstr(compst, i + 1).offset = tree->u.n;\n  getinstr(compst, i).i.aux1 = to & 0xff;\n  getinstr(compst, i).i.aux2.key = to >> 8;\n}\n\n\n/*\n** Add a capture instruction:\n** 'op' is the capture instruction; 'cap' the capture kind;\n** 'key' the key into ktable; 'aux' is the optional capture offset\n**\n*/\nstatic int addinstcap (CompileState *compst, Opcode op, int cap, int key,\n                       int aux) {\n  int i = addinstruction(compst, op, joinkindoff(cap, aux));\n  getinstr(compst, i).i.aux2.key = key;\n  return i;\n}\n\n\n#define gethere(compst) \t((compst)->ncode)\n\n#define target(code,i)\t\t((i) + code[i + 1].offset)\n\n\n/*\n** Patch 'instruction' to jump to 'target'\n*/\nstatic void jumptothere (CompileState *compst, int instruction, int target) {\n  if (instruction >= 0)\n    setoffset(compst, instruction, target - instruction);\n}\n\n\n/*\n** Patch 'instruction' to jump to current position\n*/\nstatic void jumptohere (CompileState *compst, int instruction) {\n  jumptothere(compst, instruction, gethere(compst));\n}\n\n\n/*\n** Code an IChar instruction, or IAny if there is an equivalent\n** test dominating it\n*/\nstatic void codechar (CompileState *compst, int c, int tt) {\n  if (tt >= 0 && getinstr(compst, tt).i.code == ITestChar &&\n                 getinstr(compst, tt).i.aux1 == c)\n    addinstruction(compst, IAny, 0);\n  else\n    addinstruction(compst, IChar, c);\n}\n\n\n/*\n** Add a charset posfix to an instruction.\n*/\nstatic void addcharset (CompileState *compst, int inst, charsetinfo *info) {\n  int p;\n  Instruction *I = &getinstr(compst, inst);\n  byte *charset;\n  int isize = instsize(info->size);  /* size in instructions */\n  int i;\n  I->i.aux2.set.offset = info->offset * 8;  /* offset in bits */\n  I->i.aux2.set.size = isize;\n  I->i.aux1 = info->deflt;\n  p = nextinstruction(compst, isize);  /* space for charset */\n  charset = getinstr(compst, p).buff;  /* charset buffer */\n  for (i = 0; i < isize * (int)sizeof(Instruction); i++)\n    charset[i] = getbytefromcharset(info, i);  /* copy the buffer */\n}\n\n\n/*\n** Check whether charset 'info' is dominated by instruction 'p'\n*/\nstatic int cs_equal (Instruction *p, charsetinfo *info) {\n  if (p->i.code != ITestSet)\n    return 0;\n  else if (p->i.aux2.set.offset != info->offset * 8 ||\n           p->i.aux2.set.size != instsize(info->size) ||\n           p->i.aux1 != info->deflt)\n    return 0;\n  else {\n    int i;\n    for (i = 0; i < instsize(info->size) * (int)sizeof(Instruction); i++) {\n      if ((p + 2)->buff[i] != getbytefromcharset(info, i))\n        return 0;\n    }\n  }\n  return 1;\n}\n\n\n/*\n** Code a char set, using IAny when instruction is dominated by an\n** equivalent test.\n*/\nstatic void codecharset (CompileState *compst, TTree *tree, int tt) {\n  charsetinfo info;\n  tree2cset(tree, &info);\n  if (tt >= 0 && cs_equal(&getinstr(compst, tt), &info))\n    addinstruction(compst, IAny, 0);\n  else {\n    int i = addinstruction(compst, ISet, 0);\n    addcharset(compst, i, &info);\n  }\n}\n\n\n/*\n** Code a test set, optimizing unit sets for ITestChar, \"complete\"\n** sets for ITestAny, and empty sets for IJmp (always fails).\n** 'e' is true iff test should accept the empty string. (Test\n** instructions in the current VM never accept the empty string.)\n*/\nstatic int codetestset (CompileState *compst, Charset *cs, int e) {\n  if (e) return NOINST;  /* no test */\n  else {\n    charsetinfo info;\n    Opcode op = charsettype(cs->cs, &info);\n    switch (op) {\n      case IFail: return addoffsetinst(compst, IJmp);  /* always jump */\n      case IAny: return addoffsetinst(compst, ITestAny);\n      case IChar: {\n        int i = addoffsetinst(compst, ITestChar);\n        getinstr(compst, i).i.aux1 = info.offset;\n        return i;\n      }\n      default: {  /* regular set */\n        int i = addoffsetinst(compst, ITestSet);\n        addcharset(compst, i, &info);\n        assert(op == ISet);\n        return i;\n      }\n    }\n  }\n}\n\n\n/*\n** Find the final destination of a sequence of jumps\n*/\nstatic int finaltarget (Instruction *code, int i) {\n  while (code[i].i.code == IJmp)\n    i = target(code, i);\n  return i;\n}\n\n\n/*\n** final label (after traversing any jumps)\n*/\nstatic int finallabel (Instruction *code, int i) {\n  return finaltarget(code, target(code, i));\n}\n\n\n/*\n** <behind(p)> == behind n; <p>   (where n = fixedlen(p))\n*/\nstatic void codebehind (CompileState *compst, TTree *tree) {\n  if (tree->u.n > 0)\n    addinstruction(compst, IBehind, tree->u.n);\n  codegen(compst, sib1(tree), 0, NOINST, fullset);\n}\n\n\n/*\n** Choice; optimizations:\n** - when p1 is headfail or when first(p1) and first(p2) are disjoint,\n** than a character not in first(p1) cannot go to p1 and a character\n** in first(p1) cannot go to p2, either because p1 will accept\n** (headfail) or because it is not in first(p2) (disjoint).\n** (The second case is not valid if p1 accepts the empty string,\n** as then there is no character at all...)\n** - when p2 is empty and opt is true; a IPartialCommit can reuse\n** the Choice already active in the stack.\n*/\nstatic void codechoice (CompileState *compst, TTree *p1, TTree *p2, int opt,\n                        const Charset *fl) {\n  int emptyp2 = (p2->tag == TTrue);\n  Charset cs1, cs2;\n  int e1 = getfirst(p1, fullset, &cs1);\n  if (headfail(p1) ||\n      (!e1 && (getfirst(p2, fl, &cs2), cs_disjoint(&cs1, &cs2)))) {\n    /* <p1 / p2> == test (fail(p1)) -> L1 ; p1 ; jmp L2; L1: p2; L2: */\n    int test = codetestset(compst, &cs1, 0);\n    int jmp = NOINST;\n    codegen(compst, p1, 0, test, fl);\n    if (!emptyp2)\n      jmp = addoffsetinst(compst, IJmp);\n    jumptohere(compst, test);\n    codegen(compst, p2, opt, NOINST, fl);\n    jumptohere(compst, jmp);\n  }\n  else if (opt && emptyp2) {\n    /* p1? == IPartialCommit; p1 */\n    jumptohere(compst, addoffsetinst(compst, IPartialCommit));\n    codegen(compst, p1, 1, NOINST, fullset);\n  }\n  else {\n    /* <p1 / p2> ==\n        test(first(p1)) -> L1; choice L1; <p1>; commit L2; L1: <p2>; L2: */\n    int pcommit;\n    int test = codetestset(compst, &cs1, e1);\n    int pchoice = addoffsetinst(compst, IChoice);\n    codegen(compst, p1, emptyp2, test, fullset);\n    pcommit = addoffsetinst(compst, ICommit);\n    jumptohere(compst, pchoice);\n    jumptohere(compst, test);\n    codegen(compst, p2, opt, NOINST, fl);\n    jumptohere(compst, pcommit);\n  }\n}\n\n\n/*\n** And predicate\n** optimization: fixedlen(p) = n ==> <&p> == <p>; behind n\n** (valid only when 'p' has no captures)\n*/\nstatic void codeand (CompileState *compst, TTree *tree, int tt) {\n  int n = fixedlen(tree);\n  if (n >= 0 && n <= MAXBEHIND && !hascaptures(tree)) {\n    codegen(compst, tree, 0, tt, fullset);\n    if (n > 0)\n      addinstruction(compst, IBehind, n);\n  }\n  else {  /* default: Choice L1; p1; BackCommit L2; L1: Fail; L2: */\n    int pcommit;\n    int pchoice = addoffsetinst(compst, IChoice);\n    codegen(compst, tree, 0, tt, fullset);\n    pcommit = addoffsetinst(compst, IBackCommit);\n    jumptohere(compst, pchoice);\n    addinstruction(compst, IFail, 0);\n    jumptohere(compst, pcommit);\n  }\n}\n\n\n/*\n** Captures: if pattern has fixed (and not too big) length, and it\n** has no nested captures, use a single IFullCapture instruction\n** after the match; otherwise, enclose the pattern with OpenCapture -\n** CloseCapture.\n*/\nstatic void codecapture (CompileState *compst, TTree *tree, int tt,\n                         const Charset *fl) {\n  int len = fixedlen(sib1(tree));\n  if (len >= 0 && len <= MAXOFF && !hascaptures(sib1(tree))) {\n    codegen(compst, sib1(tree), 0, tt, fl);\n    addinstcap(compst, IFullCapture, tree->cap, tree->key, len);\n  }\n  else {\n    addinstcap(compst, IOpenCapture, tree->cap, tree->key, 0);\n    codegen(compst, sib1(tree), 0, tt, fl);\n    addinstcap(compst, ICloseCapture, Cclose, 0, 0);\n  }\n}\n\n\nstatic void coderuntime (CompileState *compst, TTree *tree, int tt) {\n  addinstcap(compst, IOpenCapture, Cgroup, tree->key, 0);\n  codegen(compst, sib1(tree), 0, tt, fullset);\n  addinstcap(compst, ICloseRunTime, Cclose, 0, 0);\n}\n\n\n/*\n** Create a jump to 'test' and fix 'test' to jump to next instruction\n*/\nstatic void closeloop (CompileState *compst, int test) {\n  int jmp = addoffsetinst(compst, IJmp);\n  jumptohere(compst, test);\n  jumptothere(compst, jmp, test);\n}\n\n\n/*\n** Try repetition of charsets:\n** For an empty set, repetition of fail is a no-op;\n** For any or char, code a tight loop;\n** For generic charset, use a span instruction.\n*/\nstatic int coderepcharset (CompileState *compst, TTree *tree) {\n  switch (tree->tag) {\n    case TFalse: return 1;  /* 'fail*' is a no-op */\n    case TAny: {  /* L1: testany -> L2; any; jmp L1; L2: */\n      int test = addoffsetinst(compst, ITestAny);\n      addinstruction(compst, IAny, 0);\n      closeloop(compst, test);\n      return 1;\n    }\n    case TChar: {  /* L1: testchar c -> L2; any; jmp L1; L2: */\n      int test = addoffsetinst(compst, ITestChar);\n      getinstr(compst, test).i.aux1 = tree->u.n;\n      addinstruction(compst, IAny, 0);\n      closeloop(compst, test);\n      return 1;\n    }\n    case TSet: {  /* regular set */\n      charsetinfo info;\n      int i = addinstruction(compst, ISpan, 0);\n      tree2cset(tree, &info);\n      addcharset(compst, i, &info);\n      return 1;\n    }\n    default: return 0;  /* not a charset */\n  }\n}\n\n\n/*\n** Repetion; optimizations:\n** When pattern is a charset, use special code.\n** When pattern is head fail, or if it starts with characters that\n** are disjoint from what follows the repetions, a simple test\n** is enough (a fail inside the repetition would backtrack to fail\n** again in the following pattern, so there is no need for a choice).\n** When 'opt' is true, the repetion can reuse the Choice already\n** active in the stack.\n*/\nstatic void coderep (CompileState *compst, TTree *tree, int opt,\n                     const Charset *fl) {\n  if (!coderepcharset(compst, tree)) {\n    Charset st;\n    int e1 = getfirst(tree, fullset, &st);\n    if (headfail(tree) || (!e1 && cs_disjoint(&st, fl))) {\n      /* L1: test (fail(p1)) -> L2; <p>; jmp L1; L2: */\n      int test = codetestset(compst, &st, 0);\n      codegen(compst, tree, 0, test, fullset);\n      closeloop(compst, test);\n    }\n    else {\n      /* test(fail(p1)) -> L2; choice L2; L1: <p>; partialcommit L1; L2: */\n      /* or (if 'opt'): partialcommit L1; L1: <p>; partialcommit L1; */\n      int commit, l2;\n      int test = codetestset(compst, &st, e1);\n      int pchoice = NOINST;\n      if (opt)\n        jumptohere(compst, addoffsetinst(compst, IPartialCommit));\n      else\n        pchoice = addoffsetinst(compst, IChoice);\n      l2 = gethere(compst);\n      codegen(compst, tree, 0, NOINST, fullset);\n      commit = addoffsetinst(compst, IPartialCommit);\n      jumptothere(compst, commit, l2);\n      jumptohere(compst, pchoice);\n      jumptohere(compst, test);\n    }\n  }\n}\n\n\n/*\n** Not predicate; optimizations:\n** In any case, if first test fails, 'not' succeeds, so it can jump to\n** the end. If pattern is headfail, that is all (it cannot fail\n** in other parts); this case includes 'not' of simple sets. Otherwise,\n** use the default code (a choice plus a failtwice).\n*/\nstatic void codenot (CompileState *compst, TTree *tree) {\n  Charset st;\n  int e = getfirst(tree, fullset, &st);\n  int test = codetestset(compst, &st, e);\n  if (headfail(tree))  /* test (fail(p1)) -> L1; fail; L1:  */\n    addinstruction(compst, IFail, 0);\n  else {\n    /* test(fail(p))-> L1; choice L1; <p>; failtwice; L1:  */\n    int pchoice = addoffsetinst(compst, IChoice);\n    codegen(compst, tree, 0, NOINST, fullset);\n    addinstruction(compst, IFailTwice, 0);\n    jumptohere(compst, pchoice);\n  }\n  jumptohere(compst, test);\n}\n\n\n/*\n** change open calls to calls, using list 'positions' to find\n** correct offsets; also optimize tail calls\n*/\nstatic void correctcalls (CompileState *compst, int *positions,\n                          int from, int to) {\n  int i;\n  Instruction *code = compst->p->code;\n  for (i = from; i < to; i += sizei(&code[i])) {\n    if (code[i].i.code == IOpenCall) {\n      int n = code[i].i.aux2.key;  /* rule number */\n      int rule = positions[n];  /* rule position */\n      assert(rule == from || code[rule - 1].i.code == IRet);\n      if (code[finaltarget(code, i + 2)].i.code == IRet)  /* call; ret ? */\n        code[i].i.code = IJmp;  /* tail call */\n      else\n        code[i].i.code = ICall;\n      jumptothere(compst, i, rule);  /* call jumps to respective rule */\n    }\n  }\n  assert(i == to);\n}\n\n\n/*\n** Code for a grammar:\n** call L1; jmp L2; L1: rule 1; ret; rule 2; ret; ...; L2:\n*/\nstatic void codegrammar (CompileState *compst, TTree *grammar) {\n  int positions[MAXRULES];\n  int rulenumber = 0;\n  TTree *rule;\n  int firstcall = addoffsetinst(compst, ICall);  /* call initial rule */\n  int jumptoend = addoffsetinst(compst, IJmp);  /* jump to the end */\n  int start = gethere(compst);  /* here starts the initial rule */\n  jumptohere(compst, firstcall);\n  for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {\n    TTree *r = sib1(rule);\n    assert(r->tag == TXInfo);\n    positions[rulenumber++] = gethere(compst);  /* save rule position */\n    codegen(compst, sib1(r), 0, NOINST, fullset);  /* code rule */\n    addinstruction(compst, IRet, 0);\n  }\n  assert(rule->tag == TTrue);\n  jumptohere(compst, jumptoend);\n  correctcalls(compst, positions, start, gethere(compst));\n}\n\n\nstatic void codecall (CompileState *compst, TTree *call) {\n  int c = addoffsetinst(compst, IOpenCall);  /* to be corrected later */\n  assert(sib1(sib2(call))->tag == TXInfo);\n  getinstr(compst, c).i.aux2.key = sib1(sib2(call))->u.n;  /* rule number */\n}\n\n\n/*\n** Code first child of a sequence\n** (second child is called in-place to allow tail call)\n** Return 'tt' for second child\n*/\nstatic int codeseq1 (CompileState *compst, TTree *p1, TTree *p2,\n                     int tt, const Charset *fl) {\n  if (needfollow(p1)) {\n    Charset fl1;\n    getfirst(p2, fl, &fl1);  /* p1 follow is p2 first */\n    codegen(compst, p1, 0, tt, &fl1);\n  }\n  else  /* use 'fullset' as follow */\n    codegen(compst, p1, 0, tt, fullset);\n  if (fixedlen(p1) != 0)  /* can 'p1' consume anything? */\n    return  NOINST;  /* invalidate test */\n  else return tt;  /* else 'tt' still protects sib2 */\n}\n\n\n/*\n** Main code-generation function: dispatch to auxiliar functions\n** according to kind of tree. ('needfollow' should return true\n** only for consructions that use 'fl'.)\n*/\nstatic void codegen (CompileState *compst, TTree *tree, int opt, int tt,\n                     const Charset *fl) {\n tailcall:\n  switch (tree->tag) {\n    case TChar: codechar(compst, tree->u.n, tt); break;\n    case TAny: addinstruction(compst, IAny, 0); break;\n    case TSet: codecharset(compst, tree, tt); break;\n    case TTrue: break;\n    case TFalse: addinstruction(compst, IFail, 0); break;\n    case TUTFR: codeutfr(compst, tree); break;\n    case TChoice: codechoice(compst, sib1(tree), sib2(tree), opt, fl); break;\n    case TRep: coderep(compst, sib1(tree), opt, fl); break;\n    case TBehind: codebehind(compst, tree); break;\n    case TNot: codenot(compst, sib1(tree)); break;\n    case TAnd: codeand(compst, sib1(tree), tt); break;\n    case TCapture: codecapture(compst, tree, tt, fl); break;\n    case TRunTime: coderuntime(compst, tree, tt); break;\n    case TGrammar: codegrammar(compst, tree); break;\n    case TCall: codecall(compst, tree); break;\n    case TSeq: {\n      tt = codeseq1(compst, sib1(tree), sib2(tree), tt, fl);  /* code 'p1' */\n      /* codegen(compst, p2, opt, tt, fl); */\n      tree = sib2(tree); goto tailcall;\n    }\n    default: assert(0);\n  }\n}\n\n\n/*\n** Optimize jumps and other jump-like instructions.\n** * Update labels of instructions with labels to their final\n** destinations (e.g., choice L1; ... L1: jmp L2: becomes\n** choice L2)\n** * Jumps to other instructions that do jumps become those\n** instructions (e.g., jump to return becomes a return; jump\n** to commit becomes a commit)\n*/\nstatic void peephole (CompileState *compst) {\n  Instruction *code = compst->p->code;\n  int i;\n  for (i = 0; i < compst->ncode; i += sizei(&code[i])) {\n   redo:\n    switch (code[i].i.code) {\n      case IChoice: case ICall: case ICommit: case IPartialCommit:\n      case IBackCommit: case ITestChar: case ITestSet:\n      case ITestAny: {  /* instructions with labels */\n        jumptothere(compst, i, finallabel(code, i));  /* optimize label */\n        break;\n      }\n      case IJmp: {\n        int ft = finaltarget(code, i);\n        switch (code[ft].i.code) {  /* jumping to what? */\n          case IRet: case IFail: case IFailTwice:\n          case IEnd: {  /* instructions with unconditional implicit jumps */\n            code[i] = code[ft];  /* jump becomes that instruction */\n            code[i + 1].i.code = IEmpty;  /* 'no-op' for target position */\n            break;\n          }\n          case ICommit: case IPartialCommit:\n          case IBackCommit: {  /* inst. with unconditional explicit jumps */\n            int fft = finallabel(code, ft);\n            code[i] = code[ft];  /* jump becomes that instruction... */\n            jumptothere(compst, i, fft);  /* but must correct its offset */\n            goto redo;  /* reoptimize its label */\n          }\n          default: {\n            jumptothere(compst, i, ft);  /* optimize label */\n            break;\n          }\n        }\n        break;\n      }\n      default: break;\n    }\n  }\n  assert(code[i - 1].i.code == IEnd);\n}\n\n\n/*\n** Compile a pattern. 'size' is the size of the pattern's tree,\n** which gives a hint for the size of the final code.\n*/\nInstruction *compile (lua_State *L, Pattern *p, uint size) {\n  CompileState compst;\n  compst.p = p;  compst.ncode = 0;  compst.L = L;\n  newcode(L, p, size/2u + 2);  /* set initial size */\n  codegen(&compst, p->tree, 0, NOINST, fullset);\n  addinstruction(&compst, IEnd, 0);\n  realloccode(L, p, compst.ncode);  /* set final size */\n  peephole(&compst);\n  return p->code;\n}\n\n\n/* }====================================================== */\n\n"
  },
  {
    "path": "3rd/lpeg/lpcode.h",
    "content": "\n#if !defined(lpcode_h)\n#define lpcode_h\n\n#include \"lua.h\"\n\n#include \"lptypes.h\"\n#include \"lptree.h\"\n#include \"lpvm.h\"\n\nint checkaux (TTree *tree, int pred);\nint fixedlen (TTree *tree);\nint hascaptures (TTree *tree);\nint lp_gc (lua_State *L);\nInstruction *compile (lua_State *L, Pattern *p, uint size);\nvoid freecode (lua_State *L, Pattern *p);\nint sizei (const Instruction *i);\n\n\n#define PEnullable      0\n#define PEnofail        1\n\n/*\n** nofail(t) implies that 't' cannot fail with any input\n*/\n#define nofail(t)\tcheckaux(t, PEnofail)\n\n/*\n** (not nullable(t)) implies 't' cannot match without consuming\n** something\n*/\n#define nullable(t)\tcheckaux(t, PEnullable)\n\n\n\n#endif\n"
  },
  {
    "path": "3rd/lpeg/lpcset.c",
    "content": "\n#include \"lptypes.h\"\n#include \"lpcset.h\"\n\n\n/*\n** Add to 'c' the index of the (only) bit set in byte 'b'\n*/\nstatic int onlybit (int c, int b) {\n  if ((b & 0xF0) != 0) { c += 4; b >>= 4; }\n  if ((b & 0x0C) != 0) { c += 2; b >>= 2; }\n  if ((b & 0x02) != 0) { c += 1; }\n  return c;\n}\n\n\n/*\n** Check whether a charset is empty (returns IFail), singleton (IChar),\n** full (IAny), or none of those (ISet). When singleton, 'info.offset'\n** returns which character it is. When generic set, 'info' returns\n** information about its range.\n*/\nOpcode charsettype (const byte *cs, charsetinfo *info) {\n  int low0, low1, high0, high1;\n  for (low1 = 0; low1 < CHARSETSIZE && cs[low1] == 0; low1++)\n    /* find lowest byte with a 1-bit */;\n  if (low1 == CHARSETSIZE)\n    return IFail;  /* no characters in set */\n  for (high1 = CHARSETSIZE - 1; cs[high1] == 0; high1--)\n    /* find highest byte with a 1-bit; low1 is a sentinel */;\n  if (low1 == high1) {  /* only one byte with 1-bits? */\n    int b = cs[low1];\n    if ((b & (b - 1)) == 0) {  /* does byte has only one 1-bit? */\n      info->offset = onlybit(low1 * BITSPERCHAR, b);  /* get that bit */\n      return IChar;  /* single character */\n    }\n  }\n  for (low0 = 0; low0 < CHARSETSIZE && cs[low0] == 0xFF; low0++)\n    /* find lowest byte with a 0-bit */;\n  if (low0 == CHARSETSIZE)\n    return IAny;  /* set has all bits set */\n  for (high0 = CHARSETSIZE - 1; cs[high0] == 0xFF; high0--)\n    /* find highest byte with a 0-bit; low0 is a sentinel */;\n  if (high1 - low1 <= high0 - low0) {  /* range of 1s smaller than of 0s? */\n    info->offset = low1;\n    info->size = high1 - low1 + 1;\n    info->deflt = 0;  /* all discharged bits were 0 */\n  }\n  else {\n    info->offset = low0;\n    info->size = high0 - low0 + 1;\n    info->deflt = 0xFF;  /* all discharged bits were 1 */\n  }\n  info->cs = cs + info->offset;\n  return ISet;\n}\n\n\n/*\n** Get a byte from a compact charset. If index is inside the charset\n** range, get the byte from the supporting charset (correcting it\n** by the offset). Otherwise, return the default for the set.\n*/\nbyte getbytefromcharset (const charsetinfo *info, int index) {\n  if (index < info->size)\n    return info->cs[index];\n  else return info->deflt;\n}\n\n\n/*\n** If 'tree' is a 'char' pattern (TSet, TChar, TAny, TFalse), convert it\n** into a charset and return 1; else return 0.\n*/\nint tocharset (TTree *tree, Charset *cs) {\n  switch (tree->tag) {\n    case TChar: {  /* only one char */\n      assert(0 <= tree->u.n && tree->u.n <= UCHAR_MAX);\n      clearset(cs->cs);  /* erase all chars */\n      setchar(cs->cs, tree->u.n);  /* add that one */\n      return 1;\n    }\n    case TAny: {\n      fillset(cs->cs, 0xFF);  /* add all characters to the set */\n      return 1;\n    }\n    case TFalse: {\n      clearset(cs->cs);  /* empty set */\n      return 1;\n    }\n    case TSet: {  /* fill set */\n      int i;\n      fillset(cs->cs, tree->u.set.deflt);\n      for (i = 0; i < tree->u.set.size; i++)\n        cs->cs[tree->u.set.offset + i] = treebuffer(tree)[i];\n      return 1;\n    }\n    default: return 0;\n  }\n}\n\n\nvoid tree2cset (TTree *tree, charsetinfo *info) {\n  assert(tree->tag == TSet);\n  info->offset = tree->u.set.offset;\n  info->size = tree->u.set.size;\n  info->deflt = tree->u.set.deflt;\n  info->cs = treebuffer(tree);\n}\n\n"
  },
  {
    "path": "3rd/lpeg/lpcset.h",
    "content": "\n#if !defined(lpset_h)\n#define lpset_h\n\n#include \"lpcset.h\"\n#include \"lpcode.h\"\n#include \"lptree.h\"\n\n\n/*\n** Extra information for the result of 'charsettype'.  When result is\n** IChar, 'offset' is the character.  When result is ISet, 'cs' is the\n** supporting bit array (with offset included), 'offset' is the offset\n** (in bytes), 'size' is the size (in bytes), and 'delt' is the default\n** value for bytes outside the set.\n*/\ntypedef struct {\n  const byte *cs;\n  int offset;\n  int size;\n  int deflt;\n} charsetinfo;\n\n\nint tocharset (TTree *tree, Charset *cs);\nOpcode charsettype (const byte *cs, charsetinfo *info);\nbyte getbytefromcharset (const charsetinfo *info, int index);\nvoid tree2cset (TTree *tree, charsetinfo *info);\n\n#endif\n"
  },
  {
    "path": "3rd/lpeg/lpeg.html",
    "content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n   \"//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"//www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n    <title>LPeg - Parsing Expression Grammars For Lua</title>\n    <link rel=\"stylesheet\"\n          href=\"//www.inf.puc-rio.br/~roberto/lpeg/doc.css\"\n          type=\"text/css\"/>\n\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n</head>\n<body>\n\n\n<div id=\"container\">\n\t\n<div id=\"product\">\n  <div id=\"product_logo\">\n    <a href=\"//www.inf.puc-rio.br/~roberto/lpeg/\">\n    <img alt=\"LPeg logo\" src=\"lpeg-128.gif\"/></a>\n    \n  </div>\n  <div id=\"product_name\"><big><strong>LPeg</strong></big></div>\n  <div id=\"product_description\">\n     Parsing Expression Grammars For Lua, version 1.1\n  </div>\n</div> <!-- id=\"product\" -->\n\n<div id=\"main\">\n\t\n<div id=\"navigation\">\n<h1>LPeg</h1>\n\n<ul>\n  <li><strong>Home</strong>\n  <ul>\n    <li><a href=\"#intro\">Introduction</a></li>\n    <li><a href=\"#func\">Functions</a></li>\n    <li><a href=\"#basic\">Basic Constructions</a></li>\n    <li><a href=\"#grammar\">Grammars</a></li>\n    <li><a href=\"#captures\">Captures</a></li>\n    <li><a href=\"#ex\">Some Examples</a></li>\n    <li><a href=\"re.html\">The <code>re</code> Module</a></li>\n    <li><a href=\"#download\">Download</a></li>\n    <li><a href=\"#license\">License</a></li>\n  </ul>\n  </li>\n</ul>\n</div> <!-- id=\"navigation\" -->\n\n<div id=\"content\">\n\n\n<h2><a name=\"intro\">Introduction</a></h2>\n\n<p>\n<em>LPeg</em> is a new pattern-matching library for Lua,\nbased on\n<a href=\"//bford.info/packrat/\">\nParsing Expression Grammars</a> (PEGs).\nThis text is a reference manual for the library.\nFor a more formal treatment of LPeg,\nas well as some discussion about its implementation,\nsee\n<a href=\"//www.inf.puc-rio.br/~roberto/docs/peg.pdf\">\nA Text Pattern-Matching Tool based on Parsing Expression Grammars</a>.\n(You may also be interested in my\n<a href=\"//vimeo.com/1485123\">talk about LPeg</a>\ngiven at the III Lua Workshop.)\n</p>\n\n<p>\nFollowing the Snobol tradition,\nLPeg defines patterns as first-class objects.\nThat is, patterns are regular Lua values\n(represented by userdata).\nThe library offers several functions to create\nand compose patterns.\nWith the use of metamethods,\nseveral of these functions are provided as infix or prefix\noperators.\nOn the one hand,\nthe result is usually much more verbose than the typical\nencoding of patterns using the so called\n<em>regular expressions</em>\n(which typically are not regular expressions in the formal sense).\nOn the other hand,\nfirst-class patterns allow much better documentation\n(as it is easy to comment the code,\nto break complex definitions in smaller parts, etc.)\nand are extensible,\nas we can define new functions to create and compose patterns.\n</p>\n\n<p>\nFor a quick glance of the library,\nthe following table summarizes its basic operations\nfor creating patterns:\n</p>\n<table border=\"1\">\n<tbody><tr><td><b>Operator</b></td><td><b>Description</b></td></tr>\n<tr><td><a href=\"#op-p\"><code>lpeg.P(string)</code></a></td>\n  <td>Matches <code>string</code> literally</td></tr>\n<tr><td><a href=\"#op-p\"><code>lpeg.P(n)</code></a></td>\n  <td>Matches exactly <code>n</code> characters</td></tr>\n<tr><td><a href=\"#op-s\"><code>lpeg.S(string)</code></a></td>\n  <td>Matches any character in <code>string</code> (Set)</td></tr>\n<tr><td><a href=\"#op-r\"><code>lpeg.R(\"<em>xy</em>\")</code></a></td>\n  <td>Matches any character between <em>x</em> and <em>y</em> (Range)</td></tr>\n<tr><td><a href=\"#op-utfR\"><code>lpeg.utfR(cp1, cp2)</code></a></td>\n  <td>Matches an UTF-8 code point between <code>cp1</code> and\n  <code>cp2</code></td></tr>\n<tr><td><a href=\"#op-pow\"><code>patt^n</code></a></td>\n  <td>Matches at least <code>n</code> repetitions of <code>patt</code></td></tr>\n<tr><td><a href=\"#op-pow\"><code>patt^-n</code></a></td>\n  <td>Matches at most <code>n</code> repetitions of <code>patt</code></td></tr>\n<tr><td><a href=\"#op-mul\"><code>patt1 * patt2</code></a></td>\n  <td>Matches <code>patt1</code> followed by <code>patt2</code></td></tr>\n<tr><td><a href=\"#op-add\"><code>patt1 + patt2</code></a></td>\n  <td>Matches <code>patt1</code> or <code>patt2</code>\n      (ordered choice)</td></tr>\n<tr><td><a href=\"#op-sub\"><code>patt1 - patt2</code></a></td>\n  <td>Matches <code>patt1</code> if <code>patt2</code> does not match</td></tr>\n<tr><td><a href=\"#op-unm\"><code>-patt</code></a></td>\n  <td>Equivalent to <code>(\"\" - patt)</code></td></tr>\n<tr><td><a href=\"#op-len\"><code>#patt</code></a></td>\n  <td>Matches <code>patt</code> but consumes no input</td></tr>\n<tr><td><a href=\"#op-behind\"><code>lpeg.B(patt)</code></a></td>\n  <td>Matches <code>patt</code> behind the current position,\n      consuming no input</td></tr>\n</tbody></table>\n\n<p>As a very simple example,\n<code>lpeg.R(\"09\")^1</code> creates a pattern that\nmatches a non-empty sequence of digits.\nAs a not so simple example,\n<code>-lpeg.P(1)</code>\n(which can be written as <code>lpeg.P(-1)</code>,\nor simply <code>-1</code> for operations expecting a pattern)\nmatches an empty string only if it cannot match a single character;\nso, it succeeds only at the end of the subject.\n</p>\n\n<p>\nLPeg also offers the <a href=\"re.html\"><code>re</code> module</a>,\nwhich implements patterns following a regular-expression style\n(e.g., <code>[09]+</code>).\n(This module is 270 lines of Lua code,\nand of course it uses LPeg to parse regular expressions and\ntranslate them to regular LPeg patterns.)\n</p>\n\n\n<h2><a name=\"func\">Functions</a></h2>\n\n\n<h3><a name=\"f-match\"></a><code>lpeg.match (pattern, subject [, init])</code></h3>\n<p>\nThe matching function.\nIt attempts to match the given pattern against the subject string.\nIf the match succeeds,\nreturns the index in the subject of the first character after the match,\nor the <a href=\"#captures\">captured values</a>\n(if the pattern captured any value).\n</p>\n\n<p>\nAn optional numeric argument <code>init</code> makes the match\nstart at that position in the subject string.\nAs in the Lua standard libraries,\na negative value counts from the end.\n</p>\n\n<p>\nUnlike typical pattern-matching functions,\n<code>match</code> works only in <em>anchored</em> mode;\nthat is, it tries to match the pattern with a prefix of\nthe given subject string (at position <code>init</code>),\nnot with an arbitrary substring of the subject.\nSo, if we want to find a pattern anywhere in a string,\nwe must either write a loop in Lua or write a pattern that\nmatches anywhere.\nThis second approach is easy and quite efficient;\nsee <a href=\"#ex\">examples</a>.\n</p>\n\n<h3><a name=\"f-type\"></a><code>lpeg.type (value)</code></h3>\n<p>\nIf the given value is a pattern,\nreturns the string <code>\"pattern\"</code>.\nOtherwise returns nil.\n</p>\n\n<h3><a name=\"f-version\"></a><code>lpeg.version</code></h3>\n<p>\nA string (not a function) with the running version of LPeg.\n</p>\n\n<h3><a name=\"f-setstack\"></a><code>lpeg.setmaxstack (max)</code></h3>\n<p>\nSets a limit for the size of the backtrack stack used by LPeg to\ntrack calls and choices.\n(The default limit is 400.)\nMost well-written patterns need little backtrack levels and\ntherefore you seldom need to change this limit;\nbefore changing it you should try to rewrite your\npattern to avoid the need for extra space.\nNevertheless, a few useful patterns may overflow.\nAlso, with recursive grammars,\nsubjects with deep recursion may also need larger limits.\n</p>\n\n\n<h2><a name=\"basic\">Basic Constructions</a></h2>\n\n<p>\nThe following operations build patterns.\nAll operations that expect a pattern as an argument\nmay receive also strings, tables, numbers, booleans, or functions,\nwhich are translated to patterns according to\nthe rules of function <a href=\"#op-p\"><code>lpeg.P</code></a>.\n</p>\n\n\n\n<h3><a name=\"op-p\"></a><code>lpeg.P (value)</code></h3>\n<p>\nConverts the given value into a proper pattern,\naccording to the following rules:\n</p>\n<ul>\n\n<li><p>\nIf the argument is a pattern,\nit is returned unmodified.\n</p></li>\n\n<li><p>\nIf the argument is a string,\nit is translated to a pattern that matches the string literally.\n</p></li>\n\n<li><p>\nIf the argument is a non-negative number <em>n</em>,\nthe result is a pattern that matches exactly <em>n</em> characters.\n</p></li>\n\n<li><p>\nIf the argument is a negative number <em>-n</em>,\nthe result is a pattern that\nsucceeds only if the input string has less than <em>n</em> characters left:\n<code>lpeg.P(-n)</code>\nis equivalent to <code>-lpeg.P(n)</code>\n(see the  <a href=\"#op-unm\">unary minus operation</a>).\n</p></li>\n\n<li><p>\nIf the argument is a boolean,\nthe result is a pattern that always succeeds or always fails\n(according to the boolean value),\nwithout consuming any input.\n</p></li>\n\n<li><p>\nIf the argument is a table,\nit is interpreted as a grammar\n(see <a href=\"#grammar\">Grammars</a>).\n</p></li>\n\n<li><p>\nIf the argument is a function,\nreturns a pattern equivalent to a\n<a href=\"#matchtime\">match-time capture</a> over the empty string.\n</p></li>\n\n</ul>\n\n\n<h3><a name=\"op-behind\"></a><code>lpeg.B(patt)</code></h3>\n<p>\nReturns a pattern that\nmatches only if the input string at the current position\nis preceded by <code>patt</code>.\nPattern <code>patt</code> must match only strings\nwith some fixed length,\nand it cannot contain captures.\n</p>\n\n<p>\nLike the <a href=\"#op-len\">and predicate</a>,\nthis pattern never consumes any input,\nindependently of success or failure.\n</p>\n\n\n<h3><a name=\"op-r\"></a><code>lpeg.R ({range})</code></h3>\n<p>\nReturns a pattern that matches any single character\nbelonging to one of the given <em>ranges</em>.\nEach <code>range</code> is a string <em>xy</em> of length 2,\nrepresenting all characters with code\nbetween the codes of <em>x</em> and <em>y</em>\n(both inclusive).\n</p>\n\n<p>\nAs an example, the pattern\n<code>lpeg.R(\"09\")</code> matches any digit,\nand <code>lpeg.R(\"az\", \"AZ\")</code> matches any ASCII letter.\n</p>\n\n\n<h3><a name=\"op-s\"></a><code>lpeg.S (string)</code></h3>\n<p>\nReturns a pattern that matches any single character that\nappears in the given string.\n(The <code>S</code> stands for <em>Set</em>.)\n</p>\n\n<p>\nAs an example, the pattern\n<code>lpeg.S(\"+-*/\")</code> matches any arithmetic operator.\n</p>\n\n<p>\nNote that, if <code>s</code> is a character\n(that is, a string of length 1),\nthen <code>lpeg.P(s)</code> is equivalent to <code>lpeg.S(s)</code>\nwhich is equivalent to <code>lpeg.R(s..s)</code>.\nNote also that both <code>lpeg.S(\"\")</code> and <code>lpeg.R()</code>\nare patterns that always fail.\n</p>\n\n\n<h3><a name=\"op-utfR\"></a><code>lpeg.utfR (cp1, cp2)</code></h3>\n<p>\nReturns a pattern that matches a valid UTF-8 byte sequence\nrepresenting a code point in the range <code>[cp1, cp2]</code>.\nThe range is limited by the natural Unicode limit of 0x10FFFF,\nbut may include surrogates.\n</p>\n\n\n<h3><a name=\"op-v\"></a><code>lpeg.V (v)</code></h3>\n<p>\nThis operation creates a non-terminal (a <em>variable</em>)\nfor a grammar.\nThe created non-terminal refers to the rule indexed by <code>v</code>\nin the enclosing grammar.\n(See <a href=\"#grammar\">Grammars</a> for details.)\n</p>\n\n\n<h3><a name=\"op-locale\"></a><code>lpeg.locale ([table])</code></h3>\n<p>\nReturns a table with patterns for matching some character classes\naccording to the current locale.\nThe table has fields named\n<code>alnum</code>,\n<code>alpha</code>,\n<code>cntrl</code>,\n<code>digit</code>,\n<code>graph</code>,\n<code>lower</code>,\n<code>print</code>,\n<code>punct</code>,\n<code>space</code>,\n<code>upper</code>, and\n<code>xdigit</code>,\neach one containing a correspondent pattern.\nEach pattern matches any single character that belongs to its class.\n</p>\n\n<p>\nIf called with an argument <code>table</code>,\nthen it creates those fields inside the given table and\nreturns that table. \n</p>\n\n\n<h3><a name=\"op-len\"></a><code>#patt</code></h3>\n<p>\nReturns a pattern that\nmatches only if the input string matches <code>patt</code>,\nbut without consuming any input,\nindependently of success or failure.\n(This pattern is called an <em>and predicate</em>\nand it is equivalent to\n<em>&amp;patt</em> in the original PEG notation.)\n</p>\n\n\n<p>\nThis pattern never produces any capture.\n</p>\n\n\n<h3><a name=\"op-unm\"></a><code>-patt</code></h3>\n<p>\nReturns a pattern that\nmatches only if the input string does not match <code>patt</code>.\nIt does not consume any input,\nindependently of success or failure.\n(This pattern is equivalent to\n<em>!patt</em> in the original PEG notation.)\n</p>\n\n<p>\nAs an example, the pattern\n<code>-lpeg.P(1)</code> matches only the end of string.\n</p>\n\n<p>\nThis pattern never produces any captures,\nbecause either <code>patt</code> fails\nor <code>-patt</code> fails.\n(A failing pattern never produces captures.)\n</p>\n\n\n<h3><a name=\"op-add\"></a><code>patt1 + patt2</code></h3>\n<p>\nReturns a pattern equivalent to an <em>ordered choice</em>\nof <code>patt1</code> and <code>patt2</code>.\n(This is denoted by <em>patt1 / patt2</em> in the original PEG notation,\nnot to be confused with the <code>/</code> operation in LPeg.)\nIt matches either <code>patt1</code> or <code>patt2</code>,\nwith no backtracking once one of them succeeds.\nThe identity element for this operation is the pattern\n<code>lpeg.P(false)</code>,\nwhich always fails.\n</p>\n\n<p>\nIf both <code>patt1</code> and <code>patt2</code> are\ncharacter sets,\nthis operation is equivalent to set union.\n</p>\n<pre class=\"example\">\nlower = lpeg.R(\"az\")\nupper = lpeg.R(\"AZ\")\nletter = lower + upper\n</pre>\n\n\n<h3><a name=\"op-sub\"></a><code>patt1 - patt2</code></h3>\n<p>\nReturns a pattern equivalent to <em>!patt2 patt1</em>\nin the origial PEG notation.\nThis pattern asserts that the input does not match\n<code>patt2</code> and then matches <code>patt1</code>.\n</p>\n\n<p>\nWhen successful,\nthis pattern produces all captures from <code>patt1</code>.\nIt never produces any capture from <code>patt2</code>\n(as either <code>patt2</code> fails or\n<code>patt1 - patt2</code> fails).\n</p>\n\n<p>\nIf both <code>patt1</code> and <code>patt2</code> are\ncharacter sets,\nthis operation is equivalent to set difference.\nNote that <code>-patt</code> is equivalent to <code>\"\" - patt</code>\n(or <code>0 - patt</code>).\nIf <code>patt</code> is a character set,\n<code>1 - patt</code> is its complement.\n</p>\n\n\n<h3><a name=\"op-mul\"></a><code>patt1 * patt2</code></h3>\n<p>\nReturns a pattern that matches <code>patt1</code>\nand then matches <code>patt2</code>,\nstarting where <code>patt1</code> finished.\nThe identity element for this operation is the\npattern <code>lpeg.P(true)</code>,\nwhich always succeeds.\n</p>\n\n<p>\n(LPeg uses the <code>*</code> operator\n[instead of the more obvious <code>..</code>]\nboth because it has\nthe right priority and because in formal languages it is\ncommon to use a dot for denoting concatenation.)\n</p>\n\n\n<h3><a name=\"op-pow\"></a><code>patt^n</code></h3>\n<p>\nIf <code>n</code> is nonnegative,\nthis pattern is\nequivalent to <em>patt<sup>n</sup> patt*</em>:\nIt matches <code>n</code> or more occurrences of <code>patt</code>.\n</p>\n\n<p>\nOtherwise, when <code>n</code> is negative,\nthis pattern is equivalent to <em>(patt?)<sup>-n</sup></em>:\nIt matches at most <code>|n|</code>\noccurrences of <code>patt</code>.\n</p>\n\n<p>\nIn particular, <code>patt^0</code> is equivalent to <em>patt*</em>,\n<code>patt^1</code> is equivalent to <em>patt+</em>,\nand <code>patt^-1</code> is equivalent to <em>patt?</em>\nin the original PEG notation.\n</p>\n\n<p>\nIn all cases,\nthe resulting pattern is greedy with no backtracking\n(also called a <em>possessive</em> repetition).\nThat is, it matches only the longest possible sequence\nof matches for <code>patt</code>.\n</p>\n\n\n\n<h2><a name=\"grammar\">Grammars</a></h2>\n\n<p>\nWith the use of Lua variables,\nit is possible to define patterns incrementally,\nwith each new pattern using previously defined ones.\nHowever, this technique does not allow the definition of\nrecursive patterns.\nFor recursive patterns,\nwe need real grammars.\n</p>\n\n<p>\nLPeg represents grammars with tables,\nwhere each entry is a rule.\n</p>\n\n<p>\nThe call <code>lpeg.V(v)</code>\ncreates a pattern that represents the nonterminal\n(or <em>variable</em>) with index <code>v</code> in a grammar.\nBecause the grammar still does not exist when\nthis function is evaluated,\nthe result is an <em>open reference</em> to the respective rule.\n</p>\n\n<p>\nA table is <em>fixed</em> when it is converted to a pattern\n(either by calling <code>lpeg.P</code> or by using it wherein a\npattern is expected).\nThen every open reference created by <code>lpeg.V(v)</code>\nis corrected to refer to the rule indexed by <code>v</code> in the table.\n</p>\n\n<p>\nWhen a table is fixed,\nthe result is a pattern that matches its <em>initial rule</em>.\nThe entry with index 1 in the table defines its initial rule.\nIf that entry is a string,\nit is assumed to be the name of the initial rule.\nOtherwise, LPeg assumes that the entry 1 itself is the initial rule.\n</p>\n\n<p>\nAs an example,\nthe following grammar matches strings of a's and b's that\nhave the same number of a's and b's:\n</p>\n<pre class=\"example\">\nequalcount = lpeg.P{\n  \"S\";   -- initial rule name\n  S = \"a\" * lpeg.V\"B\" + \"b\" * lpeg.V\"A\" + \"\",\n  A = \"a\" * lpeg.V\"S\" + \"b\" * lpeg.V\"A\" * lpeg.V\"A\",\n  B = \"b\" * lpeg.V\"S\" + \"a\" * lpeg.V\"B\" * lpeg.V\"B\",\n} * -1\n</pre>\n<p>\nIt is equivalent to the following grammar in standard PEG notation:\n</p>\n<pre class=\"example\">\n  S <- 'a' B / 'b' A / ''\n  A <- 'a' S / 'b' A A\n  B <- 'b' S / 'a' B B\n</pre>\n\n\n<h2><a name=\"captures\">Captures</a></h2>\n\n<p>\nA <em>capture</em> is a pattern that produces values\n(the so called <em>semantic information</em>)\naccording to what it matches.\nLPeg offers several kinds of captures,\nwhich produces values based on matches and combine these values to\nproduce new values.\nEach capture may produce zero or more values.\n</p>\n\n<p>\nThe following table summarizes the basic captures:\n</p>\n<table border=\"1\">\n<tbody><tr><td><b>Operation</b></td><td><b>What it Produces</b></td></tr>\n<tr><td><a href=\"#cap-c\"><code>lpeg.C(patt)</code></a></td>\n  <td>the match for <code>patt</code> plus all captures\n      made by <code>patt</code></td></tr>\n<tr><td><a href=\"#cap-arg\"><code>lpeg.Carg(n)</code></a></td>\n    <td>the value of the n<sup>th</sup> extra argument to\n        <code>lpeg.match</code> (matches the empty string)</td></tr>\n<tr><td><a href=\"#cap-b\"><code>lpeg.Cb(key)</code></a></td>\n    <td>the values produced by the previous\n        group capture named <code>key</code>\n        (matches the empty string)</td></tr>\n<tr><td><a href=\"#cap-cc\"><code>lpeg.Cc(values)</code></a></td>\n    <td>the given values (matches the empty string)</td></tr>\n<tr><td><a href=\"#cap-f\"><code>lpeg.Cf(patt, func)</code></a></td>\n  <td>folding capture (<em>deprecated</em>)</td></tr>\n<tr><td><a href=\"#cap-g\"><code>lpeg.Cg(patt [, key])</code></a></td>\n    <td>the values produced by <code>patt</code>,\n        optionally tagged with <code>key</code></td></tr>\n<tr><td><a href=\"#cap-p\"><code>lpeg.Cp()</code></a></td>\n    <td>the current position (matches the empty string)</td></tr>\n<tr><td><a href=\"#cap-s\"><code>lpeg.Cs(patt)</code></a></td>\n  <td>the match for <code>patt</code>\n      with the values from nested captures replacing their matches</td></tr>\n<tr><td><a href=\"#cap-t\"><code>lpeg.Ct(patt)</code></a></td>\n  <td>a table with all captures from <code>patt</code></td></tr>\n<tr><td><a href=\"#cap-string\"><code>patt / string</code></a></td>\n  <td><code>string</code>, with some marks replaced by captures\n      of <code>patt</code></td></tr>\n<tr><td><a href=\"#cap-num\"><code>patt / number</code></a></td>\n  <td>the n-th value captured by <code>patt</code>,\nor no value when <code>number</code> is zero.</td></tr>\n<tr><td><a href=\"#cap-query\"><code>patt / table</code></a></td>\n  <td><code>table[c]</code>, where <code>c</code> is the (first)\n      capture of <code>patt</code></td></tr>\n<tr><td><a href=\"#cap-func\"><code>patt / function</code></a></td>\n  <td>the returns of <code>function</code> applied to the captures\n      of <code>patt</code></td></tr>\n<tr><td><a href=\"#cap-acc\"><code>patt % function</code></a></td>\n  <td>produces no value;\n      it <em>accummulates</em> the captures from <code>patt</code>\n      into the previous capture through <code>function</code>\n      </td></tr>\n<tr><td><a href=\"#matchtime\"><code>lpeg.Cmt(patt, function)</code></a></td>\n  <td>the returns of <code>function</code> applied to the captures\n      of <code>patt</code>; the application is done at match time</td></tr>\n</tbody></table>\n\n<p>\nA capture pattern produces its values only when it succeeds.\nFor instance,\nthe pattern <code>lpeg.C(lpeg.P\"a\"^-1)</code>\nproduces the empty string when there is no <code>\"a\"</code>\n(because the pattern <code>\"a\"?</code> succeeds),\nwhile the pattern <code>lpeg.C(\"a\")^-1</code>\ndoes not produce any value when there is no <code>\"a\"</code>\n(because the pattern <code>\"a\"</code> fails).\nA pattern inside a loop or inside a recursive structure\nproduces values for each match.\n</p>\n\n<p>\nUsually,\nLPeg does not specify when (and if) it evaluates its captures.\n(As an example,\nconsider the pattern <code>lpeg.P\"a\" / func / 0</code>.\nBecause the \"division\" by 0 instructs LPeg to throw away the\nresults from the pattern,\nit is not specified whether LPeg will call <code>func</code>.)\nTherefore, captures should avoid side effects.\nMoreover,\ncaptures cannot affect the way a pattern matches a subject.\nThe only exception to this rule is the\nso-called <a href=\"#matchtime\"><em>match-time capture</em></a>.\nWhen a match-time capture matches,\nit forces the immediate evaluation of all its nested captures\nand then calls its corresponding function,\nwhich defines whether the match succeeds and also\nwhat values are produced.\n</p>\n\n<h3><a name=\"cap-c\"></a><code>lpeg.C (patt)</code></h3>\n<p>\nCreates a <em>simple capture</em>,\nwhich captures the substring of the subject that matches <code>patt</code>.\nThe captured value is a string.\nIf <code>patt</code> has other captures,\ntheir values are returned after this one.\n</p>\n\n\n<h3><a name=\"cap-arg\"></a><code>lpeg.Carg (n)</code></h3>\n<p>\nCreates an <em>argument capture</em>.\nThis pattern matches the empty string and\nproduces the value given as the n<sup>th</sup> extra\nargument given in the call to <code>lpeg.match</code>.\n</p>\n\n\n<h3><a name=\"cap-b\"></a><code>lpeg.Cb (key)</code></h3>\n<p>\nCreates a <em>back capture</em>.\nThis pattern matches the empty string and\nproduces the values produced by the <em>most recent</em>\n<a href=\"#cap-g\">group capture</a> named <code>key</code>\n(where <code>key</code> can be any Lua value).\n</p>\n\n<p>\n<em>Most recent</em> means the last\n<em>complete</em>\n<em>outermost</em>\ngroup capture with the given key.\nA <em>Complete</em> capture means that the entire pattern\ncorresponding to the capture has matched;\nin other words, the back capture is not nested inside the group.\nAn <em>Outermost</em> capture means that the capture is not inside\nanother complete capture that does not contain the back capture itself.\n</p>\n\n<p>\nIn the same way that LPeg does not specify when it evaluates captures,\nit does not specify whether it reuses\nvalues previously produced by the group\nor re-evaluates them.\n</p>\n\n<h3><a name=\"cap-cc\"></a><code>lpeg.Cc ([value, ...])</code></h3>\n<p>\nCreates a <em>constant capture</em>.\nThis pattern matches the empty string and\nproduces all given values as its captured values.\n</p>\n\n\n<h3><a name=\"cap-f\"></a><code>lpeg.Cf (patt, func)</code></h3>\n<p>\nCreates a <em>fold capture</em>.\nThis construction is deprecated;\nuse an <a href=\"#cap-acc\">accumulator pattern</a> instead.\nIn general, a fold like\n<code>lpeg.Cf(p1 * p2^0, func)</code>\ncan be translated to\n<code>(p1 * (p2 % func)^0)</code>.\n\n\n<h3><a name=\"cap-g\"></a><code>lpeg.Cg (patt [, key])</code></h3>\n<p>\nCreates a <em>group capture</em>.\nIt groups all values returned by <code>patt</code>\ninto a single capture.\nThe group may be anonymous (if no key is given)\nor named with the given key\n(which can be any non-nil Lua value).\n</p>\n\n<p>\nAn anonymous group serves to join values from several captures into\na single capture.\nA named group has a different behavior.\nIn most situations, a named group returns no values at all.\nIts values are only relevant for a following\n<a href=\"#cap-b\">back capture</a> or when used\ninside a <a href=\"#cap-t\">table capture</a>.\n</p>\n\n\n<h3><a name=\"cap-p\"></a><code>lpeg.Cp ()</code></h3>\n<p>\nCreates a <em>position capture</em>.\nIt matches the empty string and\ncaptures the position in the subject where the match occurs.\nThe captured value is a number.\n</p>\n\n\n<h3><a name=\"cap-s\"></a><code>lpeg.Cs (patt)</code></h3>\n<p>\nCreates a <em>substitution capture</em>,\nwhich captures the substring of the subject that matches <code>patt</code>,\nwith <em>substitutions</em>.\nFor any capture inside <code>patt</code> with a value,\nthe substring that matched the capture is replaced by the capture value\n(which should be a string).\nThe final captured value is the string resulting from\nall replacements.\n</p>\n\n\n<h3><a name=\"cap-t\"></a><code>lpeg.Ct (patt)</code></h3>\n<p>\nCreates a <em>table capture</em>.\nThis capture returns a table with all values from all anonymous captures\nmade by <code>patt</code> inside this table in successive integer keys,\nstarting at 1.\nMoreover,\nfor each named capture group created by <code>patt</code>,\nthe first value of the group is put into the table\nwith the group key as its key.\nThe captured value is only the table.\n</p>\n\n\n<h3><a name=\"cap-string\"></a><code>patt / string</code></h3>\n<p>\nCreates a <em>string capture</em>.\nIt creates a capture string based on <code>string</code>.\nThe captured value is a copy of <code>string</code>,\nexcept that the character <code>%</code> works as an escape character:\nany sequence in <code>string</code> of the form <code>%<em>n</em></code>,\nwith <em>n</em> between 1 and 9,\nstands for the match of the <em>n</em>-th capture in <code>patt</code>.\nThe sequence <code>%0</code> stands for the whole match.\nThe sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.\n</p>\n\n\n<h3><a name=\"cap-num\"></a><code>patt / number</code></h3>\n<p>\nCreates a <em>numbered capture</em>.\nFor a non-zero number,\nthe captured value is the n-th value\ncaptured by <code>patt</code>. \nWhen <code>number</code> is zero,\nthere are no captured values.\n</p>\n\n\n<h3><a name=\"cap-query\"></a><code>patt / table</code></h3>\n<p>\nCreates a <em>query capture</em>.\nIt indexes the given table using as key the first value captured by\n<code>patt</code>,\nor the whole match if <code>patt</code> produced no value.\nThe value at that index is the final value of the capture.\nIf the table does not have that key,\nthere is no captured value.\n</p>\n\n\n<h3><a name=\"cap-func\"></a><code>patt / function</code></h3>\n<p>\nCreates a <em>function capture</em>.\nIt calls the given function passing all captures made by\n<code>patt</code> as arguments,\nor the whole match if <code>patt</code> made no capture.\nThe values returned by the function\nare the final values of the capture.\nIn particular,\nif <code>function</code> returns no value,\nthere is no captured value.\n</p>\n\n\n<h3><a name=\"cap-acc\"></a><code>patt % function</code></h3>\n<p>\nCreates an <em>accumulator capture</em>.\nThis pattern behaves similarly to a\n<a href=\"#cap-func\">function capture</a>,\nwith the following differences:\nThe last captured value before <code>patt</code>\nis added as a first argument to the call;\nthe return of the function is adjusted to one single value;\nthat value replaces the last captured value.\nNote that the capture itself produces no values;\nit only changes the value of its previous capture.\n</p>\n\n<p>\nAs an example,\nlet us consider the problem of adding a list of numbers.\n</p>\n<pre class=\"example\">\n-- matches a numeral and captures its numerical value\nnumber = lpeg.R\"09\"^1 / tonumber\n\n-- auxiliary function to add two numbers\nfunction add (acc, newvalue) return acc + newvalue end\n\n-- matches a list of numbers, adding their values\nsum = number * (\",\" * number % add)^0\n\n-- example of use\nprint(sum:match(\"10,30,43\"))   --&gt; 83\n</pre>\n<p>\nFirst, the initial <code>number</code> captures a number;\nthat first capture will play the role of an accumulator.\nThen, each time the sequence <code>comma-number</code>\nmatches inside the loop there is an accumulator capture:\nIt calls <code>add</code> with the current value of the\naccumulator&mdash;which is the last captured value, created by the\nfirst <code>number</code>&mdash; and the value of the new number,\nand the result of the call (the sum of the two numbers)\nreplaces the value of the accumulator.\nAt the end of the match,\nthe accumulator with all sums is the final value.\n</p>\n\n<p>\nAs another example,\nconsider the following code fragment:\n</p>\n<pre class=\"example\">\nlocal name = lpeg.C(lpeg.R(\"az\")^1)\nlocal p = name * (lpeg.P(\"^\") % string.upper)^-1\nprint(p:match(\"count\"))    --&gt; count\nprint(p:match(\"count^\"))   --&gt; COUNT\n</pre>\n<p>\nIn the match against <code>\"count\"</code>,\nas there is no <code>\"^\"</code>,\nthe optional accumulator capture does not match;\nso, the match results in its sole capture, a name.\nIn the match against <code>\"count^\"</code>,\nthe accumulator capture matches,\nso the function <code>string.upper</code>\nis called with the previous captured value (created by <code>name</code>)\nplus the string <code>\"^\"</code>;\nthe function ignores its second argument and returns the first argument\nchanged to upper case;\nthat value then becomes the first and only\ncapture value created by the match.\n</p>\n\n<p>\nDue to the nature of this capture,\nyou should avoid using it in places where it is not clear\nwhat is the \"previous\" capture,\nsuch as directly nested in a <a href=\"#cap-string\">string capture</a>\nor a <a href=\"#cap-num\">numbered capture</a>.\n(Note that these captures may not need to evaluate\nall their subcaptures to compute their results.)\nMoreover, due to implementation details,\nyou should not use this capture directly nested in a\n<a href=\"#cap-s\">substitution capture</a>.\nYou should also avoid a direct nesting of this capture inside\na <a href=\"#cap-f\">folding capture</a> (deprecated),\nas the folding will try to fold each individual accumulator capture.\nA simple and effective way to avoid all these issues is\nto enclose the whole accumulation composition\n(including the capture that generates the initial value)\ninto an anonymous <a href=\"#cap-g\">group capture</a>.\n</p>\n\n\n<h3><a name=\"matchtime\"></a><code>lpeg.Cmt(patt, function)</code></h3>\n<p>\nCreates a <em>match-time capture</em>.\nUnlike all other captures,\nthis one is evaluated immediately when a match occurs\n(even if it is part of a larger pattern that fails later).\nIt forces the immediate evaluation of all its nested captures\nand then calls <code>function</code>.\n</p>\n\n<p>\nThe given function gets as arguments the entire subject,\nthe current position (after the match of <code>patt</code>),\nplus any capture values produced by <code>patt</code>.\n</p>\n\n<p>\nThe first value returned by <code>function</code>\ndefines how the match happens.\nIf the call returns a number,\nthe match succeeds\nand the returned number becomes the new current position.\n(Assuming a subject <em>s</em> and current position <em>i</em>,\nthe returned number must be in the range <em>[i, len(s) + 1]</em>.)\nIf the call returns <b>true</b>,\nthe match succeeds without consuming any input.\n(So, to return <b>true</b> is equivalent to return <em>i</em>.)\nIf the call returns <b>false</b>, <b>nil</b>, or no value,\nthe match fails.\n</p>\n\n<p>\nAny extra values returned by the function become the\nvalues produced by the capture.\n</p>\n\n\n\n\n<h2><a name=\"ex\">Some Examples</a></h2>\n\n<h3>Using a Pattern</h3>\n<p>\nThis example shows a very simple but complete program\nthat builds and uses a pattern:\n</p>\n<pre class=\"example\">\nlocal lpeg = require \"lpeg\"\n\n-- matches a word followed by end-of-string\np = lpeg.R\"az\"^1 * -1\n\nprint(p:match(\"hello\"))        --&gt; 6\nprint(lpeg.match(p, \"hello\"))  --&gt; 6\nprint(p:match(\"1 hello\"))      --&gt; nil\n</pre>\n<p>\nThe pattern is simply a sequence of one or more lower-case letters\nfollowed by the end of string (-1).\nThe program calls <code>match</code> both as a method\nand as a function.\nIn both sucessful cases,\nthe match returns \nthe index of the first character after the match,\nwhich is the string length plus one.\n</p>\n\n\n<h3>Name-value lists</h3>\n<p>\nThis example parses a list of name-value pairs and returns a table\nwith those pairs:\n</p>\n<pre class=\"example\">\nlpeg.locale(lpeg)   -- adds locale entries into 'lpeg' table\n\nlocal space = lpeg.space^0\nlocal name = lpeg.C(lpeg.alpha^1) * space\nlocal sep = lpeg.S(\",;\") * space\nlocal pair = name * \"=\" * space * name * sep^-1\nlocal list = lpeg.Ct(\"\") * (pair % rawset)^0\nt = list:match(\"a=b, c = hi; next = pi\")\n        --&gt; { a = \"b\", c = \"hi\", next = \"pi\" }\n</pre>\n<p>\nEach pair has the format <code>name = name</code> followed by\nan optional separator (a comma or a semicolon).\nThe <code>list</code> pattern then <em>folds</em> these captures.\nIt starts with an empty table,\ncreated by a table capture matching an empty string;\nthen for each a pair of names it applies <code>rawset</code>\nover the accumulator (the table) and the capture values (the pair of names).\n<code>rawset</code> returns the table itself,\nso the accumulator is always the table.\n</p>\n\n<h3>Splitting a string</h3>\n<p>\nThe following code builds a pattern that\nsplits a string using a given pattern\n<code>sep</code> as a separator:\n</p>\n<pre class=\"example\">\nfunction split (s, sep)\n  sep = lpeg.P(sep)\n  local elem = lpeg.C((1 - sep)^0)\n  local p = elem * (sep * elem)^0\n  return lpeg.match(p, s)\nend\n</pre>\n<p>\nFirst the function ensures that <code>sep</code> is a proper pattern.\nThe pattern <code>elem</code> is a repetition of zero of more\narbitrary characters as long as there is not a match against\nthe separator.\nIt also captures its match.\nThe pattern <code>p</code> matches a list of elements separated\nby <code>sep</code>.\n</p>\n\n<p>\nIf the split results in too many values,\nit may overflow the maximum number of values\nthat can be returned by a Lua function.\nTo avoid this problem,\nwe can collect these values in a table:\n</p>\n<pre class=\"example\">\nfunction split (s, sep)\n  sep = lpeg.P(sep)\n  local elem = lpeg.C((1 - sep)^0)\n  local p = lpeg.Ct(elem * (sep * elem)^0)   -- make a table capture\n  return lpeg.match(p, s)\nend\n</pre>\n\n\n<h3>Searching for a pattern</h3>\n<p>\nThe primitive <code>match</code> works only in anchored mode.\nIf we want to find a pattern anywhere in a string,\nwe must write a pattern that matches anywhere.\n</p>\n\n<p>\nBecause patterns are composable,\nwe can write a function that,\ngiven any arbitrary pattern <code>p</code>,\nreturns a new pattern that searches for <code>p</code>\nanywhere in a string.\nThere are several ways to do the search.\nOne way is like this:\n</p>\n<pre class=\"example\">\nfunction anywhere (p)\n  return lpeg.P{ p + 1 * lpeg.V(1) }\nend\n</pre>\n<p>\nThis grammar has a straight reading:\nits sole rule matches <code>p</code> or skips one character and tries again.\n</p>\n\n<p>\nIf we want to know where the pattern is in the string\n(instead of knowing only that it is there somewhere),\nwe can add position captures to the pattern:\n</p>\n<pre class=\"example\">\nlocal Cp = lpeg.Cp()\nfunction anywhere (p)\n  return lpeg.P{ Cp * p * Cp + 1 * lpeg.V(1) }\nend\n\nprint(anywhere(\"world\"):match(\"hello world!\"))   --&gt; 7   12\n</pre>\n\n<p>\nAnother option for the search is like this:\n</p>\n<pre class=\"example\">\nlocal Cp = lpeg.Cp()\nfunction anywhere (p)\n  return (1 - lpeg.P(p))^0 * Cp * p * Cp\nend\n</pre>\n<p>\nAgain the pattern has a straight reading:\nit skips as many characters as possible while not matching <code>p</code>,\nand then matches <code>p</code> plus appropriate captures.\n</p>\n\n<p>\nIf we want to look for a pattern only at word boundaries,\nwe can use the following transformer:\n</p>\n\n<pre class=\"example\">\nlocal t = lpeg.locale()\n\nfunction atwordboundary (p)\n  return lpeg.P{\n    [1] = p + t.alpha^0 * (1 - t.alpha)^1 * lpeg.V(1)\n  }\nend\n</pre>\n\n\n<h3><a name=\"balanced\"></a>Balanced parentheses</h3>\n<p>\nThe following pattern matches only strings with balanced parentheses:\n</p>\n<pre class=\"example\">\nb = lpeg.P{ \"(\" * ((1 - lpeg.S\"()\") + lpeg.V(1))^0 * \")\" }\n</pre>\n<p>\nReading the first (and only) rule of the given grammar,\nwe have that a balanced string is\nan open parenthesis,\nfollowed by zero or more repetitions of either\na non-parenthesis character or\na balanced string (<code>lpeg.V(1)</code>),\nfollowed by a closing parenthesis.\n</p>\n\n\n<h3>Global substitution</h3>\n<p>\nThe next example does a job somewhat similar to <code>string.gsub</code>.\nIt receives a pattern and a replacement value,\nand substitutes the replacement value for all occurrences of the pattern\nin a given string:\n</p>\n<pre class=\"example\">\nfunction gsub (s, patt, repl)\n  patt = lpeg.P(patt)\n  patt = lpeg.Cs((patt / repl + 1)^0)\n  return lpeg.match(patt, s)\nend\n</pre>\n<p>\nAs in <code>string.gsub</code>,\nthe replacement value can be a string,\na function, or a table.\n</p>\n\n\n<h3><a name=\"CSV\"></a>Comma-Separated Values (CSV)</h3>\n<p>\nThis example breaks a string into comma-separated values,\nreturning all fields:\n</p>\n<pre class=\"example\">\nlocal field = '\"' * lpeg.Cs(((lpeg.P(1) - '\"') + lpeg.P'\"\"' / '\"')^0) * '\"' +\n                    lpeg.C((1 - lpeg.S',\\n\"')^0)\n\nlocal record = field * (',' * field)^0 * (lpeg.P'\\n' + -1)\n\nfunction csv (s)\n  return lpeg.match(record, s)\nend\n</pre>\n<p>\nA field is either a quoted field\n(which may contain any character except an individual quote,\nwhich may be written as two quotes that are replaced by one)\nor an unquoted field\n(which cannot contain commas, newlines, or quotes).\nA record is a list of fields separated by commas,\nending with a newline or the string end (-1).\n</p>\n\n<p>\nAs it is,\nthe previous pattern returns each field as a separated result.\nIf we add a table capture in the definition of <code>record</code>,\nthe pattern will return instead a single table\ncontaining all fields:\n</p>\n<pre>\nlocal record = lpeg.Ct(field * (',' * field)^0) * (lpeg.P'\\n' + -1)\n</pre>\n\n\n<h3>Lua's long strings</h3>\n<p>\nA long string in Lua starts with the pattern <code>[=*[</code>\nand ends at the first occurrence of <code>]=*]</code> with\nexactly the same number of equal signs.\nIf the opening brackets are followed by a newline,\nthis newline is discarded\n(that is, it is not part of the string).\n</p>\n\n<p>\nTo match a long string in Lua,\nthe pattern must capture the first repetition of equal signs and then,\nwhenever it finds a candidate for closing the string,\ncheck whether it has the same number of equal signs.\n</p>\n\n<pre class=\"example\">\nequals = lpeg.P\"=\"^0\nopen = \"[\" * lpeg.Cg(equals, \"init\") * \"[\" * lpeg.P\"\\n\"^-1\nclose = \"]\" * lpeg.C(equals) * \"]\"\ncloseeq = lpeg.Cmt(close * lpeg.Cb(\"init\"), function (s, i, a, b) return a == b end)\nstring = open * lpeg.C((lpeg.P(1) - closeeq)^0) * close / 1\n</pre>\n\n<p>\nThe <code>open</code> pattern matches <code>[=*[</code>,\ncapturing the repetitions of equal signs in a group named <code>init</code>;\nit also discharges an optional newline, if present.\nThe <code>close</code> pattern matches <code>]=*]</code>,\nalso capturing the repetitions of equal signs.\nThe <code>closeeq</code> pattern first matches <code>close</code>;\nthen it uses a back capture to recover the capture made\nby the previous <code>open</code>,\nwhich is named <code>init</code>;\nfinally it uses a match-time capture to check\nwhether both captures are equal.\nThe <code>string</code> pattern starts with an <code>open</code>,\nthen it goes as far as possible until matching <code>closeeq</code>,\nand then matches the final <code>close</code>.\nThe final numbered capture simply discards\nthe capture made by <code>close</code>.\n</p>\n\n\n<h3>Arithmetic expressions</h3>\n<p>\nThis example is a complete parser and evaluator for simple\narithmetic expressions.\nWe write it in two styles.\nThe first approach first builds a syntax tree and then\ntraverses this tree to compute the expression value:\n</p>\n<pre class=\"example\">\n-- Lexical Elements\nlocal Space = lpeg.S(\" \\n\\t\")^0\nlocal Number = lpeg.C(lpeg.P\"-\"^-1 * lpeg.R(\"09\")^1) * Space\nlocal TermOp = lpeg.C(lpeg.S(\"+-\")) * Space\nlocal FactorOp = lpeg.C(lpeg.S(\"*/\")) * Space\nlocal Open = \"(\" * Space\nlocal Close = \")\" * Space\n\n-- Grammar\nlocal Exp, Term, Factor = lpeg.V\"Exp\", lpeg.V\"Term\", lpeg.V\"Factor\"\nG = lpeg.P{ Exp,\n  Exp = lpeg.Ct(Term * (TermOp * Term)^0);\n  Term = lpeg.Ct(Factor * (FactorOp * Factor)^0);\n  Factor = Number + Open * Exp * Close;\n}\n\nG = Space * G * -1\n\n-- Evaluator\nfunction eval (x)\n  if type(x) == \"string\" then\n    return tonumber(x)\n  else\n    local op1 = eval(x[1])\n    for i = 2, #x, 2 do\n      local op = x[i]\n      local op2 = eval(x[i + 1])\n      if (op == \"+\") then op1 = op1 + op2\n      elseif (op == \"-\") then op1 = op1 - op2\n      elseif (op == \"*\") then op1 = op1 * op2\n      elseif (op == \"/\") then op1 = op1 / op2\n      end\n    end\n    return op1\n  end\nend\n\n-- Parser/Evaluator\nfunction evalExp (s)\n  local t = lpeg.match(G, s)\n  if not t then error(\"syntax error\", 2) end\n  return eval(t)\nend\n\n-- small example\nprint(evalExp\"3 + 5*9 / (1+1) - 12\")   --&gt; 13.5\n</pre>\n\n<p>\nThe second style computes the expression value on the fly,\nwithout building the syntax tree.\nThe following grammar takes this approach.\n(It assumes the same lexical elements as before.)\n</p>\n<pre class=\"example\">\n-- Auxiliary function\nfunction eval (v1, op, v2)\n  if (op == \"+\") then return v1 + v2\n  elseif (op == \"-\") then return v1 - v2\n  elseif (op == \"*\") then return v1 * v2\n  elseif (op == \"/\") then return v1 / v2\n  end\nend\n\n-- Grammar\nlocal V = lpeg.V\nG = lpeg.P{ \"Exp\",\n  Exp = V\"Term\" * (TermOp * V\"Term\" % eval)^0;\n  Term = V\"Factor\" * (FactorOp * V\"Factor\" % eval)^0;\n  Factor = Number / tonumber + Open * V\"Exp\" * Close;\n}\n\n-- small example\nprint(lpeg.match(G, \"3 + 5*9 / (1+1) - 12\"))   --&gt; 13.5\n</pre>\n<p>\nNote the use of the accumulator capture.\nTo compute the value of an expression,\nthe accumulator starts with the value of the first term,\nand then applies <code>eval</code> over\nthe accumulator, the operator,\nand the new term for each repetition.\n</p>\n\n\n\n<h2><a name=\"download\"></a>Download</h2>\n\n<p>LPeg \n<a href=\"//www.inf.puc-rio.br/~roberto/lpeg/lpeg-1.1.0.tar.gz\">source code</a>.</p>\n\n<p>\nProbably, the easiest way to install LPeg is with\n<a href=\"//luarocks.org/\">LuaRocks</a>.\nIf you have LuaRocks installed,\nthe following command is all you need to install LPeg:\n<pre>$ luarocks install lpeg</pre>\n\n\n<h2><a name=\"license\">License</a></h2>\n\n<p>\nCopyright &copy; 2007-2023 Lua.org, PUC-Rio.\n</p>\n<p>\nPermission is hereby granted, free of charge,\nto any person obtaining a copy of this software and\nassociated documentation files (the \"Software\"),\nto deal in the Software without restriction,\nincluding without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software,\nand to permit persons to whom the Software is\nfurnished to do so,\nsubject to the following conditions:\n</p>\n\n<p>\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions of the Software.\n</p>\n\n<p>\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n</p>\n\n</div> <!-- id=\"content\" -->\n\n</div> <!-- id=\"main\" -->\n\n</div> <!-- id=\"container\" -->\n\n</body>\n</html> \n"
  },
  {
    "path": "3rd/lpeg/lpprint.c",
    "content": "\n#include <ctype.h>\n#include <limits.h>\n#include <stdio.h>\n\n\n#include \"lptypes.h\"\n#include \"lpprint.h\"\n#include \"lpcode.h\"\n\n\n#if defined(LPEG_DEBUG)\n\n/*\n** {======================================================\n** Printing patterns (for debugging)\n** =======================================================\n*/\n\n\nvoid printcharset (const byte *st) {\n  int i;\n  printf(\"[\");\n  for (i = 0; i <= UCHAR_MAX; i++) {\n    int first = i;\n    while (i <= UCHAR_MAX && testchar(st, i)) i++;\n    if (i - 1 == first)  /* unary range? */\n      printf(\"(%02x)\", first);\n    else if (i - 1 > first)  /* non-empty range? */\n      printf(\"(%02x-%02x)\", first, i - 1);\n  }\n  printf(\"]\");\n}\n\n\nstatic void printIcharset (const Instruction *inst, const byte *buff) {\n  byte cs[CHARSETSIZE];\n  int i;\n  printf(\"(%02x-%d) \", inst->i.aux2.set.offset, inst->i.aux2.set.size);\n  clearset(cs);\n  for (i = 0; i < CHARSETSIZE * 8; i++) {\n    if (charinset(inst, buff, i))\n      setchar(cs, i);\n  }\n  printcharset(cs);\n}\n\n\nstatic void printTcharset (TTree *tree) {\n  byte cs[CHARSETSIZE];\n  int i;\n  printf(\"(%02x-%d) \", tree->u.set.offset, tree->u.set.size);\n  fillset(cs, tree->u.set.deflt);\n  for (i = 0; i < tree->u.set.size; i++)\n    cs[tree->u.set.offset + i] = treebuffer(tree)[i];\n  printcharset(cs);\n}\n\n\nstatic const char *capkind (int kind) {\n  const char *const modes[] = {\n    \"close\", \"position\", \"constant\", \"backref\",\n    \"argument\", \"simple\", \"table\", \"function\", \"accumulator\",\n    \"query\", \"string\", \"num\", \"substitution\", \"fold\",\n    \"runtime\", \"group\"};\n  return modes[kind];\n}\n\n\nstatic void printjmp (const Instruction *op, const Instruction *p) {\n  printf(\"-> %d\", (int)(p + (p + 1)->offset - op));\n}\n\n\nvoid printinst (const Instruction *op, const Instruction *p) {\n  const char *const names[] = {\n    \"any\", \"char\", \"set\",\n    \"testany\", \"testchar\", \"testset\",\n    \"span\", \"utf-range\", \"behind\",\n    \"ret\", \"end\",\n    \"choice\", \"jmp\", \"call\", \"open_call\",\n    \"commit\", \"partial_commit\", \"back_commit\", \"failtwice\", \"fail\", \"giveup\",\n     \"fullcapture\", \"opencapture\", \"closecapture\", \"closeruntime\",\n     \"--\"\n  };\n  printf(\"%02ld: %s \", (long)(p - op), names[p->i.code]);\n  switch ((Opcode)p->i.code) {\n    case IChar: {\n      printf(\"'%c' (%02x)\", p->i.aux1, p->i.aux1);\n      break;\n    }\n    case ITestChar: {\n      printf(\"'%c' (%02x)\", p->i.aux1, p->i.aux1); printjmp(op, p);\n      break;\n    }\n    case IUTFR: {\n      printf(\"%d - %d\", p[1].offset, utf_to(p));\n      break;\n    }\n    case IFullCapture: {\n      printf(\"%s (size = %d)  (idx = %d)\",\n             capkind(getkind(p)), getoff(p), p->i.aux2.key);\n      break;\n    }\n    case IOpenCapture: {\n      printf(\"%s (idx = %d)\", capkind(getkind(p)), p->i.aux2.key);\n      break;\n    }\n    case ISet: {\n      printIcharset(p, (p+1)->buff);\n      break;\n    }\n    case ITestSet: {\n      printIcharset(p, (p+2)->buff); printjmp(op, p);\n      break;\n    }\n    case ISpan: {\n      printIcharset(p, (p+1)->buff);\n      break;\n    }\n    case IOpenCall: {\n      printf(\"-> %d\", (p + 1)->offset);\n      break;\n    }\n    case IBehind: {\n      printf(\"%d\", p->i.aux1);\n      break;\n    }\n    case IJmp: case ICall: case ICommit: case IChoice:\n    case IPartialCommit: case IBackCommit: case ITestAny: {\n      printjmp(op, p);\n      break;\n    }\n    default: break;\n  }\n  printf(\"\\n\");\n}\n\n\nvoid printpatt (Instruction *p) {\n  Instruction *op = p;\n  uint n = op[-1].codesize - 1;\n  while (p < op + n) {\n    printinst(op, p);\n    p += sizei(p);\n  }\n}\n\n\nstatic void printcap (Capture *cap, int ident) {\n  while (ident--) printf(\" \");\n  printf(\"%s (idx: %d - size: %d) -> %lu  (%p)\\n\",\n         capkind(cap->kind), cap->idx, cap->siz, (long)cap->index, (void*)cap);\n}\n\n\n/*\n** Print a capture and its nested captures\n*/\nstatic Capture *printcap2close (Capture *cap, int ident) {\n  Capture *head = cap++;\n  printcap(head, ident);  /* print head capture */\n  while (capinside(head, cap))\n    cap = printcap2close(cap, ident + 2);  /* print nested captures */\n  if (isopencap(head)) {\n    assert(isclosecap(cap));\n    printcap(cap++, ident);  /* print and skip close capture */\n  }\n  return cap;\n}\n\n\nvoid printcaplist (Capture *cap) {\n  {  /* for debugging, print first a raw list of captures */\n    Capture *c = cap;\n    while (c->index != MAXINDT) { printcap(c, 0); c++; }\n  }\n  printf(\">======\\n\");\n  while (!isclosecap(cap))\n    cap = printcap2close(cap, 0);\n  printf(\"=======\\n\");\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Printing trees (for debugging)\n** =======================================================\n*/\n\nstatic const char *tagnames[] = {\n  \"char\", \"set\", \"any\",\n  \"true\", \"false\", \"utf8.range\",\n  \"rep\",\n  \"seq\", \"choice\",\n  \"not\", \"and\",\n  \"call\", \"opencall\", \"rule\", \"xinfo\", \"grammar\",\n  \"behind\",\n  \"capture\", \"run-time\"\n};\n\n\nvoid printtree (TTree *tree, int ident) {\n  int i;\n  int sibs = numsiblings[tree->tag];\n  for (i = 0; i < ident; i++) printf(\" \");\n  printf(\"%s\", tagnames[tree->tag]);\n  switch (tree->tag) {\n    case TChar: {\n      int c = tree->u.n;\n      if (isprint(c))\n        printf(\" '%c'\\n\", c);\n      else\n        printf(\" (%02X)\\n\", c);\n      break;\n    }\n    case TSet: {\n      printTcharset(tree);\n      printf(\"\\n\");\n      break;\n    }\n    case TUTFR: {\n      assert(sib1(tree)->tag == TXInfo);\n      printf(\" %d (%02x %d) - %d (%02x %d) \\n\",\n        tree->u.n, tree->key, tree->cap,\n        sib1(tree)->u.n, sib1(tree)->key, sib1(tree)->cap);\n      break;\n    }\n    case TOpenCall: case TCall: {\n      assert(sib1(sib2(tree))->tag == TXInfo);\n      printf(\" key: %d  (rule: %d)\\n\", tree->key, sib1(sib2(tree))->u.n);\n      break;\n    }\n    case TBehind: {\n      printf(\" %d\\n\", tree->u.n);\n      break;\n    }\n    case TCapture: {\n      printf(\" kind: '%s'  key: %d\\n\", capkind(tree->cap), tree->key);\n      break;\n    }\n    case TRule: {\n      printf(\" key: %d\\n\", tree->key);\n      sibs = 1;  /* do not print 'sib2' (next rule) as a sibling */\n      break;\n    }\n    case TXInfo: {\n      printf(\" n: %d\\n\", tree->u.n);\n      break;\n    }\n    case TGrammar: {\n      TTree *rule = sib1(tree);\n      printf(\" %d\\n\", tree->u.n);  /* number of rules */\n      for (i = 0; i < tree->u.n; i++) {\n        printtree(rule, ident + 2);\n        rule = sib2(rule);\n      }\n      assert(rule->tag == TTrue);  /* sentinel */\n      sibs = 0;  /* siblings already handled */\n      break;\n    }\n    default:\n      printf(\"\\n\");\n      break;\n  }\n  if (sibs >= 1) {\n    printtree(sib1(tree), ident + 2);\n    if (sibs >= 2)\n      printtree(sib2(tree), ident + 2);\n  }\n}\n\n\nvoid printktable (lua_State *L, int idx) {\n  int n, i;\n  lua_getuservalue(L, idx);\n  if (lua_isnil(L, -1))  /* no ktable? */\n    return;\n  n = lua_rawlen(L, -1);\n  printf(\"[\");\n  for (i = 1; i <= n; i++) {\n    printf(\"%d = \", i);\n    lua_rawgeti(L, -1, i);\n    if (lua_isstring(L, -1))\n      printf(\"%s  \", lua_tostring(L, -1));\n    else\n      printf(\"%s  \", lua_typename(L, lua_type(L, -1)));\n    lua_pop(L, 1);\n  }\n  printf(\"]\\n\");\n  /* leave ktable at the stack */\n}\n\n/* }====================================================== */\n\n#endif\n"
  },
  {
    "path": "3rd/lpeg/lpprint.h",
    "content": "\n#if !defined(lpprint_h)\n#define lpprint_h\n\n\n#include \"lptree.h\"\n#include \"lpvm.h\"\n\n\n#if defined(LPEG_DEBUG)\n\nvoid printpatt (Instruction *p);\nvoid printtree (TTree *tree, int ident);\nvoid printktable (lua_State *L, int idx);\nvoid printcharset (const byte *st);\nvoid printcaplist (Capture *cap);\nvoid printinst (const Instruction *op, const Instruction *p);\n\n#else\n\n#define printktable(L,idx)  \\\n\tluaL_error(L, \"function only implemented in debug mode\")\n#define printtree(tree,i)  \\\n\tluaL_error(L, \"function only implemented in debug mode\")\n#define printpatt(p)  \\\n\tluaL_error(L, \"function only implemented in debug mode\")\n\n#endif\n\n\n#endif\n\n"
  },
  {
    "path": "3rd/lpeg/lptree.c",
    "content": "\n#include <ctype.h>\n#include <limits.h>\n#include <string.h>\n\n\n#include \"lua.h\"\n#include \"lauxlib.h\"\n\n#include \"lptypes.h\"\n#include \"lpcap.h\"\n#include \"lpcode.h\"\n#include \"lpprint.h\"\n#include \"lptree.h\"\n#include \"lpcset.h\"\n\n\n/* number of siblings for each tree */\nconst byte numsiblings[] = {\n  0, 0, 0,\t/* char, set, any */\n  0, 0, 0,\t/* true, false, utf-range */\n  1,\t\t/* acc */\n  2, 2,\t\t/* seq, choice */\n  1, 1,\t\t/* not, and */\n  0, 0, 2, 1, 1,  /* call, opencall, rule, prerule, grammar */\n  1,  /* behind */\n  1, 1  /* capture, runtime capture */\n};\n\n\nstatic TTree *newgrammar (lua_State *L, int arg);\n\n\n/*\n** returns a reasonable name for value at index 'idx' on the stack\n*/\nstatic const char *val2str (lua_State *L, int idx) {\n  const char *k = lua_tostring(L, idx);\n  if (k != NULL)\n    return lua_pushfstring(L, \"%s\", k);\n  else\n    return lua_pushfstring(L, \"(a %s)\", luaL_typename(L, idx));\n}\n\n\n/*\n** Fix a TOpenCall into a TCall node, using table 'postable' to\n** translate a key to its rule address in the tree. Raises an\n** error if key does not exist.\n*/\nstatic void fixonecall (lua_State *L, int postable, TTree *g, TTree *t) {\n  int n;\n  lua_rawgeti(L, -1, t->key);  /* get rule's name */\n  lua_gettable(L, postable);  /* query name in position table */\n  n = lua_tonumber(L, -1);  /* get (absolute) position */\n  lua_pop(L, 1);  /* remove position */\n  if (n == 0) {  /* no position? */\n    lua_rawgeti(L, -1, t->key);  /* get rule's name again */\n    luaL_error(L, \"rule '%s' undefined in given grammar\", val2str(L, -1));\n  }\n  t->tag = TCall;\n  t->u.ps = n - (t - g);  /* position relative to node */\n  assert(sib2(t)->tag == TRule);\n  sib2(t)->key = t->key;  /* fix rule's key */\n}\n\n\n/*\n** Transform left associative constructions into right\n** associative ones, for sequence and choice; that is:\n** (t11 + t12) + t2  =>  t11 + (t12 + t2)\n** (t11 * t12) * t2  =>  t11 * (t12 * t2)\n** (that is, Op (Op t11 t12) t2 => Op t11 (Op t12 t2))\n*/\nstatic void correctassociativity (TTree *tree) {\n  TTree *t1 = sib1(tree);\n  assert(tree->tag == TChoice || tree->tag == TSeq);\n  while (t1->tag == tree->tag) {\n    int n1size = tree->u.ps - 1;  /* t1 == Op t11 t12 */\n    int n11size = t1->u.ps - 1;\n    int n12size = n1size - n11size - 1;\n    memmove(sib1(tree), sib1(t1), n11size * sizeof(TTree)); /* move t11 */\n    tree->u.ps = n11size + 1;\n    sib2(tree)->tag = tree->tag;\n    sib2(tree)->u.ps = n12size + 1;\n  }\n}\n\n\n/*\n** Make final adjustments in a tree. Fix open calls in tree 't',\n** making them refer to their respective rules or raising appropriate\n** errors (if not inside a grammar). Correct associativity of associative\n** constructions (making them right associative). Assume that tree's\n** ktable is at the top of the stack (for error messages).\n*/\nstatic void finalfix (lua_State *L, int postable, TTree *g, TTree *t) {\n tailcall:\n  switch (t->tag) {\n    case TGrammar:  /* subgrammars were already fixed */\n      return;\n    case TOpenCall: {\n      if (g != NULL)  /* inside a grammar? */\n        fixonecall(L, postable, g, t);\n      else {  /* open call outside grammar */\n        lua_rawgeti(L, -1, t->key);\n        luaL_error(L, \"rule '%s' used outside a grammar\", val2str(L, -1));\n      }\n      break;\n    }\n    case TSeq: case TChoice:\n      correctassociativity(t);\n      break;\n  }\n  switch (numsiblings[t->tag]) {\n    case 1: /* finalfix(L, postable, g, sib1(t)); */\n      t = sib1(t); goto tailcall;\n    case 2:\n      finalfix(L, postable, g, sib1(t));\n      t = sib2(t); goto tailcall;  /* finalfix(L, postable, g, sib2(t)); */\n    default: assert(numsiblings[t->tag] == 0); break;\n  }\n}\n\n\n\n/*\n** {===================================================================\n** KTable manipulation\n**\n** - The ktable of a pattern 'p' can be shared by other patterns that\n** contain 'p' and no other constants. Because of this sharing, we\n** should not add elements to a 'ktable' unless it was freshly created\n** for the new pattern.\n**\n** - The maximum index in a ktable is USHRT_MAX, because trees and\n** patterns use unsigned shorts to store those indices.\n** ====================================================================\n*/\n\n/*\n** Create a new 'ktable' to the pattern at the top of the stack.\n*/\nstatic void newktable (lua_State *L, int n) {\n  lua_createtable(L, n, 0);  /* create a fresh table */\n  lua_setuservalue(L, -2);  /* set it as 'ktable' for pattern */\n}\n\n\n/*\n** Add element 'idx' to 'ktable' of pattern at the top of the stack;\n** Return index of new element.\n** If new element is nil, does not add it to table (as it would be\n** useless) and returns 0, as ktable[0] is always nil.\n*/\nstatic int addtoktable (lua_State *L, int idx) {\n  if (lua_isnil(L, idx))  /* nil value? */\n    return 0;\n  else {\n    int n;\n    lua_getuservalue(L, -1);  /* get ktable from pattern */\n    n = lua_rawlen(L, -1);\n    if (n >= USHRT_MAX)\n      luaL_error(L, \"too many Lua values in pattern\");\n    lua_pushvalue(L, idx);  /* element to be added */\n    lua_rawseti(L, -2, ++n);\n    lua_pop(L, 1);  /* remove 'ktable' */\n    return n;\n  }\n}\n\n\n/*\n** Return the number of elements in the ktable at 'idx'.\n** In Lua 5.2/5.3, default \"environment\" for patterns is nil, not\n** a table. Treat it as an empty table. In Lua 5.1, assumes that\n** the environment has no numeric indices (len == 0)\n*/\nstatic int ktablelen (lua_State *L, int idx) {\n  if (!lua_istable(L, idx)) return 0;\n  else return lua_rawlen(L, idx);\n}\n\n\n/*\n** Concatentate the contents of table 'idx1' into table 'idx2'.\n** (Assume that both indices are negative.)\n** Return the original length of table 'idx2' (or 0, if no\n** element was added, as there is no need to correct any index).\n*/\nstatic int concattable (lua_State *L, int idx1, int idx2) {\n  int i;\n  int n1 = ktablelen(L, idx1);\n  int n2 = ktablelen(L, idx2);\n  if (n1 + n2 > USHRT_MAX)\n    luaL_error(L, \"too many Lua values in pattern\");\n  if (n1 == 0) return 0;  /* nothing to correct */\n  for (i = 1; i <= n1; i++) {\n    lua_rawgeti(L, idx1, i);\n    lua_rawseti(L, idx2 - 1, n2 + i);  /* correct 'idx2' */\n  }\n  return n2;\n}\n\n\n/*\n** When joining 'ktables', constants from one of the subpatterns must\n** be renumbered; 'correctkeys' corrects their indices (adding 'n'\n** to each of them)\n*/\nstatic void correctkeys (TTree *tree, int n) {\n  if (n == 0) return;  /* no correction? */\n tailcall:\n  switch (tree->tag) {\n    case TOpenCall: case TCall: case TRunTime: case TRule: {\n      if (tree->key > 0)\n        tree->key += n;\n      break;\n    }\n    case TCapture: {\n      if (tree->key > 0 && tree->cap != Carg && tree->cap != Cnum)\n        tree->key += n;\n      break;\n    }\n    default: break;\n  }\n  switch (numsiblings[tree->tag]) {\n    case 1:  /* correctkeys(sib1(tree), n); */\n      tree = sib1(tree); goto tailcall;\n    case 2:\n      correctkeys(sib1(tree), n);\n      tree = sib2(tree); goto tailcall;  /* correctkeys(sib2(tree), n); */\n    default: assert(numsiblings[tree->tag] == 0); break;\n  }\n}\n\n\n/*\n** Join the ktables from p1 and p2 the ktable for the new pattern at the\n** top of the stack, reusing them when possible.\n*/\nstatic void joinktables (lua_State *L, int p1, TTree *t2, int p2) {\n  int n1, n2;\n  lua_getuservalue(L, p1);  /* get ktables */\n  lua_getuservalue(L, p2);\n  n1 = ktablelen(L, -2);\n  n2 = ktablelen(L, -1);\n  if (n1 == 0 && n2 == 0)  /* are both tables empty? */\n    lua_pop(L, 2);  /* nothing to be done; pop tables */\n  else if (n2 == 0 || lp_equal(L, -2, -1)) {  /* 2nd table empty or equal? */\n    lua_pop(L, 1);  /* pop 2nd table */\n    lua_setuservalue(L, -2);  /* set 1st ktable into new pattern */\n  }\n  else if (n1 == 0) {  /* first table is empty? */\n    lua_setuservalue(L, -3);  /* set 2nd table into new pattern */\n    lua_pop(L, 1);  /* pop 1st table */\n  }\n  else {\n    lua_createtable(L, n1 + n2, 0);  /* create ktable for new pattern */\n    /* stack: new p; ktable p1; ktable p2; new ktable */\n    concattable(L, -3, -1);  /* from p1 into new ktable */\n    concattable(L, -2, -1);  /* from p2 into new ktable */\n    lua_setuservalue(L, -4);  /* new ktable becomes 'p' environment */\n    lua_pop(L, 2);  /* pop other ktables */\n    correctkeys(t2, n1);  /* correction for indices from p2 */\n  }\n}\n\n\n/*\n** copy 'ktable' of element 'idx' to new tree (on top of stack)\n*/\nstatic void copyktable (lua_State *L, int idx) {\n  lua_getuservalue(L, idx);\n  lua_setuservalue(L, -2);\n}\n\n\n/*\n** merge 'ktable' from 'stree' at stack index 'idx' into 'ktable'\n** from tree at the top of the stack, and correct corresponding\n** tree.\n*/\nstatic void mergektable (lua_State *L, int idx, TTree *stree) {\n  int n;\n  lua_getuservalue(L, -1);  /* get ktables */\n  lua_getuservalue(L, idx);\n  n = concattable(L, -1, -2);\n  lua_pop(L, 2);  /* remove both ktables */\n  correctkeys(stree, n);\n}\n\n\n/*\n** Create a new 'ktable' to the pattern at the top of the stack, adding\n** all elements from pattern 'p' (if not 0) plus element 'idx' to it.\n** Return index of new element.\n*/\nstatic int addtonewktable (lua_State *L, int p, int idx) {\n  newktable(L, 1);\n  if (p)\n    mergektable(L, p, NULL);\n  return addtoktable(L, idx);\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Tree generation\n** =======================================================\n*/\n\n/*\n** In 5.2, could use 'luaL_testudata'...\n*/\nstatic int testpattern (lua_State *L, int idx) {\n  if (lua_touserdata(L, idx)) {  /* value is a userdata? */\n    if (lua_getmetatable(L, idx)) {  /* does it have a metatable? */\n      luaL_getmetatable(L, PATTERN_T);\n      if (lua_rawequal(L, -1, -2)) {  /* does it have the correct mt? */\n        lua_pop(L, 2);  /* remove both metatables */\n        return 1;\n      }\n    }\n  }\n  return 0;\n}\n\n\nstatic Pattern *getpattern (lua_State *L, int idx) {\n  return (Pattern *)luaL_checkudata(L, idx, PATTERN_T);\n}\n\n\nstatic int getsize (lua_State *L, int idx) {\n  return (lua_rawlen(L, idx) - offsetof(Pattern, tree)) / sizeof(TTree);\n}\n\n\nstatic TTree *gettree (lua_State *L, int idx, int *len) {\n  Pattern *p = getpattern(L, idx);\n  if (len)\n    *len = getsize(L, idx);\n  return p->tree;\n}\n\n\n/*\n** create a pattern followed by a tree with 'len' nodes. Set its\n** uservalue (the 'ktable') equal to its metatable. (It could be any\n** empty sequence; the metatable is at hand here, so we use it.)\n*/\nstatic TTree *newtree (lua_State *L, int len) {\n  size_t size = offsetof(Pattern, tree) + len * sizeof(TTree);\n  Pattern *p = (Pattern *)lua_newuserdata(L, size);\n  luaL_getmetatable(L, PATTERN_T);\n  lua_pushvalue(L, -1);\n  lua_setuservalue(L, -3);\n  lua_setmetatable(L, -2);\n  p->code = NULL;\n  return p->tree;\n}\n\n\nstatic TTree *newleaf (lua_State *L, int tag) {\n  TTree *tree = newtree(L, 1);\n  tree->tag = tag;\n  return tree;\n}\n\n\n/*\n** Create a tree for a charset, optimizing for special cases: empty set,\n** full set, and singleton set.\n*/\nstatic TTree *newcharset (lua_State *L, byte *cs) {\n  charsetinfo info;\n  Opcode op = charsettype(cs, &info);\n  switch (op) {\n    case IFail: return newleaf(L, TFalse);  /* empty set */\n    case IAny: return newleaf(L, TAny);  /* full set */\n    case IChar: {  /* singleton set */\n      TTree *tree =newleaf(L, TChar);\n      tree->u.n = info.offset;\n      return tree;\n    }\n    default: {  /* regular set */\n      int i;\n      int bsize =  /* tree size in bytes */\n                  (int)offsetof(TTree, u.set.bitmap) + info.size;\n      TTree *tree = newtree(L, bytes2slots(bsize));\n      assert(op == ISet);\n      tree->tag = TSet;\n      tree->u.set.offset = info.offset;\n      tree->u.set.size = info.size;\n      tree->u.set.deflt = info.deflt;\n      for (i = 0; i < info.size; i++) {\n        assert(&treebuffer(tree)[i] < (byte*)tree + bsize);\n        treebuffer(tree)[i] = cs[info.offset + i];\n      }\n      return tree;\n    }\n  }\n}\n\n\n/*\n** Add to tree a sequence where first sibling is 'sib' (with size\n** 'sibsize'); return position for second sibling.\n*/\nstatic TTree *seqaux (TTree *tree, TTree *sib, int sibsize) {\n  tree->tag = TSeq; tree->u.ps = sibsize + 1;\n  memcpy(sib1(tree), sib, sibsize * sizeof(TTree));\n  return sib2(tree);\n}\n\n\n/*\n** Build a sequence of 'n' nodes, each with tag 'tag' and 'u.n' got\n** from the array 's' (or 0 if array is NULL). (TSeq is binary, so it\n** must build a sequence of sequence of sequence...)\n*/\nstatic void fillseq (TTree *tree, int tag, int n, const char *s) {\n  int i;\n  for (i = 0; i < n - 1; i++) {  /* initial n-1 copies of Seq tag; Seq ... */\n    tree->tag = TSeq; tree->u.ps = 2;\n    sib1(tree)->tag = tag;\n    sib1(tree)->u.n = s ? (byte)s[i] : 0;\n    tree = sib2(tree);\n  }\n  tree->tag = tag;  /* last one does not need TSeq */\n  tree->u.n = s ? (byte)s[i] : 0;\n}\n\n\n/*\n** Numbers as patterns:\n** 0 == true (always match); n == TAny repeated 'n' times;\n** -n == not (TAny repeated 'n' times)\n*/\nstatic TTree *numtree (lua_State *L, int n) {\n  if (n == 0)\n    return newleaf(L, TTrue);\n  else {\n    TTree *tree, *nd;\n    if (n > 0)\n      tree = nd = newtree(L, 2 * n - 1);\n    else {  /* negative: code it as !(-n) */\n      n = -n;\n      tree = newtree(L, 2 * n);\n      tree->tag = TNot;\n      nd = sib1(tree);\n    }\n    fillseq(nd, TAny, n, NULL);  /* sequence of 'n' any's */\n    return tree;\n  }\n}\n\n\n/*\n** Convert value at index 'idx' to a pattern\n*/\nstatic TTree *getpatt (lua_State *L, int idx, int *len) {\n  TTree *tree;\n  switch (lua_type(L, idx)) {\n    case LUA_TSTRING: {\n      size_t slen;\n      const char *s = lua_tolstring(L, idx, &slen);  /* get string */\n      if (slen == 0)  /* empty? */\n        tree = newleaf(L, TTrue);  /* always match */\n      else {\n        tree = newtree(L, 2 * (slen - 1) + 1);\n        fillseq(tree, TChar, slen, s);  /* sequence of 'slen' chars */\n      }\n      break;\n    }\n    case LUA_TNUMBER: {\n      int n = lua_tointeger(L, idx);\n      tree = numtree(L, n);\n      break;\n    }\n    case LUA_TBOOLEAN: {\n      tree = (lua_toboolean(L, idx) ? newleaf(L, TTrue) : newleaf(L, TFalse));\n      break;\n    }\n    case LUA_TTABLE: {\n      tree = newgrammar(L, idx);\n      break;\n    }\n    case LUA_TFUNCTION: {\n      tree = newtree(L, 2);\n      tree->tag = TRunTime;\n      tree->key = addtonewktable(L, 0, idx);\n      sib1(tree)->tag = TTrue;\n      break;\n    }\n    default: {\n      return gettree(L, idx, len);\n    }\n  }\n  lua_replace(L, idx);  /* put new tree into 'idx' slot */\n  if (len)\n    *len = getsize(L, idx);\n  return tree;\n}\n\n\n/*\n** create a new tree, whith a new root and one sibling.\n** Sibling must be on the Lua stack, at index 1.\n*/\nstatic TTree *newroot1sib (lua_State *L, int tag) {\n  int s1;\n  TTree *tree1 = getpatt(L, 1, &s1);\n  TTree *tree = newtree(L, 1 + s1);  /* create new tree */\n  tree->tag = tag;\n  memcpy(sib1(tree), tree1, s1 * sizeof(TTree));\n  copyktable(L, 1);\n  return tree;\n}\n\n\n/*\n** create a new tree, whith a new root and 2 siblings.\n** Siblings must be on the Lua stack, first one at index 1.\n*/\nstatic TTree *newroot2sib (lua_State *L, int tag) {\n  int s1, s2;\n  TTree *tree1 = getpatt(L, 1, &s1);\n  TTree *tree2 = getpatt(L, 2, &s2);\n  TTree *tree = newtree(L, 1 + s1 + s2);  /* create new tree */\n  tree->tag = tag;\n  tree->u.ps =  1 + s1;\n  memcpy(sib1(tree), tree1, s1 * sizeof(TTree));\n  memcpy(sib2(tree), tree2, s2 * sizeof(TTree));\n  joinktables(L, 1, sib2(tree), 2);\n  return tree;\n}\n\n\nstatic int lp_P (lua_State *L) {\n  luaL_checkany(L, 1);\n  getpatt(L, 1, NULL);\n  lua_settop(L, 1);\n  return 1;\n}\n\n\n/*\n** sequence operator; optimizations:\n** false x => false, x true => x, true x => x\n** (cannot do x . false => false because x may have runtime captures)\n*/\nstatic int lp_seq (lua_State *L) {\n  TTree *tree1 = getpatt(L, 1, NULL);\n  TTree *tree2 = getpatt(L, 2, NULL);\n  if (tree1->tag == TFalse || tree2->tag == TTrue)\n    lua_pushvalue(L, 1);  /* false . x == false, x . true = x */\n  else if (tree1->tag == TTrue)\n    lua_pushvalue(L, 2);  /* true . x = x */\n  else\n    newroot2sib(L, TSeq);\n  return 1;\n}\n\n\n/*\n** choice operator; optimizations:\n** charset / charset => charset\n** true / x => true, x / false => x, false / x => x\n** (x / true is not equivalent to true)\n*/\nstatic int lp_choice (lua_State *L) {\n  Charset st1, st2;\n  TTree *t1 = getpatt(L, 1, NULL);\n  TTree *t2 = getpatt(L, 2, NULL);\n  if (tocharset(t1, &st1) && tocharset(t2, &st2)) {\n    loopset(i, st1.cs[i] |= st2.cs[i]);\n    newcharset(L, st1.cs);\n  }\n  else if (nofail(t1) || t2->tag == TFalse)\n    lua_pushvalue(L, 1);  /* true / x => true, x / false => x */\n  else if (t1->tag == TFalse)\n    lua_pushvalue(L, 2);  /* false / x => x */\n  else\n    newroot2sib(L, TChoice);\n  return 1;\n}\n\n\n/*\n** p^n\n*/\nstatic int lp_star (lua_State *L) {\n  int size1;\n  int n = (int)luaL_checkinteger(L, 2);\n  TTree *tree1 = getpatt(L, 1, &size1);\n  if (n >= 0) {  /* seq tree1 (seq tree1 ... (seq tree1 (rep tree1))) */\n    TTree *tree = newtree(L, (n + 1) * (size1 + 1));\n    if (nullable(tree1))\n      luaL_error(L, \"loop body may accept empty string\");\n    while (n--)  /* repeat 'n' times */\n      tree = seqaux(tree, tree1, size1);\n    tree->tag = TRep;\n    memcpy(sib1(tree), tree1, size1 * sizeof(TTree));\n  }\n  else {  /* choice (seq tree1 ... choice tree1 true ...) true */\n    TTree *tree;\n    n = -n;\n    /* size = (choice + seq + tree1 + true) * n, but the last has no seq */\n    tree = newtree(L, n * (size1 + 3) - 1);\n    for (; n > 1; n--) {  /* repeat (n - 1) times */\n      tree->tag = TChoice; tree->u.ps = n * (size1 + 3) - 2;\n      sib2(tree)->tag = TTrue;\n      tree = sib1(tree);\n      tree = seqaux(tree, tree1, size1);\n    }\n    tree->tag = TChoice; tree->u.ps = size1 + 1;\n    sib2(tree)->tag = TTrue;\n    memcpy(sib1(tree), tree1, size1 * sizeof(TTree));\n  }\n  copyktable(L, 1);\n  return 1;\n}\n\n\n/*\n** #p == &p\n*/\nstatic int lp_and (lua_State *L) {\n  newroot1sib(L, TAnd);\n  return 1;\n}\n\n\n/*\n** -p == !p\n*/\nstatic int lp_not (lua_State *L) {\n  newroot1sib(L, TNot);\n  return 1;\n}\n\n\n/*\n** [t1 - t2] == Seq (Not t2) t1\n** If t1 and t2 are charsets, make their difference.\n*/\nstatic int lp_sub (lua_State *L) {\n  Charset st1, st2;\n  int s1, s2;\n  TTree *t1 = getpatt(L, 1, &s1);\n  TTree *t2 = getpatt(L, 2, &s2);\n  if (tocharset(t1, &st1) && tocharset(t2, &st2)) {\n    loopset(i, st1.cs[i] &= ~st2.cs[i]);\n    newcharset(L, st1.cs);\n  }\n  else {\n    TTree *tree = newtree(L, 2 + s1 + s2);\n    tree->tag = TSeq;  /* sequence of... */\n    tree->u.ps =  2 + s2;\n    sib1(tree)->tag = TNot;  /* ...not... */\n    memcpy(sib1(sib1(tree)), t2, s2 * sizeof(TTree));  /* ...t2 */\n    memcpy(sib2(tree), t1, s1 * sizeof(TTree));  /* ... and t1 */\n    joinktables(L, 1, sib1(tree), 2);\n  }\n  return 1;\n}\n\n\nstatic int lp_set (lua_State *L) {\n  size_t l;\n  const char *s = luaL_checklstring(L, 1, &l);\n  byte buff[CHARSETSIZE];\n  clearset(buff);\n  while (l--) {\n    setchar(buff, (byte)(*s));\n    s++;\n  }\n  newcharset(L, buff);\n  return 1;\n}\n\n\nstatic int lp_range (lua_State *L) {\n  int arg;\n  int top = lua_gettop(L);\n  byte buff[CHARSETSIZE];\n  clearset(buff);\n  for (arg = 1; arg <= top; arg++) {\n    int c;\n    size_t l;\n    const char *r = luaL_checklstring(L, arg, &l);\n    luaL_argcheck(L, l == 2, arg, \"range must have two characters\");\n    for (c = (byte)r[0]; c <= (byte)r[1]; c++)\n      setchar(buff, c);\n  }\n  newcharset(L, buff);\n  return 1;\n}\n\n\n/*\n** Fills a tree node with basic information about the UTF-8 code point\n** 'cpu': its value in 'n', its length in 'cap', and its first byte in\n** 'key'\n*/\nstatic void codeutftree (lua_State *L, TTree *t, lua_Unsigned cpu, int arg) {\n  int len, fb, cp;\n  cp = (int)cpu;\n  if (cp <= 0x7f) {  /* one byte? */\n    len = 1;\n    fb = cp;\n  } else if (cp <= 0x7ff) {\n    len = 2;\n    fb = 0xC0 | (cp >> 6);\n  } else if (cp <= 0xffff) {\n    len = 3;\n    fb = 0xE0 | (cp >> 12);\n  }\n  else {\n    luaL_argcheck(L, cpu <= 0x10ffffu, arg, \"invalid code point\");\n    len = 4;\n    fb = 0xF0 | (cp >> 18);\n  }\n  t->u.n = cp;\n  t->cap = len;\n  t->key = fb;\n}\n\n\nstatic int lp_utfr (lua_State *L) {\n  lua_Unsigned from = (lua_Unsigned)luaL_checkinteger(L, 1);\n  lua_Unsigned to = (lua_Unsigned)luaL_checkinteger(L, 2);\n  luaL_argcheck(L, from <= to, 2, \"empty range\");\n  if (to <= 0x7f) {  /* ascii range? */\n    uint f;\n    byte buff[CHARSETSIZE];  /* code it as a regular charset */\n    clearset(buff);\n    for (f = (int)from; f <= to; f++)\n      setchar(buff, f);\n    newcharset(L, buff);\n  }\n  else {  /* multi-byte utf-8 range */\n    TTree *tree = newtree(L, 2);\n    tree->tag = TUTFR;\n    codeutftree(L, tree, from, 1);\n    sib1(tree)->tag = TXInfo;\n    codeutftree(L, sib1(tree), to, 2);\n  }\n  return 1;\n}\n\n\n/*\n** Look-behind predicate\n*/\nstatic int lp_behind (lua_State *L) {\n  TTree *tree;\n  TTree *tree1 = getpatt(L, 1, NULL);\n  int n = fixedlen(tree1);\n  luaL_argcheck(L, n >= 0, 1, \"pattern may not have fixed length\");\n  luaL_argcheck(L, !hascaptures(tree1), 1, \"pattern have captures\");\n  luaL_argcheck(L, n <= MAXBEHIND, 1, \"pattern too long to look behind\");\n  tree = newroot1sib(L, TBehind);\n  tree->u.n = n;\n  return 1;\n}\n\n\n/*\n** Create a non-terminal\n*/\nstatic int lp_V (lua_State *L) {\n  TTree *tree = newleaf(L, TOpenCall);\n  luaL_argcheck(L, !lua_isnoneornil(L, 1), 1, \"non-nil value expected\");\n  tree->key = addtonewktable(L, 0, 1);\n  return 1;\n}\n\n\n/*\n** Create a tree for a non-empty capture, with a body and\n** optionally with an associated Lua value (at index 'labelidx' in the\n** stack)\n*/\nstatic int capture_aux (lua_State *L, int cap, int labelidx) {\n  TTree *tree = newroot1sib(L, TCapture);\n  tree->cap = cap;\n  tree->key = (labelidx == 0) ? 0 : addtonewktable(L, 1, labelidx);\n  return 1;\n}\n\n\n/*\n** Fill a tree with an empty capture, using an empty (TTrue) sibling.\n** (The 'key' field must be filled by the caller to finish the tree.)\n*/\nstatic TTree *auxemptycap (TTree *tree, int cap) {\n  tree->tag = TCapture;\n  tree->cap = cap;\n  sib1(tree)->tag = TTrue;\n  return tree;\n}\n\n\n/*\n** Create a tree for an empty capture.\n*/\nstatic TTree *newemptycap (lua_State *L, int cap, int key) {\n  TTree *tree = auxemptycap(newtree(L, 2), cap);\n  tree->key = key;\n  return tree;\n}\n\n\n/*\n** Create a tree for an empty capture with an associated Lua value.\n*/\nstatic TTree *newemptycapkey (lua_State *L, int cap, int idx) {\n  TTree *tree = auxemptycap(newtree(L, 2), cap);\n  tree->key = addtonewktable(L, 0, idx);\n  return tree;\n}\n\n\n/*\n** Captures with syntax p / v\n** (function capture, query capture, string capture, or number capture)\n*/\nstatic int lp_divcapture (lua_State *L) {\n  switch (lua_type(L, 2)) {\n    case LUA_TFUNCTION: return capture_aux(L, Cfunction, 2);\n    case LUA_TTABLE: return capture_aux(L, Cquery, 2);\n    case LUA_TSTRING: return capture_aux(L, Cstring, 2);\n    case LUA_TNUMBER: {\n      int n = lua_tointeger(L, 2);\n      TTree *tree = newroot1sib(L, TCapture);\n      luaL_argcheck(L, 0 <= n && n <= SHRT_MAX, 1, \"invalid number\");\n      tree->cap = Cnum;\n      tree->key = n;\n      return 1;\n    }\n    default:\n      return luaL_error(L, \"unexpected %s as 2nd operand to LPeg '/'\",\n                           luaL_typename(L, 2));\n  }\n}\n\n\nstatic int lp_acccapture (lua_State *L) {\n  return capture_aux(L, Cacc, 2);\n}\n\n\nstatic int lp_substcapture (lua_State *L) {\n  return capture_aux(L, Csubst, 0);\n}\n\n\nstatic int lp_tablecapture (lua_State *L) {\n  return capture_aux(L, Ctable, 0);\n}\n\n\nstatic int lp_groupcapture (lua_State *L) {\n  if (lua_isnoneornil(L, 2))\n    return capture_aux(L, Cgroup, 0);\n  else\n    return capture_aux(L, Cgroup, 2);\n}\n\n\nstatic int lp_foldcapture (lua_State *L) {\n  luaL_checktype(L, 2, LUA_TFUNCTION);\n  return capture_aux(L, Cfold, 2);\n}\n\n\nstatic int lp_simplecapture (lua_State *L) {\n  return capture_aux(L, Csimple, 0);\n}\n\n\nstatic int lp_poscapture (lua_State *L) {\n  newemptycap(L, Cposition, 0);\n  return 1;\n}\n\n\nstatic int lp_argcapture (lua_State *L) {\n  int n = (int)luaL_checkinteger(L, 1);\n  luaL_argcheck(L, 0 < n && n <= SHRT_MAX, 1, \"invalid argument index\");\n  newemptycap(L, Carg, n);\n  return 1;\n}\n\n\nstatic int lp_backref (lua_State *L) {\n  luaL_checkany(L, 1);\n  newemptycapkey(L, Cbackref, 1);\n  return 1;\n}\n\n\n/*\n** Constant capture\n*/\nstatic int lp_constcapture (lua_State *L) {\n  int i;\n  int n = lua_gettop(L);  /* number of values */\n  if (n == 0)  /* no values? */\n    newleaf(L, TTrue);  /* no capture */\n  else if (n == 1)\n    newemptycapkey(L, Cconst, 1);  /* single constant capture */\n  else {  /* create a group capture with all values */\n    TTree *tree = newtree(L, 1 + 3 * (n - 1) + 2);\n    newktable(L, n);  /* create a 'ktable' for new tree */\n    tree->tag = TCapture;\n    tree->cap = Cgroup;\n    tree->key = 0;\n    tree = sib1(tree);\n    for (i = 1; i <= n - 1; i++) {\n      tree->tag = TSeq;\n      tree->u.ps = 3;  /* skip TCapture and its sibling */\n      auxemptycap(sib1(tree), Cconst);\n      sib1(tree)->key = addtoktable(L, i);\n      tree = sib2(tree);\n    }\n    auxemptycap(tree, Cconst);\n    tree->key = addtoktable(L, i);\n  }\n  return 1;\n}\n\n\nstatic int lp_matchtime (lua_State *L) {\n  TTree *tree;\n  luaL_checktype(L, 2, LUA_TFUNCTION);\n  tree = newroot1sib(L, TRunTime);\n  tree->key = addtonewktable(L, 1, 2);\n  return 1;\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Grammar - Tree generation\n** =======================================================\n*/\n\n/*\n** push on the stack the index and the pattern for the\n** initial rule of grammar at index 'arg' in the stack;\n** also add that index into position table.\n*/\nstatic void getfirstrule (lua_State *L, int arg, int postab) {\n  lua_rawgeti(L, arg, 1);  /* access first element */\n  if (lua_isstring(L, -1)) {  /* is it the name of initial rule? */\n    lua_pushvalue(L, -1);  /* duplicate it to use as key */\n    lua_gettable(L, arg);  /* get associated rule */\n  }\n  else {\n    lua_pushinteger(L, 1);  /* key for initial rule */\n    lua_insert(L, -2);  /* put it before rule */\n  }\n  if (!testpattern(L, -1)) {  /* initial rule not a pattern? */\n    if (lua_isnil(L, -1))\n      luaL_error(L, \"grammar has no initial rule\");\n    else\n      luaL_error(L, \"initial rule '%s' is not a pattern\", lua_tostring(L, -2));\n  }\n  lua_pushvalue(L, -2);  /* push key */\n  lua_pushinteger(L, 1);  /* push rule position (after TGrammar) */\n  lua_settable(L, postab);  /* insert pair at position table */\n}\n\n/*\n** traverse grammar at index 'arg', pushing all its keys and patterns\n** into the stack. Create a new table (before all pairs key-pattern) to\n** collect all keys and their associated positions in the final tree\n** (the \"position table\").\n** Return the number of rules and (in 'totalsize') the total size\n** for the new tree.\n*/\nstatic int collectrules (lua_State *L, int arg, int *totalsize) {\n  int n = 1;  /* to count number of rules */\n  int postab = lua_gettop(L) + 1;  /* index of position table */\n  int size;  /* accumulator for total size */\n  lua_newtable(L);  /* create position table */\n  getfirstrule(L, arg, postab);\n  size = 3 + getsize(L, postab + 2);  /* TGrammar + TRule + TXInfo + rule */\n  lua_pushnil(L);  /* prepare to traverse grammar table */\n  while (lua_next(L, arg) != 0) {\n    if (lua_tonumber(L, -2) == 1 ||\n        lp_equal(L, -2, postab + 1)) {  /* initial rule? */\n      lua_pop(L, 1);  /* remove value (keep key for lua_next) */\n      continue;\n    }\n    if (!testpattern(L, -1))  /* value is not a pattern? */\n      luaL_error(L, \"rule '%s' is not a pattern\", val2str(L, -2));\n    luaL_checkstack(L, LUA_MINSTACK, \"grammar has too many rules\");\n    lua_pushvalue(L, -2);  /* push key (to insert into position table) */\n    lua_pushinteger(L, size);\n    lua_settable(L, postab);\n    size += 2 + getsize(L, -1);  /* add 'TRule + TXInfo + rule' to size */\n    lua_pushvalue(L, -2);  /* push key (for next lua_next) */\n    n++;\n  }\n  *totalsize = size + 1;  /* space for 'TTrue' finishing list of rules */\n  return n;\n}\n\n\nstatic void buildgrammar (lua_State *L, TTree *grammar, int frule, int n) {\n  int i;\n  TTree *nd = sib1(grammar);  /* auxiliary pointer to traverse the tree */\n  for (i = 0; i < n; i++) {  /* add each rule into new tree */\n    int ridx = frule + 2*i + 1;  /* index of i-th rule */\n    int rulesize;\n    TTree *rn = gettree(L, ridx, &rulesize);\n    TTree *pr = sib1(nd);  /* points to rule's prerule */\n    nd->tag = TRule;\n    nd->key = 0;  /* will be fixed when rule is used */\n    pr->tag = TXInfo;\n    pr->u.n = i;  /* rule number */\n    nd->u.ps = rulesize + 2;  /* point to next rule */\n    memcpy(sib1(pr), rn, rulesize * sizeof(TTree));  /* copy rule */\n    mergektable(L, ridx, sib1(nd));  /* merge its ktable into new one */\n    nd = sib2(nd);  /* move to next rule */\n  }\n  nd->tag = TTrue;  /* finish list of rules */\n}\n\n\n/*\n** Check whether a tree has potential infinite loops\n*/\nstatic int checkloops (TTree *tree) {\n tailcall:\n  if (tree->tag == TRep && nullable(sib1(tree)))\n    return 1;\n  else if (tree->tag == TGrammar)\n    return 0;  /* sub-grammars already checked */\n  else {\n    switch (numsiblings[tree->tag]) {\n      case 1:  /* return checkloops(sib1(tree)); */\n        tree = sib1(tree); goto tailcall;\n      case 2:\n        if (checkloops(sib1(tree))) return 1;\n        /* else return checkloops(sib2(tree)); */\n        tree = sib2(tree); goto tailcall;\n      default: assert(numsiblings[tree->tag] == 0); return 0;\n    }\n  }\n}\n\n\n/*\n** Give appropriate error message for 'verifyrule'. If a rule appears\n** twice in 'passed', there is path from it back to itself without\n** advancing the subject.\n*/\nstatic int verifyerror (lua_State *L, unsigned short *passed, int npassed) {\n  int i, j;\n  for (i = npassed - 1; i >= 0; i--) {  /* search for a repetition */\n    for (j = i - 1; j >= 0; j--) {\n      if (passed[i] == passed[j]) {\n        lua_rawgeti(L, -1, passed[i]);  /* get rule's key */\n        return luaL_error(L, \"rule '%s' may be left recursive\", val2str(L, -1));\n      }\n    }\n  }\n  return luaL_error(L, \"too many left calls in grammar\");\n}\n\n\n/*\n** Check whether a rule can be left recursive; raise an error in that\n** case; otherwise return 1 iff pattern is nullable.\n** The return value is used to check sequences, where the second pattern\n** is only relevant if the first is nullable.\n** Parameter 'nb' works as an accumulator, to allow tail calls in\n** choices. ('nb' true makes function returns true.)\n** Parameter 'passed' is a list of already visited rules, 'npassed'\n** counts the elements in 'passed'.\n** Assume ktable at the top of the stack.\n*/\nstatic int verifyrule (lua_State *L, TTree *tree, unsigned short *passed,\n                                     int npassed, int nb) {\n tailcall:\n  switch (tree->tag) {\n    case TChar: case TSet: case TAny:\n    case TFalse: case TUTFR:\n      return nb;  /* cannot pass from here */\n    case TTrue:\n    case TBehind:  /* look-behind cannot have calls */\n      return 1;\n    case TNot: case TAnd: case TRep:\n      /* return verifyrule(L, sib1(tree), passed, npassed, 1); */\n      tree = sib1(tree); nb = 1; goto tailcall;\n    case TCapture: case TRunTime: case TXInfo:\n      /* return verifyrule(L, sib1(tree), passed, npassed, nb); */\n      tree = sib1(tree); goto tailcall;\n    case TCall:\n      /* return verifyrule(L, sib2(tree), passed, npassed, nb); */\n      tree = sib2(tree); goto tailcall;\n    case TSeq:  /* only check 2nd child if first is nb */\n      if (!verifyrule(L, sib1(tree), passed, npassed, 0))\n        return nb;\n      /* else return verifyrule(L, sib2(tree), passed, npassed, nb); */\n      tree = sib2(tree); goto tailcall;\n    case TChoice:  /* must check both children */\n      nb = verifyrule(L, sib1(tree), passed, npassed, nb);\n      /* return verifyrule(L, sib2(tree), passed, npassed, nb); */\n      tree = sib2(tree); goto tailcall;\n    case TRule:\n      if (npassed >= MAXRULES)  /* too many steps? */\n        return verifyerror(L, passed, npassed);  /* error */\n      else {\n        passed[npassed++] = tree->key;  /* add rule to path */\n        /* return verifyrule(L, sib1(tree), passed, npassed); */\n        tree = sib1(tree); goto tailcall;\n      }\n    case TGrammar:\n      return nullable(tree);  /* sub-grammar cannot be left recursive */\n    default: assert(0); return 0;\n  }\n}\n\n\nstatic void verifygrammar (lua_State *L, TTree *grammar) {\n  unsigned short passed[MAXRULES];\n  TTree *rule;\n  /* check left-recursive rules */\n  for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {\n    if (rule->key == 0) continue;  /* unused rule */\n    verifyrule(L, sib1(rule), passed, 0, 0);\n  }\n  assert(rule->tag == TTrue);\n  /* check infinite loops inside rules */\n  for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {\n    if (rule->key == 0) continue;  /* unused rule */\n    if (checkloops(sib1(rule))) {\n      lua_rawgeti(L, -1, rule->key);  /* get rule's key */\n      luaL_error(L, \"empty loop in rule '%s'\", val2str(L, -1));\n    }\n  }\n  assert(rule->tag == TTrue);\n}\n\n\n/*\n** Give a name for the initial rule if it is not referenced\n*/\nstatic void initialrulename (lua_State *L, TTree *grammar, int frule) {\n  if (sib1(grammar)->key == 0) {  /* initial rule is not referenced? */\n    int n = lua_rawlen(L, -1) + 1;  /* index for name */\n    lua_pushvalue(L, frule);  /* rule's name */\n    lua_rawseti(L, -2, n);  /* ktable was on the top of the stack */\n    sib1(grammar)->key = n;\n  }\n}\n\n\nstatic TTree *newgrammar (lua_State *L, int arg) {\n  int treesize;\n  int frule = lua_gettop(L) + 2;  /* position of first rule's key */\n  int n = collectrules(L, arg, &treesize);\n  TTree *g = newtree(L, treesize);\n  luaL_argcheck(L, n <= MAXRULES, arg, \"grammar has too many rules\");\n  g->tag = TGrammar;  g->u.n = n;\n  lua_newtable(L);  /* create 'ktable' */\n  lua_setuservalue(L, -2);\n  buildgrammar(L, g, frule, n);\n  lua_getuservalue(L, -1);  /* get 'ktable' for new tree */\n  finalfix(L, frule - 1, g, sib1(g));\n  initialrulename(L, g, frule);\n  verifygrammar(L, g);\n  lua_pop(L, 1);  /* remove 'ktable' */\n  lua_insert(L, -(n * 2 + 2));  /* move new table to proper position */\n  lua_pop(L, n * 2 + 1);  /* remove position table + rule pairs */\n  return g;  /* new table at the top of the stack */\n}\n\n/* }====================================================== */\n\n\nstatic Instruction *prepcompile (lua_State *L, Pattern *p, int idx) {\n  lua_getuservalue(L, idx);  /* push 'ktable' (may be used by 'finalfix') */\n  finalfix(L, 0, NULL, p->tree);\n  lua_pop(L, 1);  /* remove 'ktable' */\n  return compile(L, p, getsize(L, idx));\n}\n\n\nstatic int lp_printtree (lua_State *L) {\n  TTree *tree = getpatt(L, 1, NULL);\n  int c = lua_toboolean(L, 2);\n  if (c) {\n    lua_getuservalue(L, 1);  /* push 'ktable' (may be used by 'finalfix') */\n    finalfix(L, 0, NULL, tree);\n    lua_pop(L, 1);  /* remove 'ktable' */\n  }\n  printktable(L, 1);\n  printtree(tree, 0);\n  return 0;\n}\n\n\nstatic int lp_printcode (lua_State *L) {\n  Pattern *p = getpattern(L, 1);\n  printktable(L, 1);\n  if (p->code == NULL)  /* not compiled yet? */\n    prepcompile(L, p, 1);\n  printpatt(p->code);\n  return 0;\n}\n\n\n/*\n** Get the initial position for the match, interpreting negative\n** values from the end of the subject\n*/\nstatic size_t initposition (lua_State *L, size_t len) {\n  lua_Integer ii = luaL_optinteger(L, 3, 1);\n  if (ii > 0) {  /* positive index? */\n    if ((size_t)ii <= len)  /* inside the string? */\n      return (size_t)ii - 1;  /* return it (corrected to 0-base) */\n    else return len;  /* crop at the end */\n  }\n  else {  /* negative index */\n    if ((size_t)(-ii) <= len)  /* inside the string? */\n      return len - ((size_t)(-ii));  /* return position from the end */\n    else return 0;  /* crop at the beginning */\n  }\n}\n\n\n/*\n** Main match function\n*/\nstatic int lp_match (lua_State *L) {\n  Capture capture[INITCAPSIZE];\n  const char *r;\n  size_t l;\n  Pattern *p = (getpatt(L, 1, NULL), getpattern(L, 1));\n  Instruction *code = (p->code != NULL) ? p->code : prepcompile(L, p, 1);\n  const char *s = luaL_checklstring(L, SUBJIDX, &l);\n  size_t i = initposition(L, l);\n  int ptop = lua_gettop(L);\n  luaL_argcheck(L, l < MAXINDT, SUBJIDX, \"subject too long\");\n  lua_pushnil(L);  /* initialize subscache */\n  lua_pushlightuserdata(L, capture);  /* initialize caplistidx */\n  lua_getuservalue(L, 1);  /* initialize ktableidx */\n  r = match(L, s, s + i, s + l, code, capture, ptop);\n  if (r == NULL) {\n    lua_pushnil(L);\n    return 1;\n  }\n  return getcaptures(L, s, r, ptop);\n}\n\n\n\n/*\n** {======================================================\n** Library creation and functions not related to matching\n** =======================================================\n*/\n\n/* maximum limit for stack size */\n#define MAXLIM\t\t(INT_MAX / 100)\n\nstatic int lp_setmax (lua_State *L) {\n  lua_Integer lim = luaL_checkinteger(L, 1);\n  luaL_argcheck(L, 0 < lim && lim <= MAXLIM, 1, \"out of range\");\n  lua_settop(L, 1);\n  lua_setfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);\n  return 0;\n}\n\n\nstatic int lp_type (lua_State *L) {\n  if (testpattern(L, 1))\n    lua_pushliteral(L, \"pattern\");\n  else\n    lua_pushnil(L);\n  return 1;\n}\n\n\nint lp_gc (lua_State *L) {\n  Pattern *p = getpattern(L, 1);\n  freecode(L, p);  /* delete code block */\n  return 0;\n}\n\n\n/*\n** Create a charset representing a category of characters, given by\n** the predicate 'catf'.\n*/\nstatic void createcat (lua_State *L, const char *catname, int (catf) (int)) {\n  int c;\n  byte buff[CHARSETSIZE];\n  clearset(buff);\n  for (c = 0; c <= UCHAR_MAX; c++)\n    if (catf(c)) setchar(buff, c);\n  newcharset(L, buff);\n  lua_setfield(L, -2, catname);\n}\n\n\nstatic int lp_locale (lua_State *L) {\n  if (lua_isnoneornil(L, 1)) {\n    lua_settop(L, 0);\n    lua_createtable(L, 0, 12);\n  }\n  else {\n    luaL_checktype(L, 1, LUA_TTABLE);\n    lua_settop(L, 1);\n  }\n  createcat(L, \"alnum\", isalnum);\n  createcat(L, \"alpha\", isalpha);\n  createcat(L, \"cntrl\", iscntrl);\n  createcat(L, \"digit\", isdigit);\n  createcat(L, \"graph\", isgraph);\n  createcat(L, \"lower\", islower);\n  createcat(L, \"print\", isprint);\n  createcat(L, \"punct\", ispunct);\n  createcat(L, \"space\", isspace);\n  createcat(L, \"upper\", isupper);\n  createcat(L, \"xdigit\", isxdigit);\n  return 1;\n}\n\n\nstatic struct luaL_Reg pattreg[] = {\n  {\"ptree\", lp_printtree},\n  {\"pcode\", lp_printcode},\n  {\"match\", lp_match},\n  {\"B\", lp_behind},\n  {\"V\", lp_V},\n  {\"C\", lp_simplecapture},\n  {\"Cc\", lp_constcapture},\n  {\"Cmt\", lp_matchtime},\n  {\"Cb\", lp_backref},\n  {\"Carg\", lp_argcapture},\n  {\"Cp\", lp_poscapture},\n  {\"Cs\", lp_substcapture},\n  {\"Ct\", lp_tablecapture},\n  {\"Cf\", lp_foldcapture},\n  {\"Cg\", lp_groupcapture},\n  {\"P\", lp_P},\n  {\"S\", lp_set},\n  {\"R\", lp_range},\n  {\"utfR\", lp_utfr},\n  {\"locale\", lp_locale},\n  {\"version\", NULL},\n  {\"setmaxstack\", lp_setmax},\n  {\"type\", lp_type},\n  {NULL, NULL}\n};\n\n\nstatic struct luaL_Reg metareg[] = {\n  {\"__mul\", lp_seq},\n  {\"__add\", lp_choice},\n  {\"__pow\", lp_star},\n  {\"__gc\", lp_gc},\n  {\"__len\", lp_and},\n  {\"__div\", lp_divcapture},\n  {\"__mod\", lp_acccapture},\n  {\"__unm\", lp_not},\n  {\"__sub\", lp_sub},\n  {NULL, NULL}\n};\n\n\nint luaopen_lpeg (lua_State *L);\nint luaopen_lpeg (lua_State *L) {\n  luaL_newmetatable(L, PATTERN_T);\n  lua_pushnumber(L, MAXBACK);  /* initialize maximum backtracking */\n  lua_setfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);\n  luaL_setfuncs(L, metareg, 0);\n  luaL_newlib(L, pattreg);\n  lua_pushvalue(L, -1);\n  lua_setfield(L, -3, \"__index\");\n  lua_pushliteral(L, \"LPeg \" VERSION);\n  lua_setfield(L, -2, \"version\");\n  return 1;\n}\n\n/* }====================================================== */\n"
  },
  {
    "path": "3rd/lpeg/lptree.h",
    "content": "\n#if !defined(lptree_h)\n#define lptree_h\n\n\n#include \"lptypes.h\"\n\n\n/*\n** types of trees\n*/\ntypedef enum TTag {\n  TChar = 0,  /* 'n' = char */\n  TSet,  /* the set is encoded in 'u.set' and the next 'u.set.size' bytes */\n  TAny,\n  TTrue,\n  TFalse,\n  TUTFR,  /* range of UTF-8 codepoints; 'n' has initial codepoint;\n             'cap' has length; 'key' has first byte;\n             extra info is similar for end codepoint */\n  TRep,  /* 'sib1'* */\n  TSeq,  /* 'sib1' 'sib2' */\n  TChoice,  /* 'sib1' / 'sib2' */\n  TNot,  /* !'sib1' */\n  TAnd,  /* &'sib1' */\n  TCall,  /* ktable[key] is rule's key; 'sib2' is rule being called */\n  TOpenCall,  /* ktable[key] is rule's key */\n  TRule,  /* ktable[key] is rule's key (but key == 0 for unused rules);\n             'sib1' is rule's pattern pre-rule; 'sib2' is next rule;\n             extra info 'n' is rule's sequential number */\n  TXInfo,  /* extra info */\n  TGrammar,  /* 'sib1' is initial (and first) rule */\n  TBehind,  /* 'sib1' is pattern, 'n' is how much to go back */\n  TCapture,  /* captures: 'cap' is kind of capture (enum 'CapKind');\n                ktable[key] is Lua value associated with capture;\n                'sib1' is capture body */\n  TRunTime  /* run-time capture: 'key' is Lua function;\n               'sib1' is capture body */\n} TTag;\n\n\n/*\n** Tree trees\n** The first child of a tree (if there is one) is immediately after\n** the tree.  A reference to a second child (ps) is its position\n** relative to the position of the tree itself.\n*/\ntypedef struct TTree {\n  byte tag;\n  byte cap;  /* kind of capture (if it is a capture) */\n  unsigned short key;  /* key in ktable for Lua data (0 if no key) */\n  union {\n    int ps;  /* occasional second child */\n    int n;  /* occasional counter */\n    struct {\n      byte offset;  /* compact set offset (in bytes) */\n      byte size;  /* compact set size (in bytes) */\n      byte deflt;  /* default value */\n      byte bitmap[1];  /* bitmap (open array) */\n    } set;  /* for compact sets */\n  } u;\n} TTree;\n\n\n/* access to charset */\n#define treebuffer(t)      ((t)->u.set.bitmap)\n\n\n/*\n** A complete pattern has its tree plus, if already compiled,\n** its corresponding code\n*/\ntypedef struct Pattern {\n  union Instruction *code;\n  TTree tree[1];\n} Pattern;\n\n\n/* number of children for each tree */\nextern const byte numsiblings[];\n\n/* access to children */\n#define sib1(t)         ((t) + 1)\n#define sib2(t)         ((t) + (t)->u.ps)\n\n\n\n\n\n\n#endif\n\n"
  },
  {
    "path": "3rd/lpeg/lptypes.h",
    "content": "/*\n** LPeg - PEG pattern matching for Lua\n** Copyright 2007-2023, Lua.org & PUC-Rio  (see 'lpeg.html' for license)\n** written by Roberto Ierusalimschy\n*/\n\n#if !defined(lptypes_h)\n#define lptypes_h\n\n\n#include <assert.h>\n#include <limits.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n\n#define VERSION         \"1.1.0\"\n\n\n#define PATTERN_T\t\"lpeg-pattern\"\n#define MAXSTACKIDX\t\"lpeg-maxstack\"\n\n\n/*\n** compatibility with Lua 5.1\n*/\n#if (LUA_VERSION_NUM == 501)\n\n#define lp_equal\tlua_equal\n\n#define lua_getuservalue\tlua_getfenv\n#define lua_setuservalue\tlua_setfenv\n\n#define lua_rawlen\t\tlua_objlen\n\n#define luaL_setfuncs(L,f,n)\tluaL_register(L,NULL,f)\n#define luaL_newlib(L,f)\tluaL_register(L,\"lpeg\",f)\n\ntypedef size_t lua_Unsigned;\n\n#endif\n\n\n#if !defined(lp_equal)\n#define lp_equal(L,idx1,idx2)  lua_compare(L,(idx1),(idx2),LUA_OPEQ)\n#endif\n\n\n/* default maximum size for call/backtrack stack */\n#if !defined(MAXBACK)\n#define MAXBACK         400\n#endif\n\n\n/* maximum number of rules in a grammar (limited by 'unsigned short') */\n#if !defined(MAXRULES)\n#define MAXRULES        1000\n#endif\n\n\n\n/* initial size for capture's list */\n#define INITCAPSIZE\t32\n\n\n/* index, on Lua stack, for subject */\n#define SUBJIDX\t\t2\n\n/* number of fixed arguments to 'match' (before capture arguments) */\n#define FIXEDARGS\t3\n\n/* index, on Lua stack, for capture list */\n#define caplistidx(ptop)\t((ptop) + 2)\n\n/* index, on Lua stack, for pattern's ktable */\n#define ktableidx(ptop)\t\t((ptop) + 3)\n\n/* index, on Lua stack, for backtracking stack */\n#define stackidx(ptop)\t((ptop) + 4)\n\n\n\ntypedef unsigned char byte;\n\ntypedef unsigned int uint;\n\n\n#define BITSPERCHAR\t\t8\n\n#define CHARSETSIZE\t\t((UCHAR_MAX/BITSPERCHAR) + 1)\n\n\n\ntypedef struct Charset {\n  byte cs[CHARSETSIZE];\n} Charset;\n\n\n\n#define loopset(v,b)    { int v; for (v = 0; v < CHARSETSIZE; v++) {b;} }\n\n#define fillset(s,c)\tmemset(s,c,CHARSETSIZE)\n#define clearset(s)\tfillset(s,0)\n\n/* number of slots needed for 'n' bytes */\n#define bytes2slots(n)  (((n) - 1u) / (uint)sizeof(TTree) + 1u)\n\n/* set 'b' bit in charset 'cs' */\n#define setchar(cs,b)   ((cs)[(b) >> 3] |= (1 << ((b) & 7)))\n\n\n/*\n** in capture instructions, 'kind' of capture and its offset are\n** packed in field 'aux', 4 bits for each\n*/\n#define getkind(op)\t\t((op)->i.aux1 & 0xF)\n#define getoff(op)\t\t(((op)->i.aux1 >> 4) & 0xF)\n#define joinkindoff(k,o)\t((k) | ((o) << 4))\n\n#define MAXOFF\t\t0xF\n#define MAXAUX\t\t0xFF\n\n\n/* maximum number of bytes to look behind */\n#define MAXBEHIND\tMAXAUX\n\n\n/* maximum size (in elements) for a pattern */\n#define MAXPATTSIZE\t(SHRT_MAX - 10)\n\n\n/* size (in instructions) for l bytes (l > 0) */\n#define instsize(l) ((int)(((l) + (uint)sizeof(Instruction) - 1u) \\\n\t\t\t/ (uint)sizeof(Instruction)))\n\n\n/* size (in elements) for a ISet instruction */\n#define CHARSETINSTSIZE\t\t(1 + instsize(CHARSETSIZE))\n\n/* size (in elements) for a IFunc instruction */\n#define funcinstsize(p)\t\t((p)->i.aux + 2)\n\n\n\n#define testchar(st,c)\t((((uint)(st)[((c) >> 3)]) >> ((c) & 7)) & 1)\n\n\n#endif\n\n"
  },
  {
    "path": "3rd/lpeg/lpvm.c",
    "content": "\n#include <limits.h>\n#include <string.h>\n\n\n#include \"lua.h\"\n#include \"lauxlib.h\"\n\n#include \"lpcap.h\"\n#include \"lptypes.h\"\n#include \"lpvm.h\"\n#include \"lpprint.h\"\n\n\n/* initial size for call/backtrack stack */\n#if !defined(INITBACK)\n#define INITBACK\tMAXBACK\n#endif\n\n\n#define getoffset(p)\t(((p) + 1)->offset)\n\nstatic const Instruction giveup = {{IGiveup, 0, {0}}};\n\n\nint charinset (const Instruction *i, const byte *buff, uint c) {\n  c -= i->i.aux2.set.offset;\n  if (c >= ((uint)i->i.aux2.set.size  /* size in instructions... */\n           * (uint)sizeof(Instruction)  /* in bytes... */\n           * 8u))  /* in bits */\n    return i->i.aux1;  /* out of range; return default value */\n  return testchar(buff, c);\n}\n\n\n/*\n** Decode one UTF-8 sequence, returning NULL if byte sequence is invalid.\n*/\nstatic const char *utf8_decode (const char *o, int *val) {\n  static const uint limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFFu};\n  const unsigned char *s = (const unsigned char *)o;\n  uint c = s[0];  /* first byte */\n  uint res = 0;  /* final result */\n  if (c < 0x80)  /* ascii? */\n    res = c;\n  else {\n    int count = 0;  /* to count number of continuation bytes */\n    while (c & 0x40) {  /* still have continuation bytes? */\n      int cc = s[++count];  /* read next byte */\n      if ((cc & 0xC0) != 0x80)  /* not a continuation byte? */\n        return NULL;  /* invalid byte sequence */\n      res = (res << 6) | (cc & 0x3F);  /* add lower 6 bits from cont. byte */\n      c <<= 1;  /* to test next bit */\n    }\n    res |= (c & 0x7F) << (count * 5);  /* add first byte */\n    if (count > 3 || res > 0x10FFFFu || res <= limits[count])\n      return NULL;  /* invalid byte sequence */\n    s += count;  /* skip continuation bytes read */\n  }\n  *val = res;\n  return (const char *)s + 1;  /* +1 to include first byte */\n}\n\n\n/*\n** {======================================================\n** Virtual Machine\n** =======================================================\n*/\n\n\ntypedef struct Stack {\n  const char *s;  /* saved position (or NULL for calls) */\n  const Instruction *p;  /* next instruction */\n  int caplevel;\n} Stack;\n\n\n#define getstackbase(L, ptop)\t((Stack *)lua_touserdata(L, stackidx(ptop)))\n\n\n/*\n** Ensures the size of array 'capture' (with size '*capsize' and\n** 'captop' elements being used) is enough to accomodate 'n' extra\n** elements plus one.  (Because several opcodes add stuff to the capture\n** array, it is simpler to ensure the array always has at least one free\n** slot upfront and check its size later.)\n*/\n\n/* new size in number of elements cannot overflow integers, and new\n   size in bytes cannot overflow size_t. */\n#define MAXNEWSIZE  \\\n    (((size_t)INT_MAX) <= (~(size_t)0 / sizeof(Capture)) ?  \\\n     ((size_t)INT_MAX) : (~(size_t)0 / sizeof(Capture)))\n\nstatic Capture *growcap (lua_State *L, Capture *capture, int *capsize,\n                                       int captop, int n, int ptop) {\n  if (*capsize - captop > n)\n    return capture;  /* no need to grow array */\n  else {  /* must grow */\n    Capture *newc;\n    uint newsize = captop + n + 1;  /* minimum size needed */\n    if (newsize < (MAXNEWSIZE / 3) * 2)\n      newsize += newsize / 2;  /* 1.5 that size, if not too big */\n    else if (newsize < (MAXNEWSIZE / 9) * 8)\n      newsize += newsize / 8;  /* else, try 9/8 that size */\n    else\n      luaL_error(L, \"too many captures\");\n    newc = (Capture *)lua_newuserdata(L, newsize * sizeof(Capture));\n    memcpy(newc, capture, captop * sizeof(Capture));\n    *capsize = newsize;\n    lua_replace(L, caplistidx(ptop));\n    return newc;\n  }\n}\n\n\n/*\n** Double the size of the stack\n*/\nstatic Stack *doublestack (lua_State *L, Stack **stacklimit, int ptop) {\n  Stack *stack = getstackbase(L, ptop);\n  Stack *newstack;\n  int n = *stacklimit - stack;  /* current stack size */\n  int max, newn;\n  lua_getfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);\n  max = lua_tointeger(L, -1);  /* maximum allowed size */\n  lua_pop(L, 1);\n  if (n >= max)  /* already at maximum size? */\n    luaL_error(L, \"backtrack stack overflow (current limit is %d)\", max);\n  newn = 2 * n;  /* new size */\n  if (newn > max) newn = max;\n  newstack = (Stack *)lua_newuserdata(L, newn * sizeof(Stack));\n  memcpy(newstack, stack, n * sizeof(Stack));\n  lua_replace(L, stackidx(ptop));\n  *stacklimit = newstack + newn;\n  return newstack + n;  /* return next position */\n}\n\n\n/*\n** Interpret the result of a dynamic capture: false -> fail;\n** true -> keep current position; number -> next position.\n** Return new subject position. 'fr' is stack index where\n** is the result; 'curr' is current subject position; 'limit'\n** is subject's size.\n*/\nstatic int resdyncaptures (lua_State *L, int fr, int curr, int limit) {\n  lua_Integer res;\n  if (!lua_toboolean(L, fr)) {  /* false value? */\n    lua_settop(L, fr - 1);  /* remove results */\n    return -1;  /* and fail */\n  }\n  else if (lua_isboolean(L, fr))  /* true? */\n    res = curr;  /* keep current position */\n  else {\n    res = lua_tointeger(L, fr) - 1;  /* new position */\n    if (res < curr || res > limit)\n      luaL_error(L, \"invalid position returned by match-time capture\");\n  }\n  lua_remove(L, fr);  /* remove first result (offset) */\n  return res;\n}\n\n\n/*\n** Add capture values returned by a dynamic capture to the list\n** 'capture', nested inside a group. 'fd' indexes the first capture\n** value, 'n' is the number of values (at least 1). The open group\n** capture is already in 'capture', before the place for the new entries.\n*/\nstatic void adddyncaptures (Index_t index, Capture *capture, int n, int fd) {\n  int i;\n  assert(capture[-1].kind == Cgroup && capture[-1].siz == 0);\n  capture[-1].idx = 0;  /* make group capture an anonymous group */\n  for (i = 0; i < n; i++) {  /* add runtime captures */\n    capture[i].kind = Cruntime;\n    capture[i].siz = 1;  /* mark it as closed */\n    capture[i].idx = fd + i;  /* stack index of capture value */\n    capture[i].index = index;\n  }\n  capture[n].kind = Cclose;  /* close group */\n  capture[n].siz = 1;\n  capture[n].index = index;\n}\n\n\n/*\n** Remove dynamic captures from the Lua stack (called in case of failure)\n*/\nstatic int removedyncap (lua_State *L, Capture *capture,\n                         int level, int last) {\n  int id = finddyncap(capture + level, capture + last);  /* index of 1st cap. */\n  int top = lua_gettop(L);\n  if (id == 0) return 0;  /* no dynamic captures? */\n  lua_settop(L, id - 1);  /* remove captures */\n  return top - id + 1;  /* number of values removed */\n}\n\n\n/*\n** Find the corresponding 'open' capture before 'cap', when that capture\n** can become a full capture. If a full capture c1 is followed by an\n** empty capture c2, there is no way to know whether c2 is inside\n** c1. So, full captures can enclose only captures that start *before*\n** its end.\n*/\nstatic Capture *findopen (Capture *cap, Index_t currindex) {\n  int i;\n  cap--;  /* check last capture */\n  /* Must it be inside current one, but starts where current one ends? */\n  if (!isopencap(cap) && cap->index == currindex)\n    return NULL;  /* current one cannot be a full capture */\n  /* else, look for an 'open' capture */\n  for (i = 0; i < MAXLOP; i++, cap--) {\n    if (currindex - cap->index >= UCHAR_MAX)\n      return NULL;  /* capture too long for a full capture */\n    else if (isopencap(cap))  /* open capture? */\n      return cap;  /* that's the one to be closed */\n    else if (cap->kind == Cclose)\n      return NULL;  /* a full capture should not nest a non-full one */\n  }\n  return NULL;  /* not found within allowed search limit */\n}\n\n\n/*\n** Opcode interpreter\n*/\nconst char *match (lua_State *L, const char *o, const char *s, const char *e,\n                   Instruction *op, Capture *capture, int ptop) {\n  Stack stackbase[INITBACK];\n  Stack *stacklimit = stackbase + INITBACK;\n  Stack *stack = stackbase;  /* point to first empty slot in stack */\n  int capsize = INITCAPSIZE;\n  int captop = 0;  /* point to first empty slot in captures */\n  int ndyncap = 0;  /* number of dynamic captures (in Lua stack) */\n  const Instruction *p = op;  /* current instruction */\n  stack->p = &giveup; stack->s = s; stack->caplevel = 0; stack++;\n  lua_pushlightuserdata(L, stackbase);\n  for (;;) {\n#if defined(DEBUG)\n      printf(\"-------------------------------------\\n\");\n      printcaplist(capture, capture + captop);\n      printf(\"s: |%s| stck:%d, dyncaps:%d, caps:%d  \",\n             s, (int)(stack - getstackbase(L, ptop)), ndyncap, captop);\n      printinst(op, p);\n#endif\n    assert(stackidx(ptop) + ndyncap == lua_gettop(L) && ndyncap <= captop);\n    switch ((Opcode)p->i.code) {\n      case IEnd: {\n        assert(stack == getstackbase(L, ptop) + 1);\n        capture[captop].kind = Cclose;\n        capture[captop].index = MAXINDT;\n        return s;\n      }\n      case IGiveup: {\n        assert(stack == getstackbase(L, ptop));\n        return NULL;\n      }\n      case IRet: {\n        assert(stack > getstackbase(L, ptop) && (stack - 1)->s == NULL);\n        p = (--stack)->p;\n        continue;\n      }\n      case IAny: {\n        if (s < e) { p++; s++; }\n        else goto fail;\n        continue;\n      }\n      case IUTFR: {\n        int codepoint;\n        if (s >= e)\n          goto fail;\n        s = utf8_decode (s, &codepoint);\n        if (s && p[1].offset <= codepoint && codepoint <= utf_to(p))\n          p += 2;\n        else\n          goto fail;\n        continue;\n      }\n      case ITestAny: {\n        if (s < e) p += 2;\n        else p += getoffset(p);\n        continue;\n      }\n      case IChar: {\n        if ((byte)*s == p->i.aux1 && s < e) { p++; s++; }\n        else goto fail;\n        continue;\n      }\n      case ITestChar: {\n        if ((byte)*s == p->i.aux1 && s < e) p += 2;\n        else p += getoffset(p);\n        continue;\n      }\n      case ISet: {\n        uint c = (byte)*s;\n        if (charinset(p, (p+1)->buff, c) && s < e)\n          { p += 1 + p->i.aux2.set.size; s++; }\n        else goto fail;\n        continue;\n      }\n      case ITestSet: {\n        uint c = (byte)*s;\n        if (charinset(p, (p + 2)->buff, c) && s < e)\n          p += 2 + p->i.aux2.set.size;\n        else p += getoffset(p);\n        continue;\n      }\n      case IBehind: {\n        int n = p->i.aux1;\n        if (n > s - o) goto fail;\n        s -= n; p++;\n        continue;\n      }\n      case ISpan: {\n        for (; s < e; s++) {\n          uint c = (byte)*s;\n          if (!charinset(p, (p+1)->buff, c)) break;\n        }\n        p += 1 + p->i.aux2.set.size;\n        continue;\n      }\n      case IJmp: {\n        p += getoffset(p);\n        continue;\n      }\n      case IChoice: {\n        if (stack == stacklimit)\n          stack = doublestack(L, &stacklimit, ptop);\n        stack->p = p + getoffset(p);\n        stack->s = s;\n        stack->caplevel = captop;\n        stack++;\n        p += 2;\n        continue;\n      }\n      case ICall: {\n        if (stack == stacklimit)\n          stack = doublestack(L, &stacklimit, ptop);\n        stack->s = NULL;\n        stack->p = p + 2;  /* save return address */\n        stack++;\n        p += getoffset(p);\n        continue;\n      }\n      case ICommit: {\n        assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);\n        stack--;\n        p += getoffset(p);\n        continue;\n      }\n      case IPartialCommit: {\n        assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);\n        (stack - 1)->s = s;\n        (stack - 1)->caplevel = captop;\n        p += getoffset(p);\n        continue;\n      }\n      case IBackCommit: {\n        assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);\n        s = (--stack)->s;\n        if (ndyncap > 0)  /* are there matchtime captures? */\n          ndyncap -= removedyncap(L, capture, stack->caplevel, captop);\n        captop = stack->caplevel;\n        p += getoffset(p);\n        continue;\n      }\n      case IFailTwice:\n        assert(stack > getstackbase(L, ptop));\n        stack--;\n        /* FALLTHROUGH */\n      case IFail:\n      fail: { /* pattern failed: try to backtrack */\n        do {  /* remove pending calls */\n          assert(stack > getstackbase(L, ptop));\n          s = (--stack)->s;\n        } while (s == NULL);\n        if (ndyncap > 0)  /* is there matchtime captures? */\n          ndyncap -= removedyncap(L, capture, stack->caplevel, captop);\n        captop = stack->caplevel;\n        p = stack->p;\n#if defined(DEBUG)\n        printf(\"**FAIL**\\n\");\n#endif\n        continue;\n      }\n      case ICloseRunTime: {\n        CapState cs;\n        int rem, res, n;\n        int fr = lua_gettop(L) + 1;  /* stack index of first result */\n        cs.reclevel = 0; cs.L = L;\n        cs.s = o; cs.ocap = capture; cs.ptop = ptop;\n        n = runtimecap(&cs, capture + captop, s, &rem);  /* call function */\n        captop -= n;  /* remove nested captures */\n        ndyncap -= rem;  /* update number of dynamic captures */\n        fr -= rem;  /* 'rem' items were popped from Lua stack */\n        res = resdyncaptures(L, fr, s - o, e - o);  /* get result */\n        if (res == -1)  /* fail? */\n          goto fail;\n        s = o + res;  /* else update current position */\n        n = lua_gettop(L) - fr + 1;  /* number of new captures */\n        ndyncap += n;  /* update number of dynamic captures */\n        if (n == 0)  /* no new captures? */\n          captop--;  /* remove open group */\n        else {  /* new captures; keep original open group */\n          if (fr + n >= SHRT_MAX)\n            luaL_error(L, \"too many results in match-time capture\");\n          /* add new captures + close group to 'capture' list */\n          capture = growcap(L, capture, &capsize, captop, n + 1, ptop);\n          adddyncaptures(s - o, capture + captop, n, fr);\n          captop += n + 1;  /* new captures + close group */\n        }\n        p++;\n        continue;\n      }\n      case ICloseCapture: {\n        Capture *open = findopen(capture + captop, s - o);\n        assert(captop > 0);\n        if (open) {  /* if possible, turn capture into a full capture */\n          open->siz = (s - o) - open->index + 1;\n          p++;\n          continue;\n        }\n        else {  /* must create a close capture */\n          capture[captop].siz = 1;  /* mark entry as closed */\n          capture[captop].index = s - o;\n          goto pushcapture;\n        }\n      }\n      case IOpenCapture:\n        capture[captop].siz = 0;  /* mark entry as open */\n        capture[captop].index = s - o;\n        goto pushcapture;\n      case IFullCapture:\n        capture[captop].siz = getoff(p) + 1;  /* save capture size */\n        capture[captop].index = s - o - getoff(p);\n        /* goto pushcapture; */\n      pushcapture: {\n        capture[captop].idx = p->i.aux2.key;\n        capture[captop].kind = getkind(p);\n        captop++;\n        capture = growcap(L, capture, &capsize, captop, 0, ptop);\n        p++;\n        continue;\n      }\n      default: assert(0); return NULL;\n    }\n  }\n}\n\n/* }====================================================== */\n\n\n"
  },
  {
    "path": "3rd/lpeg/lpvm.h",
    "content": "\n#if !defined(lpvm_h)\n#define lpvm_h\n\n#include \"lpcap.h\"\n\n\n/*\n** About Character sets in instructions: a set is a bit map with an\n** initial offset, in bits, and a size, in number of instructions.\n** aux1 has the default value for the bits outsize that range.\n*/\n\n\n/* Virtual Machine's instructions */\ntypedef enum Opcode {\n  IAny, /* if no char, fail */\n  IChar,  /* if char != aux1, fail */\n  ISet,  /* if char not in set, fail */\n  ITestAny,  /* in no char, jump to 'offset' */\n  ITestChar,  /* if char != aux1, jump to 'offset' */\n  ITestSet,  /* if char not in set, jump to 'offset' */\n  ISpan,  /* read a span of chars in set */\n  IUTFR,  /* if codepoint not in range [offset, utf_to], fail */\n  IBehind,  /* walk back 'aux1' characters (fail if not possible) */\n  IRet,  /* return from a rule */\n  IEnd,  /* end of pattern */\n  IChoice,  /* stack a choice; next fail will jump to 'offset' */\n  IJmp,  /* jump to 'offset' */\n  ICall,  /* call rule at 'offset' */\n  IOpenCall,  /* call rule number 'key' (must be closed to a ICall) */\n  ICommit,  /* pop choice and jump to 'offset' */\n  IPartialCommit,  /* update top choice to current position and jump */\n  IBackCommit,  /* backtrack like \"fail\" but jump to its own 'offset' */\n  IFailTwice,  /* pop one choice and then fail */\n  IFail,  /* go back to saved state on choice and jump to saved offset */\n  IGiveup,  /* internal use */\n  IFullCapture,  /* complete capture of last 'off' chars */\n  IOpenCapture,  /* start a capture */\n  ICloseCapture,\n  ICloseRunTime,\n  IEmpty  /* to fill empty slots left by optimizations */\n} Opcode;\n\n\n/*\n** All array of instructions has a 'codesize' as its first element\n** and is referred by a pointer to its second element, which is the\n** first actual opcode.\n*/\ntypedef union Instruction {\n  struct Inst {\n    byte code;\n    byte aux1;\n    union {\n      short key;\n      struct {\n        byte offset;\n        byte size;\n      } set;\n    } aux2;\n  } i;\n  int offset;\n  uint codesize;\n  byte buff[1];\n} Instruction;\n\n\n/* extract 24-bit value from an instruction */\n#define utf_to(inst)\t(((inst)->i.aux2.key << 8) | (inst)->i.aux1)\n\n\nint charinset (const Instruction *i, const byte *buff, uint c);\nconst char *match (lua_State *L, const char *o, const char *s, const char *e,\n                   Instruction *op, Capture *capture, int ptop);\n\n\n#endif\n\n"
  },
  {
    "path": "3rd/lpeg/makefile",
    "content": "LIBNAME = lpeg\nLUADIR = ../lua/\n\nCOPT = -O2 -DNDEBUG\n# COPT = -O0 -DLPEG_DEBUG -g\n\nCWARNS = -Wall -Wextra -pedantic \\\n\t-Waggregate-return \\\n\t-Wcast-align \\\n\t-Wcast-qual \\\n\t-Wdisabled-optimization \\\n\t-Wpointer-arith \\\n\t-Wshadow \\\n\t-Wredundant-decls \\\n\t-Wsign-compare \\\n\t-Wundef \\\n\t-Wwrite-strings \\\n\t-Wbad-function-cast \\\n\t-Wdeclaration-after-statement \\\n\t-Wmissing-prototypes \\\n\t-Wmissing-declarations \\\n\t-Wnested-externs \\\n\t-Wstrict-prototypes \\\n\t-Wc++-compat \\\n# -Wunreachable-code \\\n\n\nCFLAGS = $(CWARNS) $(COPT) -std=c99 -I$(LUADIR) -fPIC\nCC = gcc\n\nFILES = lpvm.o lpcap.o lptree.o lpcode.o lpprint.o lpcset.o\n\n# For Linux\nlinux:\n\t$(MAKE) lpeg.so \"DLLFLAGS = -shared -fPIC\"\n\n# For Mac OS\nmacosx:\n\t$(MAKE) lpeg.so \"DLLFLAGS = -bundle -undefined dynamic_lookup\"\n\nlpeg.so: $(FILES)\n\tenv $(CC) $(DLLFLAGS) $(FILES) -o lpeg.so\n\n$(FILES): makefile\n\ntest: test.lua re.lua lpeg.so\n\t./test.lua\n\nclean:\n\trm -f $(FILES) lpeg.so\n\n\nlpcap.o: lpcap.c lpcap.h lptypes.h\nlpcode.o: lpcode.c lptypes.h lpcode.h lptree.h lpvm.h lpcap.h lpcset.h\nlpcset.o: lpcset.c lptypes.h lpcset.h lpcode.h lptree.h lpvm.h lpcap.h\nlpprint.o: lpprint.c lptypes.h lpprint.h lptree.h lpvm.h lpcap.h lpcode.h\nlptree.o: lptree.c lptypes.h lpcap.h lpcode.h lptree.h lpvm.h lpprint.h \\\n lpcset.h\nlpvm.o: lpvm.c lpcap.h lptypes.h lpvm.h lpprint.h lptree.h\n"
  },
  {
    "path": "3rd/lpeg/re.html",
    "content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n   \"//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html>\n<head>\n    <title>LPeg.re - Regex syntax for LPEG</title>\n    <link rel=\"stylesheet\"\n          href=\"//www.inf.puc-rio.br/~roberto/lpeg/doc.css\"\n          type=\"text/css\"/>\n\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n</head>\n<body>\n\n\n<div id=\"container\">\n\t\n<div id=\"product\">\n  <div id=\"product_logo\">\n    <a href=\"//www.inf.puc-rio.br/~roberto/lpeg/\">\n    <img alt=\"LPeg logo\" src=\"lpeg-128.gif\"/>\n    </a>\n  </div>\n  <div id=\"product_name\"><big><strong>LPeg.re</strong></big></div>\n  <div id=\"product_description\">\n     Regex syntax for LPEG\n  </div>\n</div> <!-- id=\"product\" -->\n\n<div id=\"main\">\n\t\n<div id=\"navigation\">\n<h1>re</h1>\n\n<ul>\n  <li><a href=\"#basic\">Basic Constructions</a></li>\n  <li><a href=\"#func\">Functions</a></li>\n  <li><a href=\"#ex\">Some Examples</a></li>\n  <li><a href=\"#license\">License</a></li>\n  </ul>\n  </li>\n</ul>\n</div> <!-- id=\"navigation\" -->\n\n<div id=\"content\">\n\n<h2><a name=\"basic\"></a>The <code>re</code> Module</h2>\n\n<p>\nThe <code>re</code> module\n(provided by file <code>re.lua</code> in the distribution)\nsupports a somewhat conventional regex syntax\nfor pattern usage within <a href=\"lpeg.html\">LPeg</a>.\n</p>\n\n<p>\nThe next table summarizes <code>re</code>'s syntax.\nA <code>p</code> represents an arbitrary pattern;\n<code>num</code> represents a number (<code>[0-9]+</code>);\n<code>name</code> represents an identifier\n(<code>[a-zA-Z][a-zA-Z0-9_]*</code>).\nConstructions are listed in order of decreasing precedence.\n<table border=\"1\">\n<tbody><tr><td><b>Syntax</b></td><td><b>Description</b></td></tr>\n<tr><td><code>( p )</code></td> <td>grouping</td></tr>\n<tr><td><code>&amp; p</code></td> <td>and predicate</td></tr>\n<tr><td><code>! p</code></td> <td>not predicate</td></tr>\n<tr><td><code>p1 p2</code></td> <td>concatenation</td></tr>\n<tr><td><code>p1 / p2</code></td> <td>ordered choice</td></tr>\n<tr><td><code>p ?</code></td> <td>optional match</td></tr>\n<tr><td><code>p *</code></td> <td>zero or more repetitions</td></tr>\n<tr><td><code>p +</code></td> <td>one or more repetitions</td></tr>\n<tr><td><code>p^num</code></td>\n      <td>exactly <code>num</code> repetitions</td></tr>\n<tr><td><code>p^+num</code></td>\n      <td>at least <code>num</code> repetitions</td></tr>\n<tr><td><code>p^-num</code></td>\n      <td>at most <code>num</code> repetitions</td></tr>\n<tr><td>(<code>name &lt;- p</code>)<sup>+</sup></td> <td>grammar</td></tr>\n<tr><td><code>'string'</code></td> <td>literal string</td></tr>\n<tr><td><code>\"string\"</code></td> <td>literal string</td></tr>\n<tr><td><code>[class]</code></td> <td>character class</td></tr>\n<tr><td><code>.</code></td> <td>any character</td></tr>\n<tr><td><code>%name</code></td>\n  <td>pattern <code>defs[name]</code> or a pre-defined pattern</td></tr>\n<tr><td><code>name</code></td><td>non terminal</td></tr>\n<tr><td><code>&lt;name&gt;</code></td><td>non terminal</td></tr>\n\n<tr><td><code>{}</code></td> <td>position capture</td></tr>\n<tr><td><code>{ p }</code></td> <td>simple capture</td></tr>\n<tr><td><code>{: p :}</code></td> <td>anonymous group capture</td></tr>\n<tr><td><code>{:name: p :}</code></td> <td>named group capture</td></tr>\n<tr><td><code>{~ p ~}</code></td> <td>substitution capture</td></tr>\n<tr><td><code>{| p |}</code></td> <td>table capture</td></tr>\n<tr><td><code>=name</code></td> <td>back reference</td></tr>\n\n<tr><td><code>p -&gt; 'string'</code></td> <td>string capture</td></tr>\n<tr><td><code>p -&gt; \"string\"</code></td> <td>string capture</td></tr>\n<tr><td><code>p -&gt; num</code></td> <td>numbered capture</td></tr>\n<tr><td><code>p -&gt; name</code></td> <td>function/query/string capture\nequivalent to <code>p / defs[name]</code></td></tr>\n<tr><td><code>p =&gt; name</code></td> <td>match-time capture\nequivalent to <code>lpeg.Cmt(p, defs[name])</code></td></tr>\n<tr><td><code>p ~&gt; name</code></td> <td>fold capture\n(deprecated)</td></tr>\n<tr><td><code>p &gt;&gt; name</code></td> <td>accumulator capture\nequivalent to <code>(p % defs[name])</code></td></tr>\n</tbody></table>\n<p>\nAny space appearing in a syntax description can be\nreplaced by zero or more space characters and Lua-style short comments\n(<code>--</code> until end of line).\n</p>\n\n<p>\nCharacter classes define sets of characters.\nAn initial <code>^</code> complements the resulting set.\nA range <em>x</em><code>-</code><em>y</em> includes in the set\nall characters with codes between the codes of <em>x</em> and <em>y</em>.\nA pre-defined class <code>%</code><em>name</em> includes all\ncharacters of that class.\nA simple character includes itself in the set.\nThe only special characters inside a class are <code>^</code>\n(special only if it is the first character);\n<code>]</code>\n(can be included in the set as the first character,\nafter the optional <code>^</code>);\n<code>%</code> (special only if followed by a letter);\nand <code>-</code>\n(can be included in the set as the first or the last character).\n</p>\n\n<p>\nCurrently the pre-defined classes are similar to those from the\nLua's string library\n(<code>%a</code> for letters,\n<code>%A</code> for non letters, etc.).\nThere is also a class <code>%nl</code>\ncontaining only the newline character,\nwhich is particularly handy for grammars written inside long strings,\nas long strings do not interpret escape sequences like <code>\\n</code>.\n</p>\n\n\n<h2><a name=\"func\">Functions</a></h2>\n\n<h3><code>re.compile (string, [, defs])</code></h3>\n<p>\nCompiles the given string and\nreturns an equivalent LPeg pattern.\nThe given string may define either an expression or a grammar.\nThe optional <code>defs</code> table provides extra Lua values\nto be used by the pattern.\n</p>\n\n<h3><code>re.find (subject, pattern [, init])</code></h3>\n<p>\nSearches the given pattern in the given subject.\nIf it finds a match,\nreturns the index where this occurrence starts and\nthe index where it ends.\nOtherwise, returns nil.\n</p>\n\n<p>\nAn optional numeric argument <code>init</code> makes the search\nstarts at that position in the subject string.\nAs usual in Lua libraries,\na negative value counts from the end.\n</p>\n\n<h3><code>re.gsub (subject, pattern, replacement)</code></h3>\n<p>\nDoes a <em>global substitution</em>,\nreplacing all occurrences of <code>pattern</code>\nin the given <code>subject</code> by <code>replacement</code>.\n\n<h3><code>re.match (subject, pattern)</code></h3>\n<p>\nMatches the given pattern against the given subject,\nreturning all captures.\n</p>\n\n<h3><code>re.updatelocale ()</code></h3>\n<p>\nUpdates the pre-defined character classes to the current locale.\n</p>\n\n\n<h2><a name=\"ex\">Some Examples</a></h2>\n\n<h3>A complete simple program</h3>\n<p>\nThe next code shows a simple complete Lua program using\nthe <code>re</code> module:\n</p>\n<pre class=\"example\">\nlocal re = require\"re\"\n\n-- find the position of the first numeral in a string\nprint(re.find(\"the number 423 is odd\", \"[0-9]+\"))  --&gt; 12    14\n\n-- returns all words in a string\nprint(re.match(\"the number 423 is odd\", \"({%a+} / .)*\"))\n--&gt; the    number    is    odd\n\n-- returns the first numeral in a string\nprint(re.match(\"the number 423 is odd\", \"s &lt;- {%d+} / . s\"))\n--&gt; 423\n\n-- substitutes a dot for each vowel in a string\nprint(re.gsub(\"hello World\", \"[aeiou]\", \".\"))\n--&gt; h.ll. W.rld\n</pre>\n\n\n<h3>Balanced parentheses</h3>\n<p>\nThe following call will produce the same pattern produced by the\nLua expression in the\n<a href=\"lpeg.html#balanced\">balanced parentheses</a> example:\n</p>\n<pre class=\"example\">\nb = re.compile[[  balanced &lt;- \"(\" ([^()] / balanced)* \")\"  ]]\n</pre>\n\n<h3>String reversal</h3>\n<p>\nThe next example reverses a string:\n</p>\n<pre class=\"example\">\nrev = re.compile[[ R &lt;- (!.) -&gt; '' / ({.} R) -&gt; '%2%1']]\nprint(rev:match\"0123456789\")   --&gt; 9876543210\n</pre>\n\n<h3>CSV decoder</h3>\n<p>\nThe next example replicates the <a href=\"lpeg.html#CSV\">CSV decoder</a>:\n</p>\n<pre class=\"example\">\nrecord = re.compile[[\n  record &lt;- {| field (',' field)* |} (%nl / !.)\n  field &lt;- escaped / nonescaped\n  nonescaped &lt;- { [^,\"%nl]* }\n  escaped &lt;- '\"' {~ ([^\"] / '\"\"' -&gt; '\"')* ~} '\"'\n]]\n</pre>\n\n<h3>Lua's long strings</h3>\n<p>\nThe next example matches Lua long strings:\n</p>\n<pre class=\"example\">\nc = re.compile([[\n  longstring &lt;- ('[' {:eq: '='* :} '[' close)\n  close &lt;- ']' =eq ']' / . close\n]])\n\nprint(c:match'[==[]]===]]]]==]===[]')   --&gt; 17\n</pre>\n\n<h3>Abstract Syntax Trees</h3>\n<p>\nThis example shows a simple way to build an\nabstract syntax tree (AST) for a given grammar.\nTo keep our example simple,\nlet us consider the following grammar\nfor lists of names:\n</p>\n<pre class=\"example\">\np = re.compile[[\n      listname &lt;- (name s)*\n      name &lt;- [a-z][a-z]*\n      s &lt;- %s*\n]]\n</pre>\n<p>\nNow, we will add captures to build a corresponding AST.\nAs a first step, the pattern will build a table to\nrepresent each non terminal;\nterminals will be represented by their corresponding strings:\n</p>\n<pre class=\"example\">\nc = re.compile[[\n      listname &lt;- {| (name s)* |}\n      name &lt;- {| {[a-z][a-z]*} |}\n      s &lt;- %s*\n]]\n</pre>\n<p>\nNow, a match against <code>\"hi hello bye\"</code>\nresults in the table\n<code>{{\"hi\"}, {\"hello\"}, {\"bye\"}}</code>.\n</p>\n<p>\nFor such a simple grammar,\nthis AST is more than enough;\nactually, the tables around each single name\nare already overkilling.\nMore complex grammars,\nhowever, may need some more structure.\nSpecifically,\nit would be useful if each table had\na <code>tag</code> field telling what non terminal\nthat table represents.\nWe can add such a tag using\n<a href=\"lpeg.html#cap-g\">named group captures</a>:\n</p>\n<pre class=\"example\">\nx = re.compile[[\n      listname <- {| {:tag: '' -> 'list':} (name s)* |}\n      name <- {| {:tag: '' -> 'id':} {[a-z][a-z]*} |}\n      s <- ' '*\n]]\n</pre>\n<p>\nWith these group captures,\na match against <code>\"hi hello bye\"</code>\nresults in the following table:\n</p>\n<pre class=\"example\">\n{tag=\"list\",\n  {tag=\"id\", \"hi\"},\n  {tag=\"id\", \"hello\"},\n  {tag=\"id\", \"bye\"}\n}\n</pre>\n\n\n<h3>Indented blocks</h3>\n<p>\nThis example breaks indented blocks into tables,\nrespecting the indentation:\n</p>\n<pre class=\"example\">\np = re.compile[[\n  block &lt;- {| {:ident:' '*:} line\n           ((=ident !' ' line) / &amp;(=ident ' ') block)* |}\n  line &lt;- {[^%nl]*} %nl\n]]\n</pre>\n<p>\nAs an example,\nconsider the following text:\n</p>\n<pre class=\"example\">\nt = p:match[[\nfirst line\n  subline 1\n  subline 2\nsecond line\nthird line\n  subline 3.1\n    subline 3.1.1\n  subline 3.2\n]]\n</pre>\n<p>\nThe resulting table <code>t</code> will be like this:\n</p>\n<pre class=\"example\">\n   {'first line'; {'subline 1'; 'subline 2'; ident = '  '};\n    'second line';\n    'third line'; { 'subline 3.1'; {'subline 3.1.1'; ident = '    '};\n                    'subline 3.2'; ident = '  '};\n    ident = ''}\n</pre>\n\n<h3>Macro expander</h3>\n<p>\nThis example implements a simple macro expander.\nMacros must be defined as part of the pattern,\nfollowing some simple rules:\n</p>\n<pre class=\"example\">\np = re.compile[[\n      text &lt;- {~ item* ~}\n      item &lt;- macro / [^()] / '(' item* ')'\n      arg &lt;- ' '* {~ (!',' item)* ~}\n      args &lt;- '(' arg (',' arg)* ')'\n      -- now we define some macros\n      macro &lt;- ('apply' args) -&gt; '%1(%2)'\n             / ('add' args) -&gt; '%1 + %2'\n             / ('mul' args) -&gt; '%1 * %2'\n]]\n\nprint(p:match\"add(mul(a,b), apply(f,x))\")   --&gt; a * b + f(x)\n</pre>\n<p>\nA <code>text</code> is a sequence of items,\nwherein we apply a substitution capture to expand any macros.\nAn <code>item</code> is either a macro,\nany character different from parentheses,\nor a parenthesized expression.\nA macro argument (<code>arg</code>) is a sequence\nof items different from a comma.\n(Note that a comma may appear inside an item,\ne.g., inside a parenthesized expression.)\nAgain we do a substitution capture to expand any macro\nin the argument before expanding the outer macro.\n<code>args</code> is a list of arguments separated by commas.\nFinally we define the macros.\nEach macro is a string substitution;\nit replaces the macro name and its arguments by its corresponding string,\nwith each <code>%</code><em>n</em> replaced by the <em>n</em>-th argument.\n</p>\n\n<h3>Patterns</h3>\n<p>\nThis example shows the complete syntax\nof patterns accepted by <code>re</code>.\n</p>\n<pre class=\"example\">\np = [=[\n\npattern         &lt;- exp !.\nexp             &lt;- S (grammar / alternative)\n\nalternative     &lt;- seq ('/' S seq)*\nseq             &lt;- prefix*\nprefix          &lt;- '&amp;' S prefix / '!' S prefix / suffix\nsuffix          &lt;- primary S (([+*?]\n                            / '^' [+-]? num\n                            / '-&gt;' S (string / '{}' / name)\n                            / '&gt&gt;' S name\n                            / '=&gt;' S name) S)*\n\nprimary         &lt;- '(' exp ')' / string / class / defined\n                 / '{:' (name ':')? exp ':}'\n                 / '=' name\n                 / '{}'\n                 / '{~' exp '~}'\n                 / '{|' exp '|}'\n                 / '{' exp '}'\n                 / '.'\n                 / name S !arrow\n                 / '&lt;' name '&gt;'          -- old-style non terminals\n\ngrammar         &lt;- definition+\ndefinition      &lt;- name S arrow exp\n\nclass           &lt;- '[' '^'? item (!']' item)* ']'\nitem            &lt;- defined / range / .\nrange           &lt;- . '-' [^]]\n\nS               &lt;- (%s / '--' [^%nl]*)*   -- spaces and comments\nname            &lt;- [A-Za-z_][A-Za-z0-9_]*\narrow           &lt;- '&lt;-'\nnum             &lt;- [0-9]+\nstring          &lt;- '\"' [^\"]* '\"' / \"'\" [^']* \"'\"\ndefined         &lt;- '%' name\n\n]=]\n\nprint(re.match(p, p))   -- a self description must match itself\n</pre>\n\n\n\n<h2><a name=\"license\">License</a></h2>\n\n<p>\nThis module is part of the <a href=\"lpeg.html\">LPeg</a> package and shares\nits <a href=\"lpeg.html#license\">license</a>.\n\n\n</div> <!-- id=\"content\" -->\n\n</div> <!-- id=\"main\" -->\n\n</div> <!-- id=\"container\" -->\n\n</body>\n</html> \n"
  },
  {
    "path": "3rd/lpeg/re.lua",
    "content": "--\n-- Copyright 2007-2023, Lua.org & PUC-Rio  (see 'lpeg.html' for license)\n-- written by Roberto Ierusalimschy\n--\n\n-- imported functions and modules\nlocal tonumber, type, print, error = tonumber, type, print, error\nlocal setmetatable = setmetatable\nlocal m = require\"lpeg\"\n\n-- 'm' will be used to parse expressions, and 'mm' will be used to\n-- create expressions; that is, 're' runs on 'm', creating patterns\n-- on 'mm'\nlocal mm = m\n\n-- patterns' metatable\nlocal mt = getmetatable(mm.P(0))\n\n\nlocal version = _VERSION\n\n-- No more global accesses after this point\n_ENV = nil     -- does no harm in Lua 5.1\n\n\nlocal any = m.P(1)\n\n\n-- Pre-defined names\nlocal Predef = { nl = m.P\"\\n\" }\n\n\nlocal mem\nlocal fmem\nlocal gmem\n\n\nlocal function updatelocale ()\n  mm.locale(Predef)\n  Predef.a = Predef.alpha\n  Predef.c = Predef.cntrl\n  Predef.d = Predef.digit\n  Predef.g = Predef.graph\n  Predef.l = Predef.lower\n  Predef.p = Predef.punct\n  Predef.s = Predef.space\n  Predef.u = Predef.upper\n  Predef.w = Predef.alnum\n  Predef.x = Predef.xdigit\n  Predef.A = any - Predef.a\n  Predef.C = any - Predef.c\n  Predef.D = any - Predef.d\n  Predef.G = any - Predef.g\n  Predef.L = any - Predef.l\n  Predef.P = any - Predef.p\n  Predef.S = any - Predef.s\n  Predef.U = any - Predef.u\n  Predef.W = any - Predef.w\n  Predef.X = any - Predef.x\n  mem = {}    -- restart memoization\n  fmem = {}\n  gmem = {}\n  local mt = {__mode = \"v\"}\n  setmetatable(mem, mt)\n  setmetatable(fmem, mt)\n  setmetatable(gmem, mt)\nend\n\n\nupdatelocale()\n\n\n\nlocal I = m.P(function (s,i) print(i, s:sub(1, i-1)); return i end)\n\n\nlocal function patt_error (s, i)\n  local msg = (#s < i + 20) and s:sub(i)\n                             or s:sub(i,i+20) .. \"...\"\n  msg = (\"pattern error near '%s'\"):format(msg)\n  error(msg, 2)\nend\n\nlocal function mult (p, n)\n  local np = mm.P(true)\n  while n >= 1 do\n    if n%2 >= 1 then np = np * p end\n    p = p * p\n    n = n/2\n  end\n  return np\nend\n\nlocal function equalcap (s, i, c)\n  if type(c) ~= \"string\" then return nil end\n  local e = #c + i\n  if s:sub(i, e - 1) == c then return e else return nil end\nend\n\n\nlocal S = (Predef.space + \"--\" * (any - Predef.nl)^0)^0\n\nlocal name = m.R(\"AZ\", \"az\", \"__\") * m.R(\"AZ\", \"az\", \"__\", \"09\")^0\n\nlocal arrow = S * \"<-\"\n\nlocal seq_follow = m.P\"/\" + \")\" + \"}\" + \":}\" + \"~}\" + \"|}\" + (name * arrow) + -1\n\nname = m.C(name)\n\n\n-- a defined name only have meaning in a given environment\nlocal Def = name * m.Carg(1)\n\n\nlocal function getdef (id, defs)\n  local c = defs and defs[id]\n  if not c then error(\"undefined name: \" .. id) end\n  return c\nend\n\n-- match a name and return a group of its corresponding definition\n-- and 'f' (to be folded in 'Suffix')\nlocal function defwithfunc (f)\n  return m.Cg(Def / getdef * m.Cc(f))\nend\n\n\nlocal num = m.C(m.R\"09\"^1) * S / tonumber\n\nlocal String = \"'\" * m.C((any - \"'\")^0) * \"'\" +\n               '\"' * m.C((any - '\"')^0) * '\"'\n\n\nlocal defined = \"%\" * Def / function (c,Defs)\n  local cat =  Defs and Defs[c] or Predef[c]\n  if not cat then error (\"name '\" .. c .. \"' undefined\") end\n  return cat\nend\n\nlocal Range = m.Cs(any * (m.P\"-\"/\"\") * (any - \"]\")) / mm.R\n\nlocal item = (defined + Range + m.C(any)) / m.P\n\nlocal Class =\n    \"[\"\n  * (m.C(m.P\"^\"^-1))    -- optional complement symbol\n  * (item * ((item % mt.__add) - \"]\")^0) /\n                          function (c, p) return c == \"^\" and any - p or p end\n  * \"]\"\n\nlocal function adddef (t, k, exp)\n  if t[k] then\n    error(\"'\"..k..\"' already defined as a rule\")\n  else\n    t[k] = exp\n  end\n  return t\nend\n\nlocal function firstdef (n, r) return adddef({n}, n, r) end\n\n\nlocal function NT (n, b)\n  if not b then\n    error(\"rule '\"..n..\"' used outside a grammar\")\n  else return mm.V(n)\n  end\nend\n\n\nlocal exp = m.P{ \"Exp\",\n  Exp = S * ( m.V\"Grammar\"\n            + m.V\"Seq\" * (\"/\" * S * m.V\"Seq\" % mt.__add)^0 );\n  Seq = (m.Cc(m.P\"\") * (m.V\"Prefix\" % mt.__mul)^0)\n        * (#seq_follow + patt_error);\n  Prefix = \"&\" * S * m.V\"Prefix\" / mt.__len\n         + \"!\" * S * m.V\"Prefix\" / mt.__unm\n         + m.V\"Suffix\";\n  Suffix = m.V\"Primary\" * S *\n          ( ( m.P\"+\" * m.Cc(1, mt.__pow)\n            + m.P\"*\" * m.Cc(0, mt.__pow)\n            + m.P\"?\" * m.Cc(-1, mt.__pow)\n            + \"^\" * ( m.Cg(num * m.Cc(mult))\n                    + m.Cg(m.C(m.S\"+-\" * m.R\"09\"^1) * m.Cc(mt.__pow))\n                    )\n            + \"->\" * S * ( m.Cg((String + num) * m.Cc(mt.__div))\n                         + m.P\"{}\" * m.Cc(nil, m.Ct)\n                         + defwithfunc(mt.__div)\n                         )\n            + \"=>\" * S * defwithfunc(mm.Cmt)\n            + \">>\" * S * defwithfunc(mt.__mod)\n            + \"~>\" * S * defwithfunc(mm.Cf)\n            ) % function (a,b,f) return f(a,b) end * S\n          )^0;\n  Primary = \"(\" * m.V\"Exp\" * \")\"\n            + String / mm.P\n            + Class\n            + defined\n            + \"{:\" * (name * \":\" + m.Cc(nil)) * m.V\"Exp\" * \":}\" /\n                     function (n, p) return mm.Cg(p, n) end\n            + \"=\" * name / function (n) return mm.Cmt(mm.Cb(n), equalcap) end\n            + m.P\"{}\" / mm.Cp\n            + \"{~\" * m.V\"Exp\" * \"~}\" / mm.Cs\n            + \"{|\" * m.V\"Exp\" * \"|}\" / mm.Ct\n            + \"{\" * m.V\"Exp\" * \"}\" / mm.C\n            + m.P\".\" * m.Cc(any)\n            + (name * -arrow + \"<\" * name * \">\") * m.Cb(\"G\") / NT;\n  Definition = name * arrow * m.V\"Exp\";\n  Grammar = m.Cg(m.Cc(true), \"G\") *\n            ((m.V\"Definition\" / firstdef) * (m.V\"Definition\" % adddef)^0) / mm.P\n}\n\nlocal pattern = S * m.Cg(m.Cc(false), \"G\") * exp / mm.P * (-any + patt_error)\n\n\nlocal function compile (p, defs)\n  if mm.type(p) == \"pattern\" then return p end   -- already compiled\n  local cp = pattern:match(p, 1, defs)\n  if not cp then error(\"incorrect pattern\", 3) end\n  return cp\nend\n\nlocal function match (s, p, i)\n  local cp = mem[p]\n  if not cp then\n    cp = compile(p)\n    mem[p] = cp\n  end\n  return cp:match(s, i or 1)\nend\n\nlocal function find (s, p, i)\n  local cp = fmem[p]\n  if not cp then\n    cp = compile(p) / 0\n    cp = mm.P{ mm.Cp() * cp * mm.Cp() + 1 * mm.V(1) }\n    fmem[p] = cp\n  end\n  local i, e = cp:match(s, i or 1)\n  if i then return i, e - 1\n  else return i\n  end\nend\n\nlocal function gsub (s, p, rep)\n  local g = gmem[p] or {}   -- ensure gmem[p] is not collected while here\n  gmem[p] = g\n  local cp = g[rep]\n  if not cp then\n    cp = compile(p)\n    cp = mm.Cs((cp / rep + 1)^0)\n    g[rep] = cp\n  end\n  return cp:match(s)\nend\n\n\n-- exported names\nlocal re = {\n  compile = compile,\n  match = match,\n  find = find,\n  gsub = gsub,\n  updatelocale = updatelocale,\n}\n\nif version == \"Lua 5.1\" then _G.re = re end\n\nreturn re\n"
  },
  {
    "path": "3rd/lpeg/test.lua",
    "content": "#!/usr/bin/env lua\n\n-- require\"strict\"    -- just to be pedantic\n\nlocal m = require\"lpeg\"\n\n\n-- for general use\nlocal a, b, c, d, e, f, g, p, t\n\n\n-- compatibility with Lua 5.2\nlocal unpack = rawget(table, \"unpack\") or unpack\nlocal loadstring = rawget(_G, \"loadstring\") or load\n\n\nlocal any = m.P(1)\nlocal space = m.S\" \\t\\n\"^0\n\nlocal function checkeq (x, y, p)\nif p then print(x,y) end\n  if type(x) ~= \"table\" then assert(x == y)\n  else\n    for k,v in pairs(x) do checkeq(v, y[k], p) end\n    for k,v in pairs(y) do checkeq(v, x[k], p) end\n  end\nend\n\n\nlocal mt = getmetatable(m.P(1))\n\n\nlocal allchar = {}\nfor i=0,255 do allchar[i + 1] = i end\nallchar = string.char(unpack(allchar))\nassert(#allchar == 256)\n\nlocal function cs2str (c)\n  return m.match(m.Cs((c + m.P(1)/\"\")^0), allchar)\nend\n\nlocal function eqcharset (c1, c2)\n  assert(cs2str(c1) == cs2str(c2))\nend\n\n\nprint\"General tests for LPeg library\"\n\nassert(type(m.version) == \"string\")\nprint(m.version)\nassert(m.type(\"alo\") ~= \"pattern\")\nassert(m.type(io.input) ~= \"pattern\")\nassert(m.type(m.P\"alo\") == \"pattern\")\n\n-- tests for some basic optimizations\nassert(m.match(m.P(false) + \"a\", \"a\") == 2)\nassert(m.match(m.P(true) + \"a\", \"a\") == 1)\nassert(m.match(\"a\" + m.P(false), \"b\") == nil)\nassert(m.match(\"a\" + m.P(true), \"b\") == 1)\n\nassert(m.match(m.P(false) * \"a\", \"a\") == nil)\nassert(m.match(m.P(true) * \"a\", \"a\") == 2)\nassert(m.match(\"a\" * m.P(false), \"a\") == nil)\nassert(m.match(\"a\" * m.P(true), \"a\") == 2)\n\nassert(m.match(#m.P(false) * \"a\", \"a\") == nil)\nassert(m.match(#m.P(true) * \"a\", \"a\") == 2)\nassert(m.match(\"a\" * #m.P(false), \"a\") == nil)\nassert(m.match(\"a\" * #m.P(true), \"a\") == 2)\n\nassert(m.match(m.P(1)^0, \"abcd\") == 5)\nassert(m.match(m.S(\"\")^0, \"abcd\") == 1)\n\n-- tests for locale\ndo\n  assert(m.locale(m) == m)\n  local t = {}\n  assert(m.locale(t, m) == t)\n  local x = m.locale()\n  for n,v in pairs(x) do\n    assert(type(n) == \"string\")\n    eqcharset(v, m[n])\n  end\nend\n\n\nassert(m.match(3, \"aaaa\"))\nassert(m.match(4, \"aaaa\"))\nassert(not m.match(5, \"aaaa\"))\nassert(m.match(-3, \"aa\"))\nassert(not m.match(-3, \"aaa\"))\nassert(not m.match(-3, \"aaaa\"))\nassert(not m.match(-4, \"aaaa\"))\nassert(m.P(-5):match\"aaaa\")\n\nassert(m.match(\"a\", \"alo\") == 2)\nassert(m.match(\"al\", \"alo\") == 3)\nassert(not m.match(\"alu\", \"alo\"))\nassert(m.match(true, \"\") == 1)\n\nlocal digit = m.S\"0123456789\"\nlocal upper = m.S\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nlocal lower = m.S\"abcdefghijklmnopqrstuvwxyz\"\nlocal letter = m.S\"\" + upper + lower\nlocal alpha = letter + digit + m.R()\n\neqcharset(m.S\"\", m.P(false))\neqcharset(upper, m.R(\"AZ\"))\neqcharset(lower, m.R(\"az\"))\neqcharset(upper + lower, m.R(\"AZ\", \"az\"))\neqcharset(upper + lower, m.R(\"AZ\", \"cz\", \"aa\", \"bb\", \"90\"))\neqcharset(digit, m.S\"01234567\" + \"8\" + \"9\")\neqcharset(upper, letter - lower)\neqcharset(m.S(\"\"), m.R())\nassert(cs2str(m.S(\"\")) == \"\")\n\neqcharset(m.S\"\\0\", \"\\0\")\neqcharset(m.S\"\\1\\0\\2\", m.R\"\\0\\2\")\neqcharset(m.S\"\\1\\0\\2\", m.R\"\\1\\2\" + \"\\0\")\neqcharset(m.S\"\\1\\0\\2\" - \"\\0\", m.R\"\\1\\2\")\n\neqcharset(m.S(\"\\0\\255\"), m.P\"\\0\" + \"\\255\")   -- charset extremes\n\nlocal word = alpha^1 * (1 - alpha)^0\n\nassert((word^0 * -1):match\"alo alo\")\nassert(m.match(word^1 * -1, \"alo alo\"))\nassert(m.match(word^2 * -1, \"alo alo\"))\nassert(not m.match(word^3 * -1, \"alo alo\"))\n\nassert(not m.match(word^-1 * -1, \"alo alo\"))\nassert(m.match(word^-2 * -1, \"alo alo\"))\nassert(m.match(word^-3 * -1, \"alo alo\"))\n\nlocal eos = m.P(-1)\n\nassert(m.match(digit^0 * letter * digit * eos, \"1298a1\"))\nassert(not m.match(digit^0 * letter * eos, \"1257a1\"))\n\nb = {\n  [1] = \"(\" * (((1 - m.S\"()\") + #m.P\"(\" * m.V(1))^0) * \")\"\n}\n\nassert(m.match(b, \"(al())()\"))\nassert(not m.match(b * eos, \"(al())()\"))\nassert(m.match(b * eos, \"((al())()(é))\"))\nassert(not m.match(b, \"(al()()\"))\n\nassert(not m.match(letter^1 - \"for\", \"foreach\"))\nassert(m.match(letter^1 - (\"for\" * eos), \"foreach\"))\nassert(not m.match(letter^1 - (\"for\" * eos), \"for\"))\n\nfunction basiclookfor (p)\n  return m.P {\n    [1] = p + (1 * m.V(1))\n  }\nend\n\nfunction caplookfor (p)\n  return basiclookfor(p:C())\nend\n\nassert(m.match(caplookfor(letter^1), \"   4achou123...\") == \"achou\")\na = {m.match(caplookfor(letter^1)^0, \" two words, one more  \")}\ncheckeq(a, {\"two\", \"words\", \"one\", \"more\"})\n\nassert(m.match( basiclookfor((#m.P(b) * 1) * m.Cp()), \"  (  (a)\") == 7)\n\na = {m.match(m.C(digit^1 * m.Cc\"d\") + m.C(letter^1 * m.Cc\"l\"), \"123\")}\ncheckeq(a, {\"123\", \"d\"})\n\n-- bug in LPeg 0.12  (nil value does not create a 'ktable')\nassert(m.match(m.Cc(nil), \"\") == nil)\n\na = {m.match(m.C(digit^1 * m.Cc\"d\") + m.C(letter^1 * m.Cc\"l\"), \"abcd\")}\ncheckeq(a, {\"abcd\", \"l\"})\n\na = {m.match(m.Cc(10,20,30) * 'a' * m.Cp(), 'aaa')}\ncheckeq(a, {10,20,30,2})\na = {m.match(m.Cp() * m.Cc(10,20,30) * 'a' * m.Cp(), 'aaa')}\ncheckeq(a, {1,10,20,30,2})\na = m.match(m.Ct(m.Cp() * m.Cc(10,20,30) * 'a' * m.Cp()), 'aaa')\ncheckeq(a, {1,10,20,30,2})\na = m.match(m.Ct(m.Cp() * m.Cc(7,8) * m.Cc(10,20,30) * 'a' * m.Cp()), 'aaa')\ncheckeq(a, {1,7,8,10,20,30,2})\na = {m.match(m.Cc() * m.Cc() * m.Cc(1) * m.Cc(2,3,4) * m.Cc() * 'a', 'aaa')}\ncheckeq(a, {1,2,3,4})\n\na = {m.match(m.Cp() * letter^1 * m.Cp(), \"abcd\")}\ncheckeq(a, {1, 5})\n\n\nt = {m.match({[1] = m.C(m.C(1) * m.V(1) + -1)}, \"abc\")}\ncheckeq(t, {\"abc\", \"a\", \"bc\", \"b\", \"c\", \"c\", \"\"})\n\n-- bug in 0.12 ('hascapture' did not check for captures inside a rule)\ndo\n  local pat = m.P{\n    'S';\n    S1 = m.C('abc') + 3,\n    S = #m.V('S1')    -- rule has capture, but '#' must ignore it\n  }\n  assert(pat:match'abc' == 1)\nend\n\n\n-- bug: loop in 'hascaptures'\ndo\n  local p = m.C(-m.P{m.P'x' * m.V(1) + m.P'y'})\n  assert(p:match(\"xxx\") == \"\")\nend\n\n\n\n-- test for small capture boundary\nfor i = 250,260 do\n  assert(#m.match(m.C(i), string.rep('a', i)) == i)\n  assert(#m.match(m.C(m.C(i)), string.rep('a', i)) == i)\nend\n\n-- tests for any*n and any*-n\nfor n = 1, 550, 13 do\n  local x_1 = string.rep('x', n - 1)\n  local x = x_1 .. 'a'\n  assert(not m.P(n):match(x_1))\n  assert(m.P(n):match(x) == n + 1)\n  assert(n < 4 or m.match(m.P(n) + \"xxx\", x_1) == 4)\n  assert(m.C(n):match(x) == x)\n  assert(m.C(m.C(n)):match(x) == x)\n  assert(m.P(-n):match(x_1) == 1)\n  assert(not m.P(-n):match(x))\n  assert(n < 13 or m.match(m.Cc(20) * ((n - 13) * m.P(10)) * 3, x) == 20)\n  local n3 = math.floor(n/3)\n  assert(m.match(n3 * m.Cp() * n3 * n3, x) == n3 + 1)\nend\n\n-- true values\nassert(m.P(0):match(\"x\") == 1)\nassert(m.P(0):match(\"\") == 1)\nassert(m.C(0):match(\"x\") == \"\")\n\nassert(m.match(m.Cc(0) * m.P(10) + m.Cc(1) * \"xuxu\", \"xuxu\") == 1)\nassert(m.match(m.Cc(0) * m.P(10) + m.Cc(1) * \"xuxu\", \"xuxuxuxuxu\") == 0)\nassert(m.match(m.C(m.P(2)^1), \"abcde\") == \"abcd\")\np = m.Cc(0) * 1 + m.Cc(1) * 2 + m.Cc(2) * 3 + m.Cc(3) * 4\n\n\n-- test for alternation optimization\nassert(m.match(m.P\"a\"^1 + \"ab\" + m.P\"x\"^0, \"ab\") == 2)\nassert(m.match((m.P\"a\"^1 + \"ab\" + m.P\"x\"^0 * 1)^0, \"ab\") == 3)\nassert(m.match(m.P\"ab\" + \"cd\" + \"\" + \"cy\" + \"ak\", \"98\") == 1)\nassert(m.match(m.P\"ab\" + \"cd\" + \"ax\" + \"cy\", \"ax\") == 3)\nassert(m.match(\"a\" * m.P\"b\"^0 * \"c\"  + \"cd\" + \"ax\" + \"cy\", \"ax\") == 3)\nassert(m.match((m.P\"ab\" + \"cd\" + \"ax\" + \"cy\")^0, \"ax\") == 3)\nassert(m.match(m.P(1) * \"x\" + m.S\"\" * \"xu\" + \"ay\", \"ay\") == 3)\nassert(m.match(m.P\"abc\" + \"cde\" + \"aka\", \"aka\") == 4)\nassert(m.match(m.S\"abc\" * \"x\" + \"cde\" + \"aka\", \"ax\") == 3)\nassert(m.match(m.S\"abc\" * \"x\" + \"cde\" + \"aka\", \"aka\") == 4)\nassert(m.match(m.S\"abc\" * \"x\" + \"cde\" + \"aka\", \"cde\") == 4)\nassert(m.match(m.S\"abc\" * \"x\" + \"ide\" + m.S\"ab\" * \"ka\", \"aka\") == 4)\nassert(m.match(\"ab\" + m.S\"abc\" * m.P\"y\"^0 * \"x\" + \"cde\" + \"aka\", \"ax\") == 3)\nassert(m.match(\"ab\" + m.S\"abc\" * m.P\"y\"^0 * \"x\" + \"cde\" + \"aka\", \"aka\") == 4)\nassert(m.match(\"ab\" + m.S\"abc\" * m.P\"y\"^0 * \"x\" + \"cde\" + \"aka\", \"cde\") == 4)\nassert(m.match(\"ab\" + m.S\"abc\" * m.P\"y\"^0 * \"x\" + \"ide\" + m.S\"ab\" * \"ka\", \"aka\") == 4)\nassert(m.match(\"ab\" + m.S\"abc\" * m.P\"y\"^0 * \"x\" + \"ide\" + m.S\"ab\" * \"ka\", \"ax\") == 3)\nassert(m.match(m.P(1) * \"x\" + \"cde\" + m.S\"ab\" * \"ka\", \"aka\") == 4)\nassert(m.match(m.P(1) * \"x\" + \"cde\" + m.P(1) * \"ka\", \"aka\") == 4)\nassert(m.match(m.P(1) * \"x\" + \"cde\" + m.P(1) * \"ka\", \"cde\") == 4)\nassert(m.match(m.P\"eb\" + \"cd\" + m.P\"e\"^0 + \"x\", \"ee\") == 3)\nassert(m.match(m.P\"ab\" + \"cd\" + m.P\"e\"^0 + \"x\", \"abcd\") == 3)\nassert(m.match(m.P\"ab\" + \"cd\" + m.P\"e\"^0 + \"x\", \"eeex\") == 4)\nassert(m.match(m.P\"ab\" + \"cd\" + m.P\"e\"^0 + \"x\", \"cd\") == 3)\nassert(m.match(m.P\"ab\" + \"cd\" + m.P\"e\"^0 + \"x\", \"x\") == 1)\nassert(m.match(m.P\"ab\" + \"cd\" + m.P\"e\"^0 + \"x\" + \"\", \"zee\") == 1)\nassert(m.match(m.P\"ab\" + \"cd\" + m.P\"e\"^1 + \"x\", \"abcd\") == 3)\nassert(m.match(m.P\"ab\" + \"cd\" + m.P\"e\"^1 + \"x\", \"eeex\") == 4)\nassert(m.match(m.P\"ab\" + \"cd\" + m.P\"e\"^1 + \"x\", \"cd\") == 3)\nassert(m.match(m.P\"ab\" + \"cd\" + m.P\"e\"^1 + \"x\", \"x\") == 2)\nassert(m.match(m.P\"ab\" + \"cd\" + m.P\"e\"^1 + \"x\" + \"\", \"zee\") == 1)\nassert(not m.match((\"aa\" * m.P\"bc\"^-1 + \"aab\") * \"e\", \"aabe\"))\n\nassert(m.match(\"alo\" * (m.P\"\\n\" + -1), \"alo\") == 4)\n\n\n-- bug in 0.12 (rc1)\nassert(m.match((m.P\"\\128\\187\\191\" + m.S\"abc\")^0, \"\\128\\187\\191\") == 4)\n\nassert(m.match(m.S\"\\0\\128\\255\\127\"^0, string.rep(\"\\0\\128\\255\\127\", 10)) ==\n    4*10 + 1)\n\n-- optimizations with optional parts\nassert(m.match((\"ab\" * -m.P\"c\")^-1, \"abc\") == 1)\nassert(m.match((\"ab\" * #m.P\"c\")^-1, \"abd\") == 1)\nassert(m.match((\"ab\" * m.B\"c\")^-1, \"ab\") == 1)\nassert(m.match((\"ab\" * m.P\"cd\"^0)^-1, \"abcdcdc\") == 7)\n\nassert(m.match(m.P\"ab\"^-1 - \"c\", \"abcd\") == 3)\n\np = ('Aa' * ('Bb' * ('Cc' * m.P'Dd'^0)^0)^0)^-1\nassert(p:match(\"AaBbCcDdBbCcDdDdDdBb\") == 21)\n\n\n-- bug in 0.12.2\n-- p = { ('ab' ('c' 'ef'?)*)? }\np = m.C(('ab' * ('c' * m.P'ef'^-1)^0)^-1)\ns = \"abcefccefc\"\nassert(s == p:match(s))\n \n\npi = \"3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510\"\nassert(m.match(m.Cs((m.P\"1\" / \"a\" + m.P\"5\" / \"b\" + m.P\"9\" / \"c\" + 1)^0), pi) ==\n  m.match(m.Cs((m.P(1) / {[\"1\"] = \"a\", [\"5\"] = \"b\", [\"9\"] = \"c\"})^0), pi))\nprint\"+\"\n\n\n-- tests for capture optimizations\nassert(m.match((m.P(3) +  4 * m.Cp()) * \"a\", \"abca\") == 5)\nt = {m.match(((m.P\"a\" + m.Cp()) * m.P\"x\")^0, \"axxaxx\")}\ncheckeq(t, {3, 6})\n\n\n-- tests for numbered captures\np = m.C(1)\nassert(m.match(m.C(m.C(p * m.C(2)) * m.C(3)) / 3, \"abcdefgh\") == \"a\")\nassert(m.match(m.C(m.C(p * m.C(2)) * m.C(3)) / 1, \"abcdefgh\") == \"abcdef\")\nassert(m.match(m.C(m.C(p * m.C(2)) * m.C(3)) / 4, \"abcdefgh\") == \"bc\")\nassert(m.match(m.C(m.C(p * m.C(2)) * m.C(3)) / 0, \"abcdefgh\") == 7)\n\na, b, c = m.match(p * (m.C(p * m.C(2)) * m.C(3) / 4) * p, \"abcdefgh\")\nassert(a == \"a\" and b == \"efg\" and c == \"h\")\n\n-- test for table captures\nt = m.match(m.Ct(letter^1), \"alo\")\ncheckeq(t, {})\n\nt, n = m.match(m.Ct(m.C(letter)^1) * m.Cc\"t\", \"alo\")\nassert(n == \"t\" and table.concat(t) == \"alo\")\n\nt = m.match(m.Ct(m.C(m.C(letter)^1)), \"alo\")\nassert(table.concat(t, \";\") == \"alo;a;l;o\")\n\nt = m.match(m.Ct(m.C(m.C(letter)^1)), \"alo\")\nassert(table.concat(t, \";\") == \"alo;a;l;o\")\n\nt = m.match(m.Ct(m.Ct((m.Cp() * letter * m.Cp())^1)), \"alo\")\nassert(table.concat(t[1], \";\") == \"1;2;2;3;3;4\")\n\nt = m.match(m.Ct(m.C(m.C(1) * 1 * m.C(1))), \"alo\")\ncheckeq(t, {\"alo\", \"a\", \"o\"})\n\n\n-- tests for groups\np = m.Cg(1)   -- no capture\nassert(p:match('x') == 'x')\np = m.Cg(m.P(true)/function () end * 1)   -- no value\nassert(p:match('x') == 'x')\np = m.Cg(m.Cg(m.Cg(m.C(1))))\nassert(p:match('x') == 'x')\np = m.Cg(m.Cg(m.Cg(m.C(1))^0) * m.Cg(m.Cc(1) * m.Cc(2)))\nt = {p:match'abc'}\ncheckeq(t, {'a', 'b', 'c', 1, 2})\n\np = m.Ct(m.Cg(m.Cc(10), \"hi\") * m.C(1)^0 * m.Cg(m.Cc(20), \"ho\"))\nt = p:match''\ncheckeq(t, {hi = 10, ho = 20})\nt = p:match'abc'\ncheckeq(t, {hi = 10, ho = 20, 'a', 'b', 'c'})\n\n-- non-string group names\np = m.Ct(m.Cg(1, print) * m.Cg(1, 23.5) * m.Cg(1, io))\nt = p:match('abcdefghij')\nassert(t[print] == 'a' and t[23.5] == 'b' and t[io] == 'c')\n\n\n-- test for error messages\nlocal function checkerr (msg, f, ...)\n  local st, err = pcall(f, ...)\n  assert(not st and m.match({ m.P(msg) + 1 * m.V(1) }, err))\nend\n\ncheckerr(\"rule '1' may be left recursive\", m.match, { m.V(1) * 'a' }, \"a\")\ncheckerr(\"rule '1' used outside a grammar\", m.match, m.V(1), \"\")\ncheckerr(\"rule 'hiii' used outside a grammar\", m.match, m.V('hiii'), \"\")\ncheckerr(\"rule 'hiii' undefined in given grammar\", m.match, { m.V('hiii') }, \"\")\ncheckerr(\"undefined in given grammar\", m.match, { m.V{} }, \"\")\n\ncheckerr(\"rule 'A' is not a pattern\", m.P, { m.P(1), A = {} })\ncheckerr(\"grammar has no initial rule\", m.P, { [print] = {} })\n\n-- grammar with a long call chain before left recursion\np = {'a',\n  a = m.V'b' * m.V'c' * m.V'd' * m.V'a',\n  b = m.V'c',\n  c = m.V'd',\n  d = m.V'e',\n  e = m.V'f',\n  f = m.V'g',\n  g = m.P''\n}\ncheckerr(\"rule 'a' may be left recursive\", m.match, p, \"a\")\n\n-- Bug in peephole optimization of LPeg 0.12 (IJmp -> ICommit)\n-- the next grammar has an original sequence IJmp -> ICommit -> IJmp L1\n-- that is optimized to ICommit L1\n\np = m.P { (m.P {m.P'abc'} + 'ayz') * m.V'y'; y = m.P'x' }\nassert(p:match('abcx') == 5 and p:match('ayzx') == 5 and not p:match'abc')\n\n\ndo\n  print \"testing large dynamic Cc\"\n  local lim = 2^16 - 1\n  local c = 0\n  local function seq (n) \n    if n == 1 then c = c + 1; return m.Cc(c)\n    else\n      local m = math.floor(n / 2)\n      return seq(m) * seq(n - m)\n    end\n  end\n  p = m.Ct(seq(lim))\n  t = p:match('')\n  assert(t[lim] == lim)\n  checkerr(\"too many\", function () p = p / print end)\n  checkerr(\"too many\", seq, lim + 1)\nend\n\n\ndo\n  -- nesting of captures too deep\n  local p = m.C(1)\n  for i = 1, 300 do\n    p = m.Ct(p)\n  end\n  checkerr(\"too deep\", p.match, p, \"x\")\nend\n\n\n-- tests for non-pattern as arguments to pattern functions\n\np = { ('a' * m.V(1))^-1 } * m.P'b' * { 'a' * m.V(2); m.V(1)^-1 }\nassert(m.match(p, \"aaabaac\") == 7)\n\np = m.P'abc' * 2 * -5 * true * 'de'  -- mix of numbers and strings and booleans\n\nassert(p:match(\"abc01de\") == 8)\nassert(p:match(\"abc01de3456\") == nil)\n\np = 'abc' * (2 * (-5 * (true * m.P'de')))\n\nassert(p:match(\"abc01de\") == 8)\nassert(p:match(\"abc01de3456\") == nil)\n\np = { m.V(2), m.P\"abc\" } *\n     (m.P{ \"xx\", xx = m.P\"xx\" } + { \"x\", x = m.P\"a\" * m.V\"x\" + \"\" })\nassert(p:match(\"abcaaaxx\") == 7)\nassert(p:match(\"abcxx\") == 6)\n\n\n-- a large table capture\nt = m.match(m.Ct(m.C('a')^0), string.rep(\"a\", 10000))\nassert(#t == 10000 and t[1] == 'a' and t[#t] == 'a')\n\nprint('+')\n\n\n-- bug in 0.10 (rechecking a grammar, after tail-call optimization)\nm.P{ m.P { (m.P(3) + \"xuxu\")^0 * m.V\"xuxu\", xuxu = m.P(1) } }\n\nlocal V = m.V\n\nlocal Space = m.S(\" \\n\\t\")^0\nlocal Number = m.C(m.R(\"09\")^1) * Space\nlocal FactorOp = m.C(m.S(\"+-\")) * Space\nlocal TermOp = m.C(m.S(\"*/\")) * Space\nlocal Open = \"(\" * Space\nlocal Close = \")\" * Space\n\n\nlocal function f_factor (v1, op, v2, d)\n  assert(d == nil)\n  if op == \"+\" then return v1 + v2\n  else return v1 - v2\n  end\nend\n\n\nlocal function f_term (v1, op, v2, d)\n  assert(d == nil)\n  if op == \"*\" then return v1 * v2\n  else return v1 / v2\n  end\nend\n\nG = m.P{ \"Exp\",\n  Exp = V\"Factor\" * (FactorOp * V\"Factor\" % f_factor)^0;\n  Factor = V\"Term\" * (TermOp * V\"Term\" % f_term)^0;\n  Term = Number / tonumber  +  Open * V\"Exp\" * Close;\n}\n\nG = Space * G * -1\n\nfor _, s in ipairs{\" 3 + 5*9 / (1+1) \", \"3+4/2\", \"3+3-3- 9*2+3*9/1-  8\"} do\n  assert(m.match(G, s) == loadstring(\"return \"..s)())\nend\n\n\n-- test for grammars (errors deep in calling non-terminals)\ng = m.P{\n  [1] = m.V(2) + \"a\",\n  [2] = \"a\" * m.V(3) * \"x\",\n  [3] = \"b\" * m.V(3) + \"c\"\n}\n\nassert(m.match(g, \"abbbcx\") == 7)\nassert(m.match(g, \"abbbbx\") == 2)\n\n\n-- tests for \\0\nassert(m.match(m.R(\"\\0\\1\")^1, \"\\0\\1\\0\") == 4)\nassert(m.match(m.S(\"\\0\\1ab\")^1, \"\\0\\1\\0a\") == 5)\nassert(m.match(m.P(1)^3, \"\\0\\1\\0a\") == 5)\nassert(not m.match(-4, \"\\0\\1\\0a\"))\nassert(m.match(\"\\0\\1\\0a\", \"\\0\\1\\0a\") == 5)\nassert(m.match(\"\\0\\0\\0\", \"\\0\\0\\0\") == 4)\nassert(not m.match(\"\\0\\0\\0\", \"\\0\\0\"))\n\n\n-- tests for predicates\nassert(not m.match(-m.P(\"a\") * 2, \"alo\"))\nassert(m.match(- -m.P(\"a\") * 2, \"alo\") == 3)\nassert(m.match(#m.P(\"a\") * 2, \"alo\") == 3)\nassert(m.match(##m.P(\"a\") * 2, \"alo\") == 3)\nassert(not m.match(##m.P(\"c\") * 2, \"alo\"))\nassert(m.match(m.Cs((##m.P(\"a\") * 1 + m.P(1)/\".\")^0), \"aloal\") == \"a..a.\")\nassert(m.match(m.Cs((#((#m.P\"a\")/\"\") * 1 + m.P(1)/\".\")^0), \"aloal\") == \"a..a.\")\nassert(m.match(m.Cs((- -m.P(\"a\") * 1 + m.P(1)/\".\")^0), \"aloal\") == \"a..a.\")\nassert(m.match(m.Cs((-((-m.P\"a\")/\"\") * 1 + m.P(1)/\".\")^0), \"aloal\") == \"a..a.\")\n\n\n-- fixed length\ndo\n  -- 'and' predicate using fixed length\n  local p = m.C(#(\"a\" * (m.P(\"bd\") + \"cd\")) * 2)\n  assert(p:match(\"acd\") == \"ac\")\n\n  p = #m.P{ \"a\" * m.V(2), m.P\"b\" } * 2\n  assert(p:match(\"abc\") == 3)\n\n  p = #(m.P\"abc\" * m.B\"c\")\n  assert(p:match(\"abc\") == 1 and not p:match(\"ab\"))\n \n  p = m.P{ \"a\" * m.V(2), m.P\"b\"^1 }\n  checkerr(\"pattern may not have fixed length\", m.B, p)\n\n  p = \"abc\" * (m.P\"b\"^1 + m.P\"a\"^0)\n  checkerr(\"pattern may not have fixed length\", m.B, p)\nend\n\n\np = -m.P'a' * m.Cc(1) + -m.P'b' * m.Cc(2) + -m.P'c' * m.Cc(3)\nassert(p:match('a') == 2 and p:match('') == 1 and p:match('b') == 1)\n\np = -m.P'a' * m.Cc(10) + #m.P'a' * m.Cc(20)\nassert(p:match('a') == 20 and p:match('') == 10 and p:match('b') == 10)\n\n\n\n-- look-behind predicate\nassert(not m.match(m.B'a', 'a'))\nassert(m.match(1 * m.B'a', 'a') == 2)\nassert(not m.match(m.B(1), 'a'))\nassert(m.match(1 * m.B(1), 'a') == 2)\nassert(m.match(-m.B(1), 'a') == 1)\nassert(m.match(m.B(250), string.rep('a', 250)) == nil)\nassert(m.match(250 * m.B(250), string.rep('a', 250)) == 251)\n\n-- look-behind with an open call\ncheckerr(\"pattern may not have fixed length\", m.B, m.V'S1')\ncheckerr(\"too long to look behind\", m.B, 260)\n\nB = #letter * -m.B(letter) + -letter * m.B(letter)\nx = m.Ct({ (B * m.Cp())^-1 * (1 * m.V(1) + m.P(true)) })\ncheckeq(m.match(x, 'ar cal  c'), {1,3,4,7,9,10})\ncheckeq(m.match(x, ' ar cal  '), {2,4,5,8})\ncheckeq(m.match(x, '   '), {})\ncheckeq(m.match(x, 'aloalo'), {1,7})\n\nassert(m.match(B, \"a\") == 1)\nassert(m.match(1 * B, \"a\") == 2)\nassert(not m.B(1 - letter):match(\"\"))\nassert((-m.B(letter)):match(\"\") == 1)\n\nassert((4 * m.B(letter, 4)):match(\"aaaaaaaa\") == 5)\nassert(not (4 * m.B(#letter * 5)):match(\"aaaaaaaa\"))\nassert((4 * -m.B(#letter * 5)):match(\"aaaaaaaa\") == 5)\n\n-- look-behind with grammars\nassert(m.match('a' * m.B{'x', x = m.P(3)},  'aaa') == nil)\nassert(m.match('aa' * m.B{'x', x = m.P('aaa')},  'aaaa') == nil)\nassert(m.match('aaa' * m.B{'x', x = m.P('aaa')},  'aaaaa') == 4)\n\n\n\n-- bug in 0.9\nassert(m.match(('a' * #m.P'b'), \"ab\") == 2)\nassert(not m.match(('a' * #m.P'b'), \"a\"))\n\nassert(not m.match(#m.S'567', \"\"))\nassert(m.match(#m.S'567' * 1, \"6\") == 2)\n\n\n-- tests for Tail Calls\n\np = m.P{ 'a' * m.V(1) + '' }\nassert(p:match(string.rep('a', 1000)) == 1001)\n\n-- create a grammar for a simple DFA for even number of 0s and 1s\n--\n--  ->1 <---0---> 2\n--    ^           ^\n--    |           |\n--    1           1\n--    |           |\n--    V           V\n--    3 <---0---> 4\n--\n-- this grammar should keep no backtracking information\n\np = m.P{\n  [1] = '0' * m.V(2) + '1' * m.V(3) + -1,\n  [2] = '0' * m.V(1) + '1' * m.V(4),\n  [3] = '0' * m.V(4) + '1' * m.V(1),\n  [4] = '0' * m.V(3) + '1' * m.V(2),\n}\n\nassert(p:match(string.rep(\"00\", 10000)))\nassert(p:match(string.rep(\"01\", 10000)))\nassert(p:match(string.rep(\"011\", 10000)))\nassert(not p:match(string.rep(\"011\", 10000) .. \"1\"))\nassert(not p:match(string.rep(\"011\", 10001)))\n\n\n-- this grammar does need backtracking info.\nlocal lim = 10000\np = m.P{ '0' * m.V(1) + '0' }\ncheckerr(\"stack overflow\", m.match, p, string.rep(\"0\", lim))\nm.setmaxstack(2*lim)\ncheckerr(\"stack overflow\", m.match, p, string.rep(\"0\", lim))\nm.setmaxstack(2*lim + 4)\nassert(m.match(p, string.rep(\"0\", lim)) == lim + 1)\n\n-- this repetition should not need stack space (only the call does)\np = m.P{ ('a' * m.V(1))^0 * 'b' + 'c' }\nm.setmaxstack(200)\nassert(p:match(string.rep('a', 180) .. 'c' .. string.rep('b', 180)) == 362)\n\nm.setmaxstack(100)   -- restore low limit\n\n-- tests for optional start position\nassert(m.match(\"a\", \"abc\", 1))\nassert(m.match(\"b\", \"abc\", 2))\nassert(m.match(\"c\", \"abc\", 3))\nassert(not m.match(1, \"abc\", 4))\nassert(m.match(\"a\", \"abc\", -3))\nassert(m.match(\"b\", \"abc\", -2))\nassert(m.match(\"c\", \"abc\", -1))\nassert(m.match(\"abc\", \"abc\", -4))   -- truncate to position 1\n\nassert(m.match(\"\", \"abc\", 10))   -- empty string is everywhere!\nassert(m.match(\"\", \"\", 10))\nassert(not m.match(1, \"\", 1))\nassert(not m.match(1, \"\", -1))\nassert(not m.match(1, \"\", 0))\n\nprint(\"+\")\n\n\n-- tests for argument captures\ncheckerr(\"invalid argument\", m.Carg, 0)\ncheckerr(\"invalid argument\", m.Carg, -1)\ncheckerr(\"invalid argument\", m.Carg, 2^18)\ncheckerr(\"absent extra argument #1\", m.match, m.Carg(1), 'a', 1)\nassert(m.match(m.Carg(1), 'a', 1, print) == print)\nx = {m.match(m.Carg(1) * m.Carg(2), '', 1, 10, 20)}\ncheckeq(x, {10, 20})\n\nassert(m.match(m.Cmt(m.Cg(m.Carg(3), \"a\") *\n                     m.Cmt(m.Cb(\"a\"), function (s,i,x)\n                                        assert(s == \"a\" and i == 1);\n                                        return i, x+1\n                                      end) *\n                     m.Carg(2), function (s,i,a,b,c)\n                                  assert(s == \"a\" and i == 1 and c == nil);\n\t\t\t\t  return i, 2*a + 3*b\n                                end) * \"a\",\n               \"a\", 1, false, 100, 1000) == 2*1001 + 3*100)\n\n\n-- tests for Lua functions\n\nt = {}\ns = \"\"\np = m.P(function (s1, i) assert(s == s1); t[#t + 1] = i; return nil end) * false\ns = \"hi, this is a test\"\nassert(m.match(((p - m.P(-1)) + 2)^0, s) == string.len(s) + 1)\nassert(#t == string.len(s)/2 and t[1] == 1 and t[2] == 3)\n\nassert(not m.match(p, s))\n\np = mt.__add(function (s, i) return i end, function (s, i) return nil end)\nassert(m.match(p, \"alo\"))\n\np = mt.__mul(function (s, i) return i end, function (s, i) return nil end)\nassert(not m.match(p, \"alo\"))\n\n\nt = {}\np = function (s1, i) assert(s == s1); t[#t + 1] = i; return i end\ns = \"hi, this is a test\"\nassert(m.match((m.P(1) * p)^0, s) == string.len(s) + 1)\nassert(#t == string.len(s) and t[1] == 2 and t[2] == 3)\n\nt = {}\np = m.P(function (s1, i) assert(s == s1); t[#t + 1] = i;\n                         return i <= s1:len() and i end) * 1\ns = \"hi, this is a test\"\nassert(m.match(p^0, s) == string.len(s) + 1)\nassert(#t == string.len(s) + 1 and t[1] == 1 and t[2] == 2)\n\np = function (s1, i) return m.match(m.P\"a\"^1, s1, i) end\nassert(m.match(p, \"aaaa\") == 5)\nassert(m.match(p, \"abaa\") == 2)\nassert(not m.match(p, \"baaa\"))\n\ncheckerr(\"invalid position\", m.match, function () return 2^20 end, s)\ncheckerr(\"invalid position\", m.match, function () return 0 end, s)\ncheckerr(\"invalid position\", m.match, function (s, i) return i - 1 end, s)\ncheckerr(\"invalid position\", m.match,\n             m.P(1)^0 * function (_, i) return i - 1 end, s)\nassert(m.match(m.P(1)^0 * function (_, i) return i end * -1, s))\ncheckerr(\"invalid position\", m.match,\n             m.P(1)^0 * function (_, i) return i + 1 end, s)\nassert(m.match(m.P(function (s, i) return s:len() + 1 end) * -1, s))\ncheckerr(\"invalid position\", m.match, m.P(function (s, i) return s:len() + 2 end) * -1, s)\nassert(not m.match(m.P(function (s, i) return s:len() end) * -1, s))\nassert(m.match(m.P(1)^0 * function (_, i) return true end, s) ==\n       string.len(s) + 1)\nfor i = 1, string.len(s) + 1 do\n  assert(m.match(function (_, _) return i end, s) == i)\nend\n\np = (m.P(function (s, i) return i%2 == 0 and i end) * 1\n  +  m.P(function (s, i) return i%2 ~= 0 and i + 2 <= s:len() and i end) * 3)^0\n  * -1\nassert(p:match(string.rep('a', 14000)))\n\n-- tests for Function Replacements\nf = function (a, ...) if a ~= \"x\" then return {a, ...} end end\n\nt = m.match(m.C(1)^0/f, \"abc\")\ncheckeq(t, {\"a\", \"b\", \"c\"})\n\nt = m.match(m.C(1)^0/f/f, \"abc\")\ncheckeq(t, {{\"a\", \"b\", \"c\"}})\n\nt = m.match(m.P(1)^0/f/f, \"abc\")   -- no capture\ncheckeq(t, {{\"abc\"}})\n\nt = m.match((m.P(1)^0/f * m.Cp())/f, \"abc\")\ncheckeq(t, {{\"abc\"}, 4})\n\nt = m.match((m.C(1)^0/f * m.Cp())/f, \"abc\")\ncheckeq(t, {{\"a\", \"b\", \"c\"}, 4})\n\nt = m.match((m.C(1)^0/f * m.Cp())/f, \"xbc\")\ncheckeq(t, {4})\n\nt = m.match(m.C(m.C(1)^0)/f, \"abc\")\ncheckeq(t, {\"abc\", \"a\", \"b\", \"c\"})\n\ng = function (...) return 1, ... end\nt = {m.match(m.C(1)^0/g/g, \"abc\")}\ncheckeq(t, {1, 1, \"a\", \"b\", \"c\"})\n\nt = {m.match(m.Cc(nil,nil,4) * m.Cc(nil,3) * m.Cc(nil, nil) / g / g, \"\")}\nt1 = {1,1,nil,nil,4,nil,3,nil,nil}\nfor i=1,10 do assert(t[i] == t1[i]) end\n\n-- bug in 0.12.2: ktable with only nil could be eliminated when joining\n-- with a pattern without ktable\nassert((m.P\"aaa\" * m.Cc(nil)):match\"aaa\" == nil)\n\nt = {m.match((m.C(1) / function (x) return x, x..\"x\" end)^0, \"abc\")}\ncheckeq(t, {\"a\", \"ax\", \"b\", \"bx\", \"c\", \"cx\"})\n\nt = m.match(m.Ct((m.C(1) / function (x,y) return y, x end * m.Cc(1))^0), \"abc\")\ncheckeq(t, {nil, \"a\", 1, nil, \"b\", 1, nil, \"c\", 1})\n\n-- tests for Query Replacements\n\nassert(m.match(m.C(m.C(1)^0)/{abc = 10}, \"abc\") == 10)\nassert(m.match(m.C(1)^0/{a = 10}, \"abc\") == 10)\nassert(m.match(m.S(\"ba\")^0/{ab = 40}, \"abc\") == 40)\nt = m.match(m.Ct((m.S(\"ba\")/{a = 40})^0), \"abc\")\ncheckeq(t, {40})\n\nassert(m.match(m.Cs((m.C(1)/{a=\".\", d=\"..\"})^0), \"abcdde\") == \".bc....e\")\nassert(m.match(m.Cs((m.C(1)/{f=\".\"})^0), \"abcdde\") == \"abcdde\")\nassert(m.match(m.Cs((m.C(1)/{d=\".\"})^0), \"abcdde\") == \"abc..e\")\nassert(m.match(m.Cs((m.C(1)/{e=\".\"})^0), \"abcdde\") == \"abcdd.\")\nassert(m.match(m.Cs((m.C(1)/{e=\".\", f=\"+\"})^0), \"eefef\") == \"..+.+\")\nassert(m.match(m.Cs((m.C(1))^0), \"abcdde\") == \"abcdde\")\nassert(m.match(m.Cs(m.C(m.C(1)^0)), \"abcdde\") == \"abcdde\")\nassert(m.match(1 * m.Cs(m.P(1)^0), \"abcdde\") == \"bcdde\")\nassert(m.match(m.Cs((m.C('0')/'x' + 1)^0), \"abcdde\") == \"abcdde\")\nassert(m.match(m.Cs((m.C('0')/'x' + 1)^0), \"0ab0b0\") == \"xabxbx\")\nassert(m.match(m.Cs((m.C('0')/'x' + m.P(1)/{b=3})^0), \"b0a0b\") == \"3xax3\")\nassert(m.match(m.P(1)/'%0%0'/{aa = -3} * 'x', 'ax') == -3)\nassert(m.match(m.C(1)/'%0%1'/{aa = 'z'}/{z = -3} * 'x', 'ax') == -3)\n\nassert(m.match(m.Cs(m.Cc(0) * (m.P(1)/\"\")), \"4321\") == \"0\")\n\nassert(m.match(m.Cs((m.P(1) / \"%0\")^0), \"abcd\") == \"abcd\")\nassert(m.match(m.Cs((m.P(1) / \"%0.%0\")^0), \"abcd\") == \"a.ab.bc.cd.d\")\nassert(m.match(m.Cs((m.P(\"a\") / \"%0.%0\" + 1)^0), \"abcad\") == \"a.abca.ad\")\nassert(m.match(m.C(\"a\") / \"%1%%%0\", \"a\") == \"a%a\")\nassert(m.match(m.Cs((m.P(1) / \".xx\")^0), \"abcd\") == \".xx.xx.xx.xx\")\nassert(m.match(m.Cp() * m.P(3) * m.Cp()/\"%2%1%1 - %0 \", \"abcde\") ==\n   \"411 - abc \")\n\nassert(m.match(m.P(1)/\"%0\", \"abc\") == \"a\")\ncheckerr(\"invalid capture index\", m.match, m.P(1)/\"%1\", \"abc\")\ncheckerr(\"invalid capture index\", m.match, m.P(1)/\"%9\", \"abc\")\n\np = m.C(1)\np = p * p; p = p * p; p = p * p * m.C(1) / \"%9 - %1\"\nassert(p:match(\"1234567890\") == \"9 - 1\")\n\nassert(m.match(m.Cc(print), \"\") == print)\n\n-- too many captures (just ignore extra ones)\np = m.C(1)^0 / \"%2-%9-%0-%9\"\nassert(p:match\"01234567890123456789\" == \"1-8-01234567890123456789-8\")\ns = string.rep(\"12345678901234567890\", 20)\nassert(m.match(m.C(1)^0 / \"%9-%1-%0-%3\", s) == \"9-1-\" .. s .. \"-3\")\n\n-- string captures with non-string subcaptures\np = m.Cc('alo') * m.C(1) / \"%1 - %2 - %1\"\nassert(p:match'x' == 'alo - x - alo')\n\ncheckerr(\"invalid capture value (a boolean)\", m.match, m.Cc(true) / \"%1\", \"a\")\n\n-- long strings for string capture\nl = 10000\ns = string.rep('a', l) .. string.rep('b', l) .. string.rep('c', l)\n\np = (m.C(m.P'a'^1) * m.C(m.P'b'^1) * m.C(m.P'c'^1)) / '%3%2%1'\n\nassert(p:match(s) == string.rep('c', l) ..\n                     string.rep('b', l) .. \n                     string.rep('a', l))\n\nprint\"+\"\n\n-- accumulator capture\nfunction f (x) return x + 1 end\nassert(m.match(m.Cf(m.Cc(0) * m.C(1)^0, f), \"alo alo\") == 7)\nassert(m.match(m.Cc(0) * (m.C(1) % f)^0, \"alo alo\") == 7)\n\nt = {m.match(m.Cf(m.Cc(1,2,3), error), \"\")}\ncheckeq(t, {1})\np = m.Cf(m.Ct(true) * m.Cg(m.C(m.R\"az\"^1) * \"=\" * m.C(m.R\"az\"^1) * \";\")^0,\n         rawset)\nt = p:match(\"a=b;c=du;xux=yuy;\")\ncheckeq(t, {a=\"b\", c=\"du\", xux=\"yuy\"})\n\n\n-- errors in fold capture\n\n-- no initial capture\ncheckerr(\"no initial value\", m.match, m.Cf(m.P(5), print), 'aaaaaa')\n-- no initial capture (very long match forces fold to be a pair open-close)\ncheckerr(\"no initial value\", m.match, m.Cf(m.P(500), print),\n                               string.rep('a', 600))\n\n\n-- errors in accumulator capture\n\n-- no initial capture\ncheckerr(\"no previous value\", m.match, m.P(5) % print, 'aaaaaa')\n-- no initial capture (very long match forces fold to be a pair open-close)\ncheckerr(\"no previous value\", m.match, m.P(500) % print,\n                               string.rep('a', 600))\n\n\n-- tests for loop checker\n\nlocal function isnullable (p)\n  checkerr(\"may accept empty string\", function (p) return p^0 end, m.P(p))\nend\n\nisnullable(m.P(\"x\")^-4)\nassert(m.match(((m.P(0) + 1) * m.S\"al\")^0, \"alo\") == 3)\nassert(m.match(((\"x\" + #m.P(1))^-4 * m.S\"al\")^0, \"alo\") == 3)\nisnullable(\"\")\nisnullable(m.P(\"x\")^0)\nisnullable(m.P(\"x\")^-1)\nisnullable(m.P(\"x\") + 1 + 2 + m.P(\"a\")^-1)\nisnullable(-m.P(\"ab\"))\nisnullable(- -m.P(\"ab\"))\nisnullable(# #(m.P(\"ab\") + \"xy\"))\nisnullable(- #m.P(\"ab\")^0)\nisnullable(# -m.P(\"ab\")^1)\nisnullable(#m.V(3))\nisnullable(m.V(3) + m.V(1) + m.P('a')^-1)\nisnullable({[1] = m.V(2) * m.V(3), [2] = m.V(3), [3] = m.P(0)})\nassert(m.match(m.P{[1] = m.V(2) * m.V(3), [2] = m.V(3), [3] = m.P(1)}^0, \"abc\")\n       == 3)\nassert(m.match(m.P\"\"^-3, \"a\") == 1)\n\nlocal function find (p, s)\n  return m.match(basiclookfor(p), s)\nend\n\n\nlocal function badgrammar (g, expected)\n  local stat, msg = pcall(m.P, g)\n  assert(not stat)\n  if expected then assert(find(expected, msg)) end\nend\n\nbadgrammar({[1] = m.V(1)}, \"rule '1'\")\nbadgrammar({[1] = m.V(2)}, \"rule '2'\")   -- invalid non-terminal\nbadgrammar({[1] = m.V\"x\"}, \"rule 'x'\")   -- invalid non-terminal\nbadgrammar({[1] = m.V{}}, \"rule '(a table)'\")   -- invalid non-terminal\nbadgrammar({[1] = #m.P(\"a\") * m.V(1)}, \"rule '1'\")  -- left-recursive\nbadgrammar({[1] = -m.P(\"a\") * m.V(1)}, \"rule '1'\")  -- left-recursive\nbadgrammar({[1] = -1 * m.V(1)}, \"rule '1'\")  -- left-recursive\nbadgrammar({[1] = -1 + m.V(1)}, \"rule '1'\")  -- left-recursive\nbadgrammar({[1] = 1 * m.V(2), [2] = m.V(2)}, \"rule '2'\")  -- left-recursive\nbadgrammar({[1] = 1 * m.V(2)^0, [2] = m.P(0)}, \"rule '1'\")  -- inf. loop\nbadgrammar({ m.V(2), m.V(3)^0, m.P\"\" }, \"rule '2'\")  -- inf. loop\nbadgrammar({ m.V(2) * m.V(3)^0, m.V(3)^0, m.P\"\" }, \"rule '1'\")  -- inf. loop\nbadgrammar({\"x\", x = #(m.V(1) * 'a') }, \"rule '1'\")  -- inf. loop\nbadgrammar({ -(m.V(1) * 'a') }, \"rule '1'\")  -- inf. loop\nbadgrammar({\"x\", x = m.P'a'^-1 * m.V\"x\"}, \"rule 'x'\")  -- left recursive\nbadgrammar({\"x\", x = m.P'a' * m.V\"y\"^1, y = #m.P(1)}, \"rule 'x'\")\n\nassert(m.match({'a' * -m.V(1)}, \"aaa\") == 2)\nassert(m.match({'a' * -m.V(1)}, \"aaaa\") == nil)\n\n\n-- good x bad grammars\nm.P{ ('a' * m.V(1))^-1 }\nm.P{ -('a' * m.V(1)) }\nm.P{ ('abc' * m.V(1))^-1 }\nm.P{ -('abc' * m.V(1)) }\nbadgrammar{ #m.P('abc') * m.V(1) }\nbadgrammar{ -('a' + m.V(1)) }\nm.P{ #('a' * m.V(1)) }\nbadgrammar{ #('a' + m.V(1)) }\nm.P{ m.B{ m.P'abc' } * 'a' * m.V(1) }\nbadgrammar{ m.B{ m.P'abc' } * m.V(1) }\nbadgrammar{ ('a' + m.P'bcd')^-1 * m.V(1) }\n\n\n-- simple tests for maximum sizes:\nlocal p = m.P\"a\"\nfor i=1,14 do p = p * p end\n\np = {}\nfor i=1,100 do p[i] = m.P\"a\" end\np = m.P(p)\n\n\n-- strange values for rule labels\n\np = m.P{ \"print\",\n     print = m.V(print),\n     [print] = m.V(_G),\n     [_G] = m.P\"a\",\n   }\n\nassert(p:match(\"a\"))\n\n-- initial rule\ng = {}\nfor i = 1, 10 do g[\"i\"..i] =  \"a\" * m.V(\"i\"..i+1) end\ng.i11 = m.P\"\"\nfor i = 1, 10 do\n  g[1] = \"i\"..i\n  local p = m.P(g)\n  assert(p:match(\"aaaaaaaaaaa\") == 11 - i + 1)\nend\n\n\n\nprint \"testing back references\"\n\ncheckerr(\"back reference 'x' not found\", m.match, m.Cb('x'), '')\ncheckerr(\"back reference 'b' not found\", m.match, m.Cg(1, 'a') * m.Cb('b'), 'a')\n\np = m.Cg(m.C(1) * m.C(1), \"k\") * m.Ct(m.Cb(\"k\"))\nt = p:match(\"ab\")\ncheckeq(t, {\"a\", \"b\"})\n\n\ndo\n  -- some basic cases\n  assert(m.match(m.Cg(m.Cc(3), \"a\") * m.Cb(\"a\"), \"a\") == 3)\n  assert(m.match(m.Cg(m.C(1), 133) * m.Cb(133), \"X\") == \"X\")\n\n  -- first reference to 'x' should not see the group enclosing it\n  local p = m.Cg(m.Cb('x'), 'x') * m.Cb('x')\n  checkerr(\"back reference 'x' not found\", m.match, p, '')\n\n  local p = m.Cg(m.Cb('x') * m.C(1), 'x') * m.Cb('x')\n  checkerr(\"back reference 'x' not found\", m.match, p, 'abc')\n\n  -- reference to 'x' should not see the group enclosed in another capture\n  local s = string.rep(\"a\", 30)\n  local p = (m.C(1)^-4 * m.Cg(m.C(1), 'x')) / {} * m.Cb('x')\n  checkerr(\"back reference 'x' not found\", m.match, p, s)\n\n  local p = (m.C(1)^-20 * m.Cg(m.C(1), 'x')) / {} * m.Cb('x')\n  checkerr(\"back reference 'x' not found\", m.match, p, s)\n\n  -- second reference 'k' should refer to 10 and first ref. 'k'\n  p = m.Cg(m.Cc(20), 'k') * m.Cg(m.Cc(10) * m.Cb('k') * m.C(1), 'k')\n      * (m.Cb('k') / function (a,b,c) return a*10 + b + tonumber(c) end)\n  -- 10 * 10 (Cc) + 20 (Cb) + 7 (C) == 127\n  assert(p:match(\"756\") == 127)\n\nend\n\np = m.P(true)\nfor i = 1, 10 do p = p * m.Cg(1, i) end\nfor i = 1, 10 do\n  local p = p * m.Cb(i)\n  assert(p:match('abcdefghij') == string.sub('abcdefghij', i, i))\nend\n\n\nt = {}\nfunction foo (p) t[#t + 1] = p; return p .. \"x\" end\n\np = m.Cg(m.C(2)    / foo, \"x\") * m.Cb\"x\" *\n    m.Cg(m.Cb('x') / foo, \"x\") * m.Cb\"x\" *\n    m.Cg(m.Cb('x') / foo, \"x\") * m.Cb\"x\" *\n    m.Cg(m.Cb('x') / foo, \"x\") * m.Cb\"x\"\nx = {p:match'ab'}\ncheckeq(x, {'abx', 'abxx', 'abxxx', 'abxxxx'})\ncheckeq(t, {'ab',\n            'ab', 'abx',\n            'ab', 'abx', 'abxx',\n            'ab', 'abx', 'abxx', 'abxxx'})\n\n\n\n-- tests for match-time captures\n\np = m.P'a' * (function (s, i) return (s:sub(i, i) == 'b') and i + 1 end)\n  + 'acd'\n\nassert(p:match('abc') == 3)\nassert(p:match('acd') == 4)\n\nlocal function id (s, i, ...)\n  return true, ...\nend\n\ndo   -- run-time capture in an end predicate (should discard its value)\n  local x = 0\n  function foo (s, i)\n      x = x + 1\n      return true, x\n  end\n\n  local p = #(m.Cmt(\"\", foo) * \"xx\") * m.Cmt(\"\", foo)\n  assert(p:match(\"xx\") == 2)\nend\n\nassert(m.Cmt(m.Cs((m.Cmt(m.S'abc' / { a = 'x', c = 'y' }, id) +\n              m.R'09'^1 /  string.char +\n              m.P(1))^0), id):match\"acb98+68c\" == \"xyb\\98+\\68y\")\n\np = m.P{'S',\n  S = m.V'atom' * space\n    + m.Cmt(m.Ct(\"(\" * space * (m.Cmt(m.V'S'^1, id) + m.P(true)) * \")\" * space), id),\n  atom = m.Cmt(m.C(m.R(\"AZ\", \"az\", \"09\")^1), id)\n}\nx = p:match\"(a g () ((b) c) (d (e)))\"\ncheckeq(x, {'a', 'g', {}, {{'b'}, 'c'}, {'d', {'e'}}});\n\nx = {(m.Cmt(1, id)^0):match(string.rep('a', 500))}\nassert(#x == 500)\n\nlocal function id(s, i, x)\n  if x == 'a' then return i, 1, 3, 7\n  else return nil, 2, 4, 6, 8\n  end   \nend     \n\np = ((m.P(id) * 1 + m.Cmt(2, id) * 1  + m.Cmt(1, id) * 1))^0\nassert(table.concat{p:match('abababab')} == string.rep('137', 4))\n\nlocal function ref (s, i, x)\n  return m.match(x, s, i - x:len())\nend\n\nassert(m.Cmt(m.P(1)^0, ref):match('alo') == 4)\nassert((m.P(1) * m.Cmt(m.P(1)^0, ref)):match('alo') == 4)\nassert(not (m.P(1) * m.Cmt(m.C(1)^0, ref)):match('alo'))\n\nref = function (s,i,x) return i == tonumber(x) and i, 'xuxu' end\n\nassert(m.Cmt(1, ref):match'2')\nassert(not m.Cmt(1, ref):match'1')\nassert(m.Cmt(m.P(1)^0, ref):match'03')\n\nfunction ref (s, i, a, b)\n  if a == b then return i, a:upper() end\nend\n\np = m.Cmt(m.C(m.R\"az\"^1) * \"-\" * m.C(m.R\"az\"^1), ref)\np = (any - p)^0 * p * any^0 * -1\n\nassert(p:match'abbbc-bc ddaa' == 'BC')\n\ndo   -- match-time captures cannot be optimized away\n  local touch = 0\n  f = m.P(function () touch = touch + 1; return true end)\n\n  local function check(n) n = n or 1; assert(touch == n); touch = 0 end\n\n  assert(m.match(f * false + 'b', 'a') == nil); check()\n  assert(m.match(f * false + 'b', '') == nil); check()\n  assert(m.match( (f * 'a')^0 * 'b', 'b') == 2); check()\n  assert(m.match( (f * 'a')^0 * 'b', '') == nil); check()\n  assert(m.match( (f * 'a')^-1 * 'b', 'b') == 2); check()\n  assert(m.match( (f * 'a')^-1 * 'b', '') == nil); check()\n  assert(m.match( ('b' + f * 'a')^-1 * 'b', '') == nil); check()\n  assert(m.match( (m.P'b'^-1 * f * 'a')^-1 * 'b', '') == nil); check()\n  assert(m.match( (-m.P(1) * m.P'b'^-1 * f * 'a')^-1 * 'b', '') == nil);\n     check()\n  assert(m.match( (f * 'a' + 'b')^-1 * 'b', '') == nil); check()\n  assert(m.match(f * 'a' + f * 'b', 'b') == 2); check(2)\n  assert(m.match(f * 'a' + f * 'b', 'a') == 2); check(1)\n  assert(m.match(-f * 'a' + 'b', 'b') == 2); check(1)\n  assert(m.match(-f * 'a' + 'b', '') == nil); check(1)\nend\n\nc = '[' * m.Cg(m.P'='^0, \"init\") * '[' *\n    { m.Cmt(']' * m.C(m.P'='^0) * ']' * m.Cb(\"init\"), function (_, _, s1, s2)\n                                               return s1 == s2 end)\n       + 1 * m.V(1) } / 0\n\nassert(c:match'[==[]]====]]]]==]===[]' == 18)\nassert(c:match'[[]=]====]=]]]==]===[]' == 14)\nassert(not c:match'[[]=]====]=]=]==]===[]')\n\n\n-- old bug: optimization of concat with fail removed match-time capture\np = m.Cmt(0, function (s) p = s end) * m.P(false)\nassert(not p:match('alo'))\nassert(p == 'alo')\n\n\n-- ensure that failed match-time captures are not kept on Lua stack\ndo\n  local t = {__mode = \"kv\"}; setmetatable(t,t)\n  local c = 0\n\n  local function foo (s,i)\n    collectgarbage();\n    assert(next(t) == \"__mode\" and next(t, \"__mode\") == nil)\n    local x = {}\n    t[x] = true\n    c = c + 1\n    return i, x\n  end\n\n  local p = m.P{ m.Cmt(0, foo) * m.P(false) + m.P(1) * m.V(1) + m.P\"\" }\n  p:match(string.rep('1', 10))\n  assert(c == 11)\nend\n\n\n-- Return a match-time capture that returns 'n' captures\nlocal function manyCmt (n)\n    return m.Cmt(\"a\", function ()\n             local a = {}; for i = 1, n do a[i] = n - i end\n             return true, unpack(a)\n           end)\nend\n\n-- bug in 1.0: failed match-time that used previous match-time results\ndo\n  local x\n  local function aux (...) x = #{...}; return false end\n  local res = {m.match(m.Cmt(manyCmt(20), aux) + manyCmt(10), \"a\")}\n  assert(#res == 10 and res[1] == 9 and res[10] == 0)\nend\n\n\n-- bug in 1.0: problems with math-times returning too many captures\nif _VERSION >= \"Lua 5.2\" then\n  local lim = 2^11 - 10\n  local res = {m.match(manyCmt(lim), \"a\")}\n  assert(#res == lim and res[1] == lim - 1 and res[lim] == 0)\n  checkerr(\"too many\", m.match, manyCmt(2^15), \"a\")\nend\n\np = (m.P(function () return true, \"a\" end) * 'a'\n  + m.P(function (s, i) return i, \"aa\", 20 end) * 'b'\n  + m.P(function (s,i) if i <= #s then return i, \"aaa\" end end) * 1)^0\n\nt = {p:match('abacc')}\ncheckeq(t, {'a', 'aa', 20, 'a', 'aaa', 'aaa'})\n\n\ndo  print\"testing large grammars\"\n  local lim = 1000    -- number of rules\n  local t = {}\n\n  for i = 3, lim do\n    t[i] = m.V(i - 1)   -- each rule calls previous one\n  end\n  t[1] = m.V(lim)    -- start on last rule\n  t[2] = m.C(\"alo\")  -- final rule\n\n  local P = m.P(t)   -- build grammar\n  assert(P:match(\"alo\") == \"alo\")\n\n  t[#t + 1] = m.P(\"x\")   -- one more rule...\n  checkerr(\"too many rules\", m.P, t)\nend\n\n\nprint \"testing UTF-8 ranges\"\n\ndo   -- a few typical UTF-8 ranges\n  local p = m.utfR(0x410, 0x44f)^1 / \"cyr: %0\"\n          + m.utfR(0x4e00, 0x9fff)^1 / \"cjk: %0\"\n          + m.utfR(0x1F600, 0x1F64F)^1 / \"emot: %0\"\n          + m.utfR(0, 0x7f)^1 / \"ascii: %0\"\n          + m.utfR(0, 0x10ffff) / \"other: %0\"\n\n  p = m.Ct(p^0) * -m.P(1)\n\n  local cyr = \"ждюя\"\n  local emot = \"\\240\\159\\152\\128\\240\\159\\153\\128\"   --  😀🙀\n  local cjk = \"专举乸\"\n  local ascii = \"alo\"\n  local last = \"\\244\\143\\191\\191\"                -- U+10FFFF\n\n  local s = cyr .. \"—\" .. emot .. \"—\" .. cjk .. \"—\" .. ascii .. last\n  t = (p:match(s))\n\n  assert(t[1] == \"cyr: \" .. cyr and t[2] == \"other: —\" and\n         t[3] == \"emot: \" .. emot and t[4] == \"other: —\" and\n         t[5] == \"cjk: \" .. cjk and t[6] == \"other: —\" and\n         t[7] == \"ascii: \" .. ascii and t[8] == \"other: \" .. last and\n         t[9] == nil)\n\n  -- failing UTF-8 matches and borders\n  assert(not m.match(m.utfR(10, 0x2000), \"\\9\"))\n  assert(not m.match(m.utfR(10, 0x2000), \"\\226\\128\\129\"))\n  assert(m.match(m.utfR(10, 0x2000), \"\\10\") == 2)\n  assert(m.match(m.utfR(10, 0x2000), \"\\226\\128\\128\") == 4)\nend\n\n\ndo   -- valid and invalid code points\n  local p = m.utfR(0, 0x10ffff)^0\n  assert(p:match(\"汉字\\128\") == #\"汉字\" + 1)\n  assert(p:match(\"\\244\\159\\191\") == 1)\n  assert(p:match(\"\\244\\159\\191\\191\") == 1)\n  assert(p:match(\"\\255\") == 1)\n\n   -- basic errors\n  checkerr(\"empty range\", m.utfR, 1, 0)\n  checkerr(\"invalid code point\", m.utfR, 1, 0x10ffff + 1)\nend\n\n\ndo  -- back references (fixed width)\n  -- match a byte after a CJK point\n  local p = m.B(m.utfR(0x4e00, 0x9fff)) * m.C(1)\n  p = m.P{ p + m.P(1) * m.V(1) }   -- search for 'p'\n  assert(p:match(\"ab д 专X x\") == \"X\")\n\n  -- match a byte after a hebrew point\n  local p = m.B(m.utfR(0x5d0, 0x5ea)) * m.C(1)\n  p = m.P(#\"ש\") * p\n  assert(p:match(\"שX\") == \"X\")\n\n  checkerr(\"fixed length\", m.B, m.utfR(0, 0x10ffff))\nend\n\n\n\n-------------------------------------------------------------------\n-- Tests for 're' module\n-------------------------------------------------------------------\nprint\"testing 're' module\"\n\nlocal re = require \"re\"\n\nlocal match, compile = re.match, re.compile\n\n\n\nassert(match(\"a\", \".\") == 2)\nassert(match(\"a\", \"''\") == 1)\nassert(match(\"\", \" ! . \") == 1)\nassert(not match(\"a\", \" ! . \"))\nassert(match(\"abcde\", \"  ( . . ) * \") == 5)\nassert(match(\"abbcde\", \" [a-c] +\") == 5)\nassert(match(\"0abbc1de\", \"'0' [a-c]+ '1'\") == 7)\nassert(match(\"0zz1dda\", \"'0' [^a-c]+ 'a'\") == 8)\nassert(match(\"abbc--\", \" [a-c] + +\") == 5)\nassert(match(\"abbc--\", \" [ac-] +\") == 2)\nassert(match(\"abbc--\", \" [-acb] + \") == 7)\nassert(not match(\"abbcde\", \" [b-z] + \"))\nassert(match(\"abb\\\"de\", '\"abb\"[\"]\"de\"') == 7)\nassert(match(\"abceeef\", \"'ac' ? 'ab' * 'c' { 'e' * } / 'abceeef' \") == \"eee\")\nassert(match(\"abceeef\", \"'ac'? 'ab'* 'c' { 'f'+ } / 'abceeef' \") == 8)\n\nassert(re.match(\"aaand\", \"[a]^2\") == 3)\n\nlocal t = {match(\"abceefe\", \"( ( & 'e' {} ) ? . ) * \")}\ncheckeq(t, {4, 5, 7})\nlocal t = {match(\"abceefe\", \"((&&'e' {})? .)*\")}\ncheckeq(t, {4, 5, 7})\nlocal t = {match(\"abceefe\", \"( ( ! ! 'e' {} ) ? . ) *\")}\ncheckeq(t, {4, 5, 7})\nlocal t = {match(\"abceefe\", \"(( & ! & ! 'e' {})? .)*\")}\ncheckeq(t, {4, 5, 7})\n\nassert(match(\"cccx\" , \"'ab'? ('ccc' / ('cde' / 'cd'*)? / 'ccc') 'x'+\") == 5)\nassert(match(\"cdx\" , \"'ab'? ('ccc' / ('cde' / 'cd'*)? / 'ccc') 'x'+\") == 4)\nassert(match(\"abcdcdx\" , \"'ab'? ('ccc' / ('cde' / 'cd'*)? / 'ccc') 'x'+\") == 8)\n\nassert(match(\"abc\", \"a <- (. a)?\") == 4)\nb = \"balanced <- '(' ([^()] / balanced)* ')'\"\nassert(match(\"(abc)\", b))\nassert(match(\"(a(b)((c) (d)))\", b))\nassert(not match(\"(a(b ((c) (d)))\", b))\n\nb = compile[[  balanced <- \"(\" ([^()] / balanced)* \")\" ]]\nassert(b == m.P(b))\nassert(b:match\"((((a))(b)))\")\n\nlocal g = [[\n  S <- \"0\" B / \"1\" A / \"\"   -- balanced strings\n  A <- \"0\" S / \"1\" A A      -- one more 0\n  B <- \"1\" S / \"0\" B B      -- one more 1\n]]\nassert(match(\"00011011\", g) == 9)\n\nlocal g = [[\n  S <- (\"0\" B / \"1\" A)*\n  A <- \"0\" / \"1\" A A\n  B <- \"1\" / \"0\" B B\n]]\nassert(match(\"00011011\", g) == 9)\nassert(match(\"000110110\", g) == 9)\nassert(match(\"011110110\", g) == 3)\nassert(match(\"000110010\", g) == 1)\n\ns = \"aaaaaaaaaaaaaaaaaaaaaaaa\"\nassert(match(s, \"'a'^3\") == 4)\nassert(match(s, \"'a'^0\") == 1)\nassert(match(s, \"'a'^+3\") == s:len() + 1)\nassert(not match(s, \"'a'^+30\"))\nassert(match(s, \"'a'^-30\") == s:len() + 1)\nassert(match(s, \"'a'^-5\") == 6)\nfor i = 1, s:len() do\n  assert(match(s, string.format(\"'a'^+%d\", i)) >= i + 1)\n  assert(match(s, string.format(\"'a'^-%d\", i)) <= i + 1)\n  assert(match(s, string.format(\"'a'^%d\", i)) == i + 1)\nend\nassert(match(\"01234567890123456789\", \"[0-9]^3+\") == 19)\n\n\nassert(match(\"01234567890123456789\", \"({....}{...}) -> '%2%1'\") == \"4560123\")\nt = match(\"0123456789\", \"{| {.}* |}\")\ncheckeq(t, {\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"})\nassert(match(\"012345\", \"{| (..) -> '%0%0' |}\")[1] == \"0101\")\n\nassert(match(\"abcdef\", \"( {.} {.} {.} {.} {.} ) -> 3\") == \"c\")\nassert(match(\"abcdef\", \"( {:x: . :} {.} {.} {.} {.} ) -> 3\") == \"d\")\nassert(match(\"abcdef\", \"( {:x: . :} {.} {.} {.} {.} ) -> 0\") == 6)\n\nassert(not match(\"abcdef\", \"{:x: ({.} {.} {.}) -> 2 :} =x\"))\nassert(match(\"abcbef\", \"{:x: ({.} {.} {.}) -> 2 :} =x\"))\n\neqcharset(compile\"[]]\", \"]\")\neqcharset(compile\"[][]\", m.S\"[]\")\neqcharset(compile\"[]-]\", m.S\"-]\")\neqcharset(compile\"[-]\", m.S\"-\")\neqcharset(compile\"[az-]\", m.S\"a-z\")\neqcharset(compile\"[-az]\", m.S\"a-z\")\neqcharset(compile\"[a-z]\", m.R\"az\")\neqcharset(compile\"[]['\\\"]\", m.S[[]['\"]])\n\neqcharset(compile\"[^]]\", any - \"]\")\neqcharset(compile\"[^][]\", any - m.S\"[]\")\neqcharset(compile\"[^]-]\", any - m.S\"-]\")\neqcharset(compile\"[^]-]\", any - m.S\"-]\")\neqcharset(compile\"[^-]\", any - m.S\"-\")\neqcharset(compile\"[^az-]\", any - m.S\"a-z\")\neqcharset(compile\"[^-az]\", any - m.S\"a-z\")\neqcharset(compile\"[^a-z]\", any - m.R\"az\")\neqcharset(compile\"[^]['\\\"]\", any - m.S[[]['\"]])\n\n-- tests for comments in 're'\ne = compile[[\nA  <- _B   -- \\t \\n %nl .<> <- -> --\n_B <- 'x'  --]]\nassert(e:match'xy' == 2)\n\n-- tests for 're' with pre-definitions\ndefs = {digits = m.R\"09\", letters = m.R\"az\", _=m.P\"__\"}\ne = compile(\"%letters (%letters / %digits)*\", defs)\nassert(e:match\"x123\" == 5)\ne = compile(\"%_\", defs)\nassert(e:match\"__\" == 3)\n\ne = compile([[\n  S <- A+\n  A <- %letters+ B\n  B <- %digits+\n]], defs)\n\ne = compile(\"{[0-9]+'.'?[0-9]*} -> sin\", math)\nassert(e:match(\"2.34\") == math.sin(2.34))\n\ne = compile(\"'pi' -> math\", _G)\nassert(e:match(\"pi\") == math.pi)\n\ne = compile(\"[ ]* 'version' -> _VERSION\", _G)\nassert(e:match(\"  version\") == _VERSION)\n\n\nfunction eq (_, _, a, b) return a == b end\n\nc = re.compile([[\n  longstring <- '[' {:init: '='* :} '[' close\n  close <- ']' =init ']' / . close\n]])\n\nassert(c:match'[==[]]===]]]]==]===[]' == 17)\nassert(c:match'[[]=]====]=]]]==]===[]' == 14)\nassert(not c:match'[[]=]====]=]=]==]===[]')\n\nc = re.compile\" '[' {:init: '='* :} '[' (!(']' =init ']') .)* ']' =init ']' !. \"\n\nassert(c:match'[==[]]===]]]]==]')\nassert(c:match'[[]=]====]=][]==]===[]]')\nassert(not c:match'[[]=]====]=]=]==]===[]')\n\nassert(re.find(\"hi alalo\", \"{:x:..:} =x\") == 4)\nassert(re.find(\"hi alalo\", \"{:x:..:} =x\", 4) == 4)\nassert(not re.find(\"hi alalo\", \"{:x:..:} =x\", 5))\nassert(re.find(\"hi alalo\", \"{'al'}\", 5) == 6)\nassert(re.find(\"hi aloalolo\", \"{:x:..:} =x\") == 8)\nassert(re.find(\"alo alohi x x\", \"{:word:%w+:}%W*(=word)!%w\") == 11)\n\n-- re.find discards any captures\nlocal a,b,c = re.find(\"alo\", \"{.}{'o'}\")\nassert(a == 2 and b == 3 and c == nil)\n\nlocal function match (s,p)\n  local i,e = re.find(s,p)\n  if i then return s:sub(i, e) end\nend\nassert(match(\"alo alo\", '[a-z]+') == \"alo\")\nassert(match(\"alo alo\", '{:x: [a-z]+ :} =x') == nil)\nassert(match(\"alo alo\", \"{:x: [a-z]+ :} ' ' =x\") == \"alo alo\")\n\nassert(re.gsub(\"alo alo\", \"[abc]\", \"x\") == \"xlo xlo\")\nassert(re.gsub(\"alo alo\", \"%w+\", \".\") == \". .\")\nassert(re.gsub(\"hi, how are you\", \"[aeiou]\", string.upper) ==\n               \"hI, hOw ArE yOU\")\n\ns = 'hi [[a comment[=]=] ending here]] and [=[another]]=]]'\nc = re.compile\" '[' {:i: '='* :} '[' (!(']' =i ']') .)* ']' { =i } ']' \"\nassert(re.gsub(s, c, \"%2\") == 'hi  and =]')\nassert(re.gsub(s, c, \"%0\") == s)\nassert(re.gsub('[=[hi]=]', c, \"%2\") == '=')\n\nassert(re.find(\"\", \"!.\") == 1)\nassert(re.find(\"alo\", \"!.\") == 4)\n\nfunction addtag (s, i, t, tag) t.tag = tag; return i, t end\n\nc = re.compile([[\n  doc <- block !.\n  block <- (start {| (block / { [^<]+ })* |} end?) => addtag\n  start <- '<' {:tag: [a-z]+ :} '>'\n  end <- '</' { =tag } '>'\n]], {addtag = addtag})\n\nx = c:match[[\n<x>hi<b>hello</b>but<b>totheend</x>]]\ncheckeq(x, {tag='x', 'hi', {tag = 'b', 'hello'}, 'but',\n                     {'totheend'}})\n\n\n-- test for folding captures\nc = re.compile([[\n  S <- (number (%s+ number)*) ~> add\n  number <- %d+ -> tonumber\n]], {tonumber = tonumber, add = function (a,b) return a + b end})\nassert(c:match(\"3 401 50\") == 3 + 401 + 50)\n\n-- test for accumulator captures\nc = re.compile([[\n  S <- number (%s+ number >> add)*\n  number <- %d+ -> tonumber\n]], {tonumber = tonumber, add = function (a,b) return a + b end})\nassert(c:match(\"3 401 50\") == 3 + 401 + 50)\n\n-- tests for look-ahead captures\nx = {re.match(\"alo\", \"&(&{.}) !{'b'} {&(...)} &{..} {...} {!.}\")}\ncheckeq(x, {\"\", \"alo\", \"\"})\n\nassert(re.match(\"aloalo\",\n   \"{~ (((&'al' {.}) -> 'A%1' / (&%l {.}) -> '%1%1') / .)* ~}\")\n       == \"AallooAalloo\")\n\n-- bug in 0.9 (and older versions), due to captures in look-aheads\nx = re.compile[[   {~ (&(. ([a-z]* -> '*')) ([a-z]+ -> '+') ' '*)* ~}  ]]\nassert(x:match\"alo alo\" == \"+ +\")\n\n-- valid capture in look-ahead (used inside the look-ahead itself)\nx = re.compile[[\n      S <- &({:two: .. :} . =two) {[a-z]+} / . S\n]]\nassert(x:match(\"hello aloaLo aloalo xuxu\") == \"aloalo\")\n\n\np = re.compile[[\n  block <- {| {:ident:space*:} line\n           ((=ident !space line) / &(=ident space) block)* |}\n  line <- {[^%nl]*} %nl\n  space <- '_'     -- should be ' ', but '_' is simpler for editors\n]]\n\nt= p:match[[\n1\n__1.1\n__1.2\n____1.2.1\n____\n2\n__2.1\n]]\ncheckeq(t, {\"1\", {\"1.1\", \"1.2\", {\"1.2.1\", \"\", ident = \"____\"}, ident = \"__\"},\n            \"2\", {\"2.1\", ident = \"__\"}, ident = \"\"})\n\n\n-- nested grammars\np = re.compile[[\n       s <- a b !.\n       b <- ( x <- ('b' x)? )\n       a <- ( x <- 'a' x? )\n]]\n\nassert(p:match'aaabbb')\nassert(p:match'aaa')\nassert(not p:match'bbb')\nassert(not p:match'aaabbba')\n\n-- testing groups\nt = {re.match(\"abc\", \"{:S <- {:.:} {S} / '':}\")}\ncheckeq(t, {\"a\", \"bc\", \"b\", \"c\", \"c\", \"\"})\n\nt = re.match(\"1234\", \"{| {:a:.:} {:b:.:} {:c:.{.}:} |}\")\ncheckeq(t, {a=\"1\", b=\"2\", c=\"4\"})\nt = re.match(\"1234\", \"{|{:a:.:} {:b:{.}{.}:} {:c:{.}:}|}\")\ncheckeq(t, {a=\"1\", b=\"2\", c=\"4\"})\nt = re.match(\"12345\", \"{| {:.:} {:b:{.}{.}:} {:{.}{.}:} |}\")\ncheckeq(t, {\"1\", b=\"2\", \"4\", \"5\"})\nt = re.match(\"12345\", \"{| {:.:} {:{:b:{.}{.}:}:} {:{.}{.}:} |}\")\ncheckeq(t, {\"1\", \"23\", \"4\", \"5\"})\nt = re.match(\"12345\", \"{| {:.:} {{:b:{.}{.}:}} {:{.}{.}:} |}\")\ncheckeq(t, {\"1\", \"23\", \"4\", \"5\"})\n\n\n-- testing pre-defined names\nassert(os.setlocale(\"C\") == \"C\")\n\nfunction eqlpeggsub (p1, p2)\n  local s1 = cs2str(re.compile(p1))\n  local s2 = string.gsub(allchar, \"[^\" .. p2 .. \"]\", \"\")\n  -- if s1 ~= s2 then print(#s1,#s2) end\n  assert(s1 == s2)\nend\n\n\neqlpeggsub(\"%w\", \"%w\")\neqlpeggsub(\"%a\", \"%a\")\neqlpeggsub(\"%l\", \"%l\")\neqlpeggsub(\"%u\", \"%u\")\neqlpeggsub(\"%p\", \"%p\")\neqlpeggsub(\"%d\", \"%d\")\neqlpeggsub(\"%x\", \"%x\")\neqlpeggsub(\"%s\", \"%s\")\neqlpeggsub(\"%c\", \"%c\")\n\neqlpeggsub(\"%W\", \"%W\")\neqlpeggsub(\"%A\", \"%A\")\neqlpeggsub(\"%L\", \"%L\")\neqlpeggsub(\"%U\", \"%U\")\neqlpeggsub(\"%P\", \"%P\")\neqlpeggsub(\"%D\", \"%D\")\neqlpeggsub(\"%X\", \"%X\")\neqlpeggsub(\"%S\", \"%S\")\neqlpeggsub(\"%C\", \"%C\")\n\neqlpeggsub(\"[%w]\", \"%w\")\neqlpeggsub(\"[_%w]\", \"_%w\")\neqlpeggsub(\"[^%w]\", \"%W\")\neqlpeggsub(\"[%W%S]\", \"%W%S\")\n\nre.updatelocale()\n\n\n-- testing nested substitutions x string captures\n\np = re.compile[[\n      text <- {~ item* ~}\n      item <- macro / [^()] / '(' item* ')'\n      arg <- ' '* {~ (!',' item)* ~}\n      args <- '(' arg (',' arg)* ')'\n      macro <- ('apply' args) -> '%1(%2)'\n             / ('add' args) -> '%1 + %2'\n             / ('mul' args) -> '%1 * %2'\n]]\n\nassert(p:match\"add(mul(a,b), apply(f,x))\" == \"a * b + f(x)\")\n\nrev = re.compile[[ R <- (!.) -> '' / ({.} R) -> '%2%1']]\n\nassert(rev:match\"0123456789\" == \"9876543210\")\n\n\n-- testing error messages in re\n\nlocal function errmsg (p, err)\n  checkerr(err, re.compile, p)\nend\n\nerrmsg('aaaa', \"rule 'aaaa'\")\nerrmsg('a', 'outside')\nerrmsg('b <- a', 'undefined')\nerrmsg(\"x <- 'a'  x <- 'b'\", 'already defined')\nerrmsg(\"'a' -\", \"near '-'\")\n\n\nprint\"OK\"\n\n\n"
  },
  {
    "path": "3rd/lua/README",
    "content": "This is a modify version of lua 5.5 .\n\nFor detail ,\n  Shared Proto : http://lua-users.org/lists/lua-l/2014-03/msg00489.html\n  Shared short string : https://blog.codingnow.com/2019/06/string_comparison.html\n"
  },
  {
    "path": "3rd/lua/README.md",
    "content": "# Lua\n\nThis is the repository of Lua development code, as seen by the Lua team. It contains the full history of all commits but is mirrored irregularly. For complete information about Lua, visit [Lua.org](https://www.lua.org/).\n\nPlease **do not** send pull requests. To report issues, post a message to the [Lua mailing list](https://www.lua.org/lua-l.html).\n\nDownload official Lua releases from [Lua.org](https://www.lua.org/download.html).\n"
  },
  {
    "path": "3rd/lua/lapi.c",
    "content": "/*\n** $Id: lapi.c $\n** Lua API\n** See Copyright Notice in lua.h\n*/\n\n#define lapi_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <limits.h>\n#include <stdarg.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lapi.h\"\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lfunc.h\"\n#include \"lgc.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"ltm.h\"\n#include \"lundump.h\"\n#include \"lvm.h\"\n\n\n\nconst char lua_ident[] =\n  \"$LuaVersion: \" LUA_COPYRIGHT \" $\"\n  \"$LuaAuthors: \" LUA_AUTHORS \" $\";\n\n\n\n/*\n** Test for a valid index (one that is not the 'nilvalue').\n*/\n#define isvalid(L, o)\t((o) != &G(L)->nilvalue)\n\n\n/* test for pseudo index */\n#define ispseudo(i)\t\t((i) <= LUA_REGISTRYINDEX)\n\n/* test for upvalue */\n#define isupvalue(i)\t\t((i) < LUA_REGISTRYINDEX)\n\n\n/*\n** Convert an acceptable index to a pointer to its respective value.\n** Non-valid indices return the special nil value 'G(L)->nilvalue'.\n*/\nstatic TValue *index2value (lua_State *L, int idx) {\n  CallInfo *ci = L->ci;\n  if (idx > 0) {\n    StkId o = ci->func.p + idx;\n    api_check(L, idx <= ci->top.p - (ci->func.p + 1), \"unacceptable index\");\n    if (o >= L->top.p) return &G(L)->nilvalue;\n    else return s2v(o);\n  }\n  else if (!ispseudo(idx)) {  /* negative index */\n    api_check(L, idx != 0 && -idx <= L->top.p - (ci->func.p + 1),\n                 \"invalid index\");\n    return s2v(L->top.p + idx);\n  }\n  else if (idx == LUA_REGISTRYINDEX)\n    return &G(L)->l_registry;\n  else {  /* upvalues */\n    idx = LUA_REGISTRYINDEX - idx;\n    api_check(L, idx <= MAXUPVAL + 1, \"upvalue index too large\");\n    if (ttisCclosure(s2v(ci->func.p))) {  /* C closure? */\n      CClosure *func = clCvalue(s2v(ci->func.p));\n      return (idx <= func->nupvalues) ? &func->upvalue[idx-1]\n                                      : &G(L)->nilvalue;\n    }\n    else {  /* light C function or Lua function (through a hook)?) */\n      api_check(L, ttislcf(s2v(ci->func.p)), \"caller not a C function\");\n      return &G(L)->nilvalue;  /* no upvalues */\n    }\n  }\n}\n\n\n\n/*\n** Convert a valid actual index (not a pseudo-index) to its address.\n*/\nstatic StkId index2stack (lua_State *L, int idx) {\n  CallInfo *ci = L->ci;\n  if (idx > 0) {\n    StkId o = ci->func.p + idx;\n    api_check(L, o < L->top.p, \"invalid index\");\n    return o;\n  }\n  else {    /* non-positive index */\n    api_check(L, idx != 0 && -idx <= L->top.p - (ci->func.p + 1),\n                 \"invalid index\");\n    api_check(L, !ispseudo(idx), \"invalid index\");\n    return L->top.p + idx;\n  }\n}\n\n\nLUA_API int lua_checkstack (lua_State *L, int n) {\n  int res;\n  CallInfo *ci;\n  lua_lock(L);\n  ci = L->ci;\n  api_check(L, n >= 0, \"negative 'n'\");\n  if (L->stack_last.p - L->top.p > n)  /* stack large enough? */\n    res = 1;  /* yes; check is OK */\n  else  /* need to grow stack */\n    res = luaD_growstack(L, n, 0);\n  if (res && ci->top.p < L->top.p + n)\n    ci->top.p = L->top.p + n;  /* adjust frame top */\n  lua_unlock(L);\n  return res;\n}\n\n\nLUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {\n  int i;\n  if (from == to) return;\n  lua_lock(to);\n  api_checkpop(from, n);\n  api_check(from, G(from) == G(to), \"moving among independent states\");\n  api_check(from, to->ci->top.p - to->top.p >= n, \"stack overflow\");\n  from->top.p -= n;\n  for (i = 0; i < n; i++) {\n    setobjs2s(to, to->top.p, from->top.p + i);\n    to->top.p++;  /* stack already checked by previous 'api_check' */\n  }\n  lua_unlock(to);\n}\n\n\nLUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {\n  lua_CFunction old;\n  lua_lock(L);\n  old = G(L)->panic;\n  G(L)->panic = panicf;\n  lua_unlock(L);\n  return old;\n}\n\n\nLUA_API lua_Number lua_version (lua_State *L) {\n  UNUSED(L);\n  return LUA_VERSION_NUM;\n}\n\n\n\n/*\n** basic stack manipulation\n*/\n\n\n/*\n** convert an acceptable stack index into an absolute index\n*/\nLUA_API int lua_absindex (lua_State *L, int idx) {\n  return (idx > 0 || ispseudo(idx))\n         ? idx\n         : cast_int(L->top.p - L->ci->func.p) + idx;\n}\n\n\nLUA_API int lua_gettop (lua_State *L) {\n  return cast_int(L->top.p - (L->ci->func.p + 1));\n}\n\n\nLUA_API void lua_settop (lua_State *L, int idx) {\n  CallInfo *ci;\n  StkId func, newtop;\n  ptrdiff_t diff;  /* difference for new top */\n  lua_lock(L);\n  ci = L->ci;\n  func = ci->func.p;\n  if (idx >= 0) {\n    api_check(L, idx <= ci->top.p - (func + 1), \"new top too large\");\n    diff = ((func + 1) + idx) - L->top.p;\n    for (; diff > 0; diff--)\n      setnilvalue(s2v(L->top.p++));  /* clear new slots */\n  }\n  else {\n    api_check(L, -(idx+1) <= (L->top.p - (func + 1)), \"invalid new top\");\n    diff = idx + 1;  /* will \"subtract\" index (as it is negative) */\n  }\n  newtop = L->top.p + diff;\n  if (diff < 0 && L->tbclist.p >= newtop) {\n    lua_assert(ci->callstatus & CIST_TBC);\n    newtop = luaF_close(L, newtop, CLOSEKTOP, 0);\n  }\n  L->top.p = newtop;  /* correct top only after closing any upvalue */\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_closeslot (lua_State *L, int idx) {\n  StkId level;\n  lua_lock(L);\n  level = index2stack(L, idx);\n  api_check(L, (L->ci->callstatus & CIST_TBC) && (L->tbclist.p == level),\n     \"no variable to close at given level\");\n  level = luaF_close(L, level, CLOSEKTOP, 0);\n  setnilvalue(s2v(level));\n  lua_unlock(L);\n}\n\n\n/*\n** Reverse the stack segment from 'from' to 'to'\n** (auxiliary to 'lua_rotate')\n** Note that we move(copy) only the value inside the stack.\n** (We do not move additional fields that may exist.)\n*/\nstatic void reverse (lua_State *L, StkId from, StkId to) {\n  for (; from < to; from++, to--) {\n    TValue temp;\n    setobj(L, &temp, s2v(from));\n    setobjs2s(L, from, to);\n    setobj2s(L, to, &temp);\n  }\n}\n\n\n/*\n** Let x = AB, where A is a prefix of length 'n'. Then,\n** rotate x n == BA. But BA == (A^r . B^r)^r.\n*/\nLUA_API void lua_rotate (lua_State *L, int idx, int n) {\n  StkId p, t, m;\n  lua_lock(L);\n  t = L->top.p - 1;  /* end of stack segment being rotated */\n  p = index2stack(L, idx);  /* start of segment */\n  api_check(L, L->tbclist.p < p, \"moving a to-be-closed slot\");\n  api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), \"invalid 'n'\");\n  m = (n >= 0 ? t - n : p - n - 1);  /* end of prefix */\n  reverse(L, p, m);  /* reverse the prefix with length 'n' */\n  reverse(L, m + 1, t);  /* reverse the suffix */\n  reverse(L, p, t);  /* reverse the entire segment */\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {\n  TValue *fr, *to;\n  lua_lock(L);\n  fr = index2value(L, fromidx);\n  to = index2value(L, toidx);\n  api_check(L, isvalid(L, to), \"invalid index\");\n  setobj(L, to, fr);\n  if (isupvalue(toidx))  /* function upvalue? */\n    luaC_barrier(L, clCvalue(s2v(L->ci->func.p)), fr);\n  /* LUA_REGISTRYINDEX does not need gc barrier\n     (collector revisits it before finishing collection) */\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_pushvalue (lua_State *L, int idx) {\n  lua_lock(L);\n  setobj2s(L, L->top.p, index2value(L, idx));\n  api_incr_top(L);\n  lua_unlock(L);\n}\n\n\n\n/*\n** access functions (stack -> C)\n*/\n\n\nLUA_API int lua_type (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  return (isvalid(L, o) ? ttype(o) : LUA_TNONE);\n}\n\n\nLUA_API const char *lua_typename (lua_State *L, int t) {\n  UNUSED(L);\n  api_check(L, LUA_TNONE <= t && t < LUA_NUMTYPES, \"invalid type\");\n  return ttypename(t);\n}\n\n\nLUA_API int lua_iscfunction (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  return (ttislcf(o) || (ttisCclosure(o)));\n}\n\n\nLUA_API int lua_isinteger (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  return ttisinteger(o);\n}\n\n\nLUA_API int lua_isnumber (lua_State *L, int idx) {\n  lua_Number n;\n  const TValue *o = index2value(L, idx);\n  return tonumber(o, &n);\n}\n\n\nLUA_API int lua_isstring (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  return (ttisstring(o) || cvt2str(o));\n}\n\n\nLUA_API int lua_isuserdata (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  return (ttisfulluserdata(o) || ttislightuserdata(o));\n}\n\n\nLUA_API int lua_rawequal (lua_State *L, int index1, int index2) {\n  const TValue *o1 = index2value(L, index1);\n  const TValue *o2 = index2value(L, index2);\n  return (isvalid(L, o1) && isvalid(L, o2)) ? luaV_rawequalobj(o1, o2) : 0;\n}\n\n\nLUA_API void lua_arith (lua_State *L, int op) {\n  lua_lock(L);\n  if (op != LUA_OPUNM && op != LUA_OPBNOT)\n    api_checkpop(L, 2);  /* all other operations expect two operands */\n  else {  /* for unary operations, add fake 2nd operand */\n    api_checkpop(L, 1);\n    setobjs2s(L, L->top.p, L->top.p - 1);\n    api_incr_top(L);\n  }\n  /* first operand at top - 2, second at top - 1; result go to top - 2 */\n  luaO_arith(L, op, s2v(L->top.p - 2), s2v(L->top.p - 1), L->top.p - 2);\n  L->top.p--;  /* pop second operand */\n  lua_unlock(L);\n}\n\n\nLUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {\n  const TValue *o1;\n  const TValue *o2;\n  int i = 0;\n  lua_lock(L);  /* may call tag method */\n  o1 = index2value(L, index1);\n  o2 = index2value(L, index2);\n  if (isvalid(L, o1) && isvalid(L, o2)) {\n    switch (op) {\n      case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break;\n      case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;\n      case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;\n      default: api_check(L, 0, \"invalid option\");\n    }\n  }\n  lua_unlock(L);\n  return i;\n}\n\n\nLUA_API unsigned (lua_numbertocstring) (lua_State *L, int idx, char *buff) {\n  const TValue *o = index2value(L, idx);\n  if (ttisnumber(o)) {\n    unsigned len = luaO_tostringbuff(o, buff);\n    buff[len++] = '\\0';  /* add final zero */\n    return len;\n  }\n  else\n    return 0;\n}\n\n\nLUA_API size_t lua_stringtonumber (lua_State *L, const char *s) {\n  size_t sz = luaO_str2num(s, s2v(L->top.p));\n  if (sz != 0)\n    api_incr_top(L);\n  return sz;\n}\n\n\nLUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {\n  lua_Number n = 0;\n  const TValue *o = index2value(L, idx);\n  int isnum = tonumber(o, &n);\n  if (pisnum)\n    *pisnum = isnum;\n  return n;\n}\n\n\nLUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {\n  lua_Integer res = 0;\n  const TValue *o = index2value(L, idx);\n  int isnum = tointeger(o, &res);\n  if (pisnum)\n    *pisnum = isnum;\n  return res;\n}\n\n\nLUA_API int lua_toboolean (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  return !l_isfalse(o);\n}\n\n\nLUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {\n  TValue *o;\n  lua_lock(L);\n  o = index2value(L, idx);\n  if (!ttisstring(o)) {\n    if (!cvt2str(o)) {  /* not convertible? */\n      if (len != NULL) *len = 0;\n      lua_unlock(L);\n      return NULL;\n    }\n    luaO_tostring(L, o);\n    luaC_checkGC(L);\n    o = index2value(L, idx);  /* previous call may reallocate the stack */\n  }\n  lua_unlock(L);\n  if (len != NULL)\n    return getlstr(tsvalue(o), *len);\n  else\n    return getstr(tsvalue(o));\n}\n\n\nLUA_API lua_Unsigned lua_rawlen (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  switch (ttypetag(o)) {\n    case LUA_VSHRSTR: return cast(lua_Unsigned, tsvalue(o)->shrlen);\n    case LUA_VLNGSTR: return cast(lua_Unsigned, tsvalue(o)->u.lnglen);\n    case LUA_VUSERDATA: return cast(lua_Unsigned, uvalue(o)->len);\n    case LUA_VTABLE: {\n      lua_Unsigned res;\n      lua_lock(L);\n      res = luaH_getn(L, hvalue(o));\n      lua_unlock(L);\n      return res;\n    }\n    default: return 0;\n  }\n}\n\n\nLUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  if (ttislcf(o)) return fvalue(o);\n  else if (ttisCclosure(o))\n    return clCvalue(o)->f;\n  else return NULL;  /* not a C function */\n}\n\n\nl_sinline void *touserdata (const TValue *o) {\n  switch (ttype(o)) {\n    case LUA_TUSERDATA: return getudatamem(uvalue(o));\n    case LUA_TLIGHTUSERDATA: return pvalue(o);\n    default: return NULL;\n  }\n}\n\n\nLUA_API void *lua_touserdata (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  return touserdata(o);\n}\n\n\nLUA_API lua_State *lua_tothread (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  return (!ttisthread(o)) ? NULL : thvalue(o);\n}\n\n\n/*\n** Returns a pointer to the internal representation of an object.\n** Note that ISO C does not allow the conversion of a pointer to\n** function to a 'void*', so the conversion here goes through\n** a 'size_t'. (As the returned pointer is only informative, this\n** conversion should not be a problem.)\n*/\nLUA_API const void *lua_topointer (lua_State *L, int idx) {\n  const TValue *o = index2value(L, idx);\n  switch (ttypetag(o)) {\n    case LUA_VLCF: return cast_voidp(cast_sizet(fvalue(o)));\n    case LUA_VUSERDATA: case LUA_VLIGHTUSERDATA:\n      return touserdata(o);\n    default: {\n      if (iscollectable(o))\n        return gcvalue(o);\n      else\n        return NULL;\n    }\n  }\n}\n\n\n\n/*\n** push functions (C -> stack)\n*/\n\n\nLUA_API void lua_pushnil (lua_State *L) {\n  lua_lock(L);\n  setnilvalue(s2v(L->top.p));\n  api_incr_top(L);\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_pushnumber (lua_State *L, lua_Number n) {\n  lua_lock(L);\n  setfltvalue(s2v(L->top.p), n);\n  api_incr_top(L);\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {\n  lua_lock(L);\n  setivalue(s2v(L->top.p), n);\n  api_incr_top(L);\n  lua_unlock(L);\n}\n\n\n/*\n** Pushes on the stack a string with given length. Avoid using 's' when\n** 'len' == 0 (as 's' can be NULL in that case), due to later use of\n** 'memcmp' and 'memcpy'.\n*/\nLUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) {\n  TString *ts;\n  lua_lock(L);\n  ts = (len == 0) ? luaS_new(L, \"\") : luaS_newlstr(L, s, len);\n  setsvalue2s(L, L->top.p, ts);\n  api_incr_top(L);\n  luaC_checkGC(L);\n  lua_unlock(L);\n  return getstr(ts);\n}\n\n\nLUA_API const char *lua_pushexternalstring (lua_State *L,\n\t        const char *s, size_t len, lua_Alloc falloc, void *ud) {\n  TString *ts;\n  lua_lock(L);\n  api_check(L, len <= MAX_SIZE, \"string too large\");\n  api_check(L, s[len] == '\\0', \"string not ending with zero\");\n  ts = luaS_newextlstr (L, s, len, falloc, ud);\n  setsvalue2s(L, L->top.p, ts);\n  api_incr_top(L);\n  luaC_checkGC(L);\n  lua_unlock(L);\n  return getstr(ts);\n}\n\n\nLUA_API const char *lua_pushstring (lua_State *L, const char *s) {\n  lua_lock(L);\n  if (s == NULL)\n    setnilvalue(s2v(L->top.p));\n  else {\n    TString *ts;\n    ts = luaS_new(L, s);\n    setsvalue2s(L, L->top.p, ts);\n    s = getstr(ts);  /* internal copy's address */\n  }\n  api_incr_top(L);\n  luaC_checkGC(L);\n  lua_unlock(L);\n  return s;\n}\n\n\nLUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,\n                                      va_list argp) {\n  const char *ret;\n  lua_lock(L);\n  ret = luaO_pushvfstring(L, fmt, argp);\n  luaC_checkGC(L);\n  lua_unlock(L);\n  return ret;\n}\n\n\nLUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {\n  const char *ret;\n  va_list argp;\n  lua_lock(L);\n  pushvfstring(L, argp, fmt, ret);\n  luaC_checkGC(L);\n  lua_unlock(L);\n  return ret;\n}\n\n\nLUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {\n  lua_lock(L);\n  if (n == 0) {\n    setfvalue(s2v(L->top.p), fn);\n    api_incr_top(L);\n  }\n  else {\n    int i;\n    CClosure *cl;\n    api_checkpop(L, n);\n    api_check(L, n <= MAXUPVAL, \"upvalue index too large\");\n    cl = luaF_newCclosure(L, n);\n    cl->f = fn;\n    for (i = 0; i < n; i++) {\n      setobj2n(L, &cl->upvalue[i], s2v(L->top.p - n + i));\n      /* does not need barrier because closure is white */\n      lua_assert(iswhite(cl));\n    }\n    L->top.p -= n;\n    setclCvalue(L, s2v(L->top.p), cl);\n    api_incr_top(L);\n    luaC_checkGC(L);\n  }\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_pushboolean (lua_State *L, int b) {\n  lua_lock(L);\n  if (b)\n    setbtvalue(s2v(L->top.p));\n  else\n    setbfvalue(s2v(L->top.p));\n  api_incr_top(L);\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_pushlightuserdata (lua_State *L, void *p) {\n  lua_lock(L);\n  setpvalue(s2v(L->top.p), p);\n  api_incr_top(L);\n  lua_unlock(L);\n}\n\n\nLUA_API int lua_pushthread (lua_State *L) {\n  lua_lock(L);\n  setthvalue(L, s2v(L->top.p), L);\n  api_incr_top(L);\n  lua_unlock(L);\n  return (mainthread(G(L)) == L);\n}\n\n\n\n/*\n** get functions (Lua -> stack)\n*/\n\n\nstatic int auxgetstr (lua_State *L, const TValue *t, const char *k) {\n  lu_byte tag;\n  TString *str = luaS_new(L, k);\n  luaV_fastget(t, str, s2v(L->top.p), luaH_getstr, tag);\n  if (!tagisempty(tag))\n    api_incr_top(L);\n  else {\n    setsvalue2s(L, L->top.p, str);\n    api_incr_top(L);\n    tag = luaV_finishget(L, t, s2v(L->top.p - 1), L->top.p - 1, tag);\n  }\n  lua_unlock(L);\n  return novariant(tag);\n}\n\n\n/*\n** The following function assumes that the registry cannot be a weak\n** table; so, an emergency collection while using the global table\n** cannot collect it.\n*/\nstatic void getGlobalTable (lua_State *L, TValue *gt) {\n  Table *registry = hvalue(&G(L)->l_registry);\n  lu_byte tag = luaH_getint(registry, LUA_RIDX_GLOBALS, gt);\n  (void)tag;  /* avoid not-used warnings when checks are off */\n  api_check(L, novariant(tag) == LUA_TTABLE, \"global table must exist\");\n}\n\n\nLUA_API int lua_getglobal (lua_State *L, const char *name) {\n  TValue gt;\n  lua_lock(L);\n  getGlobalTable(L, &gt);\n  return auxgetstr(L, &gt, name);\n}\n\n\nLUA_API int lua_gettable (lua_State *L, int idx) {\n  lu_byte tag;\n  TValue *t;\n  lua_lock(L);\n  api_checkpop(L, 1);\n  t = index2value(L, idx);\n  luaV_fastget(t, s2v(L->top.p - 1), s2v(L->top.p - 1), luaH_get, tag);\n  if (tagisempty(tag))\n    tag = luaV_finishget(L, t, s2v(L->top.p - 1), L->top.p - 1, tag);\n  lua_unlock(L);\n  return novariant(tag);\n}\n\n\nLUA_API int lua_getfield (lua_State *L, int idx, const char *k) {\n  lua_lock(L);\n  return auxgetstr(L, index2value(L, idx), k);\n}\n\n\nLUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {\n  TValue *t;\n  lu_byte tag;\n  lua_lock(L);\n  t = index2value(L, idx);\n  luaV_fastgeti(t, n, s2v(L->top.p), tag);\n  if (tagisempty(tag)) {\n    TValue key;\n    setivalue(&key, n);\n    tag = luaV_finishget(L, t, &key, L->top.p, tag);\n  }\n  api_incr_top(L);\n  lua_unlock(L);\n  return novariant(tag);\n}\n\n\nstatic int finishrawget (lua_State *L, lu_byte tag) {\n  if (tagisempty(tag))  /* avoid copying empty items to the stack */\n    setnilvalue(s2v(L->top.p));\n  api_incr_top(L);\n  lua_unlock(L);\n  return novariant(tag);\n}\n\n\nl_sinline Table *gettable (lua_State *L, int idx) {\n  TValue *t = index2value(L, idx);\n  api_check(L, ttistable(t), \"table expected\");\n  return hvalue(t);\n}\n\n\nLUA_API int lua_rawget (lua_State *L, int idx) {\n  Table *t;\n  lu_byte tag;\n  lua_lock(L);\n  api_checkpop(L, 1);\n  t = gettable(L, idx);\n  tag = luaH_get(t, s2v(L->top.p - 1), s2v(L->top.p - 1));\n  L->top.p--;  /* pop key */\n  return finishrawget(L, tag);\n}\n\n\nLUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {\n  Table *t;\n  lu_byte tag;\n  lua_lock(L);\n  t = gettable(L, idx);\n  luaH_fastgeti(t, n, s2v(L->top.p), tag);\n  return finishrawget(L, tag);\n}\n\n\nLUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {\n  Table *t;\n  TValue k;\n  lua_lock(L);\n  t = gettable(L, idx);\n  setpvalue(&k, cast_voidp(p));\n  return finishrawget(L, luaH_get(t, &k, s2v(L->top.p)));\n}\n\n\nLUA_API void lua_createtable (lua_State *L, int narray, int nrec) {\n  Table *t;\n  lua_lock(L);\n  t = luaH_new(L);\n  sethvalue2s(L, L->top.p, t);\n  api_incr_top(L);\n  if (narray > 0 || nrec > 0)\n    luaH_resize(L, t, cast_uint(narray), cast_uint(nrec));\n  luaC_checkGC(L);\n  lua_unlock(L);\n}\n\n\nLUA_API int lua_getmetatable (lua_State *L, int objindex) {\n  const TValue *obj;\n  Table *mt;\n  int res = 0;\n  lua_lock(L);\n  obj = index2value(L, objindex);\n  switch (ttype(obj)) {\n    case LUA_TTABLE:\n      mt = hvalue(obj)->metatable;\n      break;\n    case LUA_TUSERDATA:\n      mt = uvalue(obj)->metatable;\n      break;\n    default:\n      mt = G(L)->mt[ttype(obj)];\n      break;\n  }\n  if (mt != NULL) {\n    sethvalue2s(L, L->top.p, mt);\n    api_incr_top(L);\n    res = 1;\n  }\n  lua_unlock(L);\n  return res;\n}\n\n\nLUA_API int lua_getiuservalue (lua_State *L, int idx, int n) {\n  TValue *o;\n  int t;\n  lua_lock(L);\n  o = index2value(L, idx);\n  api_check(L, ttisfulluserdata(o), \"full userdata expected\");\n  if (n <= 0 || n > uvalue(o)->nuvalue) {\n    setnilvalue(s2v(L->top.p));\n    t = LUA_TNONE;\n  }\n  else {\n    setobj2s(L, L->top.p, &uvalue(o)->uv[n - 1].uv);\n    t = ttype(s2v(L->top.p));\n  }\n  api_incr_top(L);\n  lua_unlock(L);\n  return t;\n}\n\n\n/*\n** set functions (stack -> Lua)\n*/\n\n/*\n** t[k] = value at the top of the stack (where 'k' is a string)\n*/\nstatic void auxsetstr (lua_State *L, const TValue *t, const char *k) {\n  int hres;\n  TString *str = luaS_new(L, k);\n  api_checkpop(L, 1);\n  luaV_fastset(t, str, s2v(L->top.p - 1), hres, luaH_psetstr);\n  if (hres == HOK) {\n    luaV_finishfastset(L, t, s2v(L->top.p - 1));\n    L->top.p--;  /* pop value */\n  }\n  else {\n    setsvalue2s(L, L->top.p, str);  /* push 'str' (to make it a TValue) */\n    api_incr_top(L);\n    luaV_finishset(L, t, s2v(L->top.p - 1), s2v(L->top.p - 2), hres);\n    L->top.p -= 2;  /* pop value and key */\n  }\n  lua_unlock(L);  /* lock done by caller */\n}\n\n\nLUA_API void lua_setglobal (lua_State *L, const char *name) {\n  TValue gt;\n  lua_lock(L);  /* unlock done in 'auxsetstr' */\n  getGlobalTable(L, &gt);\n  auxsetstr(L, &gt, name);\n}\n\n\nLUA_API void lua_settable (lua_State *L, int idx) {\n  TValue *t;\n  int hres;\n  lua_lock(L);\n  api_checkpop(L, 2);\n  t = index2value(L, idx);\n  luaV_fastset(t, s2v(L->top.p - 2), s2v(L->top.p - 1), hres, luaH_pset);\n  if (hres == HOK)\n    luaV_finishfastset(L, t, s2v(L->top.p - 1));\n  else\n    luaV_finishset(L, t, s2v(L->top.p - 2), s2v(L->top.p - 1), hres);\n  L->top.p -= 2;  /* pop index and value */\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_setfield (lua_State *L, int idx, const char *k) {\n  lua_lock(L);  /* unlock done in 'auxsetstr' */\n  auxsetstr(L, index2value(L, idx), k);\n}\n\n\nLUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {\n  TValue *t;\n  int hres;\n  lua_lock(L);\n  api_checkpop(L, 1);\n  t = index2value(L, idx);\n  luaV_fastseti(t, n, s2v(L->top.p - 1), hres);\n  if (hres == HOK)\n    luaV_finishfastset(L, t, s2v(L->top.p - 1));\n  else {\n    TValue temp;\n    setivalue(&temp, n);\n    luaV_finishset(L, t, &temp, s2v(L->top.p - 1), hres);\n  }\n  L->top.p--;  /* pop value */\n  lua_unlock(L);\n}\n\n\nstatic void aux_rawset (lua_State *L, int idx, TValue *key, int n) {\n  Table *t;\n  lua_lock(L);\n  api_checkpop(L, n);\n  t = gettable(L, idx);\n  luaH_set(L, t, key, s2v(L->top.p - 1));\n  invalidateTMcache(t);\n  luaC_barrierback(L, obj2gco(t), s2v(L->top.p - 1));\n  L->top.p -= n;\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_rawset (lua_State *L, int idx) {\n  aux_rawset(L, idx, s2v(L->top.p - 2), 2);\n}\n\n\nLUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {\n  TValue k;\n  setpvalue(&k, cast_voidp(p));\n  aux_rawset(L, idx, &k, 1);\n}\n\n\nLUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {\n  Table *t;\n  lua_lock(L);\n  api_checkpop(L, 1);\n  t = gettable(L, idx);\n  luaH_setint(L, t, n, s2v(L->top.p - 1));\n  luaC_barrierback(L, obj2gco(t), s2v(L->top.p - 1));\n  L->top.p--;\n  lua_unlock(L);\n}\n\n\nLUA_API int lua_setmetatable (lua_State *L, int objindex) {\n  TValue *obj;\n  Table *mt;\n  lua_lock(L);\n  api_checkpop(L, 1);\n  obj = index2value(L, objindex);\n  if (ttisnil(s2v(L->top.p - 1)))\n    mt = NULL;\n  else {\n    api_check(L, ttistable(s2v(L->top.p - 1)), \"table expected\");\n    mt = hvalue(s2v(L->top.p - 1));\n  }\n  switch (ttype(obj)) {\n    case LUA_TTABLE: {\n      if (l_unlikely(isshared(hvalue(obj))))\n        luaG_runerror(L, \"can't setmetatable to shared table\");\n      hvalue(obj)->metatable = mt;\n      if (mt) {\n        luaC_objbarrier(L, gcvalue(obj), mt);\n        luaC_checkfinalizer(L, gcvalue(obj), mt);\n      }\n      break;\n    }\n    case LUA_TUSERDATA: {\n      uvalue(obj)->metatable = mt;\n      if (mt) {\n        luaC_objbarrier(L, uvalue(obj), mt);\n        luaC_checkfinalizer(L, gcvalue(obj), mt);\n      }\n      break;\n    }\n    default: {\n      G(L)->mt[ttype(obj)] = mt;\n      break;\n    }\n  }\n  L->top.p--;\n  lua_unlock(L);\n  return 1;\n}\n\n\nLUA_API int lua_setiuservalue (lua_State *L, int idx, int n) {\n  TValue *o;\n  int res;\n  lua_lock(L);\n  api_checkpop(L, 1);\n  o = index2value(L, idx);\n  api_check(L, ttisfulluserdata(o), \"full userdata expected\");\n  if (!(cast_uint(n) - 1u < cast_uint(uvalue(o)->nuvalue)))\n    res = 0;  /* 'n' not in [1, uvalue(o)->nuvalue] */\n  else {\n    setobj(L, &uvalue(o)->uv[n - 1].uv, s2v(L->top.p - 1));\n    luaC_barrierback(L, gcvalue(o), s2v(L->top.p - 1));\n    res = 1;\n  }\n  L->top.p--;\n  lua_unlock(L);\n  return res;\n}\n\n\n/*\n** 'load' and 'call' functions (run Lua code)\n*/\n\n\n#define checkresults(L,na,nr) \\\n     (api_check(L, (nr) == LUA_MULTRET \\\n               || (L->ci->top.p - L->top.p >= (nr) - (na)), \\\n\t\"results from function overflow current stack size\"), \\\n      api_check(L, LUA_MULTRET <= (nr) && (nr) <= MAXRESULTS,  \\\n                   \"invalid number of results\"))\n\n\nLUA_API void lua_callk (lua_State *L, int nargs, int nresults,\n                        lua_KContext ctx, lua_KFunction k) {\n  StkId func;\n  lua_lock(L);\n  api_check(L, k == NULL || !isLua(L->ci),\n    \"cannot use continuations inside hooks\");\n  api_checkpop(L, nargs + 1);\n  api_check(L, L->status == LUA_OK, \"cannot do calls on non-normal thread\");\n  checkresults(L, nargs, nresults);\n  func = L->top.p - (nargs+1);\n  if (k != NULL && yieldable(L)) {  /* need to prepare continuation? */\n    L->ci->u.c.k = k;  /* save continuation */\n    L->ci->u.c.ctx = ctx;  /* save context */\n    luaD_call(L, func, nresults);  /* do the call */\n  }\n  else  /* no continuation or no yieldable */\n    luaD_callnoyield(L, func, nresults);  /* just do the call */\n  adjustresults(L, nresults);\n  lua_unlock(L);\n}\n\n\n\n/*\n** Execute a protected call.\n*/\nstruct CallS {  /* data to 'f_call' */\n  StkId func;\n  int nresults;\n};\n\n\nstatic void f_call (lua_State *L, void *ud) {\n  struct CallS *c = cast(struct CallS *, ud);\n  luaD_callnoyield(L, c->func, c->nresults);\n}\n\n\n\nLUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,\n                        lua_KContext ctx, lua_KFunction k) {\n  struct CallS c;\n  TStatus status;\n  ptrdiff_t func;\n  lua_lock(L);\n  api_check(L, k == NULL || !isLua(L->ci),\n    \"cannot use continuations inside hooks\");\n  api_checkpop(L, nargs + 1);\n  api_check(L, L->status == LUA_OK, \"cannot do calls on non-normal thread\");\n  checkresults(L, nargs, nresults);\n  if (errfunc == 0)\n    func = 0;\n  else {\n    StkId o = index2stack(L, errfunc);\n    api_check(L, ttisfunction(s2v(o)), \"error handler must be a function\");\n    func = savestack(L, o);\n  }\n  c.func = L->top.p - (nargs+1);  /* function to be called */\n  if (k == NULL || !yieldable(L)) {  /* no continuation or no yieldable? */\n    c.nresults = nresults;  /* do a 'conventional' protected call */\n    status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);\n  }\n  else {  /* prepare continuation (call is already protected by 'resume') */\n    CallInfo *ci = L->ci;\n    ci->u.c.k = k;  /* save continuation */\n    ci->u.c.ctx = ctx;  /* save context */\n    /* save information for error recovery */\n    ci->u2.funcidx = cast_int(savestack(L, c.func));\n    ci->u.c.old_errfunc = L->errfunc;\n    L->errfunc = func;\n    setoah(ci, L->allowhook);  /* save value of 'allowhook' */\n    ci->callstatus |= CIST_YPCALL;  /* function can do error recovery */\n    luaD_call(L, c.func, nresults);  /* do the call */\n    ci->callstatus &= ~CIST_YPCALL;\n    L->errfunc = ci->u.c.old_errfunc;\n    status = LUA_OK;  /* if it is here, there were no errors */\n  }\n  adjustresults(L, nresults);\n  lua_unlock(L);\n  return APIstatus(status);\n}\n\nstatic void set_env (lua_State *L, LClosure *f) {\n  if (f->nupvalues >= 1) {  /* does it have an upvalue? */\n    /* get global table from registry */\n    TValue gt;\n    getGlobalTable(L, &gt);\n    /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */\n    setobj(L, f->upvals[0]->v.p, &gt);\n    luaC_barrier(L, f->upvals[0], &gt);\n  }\n}\n\nLUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,\n                      const char *chunkname, const char *mode) {\n  ZIO z;\n  TStatus status;\n  lua_lock(L);\n  if (!chunkname) chunkname = \"?\";\n  luaZ_init(L, &z, reader, data);\n  status = luaD_protectedparser(L, &z, chunkname, mode);\n  if (status == LUA_OK) {  /* no errors? */\n    LClosure *f = clLvalue(s2v(L->top.p - 1));  /* get new function */\n    set_env(L,f);\n  }\n  lua_unlock(L);\n  return APIstatus(status);\n}\n\nLUA_API void lua_clonefunction (lua_State *L, const void * fp) {\n  LClosure *cl;\n  LClosure *f = cast(LClosure *, fp);\n  api_check(L, isshared(f->p), \"Not a shared proto\");\n  lua_lock(L);\n  cl = luaF_newLclosure(L,f->nupvalues);\n  setclLvalue2s(L,L->top.p,cl);\n  api_incr_top(L);\n  cl->p = f->p;\n  luaF_initupvals(L, cl);\n  set_env(L,cl);\n  lua_unlock(L);\n}\n\nLUA_API void lua_sharefunction (lua_State *L, int index) {\n  LClosure *f;\n  if (!lua_isfunction(L,index) || lua_iscfunction(L,index))\n    luaG_runerror(L, \"Only Lua function can share\");\n  f = cast(LClosure *, lua_topointer(L, index));\n  luaF_shareproto(f->p);\n}\n\nLUA_API void lua_sharestring (lua_State *L, int index) {\n  TString *ts;\n  if (lua_type(L,index) != LUA_TSTRING)\n    luaG_runerror(L, \"need a string to share\");\n  ts = tsvalue(index2value(L,index));\n  luaS_share(ts);\n}\n\nLUA_API void lua_clonetable(lua_State *L, const void * tp) {\n  Table *t = cast(Table *, tp);\n\n  if (l_unlikely(!isshared(t)))\n    luaG_runerror(L, \"Not a shared table\");\n\n  lua_lock(L);\n  sethvalue2s(L, L->top.p, t);\n  api_incr_top(L);\n  lua_unlock(L);\n}\n\n/*\n** Dump a Lua function, calling 'writer' to write its parts. Ensure\n** the stack returns with its original size.\n*/\nLUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) {\n  int status;\n  ptrdiff_t otop = savestack(L, L->top.p);  /* original top */\n  TValue *f = s2v(L->top.p - 1);  /* function to be dumped */\n  lua_lock(L);\n  api_checkpop(L, 1);\n  api_check(L, isLfunction(f), \"Lua function expected\");\n  status = luaU_dump(L, clLvalue(f)->p, writer, data, strip);\n  L->top.p = restorestack(L, otop);  /* restore top */\n  lua_unlock(L);\n  return status;\n}\n\n\nLUA_API int lua_status (lua_State *L) {\n  return APIstatus(L->status);\n}\n\n\n/*\n** Garbage-collection function\n*/\nLUA_API int lua_gc (lua_State *L, int what, ...) {\n  va_list argp;\n  int res = 0;\n  global_State *g = G(L);\n  if (g->gcstp & (GCSTPGC | GCSTPCLS))  /* internal stop? */\n    return -1;  /* all options are invalid when stopped */\n  lua_lock(L);\n  va_start(argp, what);\n  switch (what) {\n    case LUA_GCSTOP: {\n      g->gcstp = GCSTPUSR;  /* stopped by the user */\n      break;\n    }\n    case LUA_GCRESTART: {\n      luaE_setdebt(g, 0);\n      g->gcstp = 0;  /* (other bits must be zero here) */\n      break;\n    }\n    case LUA_GCCOLLECT: {\n      luaC_fullgc(L, 0);\n      break;\n    }\n    case LUA_GCCOUNT: {\n      /* GC values are expressed in Kbytes: #bytes/2^10 */\n      res = cast_int(gettotalbytes(g) >> 10);\n      break;\n    }\n    case LUA_GCCOUNTB: {\n      res = cast_int(gettotalbytes(g) & 0x3ff);\n      break;\n    }\n    case LUA_GCSTEP: {\n      lu_byte oldstp = g->gcstp;\n      l_mem n = cast(l_mem, va_arg(argp, size_t));\n      int work = 0;  /* true if GC did some work */\n      g->gcstp = 0;  /* allow GC to run (other bits must be zero here) */\n      if (n <= 0)\n        n = g->GCdebt;  /* force to run one basic step */\n      luaE_setdebt(g, g->GCdebt - n);\n      luaC_condGC(L, (void)0, work = 1);\n      if (work && g->gcstate == GCSpause)  /* end of cycle? */\n        res = 1;  /* signal it */\n      g->gcstp = oldstp;  /* restore previous state */\n      break;\n    }\n    case LUA_GCISRUNNING: {\n      res = gcrunning(g);\n      break;\n    }\n    case LUA_GCGEN: {\n      res = (g->gckind == KGC_INC) ? LUA_GCINC : LUA_GCGEN;\n      luaC_changemode(L, KGC_GENMINOR);\n      break;\n    }\n    case LUA_GCINC: {\n      res = (g->gckind == KGC_INC) ? LUA_GCINC : LUA_GCGEN;\n      luaC_changemode(L, KGC_INC);\n      break;\n    }\n    case LUA_GCPARAM: {\n      int param = va_arg(argp, int);\n      int value = va_arg(argp, int);\n      api_check(L, 0 <= param && param < LUA_GCPN, \"invalid parameter\");\n      res = cast_int(luaO_applyparam(g->gcparams[param], 100));\n      if (value >= 0)\n        g->gcparams[param] = luaO_codeparam(cast_uint(value));\n      break;\n    }\n    default: res = -1;  /* invalid option */\n  }\n  va_end(argp);\n  lua_unlock(L);\n  return res;\n}\n\n\n\n/*\n** miscellaneous functions\n*/\n\n\nLUA_API int lua_error (lua_State *L) {\n  TValue *errobj;\n  lua_lock(L);\n  errobj = s2v(L->top.p - 1);\n  api_checkpop(L, 1);\n  /* error object is the memory error message? */\n  if (ttisshrstring(errobj) && eqshrstr(tsvalue(errobj), G(L)->memerrmsg))\n    luaM_error(L);  /* raise a memory error */\n  else\n    luaG_errormsg(L);  /* raise a regular error */\n  /* code unreachable; will unlock when control actually leaves the kernel */\n  return 0;  /* to avoid warnings */\n}\n\n\nLUA_API int lua_next (lua_State *L, int idx) {\n  Table *t;\n  int more;\n  lua_lock(L);\n  api_checkpop(L, 1);\n  t = gettable(L, idx);\n  more = luaH_next(L, t, L->top.p - 1);\n  if (more)\n    api_incr_top(L);\n  else  /* no more elements */\n    L->top.p--;  /* pop key */\n  lua_unlock(L);\n  return more;\n}\n\n\nLUA_API void lua_toclose (lua_State *L, int idx) {\n  StkId o;\n  lua_lock(L);\n  o = index2stack(L, idx);\n  api_check(L, L->tbclist.p < o, \"given index below or equal a marked one\");\n  luaF_newtbcupval(L, o);  /* create new to-be-closed upvalue */\n  L->ci->callstatus |= CIST_TBC;  /* mark that function has TBC slots */\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_concat (lua_State *L, int n) {\n  lua_lock(L);\n  api_checknelems(L, n);\n  if (n > 0) {\n    luaV_concat(L, n);\n    luaC_checkGC(L);\n  }\n  else {  /* nothing to concatenate */\n    setsvalue2s(L, L->top.p, luaS_newlstr(L, \"\", 0));  /* push empty string */\n    api_incr_top(L);\n  }\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_len (lua_State *L, int idx) {\n  TValue *t;\n  lua_lock(L);\n  t = index2value(L, idx);\n  luaV_objlen(L, L->top.p, t);\n  api_incr_top(L);\n  lua_unlock(L);\n}\n\n\nLUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {\n  lua_Alloc f;\n  lua_lock(L);\n  if (ud) *ud = G(L)->ud;\n  f = G(L)->frealloc;\n  lua_unlock(L);\n  return f;\n}\n\n\nLUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {\n  lua_lock(L);\n  G(L)->ud = ud;\n  G(L)->frealloc = f;\n  lua_unlock(L);\n}\n\n\nvoid lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud) {\n  lua_lock(L);\n  G(L)->ud_warn = ud;\n  G(L)->warnf = f;\n  lua_unlock(L);\n}\n\n\nvoid lua_warning (lua_State *L, const char *msg, int tocont) {\n  lua_lock(L);\n  luaE_warning(L, msg, tocont);\n  lua_unlock(L);\n}\n\n\n\nLUA_API void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue) {\n  Udata *u;\n  lua_lock(L);\n  api_check(L, 0 <= nuvalue && nuvalue < SHRT_MAX, \"invalid value\");\n  u = luaS_newudata(L, size, cast(unsigned short, nuvalue));\n  setuvalue(L, s2v(L->top.p), u);\n  api_incr_top(L);\n  luaC_checkGC(L);\n  lua_unlock(L);\n  return getudatamem(u);\n}\n\n\n\nstatic const char *aux_upvalue (TValue *fi, int n, TValue **val,\n                                GCObject **owner) {\n  switch (ttypetag(fi)) {\n    case LUA_VCCL: {  /* C closure */\n      CClosure *f = clCvalue(fi);\n      if (!(cast_uint(n) - 1u < cast_uint(f->nupvalues)))\n        return NULL;  /* 'n' not in [1, f->nupvalues] */\n      *val = &f->upvalue[n-1];\n      if (owner) *owner = obj2gco(f);\n      return \"\";\n    }\n    case LUA_VLCL: {  /* Lua closure */\n      LClosure *f = clLvalue(fi);\n      TString *name;\n      Proto *p = f->p;\n      if (!(cast_uint(n) - 1u  < cast_uint(p->sizeupvalues)))\n        return NULL;  /* 'n' not in [1, p->sizeupvalues] */\n      *val = f->upvals[n-1]->v.p;\n      if (owner) *owner = obj2gco(f->upvals[n - 1]);\n      name = p->upvalues[n-1].name;\n      return (name == NULL) ? \"(no name)\" : getstr(name);\n    }\n    default: return NULL;  /* not a closure */\n  }\n}\n\n\nLUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {\n  const char *name;\n  TValue *val = NULL;  /* to avoid warnings */\n  lua_lock(L);\n  name = aux_upvalue(index2value(L, funcindex), n, &val, NULL);\n  if (name) {\n    setobj2s(L, L->top.p, val);\n    api_incr_top(L);\n  }\n  lua_unlock(L);\n  return name;\n}\n\n\nLUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {\n  const char *name;\n  TValue *val = NULL;  /* to avoid warnings */\n  GCObject *owner = NULL;  /* to avoid warnings */\n  TValue *fi;\n  lua_lock(L);\n  fi = index2value(L, funcindex);\n  api_checknelems(L, 1);\n  name = aux_upvalue(fi, n, &val, &owner);\n  if (name) {\n    L->top.p--;\n    setobj(L, val, s2v(L->top.p));\n    luaC_barrier(L, owner, val);\n  }\n  lua_unlock(L);\n  return name;\n}\n\n\nstatic UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {\n  static const UpVal *const nullup = NULL;\n  LClosure *f;\n  TValue *fi = index2value(L, fidx);\n  api_check(L, ttisLclosure(fi), \"Lua function expected\");\n  f = clLvalue(fi);\n  if (pf) *pf = f;\n  if (1 <= n && n <= f->p->sizeupvalues)\n    return &f->upvals[n - 1];  /* get its upvalue pointer */\n  else\n    return (UpVal**)&nullup;\n}\n\n\nLUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {\n  TValue *fi = index2value(L, fidx);\n  switch (ttypetag(fi)) {\n    case LUA_VLCL: {  /* lua closure */\n      return *getupvalref(L, fidx, n, NULL);\n    }\n    case LUA_VCCL: {  /* C closure */\n      CClosure *f = clCvalue(fi);\n      if (1 <= n && n <= f->nupvalues)\n        return &f->upvalue[n - 1];\n      /* else */\n    }  /* FALLTHROUGH */\n    case LUA_VLCF:\n      return NULL;  /* light C functions have no upvalues */\n    default: {\n      api_check(L, 0, \"function expected\");\n      return NULL;\n    }\n  }\n}\n\n\nLUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,\n                                            int fidx2, int n2) {\n  LClosure *f1;\n  UpVal **up1 = getupvalref(L, fidx1, n1, &f1);\n  UpVal **up2 = getupvalref(L, fidx2, n2, NULL);\n  api_check(L, *up1 != NULL && *up2 != NULL, \"invalid upvalue index\");\n  *up1 = *up2;\n  luaC_objbarrier(L, f1, *up1);\n}\n\n\n"
  },
  {
    "path": "3rd/lua/lapi.h",
    "content": "/*\n** $Id: lapi.h $\n** Auxiliary functions from Lua API\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lapi_h\n#define lapi_h\n\n\n#include \"llimits.h\"\n#include \"lstate.h\"\n\n\n#if defined(LUA_USE_APICHECK)\n#include <assert.h>\n#define api_check(l,e,msg)\tassert(e)\n#else\t/* for testing */\n#define api_check(l,e,msg)\t((void)(l), lua_assert((e) && msg))\n#endif\n\n\n\n/* Increments 'L->top.p', checking for stack overflows */\n#define api_incr_top(L)  \\\n    (L->top.p++, api_check(L, L->top.p <= L->ci->top.p, \"stack overflow\"))\n\n\n/*\n** macros that are executed whenever program enters the Lua core\n** ('lua_lock') and leaves the core ('lua_unlock')\n*/\n#if !defined(lua_lock)\n#define lua_lock(L)\t((void) 0)\n#define lua_unlock(L)\t((void) 0)\n#endif\n\n\n\n/*\n** If a call returns too many multiple returns, the callee may not have\n** stack space to accommodate all results. In this case, this macro\n** increases its stack space ('L->ci->top.p').\n*/\n#define adjustresults(L,nres) \\\n    { if ((nres) <= LUA_MULTRET && L->ci->top.p < L->top.p) \\\n\tL->ci->top.p = L->top.p; }\n\n\n/* Ensure the stack has at least 'n' elements */\n#define api_checknelems(L,n) \\\n       api_check(L, (n) < (L->top.p - L->ci->func.p), \\\n                         \"not enough elements in the stack\")\n\n\n/* Ensure the stack has at least 'n' elements to be popped. (Some\n** functions only update a slot after checking it for popping, but that\n** is only an optimization for a pop followed by a push.)\n*/\n#define api_checkpop(L,n) \\\n\tapi_check(L, (n) < L->top.p - L->ci->func.p &&  \\\n                     L->tbclist.p < L->top.p - (n), \\\n\t\t\t  \"not enough free elements in the stack\")\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lauxlib.c",
    "content": "/*\n** $Id: lauxlib.c $\n** Auxiliary functions for building Lua libraries\n** See Copyright Notice in lua.h\n*/\n\n#define lauxlib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <errno.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\n/*\n** This file uses only the official API of Lua.\n** Any function declared here could be written as an application function.\n*/\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"llimits.h\"\n\n\n/*\n** {======================================================\n** Traceback\n** =======================================================\n*/\n\n\n#define LEVELS1\t10\t/* size of the first part of the stack */\n#define LEVELS2\t11\t/* size of the second part of the stack */\n\n\n\n/*\n** Search for 'objidx' in table at index -1. ('objidx' must be an\n** absolute index.) Return 1 + string at top if it found a good name.\n*/\nstatic int findfield (lua_State *L, int objidx, int level) {\n  if (level == 0 || !lua_istable(L, -1))\n    return 0;  /* not found */\n  lua_pushnil(L);  /* start 'next' loop */\n  while (lua_next(L, -2)) {  /* for each pair in table */\n    if (lua_type(L, -2) == LUA_TSTRING) {  /* ignore non-string keys */\n      if (lua_rawequal(L, objidx, -1)) {  /* found object? */\n        lua_pop(L, 1);  /* remove value (but keep name) */\n        return 1;\n      }\n      else if (findfield(L, objidx, level - 1)) {  /* try recursively */\n        /* stack: lib_name, lib_table, field_name (top) */\n        lua_pushliteral(L, \".\");  /* place '.' between the two names */\n        lua_replace(L, -3);  /* (in the slot occupied by table) */\n        lua_concat(L, 3);  /* lib_name.field_name */\n        return 1;\n      }\n    }\n    lua_pop(L, 1);  /* remove value */\n  }\n  return 0;  /* not found */\n}\n\n\n/*\n** Search for a name for a function in all loaded modules\n*/\nstatic int pushglobalfuncname (lua_State *L, lua_Debug *ar) {\n  int top = lua_gettop(L);\n  lua_getinfo(L, \"f\", ar);  /* push function */\n  lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);\n  luaL_checkstack(L, 6, \"not enough stack\");  /* slots for 'findfield' */\n  if (findfield(L, top + 1, 2)) {\n    const char *name = lua_tostring(L, -1);\n    if (strncmp(name, LUA_GNAME \".\", 3) == 0) {  /* name start with '_G.'? */\n      lua_pushstring(L, name + 3);  /* push name without prefix */\n      lua_remove(L, -2);  /* remove original name */\n    }\n    lua_copy(L, -1, top + 1);  /* copy name to proper place */\n    lua_settop(L, top + 1);  /* remove table \"loaded\" and name copy */\n    return 1;\n  }\n  else {\n    lua_settop(L, top);  /* remove function and global table */\n    return 0;\n  }\n}\n\n\nstatic void pushfuncname (lua_State *L, lua_Debug *ar) {\n  if (*ar->namewhat != '\\0')  /* is there a name from code? */\n    lua_pushfstring(L, \"%s '%s'\", ar->namewhat, ar->name);  /* use it */\n  else if (*ar->what == 'm')  /* main? */\n      lua_pushliteral(L, \"main chunk\");\n  else if (pushglobalfuncname(L, ar)) {  /* try a global name */\n    lua_pushfstring(L, \"function '%s'\", lua_tostring(L, -1));\n    lua_remove(L, -2);  /* remove name */\n  }\n  else if (*ar->what != 'C')  /* for Lua functions, use <file:line> */\n    lua_pushfstring(L, \"function <%s:%d>\", ar->short_src, ar->linedefined);\n  else  /* nothing left... */\n    lua_pushliteral(L, \"?\");\n}\n\n\nstatic int lastlevel (lua_State *L) {\n  lua_Debug ar;\n  int li = 1, le = 1;\n  /* find an upper bound */\n  while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }\n  /* do a binary search */\n  while (li < le) {\n    int m = (li + le)/2;\n    if (lua_getstack(L, m, &ar)) li = m + 1;\n    else le = m;\n  }\n  return le - 1;\n}\n\n\nLUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,\n                                const char *msg, int level) {\n  luaL_Buffer b;\n  lua_Debug ar;\n  int last = lastlevel(L1);\n  int limit2show = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;\n  luaL_buffinit(L, &b);\n  if (msg) {\n    luaL_addstring(&b, msg);\n    luaL_addchar(&b, '\\n');\n  }\n  luaL_addstring(&b, \"stack traceback:\");\n  while (lua_getstack(L1, level++, &ar)) {\n    if (limit2show-- == 0) {  /* too many levels? */\n      int n = last - level - LEVELS2 + 1;  /* number of levels to skip */\n      lua_pushfstring(L, \"\\n\\t...\\t(skipping %d levels)\", n);\n      luaL_addvalue(&b);  /* add warning about skip */\n      level += n;  /* and skip to last levels */\n    }\n    else {\n      lua_getinfo(L1, \"Slnt\", &ar);\n      if (ar.currentline <= 0)\n        lua_pushfstring(L, \"\\n\\t%s: in \", ar.short_src);\n      else\n        lua_pushfstring(L, \"\\n\\t%s:%d: in \", ar.short_src, ar.currentline);\n      luaL_addvalue(&b);\n      pushfuncname(L, &ar);\n      luaL_addvalue(&b);\n      if (ar.istailcall)\n        luaL_addstring(&b, \"\\n\\t(...tail calls...)\");\n    }\n  }\n  luaL_pushresult(&b);\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Error-report functions\n** =======================================================\n*/\n\nLUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {\n  lua_Debug ar;\n  const char *argword;\n  if (!lua_getstack(L, 0, &ar))  /* no stack frame? */\n    return luaL_error(L, \"bad argument #%d (%s)\", arg, extramsg);\n  lua_getinfo(L, \"nt\", &ar);\n  if (arg <= ar.extraargs)  /* error in an extra argument? */\n    argword =  \"extra argument\";\n  else {\n    arg -= ar.extraargs;  /* do not count extra arguments */\n    if (strcmp(ar.namewhat, \"method\") == 0) {  /* colon syntax? */\n      arg--;  /* do not count (extra) self argument */\n      if (arg == 0)  /* error in self argument? */\n        return luaL_error(L, \"calling '%s' on bad self (%s)\",\n                               ar.name, extramsg);\n      /* else go through; error in a regular argument */\n    }\n    argword = \"argument\";\n  }\n  if (ar.name == NULL)\n    ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : \"?\";\n  return luaL_error(L, \"bad %s #%d to '%s' (%s)\",\n                       argword, arg, ar.name, extramsg);\n}\n\n\nLUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) {\n  const char *msg;\n  const char *typearg;  /* name for the type of the actual argument */\n  if (luaL_getmetafield(L, arg, \"__name\") == LUA_TSTRING)\n    typearg = lua_tostring(L, -1);  /* use the given type name */\n  else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)\n    typearg = \"light userdata\";  /* special name for messages */\n  else\n    typearg = luaL_typename(L, arg);  /* standard name */\n  msg = lua_pushfstring(L, \"%s expected, got %s\", tname, typearg);\n  return luaL_argerror(L, arg, msg);\n}\n\n\nstatic void tag_error (lua_State *L, int arg, int tag) {\n  luaL_typeerror(L, arg, lua_typename(L, tag));\n}\n\n\n/*\n** The use of 'lua_pushfstring' ensures this function does not\n** need reserved stack space when called.\n*/\nLUALIB_API void luaL_where (lua_State *L, int level) {\n  lua_Debug ar;\n  if (lua_getstack(L, level, &ar)) {  /* check function at level */\n    lua_getinfo(L, \"Sl\", &ar);  /* get info about it */\n    if (ar.currentline > 0) {  /* is there info? */\n      lua_pushfstring(L, \"%s:%d: \", ar.short_src, ar.currentline);\n      return;\n    }\n  }\n  lua_pushfstring(L, \"\");  /* else, no information available... */\n}\n\n\n/*\n** Again, the use of 'lua_pushvfstring' ensures this function does\n** not need reserved stack space when called. (At worst, it generates\n** a memory error instead of the given message.)\n*/\nLUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {\n  va_list argp;\n  va_start(argp, fmt);\n  luaL_where(L, 1);\n  lua_pushvfstring(L, fmt, argp);\n  va_end(argp);\n  lua_concat(L, 2);\n  return lua_error(L);\n}\n\n\nLUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {\n  int en = errno;  /* calls to Lua API may change this value */\n  if (stat) {\n    lua_pushboolean(L, 1);\n    return 1;\n  }\n  else {\n    const char *msg;\n    luaL_pushfail(L);\n    msg = (en != 0) ? strerror(en) : \"(no extra info)\";\n    if (fname)\n      lua_pushfstring(L, \"%s: %s\", fname, msg);\n    else\n      lua_pushstring(L, msg);\n    lua_pushinteger(L, en);\n    return 3;\n  }\n}\n\n\n#if !defined(l_inspectstat)\t/* { */\n\n#if defined(LUA_USE_POSIX)\n\n#include <sys/wait.h>\n\n/*\n** use appropriate macros to interpret 'pclose' return status\n*/\n#define l_inspectstat(stat,what)  \\\n   if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \\\n   else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = \"signal\"; }\n\n#else\n\n#define l_inspectstat(stat,what)  /* no op */\n\n#endif\n\n#endif\t\t\t\t/* } */\n\n\nLUALIB_API int luaL_execresult (lua_State *L, int stat) {\n  if (stat != 0 && errno != 0)  /* error with an 'errno'? */\n    return luaL_fileresult(L, 0, NULL);\n  else {\n    const char *what = \"exit\";  /* type of termination */\n    l_inspectstat(stat, what);  /* interpret result */\n    if (*what == 'e' && stat == 0)  /* successful termination? */\n      lua_pushboolean(L, 1);\n    else\n      luaL_pushfail(L);\n    lua_pushstring(L, what);\n    lua_pushinteger(L, stat);\n    return 3;  /* return true/fail,what,code */\n  }\n}\n\n/* }====================================================== */\n\n\n\n/*\n** {======================================================\n** Userdata's metatable manipulation\n** =======================================================\n*/\n\nLUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {\n  if (luaL_getmetatable(L, tname) != LUA_TNIL)  /* name already in use? */\n    return 0;  /* leave previous value on top, but return 0 */\n  lua_pop(L, 1);\n  lua_createtable(L, 0, 2);  /* create metatable */\n  lua_pushstring(L, tname);\n  lua_setfield(L, -2, \"__name\");  /* metatable.__name = tname */\n  lua_pushvalue(L, -1);\n  lua_setfield(L, LUA_REGISTRYINDEX, tname);  /* registry.name = metatable */\n  return 1;\n}\n\n\nLUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {\n  luaL_getmetatable(L, tname);\n  lua_setmetatable(L, -2);\n}\n\n\nLUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {\n  void *p = lua_touserdata(L, ud);\n  if (p != NULL) {  /* value is a userdata? */\n    if (lua_getmetatable(L, ud)) {  /* does it have a metatable? */\n      luaL_getmetatable(L, tname);  /* get correct metatable */\n      if (!lua_rawequal(L, -1, -2))  /* not the same? */\n        p = NULL;  /* value is a userdata with wrong metatable */\n      lua_pop(L, 2);  /* remove both metatables */\n      return p;\n    }\n  }\n  return NULL;  /* value is not a userdata with a metatable */\n}\n\n\nLUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {\n  void *p = luaL_testudata(L, ud, tname);\n  luaL_argexpected(L, p != NULL, ud, tname);\n  return p;\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Argument check functions\n** =======================================================\n*/\n\nLUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,\n                                 const char *const lst[]) {\n  const char *name = (def) ? luaL_optstring(L, arg, def) :\n                             luaL_checkstring(L, arg);\n  int i;\n  for (i=0; lst[i]; i++)\n    if (strcmp(lst[i], name) == 0)\n      return i;\n  return luaL_argerror(L, arg,\n                       lua_pushfstring(L, \"invalid option '%s'\", name));\n}\n\n\n/*\n** Ensures the stack has at least 'space' extra slots, raising an error\n** if it cannot fulfill the request. (The error handling needs a few\n** extra slots to format the error message. In case of an error without\n** this extra space, Lua will generate the same 'stack overflow' error,\n** but without 'msg'.)\n*/\nLUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {\n  if (l_unlikely(!lua_checkstack(L, space))) {\n    if (msg)\n      luaL_error(L, \"stack overflow (%s)\", msg);\n    else\n      luaL_error(L, \"stack overflow\");\n  }\n}\n\n\nLUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {\n  if (l_unlikely(lua_type(L, arg) != t))\n    tag_error(L, arg, t);\n}\n\n\nLUALIB_API void luaL_checkany (lua_State *L, int arg) {\n  if (l_unlikely(lua_type(L, arg) == LUA_TNONE))\n    luaL_argerror(L, arg, \"value expected\");\n}\n\n\nLUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {\n  const char *s = lua_tolstring(L, arg, len);\n  if (l_unlikely(!s)) tag_error(L, arg, LUA_TSTRING);\n  return s;\n}\n\n\nLUALIB_API const char *luaL_optlstring (lua_State *L, int arg,\n                                        const char *def, size_t *len) {\n  if (lua_isnoneornil(L, arg)) {\n    if (len)\n      *len = (def ? strlen(def) : 0);\n    return def;\n  }\n  else return luaL_checklstring(L, arg, len);\n}\n\n\nLUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {\n  int isnum;\n  lua_Number d = lua_tonumberx(L, arg, &isnum);\n  if (l_unlikely(!isnum))\n    tag_error(L, arg, LUA_TNUMBER);\n  return d;\n}\n\n\nLUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {\n  return luaL_opt(L, luaL_checknumber, arg, def);\n}\n\n\nstatic void interror (lua_State *L, int arg) {\n  if (lua_isnumber(L, arg))\n    luaL_argerror(L, arg, \"number has no integer representation\");\n  else\n    tag_error(L, arg, LUA_TNUMBER);\n}\n\n\nLUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {\n  int isnum;\n  lua_Integer d = lua_tointegerx(L, arg, &isnum);\n  if (l_unlikely(!isnum)) {\n    interror(L, arg);\n  }\n  return d;\n}\n\n\nLUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,\n                                                      lua_Integer def) {\n  return luaL_opt(L, luaL_checkinteger, arg, def);\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Generic Buffer manipulation\n** =======================================================\n*/\n\n/* userdata to box arbitrary data */\ntypedef struct UBox {\n  void *box;\n  size_t bsize;\n} UBox;\n\n\n/* Resize the buffer used by a box. Optimize for the common case of\n** resizing to the old size. (For instance, __gc will resize the box\n** to 0 even after it was closed. 'pushresult' may also resize it to a\n** final size that is equal to the one set when the buffer was created.)\n*/\nstatic void *resizebox (lua_State *L, int idx, size_t newsize) {\n  UBox *box = (UBox *)lua_touserdata(L, idx);\n  if (box->bsize == newsize)  /* not changing size? */\n    return box->box;  /* keep the buffer */\n  else {\n    void *ud;\n    lua_Alloc allocf = lua_getallocf(L, &ud);\n    void *temp = allocf(ud, box->box, box->bsize, newsize);\n    if (l_unlikely(temp == NULL && newsize > 0)) {  /* allocation error? */\n      lua_pushliteral(L, \"not enough memory\");\n      lua_error(L);  /* raise a memory error */\n    }\n    box->box = temp;\n    box->bsize = newsize;\n    return temp;\n  }\n}\n\n\nstatic int boxgc (lua_State *L) {\n  resizebox(L, 1, 0);\n  return 0;\n}\n\n\nstatic const luaL_Reg boxmt[] = {  /* box metamethods */\n  {\"__gc\", boxgc},\n  {\"__close\", boxgc},\n  {NULL, NULL}\n};\n\n\nstatic void newbox (lua_State *L) {\n  UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0);\n  box->box = NULL;\n  box->bsize = 0;\n  if (luaL_newmetatable(L, \"_UBOX*\"))  /* creating metatable? */\n    luaL_setfuncs(L, boxmt, 0);  /* set its metamethods */\n  lua_setmetatable(L, -2);\n}\n\n\n/*\n** check whether buffer is using a userdata on the stack as a temporary\n** buffer\n*/\n#define buffonstack(B)\t((B)->b != (B)->init.b)\n\n\n/*\n** Whenever buffer is accessed, slot 'idx' must either be a box (which\n** cannot be NULL) or it is a placeholder for the buffer.\n*/\n#define checkbufferlevel(B,idx)  \\\n  lua_assert(buffonstack(B) ? lua_touserdata(B->L, idx) != NULL  \\\n                            : lua_touserdata(B->L, idx) == (void*)B)\n\n\n/*\n** Compute new size for buffer 'B', enough to accommodate extra 'sz'\n** bytes plus one for a terminating zero.\n*/\nstatic size_t newbuffsize (luaL_Buffer *B, size_t sz) {\n  size_t newsize = B->size;\n  if (l_unlikely(sz >= MAX_SIZE - B->n))\n    return cast_sizet(luaL_error(B->L, \"resulting string too large\"));\n  /* else  B->n + sz + 1 <= MAX_SIZE */\n  if (newsize <= MAX_SIZE/3 * 2)  /* no overflow? */\n    newsize += (newsize >> 1);  /* new size *= 1.5 */\n  if (newsize < B->n + sz + 1)  /* not big enough? */\n    newsize = B->n + sz + 1;\n  return newsize;\n}\n\n\n/*\n** Returns a pointer to a free area with at least 'sz' bytes in buffer\n** 'B'. 'boxidx' is the relative position in the stack where is the\n** buffer's box or its placeholder.\n*/\nstatic char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) {\n  checkbufferlevel(B, boxidx);\n  if (B->size - B->n >= sz)  /* enough space? */\n    return B->b + B->n;\n  else {\n    lua_State *L = B->L;\n    char *newbuff;\n    size_t newsize = newbuffsize(B, sz);\n    /* create larger buffer */\n    if (buffonstack(B))  /* buffer already has a box? */\n      newbuff = (char *)resizebox(L, boxidx, newsize);  /* resize it */\n    else {  /* no box yet */\n      lua_remove(L, boxidx);  /* remove placeholder */\n      newbox(L);  /* create a new box */\n      lua_insert(L, boxidx);  /* move box to its intended position */\n      lua_toclose(L, boxidx);\n      newbuff = (char *)resizebox(L, boxidx, newsize);\n      memcpy(newbuff, B->b, B->n * sizeof(char));  /* copy original content */\n    }\n    B->b = newbuff;\n    B->size = newsize;\n    return newbuff + B->n;\n  }\n}\n\n/*\n** returns a pointer to a free area with at least 'sz' bytes\n*/\nLUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {\n  return prepbuffsize(B, sz, -1);\n}\n\n\nLUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {\n  if (l > 0) {  /* avoid 'memcpy' when 's' can be NULL */\n    char *b = prepbuffsize(B, l, -1);\n    memcpy(b, s, l * sizeof(char));\n    luaL_addsize(B, l);\n  }\n}\n\n\nLUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {\n  luaL_addlstring(B, s, strlen(s));\n}\n\n\nLUALIB_API void luaL_pushresult (luaL_Buffer *B) {\n  lua_State *L = B->L;\n  checkbufferlevel(B, -1);\n  if (!buffonstack(B))  /* using static buffer? */\n    lua_pushlstring(L, B->b, B->n);  /* save result as regular string */\n  else {  /* reuse buffer already allocated */\n    UBox *box = (UBox *)lua_touserdata(L, -1);\n    void *ud;\n    lua_Alloc allocf = lua_getallocf(L, &ud);  /* function to free buffer */\n    size_t len = B->n;  /* final string length */\n    char *s;\n    resizebox(L, -1, len + 1);  /* adjust box size to content size */\n    s = (char*)box->box;  /* final buffer address */\n    s[len] = '\\0';  /* add ending zero */\n    /* clear box, as Lua will take control of the buffer */\n    box->bsize = 0;  box->box = NULL;\n    lua_pushexternalstring(L, s, len, allocf, ud);\n    lua_closeslot(L, -2);  /* close the box */\n    lua_gc(L, LUA_GCSTEP, len);\n  }\n  lua_remove(L, -2);  /* remove box or placeholder from the stack */\n}\n\n\nLUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {\n  luaL_addsize(B, sz);\n  luaL_pushresult(B);\n}\n\n\n/*\n** 'luaL_addvalue' is the only function in the Buffer system where the\n** box (if existent) is not on the top of the stack. So, instead of\n** calling 'luaL_addlstring', it replicates the code using -2 as the\n** last argument to 'prepbuffsize', signaling that the box is (or will\n** be) below the string being added to the buffer. (Box creation can\n** trigger an emergency GC, so we should not remove the string from the\n** stack before we have the space guaranteed.)\n*/\nLUALIB_API void luaL_addvalue (luaL_Buffer *B) {\n  lua_State *L = B->L;\n  size_t len;\n  const char *s = lua_tolstring(L, -1, &len);\n  char *b = prepbuffsize(B, len, -2);\n  memcpy(b, s, len * sizeof(char));\n  luaL_addsize(B, len);\n  lua_pop(L, 1);  /* pop string */\n}\n\n\nLUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {\n  B->L = L;\n  B->b = B->init.b;\n  B->n = 0;\n  B->size = LUAL_BUFFERSIZE;\n  lua_pushlightuserdata(L, (void*)B);  /* push placeholder */\n}\n\n\nLUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {\n  luaL_buffinit(L, B);\n  return prepbuffsize(B, sz, -1);\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Reference system\n** =======================================================\n*/\n\n/*\n** The previously freed references form a linked list: t[1] is the index\n** of a first free index, t[t[1]] is the index of the second element,\n** etc. A zero signals the end of the list.\n*/\nLUALIB_API int luaL_ref (lua_State *L, int t) {\n  int ref;\n  if (lua_isnil(L, -1)) {\n    lua_pop(L, 1);  /* remove from stack */\n    return LUA_REFNIL;  /* 'nil' has a unique fixed reference */\n  }\n  t = lua_absindex(L, t);\n  if (lua_rawgeti(L, t, 1) == LUA_TNUMBER)  /* already initialized? */\n    ref = (int)lua_tointeger(L, -1);  /* ref = t[1] */\n  else {  /* first access */\n    lua_assert(!lua_toboolean(L, -1));  /* must be nil or false */\n    ref = 0;  /* list is empty */\n    lua_pushinteger(L, 0);  /* initialize as an empty list */\n    lua_rawseti(L, t, 1);  /* ref = t[1] = 0 */\n  }\n  lua_pop(L, 1);  /* remove element from stack */\n  if (ref != 0) {  /* any free element? */\n    lua_rawgeti(L, t, ref);  /* remove it from list */\n    lua_rawseti(L, t, 1);  /* (t[1] = t[ref]) */\n  }\n  else  /* no free elements */\n    ref = (int)lua_rawlen(L, t) + 1;  /* get a new reference */\n  lua_rawseti(L, t, ref);\n  return ref;\n}\n\n\nLUALIB_API void luaL_unref (lua_State *L, int t, int ref) {\n  if (ref >= 0) {\n    t = lua_absindex(L, t);\n    lua_rawgeti(L, t, 1);\n    lua_assert(lua_isinteger(L, -1));\n    lua_rawseti(L, t, ref);  /* t[ref] = t[1] */\n    lua_pushinteger(L, ref);\n    lua_rawseti(L, t, 1);  /* t[1] = ref */\n  }\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Load functions\n** =======================================================\n*/\n\ntypedef struct LoadF {\n  unsigned n;  /* number of pre-read characters */\n  FILE *f;  /* file being read */\n  char buff[BUFSIZ];  /* area for reading file */\n} LoadF;\n\n\nstatic const char *getF (lua_State *L, void *ud, size_t *size) {\n  LoadF *lf = (LoadF *)ud;\n  UNUSED(L);\n  if (lf->n > 0) {  /* are there pre-read characters to be read? */\n    *size = lf->n;  /* return them (chars already in buffer) */\n    lf->n = 0;  /* no more pre-read characters */\n  }\n  else {  /* read a block from file */\n    /* 'fread' can return > 0 *and* set the EOF flag. If next call to\n       'getF' called 'fread', it might still wait for user input.\n       The next check avoids this problem. */\n    if (feof(lf->f)) return NULL;\n    *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);  /* read block */\n  }\n  return lf->buff;\n}\n\n\nstatic int errfile (lua_State *L, const char *what, int fnameindex) {\n  int err = errno;\n  const char *filename = lua_tostring(L, fnameindex) + 1;\n  if (err != 0)\n    lua_pushfstring(L, \"cannot %s %s: %s\", what, filename, strerror(err));\n  else\n    lua_pushfstring(L, \"cannot %s %s\", what, filename);\n  lua_remove(L, fnameindex);\n  return LUA_ERRFILE;\n}\n\n\n/*\n** Skip an optional BOM at the start of a stream. If there is an\n** incomplete BOM (the first character is correct but the rest is\n** not), returns the first character anyway to force an error\n** (as no chunk can start with 0xEF).\n*/\nstatic int skipBOM (FILE *f) {\n  int c = getc(f);  /* read first character */\n  if (c == 0xEF && getc(f) == 0xBB && getc(f) == 0xBF)  /* correct BOM? */\n    return getc(f);  /* ignore BOM and return next char */\n  else  /* no (valid) BOM */\n    return c;  /* return first character */\n}\n\n\n/*\n** reads the first character of file 'f' and skips an optional BOM mark\n** in its beginning plus its first line if it starts with '#'. Returns\n** true if it skipped the first line.  In any case, '*cp' has the\n** first \"valid\" character of the file (after the optional BOM and\n** a first-line comment).\n*/\nstatic int skipcomment (FILE *f, int *cp) {\n  int c = *cp = skipBOM(f);\n  if (c == '#') {  /* first line is a comment (Unix exec. file)? */\n    do {  /* skip first line */\n      c = getc(f);\n    } while (c != EOF && c != '\\n');\n    *cp = getc(f);  /* next character after comment, if present */\n    return 1;  /* there was a comment */\n  }\n  else return 0;  /* no comment */\n}\n\n\nLUALIB_API int luaL_loadfilex_ (lua_State *L, const char *filename,\n                                             const char *mode) {\n  LoadF lf;\n  int status, readstatus;\n  int c;\n  int fnameindex = lua_gettop(L) + 1;  /* index of filename on the stack */\n  if (filename == NULL) {\n    lua_pushliteral(L, \"=stdin\");\n    lf.f = stdin;\n  }\n  else {\n    lua_pushfstring(L, \"@%s\", filename);\n    errno = 0;\n    lf.f = fopen(filename, \"r\");\n    if (lf.f == NULL) return errfile(L, \"open\", fnameindex);\n  }\n  lf.n = 0;\n  if (skipcomment(lf.f, &c))  /* read initial portion */\n    lf.buff[lf.n++] = '\\n';  /* add newline to correct line numbers */\n  if (c == LUA_SIGNATURE[0]) {  /* binary file? */\n    lf.n = 0;  /* remove possible newline */\n    if (filename) {  /* \"real\" file? */\n      errno = 0;\n      lf.f = freopen(filename, \"rb\", lf.f);  /* reopen in binary mode */\n      if (lf.f == NULL) return errfile(L, \"reopen\", fnameindex);\n      skipcomment(lf.f, &c);  /* re-read initial portion */\n    }\n  }\n  if (c != EOF)\n    lf.buff[lf.n++] = cast_char(c);  /* 'c' is the first character */\n  status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);\n  readstatus = ferror(lf.f);\n  errno = 0;  /* no useful error number until here */\n  if (filename) fclose(lf.f);  /* close file (even in case of errors) */\n  if (readstatus) {\n    lua_settop(L, fnameindex);  /* ignore results from 'lua_load' */\n    return errfile(L, \"read\", fnameindex);\n  }\n  lua_remove(L, fnameindex);\n  return status;\n}\n\n\ntypedef struct LoadS {\n  const char *s;\n  size_t size;\n} LoadS;\n\n\nstatic const char *getS (lua_State *L, void *ud, size_t *size) {\n  LoadS *ls = (LoadS *)ud;\n  UNUSED(L);\n  if (ls->size == 0) return NULL;\n  *size = ls->size;\n  ls->size = 0;\n  return ls->s;\n}\n\n\nLUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,\n                                 const char *name, const char *mode) {\n  LoadS ls;\n  ls.s = buff;\n  ls.size = size;\n  return lua_load(L, getS, &ls, name, mode);\n}\n\n\nLUALIB_API int luaL_loadstring (lua_State *L, const char *s) {\n  return luaL_loadbuffer(L, s, strlen(s), s);\n}\n\n/* }====================================================== */\n\n\n\nLUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {\n  if (!lua_getmetatable(L, obj))  /* no metatable? */\n    return LUA_TNIL;\n  else {\n    int tt;\n    lua_pushstring(L, event);\n    tt = lua_rawget(L, -2);\n    if (tt == LUA_TNIL)  /* is metafield nil? */\n      lua_pop(L, 2);  /* remove metatable and metafield */\n    else\n      lua_remove(L, -2);  /* remove only metatable */\n    return tt;  /* return metafield type */\n  }\n}\n\n\nLUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {\n  obj = lua_absindex(L, obj);\n  if (luaL_getmetafield(L, obj, event) == LUA_TNIL)  /* no metafield? */\n    return 0;\n  lua_pushvalue(L, obj);\n  lua_call(L, 1, 1);\n  return 1;\n}\n\n\nLUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {\n  lua_Integer l;\n  int isnum;\n  lua_len(L, idx);\n  l = lua_tointegerx(L, -1, &isnum);\n  if (l_unlikely(!isnum))\n    luaL_error(L, \"object length is not an integer\");\n  lua_pop(L, 1);  /* remove object */\n  return l;\n}\n\n\nLUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {\n  idx = lua_absindex(L,idx);\n  if (luaL_callmeta(L, idx, \"__tostring\")) {  /* metafield? */\n    if (!lua_isstring(L, -1))\n      luaL_error(L, \"'__tostring' must return a string\");\n  }\n  else {\n    switch (lua_type(L, idx)) {\n      case LUA_TNUMBER: {\n        char buff[LUA_N2SBUFFSZ];\n        lua_numbertocstring(L, idx, buff);\n        lua_pushstring(L, buff);\n        break;\n      }\n      case LUA_TSTRING:\n        lua_pushvalue(L, idx);\n        break;\n      case LUA_TBOOLEAN:\n        lua_pushstring(L, (lua_toboolean(L, idx) ? \"true\" : \"false\"));\n        break;\n      case LUA_TNIL:\n        lua_pushliteral(L, \"nil\");\n        break;\n      default: {\n        int tt = luaL_getmetafield(L, idx, \"__name\");  /* try name */\n        const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :\n                                                 luaL_typename(L, idx);\n        lua_pushfstring(L, \"%s: %p\", kind, lua_topointer(L, idx));\n        if (tt != LUA_TNIL)\n          lua_remove(L, -2);  /* remove '__name' */\n        break;\n      }\n    }\n  }\n  return lua_tolstring(L, -1, len);\n}\n\n\n/*\n** set functions from list 'l' into table at top - 'nup'; each\n** function gets the 'nup' elements at the top as upvalues.\n** Returns with only the table at the stack.\n*/\nLUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {\n  luaL_checkstack(L, nup, \"too many upvalues\");\n  for (; l->name != NULL; l++) {  /* fill the table with given functions */\n    if (l->func == NULL)  /* placeholder? */\n      lua_pushboolean(L, 0);\n    else {\n      int i;\n      for (i = 0; i < nup; i++)  /* copy upvalues to the top */\n        lua_pushvalue(L, -nup);\n      lua_pushcclosure(L, l->func, nup);  /* closure with those upvalues */\n    }\n    lua_setfield(L, -(nup + 2), l->name);\n  }\n  lua_pop(L, nup);  /* remove upvalues */\n}\n\n\n/*\n** ensure that stack[idx][fname] has a table and push that table\n** into the stack\n*/\nLUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {\n  if (lua_getfield(L, idx, fname) == LUA_TTABLE)\n    return 1;  /* table already there */\n  else {\n    lua_pop(L, 1);  /* remove previous result */\n    idx = lua_absindex(L, idx);\n    lua_newtable(L);\n    lua_pushvalue(L, -1);  /* copy to be left at top */\n    lua_setfield(L, idx, fname);  /* assign new table to field */\n    return 0;  /* false, because did not find table there */\n  }\n}\n\n\n/*\n** Stripped-down 'require': After checking \"loaded\" table, calls 'openf'\n** to open a module, registers the result in 'package.loaded' table and,\n** if 'glb' is true, also registers the result in the global table.\n** Leaves resulting module on the top.\n*/\nLUALIB_API void luaL_requiref (lua_State *L, const char *modname,\n                               lua_CFunction openf, int glb) {\n  luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);\n  lua_getfield(L, -1, modname);  /* LOADED[modname] */\n  if (!lua_toboolean(L, -1)) {  /* package not already loaded? */\n    lua_pop(L, 1);  /* remove field */\n    lua_pushcfunction(L, openf);\n    lua_pushstring(L, modname);  /* argument to open function */\n    lua_call(L, 1, 1);  /* call 'openf' to open module */\n    lua_pushvalue(L, -1);  /* make copy of module (call result) */\n    lua_setfield(L, -3, modname);  /* LOADED[modname] = module */\n  }\n  lua_remove(L, -2);  /* remove LOADED table */\n  if (glb) {\n    lua_pushvalue(L, -1);  /* copy of module */\n    lua_setglobal(L, modname);  /* _G[modname] = module */\n  }\n}\n\n\nLUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s,\n                                     const char *p, const char *r) {\n  const char *wild;\n  size_t l = strlen(p);\n  while ((wild = strstr(s, p)) != NULL) {\n    luaL_addlstring(b, s, ct_diff2sz(wild - s));  /* push prefix */\n    luaL_addstring(b, r);  /* push replacement in place of pattern */\n    s = wild + l;  /* continue after 'p' */\n  }\n  luaL_addstring(b, s);  /* push last suffix */\n}\n\n\nLUALIB_API const char *luaL_gsub (lua_State *L, const char *s,\n                                  const char *p, const char *r) {\n  luaL_Buffer b;\n  luaL_buffinit(L, &b);\n  luaL_addgsub(&b, s, p, r);\n  luaL_pushresult(&b);\n  return lua_tostring(L, -1);\n}\n\n\nvoid *luaL_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {\n  UNUSED(ud); UNUSED(osize);\n  if (nsize == 0) {\n    free(ptr);\n    return NULL;\n  }\n  else\n    return realloc(ptr, nsize);\n}\n\n\n/*\n** Standard panic function just prints an error message. The test\n** with 'lua_type' avoids possible memory errors in 'lua_tostring'.\n*/\nstatic int panic (lua_State *L) {\n  const char *msg = (lua_type(L, -1) == LUA_TSTRING)\n                  ? lua_tostring(L, -1)\n                  : \"error object is not a string\";\n  lua_writestringerror(\"PANIC: unprotected error in call to Lua API (%s)\\n\",\n                        msg);\n  return 0;  /* return to Lua to abort */\n}\n\n\n/*\n** Warning functions:\n** warnfoff: warning system is off\n** warnfon: ready to start a new message\n** warnfcont: previous message is to be continued\n*/\nstatic void warnfoff (void *ud, const char *message, int tocont);\nstatic void warnfon (void *ud, const char *message, int tocont);\nstatic void warnfcont (void *ud, const char *message, int tocont);\n\n\n/*\n** Check whether message is a control message. If so, execute the\n** control or ignore it if unknown.\n*/\nstatic int checkcontrol (lua_State *L, const char *message, int tocont) {\n  if (tocont || *(message++) != '@')  /* not a control message? */\n    return 0;\n  else {\n    if (strcmp(message, \"off\") == 0)\n      lua_setwarnf(L, warnfoff, L);  /* turn warnings off */\n    else if (strcmp(message, \"on\") == 0)\n      lua_setwarnf(L, warnfon, L);   /* turn warnings on */\n    return 1;  /* it was a control message */\n  }\n}\n\n\nstatic void warnfoff (void *ud, const char *message, int tocont) {\n  checkcontrol((lua_State *)ud, message, tocont);\n}\n\n\n/*\n** Writes the message and handle 'tocont', finishing the message\n** if needed and setting the next warn function.\n*/\nstatic void warnfcont (void *ud, const char *message, int tocont) {\n  lua_State *L = (lua_State *)ud;\n  lua_writestringerror(\"%s\", message);  /* write message */\n  if (tocont)  /* not the last part? */\n    lua_setwarnf(L, warnfcont, L);  /* to be continued */\n  else {  /* last part */\n    lua_writestringerror(\"%s\", \"\\n\");  /* finish message with end-of-line */\n    lua_setwarnf(L, warnfon, L);  /* next call is a new message */\n  }\n}\n\n\nstatic void warnfon (void *ud, const char *message, int tocont) {\n  if (checkcontrol((lua_State *)ud, message, tocont))  /* control message? */\n    return;  /* nothing else to be done */\n  lua_writestringerror(\"%s\", \"Lua warning: \");  /* start a new warning */\n  warnfcont(ud, message, tocont);  /* finish processing */\n}\n\n\n\n/*\n** A function to compute an unsigned int with some level of\n** randomness. Rely on Address Space Layout Randomization (if present)\n** and the current time.\n*/\n#if !defined(luai_makeseed)\n\n#include <time.h>\n\n\n/* Size for the buffer, in bytes */\n#define BUFSEEDB\t(sizeof(void*) + sizeof(time_t))\n\n/* Size for the buffer in int's, rounded up */\n#define BUFSEED\t\t((BUFSEEDB + sizeof(int) - 1) / sizeof(int))\n\n/*\n** Copy the contents of variable 'v' into the buffer pointed by 'b'.\n** (The '&b[0]' disguises 'b' to fix an absurd warning from clang.)\n*/\n#define addbuff(b,v)\t(memcpy(&b[0], &(v), sizeof(v)), b += sizeof(v))\n\n\nstatic unsigned int luai_makeseed (void) {\n  unsigned int buff[BUFSEED];\n  unsigned int res;\n  unsigned int i;\n  time_t t = time(NULL);\n  char *b = (char*)buff;\n  addbuff(b, b);  /* local variable's address */\n  addbuff(b, t);  /* time */\n  /* fill (rare but possible) remain of the buffer with zeros */\n  memset(b, 0, sizeof(buff) - BUFSEEDB);\n  res = buff[0];\n  for (i = 1; i < BUFSEED; i++)\n    res ^= (res >> 3) + (res << 7) + buff[i];\n  return res;\n}\n\n#endif\n\n\nLUALIB_API unsigned int luaL_makeseed (lua_State *L) {\n  UNUSED(L);\n  return luai_makeseed();\n}\n\n\n/*\n** Use the name with parentheses so that headers can redefine it\n** as a macro.\n*/\nLUALIB_API lua_State *(luaL_newstate) (void) {\n  lua_State *L = lua_newstate(luaL_alloc, NULL, luaL_makeseed(NULL));\n  if (l_likely(L)) {\n    lua_atpanic(L, &panic);\n    lua_setwarnf(L, warnfon, L);\n  }\n  return L;\n}\n\n\nLUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {\n  lua_Number v = lua_version(L);\n  if (sz != LUAL_NUMSIZES)  /* check numeric types */\n    luaL_error(L, \"core and library have incompatible numeric types\");\n  else if (v != ver)\n    luaL_error(L, \"version mismatch: app. needs %f, Lua core provides %f\",\n                  (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v);\n}\n\n// use clonefunction\n\n#include \"spinlock.h\"\n#include \"lstate.h\"\n\nstruct codecache {\n\tstruct spinlock lock;\n\tlua_State *L;\n};\n\nstatic struct codecache CC;\n\nstatic lua_State *\nnewState(lua_State *fromL) {\n  lua_State *L = lua_newstate(luaL_alloc, NULL, G(fromL)->seed);\n  return L;\n}\n\nstatic void\nclearcache(void) {\n\tif (CC.L == NULL)\n\t\treturn;\n\tSPIN_LOCK(&CC)\n\t\tlua_State *fromL = CC.L;\n\t\tCC.L = newState(fromL);\n\t\tlua_close(fromL);\n\tSPIN_UNLOCK(&CC)\n}\n\nstatic void\ninit(lua_State *L) {\n\tCC.L = newState(L);\n}\n\nLUALIB_API void\nluaL_initcodecache(void) {\n\tSPIN_INIT(&CC);\n}\n\nstatic const void *\nload_proto(const char *key) {\n  lua_State *L;\n  const void * result;\n  if (CC.L == NULL)\n    return NULL;\n  SPIN_LOCK(&CC)\n    L = CC.L;\n    lua_pushstring(L, key);\n    lua_rawget(L, LUA_REGISTRYINDEX);\n    result = lua_touserdata(L, -1);\n    lua_pop(L, 1);\n  SPIN_UNLOCK(&CC)\n\n  return result;\n}\n\nstatic const void *\nsave_proto(lua_State *fromL, const char *key, const void * proto) {\n  lua_State *L;\n  const void * result = NULL;\n\n  SPIN_LOCK(&CC)\n    if (CC.L == NULL) {\n      init(fromL);\n    }\n    L = CC.L;\n    lua_pushstring(L, key);\n    lua_pushvalue(L, -1);\n    lua_rawget(L, LUA_REGISTRYINDEX);\n    result = lua_touserdata(L, -1); /* stack: key oldvalue */\n    if (result == NULL) {\n      lua_pop(L,1);\n      lua_pushlightuserdata(L, (void *)proto);\n      lua_rawset(L, LUA_REGISTRYINDEX);\n    } else {\n      lua_pop(L,2);\n    }\n\n  SPIN_UNLOCK(&CC)\n  return result;\n}\n\n#define CACHE_OFF 0\n#define CACHE_EXIST 1\n#define CACHE_ON 2\n\nstatic int cache_key = 0;\n\nstatic int cache_level(lua_State *L) {\n\tint t = lua_rawgetp(L, LUA_REGISTRYINDEX, &cache_key);\n\tint r = lua_tointeger(L, -1);\n\tlua_pop(L,1);\n\tif (t == LUA_TNUMBER) {\n\t\treturn r;\n\t}\n\treturn CACHE_ON;\n}\n\nstatic int cache_mode(lua_State *L) {\n\tstatic const char * lst[] = {\n\t\t\"OFF\",\n\t\t\"EXIST\",\n\t\t\"ON\",\n\t\tNULL,\n\t};\n\tint t,r;\n\tif (lua_isnoneornil(L,1)) {\n\t\tt = lua_rawgetp(L, LUA_REGISTRYINDEX, &cache_key);\n\t\tr = lua_tointeger(L, -1);\n\t\tif (t == LUA_TNUMBER) {\n\t\t\tif (r < 0  || r >= CACHE_ON) {\n\t\t\t\tr = CACHE_ON;\n\t\t\t}\n\t\t} else {\n\t\t\tr = CACHE_ON;\n\t\t}\n\t\tlua_pushstring(L, lst[r]);\n\t\treturn 1;\n\t}\n\tt = luaL_checkoption(L, 1, \"OFF\" , lst);\n\tlua_pushinteger(L, t);\n\tlua_rawsetp(L, LUA_REGISTRYINDEX, &cache_key);\n\treturn 0;\n}\n\nLUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,\n                                             const char *mode) {\n  int level = cache_level(L);\n  const void * proto;\n  lua_State * eL;\n  int err;\n  const void * oldv;\n  if (level == CACHE_OFF || filename == NULL) {\n    return luaL_loadfilex_(L, filename, mode);\n  }\n  proto = load_proto(filename);\n  if (proto) {\n    lua_clonefunction(L, proto);\n    return LUA_OK;\n  }\n  if (level == CACHE_EXIST) {\n    return luaL_loadfilex_(L, filename, mode);\n  }\n  eL = newState(L);\n  if (eL == NULL) {\n    lua_pushliteral(L, \"New state failed\");\n    return LUA_ERRMEM;\n  }\n  err = luaL_loadfilex_(eL, filename, mode);\n  if (err != LUA_OK) {\n    size_t sz = 0;\n    const char * msg = lua_tolstring(eL, -1, &sz);\n    lua_pushlstring(L, msg, sz);\n    lua_close(eL);\n    return err;\n  }\n  lua_sharefunction(eL, -1);\n  proto = lua_topointer(eL, -1);\n  oldv = save_proto(L, filename, proto);\n  if (oldv) {\n    lua_close(eL);\n    lua_clonefunction(L, oldv);\n  } else {\n    lua_clonefunction(L, proto);\n    /* Never close it. notice: memory leak */\n  }\n\n  return LUA_OK;\n}\n\nstatic int\ncache_clear(lua_State *L) {\n\t(void)(L);\n\tclearcache();\n\treturn 0;\n}\n\nLUAMOD_API int luaopen_cache(lua_State *L) {\n\tluaL_Reg l[] = {\n\t\t{ \"clear\", cache_clear },\n\t\t{ \"mode\", cache_mode },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_newlib(L,l);\n\tlua_getglobal(L, \"loadfile\");\n\tlua_setfield(L, -2, \"loadfile\");\n\treturn 1;\n}\n"
  },
  {
    "path": "3rd/lua/lauxlib.h",
    "content": "/*\n** $Id: lauxlib.h $\n** Auxiliary functions for building Lua libraries\n** See Copyright Notice in lua.h\n*/\n\n\n#ifndef lauxlib_h\n#define lauxlib_h\n\n\n#include <stddef.h>\n#include <stdio.h>\n\n#include \"luaconf.h\"\n#include \"lua.h\"\n\n\n/* global table */\n#define LUA_GNAME\t\"_G\"\n\n\ntypedef struct luaL_Buffer luaL_Buffer;\n\n\n/* extra error code for 'luaL_loadfilex' */\n#define LUA_ERRFILE     (LUA_ERRERR+1)\n\n\n/* key, in the registry, for table of loaded modules */\n#define LUA_LOADED_TABLE\t\"_LOADED\"\n\n\n/* key, in the registry, for table of preloaded loaders */\n#define LUA_PRELOAD_TABLE\t\"_PRELOAD\"\n\n\ntypedef struct luaL_Reg {\n  const char *name;\n  lua_CFunction func;\n} luaL_Reg;\n\n\n#define LUAL_NUMSIZES\t(sizeof(lua_Integer)*16 + sizeof(lua_Number))\n\nLUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz);\n#define luaL_checkversion(L)  \\\n\t  luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES)\n\nLUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);\nLUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);\nLUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);\nLUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg);\nLUALIB_API int (luaL_typeerror) (lua_State *L, int arg, const char *tname);\nLUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg,\n                                                          size_t *l);\nLUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg,\n                                          const char *def, size_t *l);\nLUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg);\nLUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def);\n\nLUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg);\nLUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg,\n                                          lua_Integer def);\n\nLUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);\nLUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t);\nLUALIB_API void (luaL_checkany) (lua_State *L, int arg);\n\nLUALIB_API int   (luaL_newmetatable) (lua_State *L, const char *tname);\nLUALIB_API void  (luaL_setmetatable) (lua_State *L, const char *tname);\nLUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname);\nLUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname);\n\nLUALIB_API void (luaL_where) (lua_State *L, int lvl);\nLUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);\n\nLUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def,\n                                   const char *const lst[]);\n\nLUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);\nLUALIB_API int (luaL_execresult) (lua_State *L, int stat);\n\nLUALIB_API void *luaL_alloc (void *ud, void *ptr, size_t osize,\n                                                  size_t nsize);\n\n\n/* predefined references */\n#define LUA_NOREF       (-2)\n#define LUA_REFNIL      (-1)\n\nLUALIB_API int (luaL_ref) (lua_State *L, int t);\nLUALIB_API void (luaL_unref) (lua_State *L, int t, int ref);\n\nLUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename,\n                                               const char *mode);\nLUALIB_API int (luaL_loadfilex_) (lua_State *L, const char *filename,\n                                               const char *mode);\n\n#define luaL_loadfile(L,f)\tluaL_loadfilex(L,f,NULL)\n\nLUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz,\n                                   const char *name, const char *mode);\nLUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);\n\nLUALIB_API lua_State *(luaL_newstate) (void);\n\nLUALIB_API unsigned luaL_makeseed (lua_State *L);\n\nLUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx);\n\nLUALIB_API void (luaL_addgsub) (luaL_Buffer *b, const char *s,\n                                     const char *p, const char *r);\nLUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s,\n                                    const char *p, const char *r);\n\nLUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);\n\nLUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname);\n\nLUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1,\n                                  const char *msg, int level);\n\nLUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,\n                                 lua_CFunction openf, int glb);\n\n/*\n** ===============================================================\n** some useful macros\n** ===============================================================\n*/\n\n\n#define luaL_newlibtable(L,l)\t\\\n  lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)\n\n#define luaL_newlib(L,l)  \\\n  (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))\n\n#define luaL_argcheck(L, cond,arg,extramsg)\t\\\n\t((void)(luai_likely(cond) || luaL_argerror(L, (arg), (extramsg))))\n\n#define luaL_argexpected(L,cond,arg,tname)\t\\\n\t((void)(luai_likely(cond) || luaL_typeerror(L, (arg), (tname))))\n\n#define luaL_checkstring(L,n)\t(luaL_checklstring(L, (n), NULL))\n#define luaL_optstring(L,n,d)\t(luaL_optlstring(L, (n), (d), NULL))\n\n#define luaL_typename(L,i)\tlua_typename(L, lua_type(L,(i)))\n\n#define luaL_dofile(L, fn) \\\n\t(luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))\n\n#define luaL_dostring(L, s) \\\n\t(luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))\n\n#define luaL_getmetatable(L,n)\t(lua_getfield(L, LUA_REGISTRYINDEX, (n)))\n\n#define luaL_opt(L,f,n,d)\t(lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))\n\n#define luaL_loadbuffer(L,s,sz,n)\tluaL_loadbufferx(L,s,sz,n,NULL)\n\n\n/*\n** Perform arithmetic operations on lua_Integer values with wrap-around\n** semantics, as the Lua core does.\n*/\n#define luaL_intop(op,v1,v2)  \\\n\t((lua_Integer)((lua_Unsigned)(v1) op (lua_Unsigned)(v2)))\n\n\n/* push the value used to represent failure/error */\n#if defined(LUA_FAILISFALSE)\n#define luaL_pushfail(L)\tlua_pushboolean(L, 0)\n#else\n#define luaL_pushfail(L)\tlua_pushnil(L)\n#endif\n\n\n\n/*\n** {======================================================\n** Generic Buffer manipulation\n** =======================================================\n*/\n\nstruct luaL_Buffer {\n  char *b;  /* buffer address */\n  size_t size;  /* buffer size */\n  size_t n;  /* number of characters in buffer */\n  lua_State *L;\n  union {\n    LUAI_MAXALIGN;  /* ensure maximum alignment for buffer */\n    char b[LUAL_BUFFERSIZE];  /* initial buffer */\n  } init;\n};\n\n\n#define luaL_bufflen(bf)\t((bf)->n)\n#define luaL_buffaddr(bf)\t((bf)->b)\n\n\n#define luaL_addchar(B,c) \\\n  ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \\\n   ((B)->b[(B)->n++] = (c)))\n\n#define luaL_addsize(B,s)\t((B)->n += (s))\n\n#define luaL_buffsub(B,s)\t((B)->n -= (s))\n\nLUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);\nLUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);\nLUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);\nLUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s);\nLUALIB_API void (luaL_addvalue) (luaL_Buffer *B);\nLUALIB_API void (luaL_pushresult) (luaL_Buffer *B);\nLUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz);\nLUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz);\n\n#define luaL_prepbuffer(B)\tluaL_prepbuffsize(B, LUAL_BUFFERSIZE)\n\n/* }====================================================== */\n\n\n\n/*\n** {======================================================\n** File handles for IO library\n** =======================================================\n*/\n\n/*\n** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and\n** initial structure 'luaL_Stream' (it may contain other fields\n** after that initial structure).\n*/\n\n#define LUA_FILEHANDLE          \"FILE*\"\n\n\ntypedef struct luaL_Stream {\n  FILE *f;  /* stream (NULL for incompletely created streams) */\n  lua_CFunction closef;  /* to close stream (NULL for closed streams) */\n} luaL_Stream;\n\n/* }====================================================== */\n\n\n/*\n** {============================================================\n** Compatibility with deprecated conversions\n** =============================================================\n*/\n#if defined(LUA_COMPAT_APIINTCASTS)\n\n#define luaL_checkunsigned(L,a)\t((lua_Unsigned)luaL_checkinteger(L,a))\n#define luaL_optunsigned(L,a,d)\t\\\n\t((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d)))\n\n#define luaL_checkint(L,n)\t((int)luaL_checkinteger(L, (n)))\n#define luaL_optint(L,n,d)\t((int)luaL_optinteger(L, (n), (d)))\n\n#define luaL_checklong(L,n)\t((long)luaL_checkinteger(L, (n)))\n#define luaL_optlong(L,n,d)\t((long)luaL_optinteger(L, (n), (d)))\n\n#endif\n/* }============================================================ */\n\n\n\n#endif\n\n\n"
  },
  {
    "path": "3rd/lua/lbaselib.c",
    "content": "/*\n** $Id: lbaselib.c $\n** Basic library\n** See Copyright Notice in lua.h\n*/\n\n#define lbaselib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\nstatic int luaB_print (lua_State *L) {\n  int n = lua_gettop(L);  /* number of arguments */\n  int i;\n  for (i = 1; i <= n; i++) {  /* for each argument */\n    size_t l;\n    const char *s = luaL_tolstring(L, i, &l);  /* convert it to string */\n    if (i > 1)  /* not the first element? */\n      lua_writestring(\"\\t\", 1);  /* add a tab before it */\n    lua_writestring(s, l);  /* print it */\n    lua_pop(L, 1);  /* pop result */\n  }\n  lua_writeline();\n  return 0;\n}\n\n\n/*\n** Creates a warning with all given arguments.\n** Check first for errors; otherwise an error may interrupt\n** the composition of a warning, leaving it unfinished.\n*/\nstatic int luaB_warn (lua_State *L) {\n  int n = lua_gettop(L);  /* number of arguments */\n  int i;\n  luaL_checkstring(L, 1);  /* at least one argument */\n  for (i = 2; i <= n; i++)\n    luaL_checkstring(L, i);  /* make sure all arguments are strings */\n  for (i = 1; i < n; i++)  /* compose warning */\n    lua_warning(L, lua_tostring(L, i), 1);\n  lua_warning(L, lua_tostring(L, n), 0);  /* close warning */\n  return 0;\n}\n\n\n#define SPACECHARS\t\" \\f\\n\\r\\t\\v\"\n\nstatic const char *b_str2int (const char *s, unsigned base, lua_Integer *pn) {\n  lua_Unsigned n = 0;\n  int neg = 0;\n  s += strspn(s, SPACECHARS);  /* skip initial spaces */\n  if (*s == '-') { s++; neg = 1; }  /* handle sign */\n  else if (*s == '+') s++;\n  if (!isalnum(cast_uchar(*s)))  /* no digit? */\n    return NULL;\n  do {\n    unsigned digit = cast_uint(isdigit(cast_uchar(*s))\n                               ? *s - '0'\n                               : (toupper(cast_uchar(*s)) - 'A') + 10);\n    if (digit >= base) return NULL;  /* invalid numeral */\n    n = n * base + digit;\n    s++;\n  } while (isalnum(cast_uchar(*s)));\n  s += strspn(s, SPACECHARS);  /* skip trailing spaces */\n  *pn = (lua_Integer)((neg) ? (0u - n) : n);\n  return s;\n}\n\n\nstatic int luaB_tonumber (lua_State *L) {\n  if (lua_isnoneornil(L, 2)) {  /* standard conversion? */\n    if (lua_type(L, 1) == LUA_TNUMBER) {  /* already a number? */\n      lua_settop(L, 1);  /* yes; return it */\n      return 1;\n    }\n    else {\n      size_t l;\n      const char *s = lua_tolstring(L, 1, &l);\n      if (s != NULL && lua_stringtonumber(L, s) == l + 1)\n        return 1;  /* successful conversion to number */\n      /* else not a number */\n      luaL_checkany(L, 1);  /* (but there must be some parameter) */\n    }\n  }\n  else {\n    size_t l;\n    const char *s;\n    lua_Integer n = 0;  /* to avoid warnings */\n    lua_Integer base = luaL_checkinteger(L, 2);\n    luaL_checktype(L, 1, LUA_TSTRING);  /* no numbers as strings */\n    s = lua_tolstring(L, 1, &l);\n    luaL_argcheck(L, 2 <= base && base <= 36, 2, \"base out of range\");\n    if (b_str2int(s, cast_uint(base), &n) == s + l) {\n      lua_pushinteger(L, n);\n      return 1;\n    }  /* else not a number */\n  }  /* else not a number */\n  luaL_pushfail(L);  /* not a number */\n  return 1;\n}\n\n\nstatic int luaB_error (lua_State *L) {\n  int level = (int)luaL_optinteger(L, 2, 1);\n  lua_settop(L, 1);\n  if (lua_type(L, 1) == LUA_TSTRING && level > 0) {\n    luaL_where(L, level);   /* add extra information */\n    lua_pushvalue(L, 1);\n    lua_concat(L, 2);\n  }\n  return lua_error(L);\n}\n\n\nstatic int luaB_getmetatable (lua_State *L) {\n  luaL_checkany(L, 1);\n  if (!lua_getmetatable(L, 1)) {\n    lua_pushnil(L);\n    return 1;  /* no metatable */\n  }\n  luaL_getmetafield(L, 1, \"__metatable\");\n  return 1;  /* returns either __metatable field (if present) or metatable */\n}\n\n\nstatic int luaB_setmetatable (lua_State *L) {\n  int t = lua_type(L, 2);\n  luaL_checktype(L, 1, LUA_TTABLE);\n  luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, \"nil or table\");\n  if (l_unlikely(luaL_getmetafield(L, 1, \"__metatable\") != LUA_TNIL))\n    return luaL_error(L, \"cannot change a protected metatable\");\n  lua_settop(L, 2);\n  lua_setmetatable(L, 1);\n  return 1;\n}\n\n\nstatic int luaB_rawequal (lua_State *L) {\n  luaL_checkany(L, 1);\n  luaL_checkany(L, 2);\n  lua_pushboolean(L, lua_rawequal(L, 1, 2));\n  return 1;\n}\n\n\nstatic int luaB_rawlen (lua_State *L) {\n  int t = lua_type(L, 1);\n  luaL_argexpected(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,\n                      \"table or string\");\n  lua_pushinteger(L, l_castU2S(lua_rawlen(L, 1)));\n  return 1;\n}\n\n\nstatic int luaB_rawget (lua_State *L) {\n  luaL_checktype(L, 1, LUA_TTABLE);\n  luaL_checkany(L, 2);\n  lua_settop(L, 2);\n  lua_rawget(L, 1);\n  return 1;\n}\n\nstatic int luaB_rawset (lua_State *L) {\n  luaL_checktype(L, 1, LUA_TTABLE);\n  luaL_checkany(L, 2);\n  luaL_checkany(L, 3);\n  lua_settop(L, 3);\n  lua_rawset(L, 1);\n  return 1;\n}\n\n\nstatic int pushmode (lua_State *L, int oldmode) {\n  if (oldmode == -1)\n    luaL_pushfail(L);  /* invalid call to 'lua_gc' */\n  else\n    lua_pushstring(L, (oldmode == LUA_GCINC) ? \"incremental\"\n                                             : \"generational\");\n  return 1;\n}\n\n\n/*\n** check whether call to 'lua_gc' was valid (not inside a finalizer)\n*/\n#define checkvalres(res) { if (res == -1) break; }\n\nstatic int luaB_collectgarbage (lua_State *L) {\n  static const char *const opts[] = {\"stop\", \"restart\", \"collect\",\n    \"count\", \"step\", \"isrunning\", \"generational\", \"incremental\",\n    \"param\", NULL};\n  static const char optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,\n    LUA_GCCOUNT, LUA_GCSTEP, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC,\n    LUA_GCPARAM};\n  int o = optsnum[luaL_checkoption(L, 1, \"collect\", opts)];\n  switch (o) {\n    case LUA_GCCOUNT: {\n      int k = lua_gc(L, o);\n      int b = lua_gc(L, LUA_GCCOUNTB);\n      checkvalres(k);\n      lua_pushnumber(L, (lua_Number)k + ((lua_Number)b/1024));\n      return 1;\n    }\n    case LUA_GCSTEP: {\n      lua_Integer n = luaL_optinteger(L, 2, 0);\n      int res = lua_gc(L, o, cast_sizet(n));\n      checkvalres(res);\n      lua_pushboolean(L, res);\n      return 1;\n    }\n    case LUA_GCISRUNNING: {\n      int res = lua_gc(L, o);\n      checkvalres(res);\n      lua_pushboolean(L, res);\n      return 1;\n    }\n    case LUA_GCGEN: {\n      return pushmode(L, lua_gc(L, o));\n    }\n    case LUA_GCINC: {\n      return pushmode(L, lua_gc(L, o));\n    }\n    case LUA_GCPARAM: {\n      static const char *const params[] = {\n        \"minormul\", \"majorminor\", \"minormajor\",\n        \"pause\", \"stepmul\", \"stepsize\", NULL};\n      static const char pnum[] = {\n        LUA_GCPMINORMUL, LUA_GCPMAJORMINOR, LUA_GCPMINORMAJOR,\n        LUA_GCPPAUSE, LUA_GCPSTEPMUL, LUA_GCPSTEPSIZE};\n      int p = pnum[luaL_checkoption(L, 2, NULL, params)];\n      lua_Integer value = luaL_optinteger(L, 3, -1);\n      lua_pushinteger(L, lua_gc(L, o, p, (int)value));\n      return 1;\n    }\n    default: {\n      int res = lua_gc(L, o);\n      checkvalres(res);\n      lua_pushinteger(L, res);\n      return 1;\n    }\n  }\n  luaL_pushfail(L);  /* invalid call (inside a finalizer) */\n  return 1;\n}\n\n\nstatic int luaB_type (lua_State *L) {\n  int t = lua_type(L, 1);\n  luaL_argcheck(L, t != LUA_TNONE, 1, \"value expected\");\n  lua_pushstring(L, lua_typename(L, t));\n  return 1;\n}\n\n\nstatic int luaB_next (lua_State *L) {\n  luaL_checktype(L, 1, LUA_TTABLE);\n  lua_settop(L, 2);  /* create a 2nd argument if there isn't one */\n  if (lua_next(L, 1))\n    return 2;\n  else {\n    lua_pushnil(L);\n    return 1;\n  }\n}\n\n\nstatic int pairscont (lua_State *L, int status, lua_KContext k) {\n  (void)L; (void)status; (void)k;  /* unused */\n  return 4;  /* __pairs did all the work, just return its results */\n}\n\nstatic int luaB_pairs (lua_State *L) {\n  luaL_checkany(L, 1);\n  if (luaL_getmetafield(L, 1, \"__pairs\") == LUA_TNIL) {  /* no metamethod? */\n    lua_pushcfunction(L, luaB_next);  /* will return generator and */\n    lua_pushvalue(L, 1);  /* state */\n    lua_pushnil(L);  /* initial value */\n    lua_pushnil(L);  /* to-be-closed object */\n  }\n  else {\n    lua_pushvalue(L, 1);  /* argument 'self' to metamethod */\n    lua_callk(L, 1, 4, 0, pairscont);  /* get 4 values from metamethod */\n  }\n  return 4;\n}\n\n\n/*\n** Traversal function for 'ipairs'\n*/\nstatic int ipairsaux (lua_State *L) {\n  lua_Integer i = luaL_checkinteger(L, 2);\n  i = luaL_intop(+, i, 1);\n  lua_pushinteger(L, i);\n  return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;\n}\n\n\n/*\n** 'ipairs' function. Returns 'ipairsaux', given \"table\", 0.\n** (The given \"table\" may not be a table.)\n*/\nstatic int luaB_ipairs (lua_State *L) {\n  luaL_checkany(L, 1);\n  lua_pushcfunction(L, ipairsaux);  /* iteration function */\n  lua_pushvalue(L, 1);  /* state */\n  lua_pushinteger(L, 0);  /* initial value */\n  return 3;\n}\n\n\nstatic int load_aux (lua_State *L, int status, int envidx) {\n  if (l_likely(status == LUA_OK)) {\n    if (envidx != 0) {  /* 'env' parameter? */\n      lua_pushvalue(L, envidx);  /* environment for loaded function */\n      if (!lua_setupvalue(L, -2, 1))  /* set it as 1st upvalue */\n        lua_pop(L, 1);  /* remove 'env' if not used by previous call */\n    }\n    return 1;\n  }\n  else {  /* error (message is on top of the stack) */\n    luaL_pushfail(L);\n    lua_insert(L, -2);  /* put before error message */\n    return 2;  /* return fail plus error message */\n  }\n}\n\n\nstatic const char *getMode (lua_State *L, int idx) {\n  const char *mode = luaL_optstring(L, idx, \"bt\");\n  if (strchr(mode, 'B') != NULL)  /* Lua code cannot use fixed buffers */\n    luaL_argerror(L, idx, \"invalid mode\");\n  return mode;\n}\n\n\nstatic int luaB_loadfile (lua_State *L) {\n  const char *fname = luaL_optstring(L, 1, NULL);\n  const char *mode = getMode(L, 2);\n  int env = (!lua_isnone(L, 3) ? 3 : 0);  /* 'env' index or 0 if no 'env' */\n  int status = luaL_loadfilex(L, fname, mode);\n  return load_aux(L, status, env);\n}\n\n\n/*\n** {======================================================\n** Generic Read function\n** =======================================================\n*/\n\n\n/*\n** reserved slot, above all arguments, to hold a copy of the returned\n** string to avoid it being collected while parsed. 'load' has four\n** optional arguments (chunk, source name, mode, and environment).\n*/\n#define RESERVEDSLOT\t5\n\n\n/*\n** Reader for generic 'load' function: 'lua_load' uses the\n** stack for internal stuff, so the reader cannot change the\n** stack top. Instead, it keeps its resulting string in a\n** reserved slot inside the stack.\n*/\nstatic const char *generic_reader (lua_State *L, void *ud, size_t *size) {\n  (void)(ud);  /* not used */\n  luaL_checkstack(L, 2, \"too many nested functions\");\n  lua_pushvalue(L, 1);  /* get function */\n  lua_call(L, 0, 1);  /* call it */\n  if (lua_isnil(L, -1)) {\n    lua_pop(L, 1);  /* pop result */\n    *size = 0;\n    return NULL;\n  }\n  else if (l_unlikely(!lua_isstring(L, -1)))\n    luaL_error(L, \"reader function must return a string\");\n  lua_replace(L, RESERVEDSLOT);  /* save string in reserved slot */\n  return lua_tolstring(L, RESERVEDSLOT, size);\n}\n\n\nstatic int luaB_load (lua_State *L) {\n  int status;\n  size_t l;\n  const char *s = lua_tolstring(L, 1, &l);\n  const char *mode = getMode(L, 3);\n  int env = (!lua_isnone(L, 4) ? 4 : 0);  /* 'env' index or 0 if no 'env' */\n  if (s != NULL) {  /* loading a string? */\n    const char *chunkname = luaL_optstring(L, 2, s);\n    status = luaL_loadbufferx(L, s, l, chunkname, mode);\n  }\n  else {  /* loading from a reader function */\n    const char *chunkname = luaL_optstring(L, 2, \"=(load)\");\n    luaL_checktype(L, 1, LUA_TFUNCTION);\n    lua_settop(L, RESERVEDSLOT);  /* create reserved slot */\n    status = lua_load(L, generic_reader, NULL, chunkname, mode);\n  }\n  return load_aux(L, status, env);\n}\n\n/* }====================================================== */\n\n\nstatic int dofilecont (lua_State *L, int d1, lua_KContext d2) {\n  (void)d1;  (void)d2;  /* only to match 'lua_Kfunction' prototype */\n  return lua_gettop(L) - 1;\n}\n\n\nstatic int luaB_dofile (lua_State *L) {\n  const char *fname = luaL_optstring(L, 1, NULL);\n  lua_settop(L, 1);\n  if (l_unlikely(luaL_loadfile(L, fname) != LUA_OK))\n    return lua_error(L);\n  lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);\n  return dofilecont(L, 0, 0);\n}\n\n\nstatic int luaB_assert (lua_State *L) {\n  if (l_likely(lua_toboolean(L, 1)))  /* condition is true? */\n    return lua_gettop(L);  /* return all arguments */\n  else {  /* error */\n    luaL_checkany(L, 1);  /* there must be a condition */\n    lua_remove(L, 1);  /* remove it */\n    lua_pushliteral(L, \"assertion failed!\");  /* default message */\n    lua_settop(L, 1);  /* leave only message (default if no other one) */\n    return luaB_error(L);  /* call 'error' */\n  }\n}\n\n\nstatic int luaB_select (lua_State *L) {\n  int n = lua_gettop(L);\n  if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {\n    lua_pushinteger(L, n-1);\n    return 1;\n  }\n  else {\n    lua_Integer i = luaL_checkinteger(L, 1);\n    if (i < 0) i = n + i;\n    else if (i > n) i = n;\n    luaL_argcheck(L, 1 <= i, 1, \"index out of range\");\n    return n - (int)i;\n  }\n}\n\n\n/*\n** Continuation function for 'pcall' and 'xpcall'. Both functions\n** already pushed a 'true' before doing the call, so in case of success\n** 'finishpcall' only has to return everything in the stack minus\n** 'extra' values (where 'extra' is exactly the number of items to be\n** ignored).\n*/\nstatic int finishpcall (lua_State *L, int status, lua_KContext extra) {\n  if (l_unlikely(status != LUA_OK && status != LUA_YIELD)) {  /* error? */\n    lua_pushboolean(L, 0);  /* first result (false) */\n    lua_pushvalue(L, -2);  /* error message */\n    return 2;  /* return false, msg */\n  }\n  else\n    return lua_gettop(L) - (int)extra;  /* return all results */\n}\n\n\nstatic int luaB_pcall (lua_State *L) {\n  int status;\n  luaL_checkany(L, 1);\n  lua_pushboolean(L, 1);  /* first result if no errors */\n  lua_insert(L, 1);  /* put it in place */\n  status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall);\n  return finishpcall(L, status, 0);\n}\n\n\n/*\n** Do a protected call with error handling. After 'lua_rotate', the\n** stack will have <f, err, true, f, [args...]>; so, the function passes\n** 2 to 'finishpcall' to skip the 2 first values when returning results.\n*/\nstatic int luaB_xpcall (lua_State *L) {\n  int status;\n  int n = lua_gettop(L);\n  luaL_checktype(L, 2, LUA_TFUNCTION);  /* check error function */\n  lua_pushboolean(L, 1);  /* first result */\n  lua_pushvalue(L, 1);  /* function */\n  lua_rotate(L, 3, 2);  /* move them below function's arguments */\n  status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);\n  return finishpcall(L, status, 2);\n}\n\n\nstatic int luaB_tostring (lua_State *L) {\n  luaL_checkany(L, 1);\n  luaL_tolstring(L, 1, NULL);\n  return 1;\n}\n\n\nstatic const luaL_Reg base_funcs[] = {\n  {\"assert\", luaB_assert},\n  {\"collectgarbage\", luaB_collectgarbage},\n  {\"dofile\", luaB_dofile},\n  {\"error\", luaB_error},\n  {\"getmetatable\", luaB_getmetatable},\n  {\"ipairs\", luaB_ipairs},\n  {\"loadfile\", luaB_loadfile},\n  {\"load\", luaB_load},\n  {\"next\", luaB_next},\n  {\"pairs\", luaB_pairs},\n  {\"pcall\", luaB_pcall},\n  {\"print\", luaB_print},\n  {\"warn\", luaB_warn},\n  {\"rawequal\", luaB_rawequal},\n  {\"rawlen\", luaB_rawlen},\n  {\"rawget\", luaB_rawget},\n  {\"rawset\", luaB_rawset},\n  {\"select\", luaB_select},\n  {\"setmetatable\", luaB_setmetatable},\n  {\"tonumber\", luaB_tonumber},\n  {\"tostring\", luaB_tostring},\n  {\"type\", luaB_type},\n  {\"xpcall\", luaB_xpcall},\n  /* placeholders */\n  {LUA_GNAME, NULL},\n  {\"_VERSION\", NULL},\n  {NULL, NULL}\n};\n\n\nLUAMOD_API int luaopen_base (lua_State *L) {\n  /* open lib into global table */\n  lua_pushglobaltable(L);\n  luaL_setfuncs(L, base_funcs, 0);\n  /* set global _G */\n  lua_pushvalue(L, -1);\n  lua_setfield(L, -2, LUA_GNAME);\n  /* set global _VERSION */\n  lua_pushliteral(L, LUA_VERSION);\n  lua_setfield(L, -2, \"_VERSION\");\n  return 1;\n}\n\n"
  },
  {
    "path": "3rd/lua/lcode.c",
    "content": "/*\n** $Id: lcode.c $\n** Code generator for Lua\n** See Copyright Notice in lua.h\n*/\n\n#define lcode_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <float.h>\n#include <limits.h>\n#include <math.h>\n#include <stdlib.h>\n\n#include \"lua.h\"\n\n#include \"lcode.h\"\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lgc.h\"\n#include \"llex.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lopcodes.h\"\n#include \"lparser.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"lvm.h\"\n\n\n/* (note that expressions VJMP also have jumps.) */\n#define hasjumps(e)\t((e)->t != (e)->f)\n\n\nstatic int codesJ (FuncState *fs, OpCode o, int sj, int k);\n\n\n\n/* semantic error */\nl_noret luaK_semerror (LexState *ls, const char *fmt, ...) {\n  const char *msg;\n  va_list argp;\n  pushvfstring(ls->L, argp, fmt, msg);\n  ls->t.token = 0;  /* remove \"near <token>\" from final message */\n  ls->linenumber = ls->lastline;  /* back to line of last used token */\n  luaX_syntaxerror(ls, msg);\n}\n\n\n/*\n** If expression is a numeric constant, fills 'v' with its value\n** and returns 1. Otherwise, returns 0.\n*/\nstatic int tonumeral (const expdesc *e, TValue *v) {\n  if (hasjumps(e))\n    return 0;  /* not a numeral */\n  switch (e->k) {\n    case VKINT:\n      if (v) setivalue(v, e->u.ival);\n      return 1;\n    case VKFLT:\n      if (v) setfltvalue(v, e->u.nval);\n      return 1;\n    default: return 0;\n  }\n}\n\n\n/*\n** Get the constant value from a constant expression\n*/\nstatic TValue *const2val (FuncState *fs, const expdesc *e) {\n  lua_assert(e->k == VCONST);\n  return &fs->ls->dyd->actvar.arr[e->u.info].k;\n}\n\n\n/*\n** If expression is a constant, fills 'v' with its value\n** and returns 1. Otherwise, returns 0.\n*/\nint luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) {\n  if (hasjumps(e))\n    return 0;  /* not a constant */\n  switch (e->k) {\n    case VFALSE:\n      setbfvalue(v);\n      return 1;\n    case VTRUE:\n      setbtvalue(v);\n      return 1;\n    case VNIL:\n      setnilvalue(v);\n      return 1;\n    case VKSTR: {\n      setsvalue(fs->ls->L, v, e->u.strval);\n      return 1;\n    }\n    case VCONST: {\n      setobj(fs->ls->L, v, const2val(fs, e));\n      return 1;\n    }\n    default: return tonumeral(e, v);\n  }\n}\n\n\n/*\n** Return the previous instruction of the current code. If there\n** may be a jump target between the current instruction and the\n** previous one, return an invalid instruction (to avoid wrong\n** optimizations).\n*/\nstatic Instruction *previousinstruction (FuncState *fs) {\n  static const Instruction invalidinstruction = ~(Instruction)0;\n  if (fs->pc > fs->lasttarget)\n    return &fs->f->code[fs->pc - 1];  /* previous instruction */\n  else\n    return cast(Instruction*, &invalidinstruction);\n}\n\n\n/*\n** Create a OP_LOADNIL instruction, but try to optimize: if the previous\n** instruction is also OP_LOADNIL and ranges are compatible, adjust\n** range of previous instruction instead of emitting a new one. (For\n** instance, 'local a; local b' will generate a single opcode.)\n*/\nvoid luaK_nil (FuncState *fs, int from, int n) {\n  int l = from + n - 1;  /* last register to set nil */\n  Instruction *previous = previousinstruction(fs);\n  if (GET_OPCODE(*previous) == OP_LOADNIL) {  /* previous is LOADNIL? */\n    int pfrom = GETARG_A(*previous);  /* get previous range */\n    int pl = pfrom + GETARG_B(*previous);\n    if ((pfrom <= from && from <= pl + 1) ||\n        (from <= pfrom && pfrom <= l + 1)) {  /* can connect both? */\n      if (pfrom < from) from = pfrom;  /* from = min(from, pfrom) */\n      if (pl > l) l = pl;  /* l = max(l, pl) */\n      SETARG_A(*previous, from);\n      SETARG_B(*previous, l - from);\n      return;\n    }  /* else go through */\n  }\n  luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0);  /* else no optimization */\n}\n\n\n/*\n** Gets the destination address of a jump instruction. Used to traverse\n** a list of jumps.\n*/\nstatic int getjump (FuncState *fs, int pc) {\n  int offset = GETARG_sJ(fs->f->code[pc]);\n  if (offset == NO_JUMP)  /* point to itself represents end of list */\n    return NO_JUMP;  /* end of list */\n  else\n    return (pc+1)+offset;  /* turn offset into absolute position */\n}\n\n\n/*\n** Fix jump instruction at position 'pc' to jump to 'dest'.\n** (Jump addresses are relative in Lua)\n*/\nstatic void fixjump (FuncState *fs, int pc, int dest) {\n  Instruction *jmp = &fs->f->code[pc];\n  int offset = dest - (pc + 1);\n  lua_assert(dest != NO_JUMP);\n  if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ))\n    luaX_syntaxerror(fs->ls, \"control structure too long\");\n  lua_assert(GET_OPCODE(*jmp) == OP_JMP);\n  SETARG_sJ(*jmp, offset);\n}\n\n\n/*\n** Concatenate jump-list 'l2' into jump-list 'l1'\n*/\nvoid luaK_concat (FuncState *fs, int *l1, int l2) {\n  if (l2 == NO_JUMP) return;  /* nothing to concatenate? */\n  else if (*l1 == NO_JUMP)  /* no original list? */\n    *l1 = l2;  /* 'l1' points to 'l2' */\n  else {\n    int list = *l1;\n    int next;\n    while ((next = getjump(fs, list)) != NO_JUMP)  /* find last element */\n      list = next;\n    fixjump(fs, list, l2);  /* last element links to 'l2' */\n  }\n}\n\n\n/*\n** Create a jump instruction and return its position, so its destination\n** can be fixed later (with 'fixjump').\n*/\nint luaK_jump (FuncState *fs) {\n  return codesJ(fs, OP_JMP, NO_JUMP, 0);\n}\n\n\n/*\n** Code a 'return' instruction\n*/\nvoid luaK_ret (FuncState *fs, int first, int nret) {\n  OpCode op;\n  switch (nret) {\n    case 0: op = OP_RETURN0; break;\n    case 1: op = OP_RETURN1; break;\n    default: op = OP_RETURN; break;\n  }\n  luaY_checklimit(fs, nret + 1, MAXARG_B, \"returns\");\n  luaK_codeABC(fs, op, first, nret + 1, 0);\n}\n\n\n/*\n** Code a \"conditional jump\", that is, a test or comparison opcode\n** followed by a jump. Return jump position.\n*/\nstatic int condjump (FuncState *fs, OpCode op, int A, int B, int C, int k) {\n  luaK_codeABCk(fs, op, A, B, C, k);\n  return luaK_jump(fs);\n}\n\n\n/*\n** returns current 'pc' and marks it as a jump target (to avoid wrong\n** optimizations with consecutive instructions not in the same basic block).\n*/\nint luaK_getlabel (FuncState *fs) {\n  fs->lasttarget = fs->pc;\n  return fs->pc;\n}\n\n\n/*\n** Returns the position of the instruction \"controlling\" a given\n** jump (that is, its condition), or the jump itself if it is\n** unconditional.\n*/\nstatic Instruction *getjumpcontrol (FuncState *fs, int pc) {\n  Instruction *pi = &fs->f->code[pc];\n  if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))\n    return pi-1;\n  else\n    return pi;\n}\n\n\n/*\n** Patch destination register for a TESTSET instruction.\n** If instruction in position 'node' is not a TESTSET, return 0 (\"fails\").\n** Otherwise, if 'reg' is not 'NO_REG', set it as the destination\n** register. Otherwise, change instruction to a simple 'TEST' (produces\n** no register value)\n*/\nstatic int patchtestreg (FuncState *fs, int node, int reg) {\n  Instruction *i = getjumpcontrol(fs, node);\n  if (GET_OPCODE(*i) != OP_TESTSET)\n    return 0;  /* cannot patch other instructions */\n  if (reg != NO_REG && reg != GETARG_B(*i))\n    SETARG_A(*i, reg);\n  else {\n     /* no register to put value or register already has the value;\n        change instruction to simple test */\n    *i = CREATE_ABCk(OP_TEST, GETARG_B(*i), 0, 0, GETARG_k(*i));\n  }\n  return 1;\n}\n\n\n/*\n** Traverse a list of tests ensuring no one produces a value\n*/\nstatic void removevalues (FuncState *fs, int list) {\n  for (; list != NO_JUMP; list = getjump(fs, list))\n      patchtestreg(fs, list, NO_REG);\n}\n\n\n/*\n** Traverse a list of tests, patching their destination address and\n** registers: tests producing values jump to 'vtarget' (and put their\n** values in 'reg'), other tests jump to 'dtarget'.\n*/\nstatic void patchlistaux (FuncState *fs, int list, int vtarget, int reg,\n                          int dtarget) {\n  while (list != NO_JUMP) {\n    int next = getjump(fs, list);\n    if (patchtestreg(fs, list, reg))\n      fixjump(fs, list, vtarget);\n    else\n      fixjump(fs, list, dtarget);  /* jump to default target */\n    list = next;\n  }\n}\n\n\n/*\n** Path all jumps in 'list' to jump to 'target'.\n** (The assert means that we cannot fix a jump to a forward address\n** because we only know addresses once code is generated.)\n*/\nvoid luaK_patchlist (FuncState *fs, int list, int target) {\n  lua_assert(target <= fs->pc);\n  patchlistaux(fs, list, target, NO_REG, target);\n}\n\n\nvoid luaK_patchtohere (FuncState *fs, int list) {\n  int hr = luaK_getlabel(fs);  /* mark \"here\" as a jump target */\n  luaK_patchlist(fs, list, hr);\n}\n\n\n/* limit for difference between lines in relative line info. */\n#define LIMLINEDIFF\t0x80\n\n\n/*\n** Save line info for a new instruction. If difference from last line\n** does not fit in a byte, of after that many instructions, save a new\n** absolute line info; (in that case, the special value 'ABSLINEINFO'\n** in 'lineinfo' signals the existence of this absolute information.)\n** Otherwise, store the difference from last line in 'lineinfo'.\n*/\nstatic void savelineinfo (FuncState *fs, Proto *f, int line) {\n  int linedif = line - fs->previousline;\n  int pc = fs->pc - 1;  /* last instruction coded */\n  if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ >= MAXIWTHABS) {\n    luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo,\n                    f->sizeabslineinfo, AbsLineInfo, INT_MAX, \"lines\");\n    f->abslineinfo[fs->nabslineinfo].pc = pc;\n    f->abslineinfo[fs->nabslineinfo++].line = line;\n    linedif = ABSLINEINFO;  /* signal that there is absolute information */\n    fs->iwthabs = 1;  /* restart counter */\n  }\n  luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte,\n                  INT_MAX, \"opcodes\");\n  f->lineinfo[pc] = cast(ls_byte, linedif);\n  fs->previousline = line;  /* last line saved */\n}\n\n\n/*\n** Remove line information from the last instruction.\n** If line information for that instruction is absolute, set 'iwthabs'\n** above its max to force the new (replacing) instruction to have\n** absolute line info, too.\n*/\nstatic void removelastlineinfo (FuncState *fs) {\n  Proto *f = fs->f;\n  int pc = fs->pc - 1;  /* last instruction coded */\n  if (f->lineinfo[pc] != ABSLINEINFO) {  /* relative line info? */\n    fs->previousline -= f->lineinfo[pc];  /* correct last line saved */\n    fs->iwthabs--;  /* undo previous increment */\n  }\n  else {  /* absolute line information */\n    lua_assert(f->abslineinfo[fs->nabslineinfo - 1].pc == pc);\n    fs->nabslineinfo--;  /* remove it */\n    fs->iwthabs = MAXIWTHABS + 1;  /* force next line info to be absolute */\n  }\n}\n\n\n/*\n** Remove the last instruction created, correcting line information\n** accordingly.\n*/\nstatic void removelastinstruction (FuncState *fs) {\n  removelastlineinfo(fs);\n  fs->pc--;\n}\n\n\n/*\n** Emit instruction 'i', checking for array sizes and saving also its\n** line information. Return 'i' position.\n*/\nint luaK_code (FuncState *fs, Instruction i) {\n  Proto *f = fs->f;\n  /* put new instruction in code array */\n  luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,\n                  INT_MAX, \"opcodes\");\n  f->code[fs->pc++] = i;\n  savelineinfo(fs, f, fs->ls->lastline);\n  return fs->pc - 1;  /* index of new instruction */\n}\n\n\n/*\n** Format and emit an 'iABC' instruction. (Assertions check consistency\n** of parameters versus opcode.)\n*/\nint luaK_codeABCk (FuncState *fs, OpCode o, int A, int B, int C, int k) {\n  lua_assert(getOpMode(o) == iABC);\n  lua_assert(A <= MAXARG_A && B <= MAXARG_B &&\n             C <= MAXARG_C && (k & ~1) == 0);\n  return luaK_code(fs, CREATE_ABCk(o, A, B, C, k));\n}\n\n\nint luaK_codevABCk (FuncState *fs, OpCode o, int A, int B, int C, int k) {\n  lua_assert(getOpMode(o) == ivABC);\n  lua_assert(A <= MAXARG_A && B <= MAXARG_vB &&\n             C <= MAXARG_vC && (k & ~1) == 0);\n  return luaK_code(fs, CREATE_vABCk(o, A, B, C, k));\n}\n\n\n/*\n** Format and emit an 'iABx' instruction.\n*/\nint luaK_codeABx (FuncState *fs, OpCode o, int A, int Bc) {\n  lua_assert(getOpMode(o) == iABx);\n  lua_assert(A <= MAXARG_A && Bc <= MAXARG_Bx);\n  return luaK_code(fs, CREATE_ABx(o, A, Bc));\n}\n\n\n/*\n** Format and emit an 'iAsBx' instruction.\n*/\nstatic int codeAsBx (FuncState *fs, OpCode o, int A, int Bc) {\n  int b = Bc + OFFSET_sBx;\n  lua_assert(getOpMode(o) == iAsBx);\n  lua_assert(A <= MAXARG_A && b <= MAXARG_Bx);\n  return luaK_code(fs, CREATE_ABx(o, A, b));\n}\n\n\n/*\n** Format and emit an 'isJ' instruction.\n*/\nstatic int codesJ (FuncState *fs, OpCode o, int sj, int k) {\n  int j = sj + OFFSET_sJ;\n  lua_assert(getOpMode(o) == isJ);\n  lua_assert(j <= MAXARG_sJ && (k & ~1) == 0);\n  return luaK_code(fs, CREATE_sJ(o, j, k));\n}\n\n\n/*\n** Emit an \"extra argument\" instruction (format 'iAx')\n*/\nstatic int codeextraarg (FuncState *fs, int A) {\n  lua_assert(A <= MAXARG_Ax);\n  return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, A));\n}\n\n\n/*\n** Emit a \"load constant\" instruction, using either 'OP_LOADK'\n** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX'\n** instruction with \"extra argument\".\n*/\nstatic int luaK_codek (FuncState *fs, int reg, int k) {\n  if (k <= MAXARG_Bx)\n    return luaK_codeABx(fs, OP_LOADK, reg, k);\n  else {\n    int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);\n    codeextraarg(fs, k);\n    return p;\n  }\n}\n\n\n/*\n** Check register-stack level, keeping track of its maximum size\n** in field 'maxstacksize'\n*/\nvoid luaK_checkstack (FuncState *fs, int n) {\n  int newstack = fs->freereg + n;\n  if (newstack > fs->f->maxstacksize) {\n    luaY_checklimit(fs, newstack, MAX_FSTACK, \"registers\");\n    fs->f->maxstacksize = cast_byte(newstack);\n  }\n}\n\n\n/*\n** Reserve 'n' registers in register stack\n*/\nvoid luaK_reserveregs (FuncState *fs, int n) {\n  luaK_checkstack(fs, n);\n  fs->freereg =  cast_byte(fs->freereg + n);\n}\n\n\n/*\n** Free register 'reg', if it is neither a constant index nor\n** a local variable.\n)\n*/\nstatic void freereg (FuncState *fs, int reg) {\n  if (reg >= luaY_nvarstack(fs)) {\n    fs->freereg--;\n    lua_assert(reg == fs->freereg);\n  }\n}\n\n\n/*\n** Free two registers in proper order\n*/\nstatic void freeregs (FuncState *fs, int r1, int r2) {\n  if (r1 > r2) {\n    freereg(fs, r1);\n    freereg(fs, r2);\n  }\n  else {\n    freereg(fs, r2);\n    freereg(fs, r1);\n  }\n}\n\n\n/*\n** Free register used by expression 'e' (if any)\n*/\nstatic void freeexp (FuncState *fs, expdesc *e) {\n  if (e->k == VNONRELOC)\n    freereg(fs, e->u.info);\n}\n\n\n/*\n** Free registers used by expressions 'e1' and 'e2' (if any) in proper\n** order.\n*/\nstatic void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) {\n  int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1;\n  int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1;\n  freeregs(fs, r1, r2);\n}\n\n\n/*\n** Add constant 'v' to prototype's list of constants (field 'k').\n*/\nstatic int addk (FuncState *fs, Proto *f, TValue *v) {\n  lua_State *L = fs->ls->L;\n  int oldsize = f->sizek;\n  int k = fs->nk;\n  luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, \"constants\");\n  while (oldsize < f->sizek)\n    setnilvalue(&f->k[oldsize++]);\n  setobj(L, &f->k[k], v);\n  fs->nk++;\n  luaC_barrier(L, f, v);\n  return k;\n}\n\n\n/*\n** Use scanner's table to cache position of constants in constant list\n** and try to reuse constants. Because some values should not be used\n** as keys (nil cannot be a key, integer keys can collapse with float\n** keys), the caller must provide a useful 'key' for indexing the cache.\n*/\nstatic int k2proto (FuncState *fs, TValue *key, TValue *v) {\n  TValue val;\n  Proto *f = fs->f;\n  int tag = luaH_get(fs->kcache, key, &val);  /* query scanner table */\n  if (!tagisempty(tag)) {  /* is there an index there? */\n    int k = cast_int(ivalue(&val));\n    /* collisions can happen only for float keys */\n    lua_assert(ttisfloat(key) || luaV_rawequalobj(&f->k[k], v));\n    return k;  /* reuse index */\n  }\n  else {  /* constant not found; create a new entry */\n    int k = addk(fs, f, v);\n    /* cache it for reuse; numerical value does not need GC barrier;\n       table is not a metatable, so it does not need to invalidate cache */\n    setivalue(&val, k);\n    luaH_set(fs->ls->L, fs->kcache, key, &val);\n    return k;\n  }\n}\n\n\n/*\n** Add a string to list of constants and return its index.\n*/\nstatic int stringK (FuncState *fs, TString *s) {\n  TValue o;\n  setsvalue(fs->ls->L, &o, s);\n  return k2proto(fs, &o, &o);  /* use string itself as key */\n}\n\n\n/*\n** Add an integer to list of constants and return its index.\n*/\nstatic int luaK_intK (FuncState *fs, lua_Integer n) {\n  TValue o;\n  setivalue(&o, n);\n  return k2proto(fs, &o, &o);  /* use integer itself as key */\n}\n\n/*\n** Add a float to list of constants and return its index. Floats\n** with integral values need a different key, to avoid collision\n** with actual integers. To that end, we add to the number its smaller\n** power-of-two fraction that is still significant in its scale.\n** (For doubles, the fraction would be 2^-52).\n** This method is not bulletproof: different numbers may generate the\n** same key (e.g., very large numbers will overflow to 'inf') and for\n** floats larger than 2^53 the result is still an integer. For those\n** cases, just generate a new entry. At worst, this only wastes an entry\n** with a duplicate.\n*/\nstatic int luaK_numberK (FuncState *fs, lua_Number r) {\n  TValue o, kv;\n  setfltvalue(&o, r);  /* value as a TValue */\n  if (r == 0) {  /* handle zero as a special case */\n    setpvalue(&kv, fs);  /* use FuncState as index */\n    return k2proto(fs, &kv, &o);  /* cannot collide */\n  }\n  else {\n    const int nbm = l_floatatt(MANT_DIG);\n    const lua_Number q = l_mathop(ldexp)(l_mathop(1.0), -nbm + 1);\n    const lua_Number k =  r * (1 + q);  /* key */\n    lua_Integer ik;\n    setfltvalue(&kv, k);  /* key as a TValue */\n    if (!luaV_flttointeger(k, &ik, F2Ieq)) {  /* not an integer value? */\n      int n = k2proto(fs, &kv, &o);  /* use key */\n      if (luaV_rawequalobj(&fs->f->k[n], &o))  /* correct value? */\n        return n;\n    }\n    /* else, either key is still an integer or there was a collision;\n       anyway, do not try to reuse constant; instead, create a new one */\n    return addk(fs, fs->f, &o);\n  }\n}\n\n\n/*\n** Add a false to list of constants and return its index.\n*/\nstatic int boolF (FuncState *fs) {\n  TValue o;\n  setbfvalue(&o);\n  return k2proto(fs, &o, &o);  /* use boolean itself as key */\n}\n\n\n/*\n** Add a true to list of constants and return its index.\n*/\nstatic int boolT (FuncState *fs) {\n  TValue o;\n  setbtvalue(&o);\n  return k2proto(fs, &o, &o);  /* use boolean itself as key */\n}\n\n\n/*\n** Add nil to list of constants and return its index.\n*/\nstatic int nilK (FuncState *fs) {\n  TValue k, v;\n  setnilvalue(&v);\n  /* cannot use nil as key; instead use table itself */\n  sethvalue(fs->ls->L, &k, fs->kcache);\n  return k2proto(fs, &k, &v);\n}\n\n\n/*\n** Check whether 'i' can be stored in an 'sC' operand. Equivalent to\n** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of\n** overflows in the hidden addition inside 'int2sC'.\n*/\nstatic int fitsC (lua_Integer i) {\n  return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C));\n}\n\n\n/*\n** Check whether 'i' can be stored in an 'sBx' operand.\n*/\nstatic int fitsBx (lua_Integer i) {\n  return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx);\n}\n\n\nvoid luaK_int (FuncState *fs, int reg, lua_Integer i) {\n  if (fitsBx(i))\n    codeAsBx(fs, OP_LOADI, reg, cast_int(i));\n  else\n    luaK_codek(fs, reg, luaK_intK(fs, i));\n}\n\n\nstatic void luaK_float (FuncState *fs, int reg, lua_Number f) {\n  lua_Integer fi;\n  if (luaV_flttointeger(f, &fi, F2Ieq) && fitsBx(fi))\n    codeAsBx(fs, OP_LOADF, reg, cast_int(fi));\n  else\n    luaK_codek(fs, reg, luaK_numberK(fs, f));\n}\n\n\n/*\n** Get the value of 'var' in a register and generate an opcode to check\n** whether that register is nil. 'k' is the index of the variable name\n** in the list of constants. If its value cannot be encoded in Bx, a 0\n** will use '?' for the name.\n*/\nvoid luaK_codecheckglobal (FuncState *fs, expdesc *var, int k, int line) {\n  luaK_exp2anyreg(fs, var);\n  luaK_fixline(fs, line);\n  k = (k >= MAXARG_Bx) ? 0 : k + 1;\n  luaK_codeABx(fs, OP_ERRNNIL, var->u.info, k);\n  luaK_fixline(fs, line);\n  freeexp(fs, var);\n}\n\n\n/*\n** Convert a constant in 'v' into an expression description 'e'\n*/\nstatic void const2exp (TValue *v, expdesc *e) {\n  switch (ttypetag(v)) {\n    case LUA_VNUMINT:\n      e->k = VKINT; e->u.ival = ivalue(v);\n      break;\n    case LUA_VNUMFLT:\n      e->k = VKFLT; e->u.nval = fltvalue(v);\n      break;\n    case LUA_VFALSE:\n      e->k = VFALSE;\n      break;\n    case LUA_VTRUE:\n      e->k = VTRUE;\n      break;\n    case LUA_VNIL:\n      e->k = VNIL;\n      break;\n    case LUA_VSHRSTR:  case LUA_VLNGSTR:\n      e->k = VKSTR; e->u.strval = tsvalue(v);\n      break;\n    default: lua_assert(0);\n  }\n}\n\n\n/*\n** Fix an expression to return the number of results 'nresults'.\n** 'e' must be a multi-ret expression (function call or vararg).\n*/\nvoid luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {\n  Instruction *pc = &getinstruction(fs, e);\n  luaY_checklimit(fs, nresults + 1, MAXARG_C, \"multiple results\");\n  if (e->k == VCALL)  /* expression is an open function call? */\n    SETARG_C(*pc, nresults + 1);\n  else {\n    lua_assert(e->k == VVARARG);\n    SETARG_C(*pc, nresults + 1);\n    SETARG_A(*pc, fs->freereg);\n    luaK_reserveregs(fs, 1);\n  }\n}\n\n\n/*\n** Convert a VKSTR to a VK\n*/\nstatic int str2K (FuncState *fs, expdesc *e) {\n  lua_assert(e->k == VKSTR);\n  e->u.info = stringK(fs, e->u.strval);\n  e->k = VK;\n  return e->u.info;\n}\n\n\n/*\n** Fix an expression to return one result.\n** If expression is not a multi-ret expression (function call or\n** vararg), it already returns one result, so nothing needs to be done.\n** Function calls become VNONRELOC expressions (as its result comes\n** fixed in the base register of the call), while vararg expressions\n** become VRELOC (as OP_VARARG puts its results where it wants).\n** (Calls are created returning one result, so that does not need\n** to be fixed.)\n*/\nvoid luaK_setoneret (FuncState *fs, expdesc *e) {\n  if (e->k == VCALL) {  /* expression is an open function call? */\n    /* already returns 1 value */\n    lua_assert(GETARG_C(getinstruction(fs, e)) == 2);\n    e->k = VNONRELOC;  /* result has fixed position */\n    e->u.info = GETARG_A(getinstruction(fs, e));\n  }\n  else if (e->k == VVARARG) {\n    SETARG_C(getinstruction(fs, e), 2);\n    e->k = VRELOC;  /* can relocate its simple result */\n  }\n}\n\n/*\n** Change a vararg parameter into a regular local variable\n*/\nvoid luaK_vapar2local (FuncState *fs, expdesc *var) {\n  needvatab(fs->f);  /* function will need a vararg table */\n  /* now a vararg parameter is equivalent to a regular local variable */\n  var->k = VLOCAL;\n}\n\n\n/*\n** Ensure that expression 'e' is not a variable (nor a <const>).\n** (Expression still may have jump lists.)\n*/\nvoid luaK_dischargevars (FuncState *fs, expdesc *e) {\n  switch (e->k) {\n    case VCONST: {\n      const2exp(const2val(fs, e), e);\n      break;\n    }\n    case VVARGVAR: {\n      luaK_vapar2local(fs, e);  /* turn it into a local variable */\n    }  /* FALLTHROUGH */\n    case VLOCAL: {  /* already in a register */\n      int temp = e->u.var.ridx;\n      e->u.info = temp;  /* (can't do a direct assignment; values overlap) */\n      e->k = VNONRELOC;  /* becomes a non-relocatable value */\n      break;\n    }\n    case VUPVAL: {  /* move value to some (pending) register */\n      e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0);\n      e->k = VRELOC;\n      break;\n    }\n    case VINDEXUP: {\n      e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx);\n      e->k = VRELOC;\n      break;\n    }\n    case VINDEXI: {\n      freereg(fs, e->u.ind.t);\n      e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx);\n      e->k = VRELOC;\n      break;\n    }\n    case VINDEXSTR: {\n      freereg(fs, e->u.ind.t);\n      e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx);\n      e->k = VRELOC;\n      break;\n    }\n    case VINDEXED: {\n      freeregs(fs, e->u.ind.t, e->u.ind.idx);\n      e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx);\n      e->k = VRELOC;\n      break;\n    }\n    case VVARGIND: {\n      freeregs(fs, e->u.ind.t, e->u.ind.idx);\n      e->u.info = luaK_codeABC(fs, OP_GETVARG, 0, e->u.ind.t, e->u.ind.idx);\n      e->k = VRELOC;\n      break;\n    }\n    case VVARARG: case VCALL: {\n      luaK_setoneret(fs, e);\n      break;\n    }\n    default: break;  /* there is one value available (somewhere) */\n  }\n}\n\n\n/*\n** Ensure expression value is in register 'reg', making 'e' a\n** non-relocatable expression.\n** (Expression still may have jump lists.)\n*/\nstatic void discharge2reg (FuncState *fs, expdesc *e, int reg) {\n  luaK_dischargevars(fs, e);\n  switch (e->k) {\n    case VNIL: {\n      luaK_nil(fs, reg, 1);\n      break;\n    }\n    case VFALSE: {\n      luaK_codeABC(fs, OP_LOADFALSE, reg, 0, 0);\n      break;\n    }\n    case VTRUE: {\n      luaK_codeABC(fs, OP_LOADTRUE, reg, 0, 0);\n      break;\n    }\n    case VKSTR: {\n      str2K(fs, e);\n    }  /* FALLTHROUGH */\n    case VK: {\n      luaK_codek(fs, reg, e->u.info);\n      break;\n    }\n    case VKFLT: {\n      luaK_float(fs, reg, e->u.nval);\n      break;\n    }\n    case VKINT: {\n      luaK_int(fs, reg, e->u.ival);\n      break;\n    }\n    case VRELOC: {\n      Instruction *pc = &getinstruction(fs, e);\n      SETARG_A(*pc, reg);  /* instruction will put result in 'reg' */\n      break;\n    }\n    case VNONRELOC: {\n      if (reg != e->u.info)\n        luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0);\n      break;\n    }\n    default: {\n      lua_assert(e->k == VJMP);\n      return;  /* nothing to do... */\n    }\n  }\n  e->u.info = reg;\n  e->k = VNONRELOC;\n}\n\n\n/*\n** Ensure expression value is in a register, making 'e' a\n** non-relocatable expression.\n** (Expression still may have jump lists.)\n*/\nstatic void discharge2anyreg (FuncState *fs, expdesc *e) {\n  if (e->k != VNONRELOC) {  /* no fixed register yet? */\n    luaK_reserveregs(fs, 1);  /* get a register */\n    discharge2reg(fs, e, fs->freereg-1);  /* put value there */\n  }\n}\n\n\nstatic int code_loadbool (FuncState *fs, int A, OpCode op) {\n  luaK_getlabel(fs);  /* those instructions may be jump targets */\n  return luaK_codeABC(fs, op, A, 0, 0);\n}\n\n\n/*\n** check whether list has any jump that do not produce a value\n** or produce an inverted value\n*/\nstatic int need_value (FuncState *fs, int list) {\n  for (; list != NO_JUMP; list = getjump(fs, list)) {\n    Instruction i = *getjumpcontrol(fs, list);\n    if (GET_OPCODE(i) != OP_TESTSET) return 1;\n  }\n  return 0;  /* not found */\n}\n\n\n/*\n** Ensures final expression result (which includes results from its\n** jump lists) is in register 'reg'.\n** If expression has jumps, need to patch these jumps either to\n** its final position or to \"load\" instructions (for those tests\n** that do not produce values).\n*/\nstatic void exp2reg (FuncState *fs, expdesc *e, int reg) {\n  discharge2reg(fs, e, reg);\n  if (e->k == VJMP)  /* expression itself is a test? */\n    luaK_concat(fs, &e->t, e->u.info);  /* put this jump in 't' list */\n  if (hasjumps(e)) {\n    int final;  /* position after whole expression */\n    int p_f = NO_JUMP;  /* position of an eventual LOAD false */\n    int p_t = NO_JUMP;  /* position of an eventual LOAD true */\n    if (need_value(fs, e->t) || need_value(fs, e->f)) {\n      int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);\n      p_f = code_loadbool(fs, reg, OP_LFALSESKIP);  /* skip next inst. */\n      p_t = code_loadbool(fs, reg, OP_LOADTRUE);\n      /* jump around these booleans if 'e' is not a test */\n      luaK_patchtohere(fs, fj);\n    }\n    final = luaK_getlabel(fs);\n    patchlistaux(fs, e->f, final, reg, p_f);\n    patchlistaux(fs, e->t, final, reg, p_t);\n  }\n  e->f = e->t = NO_JUMP;\n  e->u.info = reg;\n  e->k = VNONRELOC;\n}\n\n\n/*\n** Ensures final expression result is in next available register.\n*/\nvoid luaK_exp2nextreg (FuncState *fs, expdesc *e) {\n  luaK_dischargevars(fs, e);\n  freeexp(fs, e);\n  luaK_reserveregs(fs, 1);\n  exp2reg(fs, e, fs->freereg - 1);\n}\n\n\n/*\n** Ensures final expression result is in some (any) register\n** and return that register.\n*/\nint luaK_exp2anyreg (FuncState *fs, expdesc *e) {\n  luaK_dischargevars(fs, e);\n  if (e->k == VNONRELOC) {  /* expression already has a register? */\n    if (!hasjumps(e))  /* no jumps? */\n      return e->u.info;  /* result is already in a register */\n    if (e->u.info >= luaY_nvarstack(fs)) {  /* reg. is not a local? */\n      exp2reg(fs, e, e->u.info);  /* put final result in it */\n      return e->u.info;\n    }\n    /* else expression has jumps and cannot change its register\n       to hold the jump values, because it is a local variable.\n       Go through to the default case. */\n  }\n  luaK_exp2nextreg(fs, e);  /* default: use next available register */\n  return e->u.info;\n}\n\n\n/*\n** Ensures final expression result is either in a register,\n** in an upvalue, or it is the vararg parameter.\n*/\nvoid luaK_exp2anyregup (FuncState *fs, expdesc *e) {\n  if ((e->k != VUPVAL && e->k != VVARGVAR) || hasjumps(e))\n    luaK_exp2anyreg(fs, e);\n}\n\n\n/*\n** Ensures final expression result is either in a register\n** or it is a constant.\n*/\nvoid luaK_exp2val (FuncState *fs, expdesc *e) {\n  if (e->k == VJMP || hasjumps(e))\n    luaK_exp2anyreg(fs, e);\n  else\n    luaK_dischargevars(fs, e);\n}\n\n\n/*\n** Try to make 'e' a K expression with an index in the range of R/K\n** indices. Return true iff succeeded.\n*/\nstatic int luaK_exp2K (FuncState *fs, expdesc *e) {\n  if (!hasjumps(e)) {\n    int info;\n    switch (e->k) {  /* move constants to 'k' */\n      case VTRUE: info = boolT(fs); break;\n      case VFALSE: info = boolF(fs); break;\n      case VNIL: info = nilK(fs); break;\n      case VKINT: info = luaK_intK(fs, e->u.ival); break;\n      case VKFLT: info = luaK_numberK(fs, e->u.nval); break;\n      case VKSTR: info = stringK(fs, e->u.strval); break;\n      case VK: info = e->u.info; break;\n      default: return 0;  /* not a constant */\n    }\n    if (info <= MAXINDEXRK) {  /* does constant fit in 'argC'? */\n      e->k = VK;  /* make expression a 'K' expression */\n      e->u.info = info;\n      return 1;\n    }\n  }\n  /* else, expression doesn't fit; leave it unchanged */\n  return 0;\n}\n\n\n/*\n** Ensures final expression result is in a valid R/K index\n** (that is, it is either in a register or in 'k' with an index\n** in the range of R/K indices).\n** Returns 1 iff expression is K.\n*/\nstatic int exp2RK (FuncState *fs, expdesc *e) {\n  if (luaK_exp2K(fs, e))\n    return 1;\n  else {  /* not a constant in the right range: put it in a register */\n    luaK_exp2anyreg(fs, e);\n    return 0;\n  }\n}\n\n\nstatic void codeABRK (FuncState *fs, OpCode o, int A, int B,\n                      expdesc *ec) {\n  int k = exp2RK(fs, ec);\n  luaK_codeABCk(fs, o, A, B, ec->u.info, k);\n}\n\n\n/*\n** Generate code to store result of expression 'ex' into variable 'var'.\n*/\nvoid luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {\n  switch (var->k) {\n    case VLOCAL: {\n      freeexp(fs, ex);\n      exp2reg(fs, ex, var->u.var.ridx);  /* compute 'ex' into proper place */\n      return;\n    }\n    case VUPVAL: {\n      int e = luaK_exp2anyreg(fs, ex);\n      luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0);\n      break;\n    }\n    case VINDEXUP: {\n      codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex);\n      break;\n    }\n    case VINDEXI: {\n      codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex);\n      break;\n    }\n    case VINDEXSTR: {\n      codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex);\n      break;\n    }\n    case VVARGIND: {\n      needvatab(fs->f);  /* function will need a vararg table */\n      /* now, assignment is to a regular table */\n    }  /* FALLTHROUGH */\n    case VINDEXED: {\n      codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex);\n      break;\n    }\n    default: lua_assert(0);  /* invalid var kind to store */\n  }\n  freeexp(fs, ex);\n}\n\n\n/*\n** Negate condition 'e' (where 'e' is a comparison).\n*/\nstatic void negatecondition (FuncState *fs, expdesc *e) {\n  Instruction *pc = getjumpcontrol(fs, e->u.info);\n  lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&\n                                           GET_OPCODE(*pc) != OP_TEST);\n  SETARG_k(*pc, (GETARG_k(*pc) ^ 1));\n}\n\n\n/*\n** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond'\n** is true, code will jump if 'e' is true.) Return jump position.\n** Optimize when 'e' is 'not' something, inverting the condition\n** and removing the 'not'.\n*/\nstatic int jumponcond (FuncState *fs, expdesc *e, int cond) {\n  if (e->k == VRELOC) {\n    Instruction ie = getinstruction(fs, e);\n    if (GET_OPCODE(ie) == OP_NOT) {\n      removelastinstruction(fs);  /* remove previous OP_NOT */\n      return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond);\n    }\n    /* else go through */\n  }\n  discharge2anyreg(fs, e);\n  freeexp(fs, e);\n  return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond);\n}\n\n\n/*\n** Emit code to go through if 'e' is true, jump otherwise.\n*/\nvoid luaK_goiftrue (FuncState *fs, expdesc *e) {\n  int pc;  /* pc of new jump */\n  luaK_dischargevars(fs, e);\n  switch (e->k) {\n    case VJMP: {  /* condition? */\n      negatecondition(fs, e);  /* jump when it is false */\n      pc = e->u.info;  /* save jump position */\n      break;\n    }\n    case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {\n      pc = NO_JUMP;  /* always true; do nothing */\n      break;\n    }\n    default: {\n      pc = jumponcond(fs, e, 0);  /* jump when false */\n      break;\n    }\n  }\n  luaK_concat(fs, &e->f, pc);  /* insert new jump in false list */\n  luaK_patchtohere(fs, e->t);  /* true list jumps to here (to go through) */\n  e->t = NO_JUMP;\n}\n\n\n/*\n** Emit code to go through if 'e' is false, jump otherwise.\n*/\nstatic void luaK_goiffalse (FuncState *fs, expdesc *e) {\n  int pc;  /* pc of new jump */\n  luaK_dischargevars(fs, e);\n  switch (e->k) {\n    case VJMP: {\n      pc = e->u.info;  /* already jump if true */\n      break;\n    }\n    case VNIL: case VFALSE: {\n      pc = NO_JUMP;  /* always false; do nothing */\n      break;\n    }\n    default: {\n      pc = jumponcond(fs, e, 1);  /* jump if true */\n      break;\n    }\n  }\n  luaK_concat(fs, &e->t, pc);  /* insert new jump in 't' list */\n  luaK_patchtohere(fs, e->f);  /* false list jumps to here (to go through) */\n  e->f = NO_JUMP;\n}\n\n\n/*\n** Code 'not e', doing constant folding.\n*/\nstatic void codenot (FuncState *fs, expdesc *e) {\n  switch (e->k) {\n    case VNIL: case VFALSE: {\n      e->k = VTRUE;  /* true == not nil == not false */\n      break;\n    }\n    case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {\n      e->k = VFALSE;  /* false == not \"x\" == not 0.5 == not 1 == not true */\n      break;\n    }\n    case VJMP: {\n      negatecondition(fs, e);\n      break;\n    }\n    case VRELOC:\n    case VNONRELOC: {\n      discharge2anyreg(fs, e);\n      freeexp(fs, e);\n      e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0);\n      e->k = VRELOC;\n      break;\n    }\n    default: lua_assert(0);  /* cannot happen */\n  }\n  /* interchange true and false lists */\n  { int temp = e->f; e->f = e->t; e->t = temp; }\n  removevalues(fs, e->f);  /* values are useless when negated */\n  removevalues(fs, e->t);\n}\n\n\n/*\n** Check whether expression 'e' is a short literal string\n*/\nstatic int isKstr (FuncState *fs, expdesc *e) {\n  return (e->k == VK && !hasjumps(e) && e->u.info <= MAXINDEXRK &&\n          ttisshrstring(&fs->f->k[e->u.info]));\n}\n\n/*\n** Check whether expression 'e' is a literal integer.\n*/\nstatic int isKint (expdesc *e) {\n  return (e->k == VKINT && !hasjumps(e));\n}\n\n\n/*\n** Check whether expression 'e' is a literal integer in\n** proper range to fit in register C\n*/\nstatic int isCint (expdesc *e) {\n  return isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C));\n}\n\n\n/*\n** Check whether expression 'e' is a literal integer in\n** proper range to fit in register sC\n*/\nstatic int isSCint (expdesc *e) {\n  return isKint(e) && fitsC(e->u.ival);\n}\n\n\n/*\n** Check whether expression 'e' is a literal integer or float in\n** proper range to fit in a register (sB or sC).\n*/\nstatic int isSCnumber (expdesc *e, int *pi, int *isfloat) {\n  lua_Integer i;\n  if (e->k == VKINT)\n    i = e->u.ival;\n  else if (e->k == VKFLT && luaV_flttointeger(e->u.nval, &i, F2Ieq))\n    *isfloat = 1;\n  else\n    return 0;  /* not a number */\n  if (!hasjumps(e) && fitsC(i)) {\n    *pi = int2sC(cast_int(i));\n    return 1;\n  }\n  else\n    return 0;\n}\n\n\n/*\n** Emit SELF instruction or equivalent: the code will convert\n** expression 'e' into 'e.key(e,'.\n*/\nvoid luaK_self (FuncState *fs, expdesc *e, expdesc *key) {\n  int ereg, base;\n  luaK_exp2anyreg(fs, e);\n  ereg = e->u.info;  /* register where 'e' (the receiver) was placed */\n  freeexp(fs, e);\n  base = e->u.info = fs->freereg;  /* base register for op_self */\n  e->k = VNONRELOC;  /* self expression has a fixed register */\n  luaK_reserveregs(fs, 2);  /* method and 'self' produced by op_self */\n  lua_assert(key->k == VKSTR);\n  /* is method name a short string in a valid K index? */\n  if (strisshr(key->u.strval) && luaK_exp2K(fs, key)) {\n    /* can use 'self' opcode */\n    luaK_codeABCk(fs, OP_SELF, base, ereg, key->u.info, 0);\n  }\n  else {  /* cannot use 'self' opcode; use move+gettable */\n    luaK_exp2anyreg(fs, key);  /* put method name in a register */\n    luaK_codeABC(fs, OP_MOVE, base + 1, ereg, 0);  /* copy self to base+1 */\n    luaK_codeABC(fs, OP_GETTABLE, base, ereg, key->u.info);  /* get method */\n  }\n  freeexp(fs, key);\n}\n\n\n/* auxiliary function to define indexing expressions */\nstatic void fillidxk (expdesc *t, int idx, expkind k) {\n  t->u.ind.idx = cast_byte(idx);\n  t->k = k;\n}\n\n\n/*\n** Create expression 't[k]'. 't' must have its final result already in a\n** register or upvalue. Upvalues can only be indexed by literal strings.\n** Keys can be literal strings in the constant table or arbitrary\n** values in registers.\n*/\nvoid luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {\n  int keystr = -1;\n  if (k->k == VKSTR)\n    keystr = str2K(fs, k);\n  lua_assert(!hasjumps(t) &&\n             (t->k == VLOCAL || t->k == VVARGVAR ||\n              t->k == VNONRELOC || t->k == VUPVAL));\n  if (t->k == VUPVAL && !isKstr(fs, k))  /* upvalue indexed by non 'Kstr'? */\n    luaK_exp2anyreg(fs, t);  /* put it in a register */\n  if (t->k == VUPVAL) {\n    lu_byte temp = cast_byte(t->u.info);  /* upvalue index */\n    t->u.ind.t = temp;  /* (can't do a direct assignment; values overlap) */\n    lua_assert(isKstr(fs, k));\n    fillidxk(t, k->u.info, VINDEXUP);  /* literal short string */\n  }\n  else if (t->k == VVARGVAR) {  /* indexing the vararg parameter? */\n    int kreg = luaK_exp2anyreg(fs, k);  /* put key in some register */\n    lu_byte vreg = cast_byte(t->u.var.ridx);  /* register with vararg param. */\n    lua_assert(vreg == fs->f->numparams);\n    t->u.ind.t = vreg;  /* (avoid a direct assignment; values may overlap) */\n    fillidxk(t, kreg, VVARGIND);  /* 't' represents 'vararg[k]' */\n  }\n  else {\n    /* register index of the table */\n    t->u.ind.t = cast_byte((t->k == VLOCAL) ? t->u.var.ridx: t->u.info);\n    if (isKstr(fs, k))\n      fillidxk(t, k->u.info, VINDEXSTR);  /* literal short string */\n    else if (isCint(k))  /* int. constant in proper range? */\n      fillidxk(t, cast_int(k->u.ival), VINDEXI);\n    else\n      fillidxk(t, luaK_exp2anyreg(fs, k), VINDEXED);  /* register */\n  }\n  t->u.ind.keystr = keystr;  /* string index in 'k' */\n  t->u.ind.ro = 0;  /* by default, not read-only */\n}\n\n\n/*\n** Return false if folding can raise an error.\n** Bitwise operations need operands convertible to integers; division\n** operations cannot have 0 as divisor.\n*/\nstatic int validop (int op, TValue *v1, TValue *v2) {\n  switch (op) {\n    case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:\n    case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: {  /* conversion errors */\n      lua_Integer i;\n      return (luaV_tointegerns(v1, &i, LUA_FLOORN2I) &&\n              luaV_tointegerns(v2, &i, LUA_FLOORN2I));\n    }\n    case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD:  /* division by 0 */\n      return (nvalue(v2) != 0);\n    default: return 1;  /* everything else is valid */\n  }\n}\n\n\n/*\n** Try to \"constant-fold\" an operation; return 1 iff successful.\n** (In this case, 'e1' has the final result.)\n*/\nstatic int constfolding (FuncState *fs, int op, expdesc *e1,\n                                        const expdesc *e2) {\n  TValue v1, v2, res;\n  if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))\n    return 0;  /* non-numeric operands or not safe to fold */\n  luaO_rawarith(fs->ls->L, op, &v1, &v2, &res);  /* does operation */\n  if (ttisinteger(&res)) {\n    e1->k = VKINT;\n    e1->u.ival = ivalue(&res);\n  }\n  else {  /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */\n    lua_Number n = fltvalue(&res);\n    if (luai_numisnan(n) || n == 0)\n      return 0;\n    e1->k = VKFLT;\n    e1->u.nval = n;\n  }\n  return 1;\n}\n\n\n/*\n** Convert a BinOpr to an OpCode  (ORDER OPR - ORDER OP)\n*/\nl_sinline OpCode binopr2op (BinOpr opr, BinOpr baser, OpCode base) {\n  lua_assert(baser <= opr &&\n            ((baser == OPR_ADD && opr <= OPR_SHR) ||\n             (baser == OPR_LT && opr <= OPR_LE)));\n  return cast(OpCode, (cast_int(opr) - cast_int(baser)) + cast_int(base));\n}\n\n\n/*\n** Convert a UnOpr to an OpCode  (ORDER OPR - ORDER OP)\n*/\nl_sinline OpCode unopr2op (UnOpr opr) {\n  return cast(OpCode, (cast_int(opr) - cast_int(OPR_MINUS)) +\n                                       cast_int(OP_UNM));\n}\n\n\n/*\n** Convert a BinOpr to a tag method  (ORDER OPR - ORDER TM)\n*/\nl_sinline TMS binopr2TM (BinOpr opr) {\n  lua_assert(OPR_ADD <= opr && opr <= OPR_SHR);\n  return cast(TMS, (cast_int(opr) - cast_int(OPR_ADD)) + cast_int(TM_ADD));\n}\n\n\n/*\n** Emit code for unary expressions that \"produce values\"\n** (everything but 'not').\n** Expression to produce final result will be encoded in 'e'.\n*/\nstatic void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) {\n  int r = luaK_exp2anyreg(fs, e);  /* opcodes operate only on registers */\n  freeexp(fs, e);\n  e->u.info = luaK_codeABC(fs, op, 0, r, 0);  /* generate opcode */\n  e->k = VRELOC;  /* all those operations are relocatable */\n  luaK_fixline(fs, line);\n}\n\n\n/*\n** Emit code for binary expressions that \"produce values\"\n** (everything but logical operators 'and'/'or' and comparison\n** operators).\n** Expression to produce final result will be encoded in 'e1'.\n*/\nstatic void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2,\n                             OpCode op, int v2, int flip, int line,\n                             OpCode mmop, TMS event) {\n  int v1 = luaK_exp2anyreg(fs, e1);\n  int pc = luaK_codeABCk(fs, op, 0, v1, v2, 0);\n  freeexps(fs, e1, e2);\n  e1->u.info = pc;\n  e1->k = VRELOC;  /* all those operations are relocatable */\n  luaK_fixline(fs, line);\n  luaK_codeABCk(fs, mmop, v1, v2, cast_int(event), flip);  /* metamethod */\n  luaK_fixline(fs, line);\n}\n\n\n/*\n** Emit code for binary expressions that \"produce values\" over\n** two registers.\n*/\nstatic void codebinexpval (FuncState *fs, BinOpr opr,\n                           expdesc *e1, expdesc *e2, int line) {\n  OpCode op = binopr2op(opr, OPR_ADD, OP_ADD);\n  int v2 = luaK_exp2anyreg(fs, e2);  /* make sure 'e2' is in a register */\n  /* 'e1' must be already in a register or it is a constant */\n  lua_assert((VNIL <= e1->k && e1->k <= VKSTR) ||\n             e1->k == VNONRELOC || e1->k == VRELOC);\n  lua_assert(OP_ADD <= op && op <= OP_SHR);\n  finishbinexpval(fs, e1, e2, op, v2, 0, line, OP_MMBIN, binopr2TM(opr));\n}\n\n\n/*\n** Code binary operators with immediate operands.\n*/\nstatic void codebini (FuncState *fs, OpCode op,\n                       expdesc *e1, expdesc *e2, int flip, int line,\n                       TMS event) {\n  int v2 = int2sC(cast_int(e2->u.ival));  /* immediate operand */\n  lua_assert(e2->k == VKINT);\n  finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINI, event);\n}\n\n\n/*\n** Code binary operators with K operand.\n*/\nstatic void codebinK (FuncState *fs, BinOpr opr,\n                      expdesc *e1, expdesc *e2, int flip, int line) {\n  TMS event = binopr2TM(opr);\n  int v2 = e2->u.info;  /* K index */\n  OpCode op = binopr2op(opr, OPR_ADD, OP_ADDK);\n  finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, event);\n}\n\n\n/* Try to code a binary operator negating its second operand.\n** For the metamethod, 2nd operand must keep its original value.\n*/\nstatic int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2,\n                             OpCode op, int line, TMS event) {\n  if (!isKint(e2))\n    return 0;  /* not an integer constant */\n  else {\n    lua_Integer i2 = e2->u.ival;\n    if (!(fitsC(i2) && fitsC(-i2)))\n      return 0;  /* not in the proper range */\n    else {  /* operating a small integer constant */\n      int v2 = cast_int(i2);\n      finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event);\n      /* correct metamethod argument */\n      SETARG_B(fs->f->code[fs->pc - 1], int2sC(v2));\n      return 1;  /* successfully coded */\n    }\n  }\n}\n\n\nstatic void swapexps (expdesc *e1, expdesc *e2) {\n  expdesc temp = *e1; *e1 = *e2; *e2 = temp;  /* swap 'e1' and 'e2' */\n}\n\n\n/*\n** Code binary operators with no constant operand.\n*/\nstatic void codebinNoK (FuncState *fs, BinOpr opr,\n                        expdesc *e1, expdesc *e2, int flip, int line) {\n  if (flip)\n    swapexps(e1, e2);  /* back to original order */\n  codebinexpval(fs, opr, e1, e2, line);  /* use standard operators */\n}\n\n\n/*\n** Code arithmetic operators ('+', '-', ...). If second operand is a\n** constant in the proper range, use variant opcodes with K operands.\n*/\nstatic void codearith (FuncState *fs, BinOpr opr,\n                       expdesc *e1, expdesc *e2, int flip, int line) {\n  if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2))  /* K operand? */\n    codebinK(fs, opr, e1, e2, flip, line);\n  else  /* 'e2' is neither an immediate nor a K operand */\n    codebinNoK(fs, opr, e1, e2, flip, line);\n}\n\n\n/*\n** Code commutative operators ('+', '*'). If first operand is a\n** numeric constant, change order of operands to try to use an\n** immediate or K operator.\n*/\nstatic void codecommutative (FuncState *fs, BinOpr op,\n                             expdesc *e1, expdesc *e2, int line) {\n  int flip = 0;\n  if (tonumeral(e1, NULL)) {  /* is first operand a numeric constant? */\n    swapexps(e1, e2);  /* change order */\n    flip = 1;\n  }\n  if (op == OPR_ADD && isSCint(e2))  /* immediate operand? */\n    codebini(fs, OP_ADDI, e1, e2, flip, line, TM_ADD);\n  else\n    codearith(fs, op, e1, e2, flip, line);\n}\n\n\n/*\n** Code bitwise operations; they are all commutative, so the function\n** tries to put an integer constant as the 2nd operand (a K operand).\n*/\nstatic void codebitwise (FuncState *fs, BinOpr opr,\n                         expdesc *e1, expdesc *e2, int line) {\n  int flip = 0;\n  if (e1->k == VKINT) {\n    swapexps(e1, e2);  /* 'e2' will be the constant operand */\n    flip = 1;\n  }\n  if (e2->k == VKINT && luaK_exp2K(fs, e2))  /* K operand? */\n    codebinK(fs, opr, e1, e2, flip, line);\n  else  /* no constants */\n    codebinNoK(fs, opr, e1, e2, flip, line);\n}\n\n\n/*\n** Emit code for order comparisons. When using an immediate operand,\n** 'isfloat' tells whether the original value was a float.\n*/\nstatic void codeorder (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {\n  int r1, r2;\n  int im;\n  int isfloat = 0;\n  OpCode op;\n  if (isSCnumber(e2, &im, &isfloat)) {\n    /* use immediate operand */\n    r1 = luaK_exp2anyreg(fs, e1);\n    r2 = im;\n    op = binopr2op(opr, OPR_LT, OP_LTI);\n  }\n  else if (isSCnumber(e1, &im, &isfloat)) {\n    /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */\n    r1 = luaK_exp2anyreg(fs, e2);\n    r2 = im;\n    op = binopr2op(opr, OPR_LT, OP_GTI);\n  }\n  else {  /* regular case, compare two registers */\n    r1 = luaK_exp2anyreg(fs, e1);\n    r2 = luaK_exp2anyreg(fs, e2);\n    op = binopr2op(opr, OPR_LT, OP_LT);\n  }\n  freeexps(fs, e1, e2);\n  e1->u.info = condjump(fs, op, r1, r2, isfloat, 1);\n  e1->k = VJMP;\n}\n\n\n/*\n** Emit code for equality comparisons ('==', '~=').\n** 'e1' was already put as RK by 'luaK_infix'.\n*/\nstatic void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {\n  int r1, r2;\n  int im;\n  int isfloat = 0;  /* not needed here, but kept for symmetry */\n  OpCode op;\n  if (e1->k != VNONRELOC) {\n    lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT);\n    swapexps(e1, e2);\n  }\n  r1 = luaK_exp2anyreg(fs, e1);  /* 1st expression must be in register */\n  if (isSCnumber(e2, &im, &isfloat)) {\n    op = OP_EQI;\n    r2 = im;  /* immediate operand */\n  }\n  else if (exp2RK(fs, e2)) {  /* 2nd expression is constant? */\n    op = OP_EQK;\n    r2 = e2->u.info;  /* constant index */\n  }\n  else {\n    op = OP_EQ;  /* will compare two registers */\n    r2 = luaK_exp2anyreg(fs, e2);\n  }\n  freeexps(fs, e1, e2);\n  e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ));\n  e1->k = VJMP;\n}\n\n\n/*\n** Apply prefix operation 'op' to expression 'e'.\n*/\nvoid luaK_prefix (FuncState *fs, UnOpr opr, expdesc *e, int line) {\n  static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP};\n  luaK_dischargevars(fs, e);\n  switch (opr) {\n    case OPR_MINUS: case OPR_BNOT:  /* use 'ef' as fake 2nd operand */\n      if (constfolding(fs, cast_int(opr + LUA_OPUNM), e, &ef))\n        break;\n      /* else */ /* FALLTHROUGH */\n    case OPR_LEN:\n      codeunexpval(fs, unopr2op(opr), e, line);\n      break;\n    case OPR_NOT: codenot(fs, e); break;\n    default: lua_assert(0);\n  }\n}\n\n\n/*\n** Process 1st operand 'v' of binary operation 'op' before reading\n** 2nd operand.\n*/\nvoid luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {\n  luaK_dischargevars(fs, v);\n  switch (op) {\n    case OPR_AND: {\n      luaK_goiftrue(fs, v);  /* go ahead only if 'v' is true */\n      break;\n    }\n    case OPR_OR: {\n      luaK_goiffalse(fs, v);  /* go ahead only if 'v' is false */\n      break;\n    }\n    case OPR_CONCAT: {\n      luaK_exp2nextreg(fs, v);  /* operand must be on the stack */\n      break;\n    }\n    case OPR_ADD: case OPR_SUB:\n    case OPR_MUL: case OPR_DIV: case OPR_IDIV:\n    case OPR_MOD: case OPR_POW:\n    case OPR_BAND: case OPR_BOR: case OPR_BXOR:\n    case OPR_SHL: case OPR_SHR: {\n      if (!tonumeral(v, NULL))\n        luaK_exp2anyreg(fs, v);\n      /* else keep numeral, which may be folded or used as an immediate\n         operand */\n      break;\n    }\n    case OPR_EQ: case OPR_NE: {\n      if (!tonumeral(v, NULL))\n        exp2RK(fs, v);\n      /* else keep numeral, which may be an immediate operand */\n      break;\n    }\n    case OPR_LT: case OPR_LE:\n    case OPR_GT: case OPR_GE: {\n      int dummy, dummy2;\n      if (!isSCnumber(v, &dummy, &dummy2))\n        luaK_exp2anyreg(fs, v);\n      /* else keep numeral, which may be an immediate operand */\n      break;\n    }\n    default: lua_assert(0);\n  }\n}\n\n/*\n** Create code for '(e1 .. e2)'.\n** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))',\n** because concatenation is right associative), merge both CONCATs.\n*/\nstatic void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) {\n  Instruction *ie2 = previousinstruction(fs);\n  if (GET_OPCODE(*ie2) == OP_CONCAT) {  /* is 'e2' a concatenation? */\n    int n = GETARG_B(*ie2);  /* # of elements concatenated in 'e2' */\n    lua_assert(e1->u.info + 1 == GETARG_A(*ie2));\n    freeexp(fs, e2);\n    SETARG_A(*ie2, e1->u.info);  /* correct first element ('e1') */\n    SETARG_B(*ie2, n + 1);  /* will concatenate one more element */\n  }\n  else {  /* 'e2' is not a concatenation */\n    luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0);  /* new concat opcode */\n    freeexp(fs, e2);\n    luaK_fixline(fs, line);\n  }\n}\n\n\n/*\n** Finalize code for binary operation, after reading 2nd operand.\n*/\nvoid luaK_posfix (FuncState *fs, BinOpr opr,\n                  expdesc *e1, expdesc *e2, int line) {\n  luaK_dischargevars(fs, e2);\n  if (foldbinop(opr) && constfolding(fs, cast_int(opr + LUA_OPADD), e1, e2))\n    return;  /* done by folding */\n  switch (opr) {\n    case OPR_AND: {\n      lua_assert(e1->t == NO_JUMP);  /* list closed by 'luaK_infix' */\n      luaK_concat(fs, &e2->f, e1->f);\n      *e1 = *e2;\n      break;\n    }\n    case OPR_OR: {\n      lua_assert(e1->f == NO_JUMP);  /* list closed by 'luaK_infix' */\n      luaK_concat(fs, &e2->t, e1->t);\n      *e1 = *e2;\n      break;\n    }\n    case OPR_CONCAT: {  /* e1 .. e2 */\n      luaK_exp2nextreg(fs, e2);\n      codeconcat(fs, e1, e2, line);\n      break;\n    }\n    case OPR_ADD: case OPR_MUL: {\n      codecommutative(fs, opr, e1, e2, line);\n      break;\n    }\n    case OPR_SUB: {\n      if (finishbinexpneg(fs, e1, e2, OP_ADDI, line, TM_SUB))\n        break; /* coded as (r1 + -I) */\n      /* ELSE */\n    }  /* FALLTHROUGH */\n    case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: {\n      codearith(fs, opr, e1, e2, 0, line);\n      break;\n    }\n    case OPR_BAND: case OPR_BOR: case OPR_BXOR: {\n      codebitwise(fs, opr, e1, e2, line);\n      break;\n    }\n    case OPR_SHL: {\n      if (isSCint(e1)) {\n        swapexps(e1, e2);\n        codebini(fs, OP_SHLI, e1, e2, 1, line, TM_SHL);  /* I << r2 */\n      }\n      else if (finishbinexpneg(fs, e1, e2, OP_SHRI, line, TM_SHL)) {\n        /* coded as (r1 >> -I) */;\n      }\n      else  /* regular case (two registers) */\n       codebinexpval(fs, opr, e1, e2, line);\n      break;\n    }\n    case OPR_SHR: {\n      if (isSCint(e2))\n        codebini(fs, OP_SHRI, e1, e2, 0, line, TM_SHR);  /* r1 >> I */\n      else  /* regular case (two registers) */\n        codebinexpval(fs, opr, e1, e2, line);\n      break;\n    }\n    case OPR_EQ: case OPR_NE: {\n      codeeq(fs, opr, e1, e2);\n      break;\n    }\n    case OPR_GT: case OPR_GE: {\n      /* '(a > b)' <=> '(b < a)';  '(a >= b)' <=> '(b <= a)' */\n      swapexps(e1, e2);\n      opr = cast(BinOpr, (opr - OPR_GT) + OPR_LT);\n    }  /* FALLTHROUGH */\n    case OPR_LT: case OPR_LE: {\n      codeorder(fs, opr, e1, e2);\n      break;\n    }\n    default: lua_assert(0);\n  }\n}\n\n\n/*\n** Change line information associated with current position, by removing\n** previous info and adding it again with new line.\n*/\nvoid luaK_fixline (FuncState *fs, int line) {\n  removelastlineinfo(fs);\n  savelineinfo(fs, fs->f, line);\n}\n\n\nvoid luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize) {\n  Instruction *inst = &fs->f->code[pc];\n  int extra = asize / (MAXARG_vC + 1);  /* higher bits of array size */\n  int rc = asize % (MAXARG_vC + 1);  /* lower bits of array size */\n  int k = (extra > 0);  /* true iff needs extra argument */\n  hsize = (hsize != 0) ? luaO_ceillog2(cast_uint(hsize)) + 1 : 0;\n  *inst = CREATE_vABCk(OP_NEWTABLE, ra, hsize, rc, k);\n  *(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra);\n}\n\n\n/*\n** Emit a SETLIST instruction.\n** 'base' is register that keeps table;\n** 'nelems' is #table plus those to be stored now;\n** 'tostore' is number of values (in registers 'base + 1',...) to add to\n** table (or LUA_MULTRET to add up to stack top).\n*/\nvoid luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {\n  lua_assert(tostore != 0);\n  if (tostore == LUA_MULTRET)\n    tostore = 0;\n  if (nelems <= MAXARG_vC)\n    luaK_codevABCk(fs, OP_SETLIST, base, tostore, nelems, 0);\n  else {\n    int extra = nelems / (MAXARG_vC + 1);\n    nelems %= (MAXARG_vC + 1);\n    luaK_codevABCk(fs, OP_SETLIST, base, tostore, nelems, 1);\n    codeextraarg(fs, extra);\n  }\n  fs->freereg = cast_byte(base + 1);  /* free registers with list values */\n}\n\n\n/*\n** return the final target of a jump (skipping jumps to jumps)\n*/\nstatic int finaltarget (Instruction *code, int i) {\n  int count;\n  for (count = 0; count < 100; count++) {  /* avoid infinite loops */\n    Instruction pc = code[i];\n    if (GET_OPCODE(pc) != OP_JMP)\n      break;\n    else\n      i += GETARG_sJ(pc) + 1;\n  }\n  return i;\n}\n\n\n/*\n** Do a final pass over the code of a function, doing small peephole\n** optimizations and adjustments.\n*/\n#include \"lopnames.h\"\nvoid luaK_finish (FuncState *fs) {\n  int i;\n  Proto *p = fs->f;\n  if (p->flag & PF_VATAB)  /* will it use a vararg table? */\n    p->flag &= cast_byte(~PF_VAHID);  /* then it will not use hidden args. */\n  for (i = 0; i < fs->pc; i++) {\n    Instruction *pc = &p->code[i];\n    /* avoid \"not used\" warnings when assert is off (for 'onelua.c') */\n    (void)luaP_isOT; (void)luaP_isIT;\n    lua_assert(i == 0 || luaP_isOT(*(pc - 1)) == luaP_isIT(*pc));\n    switch (GET_OPCODE(*pc)) {\n      case OP_RETURN0: case OP_RETURN1: {\n        if (!(fs->needclose || (p->flag & PF_VAHID)))\n          break;  /* no extra work */\n        /* else use OP_RETURN to do the extra work */\n        SET_OPCODE(*pc, OP_RETURN);\n      }  /* FALLTHROUGH */\n      case OP_RETURN: case OP_TAILCALL: {\n        if (fs->needclose)\n          SETARG_k(*pc, 1);  /* signal that it needs to close */\n        if (p->flag & PF_VAHID)  /* does it use hidden arguments? */\n          SETARG_C(*pc, p->numparams + 1);  /* signal that */\n        break;\n      }\n      case OP_GETVARG: {\n        if (p->flag & PF_VATAB)  /* function has a vararg table? */\n          SET_OPCODE(*pc, OP_GETTABLE);  /* must get vararg there */\n        break;\n      }\n      case OP_VARARG: {\n        if (p->flag & PF_VATAB)  /* function has a vararg table? */\n          SETARG_k(*pc, 1);  /* must get vararg there */\n        break;\n      }\n      case OP_JMP: {  /* to optimize jumps to jumps */\n        int target = finaltarget(p->code, i);\n        fixjump(fs, i, target);  /* jump directly to final target */\n        break;\n      }\n      default: break;\n    }\n  }\n}\n"
  },
  {
    "path": "3rd/lua/lcode.h",
    "content": "/*\n** $Id: lcode.h $\n** Code generator for Lua\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lcode_h\n#define lcode_h\n\n#include \"llex.h\"\n#include \"lobject.h\"\n#include \"lopcodes.h\"\n#include \"lparser.h\"\n\n\n/*\n** Marks the end of a patch list. It is an invalid value both as an absolute\n** address, and as a list link (would link an element to itself).\n*/\n#define NO_JUMP (-1)\n\n\n/*\n** grep \"ORDER OPR\" if you change these enums  (ORDER OP)\n*/\ntypedef enum BinOpr {\n  /* arithmetic operators */\n  OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW,\n  OPR_DIV, OPR_IDIV,\n  /* bitwise operators */\n  OPR_BAND, OPR_BOR, OPR_BXOR,\n  OPR_SHL, OPR_SHR,\n  /* string operator */\n  OPR_CONCAT,\n  /* comparison operators */\n  OPR_EQ, OPR_LT, OPR_LE,\n  OPR_NE, OPR_GT, OPR_GE,\n  /* logical operators */\n  OPR_AND, OPR_OR,\n  OPR_NOBINOPR\n} BinOpr;\n\n\n/* true if operation is foldable (that is, it is arithmetic or bitwise) */\n#define foldbinop(op)\t((op) <= OPR_SHR)\n\n\n#define luaK_codeABC(fs,o,a,b,c)\tluaK_codeABCk(fs,o,a,b,c,0)\n\n\ntypedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;\n\n\n/* get (pointer to) instruction of given 'expdesc' */\n#define getinstruction(fs,e)\t((fs)->f->code[(e)->u.info])\n\n\n#define luaK_setmultret(fs,e)\tluaK_setreturns(fs, e, LUA_MULTRET)\n\n#define luaK_jumpto(fs,t)\tluaK_patchlist(fs, luaK_jump(fs), t)\n\nLUAI_FUNC int luaK_code (FuncState *fs, Instruction i);\nLUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, int Bx);\nLUAI_FUNC int luaK_codeABCk (FuncState *fs, OpCode o, int A, int B, int C,\n                                            int k);\nLUAI_FUNC int luaK_codevABCk (FuncState *fs, OpCode o, int A, int B, int C,\n                                             int k);\nLUAI_FUNC int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v);\nLUAI_FUNC void luaK_fixline (FuncState *fs, int line);\nLUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);\nLUAI_FUNC void luaK_codecheckglobal (FuncState *fs, expdesc *var, int k,\n                                                    int line);\nLUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);\nLUAI_FUNC void luaK_checkstack (FuncState *fs, int n);\nLUAI_FUNC void luaK_int (FuncState *fs, int reg, lua_Integer n);\nLUAI_FUNC void luaK_vapar2local (FuncState *fs, expdesc *var);\nLUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);\nLUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e);\nLUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e);\nLUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e);\nLUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e);\nLUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key);\nLUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k);\nLUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e);\nLUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e);\nLUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults);\nLUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e);\nLUAI_FUNC int luaK_jump (FuncState *fs);\nLUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret);\nLUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target);\nLUAI_FUNC void luaK_patchtohere (FuncState *fs, int list);\nLUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);\nLUAI_FUNC int luaK_getlabel (FuncState *fs);\nLUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line);\nLUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v);\nLUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1,\n                            expdesc *v2, int line);\nLUAI_FUNC void luaK_settablesize (FuncState *fs, int pc,\n                                  int ra, int asize, int hsize);\nLUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore);\nLUAI_FUNC void luaK_finish (FuncState *fs);\nLUAI_FUNC l_noret luaK_semerror (LexState *ls, const char *fmt, ...);\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lcorolib.c",
    "content": "/*\n** $Id: lcorolib.c $\n** Coroutine Library\n** See Copyright Notice in lua.h\n*/\n\n#define lcorolib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <stdlib.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\nstatic lua_State *getco (lua_State *L) {\n  lua_State *co = lua_tothread(L, 1);\n  luaL_argexpected(L, co, 1, \"thread\");\n  return co;\n}\n\n\n/*\n** Resumes a coroutine. Returns the number of results for non-error\n** cases or -1 for errors.\n*/\nstatic int auxresume (lua_State *L, lua_State *co, int narg) {\n  int status, nres;\n  if (l_unlikely(!lua_checkstack(co, narg))) {\n    lua_pushliteral(L, \"too many arguments to resume\");\n    return -1;  /* error flag */\n  }\n  lua_xmove(L, co, narg);\n  status = lua_resume(co, L, narg, &nres);\n  if (l_likely(status == LUA_OK || status == LUA_YIELD)) {\n    if (l_unlikely(!lua_checkstack(L, nres + 1))) {\n      lua_pop(co, nres);  /* remove results anyway */\n      lua_pushliteral(L, \"too many results to resume\");\n      return -1;  /* error flag */\n    }\n    lua_xmove(co, L, nres);  /* move yielded values */\n    return nres;\n  }\n  else {\n    lua_xmove(co, L, 1);  /* move error message */\n    return -1;  /* error flag */\n  }\n}\n\n\nstatic int luaB_coresume (lua_State *L) {\n  lua_State *co = getco(L);\n  int r;\n  r = auxresume(L, co, lua_gettop(L) - 1);\n  if (l_unlikely(r < 0)) {\n    lua_pushboolean(L, 0);\n    lua_insert(L, -2);\n    return 2;  /* return false + error message */\n  }\n  else {\n    lua_pushboolean(L, 1);\n    lua_insert(L, -(r + 1));\n    return r + 1;  /* return true + 'resume' returns */\n  }\n}\n\n\nstatic int luaB_auxwrap (lua_State *L) {\n  lua_State *co = lua_tothread(L, lua_upvalueindex(1));\n  int r = auxresume(L, co, lua_gettop(L));\n  if (l_unlikely(r < 0)) {  /* error? */\n    int stat = lua_status(co);\n    if (stat != LUA_OK && stat != LUA_YIELD) {  /* error in the coroutine? */\n      stat = lua_closethread(co, L);  /* close its tbc variables */\n      lua_assert(stat != LUA_OK);\n      lua_xmove(co, L, 1);  /* move error message to the caller */\n    }\n    if (stat != LUA_ERRMEM &&  /* not a memory error and ... */\n        lua_type(L, -1) == LUA_TSTRING) {  /* ... error object is a string? */\n      luaL_where(L, 1);  /* add extra info, if available */\n      lua_insert(L, -2);\n      lua_concat(L, 2);\n    }\n    return lua_error(L);  /* propagate error */\n  }\n  return r;\n}\n\n\nstatic int luaB_cocreate (lua_State *L) {\n  lua_State *NL;\n  luaL_checktype(L, 1, LUA_TFUNCTION);\n  NL = lua_newthread(L);\n  lua_pushvalue(L, 1);  /* move function to top */\n  lua_xmove(L, NL, 1);  /* move function from L to NL */\n  return 1;\n}\n\n\nstatic int luaB_cowrap (lua_State *L) {\n  luaB_cocreate(L);\n  lua_pushcclosure(L, luaB_auxwrap, 1);\n  return 1;\n}\n\n\nstatic int luaB_yield (lua_State *L) {\n  return lua_yield(L, lua_gettop(L));\n}\n\n\n#define COS_RUN\t\t0\n#define COS_DEAD\t1\n#define COS_YIELD\t2\n#define COS_NORM\t3\n\n\nstatic const char *const statname[] =\n  {\"running\", \"dead\", \"suspended\", \"normal\"};\n\n\nstatic int auxstatus (lua_State *L, lua_State *co) {\n  if (L == co) return COS_RUN;\n  else {\n    switch (lua_status(co)) {\n      case LUA_YIELD:\n        return COS_YIELD;\n      case LUA_OK: {\n        lua_Debug ar;\n        if (lua_getstack(co, 0, &ar))  /* does it have frames? */\n          return COS_NORM;  /* it is running */\n        else if (lua_gettop(co) == 0)\n            return COS_DEAD;\n        else\n          return COS_YIELD;  /* initial state */\n      }\n      default:  /* some error occurred */\n        return COS_DEAD;\n    }\n  }\n}\n\n\nstatic int luaB_costatus (lua_State *L) {\n  lua_State *co = getco(L);\n  lua_pushstring(L, statname[auxstatus(L, co)]);\n  return 1;\n}\n\n\nstatic lua_State *getoptco (lua_State *L) {\n  return (lua_isnone(L, 1) ? L : getco(L));\n}\n\n\nstatic int luaB_yieldable (lua_State *L) {\n  lua_State *co = getoptco(L);\n  lua_pushboolean(L, lua_isyieldable(co));\n  return 1;\n}\n\n\nstatic int luaB_corunning (lua_State *L) {\n  int ismain = lua_pushthread(L);\n  lua_pushboolean(L, ismain);\n  return 2;\n}\n\n\nstatic int luaB_close (lua_State *L) {\n  lua_State *co = getoptco(L);\n  int status = auxstatus(L, co);\n  switch (status) {\n    case COS_DEAD: case COS_YIELD: {\n      status = lua_closethread(co, L);\n      if (status == LUA_OK) {\n        lua_pushboolean(L, 1);\n        return 1;\n      }\n      else {\n        lua_pushboolean(L, 0);\n        lua_xmove(co, L, 1);  /* move error message */\n        return 2;\n      }\n    }\n    case COS_NORM:\n      return luaL_error(L, \"cannot close a %s coroutine\", statname[status]);\n    case COS_RUN:\n      lua_geti(L, LUA_REGISTRYINDEX, LUA_RIDX_MAINTHREAD);  /* get main */\n      if (lua_tothread(L, -1) == co)\n        return luaL_error(L, \"cannot close main thread\");\n      lua_closethread(co, L);  /* close itself */\n      /* previous call does not return *//* FALLTHROUGH */\n    default:\n      lua_assert(0);\n      return 0;\n  }\n}\n\n\nstatic const luaL_Reg co_funcs[] = {\n  {\"create\", luaB_cocreate},\n  {\"resume\", luaB_coresume},\n  {\"running\", luaB_corunning},\n  {\"status\", luaB_costatus},\n  {\"wrap\", luaB_cowrap},\n  {\"yield\", luaB_yield},\n  {\"isyieldable\", luaB_yieldable},\n  {\"close\", luaB_close},\n  {NULL, NULL}\n};\n\n\n\nLUAMOD_API int luaopen_coroutine (lua_State *L) {\n  luaL_newlib(L, co_funcs);\n  return 1;\n}\n\n"
  },
  {
    "path": "3rd/lua/lctype.c",
    "content": "/*\n** $Id: lctype.c $\n** 'ctype' functions for Lua\n** See Copyright Notice in lua.h\n*/\n\n#define lctype_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include \"lctype.h\"\n\n#if !LUA_USE_CTYPE\t/* { */\n\n#include <limits.h>\n\n\n#if defined (LUA_UCID)\t\t/* accept UniCode IDentifiers? */\n/* consider all non-ASCII codepoints to be alphabetic */\n#define NONA\t\t0x01\n#else\n#define NONA\t\t0x00\t/* default */\n#endif\n\n\nLUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = {\n  0x00,  /* EOZ */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\t/* 0. */\n  0x00,  0x08,  0x08,  0x08,  0x08,  0x08,  0x00,  0x00,\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\t/* 1. */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\n  0x0c,  0x04,  0x04,  0x04,  0x04,  0x04,  0x04,  0x04,\t/* 2. */\n  0x04,  0x04,  0x04,  0x04,  0x04,  0x04,  0x04,  0x04,\n  0x16,  0x16,  0x16,  0x16,  0x16,  0x16,  0x16,  0x16,\t/* 3. */\n  0x16,  0x16,  0x04,  0x04,  0x04,  0x04,  0x04,  0x04,\n  0x04,  0x15,  0x15,  0x15,  0x15,  0x15,  0x15,  0x05,\t/* 4. */\n  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,\n  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,\t/* 5. */\n  0x05,  0x05,  0x05,  0x04,  0x04,  0x04,  0x04,  0x05,\n  0x04,  0x15,  0x15,  0x15,  0x15,  0x15,  0x15,  0x05,\t/* 6. */\n  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,\n  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,  0x05,\t/* 7. */\n  0x05,  0x05,  0x05,  0x04,  0x04,  0x04,  0x04,  0x00,\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\t/* 8. */\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\t/* 9. */\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\t/* a. */\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\t/* b. */\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\n  0x00,  0x00,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\t/* c. */\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\t/* d. */\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\t/* e. */\n  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,  NONA,\n  NONA,  NONA,  NONA,  NONA,  NONA,  0x00,  0x00,  0x00,\t/* f. */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00\n};\n\n#endif\t\t\t/* } */\n"
  },
  {
    "path": "3rd/lua/lctype.h",
    "content": "/*\n** $Id: lctype.h $\n** 'ctype' functions for Lua\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lctype_h\n#define lctype_h\n\n#include \"lua.h\"\n\n\n/*\n** WARNING: the functions defined here do not necessarily correspond\n** to the similar functions in the standard C ctype.h. They are\n** optimized for the specific needs of Lua.\n*/\n\n#if !defined(LUA_USE_CTYPE)\n\n#if 'A' == 65 && '0' == 48\n/* ASCII case: can use its own tables; faster and fixed */\n#define LUA_USE_CTYPE\t0\n#else\n/* must use standard C ctype */\n#define LUA_USE_CTYPE\t1\n#endif\n\n#endif\n\n\n#if !LUA_USE_CTYPE\t/* { */\n\n#include <limits.h>\n\n#include \"llimits.h\"\n\n\n#define ALPHABIT\t0\n#define DIGITBIT\t1\n#define PRINTBIT\t2\n#define SPACEBIT\t3\n#define XDIGITBIT\t4\n\n\n#define MASK(B)\t\t(1 << (B))\n\n\n/*\n** add 1 to char to allow index -1 (EOZ)\n*/\n#define testprop(c,p)\t(luai_ctype_[(c)+1] & (p))\n\n/*\n** 'lalpha' (Lua alphabetic) and 'lalnum' (Lua alphanumeric) both include '_'\n*/\n#define lislalpha(c)\ttestprop(c, MASK(ALPHABIT))\n#define lislalnum(c)\ttestprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT)))\n#define lisdigit(c)\ttestprop(c, MASK(DIGITBIT))\n#define lisspace(c)\ttestprop(c, MASK(SPACEBIT))\n#define lisprint(c)\ttestprop(c, MASK(PRINTBIT))\n#define lisxdigit(c)\ttestprop(c, MASK(XDIGITBIT))\n\n\n/*\n** In ASCII, this 'ltolower' is correct for alphabetic characters and\n** for '.'. That is enough for Lua needs. ('check_exp' ensures that\n** the character either is an upper-case letter or is unchanged by\n** the transformation, which holds for lower-case letters and '.'.)\n*/\n#define ltolower(c)  \\\n  check_exp(('A' <= (c) && (c) <= 'Z') || (c) == ((c) | ('A' ^ 'a')),  \\\n            (c) | ('A' ^ 'a'))\n\n\n/* one entry for each character and for -1 (EOZ) */\nLUAI_DDEC(const lu_byte luai_ctype_[UCHAR_MAX + 2];)\n\n\n#else\t\t\t/* }{ */\n\n/*\n** use standard C ctypes\n*/\n\n#include <ctype.h>\n\n\n#define lislalpha(c)\t(isalpha(c) || (c) == '_')\n#define lislalnum(c)\t(isalnum(c) || (c) == '_')\n#define lisdigit(c)\t(isdigit(c))\n#define lisspace(c)\t(isspace(c))\n#define lisprint(c)\t(isprint(c))\n#define lisxdigit(c)\t(isxdigit(c))\n\n#define ltolower(c)\t(tolower(c))\n\n#endif\t\t\t/* } */\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/ldblib.c",
    "content": "/*\n** $Id: ldblib.c $\n** Interface from Lua to its debug API\n** See Copyright Notice in lua.h\n*/\n\n#define ldblib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\n/*\n** The hook table at registry[HOOKKEY] maps threads to their current\n** hook function.\n*/\nstatic const char *const HOOKKEY = \"_HOOKKEY\";\n\n\n/*\n** If L1 != L, L1 can be in any state, and therefore there are no\n** guarantees about its stack space; any push in L1 must be\n** checked.\n*/\nstatic void checkstack (lua_State *L, lua_State *L1, int n) {\n  if (l_unlikely(L != L1 && !lua_checkstack(L1, n)))\n    luaL_error(L, \"stack overflow\");\n}\n\n\nstatic int db_getregistry (lua_State *L) {\n  lua_pushvalue(L, LUA_REGISTRYINDEX);\n  return 1;\n}\n\n\nstatic int db_getmetatable (lua_State *L) {\n  luaL_checkany(L, 1);\n  if (!lua_getmetatable(L, 1)) {\n    lua_pushnil(L);  /* no metatable */\n  }\n  return 1;\n}\n\n\nstatic int db_setmetatable (lua_State *L) {\n  int t = lua_type(L, 2);\n  luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, \"nil or table\");\n  lua_settop(L, 2);\n  lua_setmetatable(L, 1);\n  return 1;  /* return 1st argument */\n}\n\n\nstatic int db_getuservalue (lua_State *L) {\n  int n = (int)luaL_optinteger(L, 2, 1);\n  if (lua_type(L, 1) != LUA_TUSERDATA)\n    luaL_pushfail(L);\n  else if (lua_getiuservalue(L, 1, n) != LUA_TNONE) {\n    lua_pushboolean(L, 1);\n    return 2;\n  }\n  return 1;\n}\n\n\nstatic int db_setuservalue (lua_State *L) {\n  int n = (int)luaL_optinteger(L, 3, 1);\n  luaL_checktype(L, 1, LUA_TUSERDATA);\n  luaL_checkany(L, 2);\n  lua_settop(L, 2);\n  if (!lua_setiuservalue(L, 1, n))\n    luaL_pushfail(L);\n  return 1;\n}\n\n\n/*\n** Auxiliary function used by several library functions: check for\n** an optional thread as function's first argument and set 'arg' with\n** 1 if this argument is present (so that functions can skip it to\n** access their other arguments)\n*/\nstatic lua_State *getthread (lua_State *L, int *arg) {\n  if (lua_isthread(L, 1)) {\n    *arg = 1;\n    return lua_tothread(L, 1);\n  }\n  else {\n    *arg = 0;\n    return L;  /* function will operate over current thread */\n  }\n}\n\n\n/*\n** Variations of 'lua_settable', used by 'db_getinfo' to put results\n** from 'lua_getinfo' into result table. Key is always a string;\n** value can be a string, an int, or a boolean.\n*/\nstatic void settabss (lua_State *L, const char *k, const char *v) {\n  lua_pushstring(L, v);\n  lua_setfield(L, -2, k);\n}\n\nstatic void settabsi (lua_State *L, const char *k, int v) {\n  lua_pushinteger(L, v);\n  lua_setfield(L, -2, k);\n}\n\nstatic void settabsb (lua_State *L, const char *k, int v) {\n  lua_pushboolean(L, v);\n  lua_setfield(L, -2, k);\n}\n\n\n/*\n** In function 'db_getinfo', the call to 'lua_getinfo' may push\n** results on the stack; later it creates the result table to put\n** these objects. Function 'treatstackoption' puts the result from\n** 'lua_getinfo' on top of the result table so that it can call\n** 'lua_setfield'.\n*/\nstatic void treatstackoption (lua_State *L, lua_State *L1, const char *fname) {\n  if (L == L1)\n    lua_rotate(L, -2, 1);  /* exchange object and table */\n  else\n    lua_xmove(L1, L, 1);  /* move object to the \"main\" stack */\n  lua_setfield(L, -2, fname);  /* put object into table */\n}\n\n\n/*\n** Calls 'lua_getinfo' and collects all results in a new table.\n** L1 needs stack space for an optional input (function) plus\n** two optional outputs (function and line table) from function\n** 'lua_getinfo'.\n*/\nstatic int db_getinfo (lua_State *L) {\n  lua_Debug ar;\n  int arg;\n  lua_State *L1 = getthread(L, &arg);\n  const char *options = luaL_optstring(L, arg+2, \"flnSrtu\");\n  checkstack(L, L1, 3);\n  luaL_argcheck(L, options[0] != '>', arg + 2, \"invalid option '>'\");\n  if (lua_isfunction(L, arg + 1)) {  /* info about a function? */\n    options = lua_pushfstring(L, \">%s\", options);  /* add '>' to 'options' */\n    lua_pushvalue(L, arg + 1);  /* move function to 'L1' stack */\n    lua_xmove(L, L1, 1);\n  }\n  else {  /* stack level */\n    if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) {\n      luaL_pushfail(L);  /* level out of range */\n      return 1;\n    }\n  }\n  if (!lua_getinfo(L1, options, &ar))\n    return luaL_argerror(L, arg+2, \"invalid option\");\n  lua_newtable(L);  /* table to collect results */\n  if (strchr(options, 'S')) {\n    lua_pushlstring(L, ar.source, ar.srclen);\n    lua_setfield(L, -2, \"source\");\n    settabss(L, \"short_src\", ar.short_src);\n    settabsi(L, \"linedefined\", ar.linedefined);\n    settabsi(L, \"lastlinedefined\", ar.lastlinedefined);\n    settabss(L, \"what\", ar.what);\n  }\n  if (strchr(options, 'l'))\n    settabsi(L, \"currentline\", ar.currentline);\n  if (strchr(options, 'u')) {\n    settabsi(L, \"nups\", ar.nups);\n    settabsi(L, \"nparams\", ar.nparams);\n    settabsb(L, \"isvararg\", ar.isvararg);\n  }\n  if (strchr(options, 'n')) {\n    settabss(L, \"name\", ar.name);\n    settabss(L, \"namewhat\", ar.namewhat);\n  }\n  if (strchr(options, 'r')) {\n    settabsi(L, \"ftransfer\", ar.ftransfer);\n    settabsi(L, \"ntransfer\", ar.ntransfer);\n  }\n  if (strchr(options, 't')) {\n    settabsb(L, \"istailcall\", ar.istailcall);\n    settabsi(L, \"extraargs\", ar.extraargs);\n  }\n  if (strchr(options, 'L'))\n    treatstackoption(L, L1, \"activelines\");\n  if (strchr(options, 'f'))\n    treatstackoption(L, L1, \"func\");\n  return 1;  /* return table */\n}\n\n\nstatic int db_getlocal (lua_State *L) {\n  int arg;\n  lua_State *L1 = getthread(L, &arg);\n  int nvar = (int)luaL_checkinteger(L, arg + 2);  /* local-variable index */\n  if (lua_isfunction(L, arg + 1)) {  /* function argument? */\n    lua_pushvalue(L, arg + 1);  /* push function */\n    lua_pushstring(L, lua_getlocal(L, NULL, nvar));  /* push local name */\n    return 1;  /* return only name (there is no value) */\n  }\n  else {  /* stack-level argument */\n    lua_Debug ar;\n    const char *name;\n    int level = (int)luaL_checkinteger(L, arg + 1);\n    if (l_unlikely(!lua_getstack(L1, level, &ar)))  /* out of range? */\n      return luaL_argerror(L, arg+1, \"level out of range\");\n    checkstack(L, L1, 1);\n    name = lua_getlocal(L1, &ar, nvar);\n    if (name) {\n      lua_xmove(L1, L, 1);  /* move local value */\n      lua_pushstring(L, name);  /* push name */\n      lua_rotate(L, -2, 1);  /* re-order */\n      return 2;\n    }\n    else {\n      luaL_pushfail(L);  /* no name (nor value) */\n      return 1;\n    }\n  }\n}\n\n\nstatic int db_setlocal (lua_State *L) {\n  int arg;\n  const char *name;\n  lua_State *L1 = getthread(L, &arg);\n  lua_Debug ar;\n  int level = (int)luaL_checkinteger(L, arg + 1);\n  int nvar = (int)luaL_checkinteger(L, arg + 2);\n  if (l_unlikely(!lua_getstack(L1, level, &ar)))  /* out of range? */\n    return luaL_argerror(L, arg+1, \"level out of range\");\n  luaL_checkany(L, arg+3);\n  lua_settop(L, arg+3);\n  checkstack(L, L1, 1);\n  lua_xmove(L, L1, 1);\n  name = lua_setlocal(L1, &ar, nvar);\n  if (name == NULL)\n    lua_pop(L1, 1);  /* pop value (if not popped by 'lua_setlocal') */\n  lua_pushstring(L, name);\n  return 1;\n}\n\n\n/*\n** get (if 'get' is true) or set an upvalue from a closure\n*/\nstatic int auxupvalue (lua_State *L, int get) {\n  const char *name;\n  int n = (int)luaL_checkinteger(L, 2);  /* upvalue index */\n  luaL_checktype(L, 1, LUA_TFUNCTION);  /* closure */\n  name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);\n  if (name == NULL) return 0;\n  lua_pushstring(L, name);\n  lua_insert(L, -(get+1));  /* no-op if get is false */\n  return get + 1;\n}\n\n\nstatic int db_getupvalue (lua_State *L) {\n  return auxupvalue(L, 1);\n}\n\n\nstatic int db_setupvalue (lua_State *L) {\n  luaL_checkany(L, 3);\n  return auxupvalue(L, 0);\n}\n\n\n/*\n** Check whether a given upvalue from a given closure exists and\n** returns its index\n*/\nstatic void *checkupval (lua_State *L, int argf, int argnup, int *pnup) {\n  void *id;\n  int nup = (int)luaL_checkinteger(L, argnup);  /* upvalue index */\n  luaL_checktype(L, argf, LUA_TFUNCTION);  /* closure */\n  id = lua_upvalueid(L, argf, nup);\n  if (pnup) {\n    luaL_argcheck(L, id != NULL, argnup, \"invalid upvalue index\");\n    *pnup = nup;\n  }\n  return id;\n}\n\n\nstatic int db_upvalueid (lua_State *L) {\n  void *id = checkupval(L, 1, 2, NULL);\n  if (id != NULL)\n    lua_pushlightuserdata(L, id);\n  else\n    luaL_pushfail(L);\n  return 1;\n}\n\n\nstatic int db_upvaluejoin (lua_State *L) {\n  int n1, n2;\n  checkupval(L, 1, 2, &n1);\n  checkupval(L, 3, 4, &n2);\n  luaL_argcheck(L, !lua_iscfunction(L, 1), 1, \"Lua function expected\");\n  luaL_argcheck(L, !lua_iscfunction(L, 3), 3, \"Lua function expected\");\n  lua_upvaluejoin(L, 1, n1, 3, n2);\n  return 0;\n}\n\n\n/*\n** Call hook function registered at hook table for the current\n** thread (if there is one)\n*/\nstatic void hookf (lua_State *L, lua_Debug *ar) {\n  static const char *const hooknames[] =\n    {\"call\", \"return\", \"line\", \"count\", \"tail call\"};\n  lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY);\n  lua_pushthread(L);\n  if (lua_rawget(L, -2) == LUA_TFUNCTION) {  /* is there a hook function? */\n    lua_pushstring(L, hooknames[(int)ar->event]);  /* push event name */\n    if (ar->currentline >= 0)\n      lua_pushinteger(L, ar->currentline);  /* push current line */\n    else lua_pushnil(L);\n    lua_assert(lua_getinfo(L, \"lS\", ar));\n    lua_call(L, 2, 0);  /* call hook function */\n  }\n}\n\n\n/*\n** Convert a string mask (for 'sethook') into a bit mask\n*/\nstatic int makemask (const char *smask, int count) {\n  int mask = 0;\n  if (strchr(smask, 'c')) mask |= LUA_MASKCALL;\n  if (strchr(smask, 'r')) mask |= LUA_MASKRET;\n  if (strchr(smask, 'l')) mask |= LUA_MASKLINE;\n  if (count > 0) mask |= LUA_MASKCOUNT;\n  return mask;\n}\n\n\n/*\n** Convert a bit mask (for 'gethook') into a string mask\n*/\nstatic char *unmakemask (int mask, char *smask) {\n  int i = 0;\n  if (mask & LUA_MASKCALL) smask[i++] = 'c';\n  if (mask & LUA_MASKRET) smask[i++] = 'r';\n  if (mask & LUA_MASKLINE) smask[i++] = 'l';\n  smask[i] = '\\0';\n  return smask;\n}\n\n\nstatic int db_sethook (lua_State *L) {\n  int arg, mask, count;\n  lua_Hook func;\n  lua_State *L1 = getthread(L, &arg);\n  if (lua_isnoneornil(L, arg+1)) {  /* no hook? */\n    lua_settop(L, arg+1);\n    func = NULL; mask = 0; count = 0;  /* turn off hooks */\n  }\n  else {\n    const char *smask = luaL_checkstring(L, arg+2);\n    luaL_checktype(L, arg+1, LUA_TFUNCTION);\n    count = (int)luaL_optinteger(L, arg + 3, 0);\n    func = hookf; mask = makemask(smask, count);\n  }\n  if (!luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY)) {\n    /* table just created; initialize it */\n    lua_pushliteral(L, \"k\");\n    lua_setfield(L, -2, \"__mode\");  /** hooktable.__mode = \"k\" */\n    lua_pushvalue(L, -1);\n    lua_setmetatable(L, -2);  /* metatable(hooktable) = hooktable */\n  }\n  checkstack(L, L1, 1);\n  lua_pushthread(L1); lua_xmove(L1, L, 1);  /* key (thread) */\n  lua_pushvalue(L, arg + 1);  /* value (hook function) */\n  lua_rawset(L, -3);  /* hooktable[L1] = new Lua hook */\n  lua_sethook(L1, func, mask, count);\n  return 0;\n}\n\n\nstatic int db_gethook (lua_State *L) {\n  int arg;\n  lua_State *L1 = getthread(L, &arg);\n  char buff[5];\n  int mask = lua_gethookmask(L1);\n  lua_Hook hook = lua_gethook(L1);\n  if (hook == NULL) {  /* no hook? */\n    luaL_pushfail(L);\n    return 1;\n  }\n  else if (hook != hookf)  /* external hook? */\n    lua_pushliteral(L, \"external hook\");\n  else {  /* hook table must exist */\n    lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY);\n    checkstack(L, L1, 1);\n    lua_pushthread(L1); lua_xmove(L1, L, 1);\n    lua_rawget(L, -2);   /* 1st result = hooktable[L1] */\n    lua_remove(L, -2);  /* remove hook table */\n  }\n  lua_pushstring(L, unmakemask(mask, buff));  /* 2nd result = mask */\n  lua_pushinteger(L, lua_gethookcount(L1));  /* 3rd result = count */\n  return 3;\n}\n\n\nstatic int db_debug (lua_State *L) {\n  for (;;) {\n    char buffer[250];\n    lua_writestringerror(\"%s\", \"lua_debug> \");\n    if (fgets(buffer, sizeof(buffer), stdin) == NULL ||\n        strcmp(buffer, \"cont\\n\") == 0)\n      return 0;\n    if (luaL_loadbuffer(L, buffer, strlen(buffer), \"=(debug command)\") ||\n        lua_pcall(L, 0, 0, 0))\n      lua_writestringerror(\"%s\\n\", luaL_tolstring(L, -1, NULL));\n    lua_settop(L, 0);  /* remove eventual returns */\n  }\n}\n\n\nstatic int db_traceback (lua_State *L) {\n  int arg;\n  lua_State *L1 = getthread(L, &arg);\n  const char *msg = lua_tostring(L, arg + 1);\n  if (msg == NULL && !lua_isnoneornil(L, arg + 1))  /* non-string 'msg'? */\n    lua_pushvalue(L, arg + 1);  /* return it untouched */\n  else {\n    int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0);\n    luaL_traceback(L, L1, msg, level);\n  }\n  return 1;\n}\n\n\nstatic const luaL_Reg dblib[] = {\n  {\"debug\", db_debug},\n  {\"getuservalue\", db_getuservalue},\n  {\"gethook\", db_gethook},\n  {\"getinfo\", db_getinfo},\n  {\"getlocal\", db_getlocal},\n  {\"getregistry\", db_getregistry},\n  {\"getmetatable\", db_getmetatable},\n  {\"getupvalue\", db_getupvalue},\n  {\"upvaluejoin\", db_upvaluejoin},\n  {\"upvalueid\", db_upvalueid},\n  {\"setuservalue\", db_setuservalue},\n  {\"sethook\", db_sethook},\n  {\"setlocal\", db_setlocal},\n  {\"setmetatable\", db_setmetatable},\n  {\"setupvalue\", db_setupvalue},\n  {\"traceback\", db_traceback},\n  {NULL, NULL}\n};\n\n\nLUAMOD_API int luaopen_debug (lua_State *L) {\n  luaL_newlib(L, dblib);\n  return 1;\n}\n\n"
  },
  {
    "path": "3rd/lua/ldebug.c",
    "content": "/*\n** $Id: ldebug.c $\n** Debug Interface\n** See Copyright Notice in lua.h\n*/\n\n#define ldebug_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <stdarg.h>\n#include <stddef.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lapi.h\"\n#include \"lcode.h\"\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lfunc.h\"\n#include \"lobject.h\"\n#include \"lopcodes.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"ltm.h\"\n#include \"lvm.h\"\n\n\n\n#define LuaClosure(f)\t\t((f) != NULL && (f)->c.tt == LUA_VLCL)\n\nstatic const char strlocal[] = \"local\";\nstatic const char strupval[] = \"upvalue\";\n\nstatic const char *funcnamefromcall (lua_State *L, CallInfo *ci,\n                                                   const char **name);\n\n\nstatic int currentpc (CallInfo *ci) {\n  lua_assert(isLua(ci));\n  return pcRel(ci->u.l.savedpc, ci_func(ci)->p);\n}\n\n\n/*\n** Get a \"base line\" to find the line corresponding to an instruction.\n** Base lines are regularly placed at MAXIWTHABS intervals, so usually\n** an integer division gets the right place. When the source file has\n** large sequences of empty/comment lines, it may need extra entries,\n** so the original estimate needs a correction.\n** If the original estimate is -1, the initial 'if' ensures that the\n** 'while' will run at least once.\n** The assertion that the estimate is a lower bound for the correct base\n** is valid as long as the debug info has been generated with the same\n** value for MAXIWTHABS or smaller. (Previous releases use a little\n** smaller value.)\n*/\nstatic int getbaseline (const Proto *f, int pc, int *basepc) {\n  if (f->sizeabslineinfo == 0 || pc < f->abslineinfo[0].pc) {\n    *basepc = -1;  /* start from the beginning */\n    return f->linedefined;\n  }\n  else {\n    int i = pc / MAXIWTHABS - 1;  /* get an estimate */\n    /* estimate must be a lower bound of the correct base */\n    lua_assert(i < 0 ||\n              (i < f->sizeabslineinfo && f->abslineinfo[i].pc <= pc));\n    while (i + 1 < f->sizeabslineinfo && pc >= f->abslineinfo[i + 1].pc)\n      i++;  /* low estimate; adjust it */\n    *basepc = f->abslineinfo[i].pc;\n    return f->abslineinfo[i].line;\n  }\n}\n\n\n/*\n** Get the line corresponding to instruction 'pc' in function 'f';\n** first gets a base line and from there does the increments until\n** the desired instruction.\n*/\nint luaG_getfuncline (const Proto *f, int pc) {\n  if (f->lineinfo == NULL)  /* no debug information? */\n    return -1;\n  else {\n    int basepc;\n    int baseline = getbaseline(f, pc, &basepc);\n    while (basepc++ < pc) {  /* walk until given instruction */\n      lua_assert(f->lineinfo[basepc] != ABSLINEINFO);\n      baseline += f->lineinfo[basepc];  /* correct line */\n    }\n    return baseline;\n  }\n}\n\n\nstatic int getcurrentline (CallInfo *ci) {\n  return luaG_getfuncline(ci_func(ci)->p, currentpc(ci));\n}\n\n\n/*\n** Set 'trap' for all active Lua frames.\n** This function can be called during a signal, under \"reasonable\"\n** assumptions. A new 'ci' is completely linked in the list before it\n** becomes part of the \"active\" list, and we assume that pointers are\n** atomic; see comment in next function.\n** (A compiler doing interprocedural optimizations could, theoretically,\n** reorder memory writes in such a way that the list could be\n** temporarily broken while inserting a new element. We simply assume it\n** has no good reasons to do that.)\n*/\nstatic void settraps (CallInfo *ci) {\n  for (; ci != NULL; ci = ci->previous)\n    if (isLua(ci))\n      ci->u.l.trap = 1;\n}\n\n\n/*\n** This function can be called during a signal, under \"reasonable\"\n** assumptions.\n** Fields 'basehookcount' and 'hookcount' (set by 'resethookcount')\n** are for debug only, and it is no problem if they get arbitrary\n** values (causes at most one wrong hook call). 'hookmask' is an atomic\n** value. We assume that pointers are atomic too (e.g., gcc ensures that\n** for all platforms where it runs). Moreover, 'hook' is always checked\n** before being called (see 'luaD_hook').\n*/\nLUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {\n  if (func == NULL || mask == 0) {  /* turn off hooks? */\n    mask = 0;\n    func = NULL;\n  }\n  L->hook = func;\n  L->basehookcount = count;\n  resethookcount(L);\n  L->hookmask = cast_byte(mask);\n  if (mask)\n    settraps(L->ci);  /* to trace inside 'luaV_execute' */\n}\n\n\nLUA_API lua_Hook lua_gethook (lua_State *L) {\n  return L->hook;\n}\n\n\nLUA_API int lua_gethookmask (lua_State *L) {\n  return L->hookmask;\n}\n\n\nLUA_API int lua_gethookcount (lua_State *L) {\n  return L->basehookcount;\n}\n\n\nLUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {\n  int status;\n  CallInfo *ci;\n  if (level < 0) return 0;  /* invalid (negative) level */\n  lua_lock(L);\n  for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous)\n    level--;\n  if (level == 0 && ci != &L->base_ci) {  /* level found? */\n    status = 1;\n    ar->i_ci = ci;\n  }\n  else status = 0;  /* no such level */\n  lua_unlock(L);\n  return status;\n}\n\n\nstatic const char *upvalname (const Proto *p, int uv) {\n  TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name);\n  if (s == NULL) return \"?\";\n  else return getstr(s);\n}\n\n\nstatic const char *findvararg (CallInfo *ci, int n, StkId *pos) {\n  if (clLvalue(s2v(ci->func.p))->p->flag & PF_VAHID) {\n    int nextra = ci->u.l.nextraargs;\n    if (n >= -nextra) {  /* 'n' is negative */\n      *pos = ci->func.p - nextra - (n + 1);\n      return \"(vararg)\";  /* generic name for any vararg */\n    }\n  }\n  return NULL;  /* no such vararg */\n}\n\n\nconst char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) {\n  StkId base = ci->func.p + 1;\n  const char *name = NULL;\n  if (isLua(ci)) {\n    if (n < 0)  /* access to vararg values? */\n      return findvararg(ci, n, pos);\n    else\n      name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));\n  }\n  if (name == NULL) {  /* no 'standard' name? */\n    StkId limit = (ci == L->ci) ? L->top.p : ci->next->func.p;\n    if (limit - base >= n && n > 0) {  /* is 'n' inside 'ci' stack? */\n      /* generic name for any valid slot */\n      name = isLua(ci) ? \"(temporary)\" : \"(C temporary)\";\n    }\n    else\n      return NULL;  /* no name */\n  }\n  if (pos)\n    *pos = base + (n - 1);\n  return name;\n}\n\n\nLUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {\n  const char *name;\n  lua_lock(L);\n  if (ar == NULL) {  /* information about non-active function? */\n    if (!isLfunction(s2v(L->top.p - 1)))  /* not a Lua function? */\n      name = NULL;\n    else  /* consider live variables at function start (parameters) */\n      name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, n, 0);\n  }\n  else {  /* active function; get information through 'ar' */\n    StkId pos = NULL;  /* to avoid warnings */\n    name = luaG_findlocal(L, ar->i_ci, n, &pos);\n    if (name) {\n      setobjs2s(L, L->top.p, pos);\n      api_incr_top(L);\n    }\n  }\n  lua_unlock(L);\n  return name;\n}\n\n\nLUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {\n  StkId pos = NULL;  /* to avoid warnings */\n  const char *name;\n  lua_lock(L);\n  name = luaG_findlocal(L, ar->i_ci, n, &pos);\n  if (name) {\n    api_checkpop(L, 1);\n    setobjs2s(L, pos, L->top.p - 1);\n    L->top.p--;  /* pop value */\n  }\n  lua_unlock(L);\n  return name;\n}\n\n\nstatic void funcinfo (lua_Debug *ar, Closure *cl) {\n  if (!LuaClosure(cl)) {\n    ar->source = \"=[C]\";\n    ar->srclen = LL(\"=[C]\");\n    ar->linedefined = -1;\n    ar->lastlinedefined = -1;\n    ar->what = \"C\";\n  }\n  else {\n    const Proto *p = cl->l.p;\n    if (p->source) {\n      ar->source = getlstr(p->source, ar->srclen);\n    }\n    else {\n      ar->source = \"=?\";\n      ar->srclen = LL(\"=?\");\n    }\n    ar->linedefined = p->linedefined;\n    ar->lastlinedefined = p->lastlinedefined;\n    ar->what = (ar->linedefined == 0) ? \"main\" : \"Lua\";\n  }\n  luaO_chunkid(ar->short_src, ar->source, ar->srclen);\n}\n\n\nstatic int nextline (const Proto *p, int currentline, int pc) {\n  if (p->lineinfo[pc] != ABSLINEINFO)\n    return currentline + p->lineinfo[pc];\n  else\n    return luaG_getfuncline(p, pc);\n}\n\n\nstatic void collectvalidlines (lua_State *L, Closure *f) {\n  if (!LuaClosure(f)) {\n    setnilvalue(s2v(L->top.p));\n    api_incr_top(L);\n  }\n  else {\n    const Proto *p = f->l.p;\n    int currentline = p->linedefined;\n    Table *t = luaH_new(L);  /* new table to store active lines */\n    sethvalue2s(L, L->top.p, t);  /* push it on stack */\n    api_incr_top(L);\n    if (p->lineinfo != NULL) {  /* proto with debug information? */\n      int i;\n      TValue v;\n      setbtvalue(&v);  /* boolean 'true' to be the value of all indices */\n      if (!(isvararg(p)))  /* regular function? */\n        i = 0;  /* consider all instructions */\n      else {  /* vararg function */\n        lua_assert(GET_OPCODE(p->code[0]) == OP_VARARGPREP);\n        currentline = nextline(p, currentline, 0);\n        i = 1;  /* skip first instruction (OP_VARARGPREP) */\n      }\n      for (; i < p->sizelineinfo; i++) {  /* for each instruction */\n        currentline = nextline(p, currentline, i);  /* get its line */\n        luaH_setint(L, t, currentline, &v);  /* table[line] = true */\n      }\n    }\n  }\n}\n\n\nstatic const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {\n  /* calling function is a known function? */\n  if (ci != NULL && !(ci->callstatus & CIST_TAIL))\n    return funcnamefromcall(L, ci->previous, name);\n  else return NULL;  /* no way to find a name */\n}\n\n\nstatic int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,\n                       Closure *f, CallInfo *ci) {\n  int status = 1;\n  for (; *what; what++) {\n    switch (*what) {\n      case 'S': {\n        funcinfo(ar, f);\n        break;\n      }\n      case 'l': {\n        ar->currentline = (ci && isLua(ci)) ? getcurrentline(ci) : -1;\n        break;\n      }\n      case 'u': {\n        ar->nups = (f == NULL) ? 0 : f->c.nupvalues;\n        if (!LuaClosure(f)) {\n          ar->isvararg = 1;\n          ar->nparams = 0;\n        }\n        else {\n          ar->isvararg = (isvararg(f->l.p)) ? 1 : 0;\n          ar->nparams = f->l.p->numparams;\n        }\n        break;\n      }\n      case 't': {\n        if (ci != NULL) {\n          ar->istailcall = !!(ci->callstatus & CIST_TAIL);\n          ar->extraargs =\n                   cast_uchar((ci->callstatus & MAX_CCMT) >> CIST_CCMT);\n        }\n        else {\n          ar->istailcall = 0;\n          ar->extraargs = 0;\n        }\n        break;\n      }\n      case 'n': {\n        ar->namewhat = getfuncname(L, ci, &ar->name);\n        if (ar->namewhat == NULL) {\n          ar->namewhat = \"\";  /* not found */\n          ar->name = NULL;\n        }\n        break;\n      }\n      case 'r': {\n        if (ci == NULL || !(ci->callstatus & CIST_HOOKED))\n          ar->ftransfer = ar->ntransfer = 0;\n        else {\n          ar->ftransfer = L->transferinfo.ftransfer;\n          ar->ntransfer = L->transferinfo.ntransfer;\n        }\n        break;\n      }\n      case 'L':\n      case 'f':  /* handled by lua_getinfo */\n        break;\n      default: status = 0;  /* invalid option */\n    }\n  }\n  return status;\n}\n\n\nLUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {\n  int status;\n  Closure *cl;\n  CallInfo *ci;\n  TValue *func;\n  lua_lock(L);\n  if (*what == '>') {\n    ci = NULL;\n    func = s2v(L->top.p - 1);\n    api_check(L, ttisfunction(func), \"function expected\");\n    what++;  /* skip the '>' */\n    L->top.p--;  /* pop function */\n  }\n  else {\n    ci = ar->i_ci;\n    func = s2v(ci->func.p);\n    lua_assert(ttisfunction(func));\n  }\n  cl = ttisclosure(func) ? clvalue(func) : NULL;\n  status = auxgetinfo(L, what, ar, cl, ci);\n  if (strchr(what, 'f')) {\n    setobj2s(L, L->top.p, func);\n    api_incr_top(L);\n  }\n  if (strchr(what, 'L'))\n    collectvalidlines(L, cl);\n  lua_unlock(L);\n  return status;\n}\n\n\n/*\n** {======================================================\n** Symbolic Execution\n** =======================================================\n*/\n\n\nstatic int filterpc (int pc, int jmptarget) {\n  if (pc < jmptarget)  /* is code conditional (inside a jump)? */\n    return -1;  /* cannot know who sets that register */\n  else return pc;  /* current position sets that register */\n}\n\n\n/*\n** Try to find last instruction before 'lastpc' that modified register 'reg'.\n*/\nstatic int findsetreg (const Proto *p, int lastpc, int reg) {\n  int pc;\n  int setreg = -1;  /* keep last instruction that changed 'reg' */\n  int jmptarget = 0;  /* any code before this address is conditional */\n  if (testMMMode(GET_OPCODE(p->code[lastpc])))\n    lastpc--;  /* previous instruction was not actually executed */\n  for (pc = 0; pc < lastpc; pc++) {\n    Instruction i = p->code[pc];\n    OpCode op = GET_OPCODE(i);\n    int a = GETARG_A(i);\n    int change;  /* true if current instruction changed 'reg' */\n    switch (op) {\n      case OP_LOADNIL: {  /* set registers from 'a' to 'a+b' */\n        int b = GETARG_B(i);\n        change = (a <= reg && reg <= a + b);\n        break;\n      }\n      case OP_TFORCALL: {  /* affect all regs above its base */\n        change = (reg >= a + 2);\n        break;\n      }\n      case OP_CALL:\n      case OP_TAILCALL: {  /* affect all registers above base */\n        change = (reg >= a);\n        break;\n      }\n      case OP_JMP: {  /* doesn't change registers, but changes 'jmptarget' */\n        int b = GETARG_sJ(i);\n        int dest = pc + 1 + b;\n        /* jump does not skip 'lastpc' and is larger than current one? */\n        if (dest <= lastpc && dest > jmptarget)\n          jmptarget = dest;  /* update 'jmptarget' */\n        change = 0;\n        break;\n      }\n      default:  /* any instruction that sets A */\n        change = (testAMode(op) && reg == a);\n        break;\n    }\n    if (change)\n      setreg = filterpc(pc, jmptarget);\n  }\n  return setreg;\n}\n\n\n/*\n** Find a \"name\" for the constant 'c'.\n*/\nstatic const char *kname (const Proto *p, int index, const char **name) {\n  TValue *kvalue = &p->k[index];\n  if (ttisstring(kvalue)) {\n    *name = getstr(tsvalue(kvalue));\n    return \"constant\";\n  }\n  else {\n    *name = \"?\";\n    return NULL;\n  }\n}\n\n\nstatic const char *basicgetobjname (const Proto *p, int *ppc, int reg,\n                                    const char **name) {\n  int pc = *ppc;\n  *name = luaF_getlocalname(p, reg + 1, pc);\n  if (*name)  /* is a local? */\n    return strlocal;\n  /* else try symbolic execution */\n  *ppc = pc = findsetreg(p, pc, reg);\n  if (pc != -1) {  /* could find instruction? */\n    Instruction i = p->code[pc];\n    OpCode op = GET_OPCODE(i);\n    switch (op) {\n      case OP_MOVE: {\n        int b = GETARG_B(i);  /* move from 'b' to 'a' */\n        if (b < GETARG_A(i))\n          return basicgetobjname(p, ppc, b, name);  /* get name for 'b' */\n        break;\n      }\n      case OP_GETUPVAL: {\n        *name = upvalname(p, GETARG_B(i));\n        return strupval;\n      }\n      case OP_LOADK: return kname(p, GETARG_Bx(i), name);\n      case OP_LOADKX: return kname(p, GETARG_Ax(p->code[pc + 1]), name);\n      default: break;\n    }\n  }\n  return NULL;  /* could not find reasonable name */\n}\n\n\n/*\n** Find a \"name\" for the register 'c'.\n*/\nstatic void rname (const Proto *p, int pc, int c, const char **name) {\n  const char *what = basicgetobjname(p, &pc, c, name); /* search for 'c' */\n  if (!(what && *what == 'c'))  /* did not find a constant name? */\n    *name = \"?\";\n}\n\n\n/*\n** Check whether table being indexed by instruction 'i' is the\n** environment '_ENV'\n*/\nstatic const char *isEnv (const Proto *p, int pc, Instruction i, int isup) {\n  int t = GETARG_B(i);  /* table index */\n  const char *name;  /* name of indexed variable */\n  if (isup)  /* is 't' an upvalue? */\n    name = upvalname(p, t);\n  else {  /* 't' is a register */\n    const char *what = basicgetobjname(p, &pc, t, &name);\n    /* 'name' must be the name of a local variable (at the current\n       level or an upvalue) */\n    if (what != strlocal && what != strupval)\n      name = NULL;  /* cannot be the variable _ENV */\n  }\n  return (name && strcmp(name, LUA_ENV) == 0) ? \"global\" : \"field\";\n}\n\n\n/*\n** Extend 'basicgetobjname' to handle table accesses\n*/\nstatic const char *getobjname (const Proto *p, int lastpc, int reg,\n                               const char **name) {\n  const char *kind = basicgetobjname(p, &lastpc, reg, name);\n  if (kind != NULL)\n    return kind;\n  else if (lastpc != -1) {  /* could find instruction? */\n    Instruction i = p->code[lastpc];\n    OpCode op = GET_OPCODE(i);\n    switch (op) {\n      case OP_GETTABUP: {\n        int k = GETARG_C(i);  /* key index */\n        kname(p, k, name);\n        return isEnv(p, lastpc, i, 1);\n      }\n      case OP_GETTABLE: {\n        int k = GETARG_C(i);  /* key index */\n        rname(p, lastpc, k, name);\n        return isEnv(p, lastpc, i, 0);\n      }\n      case OP_GETI: {\n        *name = \"integer index\";\n        return \"field\";\n      }\n      case OP_GETFIELD: {\n        int k = GETARG_C(i);  /* key index */\n        kname(p, k, name);\n        return isEnv(p, lastpc, i, 0);\n      }\n      case OP_SELF: {\n        int k = GETARG_C(i);  /* key index */\n        kname(p, k, name);\n        return \"method\";\n      }\n      default: break;  /* go through to return NULL */\n    }\n  }\n  return NULL;  /* could not find reasonable name */\n}\n\n\n/*\n** Try to find a name for a function based on the code that called it.\n** (Only works when function was called by a Lua function.)\n** Returns what the name is (e.g., \"for iterator\", \"method\",\n** \"metamethod\") and sets '*name' to point to the name.\n*/\nstatic const char *funcnamefromcode (lua_State *L, const Proto *p,\n                                     int pc, const char **name) {\n  TMS tm = (TMS)0;  /* (initial value avoids warnings) */\n  Instruction i = p->code[pc];  /* calling instruction */\n  switch (GET_OPCODE(i)) {\n    case OP_CALL:\n    case OP_TAILCALL:\n      return getobjname(p, pc, GETARG_A(i), name);  /* get function name */\n    case OP_TFORCALL: {  /* for iterator */\n      *name = \"for iterator\";\n       return \"for iterator\";\n    }\n    /* other instructions can do calls through metamethods */\n    case OP_SELF: case OP_GETTABUP: case OP_GETTABLE:\n    case OP_GETI: case OP_GETFIELD:\n      tm = TM_INDEX;\n      break;\n    case OP_SETTABUP: case OP_SETTABLE: case OP_SETI: case OP_SETFIELD:\n      tm = TM_NEWINDEX;\n      break;\n    case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {\n      tm = cast(TMS, GETARG_C(i));\n      break;\n    }\n    case OP_UNM: tm = TM_UNM; break;\n    case OP_BNOT: tm = TM_BNOT; break;\n    case OP_LEN: tm = TM_LEN; break;\n    case OP_CONCAT: tm = TM_CONCAT; break;\n    case OP_EQ: tm = TM_EQ; break;\n    /* no cases for OP_EQI and OP_EQK, as they don't call metamethods */\n    case OP_LT: case OP_LTI: case OP_GTI: tm = TM_LT; break;\n    case OP_LE: case OP_LEI: case OP_GEI: tm = TM_LE; break;\n    case OP_CLOSE: case OP_RETURN: tm = TM_CLOSE; break;\n    default:\n      return NULL;  /* cannot find a reasonable name */\n  }\n  *name = getshrstr(G(L)->tmname[tm]) + 2;\n  return \"metamethod\";\n}\n\n\n/*\n** Try to find a name for a function based on how it was called.\n*/\nstatic const char *funcnamefromcall (lua_State *L, CallInfo *ci,\n                                                   const char **name) {\n  if (ci->callstatus & CIST_HOOKED) {  /* was it called inside a hook? */\n    *name = \"?\";\n    return \"hook\";\n  }\n  else if (ci->callstatus & CIST_FIN) {  /* was it called as a finalizer? */\n    *name = \"__gc\";\n    return \"metamethod\";  /* report it as such */\n  }\n  else if (isLua(ci))\n    return funcnamefromcode(L, ci_func(ci)->p, currentpc(ci), name);\n  else\n    return NULL;\n}\n\n/* }====================================================== */\n\n\n\n/*\n** Check whether pointer 'o' points to some value in the stack frame of\n** the current function and, if so, returns its index.  Because 'o' may\n** not point to a value in this stack, we cannot compare it with the\n** region boundaries (undefined behavior in ISO C).\n*/\nstatic int instack (CallInfo *ci, const TValue *o) {\n  int pos;\n  StkId base = ci->func.p + 1;\n  for (pos = 0; base + pos < ci->top.p; pos++) {\n    if (o == s2v(base + pos))\n      return pos;\n  }\n  return -1;  /* not found */\n}\n\n\n/*\n** Checks whether value 'o' came from an upvalue. (That can only happen\n** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on\n** upvalues.)\n*/\nstatic const char *getupvalname (CallInfo *ci, const TValue *o,\n                                 const char **name) {\n  LClosure *c = ci_func(ci);\n  int i;\n  for (i = 0; i < c->nupvalues; i++) {\n    if (c->upvals[i]->v.p == o) {\n      *name = upvalname(c->p, i);\n      return strupval;\n    }\n  }\n  return NULL;\n}\n\n\nstatic const char *formatvarinfo (lua_State *L, const char *kind,\n                                                const char *name) {\n  if (kind == NULL)\n    return \"\";  /* no information */\n  else\n    return luaO_pushfstring(L, \" (%s '%s')\", kind, name);\n}\n\n/*\n** Build a string with a \"description\" for the value 'o', such as\n** \"variable 'x'\" or \"upvalue 'y'\".\n*/\nstatic const char *varinfo (lua_State *L, const TValue *o) {\n  CallInfo *ci = L->ci;\n  const char *name = NULL;  /* to avoid warnings */\n  const char *kind = NULL;\n  if (isLua(ci)) {\n    kind = getupvalname(ci, o, &name);  /* check whether 'o' is an upvalue */\n    if (!kind) {  /* not an upvalue? */\n      int reg = instack(ci, o);  /* try a register */\n      if (reg >= 0)  /* is 'o' a register? */\n        kind = getobjname(ci_func(ci)->p, currentpc(ci), reg, &name);\n    }\n  }\n  return formatvarinfo(L, kind, name);\n}\n\n\n/*\n** Raise a type error\n*/\nstatic l_noret typeerror (lua_State *L, const TValue *o, const char *op,\n                          const char *extra) {\n  const char *t = luaT_objtypename(L, o);\n  luaG_runerror(L, \"attempt to %s a %s value%s\", op, t, extra);\n}\n\n\n/*\n** Raise a type error with \"standard\" information about the faulty\n** object 'o' (using 'varinfo').\n*/\nl_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {\n  typeerror(L, o, op, varinfo(L, o));\n}\n\n\n/*\n** Raise an error for calling a non-callable object. Try to find a name\n** for the object based on how it was called ('funcnamefromcall'); if it\n** cannot get a name there, try 'varinfo'.\n*/\nl_noret luaG_callerror (lua_State *L, const TValue *o) {\n  CallInfo *ci = L->ci;\n  const char *name = NULL;  /* to avoid warnings */\n  const char *kind = funcnamefromcall(L, ci, &name);\n  const char *extra = kind ? formatvarinfo(L, kind, name) : varinfo(L, o);\n  typeerror(L, o, \"call\", extra);\n}\n\n\nl_noret luaG_forerror (lua_State *L, const TValue *o, const char *what) {\n  luaG_runerror(L, \"bad 'for' %s (number expected, got %s)\",\n                   what, luaT_objtypename(L, o));\n}\n\n\nl_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) {\n  if (ttisstring(p1) || cvt2str(p1)) p1 = p2;\n  luaG_typeerror(L, p1, \"concatenate\");\n}\n\n\nl_noret luaG_opinterror (lua_State *L, const TValue *p1,\n                         const TValue *p2, const char *msg) {\n  if (!ttisnumber(p1))  /* first operand is wrong? */\n    p2 = p1;  /* now second is wrong */\n  luaG_typeerror(L, p2, msg);\n}\n\n\n/*\n** Error when both values are convertible to numbers, but not to integers\n*/\nl_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {\n  lua_Integer temp;\n  if (!luaV_tointegerns(p1, &temp, LUA_FLOORN2I))\n    p2 = p1;\n  luaG_runerror(L, \"number%s has no integer representation\", varinfo(L, p2));\n}\n\n\nl_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {\n  const char *t1 = luaT_objtypename(L, p1);\n  const char *t2 = luaT_objtypename(L, p2);\n  if (strcmp(t1, t2) == 0)\n    luaG_runerror(L, \"attempt to compare two %s values\", t1);\n  else\n    luaG_runerror(L, \"attempt to compare %s with %s\", t1, t2);\n}\n\n\nl_noret luaG_errnnil (lua_State *L, LClosure *cl, int k) {\n  const char *globalname = \"?\";  /* default name if k == 0 */\n  if (k > 0)\n    kname(cl->p, k - 1, &globalname);\n  luaG_runerror(L, \"global '%s' already defined\", globalname);\n}\n\n\n/* add src:line information to 'msg' */\nconst char *luaG_addinfo (lua_State *L, const char *msg, TString *src,\n                                        int line) {\n  if (src == NULL)  /* no debug information? */\n    return luaO_pushfstring(L, \"?:?: %s\", msg);\n  else {\n    char buff[LUA_IDSIZE];\n    size_t idlen;\n    const char *id = getlstr(src, idlen);\n    luaO_chunkid(buff, id, idlen);\n    return luaO_pushfstring(L, \"%s:%d: %s\", buff, line, msg);\n  }\n}\n\n\nl_noret luaG_errormsg (lua_State *L) {\n  if (L->errfunc != 0) {  /* is there an error handling function? */\n    StkId errfunc = restorestack(L, L->errfunc);\n    lua_assert(ttisfunction(s2v(errfunc)));\n    setobjs2s(L, L->top.p, L->top.p - 1);  /* move argument */\n    setobjs2s(L, L->top.p - 1, errfunc);  /* push function */\n    L->top.p++;  /* assume EXTRA_STACK */\n    luaD_callnoyield(L, L->top.p - 2, 1);  /* call it */\n  }\n  if (ttisnil(s2v(L->top.p - 1))) {  /* error object is nil? */\n    /* change it to a proper message */\n    setsvalue2s(L, L->top.p - 1, luaS_newliteral(L, \"<no error object>\"));\n  }\n  luaD_throw(L, LUA_ERRRUN);\n}\n\n\nl_noret luaG_runerror (lua_State *L, const char *fmt, ...) {\n  CallInfo *ci = L->ci;\n  const char *msg;\n  va_list argp;\n  luaC_checkGC(L);  /* error message uses memory */\n  pushvfstring(L, argp, fmt, msg);\n  if (isLua(ci)) {  /* Lua function? */\n    /* add source:line information */\n    luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));\n    setobjs2s(L, L->top.p - 2, L->top.p - 1);  /* remove 'msg' */\n    L->top.p--;\n  }\n  luaG_errormsg(L);\n}\n\n\n/*\n** Check whether new instruction 'newpc' is in a different line from\n** previous instruction 'oldpc'. More often than not, 'newpc' is only\n** one or a few instructions after 'oldpc' (it must be after, see\n** caller), so try to avoid calling 'luaG_getfuncline'. If they are\n** too far apart, there is a good chance of a ABSLINEINFO in the way,\n** so it goes directly to 'luaG_getfuncline'.\n*/\nstatic int changedline (const Proto *p, int oldpc, int newpc) {\n  if (p->lineinfo == NULL)  /* no debug information? */\n    return 0;\n  if (newpc - oldpc < MAXIWTHABS / 2) {  /* not too far apart? */\n    int delta = 0;  /* line difference */\n    int pc = oldpc;\n    for (;;) {\n      int lineinfo = p->lineinfo[++pc];\n      if (lineinfo == ABSLINEINFO)\n        break;  /* cannot compute delta; fall through */\n      delta += lineinfo;\n      if (pc == newpc)\n        return (delta != 0);  /* delta computed successfully */\n    }\n  }\n  /* either instructions are too far apart or there is an absolute line\n     info in the way; compute line difference explicitly */\n  return (luaG_getfuncline(p, oldpc) != luaG_getfuncline(p, newpc));\n}\n\n\n/*\n** Traces Lua calls. If code is running the first instruction of a function,\n** and function is not vararg, and it is not coming from an yield,\n** calls 'luaD_hookcall'. (Vararg functions will call 'luaD_hookcall'\n** after adjusting its variable arguments; otherwise, they could call\n** a line/count hook before the call hook. Functions coming from\n** an yield already called 'luaD_hookcall' before yielding.)\n*/\nint luaG_tracecall (lua_State *L) {\n  CallInfo *ci = L->ci;\n  Proto *p = ci_func(ci)->p;\n  ci->u.l.trap = 1;  /* ensure hooks will be checked */\n  if (ci->u.l.savedpc == p->code) {  /* first instruction (not resuming)? */\n    if (isvararg(p))\n      return 0;  /* hooks will start at VARARGPREP instruction */\n    else if (!(ci->callstatus & CIST_HOOKYIELD))  /* not yielded? */\n      luaD_hookcall(L, ci);  /* check 'call' hook */\n  }\n  return 1;  /* keep 'trap' on */\n}\n\n\n/*\n** Traces the execution of a Lua function. Called before the execution\n** of each opcode, when debug is on. 'L->oldpc' stores the last\n** instruction traced, to detect line changes. When entering a new\n** function, 'npci' will be zero and will test as a new line whatever\n** the value of 'oldpc'.  Some exceptional conditions may return to\n** a function without setting 'oldpc'. In that case, 'oldpc' may be\n** invalid; if so, use zero as a valid value. (A wrong but valid 'oldpc'\n** at most causes an extra call to a line hook.)\n** This function is not \"Protected\" when called, so it should correct\n** 'L->top.p' before calling anything that can run the GC.\n*/\nint luaG_traceexec (lua_State *L, const Instruction *pc) {\n  CallInfo *ci = L->ci;\n  lu_byte mask = cast_byte(L->hookmask);\n  const Proto *p = ci_func(ci)->p;\n  int counthook;\n  if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) {  /* no hooks? */\n    ci->u.l.trap = 0;  /* don't need to stop again */\n    return 0;  /* turn off 'trap' */\n  }\n  pc++;  /* reference is always next instruction */\n  ci->u.l.savedpc = pc;  /* save 'pc' */\n  counthook = (mask & LUA_MASKCOUNT) && (--L->hookcount == 0);\n  if (counthook)\n    resethookcount(L);  /* reset count */\n  else if (!(mask & LUA_MASKLINE))\n    return 1;  /* no line hook and count != 0; nothing to be done now */\n  if (ci->callstatus & CIST_HOOKYIELD) {  /* hook yielded last time? */\n    ci->callstatus &= ~CIST_HOOKYIELD;  /* erase mark */\n    return 1;  /* do not call hook again (VM yielded, so it did not move) */\n  }\n  if (!luaP_isIT(*(ci->u.l.savedpc - 1)))  /* top not being used? */\n    L->top.p = ci->top.p;  /* correct top */\n  if (counthook)\n    luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0);  /* call count hook */\n  if (mask & LUA_MASKLINE) {\n    /* 'L->oldpc' may be invalid; use zero in this case */\n    int oldpc = (L->oldpc < p->sizecode) ? L->oldpc : 0;\n    int npci = pcRel(pc, p);\n    if (npci <= oldpc ||  /* call hook when jump back (loop), */\n        changedline(p, oldpc, npci)) {  /* or when enter new line */\n      int newline = luaG_getfuncline(p, npci);\n      luaD_hook(L, LUA_HOOKLINE, newline, 0, 0);  /* call line hook */\n    }\n    L->oldpc = npci;  /* 'pc' of last call to line hook */\n  }\n  if (L->status == LUA_YIELD) {  /* did hook yield? */\n    if (counthook)\n      L->hookcount = 1;  /* undo decrement to zero */\n    ci->callstatus |= CIST_HOOKYIELD;  /* mark that it yielded */\n    luaD_throw(L, LUA_YIELD);\n  }\n  return 1;  /* keep 'trap' on */\n}\n\n"
  },
  {
    "path": "3rd/lua/ldebug.h",
    "content": "/*\n** $Id: ldebug.h $\n** Auxiliary functions from Debug Interface module\n** See Copyright Notice in lua.h\n*/\n\n#ifndef ldebug_h\n#define ldebug_h\n\n\n#include \"lstate.h\"\n\n\n#define pcRel(pc, p)\t(cast_int((pc) - (p)->code) - 1)\n\n\n/* Active Lua function (given call info) */\n#define ci_func(ci)\t\t(clLvalue(s2v((ci)->func.p)))\n\n\n#define resethookcount(L)\t(L->hookcount = L->basehookcount)\n\n/*\n** mark for entries in 'lineinfo' array that has absolute information in\n** 'abslineinfo' array\n*/\n#define ABSLINEINFO\t(-0x80)\n\n\n/*\n** MAXimum number of successive Instructions WiTHout ABSolute line\n** information. (A power of two allows fast divisions.)\n*/\n#if !defined(MAXIWTHABS)\n#define MAXIWTHABS\t128\n#endif\n\n\nLUAI_FUNC int luaG_getfuncline (const Proto *f, int pc);\nLUAI_FUNC const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n,\n                                                    StkId *pos);\nLUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o,\n                                                const char *opname);\nLUAI_FUNC l_noret luaG_callerror (lua_State *L, const TValue *o);\nLUAI_FUNC l_noret luaG_forerror (lua_State *L, const TValue *o,\n                                               const char *what);\nLUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1,\n                                                  const TValue *p2);\nLUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1,\n                                                 const TValue *p2,\n                                                 const char *msg);\nLUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1,\n                                                 const TValue *p2);\nLUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1,\n                                                 const TValue *p2);\nLUAI_FUNC l_noret luaG_errnnil (lua_State *L, LClosure *cl, int k);\nLUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...);\nLUAI_FUNC const char *luaG_addinfo (lua_State *L, const char *msg,\n                                                  TString *src, int line);\nLUAI_FUNC l_noret luaG_errormsg (lua_State *L);\nLUAI_FUNC int luaG_traceexec (lua_State *L, const Instruction *pc);\nLUAI_FUNC int luaG_tracecall (lua_State *L);\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua/ldo.c",
    "content": "/*\n** $Id: ldo.c $\n** Stack and Call structure of Lua\n** See Copyright Notice in lua.h\n*/\n\n#define ldo_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <setjmp.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lapi.h\"\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lfunc.h\"\n#include \"lgc.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lopcodes.h\"\n#include \"lparser.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"ltm.h\"\n#include \"lundump.h\"\n#include \"lvm.h\"\n#include \"lzio.h\"\n\n\n\n#define errorstatus(s)\t((s) > LUA_YIELD)\n\n\n/*\n** these macros allow user-specific actions when a thread is\n** resumed/yielded.\n*/\n#if !defined(luai_userstateresume)\n#define luai_userstateresume(L,n)\t((void)L)\n#endif\n\n#if !defined(luai_userstateyield)\n#define luai_userstateyield(L,n)\t((void)L)\n#endif\n\n\n/*\n** {======================================================\n** Error-recovery functions\n** =======================================================\n*/\n\n/* chained list of long jump buffers */\ntypedef struct lua_longjmp {\n  struct lua_longjmp *previous;\n  jmp_buf b;\n  volatile TStatus status;  /* error code */\n} lua_longjmp;\n\n\n/*\n** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By\n** default, Lua handles errors with exceptions when compiling as\n** C++ code, with _longjmp/_setjmp when available (POSIX), and with\n** longjmp/setjmp otherwise.\n*/\n#if !defined(LUAI_THROW)\t\t\t\t/* { */\n\n#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP)\t/* { */\n\n/* C++ exceptions */\n#define LUAI_THROW(L,c)\t\tthrow(c)\n\nstatic void LUAI_TRY (lua_State *L, lua_longjmp *c, Pfunc f, void *ud) {\n  try {\n    f(L, ud);  /* call function protected */\n  }\n  catch (lua_longjmp *c1) { /* Lua error */\n    if (c1 != c)  /* not the correct level? */\n      throw;  /* rethrow to upper level */\n  }\n  catch (...) {  /* non-Lua exception */\n    c->status = -1;  /* create some error code */\n  }\n}\n\n\n#elif defined(LUA_USE_POSIX)\t\t\t\t/* }{ */\n\n/* in POSIX, use _longjmp/_setjmp (more efficient) */\n#define LUAI_THROW(L,c)\t\t_longjmp((c)->b, 1)\n#define LUAI_TRY(L,c,f,ud)\tif (_setjmp((c)->b) == 0) ((f)(L, ud))\n\n#else\t\t\t\t\t\t\t/* }{ */\n\n/* ISO C handling with long jumps */\n#define LUAI_THROW(L,c)\t\tlongjmp((c)->b, 1)\n#define LUAI_TRY(L,c,f,ud)\tif (setjmp((c)->b) == 0) ((f)(L, ud))\n\n#endif\t\t\t\t\t\t\t/* } */\n\n#endif\t\t\t\t\t\t\t/* } */\n\n\nvoid luaD_seterrorobj (lua_State *L, TStatus errcode, StkId oldtop) {\n  if (errcode == LUA_ERRMEM) {  /* memory error? */\n    setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */\n  }\n  else {\n    lua_assert(errorstatus(errcode));  /* must be a real error */\n    lua_assert(!ttisnil(s2v(L->top.p - 1)));  /* with a non-nil object */\n    setobjs2s(L, oldtop, L->top.p - 1);  /* move it to 'oldtop' */\n  }\n  L->top.p = oldtop + 1;  /* top goes back to old top plus error object */\n}\n\n\nl_noret luaD_throw (lua_State *L, TStatus errcode) {\n  if (L->errorJmp) {  /* thread has an error handler? */\n    L->errorJmp->status = errcode;  /* set status */\n    LUAI_THROW(L, L->errorJmp);  /* jump to it */\n  }\n  else {  /* thread has no error handler */\n    global_State *g = G(L);\n    lua_State *mainth = mainthread(g);\n    errcode = luaE_resetthread(L, errcode);  /* close all upvalues */\n    L->status = errcode;\n    if (mainth->errorJmp) {  /* main thread has a handler? */\n      setobjs2s(L, mainth->top.p++, L->top.p - 1);  /* copy error obj. */\n      luaD_throw(mainth, errcode);  /* re-throw in main thread */\n    }\n    else {  /* no handler at all; abort */\n      if (g->panic) {  /* panic function? */\n        lua_unlock(L);\n        g->panic(L);  /* call panic function (last chance to jump out) */\n      }\n      abort();\n    }\n  }\n}\n\n\nl_noret luaD_throwbaselevel (lua_State *L, TStatus errcode) {\n  if (L->errorJmp) {\n    /* unroll error entries up to the first level */\n    while (L->errorJmp->previous != NULL)\n      L->errorJmp = L->errorJmp->previous;\n  }\n  luaD_throw(L, errcode);\n}\n\n\nTStatus luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {\n  l_uint32 oldnCcalls = L->nCcalls;\n  lua_longjmp lj;\n  lj.status = LUA_OK;\n  lj.previous = L->errorJmp;  /* chain new error handler */\n  L->errorJmp = &lj;\n  LUAI_TRY(L, &lj, f, ud);  /* call 'f' catching errors */\n  L->errorJmp = lj.previous;  /* restore old error handler */\n  L->nCcalls = oldnCcalls;\n  return lj.status;\n}\n\n/* }====================================================== */\n\n\n/*\n** {==================================================================\n** Stack reallocation\n** ===================================================================\n*/\n\n/* some stack space for error handling */\n#define STACKERRSPACE\t200\n\n\n/*\n** LUAI_MAXSTACK limits the size of the Lua stack.\n** It must fit into INT_MAX/2.\n*/\n\n#if !defined(LUAI_MAXSTACK)\n#if 1000000 < (INT_MAX / 2)\n#define LUAI_MAXSTACK           1000000\n#else\n#define LUAI_MAXSTACK           (INT_MAX / 2u)\n#endif\n#endif\n\n\n/* maximum stack size that respects size_t */\n#define MAXSTACK_BYSIZET  ((MAX_SIZET / sizeof(StackValue)) - STACKERRSPACE)\n\n/*\n** Minimum between LUAI_MAXSTACK and MAXSTACK_BYSIZET\n** (Maximum size for the stack must respect size_t.)\n*/\n#define MAXSTACK\tcast_int(LUAI_MAXSTACK < MAXSTACK_BYSIZET  \\\n\t\t\t        ? LUAI_MAXSTACK : MAXSTACK_BYSIZET)\n\n\n/* stack size with extra space for error handling */\n#define ERRORSTACKSIZE\t(MAXSTACK + STACKERRSPACE)\n\n\n/* raise a stack error while running the message handler */\nl_noret luaD_errerr (lua_State *L) {\n  TString *msg = luaS_newliteral(L, \"error in error handling\");\n  setsvalue2s(L, L->top.p, msg);\n  L->top.p++;  /* assume EXTRA_STACK */\n  luaD_throw(L, LUA_ERRERR);\n}\n\n\n/*\n** Check whether stack has enough space to run a simple function (such\n** as a finalizer): At least BASIC_STACK_SIZE in the Lua stack and\n** 2 slots in the C stack.\n*/\nint luaD_checkminstack (lua_State *L) {\n  return ((stacksize(L) < MAXSTACK - BASIC_STACK_SIZE) &&\n          (getCcalls(L) < LUAI_MAXCCALLS - 2));\n}\n\n\n/*\n** In ISO C, any pointer use after the pointer has been deallocated is\n** undefined behavior. So, before a stack reallocation, all pointers\n** should be changed to offsets, and after the reallocation they should\n** be changed back to pointers. As during the reallocation the pointers\n** are invalid, the reallocation cannot run emergency collections.\n** Alternatively, we can use the old address after the deallocation.\n** That is not strict ISO C, but seems to work fine everywhere.\n** The following macro chooses how strict is the code.\n*/\n#if !defined(LUAI_STRICT_ADDRESS)\n#define LUAI_STRICT_ADDRESS\t1\n#endif\n\n#if LUAI_STRICT_ADDRESS\n/*\n** Change all pointers to the stack into offsets.\n*/\nstatic void relstack (lua_State *L) {\n  CallInfo *ci;\n  UpVal *up;\n  L->top.offset = savestack(L, L->top.p);\n  L->tbclist.offset = savestack(L, L->tbclist.p);\n  for (up = L->openupval; up != NULL; up = up->u.open.next)\n    up->v.offset = savestack(L, uplevel(up));\n  for (ci = L->ci; ci != NULL; ci = ci->previous) {\n    ci->top.offset = savestack(L, ci->top.p);\n    ci->func.offset = savestack(L, ci->func.p);\n  }\n}\n\n\n/*\n** Change back all offsets into pointers.\n*/\nstatic void correctstack (lua_State *L, StkId oldstack) {\n  CallInfo *ci;\n  UpVal *up;\n  UNUSED(oldstack);\n  L->top.p = restorestack(L, L->top.offset);\n  L->tbclist.p = restorestack(L, L->tbclist.offset);\n  for (up = L->openupval; up != NULL; up = up->u.open.next)\n    up->v.p = s2v(restorestack(L, up->v.offset));\n  for (ci = L->ci; ci != NULL; ci = ci->previous) {\n    ci->top.p = restorestack(L, ci->top.offset);\n    ci->func.p = restorestack(L, ci->func.offset);\n    if (isLua(ci))\n      ci->u.l.trap = 1;  /* signal to update 'trap' in 'luaV_execute' */\n  }\n}\n\n#else\n/*\n** Assume that it is fine to use an address after its deallocation,\n** as long as we do not dereference it.\n*/\n\nstatic void relstack (lua_State *L) { UNUSED(L); }  /* do nothing */\n\n\n/*\n** Correct pointers into 'oldstack' to point into 'L->stack'.\n*/\nstatic void correctstack (lua_State *L, StkId oldstack) {\n  CallInfo *ci;\n  UpVal *up;\n  StkId newstack = L->stack.p;\n  if (oldstack == newstack)\n    return;\n  L->top.p = L->top.p - oldstack + newstack;\n  L->tbclist.p = L->tbclist.p - oldstack + newstack;\n  for (up = L->openupval; up != NULL; up = up->u.open.next)\n    up->v.p = s2v(uplevel(up) - oldstack + newstack);\n  for (ci = L->ci; ci != NULL; ci = ci->previous) {\n    ci->top.p = ci->top.p - oldstack + newstack;\n    ci->func.p = ci->func.p - oldstack + newstack;\n    if (isLua(ci))\n      ci->u.l.trap = 1;  /* signal to update 'trap' in 'luaV_execute' */\n  }\n}\n#endif\n\n\n/*\n** Reallocate the stack to a new size, correcting all pointers into it.\n** In case of allocation error, raise an error or return false according\n** to 'raiseerror'.\n*/\nint luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {\n  int oldsize = stacksize(L);\n  int i;\n  StkId newstack;\n  StkId oldstack = L->stack.p;\n  lu_byte oldgcstop = G(L)->gcstopem;\n  lua_assert(newsize <= MAXSTACK || newsize == ERRORSTACKSIZE);\n  relstack(L);  /* change pointers to offsets */\n  G(L)->gcstopem = 1;  /* stop emergency collection */\n  newstack = luaM_reallocvector(L, oldstack, oldsize + EXTRA_STACK,\n                                   newsize + EXTRA_STACK, StackValue);\n  G(L)->gcstopem = oldgcstop;  /* restore emergency collection */\n  if (l_unlikely(newstack == NULL)) {  /* reallocation failed? */\n    correctstack(L, oldstack);  /* change offsets back to pointers */\n    if (raiseerror)\n      luaM_error(L);\n    else return 0;  /* do not raise an error */\n  }\n  L->stack.p = newstack;\n  correctstack(L, oldstack);  /* change offsets back to pointers */\n  L->stack_last.p = L->stack.p + newsize;\n  for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++)\n    setnilvalue(s2v(newstack + i)); /* erase new segment */\n  return 1;\n}\n\n\n/*\n** Try to grow the stack by at least 'n' elements. When 'raiseerror'\n** is true, raises any error; otherwise, return 0 in case of errors.\n*/\nint luaD_growstack (lua_State *L, int n, int raiseerror) {\n  int size = stacksize(L);\n  if (l_unlikely(size > MAXSTACK)) {\n    /* if stack is larger than maximum, thread is already using the\n       extra space reserved for errors, that is, thread is handling\n       a stack error; cannot grow further than that. */\n    lua_assert(stacksize(L) == ERRORSTACKSIZE);\n    if (raiseerror)\n      luaD_errerr(L);  /* stack error inside message handler */\n    return 0;  /* if not 'raiseerror', just signal it */\n  }\n  else if (n < MAXSTACK) {  /* avoids arithmetic overflows */\n    int newsize = size + (size >> 1);  /* tentative new size (size * 1.5) */\n    int needed = cast_int(L->top.p - L->stack.p) + n;\n    if (newsize > MAXSTACK)  /* cannot cross the limit */\n      newsize = MAXSTACK;\n    if (newsize < needed)  /* but must respect what was asked for */\n      newsize = needed;\n    if (l_likely(newsize <= MAXSTACK))\n      return luaD_reallocstack(L, newsize, raiseerror);\n  }\n  /* else stack overflow */\n  /* add extra size to be able to handle the error message */\n  luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);\n  if (raiseerror)\n    luaG_runerror(L, \"stack overflow\");\n  return 0;\n}\n\n\n/*\n** Compute how much of the stack is being used, by computing the\n** maximum top of all call frames in the stack and the current top.\n*/\nstatic int stackinuse (lua_State *L) {\n  CallInfo *ci;\n  int res;\n  StkId lim = L->top.p;\n  for (ci = L->ci; ci != NULL; ci = ci->previous) {\n    if (lim < ci->top.p) lim = ci->top.p;\n  }\n  lua_assert(lim <= L->stack_last.p + EXTRA_STACK);\n  res = cast_int(lim - L->stack.p) + 1;  /* part of stack in use */\n  if (res < LUA_MINSTACK)\n    res = LUA_MINSTACK;  /* ensure a minimum size */\n  return res;\n}\n\n\n/*\n** If stack size is more than 3 times the current use, reduce that size\n** to twice the current use. (So, the final stack size is at most 2/3 the\n** previous size, and half of its entries are empty.)\n** As a particular case, if stack was handling a stack overflow and now\n** it is not, 'max' (limited by MAXSTACK) will be smaller than\n** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack\n** will be reduced to a \"regular\" size.\n*/\nvoid luaD_shrinkstack (lua_State *L) {\n  int inuse = stackinuse(L);\n  int max = (inuse > MAXSTACK / 3) ? MAXSTACK : inuse * 3;\n  /* if thread is currently not handling a stack overflow and its\n     size is larger than maximum \"reasonable\" size, shrink it */\n  if (inuse <= MAXSTACK && stacksize(L) > max) {\n    int nsize = (inuse > MAXSTACK / 2) ? MAXSTACK : inuse * 2;\n    luaD_reallocstack(L, nsize, 0);  /* ok if that fails */\n  }\n  else  /* don't change stack */\n    condmovestack(L,(void)0,(void)0);  /* (change only for debugging) */\n  luaE_shrinkCI(L);  /* shrink CI list */\n}\n\n\nvoid luaD_inctop (lua_State *L) {\n  L->top.p++;\n  luaD_checkstack(L, 1);\n}\n\n/* }================================================================== */\n\n\n/*\n** Call a hook for the given event. Make sure there is a hook to be\n** called. (Both 'L->hook' and 'L->hookmask', which trigger this\n** function, can be changed asynchronously by signals.)\n*/\nvoid luaD_hook (lua_State *L, int event, int line,\n                              int ftransfer, int ntransfer) {\n  lua_Hook hook = L->hook;\n  if (hook && L->allowhook) {  /* make sure there is a hook */\n    CallInfo *ci = L->ci;\n    ptrdiff_t top = savestack(L, L->top.p);  /* preserve original 'top' */\n    ptrdiff_t ci_top = savestack(L, ci->top.p);  /* idem for 'ci->top' */\n    lua_Debug ar;\n    ar.event = event;\n    ar.currentline = line;\n    ar.i_ci = ci;\n    L->transferinfo.ftransfer = ftransfer;\n    L->transferinfo.ntransfer = ntransfer;\n    if (isLua(ci) && L->top.p < ci->top.p)\n      L->top.p = ci->top.p;  /* protect entire activation register */\n    luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */\n    if (ci->top.p < L->top.p + LUA_MINSTACK)\n      ci->top.p = L->top.p + LUA_MINSTACK;\n    L->allowhook = 0;  /* cannot call hooks inside a hook */\n    ci->callstatus |= CIST_HOOKED;\n    lua_unlock(L);\n    (*hook)(L, &ar);\n    lua_lock(L);\n    lua_assert(!L->allowhook);\n    L->allowhook = 1;\n    ci->top.p = restorestack(L, ci_top);\n    L->top.p = restorestack(L, top);\n    ci->callstatus &= ~CIST_HOOKED;\n  }\n}\n\n\n/*\n** Executes a call hook for Lua functions. This function is called\n** whenever 'hookmask' is not zero, so it checks whether call hooks are\n** active.\n*/\nvoid luaD_hookcall (lua_State *L, CallInfo *ci) {\n  L->oldpc = 0;  /* set 'oldpc' for new function */\n  if (L->hookmask & LUA_MASKCALL) {  /* is call hook on? */\n    int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL\n                                             : LUA_HOOKCALL;\n    Proto *p = ci_func(ci)->p;\n    ci->u.l.savedpc++;  /* hooks assume 'pc' is already incremented */\n    luaD_hook(L, event, -1, 1, p->numparams);\n    ci->u.l.savedpc--;  /* correct 'pc' */\n  }\n}\n\n\n/*\n** Executes a return hook for Lua and C functions and sets/corrects\n** 'oldpc'. (Note that this correction is needed by the line hook, so it\n** is done even when return hooks are off.)\n*/\nstatic void rethook (lua_State *L, CallInfo *ci, int nres) {\n  if (L->hookmask & LUA_MASKRET) {  /* is return hook on? */\n    StkId firstres = L->top.p - nres;  /* index of first result */\n    int delta = 0;  /* correction for vararg functions */\n    int ftransfer;\n    if (isLua(ci)) {\n      Proto *p = ci_func(ci)->p;\n      if (p->flag & PF_VAHID)\n        delta = ci->u.l.nextraargs + p->numparams + 1;\n    }\n    ci->func.p += delta;  /* if vararg, back to virtual 'func' */\n    ftransfer = cast_int(firstres - ci->func.p);\n    luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres);  /* call it */\n    ci->func.p -= delta;\n  }\n  if (isLua(ci = ci->previous))\n    L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p);  /* set 'oldpc' */\n}\n\n\n/*\n** Check whether 'func' has a '__call' metafield. If so, put it in the\n** stack, below original 'func', so that 'luaD_precall' can call it.\n** Raise an error if there is no '__call' metafield.\n** Bits CIST_CCMT in status count how many _call metamethods were\n** invoked and how many corresponding extra arguments were pushed.\n** (This count will be saved in the 'callstatus' of the call).\n**  Raise an error if this counter overflows.\n*/\nstatic unsigned tryfuncTM (lua_State *L, StkId func, unsigned status) {\n  const TValue *tm;\n  StkId p;\n  tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);\n  if (l_unlikely(ttisnil(tm)))  /* no metamethod? */\n    luaG_callerror(L, s2v(func));\n  for (p = L->top.p; p > func; p--)  /* open space for metamethod */\n    setobjs2s(L, p, p-1);\n  L->top.p++;  /* stack space pre-allocated by the caller */\n  setobj2s(L, func, tm);  /* metamethod is the new function to be called */\n  if ((status & MAX_CCMT) == MAX_CCMT)  /* is counter full? */\n    luaG_runerror(L, \"'__call' chain too long\");\n  return status + (1u << CIST_CCMT);  /* increment counter */\n}\n\n\n/* Generic case for 'moveresult' */\nl_sinline void genmoveresults (lua_State *L, StkId res, int nres,\n                                             int wanted) {\n  StkId firstresult = L->top.p - nres;  /* index of first result */\n  int i;\n  if (nres > wanted)  /* extra results? */\n    nres = wanted;  /* don't need them */\n  for (i = 0; i < nres; i++)  /* move all results to correct place */\n    setobjs2s(L, res + i, firstresult + i);\n  for (; i < wanted; i++)  /* complete wanted number of results */\n    setnilvalue(s2v(res + i));\n  L->top.p = res + wanted;  /* top points after the last result */\n}\n\n\n/*\n** Given 'nres' results at 'firstResult', move 'fwanted-1' of them\n** to 'res'.  Handle most typical cases (zero results for commands,\n** one result for expressions, multiple results for tail calls/single\n** parameters) separated. The flag CIST_TBC in 'fwanted', if set,\n** forces the switch to go to the default case.\n*/\nl_sinline void moveresults (lua_State *L, StkId res, int nres,\n                                          l_uint32 fwanted) {\n  switch (fwanted) {  /* handle typical cases separately */\n    case 0 + 1:  /* no values needed */\n      L->top.p = res;\n      return;\n    case 1 + 1:  /* one value needed */\n      if (nres == 0)   /* no results? */\n        setnilvalue(s2v(res));  /* adjust with nil */\n      else  /* at least one result */\n        setobjs2s(L, res, L->top.p - nres);  /* move it to proper place */\n      L->top.p = res + 1;\n      return;\n    case LUA_MULTRET + 1:\n      genmoveresults(L, res, nres, nres);  /* we want all results */\n      break;\n    default: {  /* two/more results and/or to-be-closed variables */\n      int wanted = get_nresults(fwanted);\n      if (fwanted & CIST_TBC) {  /* to-be-closed variables? */\n        L->ci->u2.nres = nres;\n        L->ci->callstatus |= CIST_CLSRET;  /* in case of yields */\n        res = luaF_close(L, res, CLOSEKTOP, 1);\n        L->ci->callstatus &= ~CIST_CLSRET;\n        if (L->hookmask) {  /* if needed, call hook after '__close's */\n          ptrdiff_t savedres = savestack(L, res);\n          rethook(L, L->ci, nres);\n          res = restorestack(L, savedres);  /* hook can move stack */\n        }\n        if (wanted == LUA_MULTRET)\n          wanted = nres;  /* we want all results */\n      }\n      genmoveresults(L, res, nres, wanted);\n      break;\n    }\n  }\n}\n\n\n/*\n** Finishes a function call: calls hook if necessary, moves current\n** number of results to proper place, and returns to previous call\n** info. If function has to close variables, hook must be called after\n** that.\n*/\nvoid luaD_poscall (lua_State *L, CallInfo *ci, int nres) {\n  l_uint32 fwanted = ci->callstatus & (CIST_TBC | CIST_NRESULTS);\n  if (l_unlikely(L->hookmask) && !(fwanted & CIST_TBC))\n    rethook(L, ci, nres);\n  /* move results to proper place */\n  moveresults(L, ci->func.p, nres, fwanted);\n  /* function cannot be in any of these cases when returning */\n  lua_assert(!(ci->callstatus &\n        (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_CLSRET)));\n  L->ci = ci->previous;  /* back to caller (after closing variables) */\n}\n\n\n\n#define next_ci(L)  (L->ci->next ? L->ci->next : luaE_extendCI(L))\n\n\n/*\n** Allocate and initialize CallInfo structure. At this point, the\n** only valid fields in the call status are number of results,\n** CIST_C (if it's a C function), and number of extra arguments.\n** (All these bit-fields fit in 16-bit values.)\n*/\nl_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, unsigned status,\n                                                StkId top) {\n  CallInfo *ci = L->ci = next_ci(L);  /* new frame */\n  ci->func.p = func;\n  lua_assert((status & ~(CIST_NRESULTS | CIST_C | MAX_CCMT)) == 0);\n  ci->callstatus = status;\n  ci->top.p = top;\n  return ci;\n}\n\n\n/*\n** precall for C functions\n*/\nl_sinline int precallC (lua_State *L, StkId func, unsigned status,\n                                            lua_CFunction f) {\n  int n;  /* number of returns */\n  CallInfo *ci;\n  checkstackp(L, LUA_MINSTACK, func);  /* ensure minimum stack size */\n  L->ci = ci = prepCallInfo(L, func, status | CIST_C,\n                               L->top.p + LUA_MINSTACK);\n  lua_assert(ci->top.p <= L->stack_last.p);\n  if (l_unlikely(L->hookmask & LUA_MASKCALL)) {\n    int narg = cast_int(L->top.p - func) - 1;\n    luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);\n  }\n  lua_unlock(L);\n  n = (*f)(L);  /* do the actual call */\n  lua_lock(L);\n  api_checknelems(L, n);\n  luaD_poscall(L, ci, n);\n  return n;\n}\n\n\n/*\n** Prepare a function for a tail call, building its call info on top\n** of the current call info. 'narg1' is the number of arguments plus 1\n** (so that it includes the function itself). Return the number of\n** results, if it was a C function, or -1 for a Lua function.\n*/\nint luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,\n                                    int narg1, int delta) {\n  unsigned status = LUA_MULTRET + 1;\n retry:\n  switch (ttypetag(s2v(func))) {\n    case LUA_VCCL:  /* C closure */\n      return precallC(L, func, status, clCvalue(s2v(func))->f);\n    case LUA_VLCF:  /* light C function */\n      return precallC(L, func, status, fvalue(s2v(func)));\n    case LUA_VLCL: {  /* Lua function */\n      Proto *p = clLvalue(s2v(func))->p;\n      int fsize = p->maxstacksize;  /* frame size */\n      int nfixparams = p->numparams;\n      int i;\n      checkstackp(L, fsize - delta, func);\n      ci->func.p -= delta;  /* restore 'func' (if vararg) */\n      for (i = 0; i < narg1; i++)  /* move down function and arguments */\n        setobjs2s(L, ci->func.p + i, func + i);\n      func = ci->func.p;  /* moved-down function */\n      for (; narg1 <= nfixparams; narg1++)\n        setnilvalue(s2v(func + narg1));  /* complete missing arguments */\n      ci->top.p = func + 1 + fsize;  /* top for new function */\n      lua_assert(ci->top.p <= L->stack_last.p);\n      ci->u.l.savedpc = p->code;  /* starting point */\n      ci->callstatus |= CIST_TAIL;\n      L->top.p = func + narg1;  /* set top */\n      return -1;\n    }\n    default: {  /* not a function */\n      checkstackp(L, 1, func);  /* space for metamethod */\n      status = tryfuncTM(L, func, status);  /* try '__call' metamethod */\n      narg1++;\n      goto retry;  /* try again */\n    }\n  }\n}\n\n\n/*\n** Prepares the call to a function (C or Lua). For C functions, also do\n** the call. The function to be called is at '*func'.  The arguments\n** are on the stack, right after the function.  Returns the CallInfo\n** to be executed, if it was a Lua function. Otherwise (a C function)\n** returns NULL, with all the results on the stack, starting at the\n** original function position.\n*/\nCallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {\n  unsigned status = cast_uint(nresults + 1);\n  lua_assert(status <= MAXRESULTS + 1);\n retry:\n  switch (ttypetag(s2v(func))) {\n    case LUA_VCCL:  /* C closure */\n      precallC(L, func, status, clCvalue(s2v(func))->f);\n      return NULL;\n    case LUA_VLCF:  /* light C function */\n      precallC(L, func, status, fvalue(s2v(func)));\n      return NULL;\n    case LUA_VLCL: {  /* Lua function */\n      CallInfo *ci;\n      Proto *p = clLvalue(s2v(func))->p;\n      int narg = cast_int(L->top.p - func) - 1;  /* number of real arguments */\n      int nfixparams = p->numparams;\n      int fsize = p->maxstacksize;  /* frame size */\n      checkstackp(L, fsize, func);\n      L->ci = ci = prepCallInfo(L, func, status, func + 1 + fsize);\n      ci->u.l.savedpc = p->code;  /* starting point */\n      for (; narg < nfixparams; narg++)\n        setnilvalue(s2v(L->top.p++));  /* complete missing arguments */\n      lua_assert(ci->top.p <= L->stack_last.p);\n      return ci;\n    }\n    default: {  /* not a function */\n      checkstackp(L, 1, func);  /* space for metamethod */\n      status = tryfuncTM(L, func, status);  /* try '__call' metamethod */\n      goto retry;  /* try again with metamethod */\n    }\n  }\n}\n\n\n/*\n** Call a function (C or Lua) through C. 'inc' can be 1 (increment\n** number of recursive invocations in the C stack) or nyci (the same\n** plus increment number of non-yieldable calls).\n** This function can be called with some use of EXTRA_STACK, so it should\n** check the stack before doing anything else. 'luaD_precall' already\n** does that.\n*/\nl_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) {\n  CallInfo *ci;\n  L->nCcalls += inc;\n  if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) {\n    checkstackp(L, 0, func);  /* free any use of EXTRA_STACK */\n    luaE_checkcstack(L);\n  }\n  if ((ci = luaD_precall(L, func, nResults)) != NULL) {  /* Lua function? */\n    ci->callstatus |= CIST_FRESH;  /* mark that it is a \"fresh\" execute */\n    luaV_execute(L, ci);  /* call it */\n  }\n  L->nCcalls -= inc;\n}\n\n\n/*\n** External interface for 'ccall'\n*/\nvoid luaD_call (lua_State *L, StkId func, int nResults) {\n  ccall(L, func, nResults, 1);\n}\n\n\n/*\n** Similar to 'luaD_call', but does not allow yields during the call.\n*/\nvoid luaD_callnoyield (lua_State *L, StkId func, int nResults) {\n  ccall(L, func, nResults, nyci);\n}\n\n\n/*\n** Finish the job of 'lua_pcallk' after it was interrupted by an yield.\n** (The caller, 'finishCcall', does the final call to 'adjustresults'.)\n** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.\n** If a '__close' method yields here, eventually control will be back\n** to 'finishCcall' (when that '__close' method finally returns) and\n** 'finishpcallk' will run again and close any still pending '__close'\n** methods. Similarly, if a '__close' method errs, 'precover' calls\n** 'unroll' which calls ''finishCcall' and we are back here again, to\n** close any pending '__close' methods.\n** Note that, up to the call to 'luaF_close', the corresponding\n** 'CallInfo' is not modified, so that this repeated run works like the\n** first one (except that it has at least one less '__close' to do). In\n** particular, field CIST_RECST preserves the error status across these\n** multiple runs, changing only if there is a new error.\n*/\nstatic TStatus finishpcallk (lua_State *L,  CallInfo *ci) {\n  TStatus status = getcistrecst(ci);  /* get original status */\n  if (l_likely(status == LUA_OK))  /* no error? */\n    status = LUA_YIELD;  /* was interrupted by an yield */\n  else {  /* error */\n    StkId func = restorestack(L, ci->u2.funcidx);\n    L->allowhook = getoah(ci);  /* restore 'allowhook' */\n    func = luaF_close(L, func, status, 1);  /* can yield or raise an error */\n    luaD_seterrorobj(L, status, func);\n    luaD_shrinkstack(L);   /* restore stack size in case of overflow */\n    setcistrecst(ci, LUA_OK);  /* clear original status */\n  }\n  ci->callstatus &= ~CIST_YPCALL;\n  L->errfunc = ci->u.c.old_errfunc;\n  /* if it is here, there were errors or yields; unlike 'lua_pcallk',\n     do not change status */\n  return status;\n}\n\n\n/*\n** Completes the execution of a C function interrupted by an yield.\n** The interruption must have happened while the function was either\n** closing its tbc variables in 'moveresults' or executing\n** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes\n** 'luaD_poscall'. In the second case, the call to 'finishpcallk'\n** finishes the interrupted execution of 'lua_pcallk'.  After that, it\n** calls the continuation of the interrupted function and finally it\n** completes the job of the 'luaD_call' that called the function.  In\n** the call to 'adjustresults', we do not know the number of results\n** of the function called by 'lua_callk'/'lua_pcallk', so we are\n** conservative and use LUA_MULTRET (always adjust).\n*/\nstatic void finishCcall (lua_State *L, CallInfo *ci) {\n  int n;  /* actual number of results from C function */\n  if (ci->callstatus & CIST_CLSRET) {  /* was closing TBC variable? */\n    lua_assert(ci->callstatus & CIST_TBC);\n    n = ci->u2.nres;  /* just redo 'luaD_poscall' */\n    /* don't need to reset CIST_CLSRET, as it will be set again anyway */\n  }\n  else {\n    TStatus status = LUA_YIELD;  /* default if there were no errors */\n    lua_KFunction kf = ci->u.c.k;  /* continuation function */\n    /* must have a continuation and must be able to call it */\n    lua_assert(kf != NULL && yieldable(L));\n    if (ci->callstatus & CIST_YPCALL)   /* was inside a 'lua_pcallk'? */\n      status = finishpcallk(L, ci);  /* finish it */\n    adjustresults(L, LUA_MULTRET);  /* finish 'lua_callk' */\n    lua_unlock(L);\n    n = (*kf)(L, APIstatus(status), ci->u.c.ctx);  /* call continuation */\n    lua_lock(L);\n    api_checknelems(L, n);\n  }\n  luaD_poscall(L, ci, n);  /* finish 'luaD_call' */\n}\n\n\n/*\n** Executes \"full continuation\" (everything in the stack) of a\n** previously interrupted coroutine until the stack is empty (or another\n** interruption long-jumps out of the loop).\n*/\nstatic void unroll (lua_State *L, void *ud) {\n  CallInfo *ci;\n  UNUSED(ud);\n  while ((ci = L->ci) != &L->base_ci) {  /* something in the stack */\n    if (!isLua(ci))  /* C function? */\n      finishCcall(L, ci);  /* complete its execution */\n    else {  /* Lua function */\n      luaV_finishOp(L);  /* finish interrupted instruction */\n      luaV_execute(L, ci);  /* execute down to higher C 'boundary' */\n    }\n  }\n}\n\n\n/*\n** Try to find a suspended protected call (a \"recover point\") for the\n** given thread.\n*/\nstatic CallInfo *findpcall (lua_State *L) {\n  CallInfo *ci;\n  for (ci = L->ci; ci != NULL; ci = ci->previous) {  /* search for a pcall */\n    if (ci->callstatus & CIST_YPCALL)\n      return ci;\n  }\n  return NULL;  /* no pending pcall */\n}\n\n\n/*\n** Signal an error in the call to 'lua_resume', not in the execution\n** of the coroutine itself. (Such errors should not be handled by any\n** coroutine error handler and should not kill the coroutine.)\n*/\nstatic int resume_error (lua_State *L, const char *msg, int narg) {\n  api_checkpop(L, narg);\n  L->top.p -= narg;  /* remove args from the stack */\n  setsvalue2s(L, L->top.p, luaS_new(L, msg));  /* push error message */\n  api_incr_top(L);\n  lua_unlock(L);\n  return LUA_ERRRUN;\n}\n\n\n/*\n** Do the work for 'lua_resume' in protected mode. Most of the work\n** depends on the status of the coroutine: initial state, suspended\n** inside a hook, or regularly suspended (optionally with a continuation\n** function), plus erroneous cases: non-suspended coroutine or dead\n** coroutine.\n*/\nstatic void resume (lua_State *L, void *ud) {\n  int n = *(cast(int*, ud));  /* number of arguments */\n  StkId firstArg = L->top.p - n;  /* first argument */\n  CallInfo *ci = L->ci;\n  if (L->status == LUA_OK)  /* starting a coroutine? */\n    ccall(L, firstArg - 1, LUA_MULTRET, 0);  /* just call its body */\n  else {  /* resuming from previous yield */\n    lua_assert(L->status == LUA_YIELD);\n    L->status = LUA_OK;  /* mark that it is running (again) */\n    if (isLua(ci)) {  /* yielded inside a hook? */\n      /* undo increment made by 'luaG_traceexec': instruction was not\n         executed yet */\n      lua_assert(ci->callstatus & CIST_HOOKYIELD);\n      ci->u.l.savedpc--;\n      L->top.p = firstArg;  /* discard arguments */\n      luaV_execute(L, ci);  /* just continue running Lua code */\n    }\n    else {  /* 'common' yield */\n      if (ci->u.c.k != NULL) {  /* does it have a continuation function? */\n        lua_unlock(L);\n        n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */\n        lua_lock(L);\n        api_checknelems(L, n);\n      }\n      luaD_poscall(L, ci, n);  /* finish 'luaD_call' */\n    }\n    unroll(L, NULL);  /* run continuation */\n  }\n}\n\n\n/*\n** Unrolls a coroutine in protected mode while there are recoverable\n** errors, that is, errors inside a protected call. (Any error\n** interrupts 'unroll', and this loop protects it again so it can\n** continue.) Stops with a normal end (status == LUA_OK), an yield\n** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't\n** find a recover point).\n*/\nstatic TStatus precover (lua_State *L, TStatus status) {\n  CallInfo *ci;\n  while (errorstatus(status) && (ci = findpcall(L)) != NULL) {\n    L->ci = ci;  /* go down to recovery functions */\n    setcistrecst(ci, status);  /* status to finish 'pcall' */\n    status = luaD_rawrunprotected(L, unroll, NULL);\n  }\n  return status;\n}\n\n\nLUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,\n                                      int *nresults) {\n  TStatus status;\n  lua_lock(L);\n  if (L->status == LUA_OK) {  /* may be starting a coroutine */\n    if (L->ci != &L->base_ci)  /* not in base level? */\n      return resume_error(L, \"cannot resume non-suspended coroutine\", nargs);\n    else if (L->top.p - (L->ci->func.p + 1) == nargs)  /* no function? */\n      return resume_error(L, \"cannot resume dead coroutine\", nargs);\n  }\n  else if (L->status != LUA_YIELD)  /* ended with errors? */\n    return resume_error(L, \"cannot resume dead coroutine\", nargs);\n  L->nCcalls = (from) ? getCcalls(from) : 0;\n  if (getCcalls(L) >= LUAI_MAXCCALLS)\n    return resume_error(L, \"C stack overflow\", nargs);\n  L->nCcalls++;\n  luai_userstateresume(L, nargs);\n  api_checkpop(L, (L->status == LUA_OK) ? nargs + 1 : nargs);\n  status = luaD_rawrunprotected(L, resume, &nargs);\n   /* continue running after recoverable errors */\n  status = precover(L, status);\n  if (l_likely(!errorstatus(status)))\n    lua_assert(status == L->status);  /* normal end or yield */\n  else {  /* unrecoverable error */\n    L->status = status;  /* mark thread as 'dead' */\n    luaD_seterrorobj(L, status, L->top.p);  /* push error message */\n    L->ci->top.p = L->top.p;\n  }\n  *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield\n                                    : cast_int(L->top.p - (L->ci->func.p + 1));\n  lua_unlock(L);\n  return APIstatus(status);\n}\n\n\nLUA_API int lua_isyieldable (lua_State *L) {\n  return yieldable(L);\n}\n\n\nLUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,\n                        lua_KFunction k) {\n  CallInfo *ci;\n  luai_userstateyield(L, nresults);\n  lua_lock(L);\n  ci = L->ci;\n  api_checkpop(L, nresults);\n  if (l_unlikely(!yieldable(L))) {\n    if (L != mainthread(G(L)))\n      luaG_runerror(L, \"attempt to yield across a C-call boundary\");\n    else\n      luaG_runerror(L, \"attempt to yield from outside a coroutine\");\n  }\n  L->status = LUA_YIELD;\n  ci->u2.nyield = nresults;  /* save number of results */\n  if (isLua(ci)) {  /* inside a hook? */\n    lua_assert(!isLuacode(ci));\n    api_check(L, nresults == 0, \"hooks cannot yield values\");\n    api_check(L, k == NULL, \"hooks cannot continue after yielding\");\n  }\n  else {\n    if ((ci->u.c.k = k) != NULL)  /* is there a continuation? */\n      ci->u.c.ctx = ctx;  /* save context */\n    luaD_throw(L, LUA_YIELD);\n  }\n  lua_assert(ci->callstatus & CIST_HOOKED);  /* must be inside a hook */\n  lua_unlock(L);\n  return 0;  /* return to 'luaD_hook' */\n}\n\n\n/*\n** Auxiliary structure to call 'luaF_close' in protected mode.\n*/\nstruct CloseP {\n  StkId level;\n  TStatus status;\n};\n\n\n/*\n** Auxiliary function to call 'luaF_close' in protected mode.\n*/\nstatic void closepaux (lua_State *L, void *ud) {\n  struct CloseP *pcl = cast(struct CloseP *, ud);\n  luaF_close(L, pcl->level, pcl->status, 0);\n}\n\n\n/*\n** Calls 'luaF_close' in protected mode. Return the original status\n** or, in case of errors, the new status.\n*/\nTStatus luaD_closeprotected (lua_State *L, ptrdiff_t level, TStatus status) {\n  CallInfo *old_ci = L->ci;\n  lu_byte old_allowhooks = L->allowhook;\n  for (;;) {  /* keep closing upvalues until no more errors */\n    struct CloseP pcl;\n    pcl.level = restorestack(L, level); pcl.status = status;\n    status = luaD_rawrunprotected(L, &closepaux, &pcl);\n    if (l_likely(status == LUA_OK))  /* no more errors? */\n      return pcl.status;\n    else {  /* an error occurred; restore saved state and repeat */\n      L->ci = old_ci;\n      L->allowhook = old_allowhooks;\n    }\n  }\n}\n\n\n/*\n** Call the C function 'func' in protected mode, restoring basic\n** thread information ('allowhook', etc.) and in particular\n** its stack level in case of errors.\n*/\nTStatus luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t old_top,\n                                  ptrdiff_t ef) {\n  TStatus status;\n  CallInfo *old_ci = L->ci;\n  lu_byte old_allowhooks = L->allowhook;\n  ptrdiff_t old_errfunc = L->errfunc;\n  L->errfunc = ef;\n  status = luaD_rawrunprotected(L, func, u);\n  if (l_unlikely(status != LUA_OK)) {  /* an error occurred? */\n    L->ci = old_ci;\n    L->allowhook = old_allowhooks;\n    status = luaD_closeprotected(L, old_top, status);\n    luaD_seterrorobj(L, status, restorestack(L, old_top));\n    luaD_shrinkstack(L);   /* restore stack size in case of overflow */\n  }\n  L->errfunc = old_errfunc;\n  return status;\n}\n\n\n\n/*\n** Execute a protected parser.\n*/\nstruct SParser {  /* data to 'f_parser' */\n  ZIO *z;\n  Mbuffer buff;  /* dynamic structure used by the scanner */\n  Dyndata dyd;  /* dynamic structures used by the parser */\n  const char *mode;\n  const char *name;\n};\n\n\nstatic void checkmode (lua_State *L, const char *mode, const char *x) {\n  if (strchr(mode, x[0]) == NULL) {\n    luaO_pushfstring(L,\n       \"attempt to load a %s chunk (mode is '%s')\", x, mode);\n    luaD_throw(L, LUA_ERRSYNTAX);\n  }\n}\n\n\nstatic void f_parser (lua_State *L, void *ud) {\n  LClosure *cl;\n  struct SParser *p = cast(struct SParser *, ud);\n  const char *mode = p->mode ? p->mode : \"bt\";\n  int c = zgetc(p->z);  /* read first character */\n  if (c == LUA_SIGNATURE[0]) {\n    int fixed = 0;\n    if (strchr(mode, 'B') != NULL)\n      fixed = 1;\n    else\n      checkmode(L, mode, \"binary\");\n    cl = luaU_undump(L, p->z, p->name, fixed);\n  }\n  else {\n    checkmode(L, mode, \"text\");\n    cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);\n  }\n  lua_assert(cl->nupvalues == cl->p->sizeupvalues);\n  luaF_initupvals(L, cl);\n}\n\n\nTStatus luaD_protectedparser (lua_State *L, ZIO *z, const char *name,\n                                            const char *mode) {\n  struct SParser p;\n  TStatus status;\n  incnny(L);  /* cannot yield during parsing */\n  p.z = z; p.name = name; p.mode = mode;\n  p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;\n  p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;\n  p.dyd.label.arr = NULL; p.dyd.label.size = 0;\n  luaZ_initbuffer(L, &p.buff);\n  status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc);\n  luaZ_freebuffer(L, &p.buff);\n  luaM_freearray(L, p.dyd.actvar.arr, cast_sizet(p.dyd.actvar.size));\n  luaM_freearray(L, p.dyd.gt.arr, cast_sizet(p.dyd.gt.size));\n  luaM_freearray(L, p.dyd.label.arr, cast_sizet(p.dyd.label.size));\n  decnny(L);\n  return status;\n}\n\n\n"
  },
  {
    "path": "3rd/lua/ldo.h",
    "content": "/*\n** $Id: ldo.h $\n** Stack and Call structure of Lua\n** See Copyright Notice in lua.h\n*/\n\n#ifndef ldo_h\n#define ldo_h\n\n\n#include \"llimits.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n#include \"lzio.h\"\n\n\n/*\n** Macro to check stack size and grow stack if needed.  Parameters\n** 'pre'/'pos' allow the macro to preserve a pointer into the\n** stack across reallocations, doing the work only when needed.\n** It also allows the running of one GC step when the stack is\n** reallocated.\n** 'condmovestack' is used in heavy tests to force a stack reallocation\n** at every check.\n*/\n\n#if !defined(HARDSTACKTESTS)\n#define condmovestack(L,pre,pos)\t((void)0)\n#else\n/* realloc stack keeping its size */\n#define condmovestack(L,pre,pos)  \\\n  { int sz_ = stacksize(L); pre; luaD_reallocstack((L), sz_, 0); pos; }\n#endif\n\n#define luaD_checkstackaux(L,n,pre,pos)  \\\n\tif (l_unlikely(L->stack_last.p - L->top.p <= (n))) \\\n\t  { pre; luaD_growstack(L, n, 1); pos; } \\\n\telse { condmovestack(L,pre,pos); }\n\n/* In general, 'pre'/'pos' are empty (nothing to save) */\n#define luaD_checkstack(L,n)\tluaD_checkstackaux(L,n,(void)0,(void)0)\n\n\n\n#define savestack(L,pt)\t\t(cast_charp(pt) - cast_charp(L->stack.p))\n#define restorestack(L,n)\tcast(StkId, cast_charp(L->stack.p) + (n))\n\n\n/* macro to check stack size, preserving 'p' */\n#define checkstackp(L,n,p)  \\\n  luaD_checkstackaux(L, n, \\\n    ptrdiff_t t__ = savestack(L, p),  /* save 'p' */ \\\n    p = restorestack(L, t__))  /* 'pos' part: restore 'p' */\n\n\n/*\n** Maximum depth for nested C calls, syntactical nested non-terminals,\n** and other features implemented through recursion in C. (Value must\n** fit in a 16-bit unsigned integer. It must also be compatible with\n** the size of the C stack.)\n*/\n#if !defined(LUAI_MAXCCALLS)\n#define LUAI_MAXCCALLS\t\t200\n#endif\n\n\n/* type of protected functions, to be ran by 'runprotected' */\ntypedef void (*Pfunc) (lua_State *L, void *ud);\n\nLUAI_FUNC l_noret luaD_errerr (lua_State *L);\nLUAI_FUNC void luaD_seterrorobj (lua_State *L, TStatus errcode, StkId oldtop);\nLUAI_FUNC TStatus luaD_protectedparser (lua_State *L, ZIO *z,\n                                                  const char *name,\n                                                  const char *mode);\nLUAI_FUNC void luaD_hook (lua_State *L, int event, int line,\n                                        int fTransfer, int nTransfer);\nLUAI_FUNC void luaD_hookcall (lua_State *L, CallInfo *ci);\nLUAI_FUNC int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,\n                                              int narg1, int delta);\nLUAI_FUNC CallInfo *luaD_precall (lua_State *L, StkId func, int nResults);\nLUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults);\nLUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults);\nLUAI_FUNC TStatus luaD_closeprotected (lua_State *L, ptrdiff_t level,\n                                                     TStatus status);\nLUAI_FUNC TStatus luaD_pcall (lua_State *L, Pfunc func, void *u,\n                                        ptrdiff_t oldtop, ptrdiff_t ef);\nLUAI_FUNC void luaD_poscall (lua_State *L, CallInfo *ci, int nres);\nLUAI_FUNC int luaD_reallocstack (lua_State *L, int newsize, int raiseerror);\nLUAI_FUNC int luaD_growstack (lua_State *L, int n, int raiseerror);\nLUAI_FUNC void luaD_shrinkstack (lua_State *L);\nLUAI_FUNC void luaD_inctop (lua_State *L);\nLUAI_FUNC int luaD_checkminstack (lua_State *L);\n\nLUAI_FUNC l_noret luaD_throw (lua_State *L, TStatus errcode);\nLUAI_FUNC l_noret luaD_throwbaselevel (lua_State *L, TStatus errcode);\nLUAI_FUNC TStatus luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/ldump.c",
    "content": "/*\n** $Id: ldump.c $\n** save precompiled Lua chunks\n** See Copyright Notice in lua.h\n*/\n\n#define ldump_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <limits.h>\n#include <stddef.h>\n\n#include \"lua.h\"\n\n#include \"lapi.h\"\n#include \"lgc.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n#include \"ltable.h\"\n#include \"lundump.h\"\n\n\ntypedef struct {\n  lua_State *L;\n  lua_Writer writer;\n  void *data;\n  size_t offset;  /* current position relative to beginning of dump */\n  int strip;\n  int status;\n  Table *h;  /* table to track saved strings */\n  lua_Unsigned nstr;  /* counter for counting saved strings */\n} DumpState;\n\n\n/*\n** All high-level dumps go through dumpVector; you can change it to\n** change the endianness of the result\n*/\n#define dumpVector(D,v,n)\tdumpBlock(D,v,(n)*sizeof((v)[0]))\n\n#define dumpLiteral(D, s)\tdumpBlock(D,s,sizeof(s) - sizeof(char))\n\n\n/*\n** Dump the block of memory pointed by 'b' with given 'size'.\n** 'b' should not be NULL, except for the last call signaling the end\n** of the dump.\n*/\nstatic void dumpBlock (DumpState *D, const void *b, size_t size) {\n  if (D->status == 0) {  /* do not write anything after an error */\n    lua_unlock(D->L);\n    D->status = (*D->writer)(D->L, b, size, D->data);\n    lua_lock(D->L);\n    D->offset += size;\n  }\n}\n\n\n/*\n** Dump enough zeros to ensure that current position is a multiple of\n** 'align'.\n*/\nstatic void dumpAlign (DumpState *D, unsigned align) {\n  unsigned padding = align - cast_uint(D->offset % align);\n  if (padding < align) {  /* padding == align means no padding */\n    static lua_Integer paddingContent = 0;\n    lua_assert(align <= sizeof(lua_Integer));\n    dumpBlock(D, &paddingContent, padding);\n  }\n  lua_assert(D->offset % align == 0);\n}\n\n\n#define dumpVar(D,x)\t\tdumpVector(D,&x,1)\n\n\nstatic void dumpByte (DumpState *D, int y) {\n  lu_byte x = (lu_byte)y;\n  dumpVar(D, x);\n}\n\n\n/*\n** size for 'dumpVarint' buffer: each byte can store up to 7 bits.\n** (The \"+6\" rounds up the division.)\n*/\n#define DIBS    ((l_numbits(lua_Unsigned) + 6) / 7)\n\n/*\n** Dumps an unsigned integer using the MSB Varint encoding\n*/\nstatic void dumpVarint (DumpState *D, lua_Unsigned x) {\n  lu_byte buff[DIBS];\n  unsigned n = 1;\n  buff[DIBS - 1] = x & 0x7f;  /* fill least-significant byte */\n  while ((x >>= 7) != 0)  /* fill other bytes in reverse order */\n    buff[DIBS - (++n)] = cast_byte((x & 0x7f) | 0x80);\n  dumpVector(D, buff + DIBS - n, n);\n}\n\n\nstatic void dumpSize (DumpState *D, size_t sz) {\n  dumpVarint(D, cast(lua_Unsigned, sz));\n}\n\n\nstatic void dumpInt (DumpState *D, int x) {\n  lua_assert(x >= 0);\n  dumpVarint(D, cast_uint(x));\n}\n\n\nstatic void dumpNumber (DumpState *D, lua_Number x) {\n  dumpVar(D, x);\n}\n\n\n/*\n** Signed integers are coded to keep small values small. (Coding -1 as\n** 0xfff...fff would use too many bytes to save a quite common value.)\n** A non-negative x is coded as 2x; a negative x is coded as -2x - 1.\n** (0 => 0; -1 => 1; 1 => 2; -2 => 3; 2 => 4; ...)\n*/\nstatic void dumpInteger (DumpState *D, lua_Integer x) {\n  lua_Unsigned cx = (x >= 0) ? 2u * l_castS2U(x)\n                             : (2u * ~l_castS2U(x)) + 1;\n  dumpVarint(D, cx);\n}\n\n\n/*\n** Dump a String. First dump its \"size\":\n** size==0 is followed by an index and means \"reuse saved string with\n** that index\"; index==0 means NULL.\n** size>=1 is followed by the string contents with real size==size-1 and\n** means that string, which will be saved with the next available index.\n** The real size does not include the ending '\\0' (which is not dumped),\n** so adding 1 to it cannot overflow a size_t.\n*/\nstatic void dumpString (DumpState *D, TString *ts) {\n  if (ts == NULL) {\n    dumpVarint(D, 0);  /* will \"reuse\" NULL */\n    dumpVarint(D, 0);  /* special index for NULL */\n  }\n  else {\n    TValue idx;\n    int tag = luaH_getstr(D->h, ts, &idx);\n    if (!tagisempty(tag)) {  /* string already saved? */\n      dumpVarint(D, 0);  /* reuse a saved string */\n      dumpVarint(D, l_castS2U(ivalue(&idx)));  /* index of saved string */\n    }\n    else {  /* must write and save the string */\n      TValue key, value;  /* to save the string in the hash */\n      size_t size;\n      const char *s = getlstr(ts, size);\n      dumpSize(D, size + 1);\n      dumpVector(D, s, size + 1);  /* include ending '\\0' */\n      D->nstr++;  /* one more saved string */\n      setsvalue(D->L, &key, ts);  /* the string is the key */\n      setivalue(&value, l_castU2S(D->nstr));  /* its index is the value */\n      luaH_set(D->L, D->h, &key, &value);  /* h[ts] = nstr */\n      /* integer value does not need barrier */\n    }\n  }\n}\n\n\nstatic void dumpCode (DumpState *D, const Proto *f) {\n  dumpInt(D, f->sizecode);\n  dumpAlign(D, sizeof(f->code[0]));\n  lua_assert(f->code != NULL);\n  dumpVector(D, f->code, cast_uint(f->sizecode));\n}\n\n\nstatic void dumpFunction (DumpState *D, const Proto *f);\n\nstatic void dumpConstants (DumpState *D, const Proto *f) {\n  int i;\n  int n = f->sizek;\n  dumpInt(D, n);\n  for (i = 0; i < n; i++) {\n    const TValue *o = &f->k[i];\n    int tt = ttypetag(o);\n    dumpByte(D, tt);\n    switch (tt) {\n      case LUA_VNUMFLT:\n        dumpNumber(D, fltvalue(o));\n        break;\n      case LUA_VNUMINT:\n        dumpInteger(D, ivalue(o));\n        break;\n      case LUA_VSHRSTR:\n      case LUA_VLNGSTR:\n        dumpString(D, tsvalue(o));\n        break;\n      default:\n        lua_assert(tt == LUA_VNIL || tt == LUA_VFALSE || tt == LUA_VTRUE);\n    }\n  }\n}\n\n\nstatic void dumpProtos (DumpState *D, const Proto *f) {\n  int i;\n  int n = f->sizep;\n  dumpInt(D, n);\n  for (i = 0; i < n; i++)\n    dumpFunction(D, f->p[i]);\n}\n\n\nstatic void dumpUpvalues (DumpState *D, const Proto *f) {\n  int i, n = f->sizeupvalues;\n  dumpInt(D, n);\n  for (i = 0; i < n; i++) {\n    dumpByte(D, f->upvalues[i].instack);\n    dumpByte(D, f->upvalues[i].idx);\n    dumpByte(D, f->upvalues[i].kind);\n  }\n}\n\n\nstatic void dumpDebug (DumpState *D, const Proto *f) {\n  int i, n;\n  n = (D->strip) ? 0 : f->sizelineinfo;\n  dumpInt(D, n);\n  if (f->lineinfo != NULL)\n    dumpVector(D, f->lineinfo, cast_uint(n));\n  n = (D->strip) ? 0 : f->sizeabslineinfo;\n  dumpInt(D, n);\n  if (n > 0) {\n    /* 'abslineinfo' is an array of structures of int's */\n    dumpAlign(D, sizeof(int));\n    dumpVector(D, f->abslineinfo, cast_uint(n));\n  }\n  n = (D->strip) ? 0 : f->sizelocvars;\n  dumpInt(D, n);\n  for (i = 0; i < n; i++) {\n    dumpString(D, f->locvars[i].varname);\n    dumpInt(D, f->locvars[i].startpc);\n    dumpInt(D, f->locvars[i].endpc);\n  }\n  n = (D->strip) ? 0 : f->sizeupvalues;\n  dumpInt(D, n);\n  for (i = 0; i < n; i++)\n    dumpString(D, f->upvalues[i].name);\n}\n\n\nstatic void dumpFunction (DumpState *D, const Proto *f) {\n  dumpInt(D, f->linedefined);\n  dumpInt(D, f->lastlinedefined);\n  dumpByte(D, f->numparams);\n  dumpByte(D, f->flag);\n  dumpByte(D, f->maxstacksize);\n  dumpCode(D, f);\n  dumpConstants(D, f);\n  dumpUpvalues(D, f);\n  dumpProtos(D, f);\n  dumpString(D, D->strip ? NULL : f->source);\n  dumpDebug(D, f);\n}\n\n\n#define dumpNumInfo(D, tvar, value)  \\\n  { tvar i = value; dumpByte(D, sizeof(tvar)); dumpVar(D, i); }\n\n\nstatic void dumpHeader (DumpState *D) {\n  dumpLiteral(D, LUA_SIGNATURE);\n  dumpByte(D, LUAC_VERSION);\n  dumpByte(D, LUAC_FORMAT);\n  dumpLiteral(D, LUAC_DATA);\n  dumpNumInfo(D, int, LUAC_INT);\n  dumpNumInfo(D, Instruction, LUAC_INST);\n  dumpNumInfo(D, lua_Integer, LUAC_INT);\n  dumpNumInfo(D, lua_Number, LUAC_NUM);\n}\n\n\n/*\n** dump Lua function as precompiled chunk\n*/\nint luaU_dump (lua_State *L, const Proto *f, lua_Writer w, void *data,\n               int strip) {\n  DumpState D;\n  D.h = luaH_new(L);  /* aux. table to keep strings already dumped */\n  sethvalue2s(L, L->top.p, D.h);  /* anchor it */\n  L->top.p++;\n  D.L = L;\n  D.writer = w;\n  D.offset = 0;\n  D.data = data;\n  D.strip = strip;\n  D.status = 0;\n  D.nstr = 0;\n  dumpHeader(&D);\n  dumpByte(&D, f->sizeupvalues);\n  dumpFunction(&D, f);\n  dumpBlock(&D, NULL, 0);  /* signal end of dump */\n  return D.status;\n}\n\n"
  },
  {
    "path": "3rd/lua/lfunc.c",
    "content": "/*\n** $Id: lfunc.c $\n** Auxiliary functions to manipulate prototypes and closures\n** See Copyright Notice in lua.h\n*/\n\n#define lfunc_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <stddef.h>\n\n#include \"lua.h\"\n\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lfunc.h\"\n#include \"lgc.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n\n\n\nCClosure *luaF_newCclosure (lua_State *L, int nupvals) {\n  GCObject *o = luaC_newobj(L, LUA_VCCL, sizeCclosure(nupvals));\n  CClosure *c = gco2ccl(o);\n  c->nupvalues = cast_byte(nupvals);\n  return c;\n}\n\n\nLClosure *luaF_newLclosure (lua_State *L, int nupvals) {\n  GCObject *o = luaC_newobj(L, LUA_VLCL, sizeLclosure(nupvals));\n  LClosure *c = gco2lcl(o);\n  c->p = NULL;\n  c->nupvalues = cast_byte(nupvals);\n  while (nupvals--) c->upvals[nupvals] = NULL;\n  return c;\n}\n\n\n/*\n** fill a closure with new closed upvalues\n*/\nvoid luaF_initupvals (lua_State *L, LClosure *cl) {\n  int i;\n  for (i = 0; i < cl->nupvalues; i++) {\n    GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));\n    UpVal *uv = gco2upv(o);\n    uv->v.p = &uv->u.value;  /* make it closed */\n    setnilvalue(uv->v.p);\n    cl->upvals[i] = uv;\n    luaC_objbarrier(L, cl, uv);\n  }\n}\n\n\n/*\n** Create a new upvalue at the given level, and link it to the list of\n** open upvalues of 'L' after entry 'prev'.\n**/\nstatic UpVal *newupval (lua_State *L, StkId level, UpVal **prev) {\n  GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));\n  UpVal *uv = gco2upv(o);\n  UpVal *next = *prev;\n  uv->v.p = s2v(level);  /* current value lives in the stack */\n  uv->u.open.next = next;  /* link it to list of open upvalues */\n  uv->u.open.previous = prev;\n  if (next)\n    next->u.open.previous = &uv->u.open.next;\n  *prev = uv;\n  if (!isintwups(L)) {  /* thread not in list of threads with upvalues? */\n    L->twups = G(L)->twups;  /* link it to the list */\n    G(L)->twups = L;\n  }\n  return uv;\n}\n\n\n/*\n** Find and reuse, or create if it does not exist, an upvalue\n** at the given level.\n*/\nUpVal *luaF_findupval (lua_State *L, StkId level) {\n  UpVal **pp = &L->openupval;\n  UpVal *p;\n  lua_assert(isintwups(L) || L->openupval == NULL);\n  while ((p = *pp) != NULL && uplevel(p) >= level) {  /* search for it */\n    lua_assert(!isdead(G(L), p));\n    if (uplevel(p) == level)  /* corresponding upvalue? */\n      return p;  /* return it */\n    pp = &p->u.open.next;\n  }\n  /* not found: create a new upvalue after 'pp' */\n  return newupval(L, level, pp);\n}\n\n\n/*\n** Call closing method for object 'obj' with error object 'err'. The\n** boolean 'yy' controls whether the call is yieldable.\n** (This function assumes EXTRA_STACK.)\n*/\nstatic void callclosemethod (lua_State *L, TValue *obj, TValue *err, int yy) {\n  StkId top = L->top.p;\n  StkId func = top;\n  const TValue *tm = luaT_gettmbyobj(L, obj, TM_CLOSE);\n  setobj2s(L, top++, tm);  /* will call metamethod... */\n  setobj2s(L, top++, obj);  /* with 'self' as the 1st argument */\n  if (err != NULL)  /* if there was an error... */\n    setobj2s(L, top++, err);  /* then error object will be 2nd argument */\n  L->top.p = top;  /* add function and arguments */\n  if (yy)\n    luaD_call(L, func, 0);\n  else\n    luaD_callnoyield(L, func, 0);\n}\n\n\n/*\n** Check whether object at given level has a close metamethod and raise\n** an error if not.\n*/\nstatic void checkclosemth (lua_State *L, StkId level) {\n  const TValue *tm = luaT_gettmbyobj(L, s2v(level), TM_CLOSE);\n  if (ttisnil(tm)) {  /* no metamethod? */\n    int idx = cast_int(level - L->ci->func.p);  /* variable index */\n    const char *vname = luaG_findlocal(L, L->ci, idx, NULL);\n    if (vname == NULL) vname = \"?\";\n    luaG_runerror(L, \"variable '%s' got a non-closable value\", vname);\n  }\n}\n\n\n/*\n** Prepare and call a closing method.\n** If status is CLOSEKTOP, the call to the closing method will be pushed\n** at the top of the stack. Otherwise, values can be pushed right after\n** the 'level' of the upvalue being closed, as everything after that\n** won't be used again.\n*/\nstatic void prepcallclosemth (lua_State *L, StkId level, TStatus status,\n                                            int yy) {\n  TValue *uv = s2v(level);  /* value being closed */\n  TValue *errobj;\n  switch (status) {\n    case LUA_OK:\n      L->top.p = level + 1;  /* call will be at this level */\n      /* FALLTHROUGH */\n    case CLOSEKTOP:  /* don't need to change top */\n      errobj = NULL;  /* no error object */\n      break;\n    default:  /* 'luaD_seterrorobj' will set top to level + 2 */\n      errobj = s2v(level + 1);  /* error object goes after 'uv' */\n      luaD_seterrorobj(L, status, level + 1);  /* set error object */\n      break;\n  }\n  callclosemethod(L, uv, errobj, yy);\n}\n\n\n/* Maximum value for deltas in 'tbclist' */\n#define MAXDELTA       USHRT_MAX\n\n\n/*\n** Insert a variable in the list of to-be-closed variables.\n*/\nvoid luaF_newtbcupval (lua_State *L, StkId level) {\n  lua_assert(level > L->tbclist.p);\n  if (l_isfalse(s2v(level)))\n    return;  /* false doesn't need to be closed */\n  checkclosemth(L, level);  /* value must have a close method */\n  while (cast_uint(level - L->tbclist.p) > MAXDELTA) {\n    L->tbclist.p += MAXDELTA;  /* create a dummy node at maximum delta */\n    L->tbclist.p->tbclist.delta = 0;\n  }\n  level->tbclist.delta = cast(unsigned short, level - L->tbclist.p);\n  L->tbclist.p = level;\n}\n\n\nvoid luaF_unlinkupval (UpVal *uv) {\n  lua_assert(upisopen(uv));\n  *uv->u.open.previous = uv->u.open.next;\n  if (uv->u.open.next)\n    uv->u.open.next->u.open.previous = uv->u.open.previous;\n}\n\n\n/*\n** Close all upvalues up to the given stack level.\n*/\nvoid luaF_closeupval (lua_State *L, StkId level) {\n  UpVal *uv;\n  while ((uv = L->openupval) != NULL && uplevel(uv) >= level) {\n    TValue *slot = &uv->u.value;  /* new position for value */\n    lua_assert(uplevel(uv) < L->top.p);\n    luaF_unlinkupval(uv);  /* remove upvalue from 'openupval' list */\n    setobj(L, slot, uv->v.p);  /* move value to upvalue slot */\n    uv->v.p = slot;  /* now current value lives here */\n    if (!iswhite(uv)) {  /* neither white nor dead? */\n      nw2black(uv);  /* closed upvalues cannot be gray */\n      luaC_barrier(L, uv, slot);\n    }\n  }\n}\n\n\n/*\n** Remove first element from the tbclist plus its dummy nodes.\n*/\nstatic void poptbclist (lua_State *L) {\n  StkId tbc = L->tbclist.p;\n  lua_assert(tbc->tbclist.delta > 0);  /* first element cannot be dummy */\n  tbc -= tbc->tbclist.delta;\n  while (tbc > L->stack.p && tbc->tbclist.delta == 0)\n    tbc -= MAXDELTA;  /* remove dummy nodes */\n  L->tbclist.p = tbc;\n}\n\n\n/*\n** Close all upvalues and to-be-closed variables up to the given stack\n** level. Return restored 'level'.\n*/\nStkId luaF_close (lua_State *L, StkId level, TStatus status, int yy) {\n  ptrdiff_t levelrel = savestack(L, level);\n  luaF_closeupval(L, level);  /* first, close the upvalues */\n  while (L->tbclist.p >= level) {  /* traverse tbc's down to that level */\n    StkId tbc = L->tbclist.p;  /* get variable index */\n    poptbclist(L);  /* remove it from list */\n    prepcallclosemth(L, tbc, status, yy);  /* close variable */\n    level = restorestack(L, levelrel);\n  }\n  return level;\n}\n\n\nProto *luaF_newproto (lua_State *L) {\n  GCObject *o = luaC_newobj(L, LUA_VPROTO, sizeof(Proto));\n  Proto *f = gco2p(o);\n  f->k = NULL;\n  f->sizek = 0;\n  f->p = NULL;\n  f->sizep = 0;\n  f->code = NULL;\n  f->sizecode = 0;\n  f->lineinfo = NULL;\n  f->sizelineinfo = 0;\n  f->abslineinfo = NULL;\n  f->sizeabslineinfo = 0;\n  f->upvalues = NULL;\n  f->sizeupvalues = 0;\n  f->numparams = 0;\n  f->flag = 0;\n  f->maxstacksize = 0;\n  f->locvars = NULL;\n  f->sizelocvars = 0;\n  f->linedefined = 0;\n  f->lastlinedefined = 0;\n  f->source = NULL;\n  return f;\n}\n\n\nlu_mem luaF_protosize (Proto *p) {\n  lu_mem sz = cast(lu_mem, sizeof(Proto))\n            + cast_uint(p->sizep) * sizeof(Proto*)\n            + cast_uint(p->sizek) * sizeof(TValue)\n            + cast_uint(p->sizelocvars) * sizeof(LocVar)\n            + cast_uint(p->sizeupvalues) * sizeof(Upvaldesc);\n  if (!(p->flag & PF_FIXED)) {\n    sz += cast_uint(p->sizecode) * sizeof(Instruction);\n    sz += cast_uint(p->sizelineinfo) * sizeof(lu_byte);\n    sz += cast_uint(p->sizeabslineinfo) * sizeof(AbsLineInfo);\n  }\n  return sz;\n}\n\n\nvoid luaF_freeproto (lua_State *L, Proto *f) {\n  if (!(f->flag & PF_FIXED)) {\n    luaM_freearray(L, f->code, cast_sizet(f->sizecode));\n    luaM_freearray(L, f->lineinfo, cast_sizet(f->sizelineinfo));\n    luaM_freearray(L, f->abslineinfo, cast_sizet(f->sizeabslineinfo));\n  }\n  luaM_freearray(L, f->p, cast_sizet(f->sizep));\n  luaM_freearray(L, f->k, cast_sizet(f->sizek));\n  luaM_freearray(L, f->locvars, cast_sizet(f->sizelocvars));\n  luaM_freearray(L, f->upvalues, cast_sizet(f->sizeupvalues));\n  luaM_free(L, f);\n}\n\n\n/*\n** Look for n-th local variable at line 'line' in function 'func'.\n** Returns NULL if not found.\n*/\nconst char *luaF_getlocalname (const Proto *f, int local_number, int pc) {\n  int i;\n  for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {\n    if (pc < f->locvars[i].endpc) {  /* is variable active? */\n      local_number--;\n      if (local_number == 0)\n        return getstr(f->locvars[i].varname);\n    }\n  }\n  return NULL;  /* not found */\n}\n\nvoid luaF_shareproto (Proto *f) {\n  int i;\n  if (f == NULL || isshared(f))\n    return;\n  makeshared(f);\n  luaS_share(f->source);\n  for (i = 0; i < f->sizek; i++) {\n    if (ttype(&f->k[i]) == LUA_TSTRING)\n      luaS_share(tsvalue(&f->k[i]));\n  }\n  for (i = 0; i < f->sizeupvalues; i++)\n    luaS_share(f->upvalues[i].name);\n  for (i = 0; i < f->sizelocvars; i++)\n    luaS_share(f->locvars[i].varname);\n  for (i = 0; i < f->sizep; i++)\n    luaF_shareproto(f->p[i]);\n}\n"
  },
  {
    "path": "3rd/lua/lfunc.h",
    "content": "/*\n** $Id: lfunc.h $\n** Auxiliary functions to manipulate prototypes and closures\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lfunc_h\n#define lfunc_h\n\n\n#include \"lobject.h\"\n\n\n#define sizeCclosure(n)  \\\n\t(offsetof(CClosure, upvalue) + sizeof(TValue) * cast_uint(n))\n\n#define sizeLclosure(n)  \\\n\t(offsetof(LClosure, upvals) + sizeof(UpVal *) * cast_uint(n))\n\n\n/* test whether thread is in 'twups' list */\n#define isintwups(L)\t(L->twups != L)\n\n\n/*\n** maximum number of upvalues in a closure (both C and Lua). (Value\n** must fit in a VM register.)\n*/\n#define MAXUPVAL\t255\n\n\n#define upisopen(up)\t((up)->v.p != &(up)->u.value)\n\n\n#define uplevel(up)\tcheck_exp(upisopen(up), cast(StkId, (up)->v.p))\n\n\n/*\n** maximum number of misses before giving up the cache of closures\n** in prototypes\n*/\n#define MAXMISS\t\t10\n\n\n\n/* special status to close upvalues preserving the top of the stack */\n#define CLOSEKTOP\t(LUA_ERRERR + 1)\n\n\nLUAI_FUNC Proto *luaF_newproto (lua_State *L);\nLUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nupvals);\nLUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nupvals);\nLUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl);\nLUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);\nLUAI_FUNC void luaF_newtbcupval (lua_State *L, StkId level);\nLUAI_FUNC void luaF_closeupval (lua_State *L, StkId level);\nLUAI_FUNC StkId luaF_close (lua_State *L, StkId level, TStatus status, int yy);\nLUAI_FUNC void luaF_unlinkupval (UpVal *uv);\nLUAI_FUNC lu_mem luaF_protosize (Proto *p);\nLUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);\nLUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,\n                                         int pc);\nLUAI_FUNC void luaF_shareproto (Proto *func);\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lgc.c",
    "content": "/*\n** $Id: lgc.c $\n** Garbage Collector\n** See Copyright Notice in lua.h\n*/\n\n#define lgc_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n#include <string.h>\n\n\n#include \"lua.h\"\n\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lfunc.h\"\n#include \"lgc.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"ltm.h\"\n\n\n/*\n** Maximum number of elements to sweep in each single step.\n** (Large enough to dissipate fixed overheads but small enough\n** to allow small steps for the collector.)\n*/\n#define GCSWEEPMAX\t20\n\n\n/*\n** Cost (in work units) of running one finalizer.\n*/\n#define CWUFIN\t10\n\n\n/* mask with all color bits */\n#define maskcolors\t(bitmask(BLACKBIT) | WHITEBITS)\n\n/* mask with all GC bits */\n#define maskgcbits      (maskcolors | AGEBITS)\n\n\n/* macro to erase all color bits then set only the current white bit */\n#define makewhite(g,x)\t\\\n  (x->marked = cast_byte((x->marked & ~maskcolors) | luaC_white(g)))\n\n/* make an object gray (neither white nor black) */\n#define set2gray(x)\tresetbits(x->marked, maskcolors)\n\n\n/* make an object black (coming from any color) */\n#define set2black(x)  \\\n  (x->marked = cast_byte((x->marked & ~WHITEBITS) | bitmask(BLACKBIT)))\n\n\n#define valiswhite(x)   (iscollectable(x) && ispurewhite(gcvalue(x)))\n\n#define keyiswhite(n)   (keyiscollectable(n) && ispurewhite(gckey(n)))\n\n\n/*\n** Protected access to objects in values\n*/\n#define gcvalueN(o)     (iscollectable(o) ? gcvalue(o) : NULL)\n\n\n/*\n** Access to collectable objects in array part of tables\n*/\n#define gcvalarr(t,i)  \\\n\t((*getArrTag(t,i) & BIT_ISCOLLECTABLE) ? getArrVal(t,i)->gc : NULL)\n\n\n#define markvalue(g,o) { checkliveness(mainthread(g),o); \\\n  if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }\n\n#define markkey(g, n)\t{ if keyiswhite(n) reallymarkobject(g,gckey(n)); }\n\n#define markobject(g,t)\t{ if (ispurewhite(t)) reallymarkobject(g, obj2gco(t)); }\n\n/*\n** mark an object that can be NULL (either because it is really optional,\n** or it was stripped as debug info, or inside an uncompleted structure)\n*/\n#define markobjectN(g,t)\t{ if (t) markobject(g,t); }\n\n\nstatic void reallymarkobject (global_State *g, GCObject *o);\nstatic void atomic (lua_State *L);\nstatic void entersweep (lua_State *L);\n\n\n/*\n** {======================================================\n** Generic functions\n** =======================================================\n*/\n\n\n/*\n** one after last element in a hash array\n*/\n#define gnodelast(h)\tgnode(h, cast_sizet(sizenode(h)))\n\n\nstatic l_mem objsize (GCObject *o) {\n  lu_mem res;\n  switch (o->tt) {\n    case LUA_VTABLE: {\n      res = luaH_size(gco2t(o));\n      break;\n    }\n    case LUA_VLCL: {\n      LClosure *cl = gco2lcl(o);\n      res = sizeLclosure(cl->nupvalues);\n      break;\n    }\n    case LUA_VCCL: {\n      CClosure *cl = gco2ccl(o);\n      res = sizeCclosure(cl->nupvalues);\n      break;\n    }\n    case LUA_VUSERDATA: {\n      Udata *u = gco2u(o);\n      res = sizeudata(u->nuvalue, u->len);\n      break;\n    }\n    case LUA_VPROTO: {\n      res = luaF_protosize(gco2p(o));\n      break;\n    }\n    case LUA_VTHREAD: {\n      res = luaE_threadsize(gco2th(o));\n      break;\n    }\n    case LUA_VSHRSTR: {\n      TString *ts = gco2ts(o);\n      res = sizestrshr(cast_uint(ts->shrlen));\n      break;\n    }\n    case LUA_VLNGSTR: {\n      TString *ts = gco2ts(o);\n      res = luaS_sizelngstr(ts->u.lnglen, ts->shrlen);\n      break;\n    }\n    case LUA_VUPVAL: {\n      res = sizeof(UpVal);\n      break;\n    }\n    default: res = 0; lua_assert(0);\n  }\n  return cast(l_mem, res);\n}\n\n\nstatic GCObject **getgclist (GCObject *o) {\n  switch (o->tt) {\n    case LUA_VTABLE: return &gco2t(o)->gclist;\n    case LUA_VLCL: return &gco2lcl(o)->gclist;\n    case LUA_VCCL: return &gco2ccl(o)->gclist;\n    case LUA_VTHREAD: return &gco2th(o)->gclist;\n    case LUA_VPROTO: return &gco2p(o)->gclist;\n    case LUA_VUSERDATA: {\n      Udata *u = gco2u(o);\n      lua_assert(u->nuvalue > 0);\n      return &u->gclist;\n    }\n    default: lua_assert(0); return 0;\n  }\n}\n\n\n/*\n** Link a collectable object 'o' with a known type into the list 'p'.\n** (Must be a macro to access the 'gclist' field in different types.)\n*/\n#define linkgclist(o,p)\tlinkgclist_(obj2gco(o), &(o)->gclist, &(p))\n\nstatic void linkgclist_ (GCObject *o, GCObject **pnext, GCObject **list) {\n  lua_assert(!isgray(o));  /* cannot be in a gray list */\n  *pnext = *list;\n  *list = o;\n  set2gray(o);  /* now it is */\n}\n\n\n/*\n** Link a generic collectable object 'o' into the list 'p'.\n*/\n#define linkobjgclist(o,p) linkgclist_(obj2gco(o), getgclist(o), &(p))\n\n\n\n/*\n** Clear keys for empty entries in tables. If entry is empty, mark its\n** entry as dead. This allows the collection of the key, but keeps its\n** entry in the table: its removal could break a chain and could break\n** a table traversal.  Other places never manipulate dead keys, because\n** its associated empty value is enough to signal that the entry is\n** logically empty.\n*/\nstatic void clearkey (Node *n) {\n  lua_assert(isempty(gval(n)));\n  if (keyiscollectable(n))\n    setdeadkey(n);  /* unused key; remove it */\n}\n\n\n/*\n** tells whether a key or value can be cleared from a weak\n** table. Non-collectable objects are never removed from weak\n** tables. Strings behave as 'values', so are never removed too. for\n** other objects: if really collected, cannot keep them; for objects\n** being finalized, keep them in keys, but not in values\n*/\nstatic int iscleared (global_State *g, const GCObject *o) {\n  if (o == NULL) return 0;  /* non-collectable value */\n  else if (novariant(o->tt) == LUA_TSTRING) {\n    markobject(g, o);  /* strings are 'values', so are never weak */\n    return 0;\n  }\n  else return ispurewhite(o);\n}\n\n\n/*\n** Barrier that moves collector forward, that is, marks the white object\n** 'v' being pointed by the black object 'o'.  In the generational\n** mode, 'v' must also become old, if 'o' is old; however, it cannot\n** be changed directly to OLD, because it may still point to non-old\n** objects. So, it is marked as OLD0. In the next cycle it will become\n** OLD1, and in the next it will finally become OLD (regular old). By\n** then, any object it points to will also be old.  If called in the\n** incremental sweep phase, it clears the black object to white (sweep\n** it) to avoid other barrier calls for this same object. (That cannot\n** be done is generational mode, as its sweep does not distinguish\n** white from dead.)\n*/\nvoid luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {\n  global_State *g = G(L);\n  lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o) && !isshared(o));\n  if (keepinvariant(g)) {  /* must keep invariant? */\n    reallymarkobject(g, v);  /* restore invariant */\n    if (isold(o)) {\n      lua_assert(!isold(v));  /* white object could not be old */\n      setage(v, G_OLD0);  /* restore generational invariant */\n    }\n  }\n  else {  /* sweep phase */\n    lua_assert(issweepphase(g));\n    if (g->gckind != KGC_GENMINOR)  /* incremental mode? */\n      makewhite(g, o);  /* mark 'o' as white to avoid other barriers */\n  }\n}\n\n\n/*\n** barrier that moves collector backward, that is, mark the black object\n** pointing to a white object as gray again.\n*/\nvoid luaC_barrierback_ (lua_State *L, GCObject *o) {\n  global_State *g = G(L);\n  lua_assert(isblack(o) && !isdead(g, o));\n  lua_assert((g->gckind != KGC_GENMINOR)\n          || (isold(o) && getage(o) != G_TOUCHED1));\n  if (getage(o) == G_TOUCHED2)  /* already in gray list? */\n    set2gray(o);  /* make it gray to become touched1 */\n  else  /* link it in 'grayagain' and paint it gray */\n    linkobjgclist(o, g->grayagain);\n  if (isold(o))  /* generational mode? */\n    setage(o, G_TOUCHED1);  /* touched in current cycle */\n}\n\n\nvoid luaC_fix (lua_State *L, GCObject *o) {\n  global_State *g = G(L);\n  lua_assert(g->allgc == o);  /* object must be 1st in 'allgc' list! */\n  set2gray(o);  /* they will be gray forever */\n  setage(o, G_OLD);  /* and old forever */\n  g->allgc = o->next;  /* remove object from 'allgc' list */\n  o->next = g->fixedgc;  /* link it to 'fixedgc' list */\n  g->fixedgc = o;\n}\n\n\n/*\n** create a new collectable object (with given type, size, and offset)\n** and link it to 'allgc' list.\n*/\nGCObject *luaC_newobjdt (lua_State *L, lu_byte tt, size_t sz, size_t offset) {\n  global_State *g = G(L);\n  char *p = cast_charp(luaM_newobject(L, novariant(tt), sz));\n  GCObject *o = cast(GCObject *, p + offset);\n  o->marked = luaC_white(g);\n  o->tt = tt;\n  o->next = g->allgc;\n  g->allgc = o;\n  return o;\n}\n\n\n/*\n** create a new collectable object with no offset.\n*/\nGCObject *luaC_newobj (lua_State *L, lu_byte tt, size_t sz) {\n  return luaC_newobjdt(L, tt, sz, 0);\n}\n\n/* }====================================================== */\n\n\n\n/*\n** {======================================================\n** Mark functions\n** =======================================================\n*/\n\n\n/*\n** Mark an object.  Userdata with no user values, strings, and closed\n** upvalues are visited and turned black here.  Open upvalues are\n** already indirectly linked through their respective threads in the\n** 'twups' list, so they don't go to the gray list; nevertheless, they\n** are kept gray to avoid barriers, as their values will be revisited\n** by the thread or by 'remarkupvals'.  Other objects are added to the\n** gray list to be visited (and turned black) later.  Both userdata and\n** upvalues can call this function recursively, but this recursion goes\n** for at most two levels: An upvalue cannot refer to another upvalue\n** (only closures can), and a userdata's metatable must be a table.\n*/\nstatic void reallymarkobject (global_State *g, GCObject *o) {\n  g->GCmarked += objsize(o);\n  switch (o->tt) {\n    case LUA_VSHRSTR:\n    case LUA_VLNGSTR: {\n      set2black(o);  /* nothing to visit */\n      break;\n    }\n    case LUA_VUPVAL: {\n      UpVal *uv = gco2upv(o);\n      if (upisopen(uv))\n        set2gray(uv);  /* open upvalues are kept gray */\n      else\n        set2black(uv);  /* closed upvalues are visited here */\n      markvalue(g, uv->v.p);  /* mark its content */\n      break;\n    }\n    case LUA_VUSERDATA: {\n      Udata *u = gco2u(o);\n      if (u->nuvalue == 0) {  /* no user values? */\n        markobjectN(g, u->metatable);  /* mark its metatable */\n        set2black(u);  /* nothing else to mark */\n        break;\n      }\n      /* else... */\n    }  /* FALLTHROUGH */\n    case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE:\n    case LUA_VTHREAD: case LUA_VPROTO: {\n      linkobjgclist(o, g->gray);  /* to be visited later */\n      break;\n    }\n    default: lua_assert(0); break;\n  }\n}\n\n\n/*\n** mark metamethods for basic types\n*/\nstatic void markmt (global_State *g) {\n  int i;\n  for (i=0; i < LUA_NUMTYPES; i++)\n    markobjectN(g, g->mt[i]);\n}\n\n\n/*\n** mark all objects in list of being-finalized\n*/\nstatic void markbeingfnz (global_State *g) {\n  GCObject *o;\n  for (o = g->tobefnz; o != NULL; o = o->next)\n    markobject(g, o);\n}\n\n\n/*\n** For each non-marked thread, simulates a barrier between each open\n** upvalue and its value. (If the thread is collected, the value will be\n** assigned to the upvalue, but then it can be too late for the barrier\n** to act. The \"barrier\" does not need to check colors: A non-marked\n** thread must be young; upvalues cannot be older than their threads; so\n** any visited upvalue must be young too.) Also removes the thread from\n** the list, as it was already visited. Removes also threads with no\n** upvalues, as they have nothing to be checked. (If the thread gets an\n** upvalue later, it will be linked in the list again.)\n*/\nstatic void remarkupvals (global_State *g) {\n  lua_State *thread;\n  lua_State **p = &g->twups;\n  while ((thread = *p) != NULL) {\n    if (!iswhite(thread) && thread->openupval != NULL)\n      p = &thread->twups;  /* keep marked thread with upvalues in the list */\n    else {  /* thread is not marked or without upvalues */\n      UpVal *uv;\n      lua_assert(!isold(thread) || thread->openupval == NULL);\n      *p = thread->twups;  /* remove thread from the list */\n      thread->twups = thread;  /* mark that it is out of list */\n      for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {\n        lua_assert(getage(uv) <= getage(thread));\n        if (!iswhite(uv)) {  /* upvalue already visited? */\n          lua_assert(upisopen(uv) && isgray(uv));\n          markvalue(g, uv->v.p);  /* mark its value */\n        }\n      }\n    }\n  }\n}\n\n\nstatic void cleargraylists (global_State *g) {\n  g->gray = g->grayagain = NULL;\n  g->weak = g->allweak = g->ephemeron = NULL;\n}\n\n\n/*\n** mark root set and reset all gray lists, to start a new collection.\n** 'GCmarked' is initialized to count the total number of live bytes\n** during a cycle.\n*/\nstatic void restartcollection (global_State *g) {\n  cleargraylists(g);\n  g->GCmarked = 0;\n  markobject(g, mainthread(g));\n  markvalue(g, &g->l_registry);\n  markmt(g);\n  markbeingfnz(g);  /* mark any finalizing object left from previous cycle */\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Traverse functions\n** =======================================================\n*/\n\n\n/*\n** Check whether object 'o' should be kept in the 'grayagain' list for\n** post-processing by 'correctgraylist'. (It could put all old objects\n** in the list and leave all the work to 'correctgraylist', but it is\n** more efficient to avoid adding elements that will be removed.) Only\n** TOUCHED1 objects need to be in the list. TOUCHED2 doesn't need to go\n** back to a gray list, but then it must become OLD. (That is what\n** 'correctgraylist' does when it finds a TOUCHED2 object.)\n** This function is a no-op in incremental mode, as objects cannot be\n** marked as touched in that mode.\n*/\nstatic void genlink (global_State *g, GCObject *o) {\n  lua_assert(isblack(o));\n  if (getage(o) == G_TOUCHED1) {  /* touched in this cycle? */\n    linkobjgclist(o, g->grayagain);  /* link it back in 'grayagain' */\n  }  /* everything else do not need to be linked back */\n  else if (getage(o) == G_TOUCHED2)\n    setage(o, G_OLD);  /* advance age */\n}\n\n\n/*\n** Traverse a table with weak values and link it to proper list. During\n** propagate phase, keep it in 'grayagain' list, to be revisited in the\n** atomic phase. In the atomic phase, if table has any white value,\n** put it in 'weak' list, to be cleared; otherwise, call 'genlink'\n** to check table age in generational mode.\n*/\nstatic void traverseweakvalue (global_State *g, Table *h) {\n  Node *n, *limit = gnodelast(h);\n  /* if there is array part, assume it may have white values (it is not\n     worth traversing it now just to check) */\n  int hasclears = (h->asize > 0);\n  for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */\n    if (isempty(gval(n)))  /* entry is empty? */\n      clearkey(n);  /* clear its key */\n    else {\n      lua_assert(!keyisnil(n));\n      markkey(g, n);\n      if (!hasclears && iscleared(g, gcvalueN(gval(n))))  /* a white value? */\n        hasclears = 1;  /* table will have to be cleared */\n    }\n  }\n  if (g->gcstate == GCSpropagate)\n    linkgclist(h, g->grayagain);  /* must retraverse it in atomic phase */\n  else if (hasclears)\n      linkgclist(h, g->weak);  /* has to be cleared later */\n  else\n    genlink(g, obj2gco(h));\n}\n\n\n/*\n** Traverse the array part of a table.\n*/\nstatic int traversearray (global_State *g, Table *h) {\n  unsigned asize = h->asize;\n  int marked = 0;  /* true if some object is marked in this traversal */\n  unsigned i;\n  for (i = 0; i < asize; i++) {\n    GCObject *o = gcvalarr(h, i);\n    if (o != NULL && iswhite(o)) {\n      marked = 1;\n      reallymarkobject(g, o);\n    }\n  }\n  return marked;\n}\n\n\n/*\n** Traverse an ephemeron table and link it to proper list. Returns true\n** iff any object was marked during this traversal (which implies that\n** convergence has to continue). During propagation phase, keep table\n** in 'grayagain' list, to be visited again in the atomic phase. In\n** the atomic phase, if table has any white->white entry, it has to\n** be revisited during ephemeron convergence (as that key may turn\n** black). Otherwise, if it has any white key, table has to be cleared\n** (in the atomic phase). In generational mode, some tables\n** must be kept in some gray list for post-processing; this is done\n** by 'genlink'.\n*/\nstatic int traverseephemeron (global_State *g, Table *h, int inv) {\n  int hasclears = 0;  /* true if table has white keys */\n  int hasww = 0;  /* true if table has entry \"white-key -> white-value\" */\n  unsigned int i;\n  unsigned int nsize = sizenode(h);\n  int marked = traversearray(g, h);  /* traverse array part */\n  /* traverse hash part; if 'inv', traverse descending\n     (see 'convergeephemerons') */\n  for (i = 0; i < nsize; i++) {\n    Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i);\n    if (isempty(gval(n)))  /* entry is empty? */\n      clearkey(n);  /* clear its key */\n    else if (iscleared(g, gckeyN(n))) {  /* key is not marked (yet)? */\n      hasclears = 1;  /* table must be cleared */\n      if (valiswhite(gval(n)))  /* value not marked yet? */\n        hasww = 1;  /* white-white entry */\n    }\n    else if (valiswhite(gval(n))) {  /* value not marked yet? */\n      marked = 1;\n      reallymarkobject(g, gcvalue(gval(n)));  /* mark it now */\n    }\n  }\n  /* link table into proper list */\n  if (g->gcstate == GCSpropagate)\n    linkgclist(h, g->grayagain);  /* must retraverse it in atomic phase */\n  else if (hasww)  /* table has white->white entries? */\n    linkgclist(h, g->ephemeron);  /* have to propagate again */\n  else if (hasclears)  /* table has white keys? */\n    linkgclist(h, g->allweak);  /* may have to clean white keys */\n  else\n    genlink(g, obj2gco(h));  /* check whether collector still needs to see it */\n  return marked;\n}\n\n\nstatic void traversestrongtable (global_State *g, Table *h) {\n  Node *n, *limit = gnodelast(h);\n  traversearray(g, h);\n  for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */\n    if (isempty(gval(n)))  /* entry is empty? */\n      clearkey(n);  /* clear its key */\n    else {\n      lua_assert(!keyisnil(n));\n      markkey(g, n);\n      markvalue(g, gval(n));\n    }\n  }\n  genlink(g, obj2gco(h));\n}\n\n\n/*\n** (result & 1) iff weak values; (result & 2) iff weak keys.\n*/\nstatic int getmode (global_State *g, Table *h) {\n  const TValue *mode = gfasttm(g, h->metatable, TM_MODE);\n  if (mode == NULL || !ttisstring(mode))\n    return 0;  /* ignore non-string modes */\n  else {\n    const char *smode = getstr(tsvalue(mode));\n    const char *weakkey = strchr(smode, 'k');\n    const char *weakvalue = strchr(smode, 'v');\n    return ((weakkey != NULL) << 1) | (weakvalue != NULL);\n  }\n}\n\n\nstatic l_mem traversetable (global_State *g, Table *h) {\n  markobjectN(g, h->metatable);\n  switch (getmode(g, h)) {\n    case 0:  /* not weak */\n      traversestrongtable(g, h);\n      break;\n    case 1:  /* weak values */\n      traverseweakvalue(g, h);\n      break;\n    case 2:  /* weak keys */\n      traverseephemeron(g, h, 0);\n      break;\n    case 3:  /* all weak; nothing to traverse */\n      if (g->gcstate == GCSpropagate)\n        linkgclist(h, g->grayagain);  /* must visit again its metatable */\n      else\n        linkgclist(h, g->allweak);  /* must clear collected entries */\n      break;\n  }\n  return cast(l_mem, 1 + 2*sizenode(h) + h->asize);\n}\n\n\nstatic l_mem traverseudata (global_State *g, Udata *u) {\n  int i;\n  markobjectN(g, u->metatable);  /* mark its metatable */\n  for (i = 0; i < u->nuvalue; i++)\n    markvalue(g, &u->uv[i].uv);\n  genlink(g, obj2gco(u));\n  return 1 + u->nuvalue;\n}\n\n\n/*\n** Traverse a prototype. (While a prototype is being build, its\n** arrays can be larger than needed; the extra slots are filled with\n** NULL, so the use of 'markobjectN')\n*/\nstatic l_mem traverseproto (global_State *g, Proto *f) {\n  int i;\n  markobjectN(g, f->source);\n  for (i = 0; i < f->sizek; i++)  /* mark literals */\n    markvalue(g, &f->k[i]);\n  for (i = 0; i < f->sizeupvalues; i++)  /* mark upvalue names */\n    markobjectN(g, f->upvalues[i].name);\n  for (i = 0; i < f->sizep; i++)  /* mark nested protos */\n    markobjectN(g, f->p[i]);\n  for (i = 0; i < f->sizelocvars; i++)  /* mark local-variable names */\n    markobjectN(g, f->locvars[i].varname);\n  return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars;\n}\n\n\nstatic l_mem traverseCclosure (global_State *g, CClosure *cl) {\n  int i;\n  for (i = 0; i < cl->nupvalues; i++)  /* mark its upvalues */\n    markvalue(g, &cl->upvalue[i]);\n  return 1 + cl->nupvalues;\n}\n\n/*\n** Traverse a Lua closure, marking its prototype and its upvalues.\n** (Both can be NULL while closure is being created.)\n*/\nstatic l_mem traverseLclosure (global_State *g, LClosure *cl) {\n  int i;\n  markobjectN(g, cl->p);  /* mark its prototype */\n  for (i = 0; i < cl->nupvalues; i++) {  /* visit its upvalues */\n    UpVal *uv = cl->upvals[i];\n    markobjectN(g, uv);  /* mark upvalue */\n  }\n  return 1 + cl->nupvalues;\n}\n\n\n/*\n** Traverse a thread, marking the elements in the stack up to its top\n** and cleaning the rest of the stack in the final traversal. That\n** ensures that the entire stack have valid (non-dead) objects.\n** Threads have no barriers. In gen. mode, old threads must be visited\n** at every cycle, because they might point to young objects.  In inc.\n** mode, the thread can still be modified before the end of the cycle,\n** and therefore it must be visited again in the atomic phase. To ensure\n** these visits, threads must return to a gray list if they are not new\n** (which can only happen in generational mode) or if the traverse is in\n** the propagate phase (which can only happen in incremental mode).\n*/\nstatic l_mem traversethread (global_State *g, lua_State *th) {\n  UpVal *uv;\n  StkId o = th->stack.p;\n  if (isold(th) || g->gcstate == GCSpropagate)\n    linkgclist(th, g->grayagain);  /* insert into 'grayagain' list */\n  if (o == NULL)\n    return 0;  /* stack not completely built yet */\n  lua_assert(g->gcstate == GCSatomic ||\n             th->openupval == NULL || isintwups(th));\n  for (; o < th->top.p; o++)  /* mark live elements in the stack */\n    markvalue(g, s2v(o));\n  for (uv = th->openupval; uv != NULL; uv = uv->u.open.next)\n    markobject(g, uv);  /* open upvalues cannot be collected */\n  if (g->gcstate == GCSatomic) {  /* final traversal? */\n    if (!g->gcemergency)\n      luaD_shrinkstack(th); /* do not change stack in emergency cycle */\n    for (o = th->top.p; o < th->stack_last.p + EXTRA_STACK; o++)\n      setnilvalue(s2v(o));  /* clear dead stack slice */\n    /* 'remarkupvals' may have removed thread from 'twups' list */\n    if (!isintwups(th) && th->openupval != NULL) {\n      th->twups = g->twups;  /* link it back to the list */\n      g->twups = th;\n    }\n  }\n  return 1 + (th->top.p - th->stack.p);\n}\n\n\n/*\n** traverse one gray object, turning it to black. Return an estimate\n** of the number of slots traversed.\n*/\nstatic l_mem propagatemark (global_State *g) {\n  GCObject *o = g->gray;\n  nw2black(o);\n  g->gray = *getgclist(o);  /* remove from 'gray' list */\n  switch (o->tt) {\n    case LUA_VTABLE: return traversetable(g, gco2t(o));\n    case LUA_VUSERDATA: return traverseudata(g, gco2u(o));\n    case LUA_VLCL: return traverseLclosure(g, gco2lcl(o));\n    case LUA_VCCL: return traverseCclosure(g, gco2ccl(o));\n    case LUA_VPROTO: return traverseproto(g, gco2p(o));\n    case LUA_VTHREAD: return traversethread(g, gco2th(o));\n    default: lua_assert(0); return 0;\n  }\n}\n\n\nstatic void propagateall (global_State *g) {\n  while (g->gray)\n    propagatemark(g);\n}\n\n\n/*\n** Traverse all ephemeron tables propagating marks from keys to values.\n** Repeat until it converges, that is, nothing new is marked. 'dir'\n** inverts the direction of the traversals, trying to speed up\n** convergence on chains in the same table.\n*/\nstatic void convergeephemerons (global_State *g) {\n  int changed;\n  int dir = 0;\n  do {\n    GCObject *w;\n    GCObject *next = g->ephemeron;  /* get ephemeron list */\n    g->ephemeron = NULL;  /* tables may return to this list when traversed */\n    changed = 0;\n    while ((w = next) != NULL) {  /* for each ephemeron table */\n      Table *h = gco2t(w);\n      next = h->gclist;  /* list is rebuilt during loop */\n      nw2black(h);  /* out of the list (for now) */\n      if (traverseephemeron(g, h, dir)) {  /* marked some value? */\n        propagateall(g);  /* propagate changes */\n        changed = 1;  /* will have to revisit all ephemeron tables */\n      }\n    }\n    dir = !dir;  /* invert direction next time */\n  } while (changed);  /* repeat until no more changes */\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Sweep Functions\n** =======================================================\n*/\n\n\n/*\n** clear entries with unmarked keys from all weaktables in list 'l'\n*/\nstatic void clearbykeys (global_State *g, GCObject *l) {\n  for (; l; l = gco2t(l)->gclist) {\n    Table *h = gco2t(l);\n    Node *limit = gnodelast(h);\n    Node *n;\n    for (n = gnode(h, 0); n < limit; n++) {\n      if (iscleared(g, gckeyN(n)))  /* unmarked key? */\n        setempty(gval(n));  /* remove entry */\n      if (isempty(gval(n)))  /* is entry empty? */\n        clearkey(n);  /* clear its key */\n    }\n  }\n}\n\n\n/*\n** clear entries with unmarked values from all weaktables in list 'l' up\n** to element 'f'\n*/\nstatic void clearbyvalues (global_State *g, GCObject *l, GCObject *f) {\n  for (; l != f; l = gco2t(l)->gclist) {\n    Table *h = gco2t(l);\n    Node *n, *limit = gnodelast(h);\n    unsigned int i;\n    unsigned int asize = h->asize;\n    for (i = 0; i < asize; i++) {\n      GCObject *o = gcvalarr(h, i);\n      if (iscleared(g, o))  /* value was collected? */\n        *getArrTag(h, i) = LUA_VEMPTY;  /* remove entry */\n    }\n    for (n = gnode(h, 0); n < limit; n++) {\n      if (iscleared(g, gcvalueN(gval(n))))  /* unmarked value? */\n        setempty(gval(n));  /* remove entry */\n      if (isempty(gval(n)))  /* is entry empty? */\n        clearkey(n);  /* clear its key */\n    }\n  }\n}\n\n\nstatic void freeupval (lua_State *L, UpVal *uv) {\n  if (upisopen(uv))\n    luaF_unlinkupval(uv);\n  luaM_free(L, uv);\n}\n\n\nstatic void freeobj (lua_State *L, GCObject *o) {\n  assert_code(l_mem newmem = gettotalbytes(G(L)) - objsize(o));\n  switch (o->tt) {\n    case LUA_VPROTO:\n      luaF_freeproto(L, gco2p(o));\n      break;\n    case LUA_VUPVAL:\n      freeupval(L, gco2upv(o));\n      break;\n    case LUA_VLCL: {\n      LClosure *cl = gco2lcl(o);\n      luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));\n      break;\n    }\n    case LUA_VCCL: {\n      CClosure *cl = gco2ccl(o);\n      luaM_freemem(L, cl, sizeCclosure(cl->nupvalues));\n      break;\n    }\n    case LUA_VTABLE:\n      luaH_free(L, gco2t(o));\n      break;\n    case LUA_VTHREAD:\n      luaE_freethread(L, gco2th(o));\n      break;\n    case LUA_VUSERDATA: {\n      Udata *u = gco2u(o);\n      luaM_freemem(L, o, sizeudata(u->nuvalue, u->len));\n      break;\n    }\n    case LUA_VSHRSTR: {\n      TString *ts = gco2ts(o);\n      luaS_remove(L, ts);  /* remove it from hash table */\n      luaM_freemem(L, ts, sizestrshr(cast_uint(ts->shrlen)));\n      break;\n    }\n    case LUA_VLNGSTR: {\n      TString *ts = gco2ts(o);\n      if (ts->shrlen == LSTRMEM)  /* must free external string? */\n        (*ts->falloc)(ts->ud, ts->contents, ts->u.lnglen + 1, 0);\n      luaM_freemem(L, ts, luaS_sizelngstr(ts->u.lnglen, ts->shrlen));\n      break;\n    }\n    default: lua_assert(0);\n  }\n  lua_assert(gettotalbytes(G(L)) == newmem);\n}\n\n\n/*\n** sweep at most 'countin' elements from a list of GCObjects erasing dead\n** objects, where a dead object is one marked with the old (non current)\n** white; change all non-dead objects back to white (and new), preparing\n** for next collection cycle. Return where to continue the traversal or\n** NULL if list is finished.\n*/\nstatic GCObject **sweeplist (lua_State *L, GCObject **p, l_mem countin) {\n  global_State *g = G(L);\n  int ow = otherwhite(g);\n  int white = luaC_white(g);  /* current white */\n  while (*p != NULL && countin-- > 0) {\n    GCObject *curr = *p;\n    int marked = curr->marked;\n    if (isshared(curr))\n      p = &curr->next;\n    else if (isdeadm(ow, marked)) {  /* is 'curr' dead? */\n      *p = curr->next;  /* remove 'curr' from list */\n      freeobj(L, curr);  /* erase 'curr' */\n    }\n    else {  /* change mark to 'white' and age to 'new' */\n      curr->marked = cast_byte((marked & ~maskgcbits) | white | G_NEW);\n      p = &curr->next;  /* go to next element */\n    }\n  }\n  return (*p == NULL) ? NULL : p;\n}\n\n\n/*\n** sweep a list until a live object (or end of list)\n*/\nstatic GCObject **sweeptolive (lua_State *L, GCObject **p) {\n  GCObject **old = p;\n  do {\n    p = sweeplist(L, p, 1);\n  } while (p == old);\n  return p;\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Finalization\n** =======================================================\n*/\n\n/*\n** If possible, shrink string table.\n*/\nstatic void checkSizes (lua_State *L, global_State *g) {\n  if (!g->gcemergency) {\n    if (g->strt.nuse < g->strt.size / 4)  /* string table too big? */\n      luaS_resize(L, g->strt.size / 2);\n  }\n}\n\n\n/*\n** Get the next udata to be finalized from the 'tobefnz' list, and\n** link it back into the 'allgc' list.\n*/\nstatic GCObject *udata2finalize (global_State *g) {\n  GCObject *o = g->tobefnz;  /* get first element */\n  lua_assert(tofinalize(o));\n  g->tobefnz = o->next;  /* remove it from 'tobefnz' list */\n  o->next = g->allgc;  /* return it to 'allgc' list */\n  g->allgc = o;\n  resetbit(o->marked, FINALIZEDBIT);  /* object is \"normal\" again */\n  if (issweepphase(g))\n    makewhite(g, o);  /* \"sweep\" object */\n  else if (getage(o) == G_OLD1)\n    g->firstold1 = o;  /* it is the first OLD1 object in the list */\n  return o;\n}\n\n\nstatic void dothecall (lua_State *L, void *ud) {\n  UNUSED(ud);\n  luaD_callnoyield(L, L->top.p - 2, 0);\n}\n\n\nstatic void GCTM (lua_State *L) {\n  global_State *g = G(L);\n  const TValue *tm;\n  TValue v;\n  lua_assert(!g->gcemergency);\n  setgcovalue(L, &v, udata2finalize(g));\n  tm = luaT_gettmbyobj(L, &v, TM_GC);\n  if (!notm(tm)) {  /* is there a finalizer? */\n    TStatus status;\n    lu_byte oldah = L->allowhook;\n    lu_byte oldgcstp  = g->gcstp;\n    g->gcstp |= GCSTPGC;  /* avoid GC steps */\n    L->allowhook = 0;  /* stop debug hooks during GC metamethod */\n    setobj2s(L, L->top.p++, tm);  /* push finalizer... */\n    setobj2s(L, L->top.p++, &v);  /* ... and its argument */\n    L->ci->callstatus |= CIST_FIN;  /* will run a finalizer */\n    status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top.p - 2), 0);\n    L->ci->callstatus &= ~CIST_FIN;  /* not running a finalizer anymore */\n    L->allowhook = oldah;  /* restore hooks */\n    g->gcstp = oldgcstp;  /* restore state */\n    if (l_unlikely(status != LUA_OK)) {  /* error while running __gc? */\n      luaE_warnerror(L, \"__gc\");\n      L->top.p--;  /* pops error object */\n    }\n  }\n}\n\n\n/*\n** call all pending finalizers\n*/\nstatic void callallpendingfinalizers (lua_State *L) {\n  global_State *g = G(L);\n  while (g->tobefnz)\n    GCTM(L);\n}\n\n\n/*\n** find last 'next' field in list 'p' list (to add elements in its end)\n*/\nstatic GCObject **findlast (GCObject **p) {\n  while (*p != NULL)\n    p = &(*p)->next;\n  return p;\n}\n\n\n/*\n** Move all unreachable objects (or 'all' objects) that need\n** finalization from list 'finobj' to list 'tobefnz' (to be finalized).\n** (Note that objects after 'finobjold1' cannot be white, so they\n** don't need to be traversed. In incremental mode, 'finobjold1' is NULL,\n** so the whole list is traversed.)\n*/\nstatic void separatetobefnz (global_State *g, int all) {\n  GCObject *curr;\n  GCObject **p = &g->finobj;\n  GCObject **lastnext = findlast(&g->tobefnz);\n  while ((curr = *p) != g->finobjold1) {  /* traverse all finalizable objects */\n    lua_assert(tofinalize(curr));\n    if (!(iswhite(curr) || all))  /* not being collected? */\n      p = &curr->next;  /* don't bother with it */\n    else {\n      if (curr == g->finobjsur)  /* removing 'finobjsur'? */\n        g->finobjsur = curr->next;  /* correct it */\n      *p = curr->next;  /* remove 'curr' from 'finobj' list */\n      curr->next = *lastnext;  /* link at the end of 'tobefnz' list */\n      *lastnext = curr;\n      lastnext = &curr->next;\n    }\n  }\n}\n\n\n/*\n** If pointer 'p' points to 'o', move it to the next element.\n*/\nstatic void checkpointer (GCObject **p, GCObject *o) {\n  if (o == *p)\n    *p = o->next;\n}\n\n\n/*\n** Correct pointers to objects inside 'allgc' list when\n** object 'o' is being removed from the list.\n*/\nstatic void correctpointers (global_State *g, GCObject *o) {\n  checkpointer(&g->survival, o);\n  checkpointer(&g->old1, o);\n  checkpointer(&g->reallyold, o);\n  checkpointer(&g->firstold1, o);\n}\n\n\n/*\n** if object 'o' has a finalizer, remove it from 'allgc' list (must\n** search the list to find it) and link it in 'finobj' list.\n*/\nvoid luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {\n  global_State *g = G(L);\n  if (tofinalize(o) ||                 /* obj. is already marked... */\n      gfasttm(g, mt, TM_GC) == NULL ||    /* or has no finalizer... */\n      (g->gcstp & GCSTPCLS))                   /* or closing state? */\n    return;  /* nothing to be done */\n  else {  /* move 'o' to 'finobj' list */\n    GCObject **p;\n    if (issweepphase(g)) {\n      makewhite(g, o);  /* \"sweep\" object 'o' */\n      if (g->sweepgc == &o->next)  /* should not remove 'sweepgc' object */\n        g->sweepgc = sweeptolive(L, g->sweepgc);  /* change 'sweepgc' */\n    }\n    else\n      correctpointers(g, o);\n    /* search for pointer pointing to 'o' */\n    for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }\n    *p = o->next;  /* remove 'o' from 'allgc' list */\n    o->next = g->finobj;  /* link it in 'finobj' list */\n    g->finobj = o;\n    l_setbit(o->marked, FINALIZEDBIT);  /* mark it as such */\n  }\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Generational Collector\n** =======================================================\n*/\n\n/*\n** Fields 'GCmarked' and 'GCmajorminor' are used to control the pace and\n** the mode of the collector. They play several roles, depending on the\n** mode of the collector:\n** * KGC_INC:\n**     GCmarked: number of marked bytes during a cycle.\n**     GCmajorminor: not used.\n** * KGC_GENMINOR\n**     GCmarked: number of bytes that became old since last major collection.\n**     GCmajorminor: number of bytes marked in last major collection.\n** * KGC_GENMAJOR\n**     GCmarked: number of bytes that became old since last major collection.\n**     GCmajorminor: number of bytes marked in last major collection.\n*/\n\n\n/*\n** Set the \"time\" to wait before starting a new incremental cycle;\n** cycle will start when number of bytes in use hits the threshold of\n** approximately (marked * pause / 100).\n*/\nstatic void setpause (global_State *g) {\n  l_mem threshold = applygcparam(g, PAUSE, g->GCmarked);\n  l_mem debt = threshold - gettotalbytes(g);\n  if (debt < 0) debt = 0;\n  luaE_setdebt(g, debt);\n}\n\n\n/*\n** Sweep a list of objects to enter generational mode.  Deletes dead\n** objects and turns the non dead to old. All non-dead threads---which\n** are now old---must be in a gray list. Everything else is not in a\n** gray list. Open upvalues are also kept gray.\n*/\nstatic void sweep2old (lua_State *L, GCObject **p) {\n  GCObject *curr;\n  global_State *g = G(L);\n  while ((curr = *p) != NULL) {\n    if (isshared(curr))\n       p = &curr->next;  /* go to next element */\n    else if (iswhite(curr)) {  /* is 'curr' dead? */\n      lua_assert(isdead(g, curr));\n      *p = curr->next;  /* remove 'curr' from list */\n      freeobj(L, curr);  /* erase 'curr' */\n    }\n    else {  /* all surviving objects become old */\n      setage(curr, G_OLD);\n      if (curr->tt == LUA_VTHREAD) {  /* threads must be watched */\n        lua_State *th = gco2th(curr);\n        linkgclist(th, g->grayagain);  /* insert into 'grayagain' list */\n      }\n      else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr)))\n        set2gray(curr);  /* open upvalues are always gray */\n      else  /* everything else is black */\n        nw2black(curr);\n      p = &curr->next;  /* go to next element */\n    }\n  }\n}\n\n\n/*\n** Sweep for generational mode. Delete dead objects. (Because the\n** collection is not incremental, there are no \"new white\" objects\n** during the sweep. So, any white object must be dead.) For\n** non-dead objects, advance their ages and clear the color of\n** new objects. (Old objects keep their colors.)\n** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced\n** here, because these old-generation objects are usually not swept\n** here.  They will all be advanced in 'correctgraylist'. That function\n** will also remove objects turned white here from any gray list.\n*/\nstatic GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p,\n                            GCObject *limit, GCObject **pfirstold1,\n                            l_mem *paddedold) {\n  static const lu_byte nextage[] = {\n    G_SURVIVAL,  /* from G_NEW */\n    G_OLD1,      /* from G_SURVIVAL */\n    G_OLD1,      /* from G_OLD0 */\n    G_OLD,       /* from G_OLD1 */\n    G_OLD,       /* from G_OLD (do not change) */\n    G_TOUCHED1,  /* from G_TOUCHED1 (do not change) */\n    G_TOUCHED2   /* from G_TOUCHED2 (do not change) */\n  };\n  l_mem addedold = 0;\n  int white = luaC_white(g);\n  GCObject *curr;\n  while ((curr = *p) != limit) {\n    if (isshared(curr))\n      p = &curr->next;  /* go to next element */\n    else if (iswhite(curr)) {  /* is 'curr' dead? */\n      lua_assert(!isold(curr) && isdead(g, curr));\n      *p = curr->next;  /* remove 'curr' from list */\n      freeobj(L, curr);  /* erase 'curr' */\n    }\n    else {  /* correct mark and age */\n      int age = getage(curr);\n      if (age == G_NEW) {  /* new objects go back to white */\n        int marked = curr->marked & ~maskgcbits;  /* erase GC bits */\n        curr->marked = cast_byte(marked | G_SURVIVAL | white);\n      }\n      else {  /* all other objects will be old, and so keep their color */\n        lua_assert(age != G_OLD1);  /* advanced in 'markold' */\n        setage(curr, nextage[age]);\n        if (getage(curr) == G_OLD1) {\n          addedold += objsize(curr);  /* bytes becoming old */\n          if (*pfirstold1 == NULL)\n            *pfirstold1 = curr;  /* first OLD1 object in the list */\n        }\n      }\n      p = &curr->next;  /* go to next element */\n    }\n  }\n  *paddedold += addedold;\n  return p;\n}\n\n\n/*\n** Correct a list of gray objects. Return a pointer to the last element\n** left on the list, so that we can link another list to the end of\n** this one.\n** Because this correction is done after sweeping, young objects might\n** be turned white and still be in the list. They are only removed.\n** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list;\n** Non-white threads also remain on the list. 'TOUCHED2' objects and\n** anything else become regular old, are marked black, and are removed\n** from the list.\n*/\nstatic GCObject **correctgraylist (GCObject **p) {\n  GCObject *curr;\n  while ((curr = *p) != NULL) {\n    GCObject **next = getgclist(curr);\n    if (iswhite(curr))\n      goto remove;  /* remove all white objects */\n    else if (getage(curr) == G_TOUCHED1) {  /* touched in this cycle? */\n      lua_assert(isgray(curr));\n      nw2black(curr);  /* make it black, for next barrier */\n      setage(curr, G_TOUCHED2);\n      goto remain;  /* keep it in the list and go to next element */\n    }\n    else if (curr->tt == LUA_VTHREAD) {\n      lua_assert(isgray(curr));\n      goto remain;  /* keep non-white threads on the list */\n    }\n    else {  /* everything else is removed */\n      lua_assert(isold(curr));  /* young objects should be white here */\n      if (getage(curr) == G_TOUCHED2)  /* advance from TOUCHED2... */\n        setage(curr, G_OLD);  /* ... to OLD */\n      nw2black(curr);  /* make object black (to be removed) */\n      goto remove;\n    }\n    remove: *p = *next; continue;\n    remain: p = next; continue;\n  }\n  return p;\n}\n\n\n/*\n** Correct all gray lists, coalescing them into 'grayagain'.\n*/\nstatic void correctgraylists (global_State *g) {\n  GCObject **list = correctgraylist(&g->grayagain);\n  *list = g->weak; g->weak = NULL;\n  list = correctgraylist(list);\n  *list = g->allweak; g->allweak = NULL;\n  list = correctgraylist(list);\n  *list = g->ephemeron; g->ephemeron = NULL;\n  correctgraylist(list);\n}\n\n\n/*\n** Mark black 'OLD1' objects when starting a new young collection.\n** Gray objects are already in some gray list, and so will be visited in\n** the atomic step.\n*/\nstatic void markold (global_State *g, GCObject *from, GCObject *to) {\n  GCObject *p;\n  for (p = from; p != to; p = p->next) {\n    if (getage(p) == G_OLD1) {\n      lua_assert(!iswhite(p));\n      setage(p, G_OLD);  /* now they are old */\n      if (isblack(p))\n        reallymarkobject(g, p);\n    }\n  }\n}\n\n\n/*\n** Finish a young-generation collection.\n*/\nstatic void finishgencycle (lua_State *L, global_State *g) {\n  correctgraylists(g);\n  checkSizes(L, g);\n  g->gcstate = GCSpropagate;  /* skip restart */\n  if (!g->gcemergency && luaD_checkminstack(L))\n    callallpendingfinalizers(L);\n}\n\n\n/*\n** Shifts from a minor collection to major collections. It starts in\n** the \"sweep all\" state to clear all objects, which are mostly black\n** in generational mode.\n*/\nstatic void minor2inc (lua_State *L, global_State *g, lu_byte kind) {\n  g->GCmajorminor = g->GCmarked;  /* number of live bytes */\n  g->gckind = kind;\n  g->reallyold = g->old1 = g->survival = NULL;\n  g->finobjrold = g->finobjold1 = g->finobjsur = NULL;\n  entersweep(L);  /* continue as an incremental cycle */\n  /* set a debt equal to the step size */\n  luaE_setdebt(g, applygcparam(g, STEPSIZE, 100));\n}\n\n\n/*\n** Decide whether to shift to major mode. It shifts if the accumulated\n** number of added old bytes (counted in 'GCmarked') is larger than\n** 'minormajor'% of the number of lived bytes after the last major\n** collection. (This number is kept in 'GCmajorminor'.)\n*/\nstatic int checkminormajor (global_State *g) {\n  l_mem limit = applygcparam(g, MINORMAJOR, g->GCmajorminor);\n  if (limit == 0)\n    return 0;  /* special case: 'minormajor' 0 stops major collections */\n  return (g->GCmarked >= limit);\n}\n\n/*\n** Does a young collection. First, mark 'OLD1' objects. Then does the\n** atomic step. Then, check whether to continue in minor mode. If so,\n** sweep all lists and advance pointers. Finally, finish the collection.\n*/\nstatic void youngcollection (lua_State *L, global_State *g) {\n  l_mem addedold1 = 0;\n  l_mem marked = g->GCmarked;  /* preserve 'g->GCmarked' */\n  GCObject **psurvival;  /* to point to first non-dead survival object */\n  GCObject *dummy;  /* dummy out parameter to 'sweepgen' */\n  lua_assert(g->gcstate == GCSpropagate);\n  if (g->firstold1) {  /* are there regular OLD1 objects? */\n    markold(g, g->firstold1, g->reallyold);  /* mark them */\n    g->firstold1 = NULL;  /* no more OLD1 objects (for now) */\n  }\n  markold(g, g->finobj, g->finobjrold);\n  markold(g, g->tobefnz, NULL);\n\n  atomic(L);  /* will lose 'g->marked' */\n\n  /* sweep nursery and get a pointer to its last live element */\n  g->gcstate = GCSswpallgc;\n  psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1, &addedold1);\n  /* sweep 'survival' */\n  sweepgen(L, g, psurvival, g->old1, &g->firstold1, &addedold1);\n  g->reallyold = g->old1;\n  g->old1 = *psurvival;  /* 'survival' survivals are old now */\n  g->survival = g->allgc;  /* all news are survivals */\n\n  /* repeat for 'finobj' lists */\n  dummy = NULL;  /* no 'firstold1' optimization for 'finobj' lists */\n  psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy, &addedold1);\n  /* sweep 'survival' */\n  sweepgen(L, g, psurvival, g->finobjold1, &dummy, &addedold1);\n  g->finobjrold = g->finobjold1;\n  g->finobjold1 = *psurvival;  /* 'survival' survivals are old now */\n  g->finobjsur = g->finobj;  /* all news are survivals */\n\n  sweepgen(L, g, &g->tobefnz, NULL, &dummy, &addedold1);\n\n  /* keep total number of added old1 bytes */\n  g->GCmarked = marked + addedold1;\n\n  /* decide whether to shift to major mode */\n  if (checkminormajor(g)) {\n    minor2inc(L, g, KGC_GENMAJOR);  /* go to major mode */\n    g->GCmarked = 0;  /* avoid pause in first major cycle (see 'setpause') */\n  }\n  else\n    finishgencycle(L, g);  /* still in minor mode; finish it */\n}\n\n\n/*\n** Clears all gray lists, sweeps objects, and prepare sublists to enter\n** generational mode. The sweeps remove dead objects and turn all\n** surviving objects to old. Threads go back to 'grayagain'; everything\n** else is turned black (not in any gray list).\n*/\nstatic void atomic2gen (lua_State *L, global_State *g) {\n  cleargraylists(g);\n  /* sweep all elements making them old */\n  g->gcstate = GCSswpallgc;\n  sweep2old(L, &g->allgc);\n  /* everything alive now is old */\n  g->reallyold = g->old1 = g->survival = g->allgc;\n  g->firstold1 = NULL;  /* there are no OLD1 objects anywhere */\n\n  /* repeat for 'finobj' lists */\n  sweep2old(L, &g->finobj);\n  g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj;\n\n  sweep2old(L, &g->tobefnz);\n\n  g->gckind = KGC_GENMINOR;\n  g->GCmajorminor = g->GCmarked;  /* \"base\" for number of bytes */\n  g->GCmarked = 0;  /* to count the number of added old1 bytes */\n  finishgencycle(L, g);\n}\n\n\n/*\n** Set debt for the next minor collection, which will happen when\n** total number of bytes grows 'genminormul'% in relation to\n** the base, GCmajorminor, which is the number of bytes being used\n** after the last major collection.\n*/\nstatic void setminordebt (global_State *g) {\n  luaE_setdebt(g, applygcparam(g, MINORMUL, g->GCmajorminor));\n}\n\n\n/*\n** Enter generational mode. Must go until the end of an atomic cycle\n** to ensure that all objects are correctly marked and weak tables\n** are cleared. Then, turn all objects into old and finishes the\n** collection.\n*/\nstatic void entergen (lua_State *L, global_State *g) {\n  luaC_runtilstate(L, GCSpause, 1);  /* prepare to start a new cycle */\n  luaC_runtilstate(L, GCSpropagate, 1);  /* start new cycle */\n  atomic(L);  /* propagates all and then do the atomic stuff */\n  atomic2gen(L, g);\n  setminordebt(g);  /* set debt assuming next cycle will be minor */\n}\n\n\n/*\n** Change collector mode to 'newmode'.\n*/\nvoid luaC_changemode (lua_State *L, int newmode) {\n  global_State *g = G(L);\n  if (g->gckind == KGC_GENMAJOR)  /* doing major collections? */\n    g->gckind = KGC_INC;  /* already incremental but in name */\n  if (newmode != g->gckind) {  /* does it need to change? */\n    if (newmode == KGC_INC)  /* entering incremental mode? */\n      minor2inc(L, g, KGC_INC);  /* entering incremental mode */\n    else {\n      lua_assert(newmode == KGC_GENMINOR);\n      entergen(L, g);\n    }\n  }\n}\n\n\n/*\n** Does a full collection in generational mode.\n*/\nstatic void fullgen (lua_State *L, global_State *g) {\n  minor2inc(L, g, KGC_INC);\n  entergen(L, g);\n}\n\n\n/*\n** After an atomic incremental step from a major collection,\n** check whether collector could return to minor collections.\n** It checks whether the number of bytes 'tobecollected'\n** is greater than 'majorminor'% of the number of bytes added\n** since the last collection ('addedbytes').\n*/\nstatic int checkmajorminor (lua_State *L, global_State *g) {\n  if (g->gckind == KGC_GENMAJOR) {  /* generational mode? */\n    l_mem numbytes = gettotalbytes(g);\n    l_mem addedbytes = numbytes - g->GCmajorminor;\n    l_mem limit = applygcparam(g, MAJORMINOR, addedbytes);\n    l_mem tobecollected = numbytes - g->GCmarked;\n    if (tobecollected > limit) {\n      atomic2gen(L, g);  /* return to generational mode */\n      setminordebt(g);\n      return 1;  /* exit incremental collection */\n    }\n  }\n  g->GCmajorminor = g->GCmarked;  /* prepare for next collection */\n  return 0;  /* stay doing incremental collections */\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** GC control\n** =======================================================\n*/\n\n\n/*\n** Enter first sweep phase.\n** The call to 'sweeptolive' makes the pointer point to an object\n** inside the list (instead of to the header), so that the real sweep do\n** not need to skip objects created between \"now\" and the start of the\n** real sweep.\n*/\nstatic void entersweep (lua_State *L) {\n  global_State *g = G(L);\n  g->gcstate = GCSswpallgc;\n  lua_assert(g->sweepgc == NULL);\n  g->sweepgc = sweeptolive(L, &g->allgc);\n}\n\n\n/*\n** Delete all objects in list 'p' until (but not including) object\n** 'limit'.\n*/\nstatic void deletelist (lua_State *L, GCObject *p, GCObject *limit) {\n  while (p != limit) {\n    GCObject *next = p->next;\n    freeobj(L, p);\n    p = next;\n  }\n}\n\n\n/*\n** Call all finalizers of the objects in the given Lua state, and\n** then free all objects, except for the main thread.\n*/\nvoid luaC_freeallobjects (lua_State *L) {\n  global_State *g = G(L);\n  g->gcstp = GCSTPCLS;  /* no extra finalizers after here */\n  luaC_changemode(L, KGC_INC);\n  separatetobefnz(g, 1);  /* separate all objects with finalizers */\n  lua_assert(g->finobj == NULL);\n  callallpendingfinalizers(L);\n  deletelist(L, g->allgc, obj2gco(mainthread(g)));\n  lua_assert(g->finobj == NULL);  /* no new finalizers */\n  deletelist(L, g->fixedgc, NULL);  /* collect fixed objects */\n  lua_assert(g->strt.nuse == 0);\n}\n\n\nstatic void atomic (lua_State *L) {\n  global_State *g = G(L);\n  GCObject *origweak, *origall;\n  GCObject *grayagain = g->grayagain;  /* save original list */\n  g->grayagain = NULL;\n  lua_assert(g->ephemeron == NULL && g->weak == NULL);\n  lua_assert(!iswhite(mainthread(g)));\n  g->gcstate = GCSatomic;\n  markobject(g, L);  /* mark running thread */\n  /* registry and global metatables may be changed by API */\n  markvalue(g, &g->l_registry);\n  markmt(g);  /* mark global metatables */\n  propagateall(g);  /* empties 'gray' list */\n  /* remark occasional upvalues of (maybe) dead threads */\n  remarkupvals(g);\n  propagateall(g);  /* propagate changes */\n  g->gray = grayagain;\n  propagateall(g);  /* traverse 'grayagain' list */\n  convergeephemerons(g);\n  /* at this point, all strongly accessible objects are marked. */\n  /* Clear values from weak tables, before checking finalizers */\n  clearbyvalues(g, g->weak, NULL);\n  clearbyvalues(g, g->allweak, NULL);\n  origweak = g->weak; origall = g->allweak;\n  separatetobefnz(g, 0);  /* separate objects to be finalized */\n  markbeingfnz(g);  /* mark objects that will be finalized */\n  propagateall(g);  /* remark, to propagate 'resurrection' */\n  convergeephemerons(g);\n  /* at this point, all resurrected objects are marked. */\n  /* remove dead objects from weak tables */\n  clearbykeys(g, g->ephemeron);  /* clear keys from all ephemeron */\n  clearbykeys(g, g->allweak);  /* clear keys from all 'allweak' */\n  /* clear values from resurrected weak tables */\n  clearbyvalues(g, g->weak, origweak);\n  clearbyvalues(g, g->allweak, origall);\n  luaS_clearcache(g);\n  g->currentwhite = cast_byte(otherwhite(g));  /* flip current white */\n  lua_assert(g->gray == NULL);\n}\n\n\n/*\n** Do a sweep step. The normal case (not fast) sweeps at most GCSWEEPMAX\n** elements. The fast case sweeps the whole list.\n*/\nstatic void sweepstep (lua_State *L, global_State *g,\n                       lu_byte nextstate, GCObject **nextlist, int fast) {\n  if (g->sweepgc)\n    g->sweepgc = sweeplist(L, g->sweepgc, fast ? MAX_LMEM : GCSWEEPMAX);\n  else {  /* enter next state */\n    g->gcstate = nextstate;\n    g->sweepgc = nextlist;\n  }\n}\n\n\n/*\n** Performs one incremental \"step\" in an incremental garbage collection.\n** For indivisible work, a step goes to the next state. When marking\n** (propagating), a step traverses one object. When sweeping, a step\n** sweeps GCSWEEPMAX objects, to avoid a big overhead for sweeping\n** objects one by one. (Sweeping is inexpensive, no matter the\n** object.) When 'fast' is true, 'singlestep' tries to finish a state\n** \"as fast as possible\". In particular, it skips the propagation\n** phase and leaves all objects to be traversed by the atomic phase:\n** That avoids traversing twice some objects, such as threads and\n** weak tables.\n*/\n\n#define step2pause\t-3  /* finished collection; entered pause state */\n#define atomicstep\t-2  /* atomic step */\n#define step2minor\t-1  /* moved to minor collections */\n\n\nstatic l_mem singlestep (lua_State *L, int fast) {\n  global_State *g = G(L);\n  l_mem stepresult;\n  lua_assert(!g->gcstopem);  /* collector is not reentrant */\n  g->gcstopem = 1;  /* no emergency collections while collecting */\n  switch (g->gcstate) {\n    case GCSpause: {\n      restartcollection(g);\n      g->gcstate = GCSpropagate;\n      stepresult = 1;\n      break;\n    }\n    case GCSpropagate: {\n      if (fast || g->gray == NULL) {\n        g->gcstate = GCSenteratomic;  /* finish propagate phase */\n        stepresult = 1;\n      }\n      else\n        stepresult = propagatemark(g);  /* traverse one gray object */\n      break;\n    }\n    case GCSenteratomic: {\n      atomic(L);\n      if (checkmajorminor(L, g))\n        stepresult = step2minor;\n      else {\n        entersweep(L);\n        stepresult = atomicstep;\n      }\n      break;\n    }\n    case GCSswpallgc: {  /* sweep \"regular\" objects */\n      sweepstep(L, g, GCSswpfinobj, &g->finobj, fast);\n      stepresult = GCSWEEPMAX;\n      break;\n    }\n    case GCSswpfinobj: {  /* sweep objects with finalizers */\n      sweepstep(L, g, GCSswptobefnz, &g->tobefnz, fast);\n      stepresult = GCSWEEPMAX;\n      break;\n    }\n    case GCSswptobefnz: {  /* sweep objects to be finalized */\n      sweepstep(L, g, GCSswpend, NULL, fast);\n      stepresult = GCSWEEPMAX;\n      break;\n    }\n    case GCSswpend: {  /* finish sweeps */\n      checkSizes(L, g);\n      g->gcstate = GCScallfin;\n      stepresult = GCSWEEPMAX;\n      break;\n    }\n    case GCScallfin: {  /* call finalizers */\n      if (g->tobefnz && !g->gcemergency && luaD_checkminstack(L)) {\n        g->gcstopem = 0;  /* ok collections during finalizers */\n        GCTM(L);  /* call one finalizer */\n        stepresult = CWUFIN;\n      }\n      else {  /* no more finalizers or emergency mode or no enough stack\n                 to run finalizers */\n        g->gcstate = GCSpause;  /* finish collection */\n        stepresult = step2pause;\n      }\n      break;\n    }\n    default: lua_assert(0); return 0;\n  }\n  g->gcstopem = 0;\n  return stepresult;\n}\n\n\n/*\n** Advances the garbage collector until it reaches the given state.\n** (The option 'fast' is only for testing; in normal code, 'fast'\n** here is always true.)\n*/\nvoid luaC_runtilstate (lua_State *L, int state, int fast) {\n  global_State *g = G(L);\n  lua_assert(g->gckind == KGC_INC);\n  while (state != g->gcstate)\n    singlestep(L, fast);\n}\n\n\n\n/*\n** Performs a basic incremental step. The step size is\n** converted from bytes to \"units of work\"; then the function loops\n** running single steps until adding that many units of work or\n** finishing a cycle (pause state). Finally, it sets the debt that\n** controls when next step will be performed.\n*/\nstatic void incstep (lua_State *L, global_State *g) {\n  l_mem stepsize = applygcparam(g, STEPSIZE, 100);\n  l_mem work2do = applygcparam(g, STEPMUL, stepsize / cast_int(sizeof(void*)));\n  l_mem stres;\n  int fast = (work2do == 0);  /* special case: do a full collection */\n  do {  /* repeat until enough work */\n    stres = singlestep(L, fast);  /* perform one single step */\n    if (stres == step2minor)  /* returned to minor collections? */\n      return;  /* nothing else to be done here */\n    else if (stres == step2pause || (stres == atomicstep && !fast))\n      break;  /* end of cycle or atomic */\n    else\n      work2do -= stres;\n  } while (fast || work2do > 0);\n  if (g->gcstate == GCSpause)\n    setpause(g);  /* pause until next cycle */\n  else\n    luaE_setdebt(g, stepsize);\n}\n\n\n#if !defined(luai_tracegc)\n#define luai_tracegc(L,f)\t\t((void)0)\n#endif\n\n/*\n** Performs a basic GC step if collector is running. (If collector was\n** stopped by the user, set a reasonable debt to avoid it being called\n** at every single check.)\n*/\nvoid luaC_step (lua_State *L) {\n  global_State *g = G(L);\n  lua_assert(!g->gcemergency);\n  if (!gcrunning(g)) {  /* not running? */\n    if (g->gcstp & GCSTPUSR)  /* stopped by the user? */\n      luaE_setdebt(g, 20000);\n  }\n  else {\n    luai_tracegc(L, 1);  /* for internal debugging */\n    switch (g->gckind) {\n      case KGC_INC: case KGC_GENMAJOR:\n        incstep(L, g);\n        break;\n      case KGC_GENMINOR:\n        youngcollection(L, g);\n        setminordebt(g);\n        break;\n    }\n    luai_tracegc(L, 0);  /* for internal debugging */\n  }\n}\n\n\n/*\n** Perform a full collection in incremental mode.\n** Before running the collection, check 'keepinvariant'; if it is true,\n** there may be some objects marked as black, so the collector has\n** to sweep all objects to turn them back to white (as white has not\n** changed, nothing will be collected).\n*/\nstatic void fullinc (lua_State *L, global_State *g) {\n  if (keepinvariant(g))  /* black objects? */\n    entersweep(L); /* sweep everything to turn them back to white */\n  /* finish any pending sweep phase to start a new cycle */\n  luaC_runtilstate(L, GCSpause, 1);\n  luaC_runtilstate(L, GCScallfin, 1);  /* run up to finalizers */\n  luaC_runtilstate(L, GCSpause, 1);  /* finish collection */\n  setpause(g);\n}\n\n\n/*\n** Performs a full GC cycle; if 'isemergency', set a flag to avoid\n** some operations which could change the interpreter state in some\n** unexpected ways (running finalizers and shrinking some structures).\n*/\nvoid luaC_fullgc (lua_State *L, int isemergency) {\n  global_State *g = G(L);\n  lua_assert(!g->gcemergency);\n  g->gcemergency = cast_byte(isemergency);  /* set flag */\n  switch (g->gckind) {\n    case KGC_GENMINOR: fullgen(L, g); break;\n    case KGC_INC: fullinc(L, g); break;\n    case KGC_GENMAJOR:\n      g->gckind = KGC_INC;\n      fullinc(L, g);\n      g->gckind = KGC_GENMAJOR;\n      break;\n  }\n  g->gcemergency = 0;\n}\n\n/* }====================================================== */\n\n\n"
  },
  {
    "path": "3rd/lua/lgc.h",
    "content": "/*\n** $Id: lgc.h $\n** Garbage Collector\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lgc_h\n#define lgc_h\n\n\n#include <stddef.h>\n\n\n#include \"lobject.h\"\n#include \"lstate.h\"\n\n/*\n** Collectable objects may have one of three colors: white, which means\n** the object is not marked; gray, which means the object is marked, but\n** its references may be not marked; and black, which means that the\n** object and all its references are marked.  The main invariant of the\n** garbage collector, while marking objects, is that a black object can\n** never point to a white one. Moreover, any gray object must be in a\n** \"gray list\" (gray, grayagain, weak, allweak, ephemeron) so that it\n** can be visited again before finishing the collection cycle. (Open\n** upvalues are an exception to this rule, as they are attached to\n** a corresponding thread.)  These lists have no meaning when the\n** invariant is not being enforced (e.g., sweep phase).\n*/\n\n\n/*\n** Possible states of the Garbage Collector\n*/\n#define GCSpropagate\t0\n#define GCSenteratomic\t1\n#define GCSatomic\t2\n#define GCSswpallgc\t3\n#define GCSswpfinobj\t4\n#define GCSswptobefnz\t5\n#define GCSswpend\t6\n#define GCScallfin\t7\n#define GCSpause\t8\n\n\n#define issweepphase(g)  \\\n\t(GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend)\n\n\n/*\n** macro to tell when main invariant (white objects cannot point to black\n** ones) must be kept. During a collection, the sweep phase may break\n** the invariant, as objects turned white may point to still-black\n** objects. The invariant is restored when sweep ends and all objects\n** are white again.\n*/\n\n#define keepinvariant(g)\t((g)->gcstate <= GCSatomic)\n\n\n/*\n** some useful bit tricks\n*/\n#define resetbits(x,m)\t\t((x) &= cast_byte(~(m)))\n#define setbits(x,m)\t\t((x) |= (m))\n#define testbits(x,m)\t\t((x) & (m))\n#define bitmask(b)\t\t(1<<(b))\n#define bit2mask(b1,b2)\t\t(bitmask(b1) | bitmask(b2))\n#define l_setbit(x,b)\t\tsetbits(x, bitmask(b))\n#define resetbit(x,b)\t\tresetbits(x, bitmask(b))\n#define testbit(x,b)\t\ttestbits(x, bitmask(b))\n\n\n/*\n** Layout for bit use in 'marked' field. First three bits are\n** used for object \"age\" in generational mode. Last bit is used\n** by tests.\n*/\n#define WHITE0BIT\t3  /* object is white (type 0) */\n#define WHITE1BIT\t4  /* object is white (type 1) */\n#define BLACKBIT\t5  /* object is black */\n#define FINALIZEDBIT\t6  /* object has been marked for finalization */\n\n#define TESTBIT\t\t7\n\n\n\n#define WHITEBITS\tbit2mask(WHITE0BIT, WHITE1BIT)\n\n\n#define iswhite(x)      testbits((x)->marked, WHITEBITS)\n#define isblack(x)      testbit((x)->marked, BLACKBIT)\n#define isgray(x)  /* neither white nor black */  \\\n\t(!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT)))\n\n#define tofinalize(x)\ttestbit((x)->marked, FINALIZEDBIT)\n\n#define otherwhite(g)\t((g)->currentwhite ^ WHITEBITS)\n#define isdeadm(ow,m)\t((m) & (ow))\n#define isdead(g,v)\tisdeadm(otherwhite(g), (v)->marked)\n\n#define changewhite(x)\t((x)->marked ^= WHITEBITS)\n#define nw2black(x)  \\\n\tcheck_exp(!iswhite(x), l_setbit((x)->marked, BLACKBIT))\n\n#define luaC_white(g)\tcast_byte((g)->currentwhite & WHITEBITS)\n\n\n/* object age in generational mode */\n#define G_NEW\t\t0\t/* created in current cycle */\n#define G_SURVIVAL\t1\t/* created in previous cycle */\n#define G_OLD0\t\t2\t/* marked old by frw. barrier in this cycle */\n#define G_OLD1\t\t3\t/* first full cycle as old */\n#define G_OLD\t\t4\t/* really old object (not to be visited) */\n#define G_TOUCHED1\t5\t/* old object touched this cycle */\n#define G_TOUCHED2\t6\t/* old object touched in previous cycle */\n#define G_SHARED\t7\t/* object is shared */\n\n#define AGEBITS\t\t7  /* all age bits (111) */\n\n#define getage(o)\t((o)->marked & AGEBITS)\n#define setage(o,a)  ((o)->marked = cast_byte(((o)->marked & (~AGEBITS)) | a))\n#define isold(o)\t(getage(o) > G_SURVIVAL)\n\n#define isshared(x)     (getage(x) == G_SHARED)\n#define makeshared(x)   setage(x, G_SHARED)\n#define ispurewhite(x)  (iswhite(x) && !isshared(x))\n\n/*\n** In generational mode, objects are created 'new'. After surviving one\n** cycle, they become 'survival'. Both 'new' and 'survival' can point\n** to any other object, as they are traversed at the end of the cycle.\n** We call them both 'young' objects.\n** If a survival object survives another cycle, it becomes 'old1'.\n** 'old1' objects can still point to survival objects (but not to\n** new objects), so they still must be traversed. After another cycle\n** (that, being old, 'old1' objects will \"survive\" no matter what)\n** finally the 'old1' object becomes really 'old', and then they\n** are no more traversed.\n**\n** To keep its invariants, the generational mode uses the same barriers\n** also used by the incremental mode. If a young object is caught in a\n** forward barrier, it cannot become old immediately, because it can\n** still point to other young objects. Instead, it becomes 'old0',\n** which in the next cycle becomes 'old1'. So, 'old0' objects is\n** old but can point to new and survival objects; 'old1' is old\n** but cannot point to new objects; and 'old' cannot point to any\n** young object.\n**\n** If any old object ('old0', 'old1', 'old') is caught in a back\n** barrier, it becomes 'touched1' and goes into a gray list, to be\n** visited at the end of the cycle.  There it evolves to 'touched2',\n** which can point to survivals but not to new objects. In yet another\n** cycle then it becomes 'old' again.\n**\n** The generational mode must also control the colors of objects,\n** because of the barriers.  While the mutator is running, young objects\n** are kept white. 'old', 'old1', and 'touched2' objects are kept black,\n** as they cannot point to new objects; exceptions are threads and open\n** upvalues, which age to 'old1' and 'old' but are kept gray. 'old0'\n** objects may be gray or black, as in the incremental mode. 'touched1'\n** objects are kept gray, as they must be visited again at the end of\n** the cycle.\n*/\n\n\n/*\n** {======================================================\n** Default Values for GC parameters\n** =======================================================\n*/\n\n/*\n** Minor collections will shift to major ones after LUAI_MINORMAJOR%\n** bytes become old.\n*/\n#define LUAI_MINORMAJOR         70\n\n/*\n** Major collections will shift to minor ones after a collection\n** collects at least LUAI_MAJORMINOR% of the new bytes.\n*/\n#define LUAI_MAJORMINOR         50\n\n/*\n** A young (minor) collection will run after creating LUAI_GENMINORMUL%\n** new bytes.\n*/\n#define LUAI_GENMINORMUL         20\n\n\n/* incremental */\n\n/* Number of bytes must be LUAI_GCPAUSE% before starting new cycle */\n#define LUAI_GCPAUSE    250\n\n/*\n** Step multiplier: The collector handles LUAI_GCMUL% work units for\n** each new allocated word. (Each \"work unit\" corresponds roughly to\n** sweeping one object or traversing one slot.)\n*/\n#define LUAI_GCMUL      200\n\n/* How many bytes to allocate before next GC step */\n#define LUAI_GCSTEPSIZE\t(200 * sizeof(Table))\n\n\n#define setgcparam(g,p,v)  (g->gcparams[LUA_GCP##p] = luaO_codeparam(v))\n#define applygcparam(g,p,x)  luaO_applyparam(g->gcparams[LUA_GCP##p], x)\n\n/* }====================================================== */\n\n\n/*\n** Control when GC is running:\n*/\n#define GCSTPUSR\t1  /* bit true when GC stopped by user */\n#define GCSTPGC\t\t2  /* bit true when GC stopped by itself */\n#define GCSTPCLS\t4  /* bit true when closing Lua state */\n#define gcrunning(g)\t((g)->gcstp == 0)\n\n\n/*\n** Does one step of collection when debt becomes zero. 'pre'/'pos'\n** allows some adjustments to be done only when needed. macro\n** 'condchangemem' is used only for heavy tests (forcing a full\n** GC cycle on every opportunity)\n*/\n\n#if !defined(HARDMEMTESTS)\n#define condchangemem(L,pre,pos,emg)\t((void)0)\n#else\n#define condchangemem(L,pre,pos,emg)  \\\n\t{ if (gcrunning(G(L))) { pre; luaC_fullgc(L, emg); pos; } }\n#endif\n\n#define luaC_condGC(L,pre,pos) \\\n\t{ if (G(L)->GCdebt <= 0) { pre; luaC_step(L); pos;}; \\\n\t  condchangemem(L,pre,pos,0); }\n\n/* more often than not, 'pre'/'pos' are empty */\n#define luaC_checkGC(L)\t\tluaC_condGC(L,(void)0,(void)0)\n\n\n#define luaC_objbarrier(L,p,o) (  \\\n\t(isblack(p) && ispurewhite(o)) ? \\\n\tluaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0))\n\n#define luaC_barrier(L,p,v) (  \\\n\tiscollectable(v) ? luaC_objbarrier(L,p,gcvalue(v)) : cast_void(0))\n\n#define luaC_objbarrierback(L,p,o) (  \\\n\t(isblack(p) && ispurewhite(o)) ? luaC_barrierback_(L,p) : cast_void(0))\n\n#define luaC_barrierback(L,p,v) (  \\\n\tiscollectable(v) ? luaC_objbarrierback(L, p, gcvalue(v)) : cast_void(0))\n\nLUAI_FUNC void luaC_fix (lua_State *L, GCObject *o);\nLUAI_FUNC void luaC_freeallobjects (lua_State *L);\nLUAI_FUNC void luaC_step (lua_State *L);\nLUAI_FUNC void luaC_runtilstate (lua_State *L, int state, int fast);\nLUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);\nLUAI_FUNC GCObject *luaC_newobj (lua_State *L, lu_byte tt, size_t sz);\nLUAI_FUNC GCObject *luaC_newobjdt (lua_State *L, lu_byte tt, size_t sz,\n                                                 size_t offset);\nLUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);\nLUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);\nLUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);\nLUAI_FUNC void luaC_changemode (lua_State *L, int newmode);\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua/linit.c",
    "content": "/*\n** $Id: linit.c $\n** Initialization of libraries for lua.c and other clients\n** See Copyright Notice in lua.h\n*/\n\n\n#define linit_c\n#define LUA_LIB\n\n\n#include \"lprefix.h\"\n\n\n#include <stddef.h>\n\n#include \"lua.h\"\n\n#include \"lualib.h\"\n#include \"lauxlib.h\"\n#include \"llimits.h\"\n\n\n/*\n** Standard Libraries. (Must be listed in the same ORDER of their\n** respective constants LUA_<libname>K.)\n*/\nstatic const luaL_Reg stdlibs[] = {\n  {LUA_GNAME, luaopen_base},\n  {LUA_LOADLIBNAME, luaopen_package},\n  {LUA_COLIBNAME, luaopen_coroutine},\n  {LUA_DBLIBNAME, luaopen_debug},\n  {LUA_IOLIBNAME, luaopen_io},\n  {LUA_MATHLIBNAME, luaopen_math},\n  {LUA_OSLIBNAME, luaopen_os},\n  {LUA_STRLIBNAME, luaopen_string},\n  {LUA_TABLIBNAME, luaopen_table},\n  {LUA_UTF8LIBNAME, luaopen_utf8},\n  {NULL, NULL}\n};\n\n\n/*\n** require and preload selected standard libraries\n*/\nLUALIB_API void luaL_openselectedlibs (lua_State *L, int load, int preload) {\n  int mask;\n  const luaL_Reg *lib;\n  luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);\n  for (lib = stdlibs, mask = 1; lib->name != NULL; lib++, mask <<= 1) {\n    if (load & mask) {  /* selected? */\n      luaL_requiref(L, lib->name, lib->func, 1);  /* require library */\n      lua_pop(L, 1);  /* remove result from the stack */\n    }\n    else if (preload & mask) {  /* selected? */\n      lua_pushcfunction(L, lib->func);\n      lua_setfield(L, -2, lib->name);  /* add library to PRELOAD table */\n    }\n  }\n  lua_assert((mask >> 1) == LUA_UTF8LIBK);\n  lua_pop(L, 1);  /* remove PRELOAD table */\n}\n\n"
  },
  {
    "path": "3rd/lua/liolib.c",
    "content": "/*\n** $Id: liolib.c $\n** Standard I/O (and system) library\n** See Copyright Notice in lua.h\n*/\n\n#define liolib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <ctype.h>\n#include <errno.h>\n#include <locale.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\n/*\n** Change this macro to accept other modes for 'fopen' besides\n** the standard ones.\n*/\n#if !defined(l_checkmode)\n\n/* accepted extensions to 'mode' in 'fopen' */\n#if !defined(L_MODEEXT)\n#define L_MODEEXT\t\"b\"\n#endif\n\n/* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */\nstatic int l_checkmode (const char *mode) {\n  return (*mode != '\\0' && strchr(\"rwa\", *(mode++)) != NULL &&\n         (*mode != '+' || ((void)(++mode), 1)) &&  /* skip if char is '+' */\n         (strspn(mode, L_MODEEXT) == strlen(mode)));  /* check extensions */\n}\n\n#endif\n\n/*\n** {======================================================\n** l_popen spawns a new process connected to the current\n** one through the file streams.\n** =======================================================\n*/\n\n#if !defined(l_popen)\t\t/* { */\n\n#if defined(LUA_USE_POSIX)\t/* { */\n\n#define l_popen(L,c,m)\t\t(fflush(NULL), popen(c,m))\n#define l_pclose(L,file)\t(pclose(file))\n\n#elif defined(LUA_USE_WINDOWS)\t/* }{ */\n\n#define l_popen(L,c,m)\t\t(_popen(c,m))\n#define l_pclose(L,file)\t(_pclose(file))\n\n#if !defined(l_checkmodep)\n/* Windows accepts \"[rw][bt]?\" as valid modes */\n#define l_checkmodep(m)\t((m[0] == 'r' || m[0] == 'w') && \\\n  (m[1] == '\\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\\0')))\n#endif\n\n#else\t\t\t\t/* }{ */\n\n/* ISO C definitions */\n#define l_popen(L,c,m)  \\\n\t  ((void)c, (void)m, \\\n\t  luaL_error(L, \"'popen' not supported\"), \\\n\t  (FILE*)0)\n#define l_pclose(L,file)\t\t((void)L, (void)file, -1)\n\n#endif\t\t\t\t/* } */\n\n#endif\t\t\t\t/* } */\n\n\n#if !defined(l_checkmodep)\n/* By default, Lua accepts only \"r\" or \"w\" as valid modes */\n#define l_checkmodep(m)        ((m[0] == 'r' || m[0] == 'w') && m[1] == '\\0')\n#endif\n\n/* }====================================================== */\n\n\n#if !defined(l_getc)\t\t/* { */\n\n#if defined(LUA_USE_POSIX)\n#define l_getc(f)\t\tgetc_unlocked(f)\n#define l_lockfile(f)\t\tflockfile(f)\n#define l_unlockfile(f)\t\tfunlockfile(f)\n#else\n#define l_getc(f)\t\tgetc(f)\n#define l_lockfile(f)\t\t((void)0)\n#define l_unlockfile(f)\t\t((void)0)\n#endif\n\n#endif\t\t\t\t/* } */\n\n\n/*\n** {======================================================\n** l_fseek: configuration for longer offsets\n** =======================================================\n*/\n\n#if !defined(l_fseek)\t\t/* { */\n\n#if defined(LUA_USE_POSIX) || defined(LUA_USE_OFF_T)\t/* { */\n\n#include <sys/types.h>\n\n#define l_fseek(f,o,w)\t\tfseeko(f,o,w)\n#define l_ftell(f)\t\tftello(f)\n#define l_seeknum\t\toff_t\n\n#elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \\\n   && defined(_MSC_VER) && (_MSC_VER >= 1400)\t/* }{ */\n\n/* Windows (but not DDK) and Visual C++ 2005 or higher */\n#define l_fseek(f,o,w)\t\t_fseeki64(f,o,w)\n#define l_ftell(f)\t\t_ftelli64(f)\n#define l_seeknum\t\t__int64\n\n#else\t\t\t\t/* }{ */\n\n/* ISO C definitions */\n#define l_fseek(f,o,w)\t\tfseek(f,o,w)\n#define l_ftell(f)\t\tftell(f)\n#define l_seeknum\t\tlong\n\n#endif\t\t\t\t/* } */\n\n#endif\t\t\t\t/* } */\n\n/* }====================================================== */\n\n\n\n#define IO_PREFIX\t\"_IO_\"\n#define IOPREF_LEN\t(sizeof(IO_PREFIX)/sizeof(char) - 1)\n#define IO_INPUT\t(IO_PREFIX \"input\")\n#define IO_OUTPUT\t(IO_PREFIX \"output\")\n\n\ntypedef luaL_Stream LStream;\n\n\n#define tolstream(L)\t((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))\n\n#define isclosed(p)\t((p)->closef == NULL)\n\n\nstatic int io_type (lua_State *L) {\n  LStream *p;\n  luaL_checkany(L, 1);\n  p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);\n  if (p == NULL)\n    luaL_pushfail(L);  /* not a file */\n  else if (isclosed(p))\n    lua_pushliteral(L, \"closed file\");\n  else\n    lua_pushliteral(L, \"file\");\n  return 1;\n}\n\n\nstatic int f_tostring (lua_State *L) {\n  LStream *p = tolstream(L);\n  if (isclosed(p))\n    lua_pushliteral(L, \"file (closed)\");\n  else\n    lua_pushfstring(L, \"file (%p)\", p->f);\n  return 1;\n}\n\n\nstatic FILE *tofile (lua_State *L) {\n  LStream *p = tolstream(L);\n  if (l_unlikely(isclosed(p)))\n    luaL_error(L, \"attempt to use a closed file\");\n  lua_assert(p->f);\n  return p->f;\n}\n\n\n/*\n** When creating file handles, always creates a 'closed' file handle\n** before opening the actual file; so, if there is a memory error, the\n** handle is in a consistent state.\n*/\nstatic LStream *newprefile (lua_State *L) {\n  LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0);\n  p->closef = NULL;  /* mark file handle as 'closed' */\n  luaL_setmetatable(L, LUA_FILEHANDLE);\n  return p;\n}\n\n\n/*\n** Calls the 'close' function from a file handle. The 'volatile' avoids\n** a bug in some versions of the Clang compiler (e.g., clang 3.0 for\n** 32 bits).\n*/\nstatic int aux_close (lua_State *L) {\n  LStream *p = tolstream(L);\n  volatile lua_CFunction cf = p->closef;\n  p->closef = NULL;  /* mark stream as closed */\n  return (*cf)(L);  /* close it */\n}\n\n\nstatic int f_close (lua_State *L) {\n  tofile(L);  /* make sure argument is an open stream */\n  return aux_close(L);\n}\n\n\nstatic int io_close (lua_State *L) {\n  if (lua_isnone(L, 1))  /* no argument? */\n    lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT);  /* use default output */\n  return f_close(L);\n}\n\n\nstatic int f_gc (lua_State *L) {\n  LStream *p = tolstream(L);\n  if (!isclosed(p) && p->f != NULL)\n    aux_close(L);  /* ignore closed and incompletely open files */\n  return 0;\n}\n\n\n/*\n** function to close regular files\n*/\nstatic int io_fclose (lua_State *L) {\n  LStream *p = tolstream(L);\n  errno = 0;\n  return luaL_fileresult(L, (fclose(p->f) == 0), NULL);\n}\n\n\nstatic LStream *newfile (lua_State *L) {\n  LStream *p = newprefile(L);\n  p->f = NULL;\n  p->closef = &io_fclose;\n  return p;\n}\n\n\nstatic void opencheck (lua_State *L, const char *fname, const char *mode) {\n  LStream *p = newfile(L);\n  p->f = fopen(fname, mode);\n  if (l_unlikely(p->f == NULL))\n    luaL_error(L, \"cannot open file '%s' (%s)\", fname, strerror(errno));\n}\n\n\nstatic int io_open (lua_State *L) {\n  const char *filename = luaL_checkstring(L, 1);\n  const char *mode = luaL_optstring(L, 2, \"r\");\n  LStream *p = newfile(L);\n  const char *md = mode;  /* to traverse/check mode */\n  luaL_argcheck(L, l_checkmode(md), 2, \"invalid mode\");\n  errno = 0;\n  p->f = fopen(filename, mode);\n  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;\n}\n\n\n/*\n** function to close 'popen' files\n*/\nstatic int io_pclose (lua_State *L) {\n  LStream *p = tolstream(L);\n  errno = 0;\n  return luaL_execresult(L, l_pclose(L, p->f));\n}\n\n\nstatic int io_popen (lua_State *L) {\n  const char *filename = luaL_checkstring(L, 1);\n  const char *mode = luaL_optstring(L, 2, \"r\");\n  LStream *p = newprefile(L);\n  luaL_argcheck(L, l_checkmodep(mode), 2, \"invalid mode\");\n  errno = 0;\n  p->f = l_popen(L, filename, mode);\n  p->closef = &io_pclose;\n  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;\n}\n\n\nstatic int io_tmpfile (lua_State *L) {\n  LStream *p = newfile(L);\n  errno = 0;\n  p->f = tmpfile();\n  return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;\n}\n\n\nstatic FILE *getiofile (lua_State *L, const char *findex) {\n  LStream *p;\n  lua_getfield(L, LUA_REGISTRYINDEX, findex);\n  p = (LStream *)lua_touserdata(L, -1);\n  if (l_unlikely(isclosed(p)))\n    luaL_error(L, \"default %s file is closed\", findex + IOPREF_LEN);\n  return p->f;\n}\n\n\nstatic int g_iofile (lua_State *L, const char *f, const char *mode) {\n  if (!lua_isnoneornil(L, 1)) {\n    const char *filename = lua_tostring(L, 1);\n    if (filename)\n      opencheck(L, filename, mode);\n    else {\n      tofile(L);  /* check that it's a valid file handle */\n      lua_pushvalue(L, 1);\n    }\n    lua_setfield(L, LUA_REGISTRYINDEX, f);\n  }\n  /* return current value */\n  lua_getfield(L, LUA_REGISTRYINDEX, f);\n  return 1;\n}\n\n\nstatic int io_input (lua_State *L) {\n  return g_iofile(L, IO_INPUT, \"r\");\n}\n\n\nstatic int io_output (lua_State *L) {\n  return g_iofile(L, IO_OUTPUT, \"w\");\n}\n\n\nstatic int io_readline (lua_State *L);\n\n\n/*\n** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit\n** in the limit for upvalues of a closure)\n*/\n#define MAXARGLINE\t250\n\n/*\n** Auxiliary function to create the iteration function for 'lines'.\n** The iteration function is a closure over 'io_readline', with\n** the following upvalues:\n** 1) The file being read (first value in the stack)\n** 2) the number of arguments to read\n** 3) a boolean, true iff file has to be closed when finished ('toclose')\n** *) a variable number of format arguments (rest of the stack)\n*/\nstatic void aux_lines (lua_State *L, int toclose) {\n  int n = lua_gettop(L) - 1;  /* number of arguments to read */\n  luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, \"too many arguments\");\n  lua_pushvalue(L, 1);  /* file */\n  lua_pushinteger(L, n);  /* number of arguments to read */\n  lua_pushboolean(L, toclose);  /* close/not close file when finished */\n  lua_rotate(L, 2, 3);  /* move the three values to their positions */\n  lua_pushcclosure(L, io_readline, 3 + n);\n}\n\n\nstatic int f_lines (lua_State *L) {\n  tofile(L);  /* check that it's a valid file handle */\n  aux_lines(L, 0);\n  return 1;\n}\n\n\n/*\n** Return an iteration function for 'io.lines'. If file has to be\n** closed, also returns the file itself as a second result (to be\n** closed as the state at the exit of a generic for).\n*/\nstatic int io_lines (lua_State *L) {\n  int toclose;\n  if (lua_isnone(L, 1)) lua_pushnil(L);  /* at least one argument */\n  if (lua_isnil(L, 1)) {  /* no file name? */\n    lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT);  /* get default input */\n    lua_replace(L, 1);  /* put it at index 1 */\n    tofile(L);  /* check that it's a valid file handle */\n    toclose = 0;  /* do not close it after iteration */\n  }\n  else {  /* open a new file */\n    const char *filename = luaL_checkstring(L, 1);\n    opencheck(L, filename, \"r\");\n    lua_replace(L, 1);  /* put file at index 1 */\n    toclose = 1;  /* close it after iteration */\n  }\n  aux_lines(L, toclose);  /* push iteration function */\n  if (toclose) {\n    lua_pushnil(L);  /* state */\n    lua_pushnil(L);  /* control */\n    lua_pushvalue(L, 1);  /* file is the to-be-closed variable (4th result) */\n    return 4;\n  }\n  else\n    return 1;\n}\n\n\n/*\n** {======================================================\n** READ\n** =======================================================\n*/\n\n\n/* maximum length of a numeral */\n#if !defined (L_MAXLENNUM)\n#define L_MAXLENNUM     200\n#endif\n\n\n/* auxiliary structure used by 'read_number' */\ntypedef struct {\n  FILE *f;  /* file being read */\n  int c;  /* current character (look ahead) */\n  int n;  /* number of elements in buffer 'buff' */\n  char buff[L_MAXLENNUM + 1];  /* +1 for ending '\\0' */\n} RN;\n\n\n/*\n** Add current char to buffer (if not out of space) and read next one\n*/\nstatic int nextc (RN *rn) {\n  if (l_unlikely(rn->n >= L_MAXLENNUM)) {  /* buffer overflow? */\n    rn->buff[0] = '\\0';  /* invalidate result */\n    return 0;  /* fail */\n  }\n  else {\n    rn->buff[rn->n++] = cast_char(rn->c);  /* save current char */\n    rn->c = l_getc(rn->f);  /* read next one */\n    return 1;\n  }\n}\n\n\n/*\n** Accept current char if it is in 'set' (of size 2)\n*/\nstatic int test2 (RN *rn, const char *set) {\n  if (rn->c == set[0] || rn->c == set[1])\n    return nextc(rn);\n  else return 0;\n}\n\n\n/*\n** Read a sequence of (hex)digits\n*/\nstatic int readdigits (RN *rn, int hex) {\n  int count = 0;\n  while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))\n    count++;\n  return count;\n}\n\n\n/*\n** Read a number: first reads a valid prefix of a numeral into a buffer.\n** Then it calls 'lua_stringtonumber' to check whether the format is\n** correct and to convert it to a Lua number.\n*/\nstatic int read_number (lua_State *L, FILE *f) {\n  RN rn;\n  int count = 0;\n  int hex = 0;\n  char decp[2];\n  rn.f = f; rn.n = 0;\n  decp[0] = lua_getlocaledecpoint();  /* get decimal point from locale */\n  decp[1] = '.';  /* always accept a dot */\n  l_lockfile(rn.f);\n  do { rn.c = l_getc(rn.f); } while (isspace(rn.c));  /* skip spaces */\n  test2(&rn, \"-+\");  /* optional sign */\n  if (test2(&rn, \"00\")) {\n    if (test2(&rn, \"xX\")) hex = 1;  /* numeral is hexadecimal */\n    else count = 1;  /* count initial '0' as a valid digit */\n  }\n  count += readdigits(&rn, hex);  /* integral part */\n  if (test2(&rn, decp))  /* decimal point? */\n    count += readdigits(&rn, hex);  /* fractional part */\n  if (count > 0 && test2(&rn, (hex ? \"pP\" : \"eE\"))) {  /* exponent mark? */\n    test2(&rn, \"-+\");  /* exponent sign */\n    readdigits(&rn, 0);  /* exponent digits */\n  }\n  ungetc(rn.c, rn.f);  /* unread look-ahead char */\n  l_unlockfile(rn.f);\n  rn.buff[rn.n] = '\\0';  /* finish string */\n  if (l_likely(lua_stringtonumber(L, rn.buff)))\n    return 1;  /* ok, it is a valid number */\n  else {  /* invalid format */\n   lua_pushnil(L);  /* \"result\" to be removed */\n   return 0;  /* read fails */\n  }\n}\n\n\nstatic int test_eof (lua_State *L, FILE *f) {\n  int c = getc(f);\n  ungetc(c, f);  /* no-op when c == EOF */\n  lua_pushliteral(L, \"\");\n  return (c != EOF);\n}\n\n\nstatic int read_line (lua_State *L, FILE *f, int chop) {\n  luaL_Buffer b;\n  int c;\n  luaL_buffinit(L, &b);\n  do {  /* may need to read several chunks to get whole line */\n    char *buff = luaL_prepbuffer(&b);  /* preallocate buffer space */\n    unsigned i = 0;\n    l_lockfile(f);  /* no memory errors can happen inside the lock */\n    while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\\n')\n      buff[i++] = cast_char(c);  /* read up to end of line or buffer limit */\n    l_unlockfile(f);\n    luaL_addsize(&b, i);\n  } while (c != EOF && c != '\\n');  /* repeat until end of line */\n  if (!chop && c == '\\n')  /* want a newline and have one? */\n    luaL_addchar(&b, '\\n');  /* add ending newline to result */\n  luaL_pushresult(&b);  /* close buffer */\n  /* return ok if read something (either a newline or something else) */\n  return (c == '\\n' || lua_rawlen(L, -1) > 0);\n}\n\n\nstatic void read_all (lua_State *L, FILE *f) {\n  size_t nr;\n  luaL_Buffer b;\n  luaL_buffinit(L, &b);\n  do {  /* read file in chunks of LUAL_BUFFERSIZE bytes */\n    char *p = luaL_prepbuffer(&b);\n    nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);\n    luaL_addsize(&b, nr);\n  } while (nr == LUAL_BUFFERSIZE);\n  luaL_pushresult(&b);  /* close buffer */\n}\n\n\nstatic int read_chars (lua_State *L, FILE *f, size_t n) {\n  size_t nr;  /* number of chars actually read */\n  char *p;\n  luaL_Buffer b;\n  luaL_buffinit(L, &b);\n  p = luaL_prepbuffsize(&b, n);  /* prepare buffer to read whole block */\n  nr = fread(p, sizeof(char), n, f);  /* try to read 'n' chars */\n  luaL_addsize(&b, nr);\n  luaL_pushresult(&b);  /* close buffer */\n  return (nr > 0);  /* true iff read something */\n}\n\n\nstatic int g_read (lua_State *L, FILE *f, int first) {\n  int nargs = lua_gettop(L) - 1;\n  int n, success;\n  clearerr(f);\n  errno = 0;\n  if (nargs == 0) {  /* no arguments? */\n    success = read_line(L, f, 1);\n    n = first + 1;  /* to return 1 result */\n  }\n  else {\n    /* ensure stack space for all results and for auxlib's buffer */\n    luaL_checkstack(L, nargs+LUA_MINSTACK, \"too many arguments\");\n    success = 1;\n    for (n = first; nargs-- && success; n++) {\n      if (lua_type(L, n) == LUA_TNUMBER) {\n        size_t l = (size_t)luaL_checkinteger(L, n);\n        success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);\n      }\n      else {\n        const char *p = luaL_checkstring(L, n);\n        if (*p == '*') p++;  /* skip optional '*' (for compatibility) */\n        switch (*p) {\n          case 'n':  /* number */\n            success = read_number(L, f);\n            break;\n          case 'l':  /* line */\n            success = read_line(L, f, 1);\n            break;\n          case 'L':  /* line with end-of-line */\n            success = read_line(L, f, 0);\n            break;\n          case 'a':  /* file */\n            read_all(L, f);  /* read entire file */\n            success = 1; /* always success */\n            break;\n          default:\n            return luaL_argerror(L, n, \"invalid format\");\n        }\n      }\n    }\n  }\n  if (ferror(f))\n    return luaL_fileresult(L, 0, NULL);\n  if (!success) {\n    lua_pop(L, 1);  /* remove last result */\n    luaL_pushfail(L);  /* push nil instead */\n  }\n  return n - first;\n}\n\n\nstatic int io_read (lua_State *L) {\n  return g_read(L, getiofile(L, IO_INPUT), 1);\n}\n\n\nstatic int f_read (lua_State *L) {\n  return g_read(L, tofile(L), 2);\n}\n\n\n/*\n** Iteration function for 'lines'.\n*/\nstatic int io_readline (lua_State *L) {\n  LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));\n  int i;\n  int n = (int)lua_tointeger(L, lua_upvalueindex(2));\n  if (isclosed(p))  /* file is already closed? */\n    return luaL_error(L, \"file is already closed\");\n  lua_settop(L , 1);\n  luaL_checkstack(L, n, \"too many arguments\");\n  for (i = 1; i <= n; i++)  /* push arguments to 'g_read' */\n    lua_pushvalue(L, lua_upvalueindex(3 + i));\n  n = g_read(L, p->f, 2);  /* 'n' is number of results */\n  lua_assert(n > 0);  /* should return at least a nil */\n  if (lua_toboolean(L, -n))  /* read at least one value? */\n    return n;  /* return them */\n  else {  /* first result is false: EOF or error */\n    if (n > 1) {  /* is there error information? */\n      /* 2nd result is error message */\n      return luaL_error(L, \"%s\", lua_tostring(L, -n + 1));\n    }\n    if (lua_toboolean(L, lua_upvalueindex(3))) {  /* generator created file? */\n      lua_settop(L, 0);  /* clear stack */\n      lua_pushvalue(L, lua_upvalueindex(1));  /* push file at index 1 */\n      aux_close(L);  /* close it */\n    }\n    return 0;\n  }\n}\n\n/* }====================================================== */\n\n\nstatic int g_write (lua_State *L, FILE *f, int arg) {\n  int nargs = lua_gettop(L) - arg;\n  size_t totalbytes = 0;  /* total number of bytes written */\n  errno = 0;\n  for (; nargs--; arg++) {  /* for each argument */\n    char buff[LUA_N2SBUFFSZ];\n    const char *s;\n    size_t numbytes;  /* bytes written in one call to 'fwrite' */\n    size_t len = lua_numbertocstring(L, arg, buff);  /* try as a number */\n    if (len > 0) {  /* did conversion work (value was a number)? */\n      s = buff;\n      len--;\n    }\n    else  /* must be a string */\n      s = luaL_checklstring(L, arg, &len);\n    numbytes = fwrite(s, sizeof(char), len, f);\n    totalbytes += numbytes;\n    if (numbytes < len) {  /* write error? */\n      int n = luaL_fileresult(L, 0, NULL);\n      lua_pushinteger(L, cast_st2S(totalbytes));\n      return n + 1;  /* return fail, error msg., error code, and counter */\n    }\n  }\n  return 1;  /* no errors; file handle already on stack top */\n}\n\n\nstatic int io_write (lua_State *L) {\n  return g_write(L, getiofile(L, IO_OUTPUT), 1);\n}\n\n\nstatic int f_write (lua_State *L) {\n  FILE *f = tofile(L);\n  lua_pushvalue(L, 1);  /* push file at the stack top (to be returned) */\n  return g_write(L, f, 2);\n}\n\n\nstatic int f_seek (lua_State *L) {\n  static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};\n  static const char *const modenames[] = {\"set\", \"cur\", \"end\", NULL};\n  FILE *f = tofile(L);\n  int op = luaL_checkoption(L, 2, \"cur\", modenames);\n  lua_Integer p3 = luaL_optinteger(L, 3, 0);\n  l_seeknum offset = (l_seeknum)p3;\n  luaL_argcheck(L, (lua_Integer)offset == p3, 3,\n                  \"not an integer in proper range\");\n  errno = 0;\n  op = l_fseek(f, offset, mode[op]);\n  if (l_unlikely(op))\n    return luaL_fileresult(L, 0, NULL);  /* error */\n  else {\n    lua_pushinteger(L, (lua_Integer)l_ftell(f));\n    return 1;\n  }\n}\n\n\nstatic int f_setvbuf (lua_State *L) {\n  static const int mode[] = {_IONBF, _IOFBF, _IOLBF};\n  static const char *const modenames[] = {\"no\", \"full\", \"line\", NULL};\n  FILE *f = tofile(L);\n  int op = luaL_checkoption(L, 2, NULL, modenames);\n  lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);\n  int res;\n  errno = 0;\n  res = setvbuf(f, NULL, mode[op], (size_t)sz);\n  return luaL_fileresult(L, res == 0, NULL);\n}\n\n\nstatic int aux_flush (lua_State *L, FILE *f) {\n  errno = 0;\n  return luaL_fileresult(L, fflush(f) == 0, NULL);\n}\n\n\nstatic int f_flush (lua_State *L) {\n  return aux_flush(L, tofile(L));\n}\n\n\nstatic int io_flush (lua_State *L) {\n  return aux_flush(L, getiofile(L, IO_OUTPUT));\n}\n\n\n/*\n** functions for 'io' library\n*/\nstatic const luaL_Reg iolib[] = {\n  {\"close\", io_close},\n  {\"flush\", io_flush},\n  {\"input\", io_input},\n  {\"lines\", io_lines},\n  {\"open\", io_open},\n  {\"output\", io_output},\n  {\"popen\", io_popen},\n  {\"read\", io_read},\n  {\"tmpfile\", io_tmpfile},\n  {\"type\", io_type},\n  {\"write\", io_write},\n  {NULL, NULL}\n};\n\n\n/*\n** methods for file handles\n*/\nstatic const luaL_Reg meth[] = {\n  {\"read\", f_read},\n  {\"write\", f_write},\n  {\"lines\", f_lines},\n  {\"flush\", f_flush},\n  {\"seek\", f_seek},\n  {\"close\", f_close},\n  {\"setvbuf\", f_setvbuf},\n  {NULL, NULL}\n};\n\n\n/*\n** metamethods for file handles\n*/\nstatic const luaL_Reg metameth[] = {\n  {\"__index\", NULL},  /* placeholder */\n  {\"__gc\", f_gc},\n  {\"__close\", f_gc},\n  {\"__tostring\", f_tostring},\n  {NULL, NULL}\n};\n\n\nstatic void createmeta (lua_State *L) {\n  luaL_newmetatable(L, LUA_FILEHANDLE);  /* metatable for file handles */\n  luaL_setfuncs(L, metameth, 0);  /* add metamethods to new metatable */\n  luaL_newlibtable(L, meth);  /* create method table */\n  luaL_setfuncs(L, meth, 0);  /* add file methods to method table */\n  lua_setfield(L, -2, \"__index\");  /* metatable.__index = method table */\n  lua_pop(L, 1);  /* pop metatable */\n}\n\n\n/*\n** function to (not) close the standard files stdin, stdout, and stderr\n*/\nstatic int io_noclose (lua_State *L) {\n  LStream *p = tolstream(L);\n  p->closef = &io_noclose;  /* keep file opened */\n  luaL_pushfail(L);\n  lua_pushliteral(L, \"cannot close standard file\");\n  return 2;\n}\n\n\nstatic void createstdfile (lua_State *L, FILE *f, const char *k,\n                           const char *fname) {\n  LStream *p = newprefile(L);\n  p->f = f;\n  p->closef = &io_noclose;\n  if (k != NULL) {\n    lua_pushvalue(L, -1);\n    lua_setfield(L, LUA_REGISTRYINDEX, k);  /* add file to registry */\n  }\n  lua_setfield(L, -2, fname);  /* add file to module */\n}\n\n\nLUAMOD_API int luaopen_io (lua_State *L) {\n  luaL_newlib(L, iolib);  /* new module */\n  createmeta(L);\n  /* create (and set) default files */\n  createstdfile(L, stdin, IO_INPUT, \"stdin\");\n  createstdfile(L, stdout, IO_OUTPUT, \"stdout\");\n  createstdfile(L, stderr, NULL, \"stderr\");\n  return 1;\n}\n\n"
  },
  {
    "path": "3rd/lua/ljumptab.h",
    "content": "/*\n** $Id: ljumptab.h $\n** Jump Table for the Lua interpreter\n** See Copyright Notice in lua.h\n*/\n\n\n#undef vmdispatch\n#undef vmcase\n#undef vmbreak\n\n#define vmdispatch(x)     goto *disptab[x];\n\n#define vmcase(l)     L_##l:\n\n#define vmbreak\t\tvmfetch(); vmdispatch(GET_OPCODE(i));\n\n\nstatic const void *const disptab[NUM_OPCODES] = {\n\n#if 0\n** you can update the following list with this command:\n**\n**  sed -n '/^OP_/!d; s/OP_/\\&\\&L_OP_/ ; s/,.*/,/ ; s/\\/.*// ; p'  lopcodes.h\n**\n#endif\n\n&&L_OP_MOVE,\n&&L_OP_LOADI,\n&&L_OP_LOADF,\n&&L_OP_LOADK,\n&&L_OP_LOADKX,\n&&L_OP_LOADFALSE,\n&&L_OP_LFALSESKIP,\n&&L_OP_LOADTRUE,\n&&L_OP_LOADNIL,\n&&L_OP_GETUPVAL,\n&&L_OP_SETUPVAL,\n&&L_OP_GETTABUP,\n&&L_OP_GETTABLE,\n&&L_OP_GETI,\n&&L_OP_GETFIELD,\n&&L_OP_SETTABUP,\n&&L_OP_SETTABLE,\n&&L_OP_SETI,\n&&L_OP_SETFIELD,\n&&L_OP_NEWTABLE,\n&&L_OP_SELF,\n&&L_OP_ADDI,\n&&L_OP_ADDK,\n&&L_OP_SUBK,\n&&L_OP_MULK,\n&&L_OP_MODK,\n&&L_OP_POWK,\n&&L_OP_DIVK,\n&&L_OP_IDIVK,\n&&L_OP_BANDK,\n&&L_OP_BORK,\n&&L_OP_BXORK,\n&&L_OP_SHLI,\n&&L_OP_SHRI,\n&&L_OP_ADD,\n&&L_OP_SUB,\n&&L_OP_MUL,\n&&L_OP_MOD,\n&&L_OP_POW,\n&&L_OP_DIV,\n&&L_OP_IDIV,\n&&L_OP_BAND,\n&&L_OP_BOR,\n&&L_OP_BXOR,\n&&L_OP_SHL,\n&&L_OP_SHR,\n&&L_OP_MMBIN,\n&&L_OP_MMBINI,\n&&L_OP_MMBINK,\n&&L_OP_UNM,\n&&L_OP_BNOT,\n&&L_OP_NOT,\n&&L_OP_LEN,\n&&L_OP_CONCAT,\n&&L_OP_CLOSE,\n&&L_OP_TBC,\n&&L_OP_JMP,\n&&L_OP_EQ,\n&&L_OP_LT,\n&&L_OP_LE,\n&&L_OP_EQK,\n&&L_OP_EQI,\n&&L_OP_LTI,\n&&L_OP_LEI,\n&&L_OP_GTI,\n&&L_OP_GEI,\n&&L_OP_TEST,\n&&L_OP_TESTSET,\n&&L_OP_CALL,\n&&L_OP_TAILCALL,\n&&L_OP_RETURN,\n&&L_OP_RETURN0,\n&&L_OP_RETURN1,\n&&L_OP_FORLOOP,\n&&L_OP_FORPREP,\n&&L_OP_TFORPREP,\n&&L_OP_TFORCALL,\n&&L_OP_TFORLOOP,\n&&L_OP_SETLIST,\n&&L_OP_CLOSURE,\n&&L_OP_VARARG,\n&&L_OP_GETVARG,\n&&L_OP_ERRNNIL,\n&&L_OP_VARARGPREP,\n&&L_OP_EXTRAARG\n\n};\n"
  },
  {
    "path": "3rd/lua/llex.c",
    "content": "/*\n** $Id: llex.c $\n** Lexical Analyzer\n** See Copyright Notice in lua.h\n*/\n\n#define llex_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <locale.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lctype.h\"\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lgc.h\"\n#include \"llex.h\"\n#include \"lobject.h\"\n#include \"lparser.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"lzio.h\"\n\n\n\n#define next(ls)\t(ls->current = zgetc(ls->z))\n\n\n/* minimum size for string buffer */\n#if !defined(LUA_MINBUFFER)\n#define LUA_MINBUFFER   32\n#endif\n\n\n#define currIsNewline(ls)\t(ls->current == '\\n' || ls->current == '\\r')\n\n\n/* ORDER RESERVED */\nstatic const char *const luaX_tokens [] = {\n    \"and\", \"break\", \"do\", \"else\", \"elseif\",\n    \"end\", \"false\", \"for\", \"function\", \"global\", \"goto\", \"if\",\n    \"in\", \"local\", \"nil\", \"not\", \"or\", \"repeat\",\n    \"return\", \"then\", \"true\", \"until\", \"while\",\n    \"//\", \"..\", \"...\", \"==\", \">=\", \"<=\", \"~=\",\n    \"<<\", \">>\", \"::\", \"<eof>\",\n    \"<number>\", \"<integer>\", \"<name>\", \"<string>\"\n};\n\n\n#define save_and_next(ls) (save(ls, ls->current), next(ls))\n\n\nstatic l_noret lexerror (LexState *ls, const char *msg, int token);\n\n\nstatic void save (LexState *ls, int c) {\n  Mbuffer *b = ls->buff;\n  if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {\n    size_t newsize = luaZ_sizebuffer(b);  /* get old size */;\n    if (newsize >= (MAX_SIZE/3 * 2))  /* larger than MAX_SIZE/1.5 ? */\n      lexerror(ls, \"lexical element too long\", 0);\n    newsize += (newsize >> 1);  /* new size is 1.5 times the old one */\n    luaZ_resizebuffer(ls->L, b, newsize);\n  }\n  b->buffer[luaZ_bufflen(b)++] = cast_char(c);\n}\n\n\nvoid luaX_init (lua_State *L) {\n  int i;\n  TString *e = luaS_newliteral(L, LUA_ENV);  /* create env name */\n  luaC_fix(L, obj2gco(e));  /* never collect this name */\n  for (i=0; i<NUM_RESERVED; i++) {\n    TString *ts = luaS_new(L, luaX_tokens[i]);\n    luaC_fix(L, obj2gco(ts));  /* reserved words are never collected */\n    ts->extra = cast_byte(i+1);  /* reserved word */\n  }\n}\n\n\nconst char *luaX_token2str (LexState *ls, int token) {\n  if (token < FIRST_RESERVED) {  /* single-byte symbols? */\n    if (lisprint(token))\n      return luaO_pushfstring(ls->L, \"'%c'\", token);\n    else  /* control character */\n      return luaO_pushfstring(ls->L, \"'<\\\\%d>'\", token);\n  }\n  else {\n    const char *s = luaX_tokens[token - FIRST_RESERVED];\n    if (token < TK_EOS)  /* fixed format (symbols and reserved words)? */\n      return luaO_pushfstring(ls->L, \"'%s'\", s);\n    else  /* names, strings, and numerals */\n      return s;\n  }\n}\n\n\nstatic const char *txtToken (LexState *ls, int token) {\n  switch (token) {\n    case TK_NAME: case TK_STRING:\n    case TK_FLT: case TK_INT:\n      save(ls, '\\0');\n      return luaO_pushfstring(ls->L, \"'%s'\", luaZ_buffer(ls->buff));\n    default:\n      return luaX_token2str(ls, token);\n  }\n}\n\n\nstatic l_noret lexerror (LexState *ls, const char *msg, int token) {\n  msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber);\n  if (token)\n    luaO_pushfstring(ls->L, \"%s near %s\", msg, txtToken(ls, token));\n  luaD_throw(ls->L, LUA_ERRSYNTAX);\n}\n\n\nl_noret luaX_syntaxerror (LexState *ls, const char *msg) {\n  lexerror(ls, msg, ls->t.token);\n}\n\n\n/*\n** Anchors a string in scanner's table so that it will not be collected\n** until the end of the compilation; by that time it should be anchored\n** somewhere. It also internalizes long strings, ensuring there is only\n** one copy of each unique string.\n*/\nstatic TString *anchorstr (LexState *ls, TString *ts) {\n  lua_State *L = ls->L;\n  TValue oldts;\n  int tag = luaH_getstr(ls->h, ts, &oldts);\n  if (!tagisempty(tag))  /* string already present? */\n    return tsvalue(&oldts);  /* use stored value */\n  else {  /* create a new entry */\n    TValue *stv = s2v(L->top.p++);  /* reserve stack space for string */\n    setsvalue(L, stv, ts);  /* push (anchor) the string on the stack */\n    luaH_set(L, ls->h, stv, stv);  /* t[string] = string */\n    /* table is not a metatable, so it does not need to invalidate cache */\n    luaC_checkGC(L);\n    L->top.p--;  /* remove string from stack */\n    return ts;\n  }\n}\n\n\n/*\n** Creates a new string and anchors it in scanner's table.\n*/\nTString *luaX_newstring (LexState *ls, const char *str, size_t l) {\n  return anchorstr(ls, luaS_newlstr(ls->L, str, l));\n}\n\n\n/*\n** increment line number and skips newline sequence (any of\n** \\n, \\r, \\n\\r, or \\r\\n)\n*/\nstatic void inclinenumber (LexState *ls) {\n  int old = ls->current;\n  lua_assert(currIsNewline(ls));\n  next(ls);  /* skip '\\n' or '\\r' */\n  if (currIsNewline(ls) && ls->current != old)\n    next(ls);  /* skip '\\n\\r' or '\\r\\n' */\n  if (++ls->linenumber >= INT_MAX)\n    lexerror(ls, \"chunk has too many lines\", 0);\n}\n\n\nvoid luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,\n                    int firstchar) {\n  ls->t.token = 0;\n  ls->L = L;\n  ls->current = firstchar;\n  ls->lookahead.token = TK_EOS;  /* no look-ahead token */\n  ls->z = z;\n  ls->fs = NULL;\n  ls->linenumber = 1;\n  ls->lastline = 1;\n  ls->source = source;\n  /* all three strings here (\"_ENV\", \"break\", \"global\") were fixed,\n     so they cannot be collected */\n  ls->envn = luaS_newliteral(L, LUA_ENV);  /* get env string */\n  ls->brkn = luaS_newliteral(L, \"break\");  /* get \"break\" string */\n#if defined(LUA_COMPAT_GLOBAL)\n  /* compatibility mode: \"global\" is not a reserved word */\n  ls->glbn = luaS_newliteral(L, \"global\");  /* get \"global\" string */\n  ls->glbn->extra = 0;  /* mark it as not reserved */\n#endif\n  luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER);  /* initialize buffer */\n}\n\n\n\n/*\n** =======================================================\n** LEXICAL ANALYZER\n** =======================================================\n*/\n\n\nstatic int check_next1 (LexState *ls, int c) {\n  if (ls->current == c) {\n    next(ls);\n    return 1;\n  }\n  else return 0;\n}\n\n\n/*\n** Check whether current char is in set 'set' (with two chars) and\n** saves it\n*/\nstatic int check_next2 (LexState *ls, const char *set) {\n  lua_assert(set[2] == '\\0');\n  if (ls->current == set[0] || ls->current == set[1]) {\n    save_and_next(ls);\n    return 1;\n  }\n  else return 0;\n}\n\n\n/* LUA_NUMBER */\n/*\n** This function is quite liberal in what it accepts, as 'luaO_str2num'\n** will reject ill-formed numerals. Roughly, it accepts the following\n** pattern:\n**\n**   %d(%x|%.|([Ee][+-]?))* | 0[Xx](%x|%.|([Pp][+-]?))*\n**\n** The only tricky part is to accept [+-] only after a valid exponent\n** mark, to avoid reading '3-4' or '0xe+1' as a single number.\n**\n** The caller might have already read an initial dot.\n*/\nstatic int read_numeral (LexState *ls, SemInfo *seminfo) {\n  TValue obj;\n  const char *expo = \"Ee\";\n  int first = ls->current;\n  lua_assert(lisdigit(ls->current));\n  save_and_next(ls);\n  if (first == '0' && check_next2(ls, \"xX\"))  /* hexadecimal? */\n    expo = \"Pp\";\n  for (;;) {\n    if (check_next2(ls, expo))  /* exponent mark? */\n      check_next2(ls, \"-+\");  /* optional exponent sign */\n    else if (lisxdigit(ls->current) || ls->current == '.')  /* '%x|%.' */\n      save_and_next(ls);\n    else break;\n  }\n  if (lislalpha(ls->current))  /* is numeral touching a letter? */\n    save_and_next(ls);  /* force an error */\n  save(ls, '\\0');\n  if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0)  /* format error? */\n    lexerror(ls, \"malformed number\", TK_FLT);\n  if (ttisinteger(&obj)) {\n    seminfo->i = ivalue(&obj);\n    return TK_INT;\n  }\n  else {\n    lua_assert(ttisfloat(&obj));\n    seminfo->r = fltvalue(&obj);\n    return TK_FLT;\n  }\n}\n\n\n/*\n** read a sequence '[=*[' or ']=*]', leaving the last bracket. If\n** sequence is well formed, return its number of '='s + 2; otherwise,\n** return 1 if it is a single bracket (no '='s and no 2nd bracket);\n** otherwise (an unfinished '[==...') return 0.\n*/\nstatic size_t skip_sep (LexState *ls) {\n  size_t count = 0;\n  int s = ls->current;\n  lua_assert(s == '[' || s == ']');\n  save_and_next(ls);\n  while (ls->current == '=') {\n    save_and_next(ls);\n    count++;\n  }\n  return (ls->current == s) ? count + 2\n         : (count == 0) ? 1\n         : 0;\n}\n\n\nstatic void read_long_string (LexState *ls, SemInfo *seminfo, size_t sep) {\n  int line = ls->linenumber;  /* initial line (for error message) */\n  save_and_next(ls);  /* skip 2nd '[' */\n  if (currIsNewline(ls))  /* string starts with a newline? */\n    inclinenumber(ls);  /* skip it */\n  for (;;) {\n    switch (ls->current) {\n      case EOZ: {  /* error */\n        const char *what = (seminfo ? \"string\" : \"comment\");\n        const char *msg = luaO_pushfstring(ls->L,\n                     \"unfinished long %s (starting at line %d)\", what, line);\n        lexerror(ls, msg, TK_EOS);\n        break;  /* to avoid warnings */\n      }\n      case ']': {\n        if (skip_sep(ls) == sep) {\n          save_and_next(ls);  /* skip 2nd ']' */\n          goto endloop;\n        }\n        break;\n      }\n      case '\\n': case '\\r': {\n        save(ls, '\\n');\n        inclinenumber(ls);\n        if (!seminfo) luaZ_resetbuffer(ls->buff);  /* avoid wasting space */\n        break;\n      }\n      default: {\n        if (seminfo) save_and_next(ls);\n        else next(ls);\n      }\n    }\n  } endloop:\n  if (seminfo)\n    seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + sep,\n                                     luaZ_bufflen(ls->buff) - 2 * sep);\n}\n\n\nstatic void esccheck (LexState *ls, int c, const char *msg) {\n  if (!c) {\n    if (ls->current != EOZ)\n      save_and_next(ls);  /* add current to buffer for error message */\n    lexerror(ls, msg, TK_STRING);\n  }\n}\n\n\nstatic int gethexa (LexState *ls) {\n  save_and_next(ls);\n  esccheck (ls, lisxdigit(ls->current), \"hexadecimal digit expected\");\n  return luaO_hexavalue(ls->current);\n}\n\n\nstatic int readhexaesc (LexState *ls) {\n  int r = gethexa(ls);\n  r = (r << 4) + gethexa(ls);\n  luaZ_buffremove(ls->buff, 2);  /* remove saved chars from buffer */\n  return r;\n}\n\n\n/*\n** When reading a UTF-8 escape sequence, save everything to the buffer\n** for error reporting in case of errors; 'i' counts the number of\n** saved characters, so that they can be removed if case of success.\n*/\nstatic l_uint32 readutf8esc (LexState *ls) {\n  l_uint32 r;\n  int i = 4;  /* number of chars to be removed: start with #\"\\u{X\" */\n  save_and_next(ls);  /* skip 'u' */\n  esccheck(ls, ls->current == '{', \"missing '{'\");\n  r = cast_uint(gethexa(ls));  /* must have at least one digit */\n  while (cast_void(save_and_next(ls)), lisxdigit(ls->current)) {\n    i++;\n    esccheck(ls, r <= (0x7FFFFFFFu >> 4), \"UTF-8 value too large\");\n    r = (r << 4) + luaO_hexavalue(ls->current);\n  }\n  esccheck(ls, ls->current == '}', \"missing '}'\");\n  next(ls);  /* skip '}' */\n  luaZ_buffremove(ls->buff, i);  /* remove saved chars from buffer */\n  return r;\n}\n\n\nstatic void utf8esc (LexState *ls) {\n  char buff[UTF8BUFFSZ];\n  int n = luaO_utf8esc(buff, readutf8esc(ls));\n  for (; n > 0; n--)  /* add 'buff' to string */\n    save(ls, buff[UTF8BUFFSZ - n]);\n}\n\n\nstatic int readdecesc (LexState *ls) {\n  int i;\n  int r = 0;  /* result accumulator */\n  for (i = 0; i < 3 && lisdigit(ls->current); i++) {  /* read up to 3 digits */\n    r = 10*r + ls->current - '0';\n    save_and_next(ls);\n  }\n  esccheck(ls, r <= UCHAR_MAX, \"decimal escape too large\");\n  luaZ_buffremove(ls->buff, i);  /* remove read digits from buffer */\n  return r;\n}\n\n\nstatic void read_string (LexState *ls, int del, SemInfo *seminfo) {\n  save_and_next(ls);  /* keep delimiter (for error messages) */\n  while (ls->current != del) {\n    switch (ls->current) {\n      case EOZ:\n        lexerror(ls, \"unfinished string\", TK_EOS);\n        break;  /* to avoid warnings */\n      case '\\n':\n      case '\\r':\n        lexerror(ls, \"unfinished string\", TK_STRING);\n        break;  /* to avoid warnings */\n      case '\\\\': {  /* escape sequences */\n        int c;  /* final character to be saved */\n        save_and_next(ls);  /* keep '\\\\' for error messages */\n        switch (ls->current) {\n          case 'a': c = '\\a'; goto read_save;\n          case 'b': c = '\\b'; goto read_save;\n          case 'f': c = '\\f'; goto read_save;\n          case 'n': c = '\\n'; goto read_save;\n          case 'r': c = '\\r'; goto read_save;\n          case 't': c = '\\t'; goto read_save;\n          case 'v': c = '\\v'; goto read_save;\n          case 'x': c = readhexaesc(ls); goto read_save;\n          case 'u': utf8esc(ls);  goto no_save;\n          case '\\n': case '\\r':\n            inclinenumber(ls); c = '\\n'; goto only_save;\n          case '\\\\': case '\\\"': case '\\'':\n            c = ls->current; goto read_save;\n          case EOZ: goto no_save;  /* will raise an error next loop */\n          case 'z': {  /* zap following span of spaces */\n            luaZ_buffremove(ls->buff, 1);  /* remove '\\\\' */\n            next(ls);  /* skip the 'z' */\n            while (lisspace(ls->current)) {\n              if (currIsNewline(ls)) inclinenumber(ls);\n              else next(ls);\n            }\n            goto no_save;\n          }\n          default: {\n            esccheck(ls, lisdigit(ls->current), \"invalid escape sequence\");\n            c = readdecesc(ls);  /* digital escape '\\ddd' */\n            goto only_save;\n          }\n        }\n       read_save:\n         next(ls);\n         /* go through */\n       only_save:\n         luaZ_buffremove(ls->buff, 1);  /* remove '\\\\' */\n         save(ls, c);\n         /* go through */\n       no_save: break;\n      }\n      default:\n        save_and_next(ls);\n    }\n  }\n  save_and_next(ls);  /* skip delimiter */\n  seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,\n                                   luaZ_bufflen(ls->buff) - 2);\n}\n\n\nstatic int llex (LexState *ls, SemInfo *seminfo) {\n  luaZ_resetbuffer(ls->buff);\n  for (;;) {\n    switch (ls->current) {\n      case '\\n': case '\\r': {  /* line breaks */\n        inclinenumber(ls);\n        break;\n      }\n      case ' ': case '\\f': case '\\t': case '\\v': {  /* spaces */\n        next(ls);\n        break;\n      }\n      case '-': {  /* '-' or '--' (comment) */\n        next(ls);\n        if (ls->current != '-') return '-';\n        /* else is a comment */\n        next(ls);\n        if (ls->current == '[') {  /* long comment? */\n          size_t sep = skip_sep(ls);\n          luaZ_resetbuffer(ls->buff);  /* 'skip_sep' may dirty the buffer */\n          if (sep >= 2) {\n            read_long_string(ls, NULL, sep);  /* skip long comment */\n            luaZ_resetbuffer(ls->buff);  /* previous call may dirty the buff. */\n            break;\n          }\n        }\n        /* else short comment */\n        while (!currIsNewline(ls) && ls->current != EOZ)\n          next(ls);  /* skip until end of line (or end of file) */\n        break;\n      }\n      case '[': {  /* long string or simply '[' */\n        size_t sep = skip_sep(ls);\n        if (sep >= 2) {\n          read_long_string(ls, seminfo, sep);\n          return TK_STRING;\n        }\n        else if (sep == 0)  /* '[=...' missing second bracket? */\n          lexerror(ls, \"invalid long string delimiter\", TK_STRING);\n        return '[';\n      }\n      case '=': {\n        next(ls);\n        if (check_next1(ls, '=')) return TK_EQ;  /* '==' */\n        else return '=';\n      }\n      case '<': {\n        next(ls);\n        if (check_next1(ls, '=')) return TK_LE;  /* '<=' */\n        else if (check_next1(ls, '<')) return TK_SHL;  /* '<<' */\n        else return '<';\n      }\n      case '>': {\n        next(ls);\n        if (check_next1(ls, '=')) return TK_GE;  /* '>=' */\n        else if (check_next1(ls, '>')) return TK_SHR;  /* '>>' */\n        else return '>';\n      }\n      case '/': {\n        next(ls);\n        if (check_next1(ls, '/')) return TK_IDIV;  /* '//' */\n        else return '/';\n      }\n      case '~': {\n        next(ls);\n        if (check_next1(ls, '=')) return TK_NE;  /* '~=' */\n        else return '~';\n      }\n      case ':': {\n        next(ls);\n        if (check_next1(ls, ':')) return TK_DBCOLON;  /* '::' */\n        else return ':';\n      }\n      case '\"': case '\\'': {  /* short literal strings */\n        read_string(ls, ls->current, seminfo);\n        return TK_STRING;\n      }\n      case '.': {  /* '.', '..', '...', or number */\n        save_and_next(ls);\n        if (check_next1(ls, '.')) {\n          if (check_next1(ls, '.'))\n            return TK_DOTS;   /* '...' */\n          else return TK_CONCAT;   /* '..' */\n        }\n        else if (!lisdigit(ls->current)) return '.';\n        else return read_numeral(ls, seminfo);\n      }\n      case '0': case '1': case '2': case '3': case '4':\n      case '5': case '6': case '7': case '8': case '9': {\n        return read_numeral(ls, seminfo);\n      }\n      case EOZ: {\n        return TK_EOS;\n      }\n      default: {\n        if (lislalpha(ls->current)) {  /* identifier or reserved word? */\n          TString *ts;\n          do {\n            save_and_next(ls);\n          } while (lislalnum(ls->current));\n          /* find or create string */\n          ts = luaS_newlstr(ls->L, luaZ_buffer(ls->buff),\n                                   luaZ_bufflen(ls->buff));\n          if (isreserved(ts))   /* reserved word? */\n            return ts->extra - 1 + FIRST_RESERVED;\n          else {\n            seminfo->ts = anchorstr(ls, ts);\n            return TK_NAME;\n          }\n        }\n        else {  /* single-char tokens ('+', '*', '%', '{', '}', ...) */\n          int c = ls->current;\n          next(ls);\n          return c;\n        }\n      }\n    }\n  }\n}\n\n\nvoid luaX_next (LexState *ls) {\n  ls->lastline = ls->linenumber;\n  if (ls->lookahead.token != TK_EOS) {  /* is there a look-ahead token? */\n    ls->t = ls->lookahead;  /* use this one */\n    ls->lookahead.token = TK_EOS;  /* and discharge it */\n  }\n  else\n    ls->t.token = llex(ls, &ls->t.seminfo);  /* read next token */\n}\n\n\nint luaX_lookahead (LexState *ls) {\n  lua_assert(ls->lookahead.token == TK_EOS);\n  ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);\n  return ls->lookahead.token;\n}\n\n"
  },
  {
    "path": "3rd/lua/llex.h",
    "content": "/*\n** $Id: llex.h $\n** Lexical Analyzer\n** See Copyright Notice in lua.h\n*/\n\n#ifndef llex_h\n#define llex_h\n\n#include <limits.h>\n\n#include \"lobject.h\"\n#include \"lzio.h\"\n\n\n/*\n** Single-char tokens (terminal symbols) are represented by their own\n** numeric code. Other tokens start at the following value.\n*/\n#define FIRST_RESERVED\t(UCHAR_MAX + 1)\n\n\n#if !defined(LUA_ENV)\n#define LUA_ENV\t\t\"_ENV\"\n#endif\n\n\n/*\n* WARNING: if you change the order of this enumeration,\n* grep \"ORDER RESERVED\"\n*/\nenum RESERVED {\n  /* terminal symbols denoted by reserved words */\n  TK_AND = FIRST_RESERVED, TK_BREAK,\n  TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,\n  TK_GLOBAL, TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR,\n  TK_REPEAT, TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,\n  /* other terminal symbols */\n  TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE,\n  TK_SHL, TK_SHR,\n  TK_DBCOLON, TK_EOS,\n  TK_FLT, TK_INT, TK_NAME, TK_STRING\n};\n\n/* number of reserved words */\n#define NUM_RESERVED\t(cast_int(TK_WHILE-FIRST_RESERVED + 1))\n\n\ntypedef union {\n  lua_Number r;\n  lua_Integer i;\n  TString *ts;\n} SemInfo;  /* semantics information */\n\n\ntypedef struct Token {\n  int token;\n  SemInfo seminfo;\n} Token;\n\n\n/* state of the scanner plus state of the parser when shared by all\n   functions */\ntypedef struct LexState {\n  int current;  /* current character (charint) */\n  int linenumber;  /* input line counter */\n  int lastline;  /* line of last token 'consumed' */\n  Token t;  /* current token */\n  Token lookahead;  /* look ahead token */\n  struct FuncState *fs;  /* current function (parser) */\n  struct lua_State *L;\n  ZIO *z;  /* input stream */\n  Mbuffer *buff;  /* buffer for tokens */\n  Table *h;  /* to avoid collection/reuse strings */\n  struct Dyndata *dyd;  /* dynamic structures used by the parser */\n  TString *source;  /* current source name */\n  TString *envn;  /* environment variable name */\n  TString *brkn;  /* \"break\" name (used as a label) */\n  TString *glbn;  /* \"global\" name (when not a reserved word) */\n} LexState;\n\n\nLUAI_FUNC void luaX_init (lua_State *L);\nLUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z,\n                              TString *source, int firstchar);\nLUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l);\nLUAI_FUNC void luaX_next (LexState *ls);\nLUAI_FUNC int luaX_lookahead (LexState *ls);\nLUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s);\nLUAI_FUNC const char *luaX_token2str (LexState *ls, int token);\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua/llimits.h",
    "content": "/*\n** $Id: llimits.h $\n** Limits, basic types, and some other 'installation-dependent' definitions\n** See Copyright Notice in lua.h\n*/\n\n#ifndef llimits_h\n#define llimits_h\n\n\n#include <limits.h>\n#include <stddef.h>\n\n\n#include \"lua.h\"\n\n\n#define l_numbits(t)\tcast_int(sizeof(t) * CHAR_BIT)\n\n/*\n** 'l_mem' is a signed integer big enough to count the total memory\n** used by Lua.  (It is signed due to the use of debt in several\n** computations.) 'lu_mem' is a corresponding unsigned type.  Usually,\n** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines.\n*/\n#if defined(LUAI_MEM)\t\t/* { external definitions? */\ntypedef LUAI_MEM l_mem;\ntypedef LUAI_UMEM lu_mem;\n#elif LUAI_IS32INT\t/* }{ */\ntypedef ptrdiff_t l_mem;\ntypedef size_t lu_mem;\n#else  /* 16-bit ints */\t/* }{ */\ntypedef long l_mem;\ntypedef unsigned long lu_mem;\n#endif\t\t\t\t/* } */\n\n#define MAX_LMEM  \\\n\tcast(l_mem, (cast(lu_mem, 1) << (l_numbits(l_mem) - 1)) - 1)\n\n\n/* chars used as small naturals (so that 'char' is reserved for characters) */\ntypedef unsigned char lu_byte;\ntypedef signed char ls_byte;\n\n\n/* Type for thread status/error codes */\ntypedef lu_byte TStatus;\n\n/* The C API still uses 'int' for status/error codes */\n#define APIstatus(st)\tcast_int(st)\n\n/* maximum value for size_t */\n#define MAX_SIZET\t((size_t)(~(size_t)0))\n\n/*\n** Maximum size for strings and userdata visible for Lua; should be\n** representable as a lua_Integer and as a size_t.\n*/\n#define MAX_SIZE\t(sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \\\n\t\t\t  : cast_sizet(LUA_MAXINTEGER))\n\n/*\n** test whether an unsigned value is a power of 2 (or zero)\n*/\n#define ispow2(x)\t(((x) & ((x) - 1)) == 0)\n\n\n/* number of chars of a literal string without the ending \\0 */\n#define LL(x)   (sizeof(x)/sizeof(char) - 1)\n\n\n/*\n** conversion of pointer to unsigned integer: this is for hashing only;\n** there is no problem if the integer cannot hold the whole pointer\n** value. (In strict ISO C this may cause undefined behavior, but no\n** actual machine seems to bother.)\n*/\n#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \\\n    __STDC_VERSION__ >= 199901L\n#include <stdint.h>\n#if defined(UINTPTR_MAX)  /* even in C99 this type is optional */\n#define L_P2I\tuintptr_t\n#else  /* no 'intptr'? */\n#define L_P2I\tuintmax_t  /* use the largest available integer */\n#endif\n#else  /* C89 option */\n#define L_P2I\tsize_t\n#endif\n\n#define point2uint(p)\tcast_uint((L_P2I)(p) & UINT_MAX)\n\n\n\n/* types of 'usual argument conversions' for lua_Number and lua_Integer */\ntypedef LUAI_UACNUMBER l_uacNumber;\ntypedef LUAI_UACINT l_uacInt;\n\n\n/*\n** Internal assertions for in-house debugging\n*/\n#if defined LUAI_ASSERT\n#undef NDEBUG\n#include <assert.h>\n#define lua_assert(c)           assert(c)\n#define assert_code(c)\t\tc\n#endif\n\n#if defined(lua_assert)\n#else\n#define lua_assert(c)\t\t((void)0)\n#define assert_code(c)\t\t((void)0)\n#endif\n\n#define check_exp(c,e)\t\t(lua_assert(c), (e))\n/* to avoid problems with conditions too long */\n#define lua_longassert(c)\tassert_code((c) ? (void)0 : lua_assert(0))\n\n\n/* macro to avoid warnings about unused variables */\n#if !defined(UNUSED)\n#define UNUSED(x)\t((void)(x))\n#endif\n\n\n/* type casts (a macro highlights casts in the code) */\n#define cast(t, exp)\t((t)(exp))\n\n#define cast_void(i)\tcast(void, (i))\n#define cast_voidp(i)\tcast(void *, (i))\n#define cast_num(i)\tcast(lua_Number, (i))\n#define cast_int(i)\tcast(int, (i))\n#define cast_short(i)\tcast(short, (i))\n#define cast_uint(i)\tcast(unsigned int, (i))\n#define cast_byte(i)\tcast(lu_byte, (i))\n#define cast_uchar(i)\tcast(unsigned char, (i))\n#define cast_char(i)\tcast(char, (i))\n#define cast_charp(i)\tcast(char *, (i))\n#define cast_sizet(i)\tcast(size_t, (i))\n#define cast_Integer(i)\tcast(lua_Integer, (i))\n#define cast_Inst(i)\tcast(Instruction, (i))\n\n\n/* cast a signed lua_Integer to lua_Unsigned */\n#if !defined(l_castS2U)\n#define l_castS2U(i)\t((lua_Unsigned)(i))\n#endif\n\n/*\n** cast a lua_Unsigned to a signed lua_Integer; this cast is\n** not strict ISO C, but two-complement architectures should\n** work fine.\n*/\n#if !defined(l_castU2S)\n#define l_castU2S(i)\t((lua_Integer)(i))\n#endif\n\n/*\n** cast a size_t to lua_Integer: These casts are always valid for\n** sizes of Lua objects (see MAX_SIZE)\n*/\n#define cast_st2S(sz)\t((lua_Integer)(sz))\n\n/* Cast a ptrdiff_t to size_t, when it is known that the minuend\n** comes from the subtrahend (the base)\n*/\n#define ct_diff2sz(df)\t((size_t)(df))\n\n/* ptrdiff_t to lua_Integer */\n#define ct_diff2S(df)\tcast_st2S(ct_diff2sz(df))\n\n/*\n** Special type equivalent to '(void*)' for functions (to suppress some\n** warnings when converting function pointers)\n*/\ntypedef void (*voidf)(void);\n\n/*\n** Macro to convert pointer-to-void* to pointer-to-function. This cast\n** is undefined according to ISO C, but POSIX assumes that it works.\n** (The '__extension__' in gnu compilers is only to avoid warnings.)\n*/\n#if defined(__GNUC__)\n#define cast_func(p) (__extension__ (voidf)(p))\n#else\n#define cast_func(p) ((voidf)(p))\n#endif\n\n\n\n/*\n** non-return type\n*/\n#if !defined(l_noret)\n\n#if defined(__GNUC__)\n#define l_noret\t\tvoid __attribute__((noreturn))\n#elif defined(_MSC_VER) && _MSC_VER >= 1200\n#define l_noret\t\tvoid __declspec(noreturn)\n#else\n#define l_noret\t\tvoid\n#endif\n\n#endif\n\n\n/*\n** Inline functions\n*/\n#if !defined(LUA_USE_C89)\n#define l_inline\tinline\n#elif defined(__GNUC__)\n#define l_inline\t__inline__\n#else\n#define l_inline\t/* empty */\n#endif\n\n#define l_sinline\tstatic l_inline\n\n\n/*\n** An unsigned with (at least) 4 bytes\n*/\n#if LUAI_IS32INT\ntypedef unsigned int l_uint32;\n#else\ntypedef unsigned long l_uint32;\n#endif\n\n\n/*\n** The luai_num* macros define the primitive operations over numbers.\n*/\n\n/* floor division (defined as 'floor(a/b)') */\n#if !defined(luai_numidiv)\n#define luai_numidiv(L,a,b)     ((void)L, l_floor(luai_numdiv(L,a,b)))\n#endif\n\n/* float division */\n#if !defined(luai_numdiv)\n#define luai_numdiv(L,a,b)      ((a)/(b))\n#endif\n\n/*\n** modulo: defined as 'a - floor(a/b)*b'; the direct computation\n** using this definition has several problems with rounding errors,\n** so it is better to use 'fmod'. 'fmod' gives the result of\n** 'a - trunc(a/b)*b', and therefore must be corrected when\n** 'trunc(a/b) ~= floor(a/b)'. That happens when the division has a\n** non-integer negative result: non-integer result is equivalent to\n** a non-zero remainder 'm'; negative result is equivalent to 'a' and\n** 'b' with different signs, or 'm' and 'b' with different signs\n** (as the result 'm' of 'fmod' has the same sign of 'a').\n*/\n#if !defined(luai_nummod)\n#define luai_nummod(L,a,b,m)  \\\n  { (void)L; (m) = l_mathop(fmod)(a,b); \\\n    if (((m) > 0) ? (b) < 0 : ((m) < 0 && (b) > 0)) (m) += (b); }\n#endif\n\n/* exponentiation */\n#if !defined(luai_numpow)\n#define luai_numpow(L,a,b)  \\\n  ((void)L, (b == 2) ? (a)*(a) : l_mathop(pow)(a,b))\n#endif\n\n/* the others are quite standard operations */\n#if !defined(luai_numadd)\n#define luai_numadd(L,a,b)      ((a)+(b))\n#define luai_numsub(L,a,b)      ((a)-(b))\n#define luai_nummul(L,a,b)      ((a)*(b))\n#define luai_numunm(L,a)        (-(a))\n#define luai_numeq(a,b)         ((a)==(b))\n#define luai_numlt(a,b)         ((a)<(b))\n#define luai_numle(a,b)         ((a)<=(b))\n#define luai_numgt(a,b)         ((a)>(b))\n#define luai_numge(a,b)         ((a)>=(b))\n#define luai_numisnan(a)        (!luai_numeq((a), (a)))\n#endif\n\n\n\n/*\n** lua_numbertointeger converts a float number with an integral value\n** to an integer, or returns 0 if the float is not within the range of\n** a lua_Integer.  (The range comparisons are tricky because of\n** rounding. The tests here assume a two-complement representation,\n** where MININTEGER always has an exact representation as a float;\n** MAXINTEGER may not have one, and therefore its conversion to float\n** may have an ill-defined value.)\n*/\n#define lua_numbertointeger(n,p) \\\n  ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \\\n   (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \\\n      (*(p) = (LUA_INTEGER)(n), 1))\n\n\n\n/*\n** LUAI_FUNC is a mark for all extern functions that are not to be\n** exported to outside modules.\n** LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables,\n** none of which to be exported to outside modules (LUAI_DDEF for\n** definitions and LUAI_DDEC for declarations).\n** Elf and MACH/gcc (versions 3.2 and later) mark them as \"hidden\" to\n** optimize access when Lua is compiled as a shared library. Not all elf\n** targets support this attribute. Unfortunately, gcc does not offer\n** a way to check whether the target offers that support, and those\n** without support give a warning about it. To avoid these warnings,\n** change to the default definition.\n*/\n#if !defined(LUAI_FUNC)\n\n#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \\\n    (defined(__ELF__) || defined(__MACH__))\n#define LUAI_FUNC\t__attribute__((visibility(\"internal\"))) extern\n#else\n#define LUAI_FUNC\textern\n#endif\n\n#define LUAI_DDEC(dec)\tLUAI_FUNC dec\n#define LUAI_DDEF\t/* empty */\n\n#endif\n\n\n/* Give these macros simpler names for internal use */\n#define l_likely(x)\tluai_likely(x)\n#define l_unlikely(x)\tluai_unlikely(x)\n\n/*\n** {==================================================================\n** \"Abstraction Layer\" for basic report of messages and errors\n** ===================================================================\n*/\n\n/* print a string */\n#if !defined(lua_writestring)\n#define lua_writestring(s,l)   fwrite((s), sizeof(char), (l), stdout)\n#endif\n\n/* print a newline and flush the output */\n#if !defined(lua_writeline)\n#define lua_writeline()        (lua_writestring(\"\\n\", 1), fflush(stdout))\n#endif\n\n/* print an error message */\n#if !defined(lua_writestringerror)\n#define lua_writestringerror(s,p) \\\n        (fprintf(stderr, (s), (p)), fflush(stderr))\n#endif\n\n/* }================================================================== */\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/lmathlib.c",
    "content": "/*\n** $Id: lmathlib.c $\n** Standard mathematical library\n** See Copyright Notice in lua.h\n*/\n\n#define lmathlib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <float.h>\n#include <limits.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\n#undef PI\n#define PI\t(l_mathop(3.141592653589793238462643383279502884))\n\n\nstatic int math_abs (lua_State *L) {\n  if (lua_isinteger(L, 1)) {\n    lua_Integer n = lua_tointeger(L, 1);\n    if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n);\n    lua_pushinteger(L, n);\n  }\n  else\n    lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\n\nstatic int math_sin (lua_State *L) {\n  lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\n\nstatic int math_cos (lua_State *L) {\n  lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\n\nstatic int math_tan (lua_State *L) {\n  lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\n\nstatic int math_asin (lua_State *L) {\n  lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\n\nstatic int math_acos (lua_State *L) {\n  lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\n\nstatic int math_atan (lua_State *L) {\n  lua_Number y = luaL_checknumber(L, 1);\n  lua_Number x = luaL_optnumber(L, 2, 1);\n  lua_pushnumber(L, l_mathop(atan2)(y, x));\n  return 1;\n}\n\n\nstatic int math_toint (lua_State *L) {\n  int valid;\n  lua_Integer n = lua_tointegerx(L, 1, &valid);\n  if (l_likely(valid))\n    lua_pushinteger(L, n);\n  else {\n    luaL_checkany(L, 1);\n    luaL_pushfail(L);  /* value is not convertible to integer */\n  }\n  return 1;\n}\n\n\nstatic void pushnumint (lua_State *L, lua_Number d) {\n  lua_Integer n;\n  if (lua_numbertointeger(d, &n))  /* does 'd' fit in an integer? */\n    lua_pushinteger(L, n);  /* result is integer */\n  else\n    lua_pushnumber(L, d);  /* result is float */\n}\n\n\nstatic int math_floor (lua_State *L) {\n  if (lua_isinteger(L, 1))\n    lua_settop(L, 1);  /* integer is its own floor */\n  else {\n    lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1));\n    pushnumint(L, d);\n  }\n  return 1;\n}\n\n\nstatic int math_ceil (lua_State *L) {\n  if (lua_isinteger(L, 1))\n    lua_settop(L, 1);  /* integer is its own ceiling */\n  else {\n    lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1));\n    pushnumint(L, d);\n  }\n  return 1;\n}\n\n\nstatic int math_fmod (lua_State *L) {\n  if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) {\n    lua_Integer d = lua_tointeger(L, 2);\n    if ((lua_Unsigned)d + 1u <= 1u) {  /* special cases: -1 or 0 */\n      luaL_argcheck(L, d != 0, 2, \"zero\");\n      lua_pushinteger(L, 0);  /* avoid overflow with 0x80000... / -1 */\n    }\n    else\n      lua_pushinteger(L, lua_tointeger(L, 1) % d);\n  }\n  else\n    lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1),\n                                     luaL_checknumber(L, 2)));\n  return 1;\n}\n\n\n/*\n** next function does not use 'modf', avoiding problems with 'double*'\n** (which is not compatible with 'float*') when lua_Number is not\n** 'double'.\n*/\nstatic int math_modf (lua_State *L) {\n  if (lua_isinteger(L ,1)) {\n    lua_settop(L, 1);  /* number is its own integer part */\n    lua_pushnumber(L, 0);  /* no fractional part */\n  }\n  else {\n    lua_Number n = luaL_checknumber(L, 1);\n    /* integer part (rounds toward zero) */\n    lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n);\n    pushnumint(L, ip);\n    /* fractional part (test needed for inf/-inf) */\n    lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip));\n  }\n  return 2;\n}\n\n\nstatic int math_sqrt (lua_State *L) {\n  lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\n\nstatic int math_ult (lua_State *L) {\n  lua_Integer a = luaL_checkinteger(L, 1);\n  lua_Integer b = luaL_checkinteger(L, 2);\n  lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b);\n  return 1;\n}\n\n\nstatic int math_log (lua_State *L) {\n  lua_Number x = luaL_checknumber(L, 1);\n  lua_Number res;\n  if (lua_isnoneornil(L, 2))\n    res = l_mathop(log)(x);\n  else {\n    lua_Number base = luaL_checknumber(L, 2);\n#if !defined(LUA_USE_C89)\n    if (base == l_mathop(2.0))\n      res = l_mathop(log2)(x);\n    else\n#endif\n    if (base == l_mathop(10.0))\n      res = l_mathop(log10)(x);\n    else\n      res = l_mathop(log)(x)/l_mathop(log)(base);\n  }\n  lua_pushnumber(L, res);\n  return 1;\n}\n\n\nstatic int math_exp (lua_State *L) {\n  lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\n\nstatic int math_deg (lua_State *L) {\n  lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI));\n  return 1;\n}\n\n\nstatic int math_rad (lua_State *L) {\n  lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0)));\n  return 1;\n}\n\n\nstatic int math_frexp (lua_State *L) {\n  lua_Number x = luaL_checknumber(L, 1);\n  int ep;\n  lua_pushnumber(L, l_mathop(frexp)(x, &ep));\n  lua_pushinteger(L, ep);\n  return 2;\n}\n\n\nstatic int math_ldexp (lua_State *L) {\n  lua_Number x = luaL_checknumber(L, 1);\n  int ep = (int)luaL_checkinteger(L, 2);\n  lua_pushnumber(L, l_mathop(ldexp)(x, ep));\n  return 1;\n}\n\n\nstatic int math_min (lua_State *L) {\n  int n = lua_gettop(L);  /* number of arguments */\n  int imin = 1;  /* index of current minimum value */\n  int i;\n  luaL_argcheck(L, n >= 1, 1, \"value expected\");\n  for (i = 2; i <= n; i++) {\n    if (lua_compare(L, i, imin, LUA_OPLT))\n      imin = i;\n  }\n  lua_pushvalue(L, imin);\n  return 1;\n}\n\n\nstatic int math_max (lua_State *L) {\n  int n = lua_gettop(L);  /* number of arguments */\n  int imax = 1;  /* index of current maximum value */\n  int i;\n  luaL_argcheck(L, n >= 1, 1, \"value expected\");\n  for (i = 2; i <= n; i++) {\n    if (lua_compare(L, imax, i, LUA_OPLT))\n      imax = i;\n  }\n  lua_pushvalue(L, imax);\n  return 1;\n}\n\n\nstatic int math_type (lua_State *L) {\n  if (lua_type(L, 1) == LUA_TNUMBER)\n    lua_pushstring(L, (lua_isinteger(L, 1)) ? \"integer\" : \"float\");\n  else {\n    luaL_checkany(L, 1);\n    luaL_pushfail(L);\n  }\n  return 1;\n}\n\n\n\n/*\n** {==================================================================\n** Pseudo-Random Number Generator based on 'xoshiro256**'.\n** ===================================================================\n*/\n\n/*\n** This code uses lots of shifts. ISO C does not allow shifts greater\n** than or equal to the width of the type being shifted, so some shifts\n** are written in convoluted ways to match that restriction. For\n** preprocessor tests, it assumes a width of 32 bits, so the maximum\n** shift there is 31 bits.\n*/\n\n\n/* number of binary digits in the mantissa of a float */\n#define FIGS\tl_floatatt(MANT_DIG)\n\n#if FIGS > 64\n/* there are only 64 random bits; use them all */\n#undef FIGS\n#define FIGS\t64\n#endif\n\n\n/*\n** LUA_RAND32 forces the use of 32-bit integers in the implementation\n** of the PRN generator (mainly for testing).\n*/\n#if !defined(LUA_RAND32) && !defined(Rand64)\n\n/* try to find an integer type with at least 64 bits */\n\n#if ((ULONG_MAX >> 31) >> 31) >= 3\n\n/* 'long' has at least 64 bits */\n#define Rand64\t\tunsigned long\n#define SRand64\t\tlong\n\n#elif !defined(LUA_USE_C89) && defined(LLONG_MAX)\n\n/* there is a 'long long' type (which must have at least 64 bits) */\n#define Rand64\t\tunsigned long long\n#define SRand64\t\tlong long\n\n#elif ((LUA_MAXUNSIGNED >> 31) >> 31) >= 3\n\n/* 'lua_Unsigned' has at least 64 bits */\n#define Rand64\t\tlua_Unsigned\n#define SRand64\t\tlua_Integer\n\n#endif\n\n#endif\n\n\n#if defined(Rand64)  /* { */\n\n/*\n** Standard implementation, using 64-bit integers.\n** If 'Rand64' has more than 64 bits, the extra bits do not interfere\n** with the 64 initial bits, except in a right shift. Moreover, the\n** final result has to discard the extra bits.\n*/\n\n/* avoid using extra bits when needed */\n#define trim64(x)\t((x) & 0xffffffffffffffffu)\n\n\n/* rotate left 'x' by 'n' bits */\nstatic Rand64 rotl (Rand64 x, int n) {\n  return (x << n) | (trim64(x) >> (64 - n));\n}\n\nstatic Rand64 nextrand (Rand64 *state) {\n  Rand64 state0 = state[0];\n  Rand64 state1 = state[1];\n  Rand64 state2 = state[2] ^ state0;\n  Rand64 state3 = state[3] ^ state1;\n  Rand64 res = rotl(state1 * 5, 7) * 9;\n  state[0] = state0 ^ state3;\n  state[1] = state1 ^ state2;\n  state[2] = state2 ^ (state1 << 17);\n  state[3] = rotl(state3, 45);\n  return res;\n}\n\n\n/*\n** Convert bits from a random integer into a float in the\n** interval [0,1), getting the higher FIG bits from the\n** random unsigned integer and converting that to a float.\n** Some old Microsoft compilers cannot cast an unsigned long\n** to a floating-point number, so we use a signed long as an\n** intermediary. When lua_Number is float or double, the shift ensures\n** that 'sx' is non negative; in that case, a good compiler will remove\n** the correction.\n*/\n\n/* must throw out the extra (64 - FIGS) bits */\n#define shift64_FIG\t(64 - FIGS)\n\n/* 2^(-FIGS) == 2^-1 / 2^(FIGS-1) */\n#define scaleFIG\t(l_mathop(0.5) / ((Rand64)1 << (FIGS - 1)))\n\nstatic lua_Number I2d (Rand64 x) {\n  SRand64 sx = (SRand64)(trim64(x) >> shift64_FIG);\n  lua_Number res = (lua_Number)(sx) * scaleFIG;\n  if (sx < 0)\n    res += l_mathop(1.0);  /* correct the two's complement if negative */\n  lua_assert(0 <= res && res < 1);\n  return res;\n}\n\n/* convert a 'Rand64' to a 'lua_Unsigned' */\n#define I2UInt(x)\t((lua_Unsigned)trim64(x))\n\n/* convert a 'lua_Unsigned' to a 'Rand64' */\n#define Int2I(x)\t((Rand64)(x))\n\n\n#else\t/* no 'Rand64'   }{ */\n\n/*\n** Use two 32-bit integers to represent a 64-bit quantity.\n*/\ntypedef struct Rand64 {\n  l_uint32 h;  /* higher half */\n  l_uint32 l;  /* lower half */\n} Rand64;\n\n\n/*\n** If 'l_uint32' has more than 32 bits, the extra bits do not interfere\n** with the 32 initial bits, except in a right shift and comparisons.\n** Moreover, the final result has to discard the extra bits.\n*/\n\n/* avoid using extra bits when needed */\n#define trim32(x)\t((x) & 0xffffffffu)\n\n\n/*\n** basic operations on 'Rand64' values\n*/\n\n/* build a new Rand64 value */\nstatic Rand64 packI (l_uint32 h, l_uint32 l) {\n  Rand64 result;\n  result.h = h;\n  result.l = l;\n  return result;\n}\n\n/* return i << n */\nstatic Rand64 Ishl (Rand64 i, int n) {\n  lua_assert(n > 0 && n < 32);\n  return packI((i.h << n) | (trim32(i.l) >> (32 - n)), i.l << n);\n}\n\n/* i1 ^= i2 */\nstatic void Ixor (Rand64 *i1, Rand64 i2) {\n  i1->h ^= i2.h;\n  i1->l ^= i2.l;\n}\n\n/* return i1 + i2 */\nstatic Rand64 Iadd (Rand64 i1, Rand64 i2) {\n  Rand64 result = packI(i1.h + i2.h, i1.l + i2.l);\n  if (trim32(result.l) < trim32(i1.l))  /* carry? */\n    result.h++;\n  return result;\n}\n\n/* return i * 5 */\nstatic Rand64 times5 (Rand64 i) {\n  return Iadd(Ishl(i, 2), i);  /* i * 5 == (i << 2) + i */\n}\n\n/* return i * 9 */\nstatic Rand64 times9 (Rand64 i) {\n  return Iadd(Ishl(i, 3), i);  /* i * 9 == (i << 3) + i */\n}\n\n/* return 'i' rotated left 'n' bits */\nstatic Rand64 rotl (Rand64 i, int n) {\n  lua_assert(n > 0 && n < 32);\n  return packI((i.h << n) | (trim32(i.l) >> (32 - n)),\n               (trim32(i.h) >> (32 - n)) | (i.l << n));\n}\n\n/* for offsets larger than 32, rotate right by 64 - offset */\nstatic Rand64 rotl1 (Rand64 i, int n) {\n  lua_assert(n > 32 && n < 64);\n  n = 64 - n;\n  return packI((trim32(i.h) >> n) | (i.l << (32 - n)),\n               (i.h << (32 - n)) | (trim32(i.l) >> n));\n}\n\n/*\n** implementation of 'xoshiro256**' algorithm on 'Rand64' values\n*/\nstatic Rand64 nextrand (Rand64 *state) {\n  Rand64 res = times9(rotl(times5(state[1]), 7));\n  Rand64 t = Ishl(state[1], 17);\n  Ixor(&state[2], state[0]);\n  Ixor(&state[3], state[1]);\n  Ixor(&state[1], state[2]);\n  Ixor(&state[0], state[3]);\n  Ixor(&state[2], t);\n  state[3] = rotl1(state[3], 45);\n  return res;\n}\n\n\n/*\n** Converts a 'Rand64' into a float.\n*/\n\n/* an unsigned 1 with proper type */\n#define UONE\t\t((l_uint32)1)\n\n\n#if FIGS <= 32\n\n/* 2^(-FIGS) */\n#define scaleFIG       (l_mathop(0.5) / (UONE << (FIGS - 1)))\n\n/*\n** get up to 32 bits from higher half, shifting right to\n** throw out the extra bits.\n*/\nstatic lua_Number I2d (Rand64 x) {\n  lua_Number h = (lua_Number)(trim32(x.h) >> (32 - FIGS));\n  return h * scaleFIG;\n}\n\n#else\t/* 32 < FIGS <= 64 */\n\n/* 2^(-FIGS) = 1.0 / 2^30 / 2^3 / 2^(FIGS-33) */\n#define scaleFIG  \\\n    (l_mathop(1.0) / (UONE << 30) / l_mathop(8.0) / (UONE << (FIGS - 33)))\n\n/*\n** use FIGS - 32 bits from lower half, throwing out the other\n** (32 - (FIGS - 32)) = (64 - FIGS) bits\n*/\n#define shiftLOW\t(64 - FIGS)\n\n/*\n** higher 32 bits go after those (FIGS - 32) bits: shiftHI = 2^(FIGS - 32)\n*/\n#define shiftHI\t\t((lua_Number)(UONE << (FIGS - 33)) * l_mathop(2.0))\n\n\nstatic lua_Number I2d (Rand64 x) {\n  lua_Number h = (lua_Number)trim32(x.h) * shiftHI;\n  lua_Number l = (lua_Number)(trim32(x.l) >> shiftLOW);\n  return (h + l) * scaleFIG;\n}\n\n#endif\n\n\n/* convert a 'Rand64' to a 'lua_Unsigned' */\nstatic lua_Unsigned I2UInt (Rand64 x) {\n  return (((lua_Unsigned)trim32(x.h) << 31) << 1) | (lua_Unsigned)trim32(x.l);\n}\n\n/* convert a 'lua_Unsigned' to a 'Rand64' */\nstatic Rand64 Int2I (lua_Unsigned n) {\n  return packI((l_uint32)((n >> 31) >> 1), (l_uint32)n);\n}\n\n#endif  /* } */\n\n\n/*\n** A state uses four 'Rand64' values.\n*/\ntypedef struct {\n  Rand64 s[4];\n} RanState;\n\n\n/*\n** Project the random integer 'ran' into the interval [0, n].\n** Because 'ran' has 2^B possible values, the projection can only be\n** uniform when the size of the interval is a power of 2 (exact\n** division). So, to get a uniform projection into [0, n], we\n** first compute 'lim', the smallest Mersenne number not smaller than\n** 'n'. We then project 'ran' into the interval [0, lim].  If the result\n** is inside [0, n], we are done. Otherwise, we try with another 'ran',\n** until we have a result inside the interval.\n*/\nstatic lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n,\n                             RanState *state) {\n  lua_Unsigned lim = n;  /* to compute the Mersenne number */\n  int sh;  /* how much to spread bits to the right in 'lim' */\n  /* spread '1' bits in 'lim' until it becomes a Mersenne number */\n  for (sh = 1; (lim & (lim + 1)) != 0; sh *= 2)\n    lim |= (lim >> sh);  /* spread '1's to the right */\n  while ((ran &= lim) > n)  /* project 'ran' into [0..lim] and test */\n    ran = I2UInt(nextrand(state->s));  /* not inside [0..n]? try again */\n  return ran;\n}\n\n\nstatic int math_random (lua_State *L) {\n  lua_Integer low, up;\n  lua_Unsigned p;\n  RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));\n  Rand64 rv = nextrand(state->s);  /* next pseudo-random value */\n  switch (lua_gettop(L)) {  /* check number of arguments */\n    case 0: {  /* no arguments */\n      lua_pushnumber(L, I2d(rv));  /* float between 0 and 1 */\n      return 1;\n    }\n    case 1: {  /* only upper limit */\n      low = 1;\n      up = luaL_checkinteger(L, 1);\n      if (up == 0) {  /* single 0 as argument? */\n        lua_pushinteger(L, l_castU2S(I2UInt(rv)));  /* full random integer */\n        return 1;\n      }\n      break;\n    }\n    case 2: {  /* lower and upper limits */\n      low = luaL_checkinteger(L, 1);\n      up = luaL_checkinteger(L, 2);\n      break;\n    }\n    default: return luaL_error(L, \"wrong number of arguments\");\n  }\n  /* random integer in the interval [low, up] */\n  luaL_argcheck(L, low <= up, 1, \"interval is empty\");\n  /* project random integer into the interval [0, up - low] */\n  p = project(I2UInt(rv), l_castS2U(up) - l_castS2U(low), state);\n  lua_pushinteger(L, l_castU2S(p + l_castS2U(low)));\n  return 1;\n}\n\n\nstatic void setseed (lua_State *L, Rand64 *state,\n                     lua_Unsigned n1, lua_Unsigned n2) {\n  int i;\n  state[0] = Int2I(n1);\n  state[1] = Int2I(0xff);  /* avoid a zero state */\n  state[2] = Int2I(n2);\n  state[3] = Int2I(0);\n  for (i = 0; i < 16; i++)\n    nextrand(state);  /* discard initial values to \"spread\" seed */\n  lua_pushinteger(L, l_castU2S(n1));\n  lua_pushinteger(L, l_castU2S(n2));\n}\n\n\nstatic int math_randomseed (lua_State *L) {\n  RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));\n  lua_Unsigned n1, n2;\n  if (lua_isnone(L, 1)) {\n    n1 = luaL_makeseed(L);  /* \"random\" seed */\n    n2 = I2UInt(nextrand(state->s));  /* in case seed is not that random... */\n  }\n  else {\n    n1 = l_castS2U(luaL_checkinteger(L, 1));\n    n2 = l_castS2U(luaL_optinteger(L, 2, 0));\n  }\n  setseed(L, state->s, n1, n2);\n  return 2;  /* return seeds */\n}\n\n\nstatic const luaL_Reg randfuncs[] = {\n  {\"random\", math_random},\n  {\"randomseed\", math_randomseed},\n  {NULL, NULL}\n};\n\n\n/*\n** Register the random functions and initialize their state.\n*/\nstatic void setrandfunc (lua_State *L) {\n  RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0);\n  setseed(L, state->s, luaL_makeseed(L), 0);  /* initialize with random seed */\n  lua_pop(L, 2);  /* remove pushed seeds */\n  luaL_setfuncs(L, randfuncs, 1);\n}\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Deprecated functions (for compatibility only)\n** ===================================================================\n*/\n#if defined(LUA_COMPAT_MATHLIB)\n\nstatic int math_cosh (lua_State *L) {\n  lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\nstatic int math_sinh (lua_State *L) {\n  lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\nstatic int math_tanh (lua_State *L) {\n  lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\nstatic int math_pow (lua_State *L) {\n  lua_Number x = luaL_checknumber(L, 1);\n  lua_Number y = luaL_checknumber(L, 2);\n  lua_pushnumber(L, l_mathop(pow)(x, y));\n  return 1;\n}\n\nstatic int math_log10 (lua_State *L) {\n  lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1)));\n  return 1;\n}\n\n#endif\n/* }================================================================== */\n\n\n\nstatic const luaL_Reg mathlib[] = {\n  {\"abs\",   math_abs},\n  {\"acos\",  math_acos},\n  {\"asin\",  math_asin},\n  {\"atan\",  math_atan},\n  {\"ceil\",  math_ceil},\n  {\"cos\",   math_cos},\n  {\"deg\",   math_deg},\n  {\"exp\",   math_exp},\n  {\"tointeger\", math_toint},\n  {\"floor\", math_floor},\n  {\"fmod\",   math_fmod},\n  {\"frexp\", math_frexp},\n  {\"ult\",   math_ult},\n  {\"ldexp\", math_ldexp},\n  {\"log\",   math_log},\n  {\"max\",   math_max},\n  {\"min\",   math_min},\n  {\"modf\",   math_modf},\n  {\"rad\",   math_rad},\n  {\"sin\",   math_sin},\n  {\"sqrt\",  math_sqrt},\n  {\"tan\",   math_tan},\n  {\"type\", math_type},\n#if defined(LUA_COMPAT_MATHLIB)\n  {\"atan2\", math_atan},\n  {\"cosh\",   math_cosh},\n  {\"sinh\",   math_sinh},\n  {\"tanh\",   math_tanh},\n  {\"pow\",   math_pow},\n  {\"log10\", math_log10},\n#endif\n  /* placeholders */\n  {\"random\", NULL},\n  {\"randomseed\", NULL},\n  {\"pi\", NULL},\n  {\"huge\", NULL},\n  {\"maxinteger\", NULL},\n  {\"mininteger\", NULL},\n  {NULL, NULL}\n};\n\n\n/*\n** Open math library\n*/\nLUAMOD_API int luaopen_math (lua_State *L) {\n  luaL_newlib(L, mathlib);\n  lua_pushnumber(L, PI);\n  lua_setfield(L, -2, \"pi\");\n  lua_pushnumber(L, (lua_Number)HUGE_VAL);\n  lua_setfield(L, -2, \"huge\");\n  lua_pushinteger(L, LUA_MAXINTEGER);\n  lua_setfield(L, -2, \"maxinteger\");\n  lua_pushinteger(L, LUA_MININTEGER);\n  lua_setfield(L, -2, \"mininteger\");\n  setrandfunc(L);\n  return 1;\n}\n\n"
  },
  {
    "path": "3rd/lua/lmem.c",
    "content": "/*\n** $Id: lmem.c $\n** Interface to Memory Manager\n** See Copyright Notice in lua.h\n*/\n\n#define lmem_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <stddef.h>\n\n#include \"lua.h\"\n\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lgc.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n\n\n\n/*\n** About the realloc function:\n** void *frealloc (void *ud, void *ptr, size_t osize, size_t nsize);\n** ('osize' is the old size, 'nsize' is the new size)\n**\n** - frealloc(ud, p, x, 0) frees the block 'p' and returns NULL.\n** Particularly, frealloc(ud, NULL, 0, 0) does nothing,\n** which is equivalent to free(NULL) in ISO C.\n**\n** - frealloc(ud, NULL, x, s) creates a new block of size 's'\n** (no matter 'x'). Returns NULL if it cannot create the new block.\n**\n** - otherwise, frealloc(ud, b, x, y) reallocates the block 'b' from\n** size 'x' to size 'y'. Returns NULL if it cannot reallocate the\n** block to the new size.\n*/\n\n\n/*\n** Macro to call the allocation function.\n*/\n#define callfrealloc(g,block,os,ns)    ((*g->frealloc)(g->ud, block, os, ns))\n\n\n/*\n** When an allocation fails, it will try again after an emergency\n** collection, except when it cannot run a collection.  The GC should\n** not be called while the state is not fully built, as the collector\n** is not yet fully initialized. Also, it should not be called when\n** 'gcstopem' is true, because then the interpreter is in the middle of\n** a collection step.\n*/\n#define cantryagain(g)\t(completestate(g) && !g->gcstopem)\n\n\n\n\n#if defined(EMERGENCYGCTESTS)\n/*\n** First allocation will fail except when freeing a block (frees never\n** fail) and when it cannot try again; this fail will trigger 'tryagain'\n** and a full GC cycle at every allocation.\n*/\nstatic void *firsttry (global_State *g, void *block, size_t os, size_t ns) {\n  if (ns > 0 && cantryagain(g))\n    return NULL;  /* fail */\n  else  /* normal allocation */\n    return callfrealloc(g, block, os, ns);\n}\n#else\n#define firsttry(g,block,os,ns)    callfrealloc(g, block, os, ns)\n#endif\n\n\n\n\n\n/*\n** {==================================================================\n** Functions to allocate/deallocate arrays for the Parser\n** ===================================================================\n*/\n\n/*\n** Minimum size for arrays during parsing, to avoid overhead of\n** reallocating to size 1, then 2, and then 4. All these arrays\n** will be reallocated to exact sizes or erased when parsing ends.\n*/\n#define MINSIZEARRAY\t4\n\n\nvoid *luaM_growaux_ (lua_State *L, void *block, int nelems, int *psize,\n                     unsigned size_elems, int limit, const char *what) {\n  void *newblock;\n  int size = *psize;\n  if (nelems + 1 <= size)  /* does one extra element still fit? */\n    return block;  /* nothing to be done */\n  if (size >= limit / 2) {  /* cannot double it? */\n    if (l_unlikely(size >= limit))  /* cannot grow even a little? */\n      luaG_runerror(L, \"too many %s (limit is %d)\", what, limit);\n    size = limit;  /* still have at least one free place */\n  }\n  else {\n    size *= 2;\n    if (size < MINSIZEARRAY)\n      size = MINSIZEARRAY;  /* minimum size */\n  }\n  lua_assert(nelems + 1 <= size && size <= limit);\n  /* 'limit' ensures that multiplication will not overflow */\n  newblock = luaM_saferealloc_(L, block, cast_sizet(*psize) * size_elems,\n                                         cast_sizet(size) * size_elems);\n  *psize = size;  /* update only when everything else is OK */\n  return newblock;\n}\n\n\n/*\n** In prototypes, the size of the array is also its number of\n** elements (to save memory). So, if it cannot shrink an array\n** to its number of elements, the only option is to raise an\n** error.\n*/\nvoid *luaM_shrinkvector_ (lua_State *L, void *block, int *size,\n                          int final_n, unsigned size_elem) {\n  void *newblock;\n  size_t oldsize = cast_sizet(*size) * size_elem;\n  size_t newsize = cast_sizet(final_n) * size_elem;\n  lua_assert(newsize <= oldsize);\n  newblock = luaM_saferealloc_(L, block, oldsize, newsize);\n  *size = final_n;\n  return newblock;\n}\n\n/* }================================================================== */\n\n\nl_noret luaM_toobig (lua_State *L) {\n  luaG_runerror(L, \"memory allocation error: block too big\");\n}\n\n\n/*\n** Free memory\n*/\nvoid luaM_free_ (lua_State *L, void *block, size_t osize) {\n  global_State *g = G(L);\n  lua_assert((osize == 0) == (block == NULL));\n  callfrealloc(g, block, osize, 0);\n  g->GCdebt += cast(l_mem, osize);\n}\n\n\n/*\n** In case of allocation fail, this function will do an emergency\n** collection to free some memory and then try the allocation again.\n*/\nstatic void *tryagain (lua_State *L, void *block,\n                       size_t osize, size_t nsize) {\n  global_State *g = G(L);\n  if (cantryagain(g)) {\n    luaC_fullgc(L, 1);  /* try to free some memory... */\n    return callfrealloc(g, block, osize, nsize);  /* try again */\n  }\n  else return NULL;  /* cannot run an emergency collection */\n}\n\n\n/*\n** Generic allocation routine.\n*/\nvoid *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {\n  void *newblock;\n  global_State *g = G(L);\n  lua_assert((osize == 0) == (block == NULL));\n  newblock = firsttry(g, block, osize, nsize);\n  if (l_unlikely(newblock == NULL && nsize > 0)) {\n    newblock = tryagain(L, block, osize, nsize);\n    if (newblock == NULL)  /* still no memory? */\n      return NULL;  /* do not update 'GCdebt' */\n  }\n  lua_assert((nsize == 0) == (newblock == NULL));\n  g->GCdebt -= cast(l_mem, nsize) - cast(l_mem, osize);\n  return newblock;\n}\n\n\nvoid *luaM_saferealloc_ (lua_State *L, void *block, size_t osize,\n                                                    size_t nsize) {\n  void *newblock = luaM_realloc_(L, block, osize, nsize);\n  if (l_unlikely(newblock == NULL && nsize > 0))  /* allocation failed? */\n    luaM_error(L);\n  return newblock;\n}\n\n\nvoid *luaM_malloc_ (lua_State *L, size_t size, int tag) {\n  if (size == 0)\n    return NULL;  /* that's all */\n  else {\n    global_State *g = G(L);\n    void *newblock = firsttry(g, NULL, cast_sizet(tag), size);\n    if (l_unlikely(newblock == NULL)) {\n      newblock = tryagain(L, NULL, cast_sizet(tag), size);\n      if (newblock == NULL)\n        luaM_error(L);\n    }\n    g->GCdebt -= cast(l_mem, size);\n    return newblock;\n  }\n}\n"
  },
  {
    "path": "3rd/lua/lmem.h",
    "content": "/*\n** $Id: lmem.h $\n** Interface to Memory Manager\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lmem_h\n#define lmem_h\n\n\n#include <stddef.h>\n\n#include \"llimits.h\"\n#include \"lua.h\"\n\n\n#define luaM_error(L)\tluaD_throw(L, LUA_ERRMEM)\n\n\n/*\n** This macro tests whether it is safe to multiply 'n' by the size of\n** type 't' without overflows. Because 'e' is always constant, it avoids\n** the runtime division MAX_SIZET/(e).\n** (The macro is somewhat complex to avoid warnings:  The 'sizeof'\n** comparison avoids a runtime comparison when overflow cannot occur.\n** The compiler should be able to optimize the real test by itself, but\n** when it does it, it may give a warning about \"comparison is always\n** false due to limited range of data type\"; the +1 tricks the compiler,\n** avoiding this warning but also this optimization.)\n*/\n#define luaM_testsize(n,e)  \\\n\t(sizeof(n) >= sizeof(size_t) && cast_sizet((n)) + 1 > MAX_SIZET/(e))\n\n#define luaM_checksize(L,n,e)  \\\n\t(luaM_testsize(n,e) ? luaM_toobig(L) : cast_void(0))\n\n\n/*\n** Computes the minimum between 'n' and 'MAX_SIZET/sizeof(t)', so that\n** the result is not larger than 'n' and cannot overflow a 'size_t'\n** when multiplied by the size of type 't'. (Assumes that 'n' is an\n** 'int' and that 'int' is not larger than 'size_t'.)\n*/\n#define luaM_limitN(n,t)  \\\n  ((cast_sizet(n) <= MAX_SIZET/sizeof(t)) ? (n) :  \\\n     cast_int((MAX_SIZET/sizeof(t))))\n\n\n/*\n** Arrays of chars do not need any test\n*/\n#define luaM_reallocvchar(L,b,on,n)  \\\n  cast_charp(luaM_saferealloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char)))\n\n#define luaM_freemem(L, b, s)\tluaM_free_(L, (b), (s))\n#define luaM_free(L, b)\t\tluaM_free_(L, (b), sizeof(*(b)))\n#define luaM_freearray(L, b, n)   luaM_free_(L, (b), (n)*sizeof(*(b)))\n\n#define luaM_new(L,t)\t\tcast(t*, luaM_malloc_(L, sizeof(t), 0))\n#define luaM_newvector(L,n,t)  \\\n\tcast(t*, luaM_malloc_(L, cast_sizet(n)*sizeof(t), 0))\n#define luaM_newvectorchecked(L,n,t) \\\n  (luaM_checksize(L,n,sizeof(t)), luaM_newvector(L,n,t))\n\n#define luaM_newobject(L,tag,s)\tluaM_malloc_(L, (s), tag)\n\n#define luaM_newblock(L, size)\tluaM_newvector(L, size, char)\n\n#define luaM_growvector(L,v,nelems,size,t,limit,e) \\\n\t((v)=cast(t *, luaM_growaux_(L,v,nelems,&(size),sizeof(t), \\\n                         luaM_limitN(limit,t),e)))\n\n#define luaM_reallocvector(L, v,oldn,n,t) \\\n   (cast(t *, luaM_realloc_(L, v, cast_sizet(oldn) * sizeof(t), \\\n                                  cast_sizet(n) * sizeof(t))))\n\n#define luaM_shrinkvector(L,v,size,fs,t) \\\n   ((v)=cast(t *, luaM_shrinkvector_(L, v, &(size), fs, sizeof(t))))\n\nLUAI_FUNC l_noret luaM_toobig (lua_State *L);\n\n/* not to be called directly */\nLUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,\n                                                          size_t size);\nLUAI_FUNC void *luaM_saferealloc_ (lua_State *L, void *block, size_t oldsize,\n                                                              size_t size);\nLUAI_FUNC void luaM_free_ (lua_State *L, void *block, size_t osize);\nLUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int nelems,\n                               int *size, unsigned size_elem, int limit,\n                               const char *what);\nLUAI_FUNC void *luaM_shrinkvector_ (lua_State *L, void *block, int *nelem,\n                                    int final_n, unsigned size_elem);\nLUAI_FUNC void *luaM_malloc_ (lua_State *L, size_t size, int tag);\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/loadlib.c",
    "content": "/*\n** $Id: loadlib.c $\n** Dynamic library loader for Lua\n** See Copyright Notice in lua.h\n**\n** This module contains an implementation of loadlib for Unix systems\n** that have dlfcn, an implementation for Windows, and a stub for other\n** systems.\n*/\n\n#define loadlib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\n/*\n** LUA_CSUBSEP is the character that replaces dots in submodule names\n** when searching for a C loader.\n** LUA_LSUBSEP is the character that replaces dots in submodule names\n** when searching for a Lua loader.\n*/\n#if !defined(LUA_CSUBSEP)\n#define LUA_CSUBSEP\t\tLUA_DIRSEP\n#endif\n\n#if !defined(LUA_LSUBSEP)\n#define LUA_LSUBSEP\t\tLUA_DIRSEP\n#endif\n\n\n/* prefix for open functions in C libraries */\n#define LUA_POF\t\t\"luaopen_\"\n\n/* separator for open functions in C libraries */\n#define LUA_OFSEP\t\"_\"\n\n\n/*\n** key for table in the registry that keeps handles\n** for all loaded C libraries\n*/\nstatic const char *const CLIBS = \"_CLIBS\";\n\n#define LIB_FAIL\t\"open\"\n\n\n#define setprogdir(L)           ((void)0)\n\n\n/* cast void* to a Lua function */\n#define cast_Lfunc(p)\tcast(lua_CFunction, cast_func(p))\n\n\n/*\n** system-dependent functions\n*/\n\n/*\n** unload library 'lib'\n*/\nstatic void lsys_unloadlib (void *lib);\n\n/*\n** load C library in file 'path'. If 'seeglb', load with all names in\n** the library global.\n** Returns the library; in case of error, returns NULL plus an\n** error string in the stack.\n*/\nstatic void *lsys_load (lua_State *L, const char *path, int seeglb);\n\n/*\n** Try to find a function named 'sym' in library 'lib'.\n** Returns the function; in case of error, returns NULL plus an\n** error string in the stack.\n*/\nstatic lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym);\n\n\n\n\n#if defined(LUA_USE_DLOPEN)\t/* { */\n/*\n** {========================================================================\n** This is an implementation of loadlib based on the dlfcn interface,\n** which is available in all POSIX systems.\n** =========================================================================\n*/\n\n#include <dlfcn.h>\n\n\nstatic void lsys_unloadlib (void *lib) {\n  dlclose(lib);\n}\n\n\nstatic void *lsys_load (lua_State *L, const char *path, int seeglb) {\n  void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));\n  if (l_unlikely(lib == NULL))\n    lua_pushstring(L, dlerror());\n  return lib;\n}\n\n\nstatic lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {\n  lua_CFunction f = cast_Lfunc(dlsym(lib, sym));\n  if (l_unlikely(f == NULL))\n    lua_pushstring(L, dlerror());\n  return f;\n}\n\n/* }====================================================== */\n\n\n\n#elif defined(LUA_DL_DLL)\t/* }{ */\n/*\n** {======================================================================\n** This is an implementation of loadlib for Windows using native functions.\n** =======================================================================\n*/\n\n#include <windows.h>\n\n\n/*\n** optional flags for LoadLibraryEx\n*/\n#if !defined(LUA_LLE_FLAGS)\n#define LUA_LLE_FLAGS\t0\n#endif\n\n\n#undef setprogdir\n\n\n/*\n** Replace in the path (on the top of the stack) any occurrence\n** of LUA_EXEC_DIR with the executable's path.\n*/\nstatic void setprogdir (lua_State *L) {\n  char buff[MAX_PATH + 1];\n  char *lb;\n  DWORD nsize = sizeof(buff)/sizeof(char);\n  DWORD n = GetModuleFileNameA(NULL, buff, nsize);  /* get exec. name */\n  if (n == 0 || n == nsize || (lb = strrchr(buff, '\\\\')) == NULL)\n    luaL_error(L, \"unable to get ModuleFileName\");\n  else {\n    *lb = '\\0';  /* cut name on the last '\\\\' to get the path */\n    luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff);\n    lua_remove(L, -2);  /* remove original string */\n  }\n}\n\n\n\n\nstatic void pusherror (lua_State *L) {\n  int error = GetLastError();\n  char buffer[128];\n  if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,\n      NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL))\n    lua_pushstring(L, buffer);\n  else\n    lua_pushfstring(L, \"system error %d\\n\", error);\n}\n\nstatic void lsys_unloadlib (void *lib) {\n  FreeLibrary((HMODULE)lib);\n}\n\n\nstatic void *lsys_load (lua_State *L, const char *path, int seeglb) {\n  HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);\n  (void)(seeglb);  /* not used: symbols are 'global' by default */\n  if (lib == NULL) pusherror(L);\n  return lib;\n}\n\n\nstatic lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {\n  lua_CFunction f = cast_Lfunc(GetProcAddress((HMODULE)lib, sym));\n  if (f == NULL) pusherror(L);\n  return f;\n}\n\n/* }====================================================== */\n\n\n#else\t\t\t\t/* }{ */\n/*\n** {======================================================\n** Fallback for other systems\n** =======================================================\n*/\n\n#undef LIB_FAIL\n#define LIB_FAIL\t\"absent\"\n\n\n#define DLMSG\t\"dynamic libraries not enabled; check your Lua installation\"\n\n\nstatic void lsys_unloadlib (void *lib) {\n  (void)(lib);  /* not used */\n}\n\n\nstatic void *lsys_load (lua_State *L, const char *path, int seeglb) {\n  (void)(path); (void)(seeglb);  /* not used */\n  lua_pushliteral(L, DLMSG);\n  return NULL;\n}\n\n\nstatic lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {\n  (void)(lib); (void)(sym);  /* not used */\n  lua_pushliteral(L, DLMSG);\n  return NULL;\n}\n\n/* }====================================================== */\n#endif\t\t\t\t/* } */\n\n\n/*\n** {==================================================================\n** Set Paths\n** ===================================================================\n*/\n\n/*\n** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment\n** variables that Lua check to set its paths.\n*/\n#if !defined(LUA_PATH_VAR)\n#define LUA_PATH_VAR    \"LUA_PATH\"\n#endif\n\n#if !defined(LUA_CPATH_VAR)\n#define LUA_CPATH_VAR   \"LUA_CPATH\"\n#endif\n\n\n\n/*\n** return registry.LUA_NOENV as a boolean\n*/\nstatic int noenv (lua_State *L) {\n  int b;\n  lua_getfield(L, LUA_REGISTRYINDEX, \"LUA_NOENV\");\n  b = lua_toboolean(L, -1);\n  lua_pop(L, 1);  /* remove value */\n  return b;\n}\n\n\n/*\n** Set a path. (If using the default path, assume it is a string\n** literal in C and create it as an external string.)\n*/\nstatic void setpath (lua_State *L, const char *fieldname,\n                                   const char *envname,\n                                   const char *dft) {\n  const char *dftmark;\n  const char *nver = lua_pushfstring(L, \"%s%s\", envname, LUA_VERSUFFIX);\n  const char *path = getenv(nver);  /* try versioned name */\n  if (path == NULL)  /* no versioned environment variable? */\n    path = getenv(envname);  /* try unversioned name */\n  if (path == NULL || noenv(L))  /* no environment variable? */\n    lua_pushexternalstring(L, dft, strlen(dft), NULL, NULL);  /* use default */\n  else if ((dftmark = strstr(path, LUA_PATH_SEP LUA_PATH_SEP)) == NULL)\n    lua_pushstring(L, path);  /* nothing to change */\n  else {  /* path contains a \";;\": insert default path in its place */\n    size_t len = strlen(path);\n    luaL_Buffer b;\n    luaL_buffinit(L, &b);\n    if (path < dftmark) {  /* is there a prefix before ';;'? */\n      luaL_addlstring(&b, path, ct_diff2sz(dftmark - path));  /* add it */\n      luaL_addchar(&b, *LUA_PATH_SEP);\n    }\n    luaL_addstring(&b, dft);  /* add default */\n    if (dftmark < path + len - 2) {  /* is there a suffix after ';;'? */\n      luaL_addchar(&b, *LUA_PATH_SEP);\n      luaL_addlstring(&b, dftmark + 2, ct_diff2sz((path + len - 2) - dftmark));\n    }\n    luaL_pushresult(&b);\n  }\n  setprogdir(L);\n  lua_setfield(L, -3, fieldname);  /* package[fieldname] = path value */\n  lua_pop(L, 1);  /* pop versioned variable name ('nver') */\n}\n\n/* }================================================================== */\n\n\n/*\n** External strings created by DLLs may need the DLL code to be\n** deallocated. This implies that a DLL can only be unloaded after all\n** its strings were deallocated. To ensure that, we create a 'library\n** string' to represent each DLL, and when this string is deallocated\n** it closes its corresponding DLL.\n** (The string itself is irrelevant; its userdata is the DLL pointer.)\n*/\n\n\n/*\n** return registry.CLIBS[path]\n*/\nstatic void *checkclib (lua_State *L, const char *path) {\n  void *plib;\n  lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);\n  lua_getfield(L, -1, path);\n  plib = lua_touserdata(L, -1);  /* plib = CLIBS[path] */\n  lua_pop(L, 2);  /* pop CLIBS table and 'plib' */\n  return plib;\n}\n\n\n/*\n** Deallocate function for library strings.\n** Unload the DLL associated with the string being deallocated.\n*/\nstatic void *freelib (void *ud, void *ptr, size_t osize, size_t nsize) {\n  /* string itself is irrelevant and static */\n  (void)ptr; (void)osize; (void)nsize;\n  lsys_unloadlib(ud);  /* unload library represented by the string */\n  return NULL;\n}\n\n\n/*\n** Create a library string that, when deallocated, will unload 'plib'\n*/\nstatic void createlibstr (lua_State *L, void *plib) {\n  /* common content for all library strings */\n  static const char dummy[] = \"01234567890\";\n  lua_pushexternalstring(L, dummy, sizeof(dummy) - 1, freelib, plib);\n}\n\n\n/*\n** registry.CLIBS[path] = plib          -- for queries.\n** Also create a reference to strlib, so that the library string will\n** only be collected when registry.CLIBS is collected.\n*/\nstatic void addtoclib (lua_State *L, const char *path, void *plib) {\n  lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);\n  lua_pushlightuserdata(L, plib);\n  lua_setfield(L, -2, path);  /* CLIBS[path] = plib */\n  createlibstr(L, plib);\n  luaL_ref(L, -2);  /* keep library string in CLIBS */\n  lua_pop(L, 1);  /* pop CLIBS table */\n}\n\n\n/* error codes for 'lookforfunc' */\n#define ERRLIB\t\t1\n#define ERRFUNC\t\t2\n\n/*\n** Look for a C function named 'sym' in a dynamically loaded library\n** 'path'.\n** First, check whether the library is already loaded; if not, try\n** to load it.\n** Then, if 'sym' is '*', return true (as library has been loaded).\n** Otherwise, look for symbol 'sym' in the library and push a\n** C function with that symbol.\n** Return 0 with 'true' or a function in the stack; in case of\n** errors, return an error code with an error message in the stack.\n*/\nstatic int lookforfunc (lua_State *L, const char *path, const char *sym) {\n  void *reg = checkclib(L, path);  /* check loaded C libraries */\n  if (reg == NULL) {  /* must load library? */\n    reg = lsys_load(L, path, *sym == '*');  /* global symbols if 'sym'=='*' */\n    if (reg == NULL) return ERRLIB;  /* unable to load library */\n    addtoclib(L, path, reg);\n  }\n  if (*sym == '*') {  /* loading only library (no function)? */\n    lua_pushboolean(L, 1);  /* return 'true' */\n    return 0;  /* no errors */\n  }\n  else {\n    lua_CFunction f = lsys_sym(L, reg, sym);\n    if (f == NULL)\n      return ERRFUNC;  /* unable to find function */\n    lua_pushcfunction(L, f);  /* else create new function */\n    return 0;  /* no errors */\n  }\n}\n\n\nstatic int ll_loadlib (lua_State *L) {\n  const char *path = luaL_checkstring(L, 1);\n  const char *init = luaL_checkstring(L, 2);\n  int stat = lookforfunc(L, path, init);\n  if (l_likely(stat == 0))  /* no errors? */\n    return 1;  /* return the loaded function */\n  else {  /* error; error message is on stack top */\n    luaL_pushfail(L);\n    lua_insert(L, -2);\n    lua_pushstring(L, (stat == ERRLIB) ?  LIB_FAIL : \"init\");\n    return 3;  /* return fail, error message, and where */\n  }\n}\n\n\n\n/*\n** {======================================================\n** 'require' function\n** =======================================================\n*/\n\n\nstatic int readable (const char *filename) {\n  FILE *f = fopen(filename, \"r\");  /* try to open file */\n  if (f == NULL) return 0;  /* open failed */\n  fclose(f);\n  return 1;\n}\n\n\n/*\n** Get the next name in '*path' = 'name1;name2;name3;...', changing\n** the ending ';' to '\\0' to create a zero-terminated string. Return\n** NULL when list ends.\n*/\nstatic const char *getnextfilename (char **path, char *end) {\n  char *sep;\n  char *name = *path;\n  if (name == end)\n    return NULL;  /* no more names */\n  else if (*name == '\\0') {  /* from previous iteration? */\n    *name = *LUA_PATH_SEP;  /* restore separator */\n    name++;  /* skip it */\n  }\n  sep = strchr(name, *LUA_PATH_SEP);  /* find next separator */\n  if (sep == NULL)  /* separator not found? */\n    sep = end;  /* name goes until the end */\n  *sep = '\\0';  /* finish file name */\n  *path = sep;  /* will start next search from here */\n  return name;\n}\n\n\n/*\n** Given a path such as \";blabla.so;blublu.so\", pushes the string\n**\n** no file 'blabla.so'\n**\tno file 'blublu.so'\n*/\nstatic void pusherrornotfound (lua_State *L, const char *path) {\n  luaL_Buffer b;\n  luaL_buffinit(L, &b);\n  luaL_addstring(&b, \"no file '\");\n  luaL_addgsub(&b, path, LUA_PATH_SEP, \"'\\n\\tno file '\");\n  luaL_addstring(&b, \"'\");\n  luaL_pushresult(&b);\n}\n\n\nstatic const char *searchpath (lua_State *L, const char *name,\n                                             const char *path,\n                                             const char *sep,\n                                             const char *dirsep) {\n  luaL_Buffer buff;\n  char *pathname;  /* path with name inserted */\n  char *endpathname;  /* its end */\n  const char *filename;\n  /* separator is non-empty and appears in 'name'? */\n  if (*sep != '\\0' && strchr(name, *sep) != NULL)\n    name = luaL_gsub(L, name, sep, dirsep);  /* replace it by 'dirsep' */\n  luaL_buffinit(L, &buff);\n  /* add path to the buffer, replacing marks ('?') with the file name */\n  luaL_addgsub(&buff, path, LUA_PATH_MARK, name);\n  luaL_addchar(&buff, '\\0');\n  pathname = luaL_buffaddr(&buff);  /* writable list of file names */\n  endpathname = pathname + luaL_bufflen(&buff) - 1;\n  while ((filename = getnextfilename(&pathname, endpathname)) != NULL) {\n    if (readable(filename))  /* does file exist and is readable? */\n      return lua_pushstring(L, filename);  /* save and return name */\n  }\n  luaL_pushresult(&buff);  /* push path to create error message */\n  pusherrornotfound(L, lua_tostring(L, -1));  /* create error message */\n  return NULL;  /* not found */\n}\n\n\nstatic int ll_searchpath (lua_State *L) {\n  const char *f = searchpath(L, luaL_checkstring(L, 1),\n                                luaL_checkstring(L, 2),\n                                luaL_optstring(L, 3, \".\"),\n                                luaL_optstring(L, 4, LUA_DIRSEP));\n  if (f != NULL) return 1;\n  else {  /* error message is on top of the stack */\n    luaL_pushfail(L);\n    lua_insert(L, -2);\n    return 2;  /* return fail + error message */\n  }\n}\n\n\nstatic const char *findfile (lua_State *L, const char *name,\n                                           const char *pname,\n                                           const char *dirsep) {\n  const char *path;\n  lua_getfield(L, lua_upvalueindex(1), pname);\n  path = lua_tostring(L, -1);\n  if (l_unlikely(path == NULL))\n    luaL_error(L, \"'package.%s' must be a string\", pname);\n  return searchpath(L, name, path, \".\", dirsep);\n}\n\n\nstatic int checkload (lua_State *L, int stat, const char *filename) {\n  if (l_likely(stat)) {  /* module loaded successfully? */\n    lua_pushstring(L, filename);  /* will be 2nd argument to module */\n    return 2;  /* return open function and file name */\n  }\n  else\n    return luaL_error(L, \"error loading module '%s' from file '%s':\\n\\t%s\",\n                          lua_tostring(L, 1), filename, lua_tostring(L, -1));\n}\n\n\nstatic int searcher_Lua (lua_State *L) {\n  const char *filename;\n  const char *name = luaL_checkstring(L, 1);\n  filename = findfile(L, name, \"path\", LUA_LSUBSEP);\n  if (filename == NULL) return 1;  /* module not found in this path */\n  return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);\n}\n\n\n/*\n** Try to find a load function for module 'modname' at file 'filename'.\n** First, change '.' to '_' in 'modname'; then, if 'modname' has\n** the form X-Y (that is, it has an \"ignore mark\"), build a function\n** name \"luaopen_X\" and look for it. (For compatibility, if that\n** fails, it also tries \"luaopen_Y\".) If there is no ignore mark,\n** look for a function named \"luaopen_modname\".\n*/\nstatic int loadfunc (lua_State *L, const char *filename, const char *modname) {\n  const char *openfunc;\n  const char *mark;\n  modname = luaL_gsub(L, modname, \".\", LUA_OFSEP);\n  mark = strchr(modname, *LUA_IGMARK);\n  if (mark) {\n    int stat;\n    openfunc = lua_pushlstring(L, modname, ct_diff2sz(mark - modname));\n    openfunc = lua_pushfstring(L, LUA_POF\"%s\", openfunc);\n    stat = lookforfunc(L, filename, openfunc);\n    if (stat != ERRFUNC) return stat;\n    modname = mark + 1;  /* else go ahead and try old-style name */\n  }\n  openfunc = lua_pushfstring(L, LUA_POF\"%s\", modname);\n  return lookforfunc(L, filename, openfunc);\n}\n\n\nstatic int searcher_C (lua_State *L) {\n  const char *name = luaL_checkstring(L, 1);\n  const char *filename = findfile(L, name, \"cpath\", LUA_CSUBSEP);\n  if (filename == NULL) return 1;  /* module not found in this path */\n  return checkload(L, (loadfunc(L, filename, name) == 0), filename);\n}\n\n\nstatic int searcher_Croot (lua_State *L) {\n  const char *filename;\n  const char *name = luaL_checkstring(L, 1);\n  const char *p = strchr(name, '.');\n  int stat;\n  if (p == NULL) return 0;  /* is root */\n  lua_pushlstring(L, name, ct_diff2sz(p - name));\n  filename = findfile(L, lua_tostring(L, -1), \"cpath\", LUA_CSUBSEP);\n  if (filename == NULL) return 1;  /* root not found */\n  if ((stat = loadfunc(L, filename, name)) != 0) {\n    if (stat != ERRFUNC)\n      return checkload(L, 0, filename);  /* real error */\n    else {  /* open function not found */\n      lua_pushfstring(L, \"no module '%s' in file '%s'\", name, filename);\n      return 1;\n    }\n  }\n  lua_pushstring(L, filename);  /* will be 2nd argument to module */\n  return 2;\n}\n\n\nstatic int searcher_preload (lua_State *L) {\n  const char *name = luaL_checkstring(L, 1);\n  lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);\n  if (lua_getfield(L, -1, name) == LUA_TNIL) {  /* not found? */\n    lua_pushfstring(L, \"no field package.preload['%s']\", name);\n    return 1;\n  }\n  else {\n    lua_pushliteral(L, \":preload:\");\n    return 2;\n  }\n}\n\n\nstatic void findloader (lua_State *L, const char *name) {\n  int i;\n  luaL_Buffer msg;  /* to build error message */\n  /* push 'package.searchers' to index 3 in the stack */\n  if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), \"searchers\")\n                 != LUA_TTABLE))\n    luaL_error(L, \"'package.searchers' must be a table\");\n  luaL_buffinit(L, &msg);\n  luaL_addstring(&msg, \"\\n\\t\");  /* error-message prefix for first message */\n  /*  iterate over available searchers to find a loader */\n  for (i = 1; ; i++) {\n    if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) {  /* no more searchers? */\n      lua_pop(L, 1);  /* remove nil */\n      luaL_buffsub(&msg, 2);  /* remove last prefix */\n      luaL_pushresult(&msg);  /* create error message */\n      luaL_error(L, \"module '%s' not found:%s\", name, lua_tostring(L, -1));\n    }\n    lua_pushstring(L, name);\n    lua_call(L, 1, 2);  /* call it */\n    if (lua_isfunction(L, -2))  /* did it find a loader? */\n      return;  /* module loader found */\n    else if (lua_isstring(L, -2)) {  /* searcher returned error message? */\n      lua_pop(L, 1);  /* remove extra return */\n      luaL_addvalue(&msg);  /* concatenate error message */\n      luaL_addstring(&msg, \"\\n\\t\");  /* prefix for next message */\n    }\n    else  /* no error message */\n      lua_pop(L, 2);  /* remove both returns */\n  }\n}\n\n\nstatic int ll_require (lua_State *L) {\n  const char *name = luaL_checkstring(L, 1);\n  lua_settop(L, 1);  /* LOADED table will be at index 2 */\n  lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);\n  lua_getfield(L, 2, name);  /* LOADED[name] */\n  if (lua_toboolean(L, -1))  /* is it there? */\n    return 1;  /* package is already loaded */\n  /* else must load package */\n  lua_pop(L, 1);  /* remove 'getfield' result */\n  findloader(L, name);\n  lua_rotate(L, -2, 1);  /* function <-> loader data */\n  lua_pushvalue(L, 1);  /* name is 1st argument to module loader */\n  lua_pushvalue(L, -3);  /* loader data is 2nd argument */\n  /* stack: ...; loader data; loader function; mod. name; loader data */\n  lua_call(L, 2, 1);  /* run loader to load module */\n  /* stack: ...; loader data; result from loader */\n  if (!lua_isnil(L, -1))  /* non-nil return? */\n    lua_setfield(L, 2, name);  /* LOADED[name] = returned value */\n  else\n    lua_pop(L, 1);  /* pop nil */\n  if (lua_getfield(L, 2, name) == LUA_TNIL) {   /* module set no value? */\n    lua_pushboolean(L, 1);  /* use true as result */\n    lua_copy(L, -1, -2);  /* replace loader result */\n    lua_setfield(L, 2, name);  /* LOADED[name] = true */\n  }\n  lua_rotate(L, -2, 1);  /* loader data <-> module result  */\n  return 2;  /* return module result and loader data */\n}\n\n/* }====================================================== */\n\n\n\n\nstatic const luaL_Reg pk_funcs[] = {\n  {\"loadlib\", ll_loadlib},\n  {\"searchpath\", ll_searchpath},\n  /* placeholders */\n  {\"preload\", NULL},\n  {\"cpath\", NULL},\n  {\"path\", NULL},\n  {\"searchers\", NULL},\n  {\"loaded\", NULL},\n  {NULL, NULL}\n};\n\n\nstatic const luaL_Reg ll_funcs[] = {\n  {\"require\", ll_require},\n  {NULL, NULL}\n};\n\n\nstatic void createsearcherstable (lua_State *L) {\n  static const lua_CFunction searchers[] = {\n    searcher_preload,\n    searcher_Lua,\n    searcher_C,\n    searcher_Croot,\n    NULL\n  };\n  int i;\n  /* create 'searchers' table */\n  lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);\n  /* fill it with predefined searchers */\n  for (i=0; searchers[i] != NULL; i++) {\n    lua_pushvalue(L, -2);  /* set 'package' as upvalue for all searchers */\n    lua_pushcclosure(L, searchers[i], 1);\n    lua_rawseti(L, -2, i+1);\n  }\n  lua_setfield(L, -2, \"searchers\");  /* put it in field 'searchers' */\n}\n\n\nLUAMOD_API int luaopen_package (lua_State *L) {\n  luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS);  /* create CLIBS table */\n  lua_pop(L, 1);  /* will not use it now */\n  luaL_newlib(L, pk_funcs);  /* create 'package' table */\n  createsearcherstable(L);\n  /* set paths */\n  setpath(L, \"path\", LUA_PATH_VAR, LUA_PATH_DEFAULT);\n  setpath(L, \"cpath\", LUA_CPATH_VAR, LUA_CPATH_DEFAULT);\n  /* store config information */\n  lua_pushliteral(L, LUA_DIRSEP \"\\n\" LUA_PATH_SEP \"\\n\" LUA_PATH_MARK \"\\n\"\n                     LUA_EXEC_DIR \"\\n\" LUA_IGMARK \"\\n\");\n  lua_setfield(L, -2, \"config\");\n  /* set field 'loaded' */\n  luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);\n  lua_setfield(L, -2, \"loaded\");\n  /* set field 'preload' */\n  luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);\n  lua_setfield(L, -2, \"preload\");\n  lua_pushglobaltable(L);\n  lua_pushvalue(L, -2);  /* set 'package' as upvalue for next lib */\n  luaL_setfuncs(L, ll_funcs, 1);  /* open lib into global table */\n  lua_pop(L, 1);  /* pop global table */\n  return 1;  /* return 'package' table */\n}\n\n"
  },
  {
    "path": "3rd/lua/lobject.c",
    "content": "/*\n** $Id: lobject.c $\n** Some generic functions over Lua objects\n** See Copyright Notice in lua.h\n*/\n\n#define lobject_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <float.h>\n#include <locale.h>\n#include <math.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lctype.h\"\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"lvm.h\"\n\n\n/*\n** Computes ceil(log2(x)), which is the smallest integer n such that\n** x <= (1 << n).\n*/\nlu_byte luaO_ceillog2 (unsigned int x) {\n  static const lu_byte log_2[256] = {  /* log_2[i - 1] = ceil(log2(i)) */\n    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,\n    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,\n    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,\n    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,\n    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,\n    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,\n    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,\n    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\n  };\n  int l = 0;\n  x--;\n  while (x >= 256) { l += 8; x >>= 8; }\n  return cast_byte(l + log_2[x]);\n}\n\n/*\n** Encodes 'p'% as a floating-point byte, represented as (eeeexxxx).\n** The exponent is represented using excess-7. Mimicking IEEE 754, the\n** representation normalizes the number when possible, assuming an extra\n** 1 before the mantissa (xxxx) and adding one to the exponent (eeee)\n** to signal that. So, the real value is (1xxxx) * 2^(eeee - 7 - 1) if\n** eeee != 0, and (xxxx) * 2^-7 otherwise (subnormal numbers).\n*/\nlu_byte luaO_codeparam (unsigned int p) {\n  if (p >= (cast(lu_mem, 0x1F) << (0xF - 7 - 1)) * 100u)  /* overflow? */\n    return 0xFF;  /* return maximum value */\n  else {\n    p = (cast(l_uint32, p) * 128 + 99) / 100;  /* round up the division */\n    if (p < 0x10) {  /* subnormal number? */\n      /* exponent bits are already zero; nothing else to do */\n      return cast_byte(p);\n    }\n    else {  /* p >= 0x10 implies ceil(log2(p + 1)) >= 5 */\n      /* preserve 5 bits in 'p' */\n      unsigned log = luaO_ceillog2(p + 1) - 5u;\n      return cast_byte(((p >> log) - 0x10) | ((log + 1) << 4));\n    }\n  }\n}\n\n\n/*\n** Computes 'p' times 'x', where 'p' is a floating-point byte. Roughly,\n** we have to multiply 'x' by the mantissa and then shift accordingly to\n** the exponent.  If the exponent is positive, both the multiplication\n** and the shift increase 'x', so we have to care only about overflows.\n** For negative exponents, however, multiplying before the shift keeps\n** more significant bits, as long as the multiplication does not\n** overflow, so we check which order is best.\n*/\nl_mem luaO_applyparam (lu_byte p, l_mem x) {\n  int m = p & 0xF;  /* mantissa */\n  int e = (p >> 4);  /* exponent */\n  if (e > 0) {  /* normalized? */\n    e--;  /* correct exponent */\n    m += 0x10;  /* correct mantissa; maximum value is 0x1F */\n  }\n  e -= 7;  /* correct excess-7 */\n  if (e >= 0) {\n    if (x < (MAX_LMEM / 0x1F) >> e)  /* no overflow? */\n      return (x * m) << e;  /* order doesn't matter here */\n    else  /* real overflow */\n      return MAX_LMEM;\n  }\n  else {  /* negative exponent */\n    e = -e;\n    if (x < MAX_LMEM / 0x1F)  /* multiplication cannot overflow? */\n      return (x * m) >> e;  /* multiplying first gives more precision */\n    else if ((x >> e) <  MAX_LMEM / 0x1F)  /* cannot overflow after shift? */\n      return (x >> e) * m;\n    else  /* real overflow */\n      return MAX_LMEM;\n  }\n}\n\n\nstatic lua_Integer intarith (lua_State *L, int op, lua_Integer v1,\n                                                   lua_Integer v2) {\n  switch (op) {\n    case LUA_OPADD: return intop(+, v1, v2);\n    case LUA_OPSUB:return intop(-, v1, v2);\n    case LUA_OPMUL:return intop(*, v1, v2);\n    case LUA_OPMOD: return luaV_mod(L, v1, v2);\n    case LUA_OPIDIV: return luaV_idiv(L, v1, v2);\n    case LUA_OPBAND: return intop(&, v1, v2);\n    case LUA_OPBOR: return intop(|, v1, v2);\n    case LUA_OPBXOR: return intop(^, v1, v2);\n    case LUA_OPSHL: return luaV_shiftl(v1, v2);\n    case LUA_OPSHR: return luaV_shiftr(v1, v2);\n    case LUA_OPUNM: return intop(-, 0, v1);\n    case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);\n    default: lua_assert(0); return 0;\n  }\n}\n\n\nstatic lua_Number numarith (lua_State *L, int op, lua_Number v1,\n                                                  lua_Number v2) {\n  switch (op) {\n    case LUA_OPADD: return luai_numadd(L, v1, v2);\n    case LUA_OPSUB: return luai_numsub(L, v1, v2);\n    case LUA_OPMUL: return luai_nummul(L, v1, v2);\n    case LUA_OPDIV: return luai_numdiv(L, v1, v2);\n    case LUA_OPPOW: return luai_numpow(L, v1, v2);\n    case LUA_OPIDIV: return luai_numidiv(L, v1, v2);\n    case LUA_OPUNM: return luai_numunm(L, v1);\n    case LUA_OPMOD: return luaV_modf(L, v1, v2);\n    default: lua_assert(0); return 0;\n  }\n}\n\n\nint luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2,\n                   TValue *res) {\n  switch (op) {\n    case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:\n    case LUA_OPSHL: case LUA_OPSHR:\n    case LUA_OPBNOT: {  /* operate only on integers */\n      lua_Integer i1; lua_Integer i2;\n      if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) {\n        setivalue(res, intarith(L, op, i1, i2));\n        return 1;\n      }\n      else return 0;  /* fail */\n    }\n    case LUA_OPDIV: case LUA_OPPOW: {  /* operate only on floats */\n      lua_Number n1; lua_Number n2;\n      if (tonumberns(p1, n1) && tonumberns(p2, n2)) {\n        setfltvalue(res, numarith(L, op, n1, n2));\n        return 1;\n      }\n      else return 0;  /* fail */\n    }\n    default: {  /* other operations */\n      lua_Number n1; lua_Number n2;\n      if (ttisinteger(p1) && ttisinteger(p2)) {\n        setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));\n        return 1;\n      }\n      else if (tonumberns(p1, n1) && tonumberns(p2, n2)) {\n        setfltvalue(res, numarith(L, op, n1, n2));\n        return 1;\n      }\n      else return 0;  /* fail */\n    }\n  }\n}\n\n\nvoid luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,\n                 StkId res) {\n  if (!luaO_rawarith(L, op, p1, p2, s2v(res))) {\n    /* could not perform raw operation; try metamethod */\n    luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));\n  }\n}\n\n\nlu_byte luaO_hexavalue (int c) {\n  lua_assert(lisxdigit(c));\n  if (lisdigit(c)) return cast_byte(c - '0');\n  else return cast_byte((ltolower(c) - 'a') + 10);\n}\n\n\nstatic int isneg (const char **s) {\n  if (**s == '-') { (*s)++; return 1; }\n  else if (**s == '+') (*s)++;\n  return 0;\n}\n\n\n\n/*\n** {==================================================================\n** Lua's implementation for 'lua_strx2number'\n** ===================================================================\n*/\n\n#if !defined(lua_strx2number)\n\n/* maximum number of significant digits to read (to avoid overflows\n   even with single floats) */\n#define MAXSIGDIG\t30\n\n/*\n** convert a hexadecimal numeric string to a number, following\n** C99 specification for 'strtod'\n*/\nstatic lua_Number lua_strx2number (const char *s, char **endptr) {\n  int dot = lua_getlocaledecpoint();\n  lua_Number r = l_mathop(0.0);  /* result (accumulator) */\n  int sigdig = 0;  /* number of significant digits */\n  int nosigdig = 0;  /* number of non-significant digits */\n  int e = 0;  /* exponent correction */\n  int neg;  /* 1 if number is negative */\n  int hasdot = 0;  /* true after seen a dot */\n  *endptr = cast_charp(s);  /* nothing is valid yet */\n  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */\n  neg = isneg(&s);  /* check sign */\n  if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X')))  /* check '0x' */\n    return l_mathop(0.0);  /* invalid format (no '0x') */\n  for (s += 2; ; s++) {  /* skip '0x' and read numeral */\n    if (*s == dot) {\n      if (hasdot) break;  /* second dot? stop loop */\n      else hasdot = 1;\n    }\n    else if (lisxdigit(cast_uchar(*s))) {\n      if (sigdig == 0 && *s == '0')  /* non-significant digit (zero)? */\n        nosigdig++;\n      else if (++sigdig <= MAXSIGDIG)  /* can read it without overflow? */\n          r = (r * l_mathop(16.0)) + luaO_hexavalue(*s);\n      else e++;  /* too many digits; ignore, but still count for exponent */\n      if (hasdot) e--;  /* decimal digit? correct exponent */\n    }\n    else break;  /* neither a dot nor a digit */\n  }\n  if (nosigdig + sigdig == 0)  /* no digits? */\n    return l_mathop(0.0);  /* invalid format */\n  *endptr = cast_charp(s);  /* valid up to here */\n  e *= 4;  /* each digit multiplies/divides value by 2^4 */\n  if (*s == 'p' || *s == 'P') {  /* exponent part? */\n    int exp1 = 0;  /* exponent value */\n    int neg1;  /* exponent sign */\n    s++;  /* skip 'p' */\n    neg1 = isneg(&s);  /* sign */\n    if (!lisdigit(cast_uchar(*s)))\n      return l_mathop(0.0);  /* invalid; must have at least one digit */\n    while (lisdigit(cast_uchar(*s)))  /* read exponent */\n      exp1 = exp1 * 10 + *(s++) - '0';\n    if (neg1) exp1 = -exp1;\n    e += exp1;\n    *endptr = cast_charp(s);  /* valid up to here */\n  }\n  if (neg) r = -r;\n  return l_mathop(ldexp)(r, e);\n}\n\n#endif\n/* }====================================================== */\n\n\n/* maximum length of a numeral to be converted to a number */\n#if !defined (L_MAXLENNUM)\n#define L_MAXLENNUM\t200\n#endif\n\n/*\n** Convert string 's' to a Lua number (put in 'result'). Return NULL on\n** fail or the address of the ending '\\0' on success. ('mode' == 'x')\n** means a hexadecimal numeral.\n*/\nstatic const char *l_str2dloc (const char *s, lua_Number *result, int mode) {\n  char *endptr;\n  *result = (mode == 'x') ? lua_strx2number(s, &endptr)  /* try to convert */\n                          : lua_str2number(s, &endptr);\n  if (endptr == s) return NULL;  /* nothing recognized? */\n  while (lisspace(cast_uchar(*endptr))) endptr++;  /* skip trailing spaces */\n  return (*endptr == '\\0') ? endptr : NULL;  /* OK iff no trailing chars */\n}\n\n\n/*\n** Convert string 's' to a Lua number (put in 'result') handling the\n** current locale.\n** This function accepts both the current locale or a dot as the radix\n** mark. If the conversion fails, it may mean number has a dot but\n** locale accepts something else. In that case, the code copies 's'\n** to a buffer (because 's' is read-only), changes the dot to the\n** current locale radix mark, and tries to convert again.\n** The variable 'mode' checks for special characters in the string:\n** - 'n' means 'inf' or 'nan' (which should be rejected)\n** - 'x' means a hexadecimal numeral\n** - '.' just optimizes the search for the common case (no special chars)\n*/\nstatic const char *l_str2d (const char *s, lua_Number *result) {\n  const char *endptr;\n  const char *pmode = strpbrk(s, \".xXnN\");  /* look for special chars */\n  int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;\n  if (mode == 'n')  /* reject 'inf' and 'nan' */\n    return NULL;\n  endptr = l_str2dloc(s, result, mode);  /* try to convert */\n  if (endptr == NULL) {  /* failed? may be a different locale */\n    char buff[L_MAXLENNUM + 1];\n    const char *pdot = strchr(s, '.');\n    if (pdot == NULL || strlen(s) > L_MAXLENNUM)\n      return NULL;  /* string too long or no dot; fail */\n    strcpy(buff, s);  /* copy string to buffer */\n    buff[pdot - s] = lua_getlocaledecpoint();  /* correct decimal point */\n    endptr = l_str2dloc(buff, result, mode);  /* try again */\n    if (endptr != NULL)\n      endptr = s + (endptr - buff);  /* make relative to 's' */\n  }\n  return endptr;\n}\n\n\n#define MAXBY10\t\tcast(lua_Unsigned, LUA_MAXINTEGER / 10)\n#define MAXLASTD\tcast_int(LUA_MAXINTEGER % 10)\n\nstatic const char *l_str2int (const char *s, lua_Integer *result) {\n  lua_Unsigned a = 0;\n  int empty = 1;\n  int neg;\n  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */\n  neg = isneg(&s);\n  if (s[0] == '0' &&\n      (s[1] == 'x' || s[1] == 'X')) {  /* hex? */\n    s += 2;  /* skip '0x' */\n    for (; lisxdigit(cast_uchar(*s)); s++) {\n      a = a * 16 + luaO_hexavalue(*s);\n      empty = 0;\n    }\n  }\n  else {  /* decimal */\n    for (; lisdigit(cast_uchar(*s)); s++) {\n      int d = *s - '0';\n      if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg))  /* overflow? */\n        return NULL;  /* do not accept it (as integer) */\n      a = a * 10 + cast_uint(d);\n      empty = 0;\n    }\n  }\n  while (lisspace(cast_uchar(*s))) s++;  /* skip trailing spaces */\n  if (empty || *s != '\\0') return NULL;  /* something wrong in the numeral */\n  else {\n    *result = l_castU2S((neg) ? 0u - a : a);\n    return s;\n  }\n}\n\n\nsize_t luaO_str2num (const char *s, TValue *o) {\n  lua_Integer i; lua_Number n;\n  const char *e;\n  if ((e = l_str2int(s, &i)) != NULL) {  /* try as an integer */\n    setivalue(o, i);\n  }\n  else if ((e = l_str2d(s, &n)) != NULL) {  /* else try as a float */\n    setfltvalue(o, n);\n  }\n  else\n    return 0;  /* conversion failed */\n  return ct_diff2sz(e - s) + 1;  /* success; return string size */\n}\n\n\nint luaO_utf8esc (char *buff, l_uint32 x) {\n  int n = 1;  /* number of bytes put in buffer (backwards) */\n  lua_assert(x <= 0x7FFFFFFFu);\n  if (x < 0x80)  /* ASCII? */\n    buff[UTF8BUFFSZ - 1] = cast_char(x);\n  else {  /* need continuation bytes */\n    unsigned int mfb = 0x3f;  /* maximum that fits in first byte */\n    do {  /* add continuation bytes */\n      buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f));\n      x >>= 6;  /* remove added bits */\n      mfb >>= 1;  /* now there is one less bit available in first byte */\n    } while (x > mfb);  /* still needs continuation byte? */\n    buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x);  /* add first byte */\n  }\n  return n;\n}\n\n\n/*\n** The size of the buffer for the conversion of a number to a string\n** 'LUA_N2SBUFFSZ' must be enough to accommodate both LUA_INTEGER_FMT\n** and LUA_NUMBER_FMT.  For a long long int, this is 19 digits plus a\n** sign and a final '\\0', adding to 21. For a long double, it can go to\n** a sign, the dot, an exponent letter, an exponent sign, 4 exponent\n** digits, the final '\\0', plus the significant digits, which are\n** approximately the *_DIG attribute.\n*/\n#if LUA_N2SBUFFSZ < (20 + l_floatatt(DIG))\n#error \"invalid value for LUA_N2SBUFFSZ\"\n#endif\n\n\n/*\n** Convert a float to a string, adding it to a buffer. First try with\n** a not too large number of digits, to avoid noise (for instance,\n** 1.1 going to \"1.1000000000000001\"). If that lose precision, so\n** that reading the result back gives a different number, then do the\n** conversion again with extra precision. Moreover, if the numeral looks\n** like an integer (without a decimal point or an exponent), add \".0\" to\n** its end.\n*/\nstatic int tostringbuffFloat (lua_Number n, char *buff) {\n  /* first conversion */\n  int len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT,\n                            (LUAI_UACNUMBER)n);\n  lua_Number check = lua_str2number(buff, NULL);  /* read it back */\n  if (check != n) {  /* not enough precision? */\n    /* convert again with more precision */\n    len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT_N,\n                          (LUAI_UACNUMBER)n);\n  }\n  /* looks like an integer? */\n  if (buff[strspn(buff, \"-0123456789\")] == '\\0') {\n    buff[len++] = lua_getlocaledecpoint();\n    buff[len++] = '0';  /* adds '.0' to result */\n  }\n  return len;\n}\n\n\n/*\n** Convert a number object to a string, adding it to a buffer.\n*/\nunsigned luaO_tostringbuff (const TValue *obj, char *buff) {\n  int len;\n  lua_assert(ttisnumber(obj));\n  if (ttisinteger(obj))\n    len = lua_integer2str(buff, LUA_N2SBUFFSZ, ivalue(obj));\n  else\n    len = tostringbuffFloat(fltvalue(obj), buff);\n  lua_assert(len < LUA_N2SBUFFSZ);\n  return cast_uint(len);\n}\n\n\n/*\n** Convert a number object to a Lua string, replacing the value at 'obj'\n*/\nvoid luaO_tostring (lua_State *L, TValue *obj) {\n  char buff[LUA_N2SBUFFSZ];\n  unsigned len = luaO_tostringbuff(obj, buff);\n  setsvalue(L, obj, luaS_newlstr(L, buff, len));\n}\n\n\n\n\n/*\n** {==================================================================\n** 'luaO_pushvfstring'\n** ===================================================================\n*/\n\n/*\n** Size for buffer space used by 'luaO_pushvfstring'. It should be\n** (LUA_IDSIZE + LUA_N2SBUFFSZ) + a minimal space for basic messages,\n** so that 'luaG_addinfo' can work directly on the static buffer.\n*/\n#define BUFVFS\t\tcast_uint(LUA_IDSIZE + LUA_N2SBUFFSZ + 95)\n\n/*\n** Buffer used by 'luaO_pushvfstring'. 'err' signals an error while\n** building result (memory error [1] or buffer overflow [2]).\n*/\ntypedef struct BuffFS {\n  lua_State *L;\n  char *b;\n  size_t buffsize;\n  size_t blen;  /* length of string in 'buff' */\n  int err;\n  char space[BUFVFS];  /* initial buffer */\n} BuffFS;\n\n\nstatic void initbuff (lua_State *L, BuffFS *buff) {\n  buff->L = L;\n  buff->b = buff->space;\n  buff->buffsize = sizeof(buff->space);\n  buff->blen = 0;\n  buff->err = 0;\n}\n\n\n/*\n** Push final result from 'luaO_pushvfstring'. This function may raise\n** errors explicitly or through memory errors, so it must run protected.\n*/\nstatic void pushbuff (lua_State *L, void *ud) {\n  BuffFS *buff = cast(BuffFS*, ud);\n  switch (buff->err) {\n    case 1:  /* memory error */\n      luaD_throw(L, LUA_ERRMEM);\n      break;\n    case 2:  /* length overflow: Add \"...\" at the end of result */\n      if (buff->buffsize - buff->blen < 3)\n        strcpy(buff->b + buff->blen - 3, \"...\");  /* 'blen' must be > 3 */\n      else {  /* there is enough space left for the \"...\" */\n        strcpy(buff->b + buff->blen, \"...\");\n        buff->blen += 3;\n      }\n      /* FALLTHROUGH */\n    default: {  /* no errors, but it can raise one creating the new string */\n      TString *ts = luaS_newlstr(L, buff->b, buff->blen);\n      setsvalue2s(L, L->top.p, ts);\n      L->top.p++;\n    }\n  }\n}\n\n\nstatic const char *clearbuff (BuffFS *buff) {\n  lua_State *L = buff->L;\n  const char *res;\n  if (luaD_rawrunprotected(L, pushbuff, buff) != LUA_OK)  /* errors? */\n    res = NULL;  /* error message is on the top of the stack */\n  else\n    res = getstr(tsvalue(s2v(L->top.p - 1)));\n  if (buff->b != buff->space)  /* using dynamic buffer? */\n    luaM_freearray(L, buff->b, buff->buffsize);  /* free it */\n  return res;\n}\n\n\nstatic void addstr2buff (BuffFS *buff, const char *str, size_t slen) {\n  size_t left = buff->buffsize - buff->blen;  /* space left in the buffer */\n  if (buff->err)  /* do nothing else after an error */\n    return;\n  if (slen > left) {  /* new string doesn't fit into current buffer? */\n    if (slen > ((MAX_SIZE/2) - buff->blen)) {  /* overflow? */\n      memcpy(buff->b + buff->blen, str, left);  /* copy what it can */\n      buff->blen = buff->buffsize;\n      buff->err = 2;  /* doesn't add anything else */\n      return;\n    }\n    else {\n      size_t newsize = buff->buffsize + slen;  /* limited to MAX_SIZE/2 */\n      char *newb =\n        (buff->b == buff->space)  /* still using static space? */\n        ? luaM_reallocvector(buff->L, NULL, 0, newsize, char)\n        : luaM_reallocvector(buff->L, buff->b, buff->buffsize, newsize,\n                                                               char);\n      if (newb == NULL) {  /* allocation error? */\n        buff->err = 1;  /* signal a memory error */\n        return;\n      }\n      if (buff->b == buff->space)  /* new buffer (not reallocated)? */\n        memcpy(newb, buff->b, buff->blen);  /* copy previous content */\n      buff->b = newb;  /* set new (larger) buffer... */\n      buff->buffsize = newsize;  /* ...and its new size */\n    }\n  }\n  memcpy(buff->b + buff->blen, str, slen);  /* copy new content */\n  buff->blen += slen;\n}\n\n\n/*\n** Add a numeral to the buffer.\n*/\nstatic void addnum2buff (BuffFS *buff, TValue *num) {\n  char numbuff[LUA_N2SBUFFSZ];\n  unsigned len = luaO_tostringbuff(num, numbuff);\n  addstr2buff(buff, numbuff, len);\n}\n\n\n/*\n** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%'\n   conventional formats, plus Lua-specific '%I' and '%U'\n*/\nconst char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {\n  BuffFS buff;  /* holds last part of the result */\n  const char *e;  /* points to next '%' */\n  initbuff(L, &buff);\n  while ((e = strchr(fmt, '%')) != NULL) {\n    addstr2buff(&buff, fmt, ct_diff2sz(e - fmt));  /* add 'fmt' up to '%' */\n    switch (*(e + 1)) {  /* conversion specifier */\n      case 's': {  /* zero-terminated string */\n        const char *s = va_arg(argp, char *);\n        if (s == NULL) s = \"(null)\";\n        addstr2buff(&buff, s, strlen(s));\n        break;\n      }\n      case 'c': {  /* an 'int' as a character */\n        char c = cast_char(va_arg(argp, int));\n        addstr2buff(&buff, &c, sizeof(char));\n        break;\n      }\n      case 'd': {  /* an 'int' */\n        TValue num;\n        setivalue(&num, va_arg(argp, int));\n        addnum2buff(&buff, &num);\n        break;\n      }\n      case 'I': {  /* a 'lua_Integer' */\n        TValue num;\n        setivalue(&num, cast_Integer(va_arg(argp, l_uacInt)));\n        addnum2buff(&buff, &num);\n        break;\n      }\n      case 'f': {  /* a 'lua_Number' */\n        TValue num;\n        setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber)));\n        addnum2buff(&buff, &num);\n        break;\n      }\n      case 'p': {  /* a pointer */\n        char bf[LUA_N2SBUFFSZ];  /* enough space for '%p' */\n        void *p = va_arg(argp, void *);\n        int len = lua_pointer2str(bf, LUA_N2SBUFFSZ, p);\n        addstr2buff(&buff, bf, cast_uint(len));\n        break;\n      }\n      case 'U': {  /* an 'unsigned long' as a UTF-8 sequence */\n        char bf[UTF8BUFFSZ];\n        unsigned long arg = va_arg(argp, unsigned long);\n        int len = luaO_utf8esc(bf, cast(l_uint32, arg));\n        addstr2buff(&buff, bf + UTF8BUFFSZ - len, cast_uint(len));\n        break;\n      }\n      case '%': {\n        addstr2buff(&buff, \"%\", 1);\n        break;\n      }\n      default: {\n        addstr2buff(&buff, e, 2);  /* keep unknown format in the result */\n        break;\n      }\n    }\n    fmt = e + 2;  /* skip '%' and the specifier */\n  }\n  addstr2buff(&buff, fmt, strlen(fmt));  /* rest of 'fmt' */\n  return clearbuff(&buff);  /* empty buffer into a new string */\n}\n\n\nconst char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {\n  const char *msg;\n  va_list argp;\n  va_start(argp, fmt);\n  msg = luaO_pushvfstring(L, fmt, argp);\n  va_end(argp);\n  if (msg == NULL)  /* error? */\n    luaD_throw(L, LUA_ERRMEM);\n  return msg;\n}\n\n/* }================================================================== */\n\n\n#define RETS\t\"...\"\n#define PRE\t\"[string \\\"\"\n#define POS\t\"\\\"]\"\n\n#define addstr(a,b,l)\t( memcpy(a,b,(l) * sizeof(char)), a += (l) )\n\nvoid luaO_chunkid (char *out, const char *source, size_t srclen) {\n  size_t bufflen = LUA_IDSIZE;  /* free space in buffer */\n  if (*source == '=') {  /* 'literal' source */\n    if (srclen <= bufflen)  /* small enough? */\n      memcpy(out, source + 1, srclen * sizeof(char));\n    else {  /* truncate it */\n      addstr(out, source + 1, bufflen - 1);\n      *out = '\\0';\n    }\n  }\n  else if (*source == '@') {  /* file name */\n    if (srclen <= bufflen)  /* small enough? */\n      memcpy(out, source + 1, srclen * sizeof(char));\n    else {  /* add '...' before rest of name */\n      addstr(out, RETS, LL(RETS));\n      bufflen -= LL(RETS);\n      memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char));\n    }\n  }\n  else {  /* string; format as [string \"source\"] */\n    const char *nl = strchr(source, '\\n');  /* find first new line (if any) */\n    addstr(out, PRE, LL(PRE));  /* add prefix */\n    bufflen -= LL(PRE RETS POS) + 1;  /* save space for prefix+suffix+'\\0' */\n    if (srclen < bufflen && nl == NULL) {  /* small one-line source? */\n      addstr(out, source, srclen);  /* keep it */\n    }\n    else {\n      if (nl != NULL)\n        srclen = ct_diff2sz(nl - source);  /* stop at first newline */\n      if (srclen > bufflen) srclen = bufflen;\n      addstr(out, source, srclen);\n      addstr(out, RETS, LL(RETS));\n    }\n    memcpy(out, POS, (LL(POS) + 1) * sizeof(char));\n  }\n}\n\n"
  },
  {
    "path": "3rd/lua/lobject.h",
    "content": "/*\n** $Id: lobject.h $\n** Type definitions for Lua objects\n** See Copyright Notice in lua.h\n*/\n\n\n#ifndef lobject_h\n#define lobject_h\n\n\n#include <stdarg.h>\n\n\n#include \"llimits.h\"\n#include \"lua.h\"\n\n\n/*\n** Extra types for collectable non-values\n*/\n#define LUA_TUPVAL\tLUA_NUMTYPES  /* upvalues */\n#define LUA_TPROTO\t(LUA_NUMTYPES+1)  /* function prototypes */\n#define LUA_TDEADKEY\t(LUA_NUMTYPES+2)  /* removed keys in tables */\n\n\n\n/*\n** number of all possible types (including LUA_TNONE but excluding DEADKEY)\n*/\n#define LUA_TOTALTYPES\t\t(LUA_TPROTO + 2)\n\n\n/*\n** tags for Tagged Values have the following use of bits:\n** bits 0-3: actual tag (a LUA_T* constant)\n** bits 4-5: variant bits\n** bit 6: whether value is collectable\n*/\n\n/* add variant bits to a type */\n#define makevariant(t,v)\t((t) | ((v) << 4))\n\n\n\n/*\n** Union of all Lua values\n*/\ntypedef union Value {\n  struct GCObject *gc;    /* collectable objects */\n  void *p;         /* light userdata */\n  lua_CFunction f; /* light C functions */\n  lua_Integer i;   /* integer numbers */\n  lua_Number n;    /* float numbers */\n  /* not used, but may avoid warnings for uninitialized value */\n  lu_byte ub;\n} Value;\n\n\n/*\n** Tagged Values. This is the basic representation of values in Lua:\n** an actual value plus a tag with its type.\n*/\n\n#define TValuefields\tValue value_; lu_byte tt_\n\ntypedef struct TValue {\n  TValuefields;\n} TValue;\n\n\n#define val_(o)\t\t((o)->value_)\n#define valraw(o)\t(val_(o))\n\n\n/* raw type tag of a TValue */\n#define rawtt(o)\t((o)->tt_)\n\n/* tag with no variants (bits 0-3) */\n#define novariant(t)\t((t) & 0x0F)\n\n/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */\n#define withvariant(t)\t((t) & 0x3F)\n#define ttypetag(o)\twithvariant(rawtt(o))\n\n/* type of a TValue */\n#define ttype(o)\t(novariant(rawtt(o)))\n\n\n/* Macros to test type */\n#define checktag(o,t)\t\t(rawtt(o) == (t))\n#define checktype(o,t)\t\t(ttype(o) == (t))\n\n\n/* Macros for internal tests */\n\n/* collectable object has the same tag as the original value */\n#define righttt(obj)\t\t(ttypetag(obj) == gcvalue(obj)->tt)\n\n/*\n** Any value being manipulated by the program either is non\n** collectable, or the collectable object has the right tag\n** and it is not dead. The option 'L == NULL' allows other\n** macros using this one to be used where L is not available.\n*/\n#define checkliveness(L,obj) \\\n\t((void)L, lua_longassert(!iscollectable(obj) || \\\n\t\t(righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj)) || isshared(gcvalue(obj))))))\n\n\n/* Macros to set values */\n\n/* set a value's tag */\n#define settt_(o,t)\t((o)->tt_=(t))\n\n\n/* main macro to copy values (from 'obj2' to 'obj1') */\n#define setobj(L,obj1,obj2) \\\n\t{ TValue *io1=(obj1); const TValue *io2=(obj2); \\\n          io1->value_ = io2->value_; settt_(io1, io2->tt_); \\\n\t  checkliveness(L,io1); lua_assert(!isnonstrictnil(io1)); }\n\n/*\n** Different types of assignments, according to source and destination.\n** (They are mostly equal now, but may be different in the future.)\n*/\n\n/* from stack to stack */\n#define setobjs2s(L,o1,o2)\tsetobj(L,s2v(o1),s2v(o2))\n/* to stack (not from same stack) */\n#define setobj2s(L,o1,o2)\tsetobj(L,s2v(o1),o2)\n/* from table to same table */\n#define setobjt2t\tsetobj\n/* to new object */\n#define setobj2n\tsetobj\n/* to table */\n#define setobj2t\tsetobj\n\n\n/*\n** Entries in a Lua stack. Field 'tbclist' forms a list of all\n** to-be-closed variables active in this stack. Dummy entries are\n** used when the distance between two tbc variables does not fit\n** in an unsigned short. They are represented by delta==0, and\n** their real delta is always the maximum value that fits in\n** that field.\n*/\ntypedef union StackValue {\n  TValue val;\n  struct {\n    TValuefields;\n    unsigned short delta;\n  } tbclist;\n} StackValue;\n\n\n/* index to stack elements */\ntypedef StackValue *StkId;\n\n\n/*\n** When reallocating the stack, change all pointers to the stack into\n** proper offsets.\n*/\ntypedef union {\n  StkId p;  /* actual pointer */\n  ptrdiff_t offset;  /* used while the stack is being reallocated */\n} StkIdRel;\n\n\n/* convert a 'StackValue' to a 'TValue' */\n#define s2v(o)\t(&(o)->val)\n\n\n\n/*\n** {==================================================================\n** Nil\n** ===================================================================\n*/\n\n/* Standard nil */\n#define LUA_VNIL\tmakevariant(LUA_TNIL, 0)\n\n/* Empty slot (which might be different from a slot containing nil) */\n#define LUA_VEMPTY\tmakevariant(LUA_TNIL, 1)\n\n/* Value returned for a key not found in a table (absent key) */\n#define LUA_VABSTKEY\tmakevariant(LUA_TNIL, 2)\n\n/* Special variant to signal that a fast get is accessing a non-table */\n#define LUA_VNOTABLE    makevariant(LUA_TNIL, 3)\n\n\n/* macro to test for (any kind of) nil */\n#define ttisnil(v)\t\tchecktype((v), LUA_TNIL)\n\n/*\n** Macro to test the result of a table access. Formally, it should\n** distinguish between LUA_VEMPTY/LUA_VABSTKEY/LUA_VNOTABLE and\n** other tags. As currently nil is equivalent to LUA_VEMPTY, it is\n** simpler to just test whether the value is nil.\n*/\n#define tagisempty(tag)\t\t(novariant(tag) == LUA_TNIL)\n\n\n/* macro to test for a standard nil */\n#define ttisstrictnil(o)\tchecktag((o), LUA_VNIL)\n\n\n#define setnilvalue(obj) settt_(obj, LUA_VNIL)\n\n\n#define isabstkey(v)\t\tchecktag((v), LUA_VABSTKEY)\n\n\n/*\n** macro to detect non-standard nils (used only in assertions)\n*/\n#define isnonstrictnil(v)\t(ttisnil(v) && !ttisstrictnil(v))\n\n\n/*\n** By default, entries with any kind of nil are considered empty.\n** (In any definition, values associated with absent keys must also\n** be accepted as empty.)\n*/\n#define isempty(v)\t\tttisnil(v)\n\n\n/* macro defining a value corresponding to an absent key */\n#define ABSTKEYCONSTANT\t\t{NULL}, LUA_VABSTKEY\n\n\n/* mark an entry as empty */\n#define setempty(v)\t\tsettt_(v, LUA_VEMPTY)\n\n\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Booleans\n** ===================================================================\n*/\n\n\n#define LUA_VFALSE\tmakevariant(LUA_TBOOLEAN, 0)\n#define LUA_VTRUE\tmakevariant(LUA_TBOOLEAN, 1)\n\n#define ttisboolean(o)\t\tchecktype((o), LUA_TBOOLEAN)\n#define ttisfalse(o)\t\tchecktag((o), LUA_VFALSE)\n#define ttistrue(o)\t\tchecktag((o), LUA_VTRUE)\n\n\n#define l_isfalse(o)\t(ttisfalse(o) || ttisnil(o))\n#define tagisfalse(t)\t((t) == LUA_VFALSE || novariant(t) == LUA_TNIL)\n\n\n\n#define setbfvalue(obj)\t\tsettt_(obj, LUA_VFALSE)\n#define setbtvalue(obj)\t\tsettt_(obj, LUA_VTRUE)\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Threads\n** ===================================================================\n*/\n\n#define LUA_VTHREAD\t\tmakevariant(LUA_TTHREAD, 0)\n\n#define ttisthread(o)\t\tchecktag((o), ctb(LUA_VTHREAD))\n\n#define thvalue(o)\tcheck_exp(ttisthread(o), gco2th(val_(o).gc))\n\n#define setthvalue(L,obj,x) \\\n  { TValue *io = (obj); lua_State *x_ = (x); \\\n    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTHREAD)); \\\n    checkliveness(L,io); }\n\n#define setthvalue2s(L,o,t)\tsetthvalue(L,s2v(o),t)\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Collectable Objects\n** ===================================================================\n*/\n\n/*\n** Common Header for all collectable objects (in macro form, to be\n** included in other objects)\n*/\n#define CommonHeader\tstruct GCObject *next; lu_byte tt; lu_byte marked\n\n\n/* Common type for all collectable objects */\ntypedef struct GCObject {\n  CommonHeader;\n} GCObject;\n\n\n/* Bit mark for collectable types */\n#define BIT_ISCOLLECTABLE\t(1 << 6)\n\n#define iscollectable(o)\t(rawtt(o) & BIT_ISCOLLECTABLE)\n\n/* mark a tag as collectable */\n#define ctb(t)\t\t\t((t) | BIT_ISCOLLECTABLE)\n\n#define gcvalue(o)\tcheck_exp(iscollectable(o), val_(o).gc)\n\n#define gcvalueraw(v)\t((v).gc)\n\n#define setgcovalue(L,obj,x) \\\n  { TValue *io = (obj); GCObject *i_g=(x); \\\n    val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); }\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Numbers\n** ===================================================================\n*/\n\n/* Variant tags for numbers */\n#define LUA_VNUMINT\tmakevariant(LUA_TNUMBER, 0)  /* integer numbers */\n#define LUA_VNUMFLT\tmakevariant(LUA_TNUMBER, 1)  /* float numbers */\n\n#define ttisnumber(o)\t\tchecktype((o), LUA_TNUMBER)\n#define ttisfloat(o)\t\tchecktag((o), LUA_VNUMFLT)\n#define ttisinteger(o)\t\tchecktag((o), LUA_VNUMINT)\n\n#define nvalue(o)\tcheck_exp(ttisnumber(o), \\\n\t(ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o)))\n#define fltvalue(o)\tcheck_exp(ttisfloat(o), val_(o).n)\n#define ivalue(o)\tcheck_exp(ttisinteger(o), val_(o).i)\n\n#define fltvalueraw(v)\t((v).n)\n#define ivalueraw(v)\t((v).i)\n\n#define setfltvalue(obj,x) \\\n  { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_VNUMFLT); }\n\n#define chgfltvalue(obj,x) \\\n  { TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); }\n\n#define setivalue(obj,x) \\\n  { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_VNUMINT); }\n\n#define chgivalue(obj,x) \\\n  { TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); }\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Strings\n** ===================================================================\n*/\n\n/* Variant tags for strings */\n#define LUA_VSHRSTR\tmakevariant(LUA_TSTRING, 0)  /* short strings */\n#define LUA_VLNGSTR\tmakevariant(LUA_TSTRING, 1)  /* long strings */\n\n#define ttisstring(o)\t\tchecktype((o), LUA_TSTRING)\n#define ttisshrstring(o)\tchecktag((o), ctb(LUA_VSHRSTR))\n#define ttislngstring(o)\tchecktag((o), ctb(LUA_VLNGSTR))\n\n#define tsvalueraw(v)\t(gco2ts((v).gc))\n\n#define tsvalue(o)\tcheck_exp(ttisstring(o), gco2ts(val_(o).gc))\n\n#define setsvalue(L,obj,x) \\\n  { TValue *io = (obj); TString *x_ = (x); \\\n    val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \\\n    checkliveness(L,io); }\n\n/* set a string to the stack */\n#define setsvalue2s(L,o,s)\tsetsvalue(L,s2v(o),s)\n\n/* set a string to a new object */\n#define setsvalue2n\tsetsvalue\n\n\n/* Kinds of long strings (stored in 'shrlen') */\n#define LSTRREG\t\t-1  /* regular long string */\n#define LSTRFIX\t\t-2  /* fixed external long string */\n#define LSTRMEM\t\t-3  /* external long string with deallocation */\n\n\n/*\n** Header for a string value.\n*/\ntypedef struct TString {\n  CommonHeader;\n  lu_byte extra;  /* reserved words for short strings; \"has hash\" for longs */\n  ls_byte shrlen;  /* length for short strings, negative for long strings */\n  unsigned int hash;\n  size_t id;\t/* id for short strings */\n  union {\n    size_t lnglen;  /* length for long strings */\n    struct TString *hnext;  /* linked list for hash table */\n  } u;\n  char *contents;  /* pointer to content in long strings */\n  lua_Alloc falloc;  /* deallocation function for external strings */\n  void *ud;  /* user data for external strings */\n} TString;\n\n\n#define strisshr(ts)\t((ts)->shrlen >= 0)\n#define isextstr(ts)\t(ttislngstring(ts) && tsvalue(ts)->shrlen != LSTRREG)\n\n\n/*\n** Get the actual string (array of bytes) from a 'TString'. (Generic\n** version and specialized versions for long and short strings.)\n*/\n#define rawgetshrstr(ts)  (cast_charp(&(ts)->contents))\n#define getshrstr(ts)\tcheck_exp(strisshr(ts), rawgetshrstr(ts))\n#define getlngstr(ts)\tcheck_exp(!strisshr(ts), (ts)->contents)\n#define getstr(ts) \t(strisshr(ts) ? rawgetshrstr(ts) : (ts)->contents)\n\n\n/* get string length from 'TString *ts' */\n#define tsslen(ts)  \\\n\t(strisshr(ts) ? cast_sizet((ts)->shrlen) : (ts)->u.lnglen)\n\n/*\n** Get string and length */\n#define getlstr(ts, len)  \\\n\t(strisshr(ts) \\\n\t? (cast_void((len) = cast_sizet((ts)->shrlen)), rawgetshrstr(ts)) \\\n\t: (cast_void((len) = (ts)->u.lnglen), (ts)->contents))\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Userdata\n** ===================================================================\n*/\n\n\n/*\n** Light userdata should be a variant of userdata, but for compatibility\n** reasons they are also different types.\n*/\n#define LUA_VLIGHTUSERDATA\tmakevariant(LUA_TLIGHTUSERDATA, 0)\n\n#define LUA_VUSERDATA\t\tmakevariant(LUA_TUSERDATA, 0)\n\n#define ttislightuserdata(o)\tchecktag((o), LUA_VLIGHTUSERDATA)\n#define ttisfulluserdata(o)\tchecktag((o), ctb(LUA_VUSERDATA))\n\n#define pvalue(o)\tcheck_exp(ttislightuserdata(o), val_(o).p)\n#define uvalue(o)\tcheck_exp(ttisfulluserdata(o), gco2u(val_(o).gc))\n\n#define pvalueraw(v)\t((v).p)\n\n#define setpvalue(obj,x) \\\n  { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_VLIGHTUSERDATA); }\n\n#define setuvalue(L,obj,x) \\\n  { TValue *io = (obj); Udata *x_ = (x); \\\n    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VUSERDATA)); \\\n    checkliveness(L,io); }\n\n\n/* Ensures that addresses after this type are always fully aligned. */\ntypedef union UValue {\n  TValue uv;\n  LUAI_MAXALIGN;  /* ensures maximum alignment for udata bytes */\n} UValue;\n\n\n/*\n** Header for userdata with user values;\n** memory area follows the end of this structure.\n*/\ntypedef struct Udata {\n  CommonHeader;\n  unsigned short nuvalue;  /* number of user values */\n  size_t len;  /* number of bytes */\n  struct Table *metatable;\n  GCObject *gclist;\n  UValue uv[1];  /* user values */\n} Udata;\n\n\n/*\n** Header for userdata with no user values. These userdata do not need\n** to be gray during GC, and therefore do not need a 'gclist' field.\n** To simplify, the code always use 'Udata' for both kinds of userdata,\n** making sure it never accesses 'gclist' on userdata with no user values.\n** This structure here is used only to compute the correct size for\n** this representation. (The 'bindata' field in its end ensures correct\n** alignment for binary data following this header.)\n*/\ntypedef struct Udata0 {\n  CommonHeader;\n  unsigned short nuvalue;  /* number of user values */\n  size_t len;  /* number of bytes */\n  struct Table *metatable;\n  union {LUAI_MAXALIGN;} bindata;\n} Udata0;\n\n\n/* compute the offset of the memory area of a userdata */\n#define udatamemoffset(nuv) \\\n       ((nuv) == 0 ? offsetof(Udata0, bindata)  \\\n\t\t   : offsetof(Udata, uv) + (sizeof(UValue) * (nuv)))\n\n/* get the address of the memory block inside 'Udata' */\n#define getudatamem(u)\t(cast_charp(u) + udatamemoffset((u)->nuvalue))\n\n/* compute the size of a userdata */\n#define sizeudata(nuv,nb)\t(udatamemoffset(nuv) + (nb))\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Prototypes\n** ===================================================================\n*/\n\n#define LUA_VPROTO\tmakevariant(LUA_TPROTO, 0)\n\n\ntypedef l_uint32 Instruction;\n\n\n/*\n** Description of an upvalue for function prototypes\n*/\ntypedef struct Upvaldesc {\n  TString *name;  /* upvalue name (for debug information) */\n  lu_byte instack;  /* whether it is in stack (register) */\n  lu_byte idx;  /* index of upvalue (in stack or in outer function's list) */\n  lu_byte kind;  /* kind of corresponding variable */\n} Upvaldesc;\n\n\n/*\n** Description of a local variable for function prototypes\n** (used for debug information)\n*/\ntypedef struct LocVar {\n  TString *varname;\n  int startpc;  /* first point where variable is active */\n  int endpc;    /* first point where variable is dead */\n} LocVar;\n\n\n/*\n** Associates the absolute line source for a given instruction ('pc').\n** The array 'lineinfo' gives, for each instruction, the difference in\n** lines from the previous instruction. When that difference does not\n** fit into a byte, Lua saves the absolute line for that instruction.\n** (Lua also saves the absolute line periodically, to speed up the\n** computation of a line number: we can use binary search in the\n** absolute-line array, but we must traverse the 'lineinfo' array\n** linearly to compute a line.)\n*/\ntypedef struct AbsLineInfo {\n  int pc;\n  int line;\n} AbsLineInfo;\n\n\n/*\n** Flags in Prototypes\n*/\n#define PF_VAHID\t1  /* function has hidden vararg arguments */\n#define PF_VATAB\t2  /* function has vararg table */\n#define PF_FIXED\t4  /* prototype has parts in fixed memory */\n\n/* a vararg function either has hidden args. or a vararg table */\n#define isvararg(p)\t((p)->flag & (PF_VAHID | PF_VATAB))\n\n/*\n** mark that a function needs a vararg table. (The flag PF_VAHID will\n** be cleared later.)\n*/\n#define needvatab(p)\t((p)->flag |= PF_VATAB)\n\n/*\n** Function Prototypes\n*/\ntypedef struct Proto {\n  CommonHeader;\n  lu_byte numparams;  /* number of fixed (named) parameters */\n  lu_byte flag;\n  lu_byte maxstacksize;  /* number of registers needed by this function */\n  int sizeupvalues;  /* size of 'upvalues' */\n  int sizek;  /* size of 'k' */\n  int sizecode;\n  int sizelineinfo;\n  int sizep;  /* size of 'p' */\n  int sizelocvars;\n  int sizeabslineinfo;  /* size of 'abslineinfo' */\n  int linedefined;  /* debug information  */\n  int lastlinedefined;  /* debug information  */\n  TValue *k;  /* constants used by the function */\n  Instruction *code;  /* opcodes */\n  struct Proto **p;  /* functions defined inside the function */\n  Upvaldesc *upvalues;  /* upvalue information */\n  ls_byte *lineinfo;  /* information about source lines (debug information) */\n  AbsLineInfo *abslineinfo;  /* idem */\n  LocVar *locvars;  /* information about local variables (debug information) */\n  TString  *source;  /* used for debug information */\n  GCObject *gclist;\n} Proto;\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Functions\n** ===================================================================\n*/\n\n#define LUA_VUPVAL\tmakevariant(LUA_TUPVAL, 0)\n\n\n/* Variant tags for functions */\n#define LUA_VLCL\tmakevariant(LUA_TFUNCTION, 0)  /* Lua closure */\n#define LUA_VLCF\tmakevariant(LUA_TFUNCTION, 1)  /* light C function */\n#define LUA_VCCL\tmakevariant(LUA_TFUNCTION, 2)  /* C closure */\n\n#define ttisfunction(o)\t\tchecktype(o, LUA_TFUNCTION)\n#define ttisLclosure(o)\t\tchecktag((o), ctb(LUA_VLCL))\n#define ttislcf(o)\t\tchecktag((o), LUA_VLCF)\n#define ttisCclosure(o)\t\tchecktag((o), ctb(LUA_VCCL))\n#define ttisclosure(o)         (ttisLclosure(o) || ttisCclosure(o))\n\n\n#define isLfunction(o)\tttisLclosure(o)\n\n#define clvalue(o)\tcheck_exp(ttisclosure(o), gco2cl(val_(o).gc))\n#define clLvalue(o)\tcheck_exp(ttisLclosure(o), gco2lcl(val_(o).gc))\n#define fvalue(o)\tcheck_exp(ttislcf(o), val_(o).f)\n#define clCvalue(o)\tcheck_exp(ttisCclosure(o), gco2ccl(val_(o).gc))\n\n#define fvalueraw(v)\t((v).f)\n\n#define setclLvalue(L,obj,x) \\\n  { TValue *io = (obj); LClosure *x_ = (x); \\\n    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VLCL)); \\\n    checkliveness(L,io); }\n\n#define setclLvalue2s(L,o,cl)\tsetclLvalue(L,s2v(o),cl)\n\n#define setfvalue(obj,x) \\\n  { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_VLCF); }\n\n#define setclCvalue(L,obj,x) \\\n  { TValue *io = (obj); CClosure *x_ = (x); \\\n    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VCCL)); \\\n    checkliveness(L,io); }\n\n\n/*\n** Upvalues for Lua closures\n*/\ntypedef struct UpVal {\n  CommonHeader;\n  union {\n    TValue *p;  /* points to stack or to its own value */\n    ptrdiff_t offset;  /* used while the stack is being reallocated */\n  } v;\n  union {\n    struct {  /* (when open) */\n      struct UpVal *next;  /* linked list */\n      struct UpVal **previous;\n    } open;\n    TValue value;  /* the value (when closed) */\n  } u;\n} UpVal;\n\n\n\n#define ClosureHeader \\\n\tCommonHeader; lu_byte nupvalues; GCObject *gclist\n\ntypedef struct CClosure {\n  ClosureHeader;\n  lua_CFunction f;\n  TValue upvalue[1];  /* list of upvalues */\n} CClosure;\n\n\ntypedef struct LClosure {\n  ClosureHeader;\n  struct Proto *p;\n  UpVal *upvals[1];  /* list of upvalues */\n} LClosure;\n\n\ntypedef union Closure {\n  CClosure c;\n  LClosure l;\n} Closure;\n\n\n#define getproto(o)\t(clLvalue(o)->p)\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Tables\n** ===================================================================\n*/\n\n#define LUA_VTABLE\tmakevariant(LUA_TTABLE, 0)\n\n#define ttistable(o)\t\tchecktag((o), ctb(LUA_VTABLE))\n\n#define hvalue(o)\tcheck_exp(ttistable(o), gco2t(val_(o).gc))\n\n#define sethvalue(L,obj,x) \\\n  { TValue *io = (obj); Table *x_ = (x); \\\n    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTABLE)); \\\n    checkliveness(L,io); }\n\n#define sethvalue2s(L,o,h)\tsethvalue(L,s2v(o),h)\n\n\n/*\n** Nodes for Hash tables: A pack of two TValue's (key-value pairs)\n** plus a 'next' field to link colliding entries. The distribution\n** of the key's fields ('key_tt' and 'key_val') not forming a proper\n** 'TValue' allows for a smaller size for 'Node' both in 4-byte\n** and 8-byte alignments.\n*/\ntypedef union Node {\n  struct NodeKey {\n    TValuefields;  /* fields for value */\n    lu_byte key_tt;  /* key type */\n    int next;  /* for chaining */\n    Value key_val;  /* key value */\n  } u;\n  TValue i_val;  /* direct access to node's value as a proper 'TValue' */\n} Node;\n\n\n/* copy a value into a key */\n#define setnodekey(node,obj) \\\n\t{ Node *n_=(node); const TValue *io_=(obj); \\\n\t  n_->u.key_val = io_->value_; n_->u.key_tt = io_->tt_; }\n\n\n/* copy a value from a key */\n#define getnodekey(L,obj,node) \\\n\t{ TValue *io_=(obj); const Node *n_=(node); \\\n\t  io_->value_ = n_->u.key_val; io_->tt_ = n_->u.key_tt; \\\n\t  checkliveness(L,io_); }\n\n\n\ntypedef struct Table {\n  CommonHeader;\n  lu_byte flags;  /* 1<<p means tagmethod(p) is not present */\n  lu_byte lsizenode;  /* log2 of number of slots of 'node' array */\n  unsigned int asize;  /* number of slots in 'array' array */\n  Value *array;  /* array part */\n  Node *node;\n  struct Table *metatable;\n  GCObject *gclist;\n} Table;\n\n\n/*\n** Macros to manipulate keys inserted in nodes\n*/\n#define keytt(node)\t\t((node)->u.key_tt)\n#define keyval(node)\t\t((node)->u.key_val)\n\n#define keyisnil(node)\t\t(keytt(node) == LUA_TNIL)\n#define keyisinteger(node)\t(keytt(node) == LUA_VNUMINT)\n#define keyival(node)\t\t(keyval(node).i)\n#define keyisshrstr(node)\t(keytt(node) == ctb(LUA_VSHRSTR))\n#define keystrval(node)\t\t(gco2ts(keyval(node).gc))\n\n#define setnilkey(node)\t\t(keytt(node) = LUA_TNIL)\n\n#define keyiscollectable(n)\t(keytt(n) & BIT_ISCOLLECTABLE)\n\n#define gckey(n)\t(keyval(n).gc)\n#define gckeyN(n)\t(keyiscollectable(n) ? gckey(n) : NULL)\n\n\n/*\n** Dead keys in tables have the tag DEADKEY but keep their original\n** gcvalue. This distinguishes them from regular keys but allows them to\n** be found when searched in a special way. ('next' needs that to find\n** keys removed from a table during a traversal.)\n*/\n#define setdeadkey(node)\t(keytt(node) = LUA_TDEADKEY)\n#define keyisdead(node)\t\t(keytt(node) == LUA_TDEADKEY)\n\n/* }================================================================== */\n\n\n\n/*\n** 'module' operation for hashing (size is always a power of 2)\n*/\n#define lmod(s,size) \\\n\t(check_exp((size&(size-1))==0, (cast_uint(s) & cast_uint((size)-1))))\n\n\n#define twoto(x)\t(1u<<(x))\n#define sizenode(t)\t(twoto((t)->lsizenode))\n\n\n/* size of buffer for 'luaO_utf8esc' function */\n#define UTF8BUFFSZ\t8\n\n\n/* macro to call 'luaO_pushvfstring' correctly */\n#define pushvfstring(L, argp, fmt, msg)\t\\\n  { va_start(argp, fmt); \\\n  msg = luaO_pushvfstring(L, fmt, argp); \\\n  va_end(argp); \\\n  if (msg == NULL) luaD_throw(L, LUA_ERRMEM);  /* only after 'va_end' */ }\n\n\nLUAI_FUNC int luaO_utf8esc (char *buff, l_uint32 x);\nLUAI_FUNC lu_byte luaO_ceillog2 (unsigned int x);\nLUAI_FUNC lu_byte luaO_codeparam (unsigned int p);\nLUAI_FUNC l_mem luaO_applyparam (lu_byte p, l_mem x);\n\nLUAI_FUNC int luaO_rawarith (lua_State *L, int op, const TValue *p1,\n                             const TValue *p2, TValue *res);\nLUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1,\n                           const TValue *p2, StkId res);\nLUAI_FUNC size_t luaO_str2num (const char *s, TValue *o);\nLUAI_FUNC unsigned luaO_tostringbuff (const TValue *obj, char *buff);\nLUAI_FUNC lu_byte luaO_hexavalue (int c);\nLUAI_FUNC void luaO_tostring (lua_State *L, TValue *obj);\nLUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,\n                                                       va_list argp);\nLUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);\nLUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t srclen);\n\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/lopcodes.c",
    "content": "/*\n** $Id: lopcodes.c $\n** Opcodes for Lua virtual machine\n** See Copyright Notice in lua.h\n*/\n\n#define lopcodes_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include \"lopcodes.h\"\n\n\n#define opmode(mm,ot,it,t,a,m)  \\\n    (((mm) << 7) | ((ot) << 6) | ((it) << 5) | ((t) << 4) | ((a) << 3) | (m))\n\n\n/* ORDER OP */\n\nLUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {\n/*       MM OT IT T  A  mode\t\t   opcode  */\n  opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_MOVE */\n ,opmode(0, 0, 0, 0, 1, iAsBx)\t\t/* OP_LOADI */\n ,opmode(0, 0, 0, 0, 1, iAsBx)\t\t/* OP_LOADF */\n ,opmode(0, 0, 0, 0, 1, iABx)\t\t/* OP_LOADK */\n ,opmode(0, 0, 0, 0, 1, iABx)\t\t/* OP_LOADKX */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_LOADFALSE */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_LFALSESKIP */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_LOADTRUE */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_LOADNIL */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_GETUPVAL */\n ,opmode(0, 0, 0, 0, 0, iABC)\t\t/* OP_SETUPVAL */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_GETTABUP */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_GETTABLE */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_GETI */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_GETFIELD */\n ,opmode(0, 0, 0, 0, 0, iABC)\t\t/* OP_SETTABUP */\n ,opmode(0, 0, 0, 0, 0, iABC)\t\t/* OP_SETTABLE */\n ,opmode(0, 0, 0, 0, 0, iABC)\t\t/* OP_SETI */\n ,opmode(0, 0, 0, 0, 0, iABC)\t\t/* OP_SETFIELD */\n ,opmode(0, 0, 0, 0, 1, ivABC)\t\t/* OP_NEWTABLE */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_SELF */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_ADDI */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_ADDK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_SUBK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_MULK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_MODK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_POWK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_DIVK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_IDIVK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_BANDK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_BORK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_BXORK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_SHLI */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_SHRI */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_ADD */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_SUB */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_MUL */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_MOD */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_POW */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_DIV */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_IDIV */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_BAND */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_BOR */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_BXOR */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_SHL */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_SHR */\n ,opmode(1, 0, 0, 0, 0, iABC)\t\t/* OP_MMBIN */\n ,opmode(1, 0, 0, 0, 0, iABC)\t\t/* OP_MMBINI */\n ,opmode(1, 0, 0, 0, 0, iABC)\t\t/* OP_MMBINK */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_UNM */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_BNOT */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_NOT */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_LEN */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_CONCAT */\n ,opmode(0, 0, 0, 0, 0, iABC)\t\t/* OP_CLOSE */\n ,opmode(0, 0, 0, 0, 0, iABC)\t\t/* OP_TBC */\n ,opmode(0, 0, 0, 0, 0, isJ)\t\t/* OP_JMP */\n ,opmode(0, 0, 0, 1, 0, iABC)\t\t/* OP_EQ */\n ,opmode(0, 0, 0, 1, 0, iABC)\t\t/* OP_LT */\n ,opmode(0, 0, 0, 1, 0, iABC)\t\t/* OP_LE */\n ,opmode(0, 0, 0, 1, 0, iABC)\t\t/* OP_EQK */\n ,opmode(0, 0, 0, 1, 0, iABC)\t\t/* OP_EQI */\n ,opmode(0, 0, 0, 1, 0, iABC)\t\t/* OP_LTI */\n ,opmode(0, 0, 0, 1, 0, iABC)\t\t/* OP_LEI */\n ,opmode(0, 0, 0, 1, 0, iABC)\t\t/* OP_GTI */\n ,opmode(0, 0, 0, 1, 0, iABC)\t\t/* OP_GEI */\n ,opmode(0, 0, 0, 1, 0, iABC)\t\t/* OP_TEST */\n ,opmode(0, 0, 0, 1, 1, iABC)\t\t/* OP_TESTSET */\n ,opmode(0, 1, 1, 0, 1, iABC)\t\t/* OP_CALL */\n ,opmode(0, 1, 1, 0, 1, iABC)\t\t/* OP_TAILCALL */\n ,opmode(0, 0, 1, 0, 0, iABC)\t\t/* OP_RETURN */\n ,opmode(0, 0, 0, 0, 0, iABC)\t\t/* OP_RETURN0 */\n ,opmode(0, 0, 0, 0, 0, iABC)\t\t/* OP_RETURN1 */\n ,opmode(0, 0, 0, 0, 1, iABx)\t\t/* OP_FORLOOP */\n ,opmode(0, 0, 0, 0, 1, iABx)\t\t/* OP_FORPREP */\n ,opmode(0, 0, 0, 0, 0, iABx)\t\t/* OP_TFORPREP */\n ,opmode(0, 0, 0, 0, 0, iABC)\t\t/* OP_TFORCALL */\n ,opmode(0, 0, 0, 0, 1, iABx)\t\t/* OP_TFORLOOP */\n ,opmode(0, 0, 1, 0, 0, ivABC)\t\t/* OP_SETLIST */\n ,opmode(0, 0, 0, 0, 1, iABx)\t\t/* OP_CLOSURE */\n ,opmode(0, 1, 0, 0, 1, iABC)\t\t/* OP_VARARG */\n ,opmode(0, 0, 0, 0, 1, iABC)\t\t/* OP_GETVARG */\n ,opmode(0, 0, 0, 0, 0, iABx)\t\t/* OP_ERRNNIL */\n ,opmode(0, 0, 1, 0, 1, iABC)\t\t/* OP_VARARGPREP */\n ,opmode(0, 0, 0, 0, 0, iAx)\t\t/* OP_EXTRAARG */\n};\n\n\n\n/*\n** Check whether instruction sets top for next instruction, that is,\n** it results in multiple values.\n*/\nint luaP_isOT (Instruction i) {\n  OpCode op = GET_OPCODE(i);\n  switch (op) {\n    case OP_TAILCALL: return 1;\n    default:\n      return testOTMode(op) && GETARG_C(i) == 0;\n  }\n}\n\n\n/*\n** Check whether instruction uses top from previous instruction, that is,\n** it accepts multiple results.\n*/\nint luaP_isIT (Instruction i) {\n  OpCode op = GET_OPCODE(i);\n  switch (op) {\n    case OP_SETLIST:\n      return testITMode(GET_OPCODE(i)) && GETARG_vB(i) == 0;\n    default:\n      return testITMode(GET_OPCODE(i)) && GETARG_B(i) == 0;\n  }\n}\n\n"
  },
  {
    "path": "3rd/lua/lopcodes.h",
    "content": "/*\n** $Id: lopcodes.h $\n** Opcodes for Lua virtual machine\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lopcodes_h\n#define lopcodes_h\n\n#include \"llimits.h\"\n#include \"lobject.h\"\n\n\n/*===========================================================================\n  We assume that instructions are unsigned 32-bit integers.\n  All instructions have an opcode in the first 7 bits.\n  Instructions can have the following formats:\n\n        3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0\n        1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0\niABC          C(8)     |      B(8)     |k|     A(8)      |   Op(7)     |\nivABC         vC(10)     |     vB(6)   |k|     A(8)      |   Op(7)     |\niABx                Bx(17)               |     A(8)      |   Op(7)     |\niAsBx              sBx (signed)(17)      |     A(8)      |   Op(7)     |\niAx                           Ax(25)                     |   Op(7)     |\nisJ                           sJ (signed)(25)            |   Op(7)     |\n\n  ('v' stands for \"variant\", 's' for \"signed\", 'x' for \"extended\".)\n  A signed argument is represented in excess K: The represented value is\n  the written unsigned value minus K, where K is half (rounded down) the\n  maximum value for the corresponding unsigned argument.\n===========================================================================*/\n\n\n/* basic instruction formats */\nenum OpMode {iABC, ivABC, iABx, iAsBx, iAx, isJ};\n\n\n/*\n** size and position of opcode arguments.\n*/\n#define SIZE_C\t\t8\n#define SIZE_vC\t\t10\n#define SIZE_B\t\t8\n#define SIZE_vB\t\t6\n#define SIZE_Bx\t\t(SIZE_C + SIZE_B + 1)\n#define SIZE_A\t\t8\n#define SIZE_Ax\t\t(SIZE_Bx + SIZE_A)\n#define SIZE_sJ\t\t(SIZE_Bx + SIZE_A)\n\n#define SIZE_OP\t\t7\n\n#define POS_OP\t\t0\n\n#define POS_A\t\t(POS_OP + SIZE_OP)\n#define POS_k\t\t(POS_A + SIZE_A)\n#define POS_B\t\t(POS_k + 1)\n#define POS_vB\t\t(POS_k + 1)\n#define POS_C\t\t(POS_B + SIZE_B)\n#define POS_vC\t\t(POS_vB + SIZE_vB)\n\n#define POS_Bx\t\tPOS_k\n\n#define POS_Ax\t\tPOS_A\n\n#define POS_sJ\t\tPOS_A\n\n\n/*\n** limits for opcode arguments.\n** we use (signed) 'int' to manipulate most arguments,\n** so they must fit in ints.\n*/\n\n/*\n** Check whether type 'int' has at least 'b' + 1 bits.\n** 'b' < 32; +1 for the sign bit.\n*/\n#define L_INTHASBITS(b)\t\t((UINT_MAX >> (b)) >= 1)\n\n\n#if L_INTHASBITS(SIZE_Bx)\n#define MAXARG_Bx\t((1<<SIZE_Bx)-1)\n#else\n#define MAXARG_Bx\tINT_MAX\n#endif\n\n#define OFFSET_sBx\t(MAXARG_Bx>>1)         /* 'sBx' is signed */\n\n\n#if L_INTHASBITS(SIZE_Ax)\n#define MAXARG_Ax\t((1<<SIZE_Ax)-1)\n#else\n#define MAXARG_Ax\tINT_MAX\n#endif\n\n#if L_INTHASBITS(SIZE_sJ)\n#define MAXARG_sJ\t((1 << SIZE_sJ) - 1)\n#else\n#define MAXARG_sJ\tINT_MAX\n#endif\n\n#define OFFSET_sJ\t(MAXARG_sJ >> 1)\n\n\n#define MAXARG_A\t((1<<SIZE_A)-1)\n#define MAXARG_B\t((1<<SIZE_B)-1)\n#define MAXARG_vB\t((1<<SIZE_vB)-1)\n#define MAXARG_C\t((1<<SIZE_C)-1)\n#define MAXARG_vC\t((1<<SIZE_vC)-1)\n#define OFFSET_sC\t(MAXARG_C >> 1)\n\n#define int2sC(i)\t((i) + OFFSET_sC)\n#define sC2int(i)\t((i) - OFFSET_sC)\n\n\n/* creates a mask with 'n' 1 bits at position 'p' */\n#define MASK1(n,p)\t((~((~(Instruction)0)<<(n)))<<(p))\n\n/* creates a mask with 'n' 0 bits at position 'p' */\n#define MASK0(n,p)\t(~MASK1(n,p))\n\n/*\n** the following macros help to manipulate instructions\n*/\n\n#define GET_OPCODE(i)\t(cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0)))\n#define SET_OPCODE(i,o)\t((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \\\n\t\t((cast_Inst(o)<<POS_OP)&MASK1(SIZE_OP,POS_OP))))\n\n#define checkopm(i,m)\t(getOpMode(GET_OPCODE(i)) == m)\n\n\n#define getarg(i,pos,size)\t(cast_int(((i)>>(pos)) & MASK1(size,0)))\n#define setarg(i,v,pos,size)\t((i) = (((i)&MASK0(size,pos)) | \\\n                ((cast_Inst(v)<<pos)&MASK1(size,pos))))\n\n#define GETARG_A(i)\tgetarg(i, POS_A, SIZE_A)\n#define SETARG_A(i,v)\tsetarg(i, v, POS_A, SIZE_A)\n\n#define GETARG_B(i)  \\\n\tcheck_exp(checkopm(i, iABC), getarg(i, POS_B, SIZE_B))\n#define GETARG_vB(i)  \\\n\tcheck_exp(checkopm(i, ivABC), getarg(i, POS_vB, SIZE_vB))\n#define GETARG_sB(i)\tsC2int(GETARG_B(i))\n#define SETARG_B(i,v)\tsetarg(i, v, POS_B, SIZE_B)\n#define SETARG_vB(i,v)\tsetarg(i, v, POS_vB, SIZE_vB)\n\n#define GETARG_C(i)  \\\n\tcheck_exp(checkopm(i, iABC), getarg(i, POS_C, SIZE_C))\n#define GETARG_vC(i)  \\\n\tcheck_exp(checkopm(i, ivABC), getarg(i, POS_vC, SIZE_vC))\n#define GETARG_sC(i)\tsC2int(GETARG_C(i))\n#define SETARG_C(i,v)\tsetarg(i, v, POS_C, SIZE_C)\n#define SETARG_vC(i,v)\tsetarg(i, v, POS_vC, SIZE_vC)\n\n#define TESTARG_k(i)\t(cast_int(((i) & (1u << POS_k))))\n#define GETARG_k(i)\tgetarg(i, POS_k, 1)\n#define SETARG_k(i,v)\tsetarg(i, v, POS_k, 1)\n\n#define GETARG_Bx(i)\tcheck_exp(checkopm(i, iABx), getarg(i, POS_Bx, SIZE_Bx))\n#define SETARG_Bx(i,v)\tsetarg(i, v, POS_Bx, SIZE_Bx)\n\n#define GETARG_Ax(i)\tcheck_exp(checkopm(i, iAx), getarg(i, POS_Ax, SIZE_Ax))\n#define SETARG_Ax(i,v)\tsetarg(i, v, POS_Ax, SIZE_Ax)\n\n#define GETARG_sBx(i)  \\\n\tcheck_exp(checkopm(i, iAsBx), getarg(i, POS_Bx, SIZE_Bx) - OFFSET_sBx)\n#define SETARG_sBx(i,b)\tSETARG_Bx((i),cast_uint((b)+OFFSET_sBx))\n\n#define GETARG_sJ(i)  \\\n\tcheck_exp(checkopm(i, isJ), getarg(i, POS_sJ, SIZE_sJ) - OFFSET_sJ)\n#define SETARG_sJ(i,j) \\\n\tsetarg(i, cast_uint((j)+OFFSET_sJ), POS_sJ, SIZE_sJ)\n\n\n#define CREATE_ABCk(o,a,b,c,k)\t((cast_Inst(o)<<POS_OP) \\\n\t\t\t| (cast_Inst(a)<<POS_A) \\\n\t\t\t| (cast_Inst(b)<<POS_B) \\\n\t\t\t| (cast_Inst(c)<<POS_C) \\\n\t\t\t| (cast_Inst(k)<<POS_k))\n\n#define CREATE_vABCk(o,a,b,c,k)\t((cast_Inst(o)<<POS_OP) \\\n\t\t\t| (cast_Inst(a)<<POS_A) \\\n\t\t\t| (cast_Inst(b)<<POS_vB) \\\n\t\t\t| (cast_Inst(c)<<POS_vC) \\\n\t\t\t| (cast_Inst(k)<<POS_k))\n\n#define CREATE_ABx(o,a,bc)\t((cast_Inst(o)<<POS_OP) \\\n\t\t\t| (cast_Inst(a)<<POS_A) \\\n\t\t\t| (cast_Inst(bc)<<POS_Bx))\n\n#define CREATE_Ax(o,a)\t\t((cast_Inst(o)<<POS_OP) \\\n\t\t\t| (cast_Inst(a)<<POS_Ax))\n\n#define CREATE_sJ(o,j,k)\t((cast_Inst(o) << POS_OP) \\\n\t\t\t| (cast_Inst(j) << POS_sJ) \\\n\t\t\t| (cast_Inst(k) << POS_k))\n\n\n#if !defined(MAXINDEXRK)  /* (for debugging only) */\n#define MAXINDEXRK\tMAXARG_B\n#endif\n\n\n/*\n** Maximum size for the stack of a Lua function. It must fit in 8 bits.\n** The highest valid register is one less than this value.\n*/\n#define MAX_FSTACK\tMAXARG_A\n\n/*\n** Invalid register (one more than last valid register).\n*/\n#define NO_REG\t\tMAX_FSTACK\n\n\n\n/*\n** R[x] - register\n** K[x] - constant (in constant table)\n** RK(x) == if k(i) then K[x] else R[x]\n*/\n\n\n/*\n** Grep \"ORDER OP\" if you change this enum.\n** See \"Notes\" below for more information about some instructions.\n*/\n\ntypedef enum {\n/*----------------------------------------------------------------------\n  name\t\targs\tdescription\n------------------------------------------------------------------------*/\nOP_MOVE,/*\tA B\tR[A] := R[B]\t\t\t\t\t*/\nOP_LOADI,/*\tA sBx\tR[A] := sBx\t\t\t\t\t*/\nOP_LOADF,/*\tA sBx\tR[A] := (lua_Number)sBx\t\t\t\t*/\nOP_LOADK,/*\tA Bx\tR[A] := K[Bx]\t\t\t\t\t*/\nOP_LOADKX,/*\tA\tR[A] := K[extra arg]\t\t\t\t*/\nOP_LOADFALSE,/*\tA\tR[A] := false\t\t\t\t\t*/\nOP_LFALSESKIP,/*A\tR[A] := false; pc++\t\t\t\t*/\nOP_LOADTRUE,/*\tA\tR[A] := true\t\t\t\t\t*/\nOP_LOADNIL,/*\tA B\tR[A], R[A+1], ..., R[A+B] := nil\t\t*/\nOP_GETUPVAL,/*\tA B\tR[A] := UpValue[B]\t\t\t\t*/\nOP_SETUPVAL,/*\tA B\tUpValue[B] := R[A]\t\t\t\t*/\n\nOP_GETTABUP,/*\tA B C\tR[A] := UpValue[B][K[C]:shortstring]\t\t*/\nOP_GETTABLE,/*\tA B C\tR[A] := R[B][R[C]]\t\t\t\t*/\nOP_GETI,/*\tA B C\tR[A] := R[B][C]\t\t\t\t\t*/\nOP_GETFIELD,/*\tA B C\tR[A] := R[B][K[C]:shortstring]\t\t\t*/\n\nOP_SETTABUP,/*\tA B C\tUpValue[A][K[B]:shortstring] := RK(C)\t\t*/\nOP_SETTABLE,/*\tA B C\tR[A][R[B]] := RK(C)\t\t\t\t*/\nOP_SETI,/*\tA B C\tR[A][B] := RK(C)\t\t\t\t*/\nOP_SETFIELD,/*\tA B C\tR[A][K[B]:shortstring] := RK(C)\t\t\t*/\n\nOP_NEWTABLE,/*\tA vB vC k\tR[A] := {}\t\t\t\t*/\n\nOP_SELF,/*\tA B C\tR[A+1] := R[B]; R[A] := R[B][K[C]:shortstring]\t*/\n\nOP_ADDI,/*\tA B sC\tR[A] := R[B] + sC\t\t\t\t*/\n\nOP_ADDK,/*\tA B C\tR[A] := R[B] + K[C]:number\t\t\t*/\nOP_SUBK,/*\tA B C\tR[A] := R[B] - K[C]:number\t\t\t*/\nOP_MULK,/*\tA B C\tR[A] := R[B] * K[C]:number\t\t\t*/\nOP_MODK,/*\tA B C\tR[A] := R[B] % K[C]:number\t\t\t*/\nOP_POWK,/*\tA B C\tR[A] := R[B] ^ K[C]:number\t\t\t*/\nOP_DIVK,/*\tA B C\tR[A] := R[B] / K[C]:number\t\t\t*/\nOP_IDIVK,/*\tA B C\tR[A] := R[B] // K[C]:number\t\t\t*/\n\nOP_BANDK,/*\tA B C\tR[A] := R[B] & K[C]:integer\t\t\t*/\nOP_BORK,/*\tA B C\tR[A] := R[B] | K[C]:integer\t\t\t*/\nOP_BXORK,/*\tA B C\tR[A] := R[B] ~ K[C]:integer\t\t\t*/\n\nOP_SHLI,/*\tA B sC\tR[A] := sC << R[B]\t\t\t\t*/\nOP_SHRI,/*\tA B sC\tR[A] := R[B] >> sC\t\t\t\t*/\n\nOP_ADD,/*\tA B C\tR[A] := R[B] + R[C]\t\t\t\t*/\nOP_SUB,/*\tA B C\tR[A] := R[B] - R[C]\t\t\t\t*/\nOP_MUL,/*\tA B C\tR[A] := R[B] * R[C]\t\t\t\t*/\nOP_MOD,/*\tA B C\tR[A] := R[B] % R[C]\t\t\t\t*/\nOP_POW,/*\tA B C\tR[A] := R[B] ^ R[C]\t\t\t\t*/\nOP_DIV,/*\tA B C\tR[A] := R[B] / R[C]\t\t\t\t*/\nOP_IDIV,/*\tA B C\tR[A] := R[B] // R[C]\t\t\t\t*/\n\nOP_BAND,/*\tA B C\tR[A] := R[B] & R[C]\t\t\t\t*/\nOP_BOR,/*\tA B C\tR[A] := R[B] | R[C]\t\t\t\t*/\nOP_BXOR,/*\tA B C\tR[A] := R[B] ~ R[C]\t\t\t\t*/\nOP_SHL,/*\tA B C\tR[A] := R[B] << R[C]\t\t\t\t*/\nOP_SHR,/*\tA B C\tR[A] := R[B] >> R[C]\t\t\t\t*/\n\nOP_MMBIN,/*\tA B C\tcall C metamethod over R[A] and R[B]\t\t*/\nOP_MMBINI,/*\tA sB C k\tcall C metamethod over R[A] and sB\t*/\nOP_MMBINK,/*\tA B C k\t\tcall C metamethod over R[A] and K[B]\t*/\n\nOP_UNM,/*\tA B\tR[A] := -R[B]\t\t\t\t\t*/\nOP_BNOT,/*\tA B\tR[A] := ~R[B]\t\t\t\t\t*/\nOP_NOT,/*\tA B\tR[A] := not R[B]\t\t\t\t*/\nOP_LEN,/*\tA B\tR[A] := #R[B] (length operator)\t\t\t*/\n\nOP_CONCAT,/*\tA B\tR[A] := R[A].. ... ..R[A + B - 1]\t\t*/\n\nOP_CLOSE,/*\tA\tclose all upvalues >= R[A]\t\t\t*/\nOP_TBC,/*\tA\tmark variable A \"to be closed\"\t\t\t*/\nOP_JMP,/*\tsJ\tpc += sJ\t\t\t\t\t*/\nOP_EQ,/*\tA B k\tif ((R[A] == R[B]) ~= k) then pc++\t\t*/\nOP_LT,/*\tA B k\tif ((R[A] <  R[B]) ~= k) then pc++\t\t*/\nOP_LE,/*\tA B k\tif ((R[A] <= R[B]) ~= k) then pc++\t\t*/\n\nOP_EQK,/*\tA B k\tif ((R[A] == K[B]) ~= k) then pc++\t\t*/\nOP_EQI,/*\tA sB k\tif ((R[A] == sB) ~= k) then pc++\t\t*/\nOP_LTI,/*\tA sB k\tif ((R[A] < sB) ~= k) then pc++\t\t\t*/\nOP_LEI,/*\tA sB k\tif ((R[A] <= sB) ~= k) then pc++\t\t*/\nOP_GTI,/*\tA sB k\tif ((R[A] > sB) ~= k) then pc++\t\t\t*/\nOP_GEI,/*\tA sB k\tif ((R[A] >= sB) ~= k) then pc++\t\t*/\n\nOP_TEST,/*\tA k\tif (not R[A] == k) then pc++\t\t\t*/\nOP_TESTSET,/*\tA B k\tif (not R[B] == k) then pc++ else R[A] := R[B]  */\n\nOP_CALL,/*\tA B C\tR[A], ... ,R[A+C-2] := R[A](R[A+1], ... ,R[A+B-1]) */\nOP_TAILCALL,/*\tA B C k\treturn R[A](R[A+1], ... ,R[A+B-1])\t\t*/\n\nOP_RETURN,/*\tA B C k\treturn R[A], ... ,R[A+B-2]\t\t\t*/\nOP_RETURN0,/*\t\treturn\t\t\t\t\t\t*/\nOP_RETURN1,/*\tA\treturn R[A]\t\t\t\t\t*/\n\nOP_FORLOOP,/*\tA Bx\tupdate counters; if loop continues then pc-=Bx; */\nOP_FORPREP,/*\tA Bx\t<check values and prepare counters>;\n                        if not to run then pc+=Bx+1;\t\t\t*/\n\nOP_TFORPREP,/*\tA Bx\tcreate upvalue for R[A + 3]; pc+=Bx\t\t*/\nOP_TFORCALL,/*\tA C\tR[A+4], ... ,R[A+3+C] := R[A](R[A+1], R[A+2]);\t*/\nOP_TFORLOOP,/*\tA Bx\tif R[A+2] ~= nil then { R[A]=R[A+2]; pc -= Bx }\t*/\n\nOP_SETLIST,/*\tA vB vC k\tR[A][vC+i] := R[A+i], 1 <= i <= vB\t*/\n\nOP_CLOSURE,/*\tA Bx\tR[A] := closure(KPROTO[Bx])\t\t\t*/\n\nOP_VARARG,/*\tA B C k\tR[A], ..., R[A+C-2] = varargs  \t\t\t*/\n\nOP_GETVARG, /* A B C\tR[A] := R[B][R[C]], R[B] is vararg parameter    */\n\nOP_ERRNNIL,/*\tA Bx\traise error if R[A] ~= nil (K[Bx - 1] is global name)*/\n\nOP_VARARGPREP,/* \t(adjust varargs)\t\t\t\t*/\n\nOP_EXTRAARG/*\tAx\textra (larger) argument for previous opcode\t*/\n} OpCode;\n\n\n#define NUM_OPCODES\t((int)(OP_EXTRAARG) + 1)\n\n\n\n/*===========================================================================\n  Notes:\n\n  (*) Opcode OP_LFALSESKIP is used to convert a condition to a boolean\n  value, in a code equivalent to (not cond ? false : true).  (It\n  produces false and skips the next instruction producing true.)\n\n  (*) Opcodes OP_MMBIN and variants follow each arithmetic and\n  bitwise opcode. If the operation succeeds, it skips this next\n  opcode. Otherwise, this opcode calls the corresponding metamethod.\n\n  (*) Opcode OP_TESTSET is used in short-circuit expressions that need\n  both to jump and to produce a value, such as (a = b or c).\n\n  (*) In OP_CALL, if (B == 0) then B = top - A. If (C == 0), then\n  'top' is set to last_result+1, so next open instruction (OP_CALL,\n  OP_RETURN*, OP_SETLIST) may use 'top'.\n\n  (*) In OP_VARARG, if (C == 0) then use actual number of varargs and\n  set top (like in OP_CALL with C == 0). 'k' means function has a\n  vararg table, which is in R[B].\n\n  (*) In OP_RETURN, if (B == 0) then return up to 'top'.\n\n  (*) In OP_LOADKX and OP_NEWTABLE, the next instruction is always\n  OP_EXTRAARG.\n\n  (*) In OP_SETLIST, if (B == 0) then real B = 'top'; if k, then\n  real C = EXTRAARG _ C (the bits of EXTRAARG concatenated with the\n  bits of C).\n\n  (*) In OP_NEWTABLE, vB is log2 of the hash size (which is always a\n  power of 2) plus 1, or zero for size zero. If not k, the array size\n  is vC. Otherwise, the array size is EXTRAARG _ vC.\n\n  (*) In OP_ERRNNIL, (Bx == 0) means index of global name doesn't\n  fit in Bx. (So, that name is not available for the error message.)\n\n  (*) For comparisons, k specifies what condition the test should accept\n  (true or false).\n\n  (*) In OP_MMBINI/OP_MMBINK, k means the arguments were flipped\n  (the constant is the first operand).\n\n  (*) All comparison and test instructions assume that the instruction\n  being skipped (pc++) is a jump.\n\n  (*) In instructions OP_RETURN/OP_TAILCALL, 'k' specifies that the\n  function builds upvalues, which may need to be closed. C > 0 means\n  the function has hidden vararg arguments, so that its 'func' must be\n  corrected before returning; in this case, (C - 1) is its number of\n  fixed parameters.\n\n  (*) In comparisons with an immediate operand, C signals whether the\n  original operand was a float. (It must be corrected in case of\n  metamethods.)\n\n===========================================================================*/\n\n\n/*\n** masks for instruction properties. The format is:\n** bits 0-2: op mode\n** bit 3: instruction set register A\n** bit 4: operator is a test (next instruction must be a jump)\n** bit 5: instruction uses 'L->top' set by previous instruction (when B == 0)\n** bit 6: instruction sets 'L->top' for next instruction (when C == 0)\n** bit 7: instruction is an MM instruction (call a metamethod)\n*/\n\nLUAI_DDEC(const lu_byte luaP_opmodes[NUM_OPCODES];)\n\n#define getOpMode(m)\t(cast(enum OpMode, luaP_opmodes[m] & 7))\n#define testAMode(m)\t(luaP_opmodes[m] & (1 << 3))\n#define testTMode(m)\t(luaP_opmodes[m] & (1 << 4))\n#define testITMode(m)\t(luaP_opmodes[m] & (1 << 5))\n#define testOTMode(m)\t(luaP_opmodes[m] & (1 << 6))\n#define testMMMode(m)\t(luaP_opmodes[m] & (1 << 7))\n\n\nLUAI_FUNC int luaP_isOT (Instruction i);\nLUAI_FUNC int luaP_isIT (Instruction i);\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lopnames.h",
    "content": "/*\n** $Id: lopnames.h $\n** Opcode names\n** See Copyright Notice in lua.h\n*/\n\n#if !defined(lopnames_h)\n#define lopnames_h\n\n#include <stddef.h>\n\n\n/* ORDER OP */\n\nstatic const char *const opnames[] = {\n  \"MOVE\",\n  \"LOADI\",\n  \"LOADF\",\n  \"LOADK\",\n  \"LOADKX\",\n  \"LOADFALSE\",\n  \"LFALSESKIP\",\n  \"LOADTRUE\",\n  \"LOADNIL\",\n  \"GETUPVAL\",\n  \"SETUPVAL\",\n  \"GETTABUP\",\n  \"GETTABLE\",\n  \"GETI\",\n  \"GETFIELD\",\n  \"SETTABUP\",\n  \"SETTABLE\",\n  \"SETI\",\n  \"SETFIELD\",\n  \"NEWTABLE\",\n  \"SELF\",\n  \"ADDI\",\n  \"ADDK\",\n  \"SUBK\",\n  \"MULK\",\n  \"MODK\",\n  \"POWK\",\n  \"DIVK\",\n  \"IDIVK\",\n  \"BANDK\",\n  \"BORK\",\n  \"BXORK\",\n  \"SHLI\",\n  \"SHRI\",\n  \"ADD\",\n  \"SUB\",\n  \"MUL\",\n  \"MOD\",\n  \"POW\",\n  \"DIV\",\n  \"IDIV\",\n  \"BAND\",\n  \"BOR\",\n  \"BXOR\",\n  \"SHL\",\n  \"SHR\",\n  \"MMBIN\",\n  \"MMBINI\",\n  \"MMBINK\",\n  \"UNM\",\n  \"BNOT\",\n  \"NOT\",\n  \"LEN\",\n  \"CONCAT\",\n  \"CLOSE\",\n  \"TBC\",\n  \"JMP\",\n  \"EQ\",\n  \"LT\",\n  \"LE\",\n  \"EQK\",\n  \"EQI\",\n  \"LTI\",\n  \"LEI\",\n  \"GTI\",\n  \"GEI\",\n  \"TEST\",\n  \"TESTSET\",\n  \"CALL\",\n  \"TAILCALL\",\n  \"RETURN\",\n  \"RETURN0\",\n  \"RETURN1\",\n  \"FORLOOP\",\n  \"FORPREP\",\n  \"TFORPREP\",\n  \"TFORCALL\",\n  \"TFORLOOP\",\n  \"SETLIST\",\n  \"CLOSURE\",\n  \"VARARG\",\n  \"GETVARG\",\n  \"ERRNNIL\",\n  \"VARARGPREP\",\n  \"EXTRAARG\",\n  NULL\n};\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/loslib.c",
    "content": "/*\n** $Id: loslib.c $\n** Standard Operating System library\n** See Copyright Notice in lua.h\n*/\n\n#define loslib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <errno.h>\n#include <locale.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\n/*\n** {==================================================================\n** List of valid conversion specifiers for the 'strftime' function;\n** options are grouped by length; group of length 2 start with '||'.\n** ===================================================================\n*/\n#if !defined(LUA_STRFTIMEOPTIONS)\t/* { */\n\n#if defined(LUA_USE_WINDOWS)\n#define LUA_STRFTIMEOPTIONS  \"aAbBcdHIjmMpSUwWxXyYzZ%\" \\\n    \"||\" \"#c#x#d#H#I#j#m#M#S#U#w#W#y#Y\"  /* two-char options */\n#elif defined(LUA_USE_C89)  /* C89 (only 1-char options) */\n#define LUA_STRFTIMEOPTIONS  \"aAbBcdHIjmMpSUwWxXyYZ%\"\n#else  /* C99 specification */\n#define LUA_STRFTIMEOPTIONS  \"aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%\" \\\n    \"||\" \"EcECExEXEyEY\" \"OdOeOHOIOmOMOSOuOUOVOwOWOy\"  /* two-char options */\n#endif\n\n#endif\t\t\t\t\t/* } */\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Configuration for time-related stuff\n** ===================================================================\n*/\n\n/*\n** type to represent time_t in Lua\n*/\n#if !defined(LUA_NUMTIME)\t/* { */\n\n#define l_timet\t\t\tlua_Integer\n#define l_pushtime(L,t)\t\tlua_pushinteger(L,(lua_Integer)(t))\n#define l_gettime(L,arg)\tluaL_checkinteger(L, arg)\n\n#else\t\t\t\t/* }{ */\n\n#define l_timet\t\t\tlua_Number\n#define l_pushtime(L,t)\t\tlua_pushnumber(L,(lua_Number)(t))\n#define l_gettime(L,arg)\tluaL_checknumber(L, arg)\n\n#endif\t\t\t\t/* } */\n\n\n#if !defined(l_gmtime)\t\t/* { */\n/*\n** By default, Lua uses gmtime/localtime, except when POSIX is available,\n** where it uses gmtime_r/localtime_r\n*/\n\n#if defined(LUA_USE_POSIX)\t/* { */\n\n#define l_gmtime(t,r)\t\tgmtime_r(t,r)\n#define l_localtime(t,r)\tlocaltime_r(t,r)\n\n#else\t\t\t\t/* }{ */\n\n/* ISO C definitions */\n#define l_gmtime(t,r)\t\t((void)(r)->tm_sec, gmtime(t))\n#define l_localtime(t,r)\t((void)(r)->tm_sec, localtime(t))\n\n#endif\t\t\t\t/* } */\n\n#endif\t\t\t\t/* } */\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Configuration for 'tmpnam':\n** By default, Lua uses tmpnam except when POSIX is available, where\n** it uses mkstemp.\n** ===================================================================\n*/\n#if !defined(lua_tmpnam)\t/* { */\n\n#if defined(LUA_USE_POSIX)\t/* { */\n\n#include <unistd.h>\n\n#define LUA_TMPNAMBUFSIZE\t32\n\n#if !defined(LUA_TMPNAMTEMPLATE)\n#define LUA_TMPNAMTEMPLATE\t\"/tmp/lua_XXXXXX\"\n#endif\n\n#define lua_tmpnam(b,e) { \\\n        strcpy(b, LUA_TMPNAMTEMPLATE); \\\n        e = mkstemp(b); \\\n        if (e != -1) close(e); \\\n        e = (e == -1); }\n\n#else\t\t\t\t/* }{ */\n\n/* ISO C definitions */\n#define LUA_TMPNAMBUFSIZE\tL_tmpnam\n#define lua_tmpnam(b,e)\t\t{ e = (tmpnam(b) == NULL); }\n\n#endif\t\t\t\t/* } */\n\n#endif\t\t\t\t/* } */\n/* }================================================================== */\n\n\n#if !defined(l_system)\n#if defined(LUA_USE_IOS)\n/* Despite claiming to be ISO C, iOS does not implement 'system'. */\n#define l_system(cmd) ((cmd) == NULL ? 0 : -1)\n#else\n#define l_system(cmd)\tsystem(cmd)  /* default definition */\n#endif\n#endif\n\n\nstatic int os_execute (lua_State *L) {\n  const char *cmd = luaL_optstring(L, 1, NULL);\n  int stat;\n  errno = 0;\n  stat = l_system(cmd);\n  if (cmd != NULL)\n    return luaL_execresult(L, stat);\n  else {\n    lua_pushboolean(L, stat);  /* true if there is a shell */\n    return 1;\n  }\n}\n\n\nstatic int os_remove (lua_State *L) {\n  const char *filename = luaL_checkstring(L, 1);\n  errno = 0;\n  return luaL_fileresult(L, remove(filename) == 0, filename);\n}\n\n\nstatic int os_rename (lua_State *L) {\n  const char *fromname = luaL_checkstring(L, 1);\n  const char *toname = luaL_checkstring(L, 2);\n  errno = 0;\n  return luaL_fileresult(L, rename(fromname, toname) == 0, NULL);\n}\n\n\nstatic int os_tmpname (lua_State *L) {\n  char buff[LUA_TMPNAMBUFSIZE];\n  int err;\n  lua_tmpnam(buff, err);\n  if (l_unlikely(err))\n    return luaL_error(L, \"unable to generate a unique filename\");\n  lua_pushstring(L, buff);\n  return 1;\n}\n\n\nstatic int os_getenv (lua_State *L) {\n  lua_pushstring(L, getenv(luaL_checkstring(L, 1)));  /* if NULL push nil */\n  return 1;\n}\n\n\nstatic int os_clock (lua_State *L) {\n  lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);\n  return 1;\n}\n\n\n/*\n** {======================================================\n** Time/Date operations\n** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,\n**   wday=%w+1, yday=%j, isdst=? }\n** =======================================================\n*/\n\n/*\n** About the overflow check: an overflow cannot occur when time\n** is represented by a lua_Integer, because either lua_Integer is\n** large enough to represent all int fields or it is not large enough\n** to represent a time that cause a field to overflow.  However, if\n** times are represented as doubles and lua_Integer is int, then the\n** time 0x1.e1853b0d184f6p+55 would cause an overflow when adding 1900\n** to compute the year.\n*/\nstatic void setfield (lua_State *L, const char *key, int value, int delta) {\n  #if (defined(LUA_NUMTIME) && LUA_MAXINTEGER <= INT_MAX)\n    if (l_unlikely(value > LUA_MAXINTEGER - delta))\n      luaL_error(L, \"field '%s' is out-of-bound\", key);\n  #endif\n  lua_pushinteger(L, (lua_Integer)value + delta);\n  lua_setfield(L, -2, key);\n}\n\n\nstatic void setboolfield (lua_State *L, const char *key, int value) {\n  if (value < 0)  /* undefined? */\n    return;  /* does not set field */\n  lua_pushboolean(L, value);\n  lua_setfield(L, -2, key);\n}\n\n\n/*\n** Set all fields from structure 'tm' in the table on top of the stack\n*/\nstatic void setallfields (lua_State *L, struct tm *stm) {\n  setfield(L, \"year\", stm->tm_year, 1900);\n  setfield(L, \"month\", stm->tm_mon, 1);\n  setfield(L, \"day\", stm->tm_mday, 0);\n  setfield(L, \"hour\", stm->tm_hour, 0);\n  setfield(L, \"min\", stm->tm_min, 0);\n  setfield(L, \"sec\", stm->tm_sec, 0);\n  setfield(L, \"yday\", stm->tm_yday, 1);\n  setfield(L, \"wday\", stm->tm_wday, 1);\n  setboolfield(L, \"isdst\", stm->tm_isdst);\n}\n\n\nstatic int getboolfield (lua_State *L, const char *key) {\n  int res;\n  res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);\n  lua_pop(L, 1);\n  return res;\n}\n\n\nstatic int getfield (lua_State *L, const char *key, int d, int delta) {\n  int isnum;\n  int t = lua_getfield(L, -1, key);  /* get field and its type */\n  lua_Integer res = lua_tointegerx(L, -1, &isnum);\n  if (!isnum) {  /* field is not an integer? */\n    if (l_unlikely(t != LUA_TNIL))  /* some other value? */\n      return luaL_error(L, \"field '%s' is not an integer\", key);\n    else if (l_unlikely(d < 0))  /* absent field; no default? */\n      return luaL_error(L, \"field '%s' missing in date table\", key);\n    res = d;\n  }\n  else {\n    if (!(res >= 0 ? res - delta <= INT_MAX : INT_MIN + delta <= res))\n      return luaL_error(L, \"field '%s' is out-of-bound\", key);\n    res -= delta;\n  }\n  lua_pop(L, 1);\n  return (int)res;\n}\n\n\nstatic const char *checkoption (lua_State *L, const char *conv,\n                                size_t convlen, char *buff) {\n  const char *option = LUA_STRFTIMEOPTIONS;\n  unsigned oplen = 1;  /* length of options being checked */\n  for (; *option != '\\0' && oplen <= convlen; option += oplen) {\n    if (*option == '|')  /* next block? */\n      oplen++;  /* will check options with next length (+1) */\n    else if (memcmp(conv, option, oplen) == 0) {  /* match? */\n      memcpy(buff, conv, oplen);  /* copy valid option to buffer */\n      buff[oplen] = '\\0';\n      return conv + oplen;  /* return next item */\n    }\n  }\n  luaL_argerror(L, 1,\n    lua_pushfstring(L, \"invalid conversion specifier '%%%s'\", conv));\n  return conv;  /* to avoid warnings */\n}\n\n\nstatic time_t l_checktime (lua_State *L, int arg) {\n  l_timet t = l_gettime(L, arg);\n  luaL_argcheck(L, (time_t)t == t, arg, \"time out-of-bounds\");\n  return (time_t)t;\n}\n\n\n/* maximum size for an individual 'strftime' item */\n#define SIZETIMEFMT\t250\n\n\nstatic int os_date (lua_State *L) {\n  size_t slen;\n  const char *s = luaL_optlstring(L, 1, \"%c\", &slen);\n  time_t t = luaL_opt(L, l_checktime, 2, time(NULL));\n  const char *se = s + slen;  /* 's' end */\n  struct tm tmr, *stm;\n  if (*s == '!') {  /* UTC? */\n    stm = l_gmtime(&t, &tmr);\n    s++;  /* skip '!' */\n  }\n  else\n    stm = l_localtime(&t, &tmr);\n  if (stm == NULL)  /* invalid date? */\n    return luaL_error(L,\n                 \"date result cannot be represented in this installation\");\n  if (strcmp(s, \"*t\") == 0) {\n    lua_createtable(L, 0, 9);  /* 9 = number of fields */\n    setallfields(L, stm);\n  }\n  else {\n    char cc[4];  /* buffer for individual conversion specifiers */\n    luaL_Buffer b;\n    cc[0] = '%';\n    luaL_buffinit(L, &b);\n    while (s < se) {\n      if (*s != '%')  /* not a conversion specifier? */\n        luaL_addchar(&b, *s++);\n      else {\n        size_t reslen;\n        char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT);\n        s++;  /* skip '%' */\n        /* copy specifier to 'cc' */\n        s = checkoption(L, s, ct_diff2sz(se - s), cc + 1);\n        reslen = strftime(buff, SIZETIMEFMT, cc, stm);\n        luaL_addsize(&b, reslen);\n      }\n    }\n    luaL_pushresult(&b);\n  }\n  return 1;\n}\n\n\nstatic int os_time (lua_State *L) {\n  time_t t;\n  if (lua_isnoneornil(L, 1))  /* called without args? */\n    t = time(NULL);  /* get current time */\n  else {\n    struct tm ts;\n    luaL_checktype(L, 1, LUA_TTABLE);\n    lua_settop(L, 1);  /* make sure table is at the top */\n    ts.tm_year = getfield(L, \"year\", -1, 1900);\n    ts.tm_mon = getfield(L, \"month\", -1, 1);\n    ts.tm_mday = getfield(L, \"day\", -1, 0);\n    ts.tm_hour = getfield(L, \"hour\", 12, 0);\n    ts.tm_min = getfield(L, \"min\", 0, 0);\n    ts.tm_sec = getfield(L, \"sec\", 0, 0);\n    ts.tm_isdst = getboolfield(L, \"isdst\");\n    t = mktime(&ts);\n    setallfields(L, &ts);  /* update fields with normalized values */\n  }\n  if (t != (time_t)(l_timet)t || t == (time_t)(-1))\n    return luaL_error(L,\n                  \"time result cannot be represented in this installation\");\n  l_pushtime(L, t);\n  return 1;\n}\n\n\nstatic int os_difftime (lua_State *L) {\n  time_t t1 = l_checktime(L, 1);\n  time_t t2 = l_checktime(L, 2);\n  lua_pushnumber(L, (lua_Number)difftime(t1, t2));\n  return 1;\n}\n\n/* }====================================================== */\n\n\nstatic int os_setlocale (lua_State *L) {\n  static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,\n                      LC_NUMERIC, LC_TIME};\n  static const char *const catnames[] = {\"all\", \"collate\", \"ctype\", \"monetary\",\n     \"numeric\", \"time\", NULL};\n  const char *l = luaL_optstring(L, 1, NULL);\n  int op = luaL_checkoption(L, 2, \"all\", catnames);\n  lua_pushstring(L, setlocale(cat[op], l));\n  return 1;\n}\n\n\nstatic int os_exit (lua_State *L) {\n  int status;\n  if (lua_isboolean(L, 1))\n    status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);\n  else\n    status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);\n  if (lua_toboolean(L, 2))\n    lua_close(L);\n  if (L) exit(status);  /* 'if' to avoid warnings for unreachable 'return' */\n  return 0;\n}\n\n\nstatic const luaL_Reg syslib[] = {\n  {\"clock\",     os_clock},\n  {\"date\",      os_date},\n  {\"difftime\",  os_difftime},\n  {\"execute\",   os_execute},\n  {\"exit\",      os_exit},\n  {\"getenv\",    os_getenv},\n  {\"remove\",    os_remove},\n  {\"rename\",    os_rename},\n  {\"setlocale\", os_setlocale},\n  {\"time\",      os_time},\n  {\"tmpname\",   os_tmpname},\n  {NULL, NULL}\n};\n\n/* }====================================================== */\n\n\n\nLUAMOD_API int luaopen_os (lua_State *L) {\n  luaL_newlib(L, syslib);\n  return 1;\n}\n\n"
  },
  {
    "path": "3rd/lua/lparser.c",
    "content": "/*\n** $Id: lparser.c $\n** Lua Parser\n** See Copyright Notice in lua.h\n*/\n\n#define lparser_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <limits.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lcode.h\"\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lfunc.h\"\n#include \"llex.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lopcodes.h\"\n#include \"lparser.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n\n\n\n/* maximum number of variable declarations per function (must be\n   smaller than 250, due to the bytecode format) */\n#define MAXVARS\t\t200\n\n\n#define hasmultret(k)\t\t((k) == VCALL || (k) == VVARARG)\n\n\n/* because all strings are unified by the scanner, the parser\n   can use pointer equality for string equality */\n#define eqstr(a,b)\t((a) == (b))\n\n\n/*\n** nodes for block list (list of active blocks)\n*/\ntypedef struct BlockCnt {\n  struct BlockCnt *previous;  /* chain */\n  int firstlabel;  /* index of first label in this block */\n  int firstgoto;  /* index of first pending goto in this block */\n  short nactvar;  /* number of active declarations at block entry */\n  lu_byte upval;  /* true if some variable in the block is an upvalue */\n  lu_byte isloop;  /* 1 if 'block' is a loop; 2 if it has pending breaks */\n  lu_byte insidetbc;  /* true if inside the scope of a to-be-closed var. */\n} BlockCnt;\n\n\n\n/*\n** prototypes for recursive non-terminal functions\n*/\nstatic void statement (LexState *ls);\nstatic void expr (LexState *ls, expdesc *v);\n\n\nstatic l_noret error_expected (LexState *ls, int token) {\n  luaX_syntaxerror(ls,\n      luaO_pushfstring(ls->L, \"%s expected\", luaX_token2str(ls, token)));\n}\n\n\nstatic l_noret errorlimit (FuncState *fs, int limit, const char *what) {\n  lua_State *L = fs->ls->L;\n  const char *msg;\n  int line = fs->f->linedefined;\n  const char *where = (line == 0)\n                      ? \"main function\"\n                      : luaO_pushfstring(L, \"function at line %d\", line);\n  msg = luaO_pushfstring(L, \"too many %s (limit is %d) in %s\",\n                             what, limit, where);\n  luaX_syntaxerror(fs->ls, msg);\n}\n\n\nvoid luaY_checklimit (FuncState *fs, int v, int l, const char *what) {\n  if (l_unlikely(v > l)) errorlimit(fs, l, what);\n}\n\n\n/*\n** Test whether next token is 'c'; if so, skip it.\n*/\nstatic int testnext (LexState *ls, int c) {\n  if (ls->t.token == c) {\n    luaX_next(ls);\n    return 1;\n  }\n  else return 0;\n}\n\n\n/*\n** Check that next token is 'c'.\n*/\nstatic void check (LexState *ls, int c) {\n  if (ls->t.token != c)\n    error_expected(ls, c);\n}\n\n\n/*\n** Check that next token is 'c' and skip it.\n*/\nstatic void checknext (LexState *ls, int c) {\n  check(ls, c);\n  luaX_next(ls);\n}\n\n\n#define check_condition(ls,c,msg)\t{ if (!(c)) luaX_syntaxerror(ls, msg); }\n\n\n/*\n** Check that next token is 'what' and skip it. In case of error,\n** raise an error that the expected 'what' should match a 'who'\n** in line 'where' (if that is not the current line).\n*/\nstatic void check_match (LexState *ls, int what, int who, int where) {\n  if (l_unlikely(!testnext(ls, what))) {\n    if (where == ls->linenumber)  /* all in the same line? */\n      error_expected(ls, what);  /* do not need a complex message */\n    else {\n      luaX_syntaxerror(ls, luaO_pushfstring(ls->L,\n             \"%s expected (to close %s at line %d)\",\n              luaX_token2str(ls, what), luaX_token2str(ls, who), where));\n    }\n  }\n}\n\n\nstatic TString *str_checkname (LexState *ls) {\n  TString *ts;\n  check(ls, TK_NAME);\n  ts = ls->t.seminfo.ts;\n  luaX_next(ls);\n  return ts;\n}\n\n\nstatic void init_exp (expdesc *e, expkind k, int i) {\n  e->f = e->t = NO_JUMP;\n  e->k = k;\n  e->u.info = i;\n}\n\n\nstatic void codestring (expdesc *e, TString *s) {\n  e->f = e->t = NO_JUMP;\n  e->k = VKSTR;\n  e->u.strval = s;\n}\n\n\nstatic void codename (LexState *ls, expdesc *e) {\n  codestring(e, str_checkname(ls));\n}\n\n\n/*\n** Register a new local variable in the active 'Proto' (for debug\n** information).\n*/\nstatic short registerlocalvar (LexState *ls, FuncState *fs,\n                               TString *varname) {\n  Proto *f = fs->f;\n  int oldsize = f->sizelocvars;\n  luaM_growvector(ls->L, f->locvars, fs->ndebugvars, f->sizelocvars,\n                  LocVar, SHRT_MAX, \"local variables\");\n  while (oldsize < f->sizelocvars)\n    f->locvars[oldsize++].varname = NULL;\n  f->locvars[fs->ndebugvars].varname = varname;\n  f->locvars[fs->ndebugvars].startpc = fs->pc;\n  luaC_objbarrier(ls->L, f, varname);\n  return fs->ndebugvars++;\n}\n\n\n/*\n** Create a new variable with the given 'name' and given 'kind'.\n** Return its index in the function.\n*/\nstatic int new_varkind (LexState *ls, TString *name, lu_byte kind) {\n  lua_State *L = ls->L;\n  FuncState *fs = ls->fs;\n  Dyndata *dyd = ls->dyd;\n  Vardesc *var;\n  luaM_growvector(L, dyd->actvar.arr, dyd->actvar.n + 1,\n             dyd->actvar.size, Vardesc, SHRT_MAX, \"variable declarations\");\n  var = &dyd->actvar.arr[dyd->actvar.n++];\n  var->vd.kind = kind;  /* default */\n  var->vd.name = name;\n  return dyd->actvar.n - 1 - fs->firstlocal;\n}\n\n\n/*\n** Create a new local variable with the given 'name' and regular kind.\n*/\nstatic int new_localvar (LexState *ls, TString *name) {\n  return new_varkind(ls, name, VDKREG);\n}\n\n#define new_localvarliteral(ls,v) \\\n    new_localvar(ls,  \\\n      luaX_newstring(ls, \"\" v, (sizeof(v)/sizeof(char)) - 1));\n\n\n\n/*\n** Return the \"variable description\" (Vardesc) of a given variable.\n** (Unless noted otherwise, all variables are referred to by their\n** compiler indices.)\n*/\nstatic Vardesc *getlocalvardesc (FuncState *fs, int vidx) {\n  return &fs->ls->dyd->actvar.arr[fs->firstlocal + vidx];\n}\n\n\n/*\n** Convert 'nvar', a compiler index level, to its corresponding\n** register. For that, search for the highest variable below that level\n** that is in a register and uses its register index ('ridx') plus one.\n*/\nstatic lu_byte reglevel (FuncState *fs, int nvar) {\n  while (nvar-- > 0) {\n    Vardesc *vd = getlocalvardesc(fs, nvar);  /* get previous variable */\n    if (varinreg(vd))  /* is in a register? */\n      return cast_byte(vd->vd.ridx + 1);\n  }\n  return 0;  /* no variables in registers */\n}\n\n\n/*\n** Return the number of variables in the register stack for the given\n** function.\n*/\nlu_byte luaY_nvarstack (FuncState *fs) {\n  return reglevel(fs, fs->nactvar);\n}\n\n\n/*\n** Get the debug-information entry for current variable 'vidx'.\n*/\nstatic LocVar *localdebuginfo (FuncState *fs, int vidx) {\n  Vardesc *vd = getlocalvardesc(fs,  vidx);\n  if (!varinreg(vd))\n    return NULL;  /* no debug info. for constants */\n  else {\n    int idx = vd->vd.pidx;\n    lua_assert(idx < fs->ndebugvars);\n    return &fs->f->locvars[idx];\n  }\n}\n\n\n/*\n** Create an expression representing variable 'vidx'\n*/\nstatic void init_var (FuncState *fs, expdesc *e, int vidx) {\n  e->f = e->t = NO_JUMP;\n  e->k = VLOCAL;\n  e->u.var.vidx = cast_short(vidx);\n  e->u.var.ridx = getlocalvardesc(fs, vidx)->vd.ridx;\n}\n\n\n/*\n** Raises an error if variable described by 'e' is read only; moreover,\n** if 'e' is t[exp] where t is the vararg parameter, change it to index\n** a real table. (Virtual vararg tables cannot be changed.)\n*/\nstatic void check_readonly (LexState *ls, expdesc *e) {\n  FuncState *fs = ls->fs;\n  TString *varname = NULL;  /* to be set if variable is const */\n  switch (e->k) {\n    case VCONST: {\n      varname = ls->dyd->actvar.arr[e->u.info].vd.name;\n      break;\n    }\n    case VLOCAL: case VVARGVAR: {\n      Vardesc *vardesc = getlocalvardesc(fs, e->u.var.vidx);\n      if (vardesc->vd.kind != VDKREG)  /* not a regular variable? */\n        varname = vardesc->vd.name;\n      break;\n    }\n    case VUPVAL: {\n      Upvaldesc *up = &fs->f->upvalues[e->u.info];\n      if (up->kind != VDKREG)\n        varname = up->name;\n      break;\n    }\n    case VVARGIND: {\n      needvatab(fs->f);  /* function will need a vararg table */\n      e->k = VINDEXED;\n    }  /* FALLTHROUGH */\n    case VINDEXUP: case VINDEXSTR: case VINDEXED: {  /* global variable */\n      if (e->u.ind.ro)  /* read-only? */\n        varname = tsvalue(&fs->f->k[e->u.ind.keystr]);\n      break;\n    }\n    default:\n      lua_assert(e->k == VINDEXI);  /* this one doesn't need any check */\n      return;  /* integer index cannot be read-only */\n  }\n  if (varname)\n    luaK_semerror(ls, \"attempt to assign to const variable '%s'\",\n                      getstr(varname));\n}\n\n\n/*\n** Start the scope for the last 'nvars' created variables.\n*/\nstatic void adjustlocalvars (LexState *ls, int nvars) {\n  FuncState *fs = ls->fs;\n  int reglevel = luaY_nvarstack(fs);\n  int i;\n  for (i = 0; i < nvars; i++) {\n    int vidx = fs->nactvar++;\n    Vardesc *var = getlocalvardesc(fs, vidx);\n    var->vd.ridx = cast_byte(reglevel++);\n    var->vd.pidx = registerlocalvar(ls, fs, var->vd.name);\n    luaY_checklimit(fs, reglevel, MAXVARS, \"local variables\");\n  }\n}\n\n\n/*\n** Close the scope for all variables up to level 'tolevel'.\n** (debug info.)\n*/\nstatic void removevars (FuncState *fs, int tolevel) {\n  fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);\n  while (fs->nactvar > tolevel) {\n    LocVar *var = localdebuginfo(fs, --fs->nactvar);\n    if (var)  /* does it have debug information? */\n      var->endpc = fs->pc;\n  }\n}\n\n\n/*\n** Search the upvalues of the function 'fs' for one\n** with the given 'name'.\n*/\nstatic int searchupvalue (FuncState *fs, TString *name) {\n  int i;\n  Upvaldesc *up = fs->f->upvalues;\n  for (i = 0; i < fs->nups; i++) {\n    if (eqstr(up[i].name, name)) return i;\n  }\n  return -1;  /* not found */\n}\n\n\nstatic Upvaldesc *allocupvalue (FuncState *fs) {\n  Proto *f = fs->f;\n  int oldsize = f->sizeupvalues;\n  luaY_checklimit(fs, fs->nups + 1, MAXUPVAL, \"upvalues\");\n  luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,\n                  Upvaldesc, MAXUPVAL, \"upvalues\");\n  while (oldsize < f->sizeupvalues)\n    f->upvalues[oldsize++].name = NULL;\n  return &f->upvalues[fs->nups++];\n}\n\n\nstatic int newupvalue (FuncState *fs, TString *name, expdesc *v) {\n  Upvaldesc *up = allocupvalue(fs);\n  FuncState *prev = fs->prev;\n  if (v->k == VLOCAL) {\n    up->instack = 1;\n    up->idx = v->u.var.ridx;\n    up->kind = getlocalvardesc(prev, v->u.var.vidx)->vd.kind;\n    lua_assert(eqstr(name, getlocalvardesc(prev, v->u.var.vidx)->vd.name));\n  }\n  else {\n    up->instack = 0;\n    up->idx = cast_byte(v->u.info);\n    up->kind = prev->f->upvalues[v->u.info].kind;\n    lua_assert(eqstr(name, prev->f->upvalues[v->u.info].name));\n  }\n  up->name = name;\n  luaC_objbarrier(fs->ls->L, fs->f, name);\n  return fs->nups - 1;\n}\n\n\n/*\n** Look for an active variable with the name 'n' in the\n** function 'fs'. If found, initialize 'var' with it and return\n** its expression kind; otherwise return -1. While searching,\n** var->u.info==-1 means that the preambular global declaration is\n** active (the default while there is no other global declaration);\n** var->u.info==-2 means there is no active collective declaration\n** (some previous global declaration but no collective declaration);\n** and var->u.info>=0 points to the inner-most (the first one found)\n** collective declaration, if there is one.\n*/\nstatic int searchvar (FuncState *fs, TString *n, expdesc *var) {\n  int i;\n  for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {\n    Vardesc *vd = getlocalvardesc(fs, i);\n    if (varglobal(vd)) {  /* global declaration? */\n      if (vd->vd.name == NULL) {  /* collective declaration? */\n        if (var->u.info < 0)  /* no previous collective declaration? */\n          var->u.info = fs->firstlocal + i;  /* this is the first one */\n      }\n      else {  /* global name */\n        if (eqstr(n, vd->vd.name)) {  /* found? */\n          init_exp(var, VGLOBAL, fs->firstlocal + i);\n          return VGLOBAL;\n        }\n        else if (var->u.info == -1)  /* active preambular declaration? */\n          var->u.info = -2;  /* invalidate preambular declaration */\n      }\n    }\n    else if (eqstr(n, vd->vd.name)) {  /* found? */\n      if (vd->vd.kind == RDKCTC)  /* compile-time constant? */\n        init_exp(var, VCONST, fs->firstlocal + i);\n      else {  /* local variable */\n        init_var(fs, var, i);\n        if (vd->vd.kind == RDKVAVAR)  /* vararg parameter? */\n          var->k = VVARGVAR;\n      }\n      return cast_int(var->k);\n    }\n  }\n  return -1;  /* not found */\n}\n\n\n/*\n** Mark block where variable at given level was defined\n** (to emit close instructions later).\n*/\nstatic void markupval (FuncState *fs, int level) {\n  BlockCnt *bl = fs->bl;\n  while (bl->nactvar > level)\n    bl = bl->previous;\n  bl->upval = 1;\n  fs->needclose = 1;\n}\n\n\n/*\n** Mark that current block has a to-be-closed variable.\n*/\nstatic void marktobeclosed (FuncState *fs) {\n  BlockCnt *bl = fs->bl;\n  bl->upval = 1;\n  bl->insidetbc = 1;\n  fs->needclose = 1;\n}\n\n\n/*\n** Find a variable with the given name 'n'. If it is an upvalue, add\n** this upvalue into all intermediate functions. If it is a global, set\n** 'var' as 'void' as a flag.\n*/\nstatic void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {\n  int v = searchvar(fs, n, var);  /* look up variables at current level */\n  if (v >= 0) {  /* found? */\n    if (!base) {\n      if (var->k == VVARGVAR)  /* vararg parameter? */\n        luaK_vapar2local(fs, var);  /* change it to a regular local */\n      if (var->k == VLOCAL)\n        markupval(fs, var->u.var.vidx);  /* will be used as an upvalue */\n    }\n    /* else nothing else to be done */\n  }\n  else {  /* not found at current level; try upvalues */\n    int idx = searchupvalue(fs, n);  /* try existing upvalues */\n    if (idx < 0) {  /* not found? */\n      if (fs->prev != NULL)  /* more levels? */\n        singlevaraux(fs->prev, n, var, 0);  /* try upper levels */\n      if (var->k == VLOCAL || var->k == VUPVAL)  /* local or upvalue? */\n        idx  = newupvalue(fs, n, var);  /* will be a new upvalue */\n      else  /* it is a global or a constant */\n        return;  /* don't need to do anything at this level */\n    }\n    init_exp(var, VUPVAL, idx);  /* new or old upvalue */\n  }\n}\n\n\nstatic void buildglobal (LexState *ls, TString *varname, expdesc *var) {\n  FuncState *fs = ls->fs;\n  expdesc key;\n  init_exp(var, VGLOBAL, -1);  /* global by default */\n  singlevaraux(fs, ls->envn, var, 1);  /* get environment variable */\n  if (var->k == VGLOBAL)\n    luaK_semerror(ls, \"%s is global when accessing variable '%s'\",\n                      LUA_ENV, getstr(varname));\n  luaK_exp2anyregup(fs, var);  /* _ENV could be a constant */\n  codestring(&key, varname);  /* key is variable name */\n  luaK_indexed(fs, var, &key);  /* 'var' represents _ENV[varname] */\n}\n\n\n/*\n** Find a variable with the given name 'n', handling global variables\n** too.\n*/\nstatic void buildvar (LexState *ls, TString *varname, expdesc *var) {\n  FuncState *fs = ls->fs;\n  init_exp(var, VGLOBAL, -1);  /* global by default */\n  singlevaraux(fs, varname, var, 1);\n  if (var->k == VGLOBAL) {  /* global name? */\n    int info = var->u.info;\n    /* global by default in the scope of a global declaration? */\n    if (info == -2)\n      luaK_semerror(ls, \"variable '%s' not declared\", getstr(varname));\n    buildglobal(ls, varname, var);\n    if (info != -1 && ls->dyd->actvar.arr[info].vd.kind == GDKCONST)\n      var->u.ind.ro = 1;  /* mark variable as read-only */\n    else  /* anyway must be a global */\n      lua_assert(info == -1 || ls->dyd->actvar.arr[info].vd.kind == GDKREG);\n  }\n}\n\n\nstatic void singlevar (LexState *ls, expdesc *var) {\n  buildvar(ls, str_checkname(ls), var);\n}\n\n\n/*\n** Adjust the number of results from an expression list 'e' with 'nexps'\n** expressions to 'nvars' values.\n*/\nstatic void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {\n  FuncState *fs = ls->fs;\n  int needed = nvars - nexps;  /* extra values needed */\n  luaK_checkstack(fs, needed);\n  if (hasmultret(e->k)) {  /* last expression has multiple returns? */\n    int extra = needed + 1;  /* discount last expression itself */\n    if (extra < 0)\n      extra = 0;\n    luaK_setreturns(fs, e, extra);  /* last exp. provides the difference */\n  }\n  else {\n    if (e->k != VVOID)  /* at least one expression? */\n      luaK_exp2nextreg(fs, e);  /* close last expression */\n    if (needed > 0)  /* missing values? */\n      luaK_nil(fs, fs->freereg, needed);  /* complete with nils */\n  }\n  if (needed > 0)\n    luaK_reserveregs(fs, needed);  /* registers for extra values */\n  else  /* adding 'needed' is actually a subtraction */\n    fs->freereg = cast_byte(fs->freereg + needed);  /* remove extra values */\n}\n\n\n#define enterlevel(ls)\tluaE_incCstack(ls->L)\n\n\n#define leavelevel(ls) ((ls)->L->nCcalls--)\n\n\n/*\n** Generates an error that a goto jumps into the scope of some\n** variable declaration.\n*/\nstatic l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) {\n  TString *tsname = getlocalvardesc(ls->fs, gt->nactvar)->vd.name;\n  const char *varname = (tsname != NULL) ? getstr(tsname) : \"*\";\n  luaK_semerror(ls,\n     \"<goto %s> at line %d jumps into the scope of '%s'\",\n      getstr(gt->name), gt->line, varname);  /* raise the error */\n}\n\n\n/*\n** Closes the goto at index 'g' to given 'label' and removes it\n** from the list of pending gotos.\n** If it jumps into the scope of some variable, raises an error.\n** The goto needs a CLOSE if it jumps out of a block with upvalues,\n** or out of the scope of some variable and the block has upvalues\n** (signaled by parameter 'bup').\n*/\nstatic void closegoto (LexState *ls, int g, Labeldesc *label, int bup) {\n  int i;\n  FuncState *fs = ls->fs;\n  Labellist *gl = &ls->dyd->gt;  /* list of gotos */\n  Labeldesc *gt = &gl->arr[g];  /* goto to be resolved */\n  lua_assert(eqstr(gt->name, label->name));\n  if (l_unlikely(gt->nactvar < label->nactvar))  /* enter some scope? */\n    jumpscopeerror(ls, gt);\n  if (gt->close ||\n      (label->nactvar < gt->nactvar && bup)) {  /* needs close? */\n    lu_byte stklevel = reglevel(fs, label->nactvar);\n    /* move jump to CLOSE position */\n    fs->f->code[gt->pc + 1] = fs->f->code[gt->pc];\n    /* put CLOSE instruction at original position */\n    fs->f->code[gt->pc] = CREATE_ABCk(OP_CLOSE, stklevel, 0, 0, 0);\n    gt->pc++;  /* must point to jump instruction */\n  }\n  luaK_patchlist(ls->fs, gt->pc, label->pc);  /* goto jumps to label */\n  for (i = g; i < gl->n - 1; i++)  /* remove goto from pending list */\n    gl->arr[i] = gl->arr[i + 1];\n  gl->n--;\n}\n\n\n/*\n** Search for an active label with the given name, starting at\n** index 'ilb' (so that it can search for all labels in current block\n** or all labels in current function).\n*/\nstatic Labeldesc *findlabel (LexState *ls, TString *name, int ilb) {\n  Dyndata *dyd = ls->dyd;\n  for (; ilb < dyd->label.n; ilb++) {\n    Labeldesc *lb = &dyd->label.arr[ilb];\n    if (eqstr(lb->name, name))  /* correct label? */\n      return lb;\n  }\n  return NULL;  /* label not found */\n}\n\n\n/*\n** Adds a new label/goto in the corresponding list.\n*/\nstatic int newlabelentry (LexState *ls, Labellist *l, TString *name,\n                          int line, int pc) {\n  int n = l->n;\n  luaM_growvector(ls->L, l->arr, n, l->size,\n                  Labeldesc, SHRT_MAX, \"labels/gotos\");\n  l->arr[n].name = name;\n  l->arr[n].line = line;\n  l->arr[n].nactvar = ls->fs->nactvar;\n  l->arr[n].close = 0;\n  l->arr[n].pc = pc;\n  l->n = n + 1;\n  return n;\n}\n\n\n/*\n** Create an entry for the goto and the code for it. As it is not known\n** at this point whether the goto may need a CLOSE, the code has a jump\n** followed by an CLOSE. (As the CLOSE comes after the jump, it is a\n** dead instruction; it works as a placeholder.) When the goto is closed\n** against a label, if it needs a CLOSE, the two instructions swap\n** positions, so that the CLOSE comes before the jump.\n*/\nstatic int newgotoentry (LexState *ls, TString *name, int line) {\n  FuncState *fs = ls->fs;\n  int pc = luaK_jump(fs);  /* create jump */\n  luaK_codeABC(fs, OP_CLOSE, 0, 1, 0);  /* spaceholder, marked as dead */\n  return newlabelentry(ls, &ls->dyd->gt, name, line, pc);\n}\n\n\n/*\n** Create a new label with the given 'name' at the given 'line'.\n** 'last' tells whether label is the last non-op statement in its\n** block. Solves all pending gotos to this new label and adds\n** a close instruction if necessary.\n** Returns true iff it added a close instruction.\n*/\nstatic void createlabel (LexState *ls, TString *name, int line, int last) {\n  FuncState *fs = ls->fs;\n  Labellist *ll = &ls->dyd->label;\n  int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs));\n  if (last) {  /* label is last no-op statement in the block? */\n    /* assume that locals are already out of scope */\n    ll->arr[l].nactvar = fs->bl->nactvar;\n  }\n}\n\n\n/*\n** Traverse the pending gotos of the finishing block checking whether\n** each match some label of that block. Those that do not match are\n** \"exported\" to the outer block, to be solved there. In particular,\n** its 'nactvar' is updated with the level of the inner block,\n** as the variables of the inner block are now out of scope.\n*/\nstatic void solvegotos (FuncState *fs, BlockCnt *bl) {\n  LexState *ls = fs->ls;\n  Labellist *gl = &ls->dyd->gt;\n  int outlevel = reglevel(fs, bl->nactvar);  /* level outside the block */\n  int igt = bl->firstgoto;  /* first goto in the finishing block */\n  while (igt < gl->n) {   /* for each pending goto */\n    Labeldesc *gt = &gl->arr[igt];\n    /* search for a matching label in the current block */\n    Labeldesc *lb = findlabel(ls, gt->name, bl->firstlabel);\n    if (lb != NULL)  /* found a match? */\n      closegoto(ls, igt, lb, bl->upval);  /* close and remove goto */\n    else {  /* adjust 'goto' for outer block */\n      /* block has variables to be closed and goto escapes the scope of\n         some variable? */\n      if (bl->upval && reglevel(fs, gt->nactvar) > outlevel)\n        gt->close = 1;  /* jump may need a close */\n      gt->nactvar = bl->nactvar;  /* correct level for outer block */\n      igt++;  /* go to next goto */\n    }\n  }\n  ls->dyd->label.n = bl->firstlabel;  /* remove local labels */\n}\n\n\nstatic void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {\n  bl->isloop = isloop;\n  bl->nactvar = fs->nactvar;\n  bl->firstlabel = fs->ls->dyd->label.n;\n  bl->firstgoto = fs->ls->dyd->gt.n;\n  bl->upval = 0;\n  /* inherit 'insidetbc' from enclosing block */\n  bl->insidetbc = (fs->bl != NULL && fs->bl->insidetbc);\n  bl->previous = fs->bl;  /* link block in function's block list */\n  fs->bl = bl;\n  lua_assert(fs->freereg == luaY_nvarstack(fs));\n}\n\n\n/*\n** generates an error for an undefined 'goto'.\n*/\nstatic l_noret undefgoto (LexState *ls, Labeldesc *gt) {\n  /* breaks are checked when created, cannot be undefined */\n  lua_assert(!eqstr(gt->name, ls->brkn));\n  luaK_semerror(ls, \"no visible label '%s' for <goto> at line %d\",\n                    getstr(gt->name), gt->line);\n}\n\n\nstatic void leaveblock (FuncState *fs) {\n  BlockCnt *bl = fs->bl;\n  LexState *ls = fs->ls;\n  lu_byte stklevel = reglevel(fs, bl->nactvar);  /* level outside block */\n  if (bl->previous && bl->upval)  /* need a 'close'? */\n    luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0);\n  fs->freereg = stklevel;  /* free registers */\n  removevars(fs, bl->nactvar);  /* remove block locals */\n  lua_assert(bl->nactvar == fs->nactvar);  /* back to level on entry */\n  if (bl->isloop == 2)  /* has to fix pending breaks? */\n    createlabel(ls, ls->brkn, 0, 0);\n  solvegotos(fs, bl);\n  if (bl->previous == NULL) {  /* was it the last block? */\n    if (bl->firstgoto < ls->dyd->gt.n)  /* still pending gotos? */\n      undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]);  /* error */\n  }\n  fs->bl = bl->previous;  /* current block now is previous one */\n}\n\n\n/*\n** adds a new prototype into list of prototypes\n*/\nstatic Proto *addprototype (LexState *ls) {\n  Proto *clp;\n  lua_State *L = ls->L;\n  FuncState *fs = ls->fs;\n  Proto *f = fs->f;  /* prototype of current function */\n  if (fs->np >= f->sizep) {\n    int oldsize = f->sizep;\n    luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, \"functions\");\n    while (oldsize < f->sizep)\n      f->p[oldsize++] = NULL;\n  }\n  f->p[fs->np++] = clp = luaF_newproto(L);\n  luaC_objbarrier(L, f, clp);\n  return clp;\n}\n\n\n/*\n** codes instruction to create new closure in parent function.\n** The OP_CLOSURE instruction uses the last available register,\n** so that, if it invokes the GC, the GC knows which registers\n** are in use at that time.\n\n*/\nstatic void codeclosure (LexState *ls, expdesc *v) {\n  FuncState *fs = ls->fs->prev;\n  init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));\n  luaK_exp2nextreg(fs, v);  /* fix it at the last register */\n}\n\n\nstatic void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {\n  lua_State *L = ls->L;\n  Proto *f = fs->f;\n  fs->prev = ls->fs;  /* linked list of funcstates */\n  fs->ls = ls;\n  ls->fs = fs;\n  fs->pc = 0;\n  fs->previousline = f->linedefined;\n  fs->iwthabs = 0;\n  fs->lasttarget = 0;\n  fs->freereg = 0;\n  fs->nk = 0;\n  fs->nabslineinfo = 0;\n  fs->np = 0;\n  fs->nups = 0;\n  fs->ndebugvars = 0;\n  fs->nactvar = 0;\n  fs->needclose = 0;\n  fs->firstlocal = ls->dyd->actvar.n;\n  fs->firstlabel = ls->dyd->label.n;\n  fs->bl = NULL;\n  f->source = ls->source;\n  luaC_objbarrier(L, f, f->source);\n  f->maxstacksize = 2;  /* registers 0/1 are always valid */\n  fs->kcache = luaH_new(L);  /* create table for function */\n  sethvalue2s(L, L->top.p, fs->kcache);  /* anchor it */\n  luaD_inctop(L);\n  enterblock(fs, bl, 0);\n}\n\n\nstatic void close_func (LexState *ls) {\n  lua_State *L = ls->L;\n  FuncState *fs = ls->fs;\n  Proto *f = fs->f;\n  luaK_ret(fs, luaY_nvarstack(fs), 0);  /* final return */\n  leaveblock(fs);\n  lua_assert(fs->bl == NULL);\n  luaK_finish(fs);\n  luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction);\n  luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte);\n  luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo,\n                       fs->nabslineinfo, AbsLineInfo);\n  luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue);\n  luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *);\n  luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar);\n  luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);\n  ls->fs = fs->prev;\n  L->top.p--;  /* pop kcache table */\n  luaC_checkGC(L);\n}\n\n\n/*\n** {======================================================================\n** GRAMMAR RULES\n** =======================================================================\n*/\n\n\n/*\n** check whether current token is in the follow set of a block.\n** 'until' closes syntactical blocks, but do not close scope,\n** so it is handled in separate.\n*/\nstatic int block_follow (LexState *ls, int withuntil) {\n  switch (ls->t.token) {\n    case TK_ELSE: case TK_ELSEIF:\n    case TK_END: case TK_EOS:\n      return 1;\n    case TK_UNTIL: return withuntil;\n    default: return 0;\n  }\n}\n\n\nstatic void statlist (LexState *ls) {\n  /* statlist -> { stat [';'] } */\n  while (!block_follow(ls, 1)) {\n    if (ls->t.token == TK_RETURN) {\n      statement(ls);\n      return;  /* 'return' must be last statement */\n    }\n    statement(ls);\n  }\n}\n\n\nstatic void fieldsel (LexState *ls, expdesc *v) {\n  /* fieldsel -> ['.' | ':'] NAME */\n  FuncState *fs = ls->fs;\n  expdesc key;\n  luaK_exp2anyregup(fs, v);\n  luaX_next(ls);  /* skip the dot or colon */\n  codename(ls, &key);\n  luaK_indexed(fs, v, &key);\n}\n\n\nstatic void yindex (LexState *ls, expdesc *v) {\n  /* index -> '[' expr ']' */\n  luaX_next(ls);  /* skip the '[' */\n  expr(ls, v);\n  luaK_exp2val(ls->fs, v);\n  checknext(ls, ']');\n}\n\n\n/*\n** {======================================================================\n** Rules for Constructors\n** =======================================================================\n*/\n\ntypedef struct ConsControl {\n  expdesc v;  /* last list item read */\n  expdesc *t;  /* table descriptor */\n  int nh;  /* total number of 'record' elements */\n  int na;  /* number of array elements already stored */\n  int tostore;  /* number of array elements pending to be stored */\n  int maxtostore;  /* maximum number of pending elements */\n} ConsControl;\n\n\n/*\n** Maximum number of elements in a constructor, to control the following:\n** * counter overflows;\n** * overflows in 'extra' for OP_NEWTABLE and OP_SETLIST;\n** * overflows when adding multiple returns in OP_SETLIST.\n*/\n#define MAX_CNST\t(INT_MAX/2)\n#if MAX_CNST/(MAXARG_vC + 1) > MAXARG_Ax\n#undef MAX_CNST\n#define MAX_CNST\t(MAXARG_Ax * (MAXARG_vC + 1))\n#endif\n\n\nstatic void recfield (LexState *ls, ConsControl *cc) {\n  /* recfield -> (NAME | '['exp']') = exp */\n  FuncState *fs = ls->fs;\n  lu_byte reg = ls->fs->freereg;\n  expdesc tab, key, val;\n  if (ls->t.token == TK_NAME)\n    codename(ls, &key);\n  else  /* ls->t.token == '[' */\n    yindex(ls, &key);\n  cc->nh++;\n  checknext(ls, '=');\n  tab = *cc->t;\n  luaK_indexed(fs, &tab, &key);\n  expr(ls, &val);\n  luaK_storevar(fs, &tab, &val);\n  fs->freereg = reg;  /* free registers */\n}\n\n\nstatic void closelistfield (FuncState *fs, ConsControl *cc) {\n  lua_assert(cc->tostore > 0);\n  luaK_exp2nextreg(fs, &cc->v);\n  cc->v.k = VVOID;\n  if (cc->tostore >= cc->maxtostore) {\n    luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);  /* flush */\n    cc->na += cc->tostore;\n    cc->tostore = 0;  /* no more items pending */\n  }\n}\n\n\nstatic void lastlistfield (FuncState *fs, ConsControl *cc) {\n  if (cc->tostore == 0) return;\n  if (hasmultret(cc->v.k)) {\n    luaK_setmultret(fs, &cc->v);\n    luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);\n    cc->na--;  /* do not count last expression (unknown number of elements) */\n  }\n  else {\n    if (cc->v.k != VVOID)\n      luaK_exp2nextreg(fs, &cc->v);\n    luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);\n  }\n  cc->na += cc->tostore;\n}\n\n\nstatic void listfield (LexState *ls, ConsControl *cc) {\n  /* listfield -> exp */\n  expr(ls, &cc->v);\n  cc->tostore++;\n}\n\n\nstatic void field (LexState *ls, ConsControl *cc) {\n  /* field -> listfield | recfield */\n  switch(ls->t.token) {\n    case TK_NAME: {  /* may be 'listfield' or 'recfield' */\n      if (luaX_lookahead(ls) != '=')  /* expression? */\n        listfield(ls, cc);\n      else\n        recfield(ls, cc);\n      break;\n    }\n    case '[': {\n      recfield(ls, cc);\n      break;\n    }\n    default: {\n      listfield(ls, cc);\n      break;\n    }\n  }\n}\n\n\n/*\n** Compute a limit for how many registers a constructor can use before\n** emitting a 'SETLIST' instruction, based on how many registers are\n** available.\n*/\nstatic int maxtostore (FuncState *fs) {\n  int numfreeregs = MAX_FSTACK - fs->freereg;\n  if (numfreeregs >= 160)  /* \"lots\" of registers? */\n    return numfreeregs / 5;  /* use up to 1/5 of them */\n  else if (numfreeregs >= 80)  /* still \"enough\" registers? */\n    return 10;  /* one 'SETLIST' instruction for each 10 values */\n  else  /* save registers for potential more nesting */\n    return 1;\n}\n\n\nstatic void constructor (LexState *ls, expdesc *t) {\n  /* constructor -> '{' [ field { sep field } [sep] ] '}'\n     sep -> ',' | ';' */\n  FuncState *fs = ls->fs;\n  int line = ls->linenumber;\n  int pc = luaK_codevABCk(fs, OP_NEWTABLE, 0, 0, 0, 0);\n  ConsControl cc;\n  luaK_code(fs, 0);  /* space for extra arg. */\n  cc.na = cc.nh = cc.tostore = 0;\n  cc.t = t;\n  init_exp(t, VNONRELOC, fs->freereg);  /* table will be at stack top */\n  luaK_reserveregs(fs, 1);\n  init_exp(&cc.v, VVOID, 0);  /* no value (yet) */\n  checknext(ls, '{' /*}*/);\n  cc.maxtostore = maxtostore(fs);\n  do {\n    if (ls->t.token == /*{*/ '}') break;\n    if (cc.v.k != VVOID)  /* is there a previous list item? */\n      closelistfield(fs, &cc);  /* close it */\n    field(ls, &cc);\n    luaY_checklimit(fs, cc.tostore + cc.na + cc.nh, MAX_CNST,\n                    \"items in a constructor\");\n  } while (testnext(ls, ',') || testnext(ls, ';'));\n  check_match(ls, /*{*/ '}', '{' /*}*/, line);\n  lastlistfield(fs, &cc);\n  luaK_settablesize(fs, pc, t->u.info, cc.na, cc.nh);\n}\n\n/* }====================================================================== */\n\n\nstatic void setvararg (FuncState *fs) {\n  fs->f->flag |= PF_VAHID;  /* by default, use hidden vararg arguments */\n  luaK_codeABC(fs, OP_VARARGPREP, 0, 0, 0);\n}\n\n\nstatic void parlist (LexState *ls) {\n  /* parlist -> [ {NAME ','} (NAME | '...') ] */\n  FuncState *fs = ls->fs;\n  Proto *f = fs->f;\n  int nparams = 0;\n  int varargk = 0;\n  if (ls->t.token != ')') {  /* is 'parlist' not empty? */\n    do {\n      switch (ls->t.token) {\n        case TK_NAME: {\n          new_localvar(ls, str_checkname(ls));\n          nparams++;\n          break;\n        }\n        case TK_DOTS: {\n          varargk = 1;\n          luaX_next(ls);  /* skip '...' */\n          if (ls->t.token == TK_NAME)\n            new_varkind(ls, str_checkname(ls), RDKVAVAR);\n          else\n            new_localvarliteral(ls, \"(vararg table)\");\n          break;\n        }\n        default: luaX_syntaxerror(ls, \"<name> or '...' expected\");\n      }\n    } while (!varargk && testnext(ls, ','));\n  }\n  adjustlocalvars(ls, nparams);\n  f->numparams = cast_byte(fs->nactvar);\n  if (varargk) {\n    setvararg(fs);  /* declared vararg */\n    adjustlocalvars(ls, 1);  /* vararg parameter */\n  }\n  /* reserve registers for parameters (plus vararg parameter, if present) */\n  luaK_reserveregs(fs, fs->nactvar);\n}\n\n\nstatic void body (LexState *ls, expdesc *e, int ismethod, int line) {\n  /* body ->  '(' parlist ')' block END */\n  FuncState new_fs;\n  BlockCnt bl;\n  new_fs.f = addprototype(ls);\n  new_fs.f->linedefined = line;\n  open_func(ls, &new_fs, &bl);\n  checknext(ls, '(');\n  if (ismethod) {\n    new_localvarliteral(ls, \"self\");  /* create 'self' parameter */\n    adjustlocalvars(ls, 1);\n  }\n  parlist(ls);\n  checknext(ls, ')');\n  statlist(ls);\n  new_fs.f->lastlinedefined = ls->linenumber;\n  check_match(ls, TK_END, TK_FUNCTION, line);\n  codeclosure(ls, e);\n  close_func(ls);\n}\n\n\nstatic int explist (LexState *ls, expdesc *v) {\n  /* explist -> expr { ',' expr } */\n  int n = 1;  /* at least one expression */\n  expr(ls, v);\n  while (testnext(ls, ',')) {\n    luaK_exp2nextreg(ls->fs, v);\n    expr(ls, v);\n    n++;\n  }\n  return n;\n}\n\n\nstatic void funcargs (LexState *ls, expdesc *f) {\n  FuncState *fs = ls->fs;\n  expdesc args;\n  int base, nparams;\n  int line = ls->linenumber;\n  switch (ls->t.token) {\n    case '(': {  /* funcargs -> '(' [ explist ] ')' */\n      luaX_next(ls);\n      if (ls->t.token == ')')  /* arg list is empty? */\n        args.k = VVOID;\n      else {\n        explist(ls, &args);\n        if (hasmultret(args.k))\n          luaK_setmultret(fs, &args);\n      }\n      check_match(ls, ')', '(', line);\n      break;\n    }\n    case '{' /*}*/: {  /* funcargs -> constructor */\n      constructor(ls, &args);\n      break;\n    }\n    case TK_STRING: {  /* funcargs -> STRING */\n      codestring(&args, ls->t.seminfo.ts);\n      luaX_next(ls);  /* must use 'seminfo' before 'next' */\n      break;\n    }\n    default: {\n      luaX_syntaxerror(ls, \"function arguments expected\");\n    }\n  }\n  lua_assert(f->k == VNONRELOC);\n  base = f->u.info;  /* base register for call */\n  if (hasmultret(args.k))\n    nparams = LUA_MULTRET;  /* open call */\n  else {\n    if (args.k != VVOID)\n      luaK_exp2nextreg(fs, &args);  /* close last argument */\n    nparams = fs->freereg - (base+1);\n  }\n  init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));\n  luaK_fixline(fs, line);\n  /* call removes function and arguments and leaves one result (unless\n     changed later) */\n  fs->freereg = cast_byte(base + 1);\n}\n\n\n\n\n/*\n** {======================================================================\n** Expression parsing\n** =======================================================================\n*/\n\n\nstatic void primaryexp (LexState *ls, expdesc *v) {\n  /* primaryexp -> NAME | '(' expr ')' */\n  switch (ls->t.token) {\n    case '(': {\n      int line = ls->linenumber;\n      luaX_next(ls);\n      expr(ls, v);\n      check_match(ls, ')', '(', line);\n      luaK_dischargevars(ls->fs, v);\n      return;\n    }\n    case TK_NAME: {\n      singlevar(ls, v);\n      return;\n    }\n    default: {\n      luaX_syntaxerror(ls, \"unexpected symbol\");\n    }\n  }\n}\n\n\nstatic void suffixedexp (LexState *ls, expdesc *v) {\n  /* suffixedexp ->\n       primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */\n  FuncState *fs = ls->fs;\n  primaryexp(ls, v);\n  for (;;) {\n    switch (ls->t.token) {\n      case '.': {  /* fieldsel */\n        fieldsel(ls, v);\n        break;\n      }\n      case '[': {  /* '[' exp ']' */\n        expdesc key;\n        luaK_exp2anyregup(fs, v);\n        yindex(ls, &key);\n        luaK_indexed(fs, v, &key);\n        break;\n      }\n      case ':': {  /* ':' NAME funcargs */\n        expdesc key;\n        luaX_next(ls);\n        codename(ls, &key);\n        luaK_self(fs, v, &key);\n        funcargs(ls, v);\n        break;\n      }\n      case '(': case TK_STRING: case '{' /*}*/: {  /* funcargs */\n        luaK_exp2nextreg(fs, v);\n        funcargs(ls, v);\n        break;\n      }\n      default: return;\n    }\n  }\n}\n\n\nstatic void simpleexp (LexState *ls, expdesc *v) {\n  /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |\n                  constructor | FUNCTION body | suffixedexp */\n  switch (ls->t.token) {\n    case TK_FLT: {\n      init_exp(v, VKFLT, 0);\n      v->u.nval = ls->t.seminfo.r;\n      break;\n    }\n    case TK_INT: {\n      init_exp(v, VKINT, 0);\n      v->u.ival = ls->t.seminfo.i;\n      break;\n    }\n    case TK_STRING: {\n      codestring(v, ls->t.seminfo.ts);\n      break;\n    }\n    case TK_NIL: {\n      init_exp(v, VNIL, 0);\n      break;\n    }\n    case TK_TRUE: {\n      init_exp(v, VTRUE, 0);\n      break;\n    }\n    case TK_FALSE: {\n      init_exp(v, VFALSE, 0);\n      break;\n    }\n    case TK_DOTS: {  /* vararg */\n      FuncState *fs = ls->fs;\n      check_condition(ls, isvararg(fs->f),\n                      \"cannot use '...' outside a vararg function\");\n      init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, fs->f->numparams, 1));\n      break;\n    }\n    case '{' /*}*/: {  /* constructor */\n      constructor(ls, v);\n      return;\n    }\n    case TK_FUNCTION: {\n      luaX_next(ls);\n      body(ls, v, 0, ls->linenumber);\n      return;\n    }\n    default: {\n      suffixedexp(ls, v);\n      return;\n    }\n  }\n  luaX_next(ls);\n}\n\n\nstatic UnOpr getunopr (int op) {\n  switch (op) {\n    case TK_NOT: return OPR_NOT;\n    case '-': return OPR_MINUS;\n    case '~': return OPR_BNOT;\n    case '#': return OPR_LEN;\n    default: return OPR_NOUNOPR;\n  }\n}\n\n\nstatic BinOpr getbinopr (int op) {\n  switch (op) {\n    case '+': return OPR_ADD;\n    case '-': return OPR_SUB;\n    case '*': return OPR_MUL;\n    case '%': return OPR_MOD;\n    case '^': return OPR_POW;\n    case '/': return OPR_DIV;\n    case TK_IDIV: return OPR_IDIV;\n    case '&': return OPR_BAND;\n    case '|': return OPR_BOR;\n    case '~': return OPR_BXOR;\n    case TK_SHL: return OPR_SHL;\n    case TK_SHR: return OPR_SHR;\n    case TK_CONCAT: return OPR_CONCAT;\n    case TK_NE: return OPR_NE;\n    case TK_EQ: return OPR_EQ;\n    case '<': return OPR_LT;\n    case TK_LE: return OPR_LE;\n    case '>': return OPR_GT;\n    case TK_GE: return OPR_GE;\n    case TK_AND: return OPR_AND;\n    case TK_OR: return OPR_OR;\n    default: return OPR_NOBINOPR;\n  }\n}\n\n\n/*\n** Priority table for binary operators.\n*/\nstatic const struct {\n  lu_byte left;  /* left priority for each binary operator */\n  lu_byte right; /* right priority */\n} priority[] = {  /* ORDER OPR */\n   {10, 10}, {10, 10},           /* '+' '-' */\n   {11, 11}, {11, 11},           /* '*' '%' */\n   {14, 13},                  /* '^' (right associative) */\n   {11, 11}, {11, 11},           /* '/' '//' */\n   {6, 6}, {4, 4}, {5, 5},   /* '&' '|' '~' */\n   {7, 7}, {7, 7},           /* '<<' '>>' */\n   {9, 8},                   /* '..' (right associative) */\n   {3, 3}, {3, 3}, {3, 3},   /* ==, <, <= */\n   {3, 3}, {3, 3}, {3, 3},   /* ~=, >, >= */\n   {2, 2}, {1, 1}            /* and, or */\n};\n\n#define UNARY_PRIORITY\t12  /* priority for unary operators */\n\n\n/*\n** subexpr -> (simpleexp | unop subexpr) { binop subexpr }\n** where 'binop' is any binary operator with a priority higher than 'limit'\n*/\nstatic BinOpr subexpr (LexState *ls, expdesc *v, int limit) {\n  BinOpr op;\n  UnOpr uop;\n  enterlevel(ls);\n  uop = getunopr(ls->t.token);\n  if (uop != OPR_NOUNOPR) {  /* prefix (unary) operator? */\n    int line = ls->linenumber;\n    luaX_next(ls);  /* skip operator */\n    subexpr(ls, v, UNARY_PRIORITY);\n    luaK_prefix(ls->fs, uop, v, line);\n  }\n  else simpleexp(ls, v);\n  /* expand while operators have priorities higher than 'limit' */\n  op = getbinopr(ls->t.token);\n  while (op != OPR_NOBINOPR && priority[op].left > limit) {\n    expdesc v2;\n    BinOpr nextop;\n    int line = ls->linenumber;\n    luaX_next(ls);  /* skip operator */\n    luaK_infix(ls->fs, op, v);\n    /* read sub-expression with higher priority */\n    nextop = subexpr(ls, &v2, priority[op].right);\n    luaK_posfix(ls->fs, op, v, &v2, line);\n    op = nextop;\n  }\n  leavelevel(ls);\n  return op;  /* return first untreated operator */\n}\n\n\nstatic void expr (LexState *ls, expdesc *v) {\n  subexpr(ls, v, 0);\n}\n\n/* }==================================================================== */\n\n\n\n/*\n** {======================================================================\n** Rules for Statements\n** =======================================================================\n*/\n\n\nstatic void block (LexState *ls) {\n  /* block -> statlist */\n  FuncState *fs = ls->fs;\n  BlockCnt bl;\n  enterblock(fs, &bl, 0);\n  statlist(ls);\n  leaveblock(fs);\n}\n\n\n/*\n** structure to chain all variables in the left-hand side of an\n** assignment\n*/\nstruct LHS_assign {\n  struct LHS_assign *prev;\n  expdesc v;  /* variable (global, local, upvalue, or indexed) */\n};\n\n\n/*\n** check whether, in an assignment to an upvalue/local variable, the\n** upvalue/local variable is begin used in a previous assignment to a\n** table. If so, save original upvalue/local value in a safe place and\n** use this safe copy in the previous assignment.\n*/\nstatic void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {\n  FuncState *fs = ls->fs;\n  lu_byte extra = fs->freereg;  /* eventual position to save local variable */\n  int conflict = 0;\n  for (; lh; lh = lh->prev) {  /* check all previous assignments */\n    if (vkisindexed(lh->v.k)) {  /* assignment to table field? */\n      if (lh->v.k == VINDEXUP) {  /* is table an upvalue? */\n        if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) {\n          conflict = 1;  /* table is the upvalue being assigned now */\n          lh->v.k = VINDEXSTR;\n          lh->v.u.ind.t = extra;  /* assignment will use safe copy */\n        }\n      }\n      else {  /* table is a register */\n        if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.ridx) {\n          conflict = 1;  /* table is the local being assigned now */\n          lh->v.u.ind.t = extra;  /* assignment will use safe copy */\n        }\n        /* is index the local being assigned? */\n        if (lh->v.k == VINDEXED && v->k == VLOCAL &&\n            lh->v.u.ind.idx == v->u.var.ridx) {\n          conflict = 1;\n          lh->v.u.ind.idx = extra;  /* previous assignment will use safe copy */\n        }\n      }\n    }\n  }\n  if (conflict) {\n    /* copy upvalue/local value to a temporary (in position 'extra') */\n    if (v->k == VLOCAL)\n      luaK_codeABC(fs, OP_MOVE, extra, v->u.var.ridx, 0);\n    else\n      luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0);\n    luaK_reserveregs(fs, 1);\n  }\n}\n\n\n/* Create code to store the \"top\" register in 'var' */\nstatic void storevartop (FuncState *fs, expdesc *var) {\n  expdesc e;\n  init_exp(&e, VNONRELOC, fs->freereg - 1);\n  luaK_storevar(fs, var, &e);  /* will also free the top register */\n}\n\n\n/*\n** Parse and compile a multiple assignment. The first \"variable\"\n** (a 'suffixedexp') was already read by the caller.\n**\n** assignment -> suffixedexp restassign\n** restassign -> ',' suffixedexp restassign | '=' explist\n*/\nstatic void restassign (LexState *ls, struct LHS_assign *lh, int nvars) {\n  expdesc e;\n  check_condition(ls, vkisvar(lh->v.k), \"syntax error\");\n  check_readonly(ls, &lh->v);\n  if (testnext(ls, ',')) {  /* restassign -> ',' suffixedexp restassign */\n    struct LHS_assign nv;\n    nv.prev = lh;\n    suffixedexp(ls, &nv.v);\n    if (!vkisindexed(nv.v.k))\n      check_conflict(ls, lh, &nv.v);\n    enterlevel(ls);  /* control recursion depth */\n    restassign(ls, &nv, nvars+1);\n    leavelevel(ls);\n  }\n  else {  /* restassign -> '=' explist */\n    int nexps;\n    checknext(ls, '=');\n    nexps = explist(ls, &e);\n    if (nexps != nvars)\n      adjust_assign(ls, nvars, nexps, &e);\n    else {\n      luaK_setoneret(ls->fs, &e);  /* close last expression */\n      luaK_storevar(ls->fs, &lh->v, &e);\n      return;  /* avoid default */\n    }\n  }\n  storevartop(ls->fs, &lh->v);  /* default assignment */\n}\n\n\nstatic int cond (LexState *ls) {\n  /* cond -> exp */\n  expdesc v;\n  expr(ls, &v);  /* read condition */\n  if (v.k == VNIL) v.k = VFALSE;  /* 'falses' are all equal here */\n  luaK_goiftrue(ls->fs, &v);\n  return v.f;\n}\n\n\nstatic void gotostat (LexState *ls, int line) {\n  TString *name = str_checkname(ls);  /* label's name */\n  newgotoentry(ls, name, line);\n}\n\n\n/*\n** Break statement. Semantically equivalent to \"goto break\".\n*/\nstatic void breakstat (LexState *ls, int line) {\n  BlockCnt *bl;  /* to look for an enclosing loop */\n  for (bl = ls->fs->bl; bl != NULL; bl = bl->previous) {\n    if (bl->isloop)  /* found one? */\n      goto ok;\n  }\n  luaX_syntaxerror(ls, \"break outside loop\");\n ok:\n  bl->isloop = 2;  /* signal that block has pending breaks */\n  luaX_next(ls);  /* skip break */\n  newgotoentry(ls, ls->brkn, line);\n}\n\n\n/*\n** Check whether there is already a label with the given 'name' at\n** current function.\n*/\nstatic void checkrepeated (LexState *ls, TString *name) {\n  Labeldesc *lb = findlabel(ls, name, ls->fs->firstlabel);\n  if (l_unlikely(lb != NULL))  /* already defined? */\n    luaK_semerror(ls, \"label '%s' already defined on line %d\",\n                      getstr(name), lb->line);  /* error */\n}\n\n\nstatic void labelstat (LexState *ls, TString *name, int line) {\n  /* label -> '::' NAME '::' */\n  checknext(ls, TK_DBCOLON);  /* skip double colon */\n  while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)\n    statement(ls);  /* skip other no-op statements */\n  checkrepeated(ls, name);  /* check for repeated labels */\n  createlabel(ls, name, line, block_follow(ls, 0));\n}\n\n\nstatic void whilestat (LexState *ls, int line) {\n  /* whilestat -> WHILE cond DO block END */\n  FuncState *fs = ls->fs;\n  int whileinit;\n  int condexit;\n  BlockCnt bl;\n  luaX_next(ls);  /* skip WHILE */\n  whileinit = luaK_getlabel(fs);\n  condexit = cond(ls);\n  enterblock(fs, &bl, 1);\n  checknext(ls, TK_DO);\n  block(ls);\n  luaK_jumpto(fs, whileinit);\n  check_match(ls, TK_END, TK_WHILE, line);\n  leaveblock(fs);\n  luaK_patchtohere(fs, condexit);  /* false conditions finish the loop */\n}\n\n\nstatic void repeatstat (LexState *ls, int line) {\n  /* repeatstat -> REPEAT block UNTIL cond */\n  int condexit;\n  FuncState *fs = ls->fs;\n  int repeat_init = luaK_getlabel(fs);\n  BlockCnt bl1, bl2;\n  enterblock(fs, &bl1, 1);  /* loop block */\n  enterblock(fs, &bl2, 0);  /* scope block */\n  luaX_next(ls);  /* skip REPEAT */\n  statlist(ls);\n  check_match(ls, TK_UNTIL, TK_REPEAT, line);\n  condexit = cond(ls);  /* read condition (inside scope block) */\n  leaveblock(fs);  /* finish scope */\n  if (bl2.upval) {  /* upvalues? */\n    int exit = luaK_jump(fs);  /* normal exit must jump over fix */\n    luaK_patchtohere(fs, condexit);  /* repetition must close upvalues */\n    luaK_codeABC(fs, OP_CLOSE, reglevel(fs, bl2.nactvar), 0, 0);\n    condexit = luaK_jump(fs);  /* repeat after closing upvalues */\n    luaK_patchtohere(fs, exit);  /* normal exit comes to here */\n  }\n  luaK_patchlist(fs, condexit, repeat_init);  /* close the loop */\n  leaveblock(fs);  /* finish loop */\n}\n\n\n/*\n** Read an expression and generate code to put its results in next\n** stack slot.\n**\n*/\nstatic void exp1 (LexState *ls) {\n  expdesc e;\n  expr(ls, &e);\n  luaK_exp2nextreg(ls->fs, &e);\n  lua_assert(e.k == VNONRELOC);\n}\n\n\n/*\n** Fix for instruction at position 'pc' to jump to 'dest'.\n** (Jump addresses are relative in Lua). 'back' true means\n** a back jump.\n*/\nstatic void fixforjump (FuncState *fs, int pc, int dest, int back) {\n  Instruction *jmp = &fs->f->code[pc];\n  int offset = dest - (pc + 1);\n  if (back)\n    offset = -offset;\n  if (l_unlikely(offset > MAXARG_Bx))\n    luaX_syntaxerror(fs->ls, \"control structure too long\");\n  SETARG_Bx(*jmp, offset);\n}\n\n\n/*\n** Generate code for a 'for' loop.\n*/\nstatic void forbody (LexState *ls, int base, int line, int nvars, int isgen) {\n  /* forbody -> DO block */\n  static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP};\n  static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP};\n  BlockCnt bl;\n  FuncState *fs = ls->fs;\n  int prep, endfor;\n  checknext(ls, TK_DO);\n  prep = luaK_codeABx(fs, forprep[isgen], base, 0);\n  fs->freereg--;  /* both 'forprep' remove one register from the stack */\n  enterblock(fs, &bl, 0);  /* scope for declared variables */\n  adjustlocalvars(ls, nvars);\n  luaK_reserveregs(fs, nvars);\n  block(ls);\n  leaveblock(fs);  /* end of scope for declared variables */\n  fixforjump(fs, prep, luaK_getlabel(fs), 0);\n  if (isgen) {  /* generic for? */\n    luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);\n    luaK_fixline(fs, line);\n  }\n  endfor = luaK_codeABx(fs, forloop[isgen], base, 0);\n  fixforjump(fs, endfor, prep + 1, 1);\n  luaK_fixline(fs, line);\n}\n\n\nstatic void fornum (LexState *ls, TString *varname, int line) {\n  /* fornum -> NAME = exp,exp[,exp] forbody */\n  FuncState *fs = ls->fs;\n  int base = fs->freereg;\n  new_localvarliteral(ls, \"(for state)\");\n  new_localvarliteral(ls, \"(for state)\");\n  new_varkind(ls, varname, RDKCONST);  /* control variable */\n  checknext(ls, '=');\n  exp1(ls);  /* initial value */\n  checknext(ls, ',');\n  exp1(ls);  /* limit */\n  if (testnext(ls, ','))\n    exp1(ls);  /* optional step */\n  else {  /* default step = 1 */\n    luaK_int(fs, fs->freereg, 1);\n    luaK_reserveregs(fs, 1);\n  }\n  adjustlocalvars(ls, 2);  /* start scope for internal variables */\n  forbody(ls, base, line, 1, 0);\n}\n\n\nstatic void forlist (LexState *ls, TString *indexname) {\n  /* forlist -> NAME {,NAME} IN explist forbody */\n  FuncState *fs = ls->fs;\n  expdesc e;\n  int nvars = 4;  /* function, state, closing, control */\n  int line;\n  int base = fs->freereg;\n  /* create internal variables */\n  new_localvarliteral(ls, \"(for state)\");  /* iterator function */\n  new_localvarliteral(ls, \"(for state)\");  /* state */\n  new_localvarliteral(ls, \"(for state)\");  /* closing var. (after swap) */\n  new_varkind(ls, indexname, RDKCONST);  /* control variable */\n  /* other declared variables */\n  while (testnext(ls, ',')) {\n    new_localvar(ls, str_checkname(ls));\n    nvars++;\n  }\n  checknext(ls, TK_IN);\n  line = ls->linenumber;\n  adjust_assign(ls, 4, explist(ls, &e), &e);\n  adjustlocalvars(ls, 3);  /* start scope for internal variables */\n  marktobeclosed(fs);  /* last internal var. must be closed */\n  luaK_checkstack(fs, 2);  /* extra space to call iterator */\n  forbody(ls, base, line, nvars - 3, 1);\n}\n\n\nstatic void forstat (LexState *ls, int line) {\n  /* forstat -> FOR (fornum | forlist) END */\n  FuncState *fs = ls->fs;\n  TString *varname;\n  BlockCnt bl;\n  enterblock(fs, &bl, 1);  /* scope for loop and control variables */\n  luaX_next(ls);  /* skip 'for' */\n  varname = str_checkname(ls);  /* first variable name */\n  switch (ls->t.token) {\n    case '=': fornum(ls, varname, line); break;\n    case ',': case TK_IN: forlist(ls, varname); break;\n    default: luaX_syntaxerror(ls, \"'=' or 'in' expected\");\n  }\n  check_match(ls, TK_END, TK_FOR, line);\n  leaveblock(fs);  /* loop scope ('break' jumps to this point) */\n}\n\n\nstatic void test_then_block (LexState *ls, int *escapelist) {\n  /* test_then_block -> [IF | ELSEIF] cond THEN block */\n  FuncState *fs = ls->fs;\n  int condtrue;\n  luaX_next(ls);  /* skip IF or ELSEIF */\n  condtrue = cond(ls);  /* read condition */\n  checknext(ls, TK_THEN);\n  block(ls);  /* 'then' part */\n  if (ls->t.token == TK_ELSE ||\n      ls->t.token == TK_ELSEIF)  /* followed by 'else'/'elseif'? */\n    luaK_concat(fs, escapelist, luaK_jump(fs));  /* must jump over it */\n  luaK_patchtohere(fs, condtrue);\n}\n\n\nstatic void ifstat (LexState *ls, int line) {\n  /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */\n  FuncState *fs = ls->fs;\n  int escapelist = NO_JUMP;  /* exit list for finished parts */\n  test_then_block(ls, &escapelist);  /* IF cond THEN block */\n  while (ls->t.token == TK_ELSEIF)\n    test_then_block(ls, &escapelist);  /* ELSEIF cond THEN block */\n  if (testnext(ls, TK_ELSE))\n    block(ls);  /* 'else' part */\n  check_match(ls, TK_END, TK_IF, line);\n  luaK_patchtohere(fs, escapelist);  /* patch escape list to 'if' end */\n}\n\n\nstatic void localfunc (LexState *ls) {\n  expdesc b;\n  FuncState *fs = ls->fs;\n  int fvar = fs->nactvar;  /* function's variable index */\n  new_localvar(ls, str_checkname(ls));  /* new local variable */\n  adjustlocalvars(ls, 1);  /* enter its scope */\n  body(ls, &b, 0, ls->linenumber);  /* function created in next register */\n  /* debug information will only see the variable after this point! */\n  localdebuginfo(fs, fvar)->startpc = fs->pc;\n}\n\n\nstatic lu_byte getvarattribute (LexState *ls, lu_byte df) {\n  /* attrib -> ['<' NAME '>'] */\n  if (testnext(ls, '<')) {\n    TString *ts = str_checkname(ls);\n    const char *attr = getstr(ts);\n    checknext(ls, '>');\n    if (strcmp(attr, \"const\") == 0)\n      return RDKCONST;  /* read-only variable */\n    else if (strcmp(attr, \"close\") == 0)\n      return RDKTOCLOSE;  /* to-be-closed variable */\n    else\n      luaK_semerror(ls, \"unknown attribute '%s'\", attr);\n  }\n  return df;  /* return default value */\n}\n\n\nstatic void checktoclose (FuncState *fs, int level) {\n  if (level != -1) {  /* is there a to-be-closed variable? */\n    marktobeclosed(fs);\n    luaK_codeABC(fs, OP_TBC, reglevel(fs, level), 0, 0);\n  }\n}\n\n\nstatic void localstat (LexState *ls) {\n  /* stat -> LOCAL NAME attrib { ',' NAME attrib } ['=' explist] */\n  FuncState *fs = ls->fs;\n  int toclose = -1;  /* index of to-be-closed variable (if any) */\n  Vardesc *var;  /* last variable */\n  int vidx;  /* index of last variable */\n  int nvars = 0;\n  int nexps;\n  expdesc e;\n  /* get prefixed attribute (if any); default is regular local variable */\n  lu_byte defkind = getvarattribute(ls, VDKREG);\n  do {  /* for each variable */\n    TString *vname = str_checkname(ls);  /* get its name */\n    lu_byte kind = getvarattribute(ls, defkind);  /* postfixed attribute */\n    vidx = new_varkind(ls, vname, kind);  /* predeclare it */\n    if (kind == RDKTOCLOSE) {  /* to-be-closed? */\n      if (toclose != -1)  /* one already present? */\n        luaK_semerror(ls, \"multiple to-be-closed variables in local list\");\n      toclose = fs->nactvar + nvars;\n    }\n    nvars++;\n  } while (testnext(ls, ','));\n  if (testnext(ls, '='))  /* initialization? */\n    nexps = explist(ls, &e);\n  else {\n    e.k = VVOID;\n    nexps = 0;\n  }\n  var = getlocalvardesc(fs, vidx);  /* retrieve last variable */\n  if (nvars == nexps &&  /* no adjustments? */\n      var->vd.kind == RDKCONST &&  /* last variable is const? */\n      luaK_exp2const(fs, &e, &var->k)) {  /* compile-time constant? */\n    var->vd.kind = RDKCTC;  /* variable is a compile-time constant */\n    adjustlocalvars(ls, nvars - 1);  /* exclude last variable */\n    fs->nactvar++;  /* but count it */\n  }\n  else {\n    adjust_assign(ls, nvars, nexps, &e);\n    adjustlocalvars(ls, nvars);\n  }\n  checktoclose(fs, toclose);\n}\n\n\nstatic lu_byte getglobalattribute (LexState *ls, lu_byte df) {\n  lu_byte kind = getvarattribute(ls, df);\n  switch (kind) {\n    case RDKTOCLOSE:\n      luaK_semerror(ls, \"global variables cannot be to-be-closed\");\n      return kind;  /* to avoid warnings */\n    case RDKCONST:\n      return GDKCONST;  /* adjust kind for global variable */\n    default:\n      return kind;\n  }\n}\n\n\nstatic void checkglobal (LexState *ls, TString *varname, int line) {\n  FuncState *fs = ls->fs;\n  expdesc var;\n  int k;\n  buildglobal(ls, varname, &var);  /* create global variable in 'var' */\n  k = var.u.ind.keystr;  /* index of global name in 'k' */\n  luaK_codecheckglobal(fs, &var, k, line);\n}\n\n\n/*\n** Recursively traverse list of globals to be initalized. When\n** going, generate table description for the global. In the end,\n** after all indices have been generated, read list of initializing\n** expressions. When returning, generate the assignment of the value on\n** the stack to the corresponding table description. 'n' is the variable\n** being handled, range [0, nvars - 1].\n*/\nstatic void initglobal (LexState *ls, int nvars, int firstidx, int n,\n                        int line) {\n  if (n == nvars) {  /* traversed all variables? */\n    expdesc e;\n    int nexps = explist(ls, &e);  /* read list of expressions */\n    adjust_assign(ls, nvars, nexps, &e);\n  }\n  else {  /* handle variable 'n' */\n    FuncState *fs = ls->fs;\n    expdesc var;\n    TString *varname = getlocalvardesc(fs, firstidx + n)->vd.name;\n    buildglobal(ls, varname, &var);  /* create global variable in 'var' */\n    enterlevel(ls);  /* control recursion depth */\n    initglobal(ls, nvars, firstidx, n + 1, line);\n    leavelevel(ls);\n    checkglobal(ls, varname, line);\n    storevartop(fs, &var);\n  }\n}\n\n\nstatic void globalnames (LexState *ls, lu_byte defkind) {\n  FuncState *fs = ls->fs;\n  int nvars = 0;\n  int lastidx;  /* index of last registered variable */\n  do {  /* for each name */\n    TString *vname = str_checkname(ls);\n    lu_byte kind = getglobalattribute(ls, defkind);\n    lastidx = new_varkind(ls, vname, kind);\n    nvars++;\n  } while (testnext(ls, ','));\n  if (testnext(ls, '='))  /* initialization? */\n    initglobal(ls, nvars, lastidx - nvars + 1, 0, ls->linenumber);\n  fs->nactvar = cast_short(fs->nactvar + nvars);  /* activate declaration */\n}\n\n\nstatic void globalstat (LexState *ls) {\n  /* globalstat -> (GLOBAL) attrib '*'\n     globalstat -> (GLOBAL) attrib NAME attrib {',' NAME attrib} */\n  FuncState *fs = ls->fs;\n  /* get prefixed attribute (if any); default is regular global variable */\n  lu_byte defkind = getglobalattribute(ls, GDKREG);\n  if (!testnext(ls, '*'))\n    globalnames(ls, defkind);\n  else {\n    /* use NULL as name to represent '*' entries */\n    new_varkind(ls, NULL, defkind);\n    fs->nactvar++;  /* activate declaration */\n  }\n}\n\n\nstatic void globalfunc (LexState *ls, int line) {\n  /* globalfunc -> (GLOBAL FUNCTION) NAME body */\n  expdesc var, b;\n  FuncState *fs = ls->fs;\n  TString *fname = str_checkname(ls);\n  new_varkind(ls, fname, GDKREG);  /* declare global variable */\n  fs->nactvar++;  /* enter its scope */\n  buildglobal(ls, fname, &var);\n  body(ls, &b, 0, ls->linenumber);  /* compile and return closure in 'b' */\n  checkglobal(ls, fname, line);\n  luaK_storevar(fs, &var, &b);\n  luaK_fixline(fs, line);  /* definition \"happens\" in the first line */\n}\n\n\nstatic void globalstatfunc (LexState *ls, int line) {\n  /* stat -> GLOBAL globalfunc | GLOBAL globalstat */\n  luaX_next(ls);  /* skip 'global' */\n  if (testnext(ls, TK_FUNCTION))\n    globalfunc(ls, line);\n  else\n    globalstat(ls);\n}\n\n\nstatic int funcname (LexState *ls, expdesc *v) {\n  /* funcname -> NAME {fieldsel} [':' NAME] */\n  int ismethod = 0;\n  singlevar(ls, v);\n  while (ls->t.token == '.')\n    fieldsel(ls, v);\n  if (ls->t.token == ':') {\n    ismethod = 1;\n    fieldsel(ls, v);\n  }\n  return ismethod;\n}\n\n\nstatic void funcstat (LexState *ls, int line) {\n  /* funcstat -> FUNCTION funcname body */\n  int ismethod;\n  expdesc v, b;\n  luaX_next(ls);  /* skip FUNCTION */\n  ismethod = funcname(ls, &v);\n  check_readonly(ls, &v);\n  body(ls, &b, ismethod, line);\n  luaK_storevar(ls->fs, &v, &b);\n  luaK_fixline(ls->fs, line);  /* definition \"happens\" in the first line */\n}\n\n\nstatic void exprstat (LexState *ls) {\n  /* stat -> func | assignment */\n  FuncState *fs = ls->fs;\n  struct LHS_assign v;\n  suffixedexp(ls, &v.v);\n  if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */\n    v.prev = NULL;\n    restassign(ls, &v, 1);\n  }\n  else {  /* stat -> func */\n    Instruction *inst;\n    check_condition(ls, v.v.k == VCALL, \"syntax error\");\n    inst = &getinstruction(fs, &v.v);\n    SETARG_C(*inst, 1);  /* call statement uses no results */\n  }\n}\n\n\nstatic void retstat (LexState *ls) {\n  /* stat -> RETURN [explist] [';'] */\n  FuncState *fs = ls->fs;\n  expdesc e;\n  int nret;  /* number of values being returned */\n  int first = luaY_nvarstack(fs);  /* first slot to be returned */\n  if (block_follow(ls, 1) || ls->t.token == ';')\n    nret = 0;  /* return no values */\n  else {\n    nret = explist(ls, &e);  /* optional return values */\n    if (hasmultret(e.k)) {\n      luaK_setmultret(fs, &e);\n      if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc) {  /* tail call? */\n        SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);\n        lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs));\n      }\n      nret = LUA_MULTRET;  /* return all values */\n    }\n    else {\n      if (nret == 1)  /* only one single value? */\n        first = luaK_exp2anyreg(fs, &e);  /* can use original slot */\n      else {  /* values must go to the top of the stack */\n        luaK_exp2nextreg(fs, &e);\n        lua_assert(nret == fs->freereg - first);\n      }\n    }\n  }\n  luaK_ret(fs, first, nret);\n  testnext(ls, ';');  /* skip optional semicolon */\n}\n\n\nstatic void statement (LexState *ls) {\n  int line = ls->linenumber;  /* may be needed for error messages */\n  enterlevel(ls);\n  switch (ls->t.token) {\n    case ';': {  /* stat -> ';' (empty statement) */\n      luaX_next(ls);  /* skip ';' */\n      break;\n    }\n    case TK_IF: {  /* stat -> ifstat */\n      ifstat(ls, line);\n      break;\n    }\n    case TK_WHILE: {  /* stat -> whilestat */\n      whilestat(ls, line);\n      break;\n    }\n    case TK_DO: {  /* stat -> DO block END */\n      luaX_next(ls);  /* skip DO */\n      block(ls);\n      check_match(ls, TK_END, TK_DO, line);\n      break;\n    }\n    case TK_FOR: {  /* stat -> forstat */\n      forstat(ls, line);\n      break;\n    }\n    case TK_REPEAT: {  /* stat -> repeatstat */\n      repeatstat(ls, line);\n      break;\n    }\n    case TK_FUNCTION: {  /* stat -> funcstat */\n      funcstat(ls, line);\n      break;\n    }\n    case TK_LOCAL: {  /* stat -> localstat */\n      luaX_next(ls);  /* skip LOCAL */\n      if (testnext(ls, TK_FUNCTION))  /* local function? */\n        localfunc(ls);\n      else\n        localstat(ls);\n      break;\n    }\n    case TK_GLOBAL: {  /* stat -> globalstatfunc */\n      globalstatfunc(ls, line);\n      break;\n    }\n    case TK_DBCOLON: {  /* stat -> label */\n      luaX_next(ls);  /* skip double colon */\n      labelstat(ls, str_checkname(ls), line);\n      break;\n    }\n    case TK_RETURN: {  /* stat -> retstat */\n      luaX_next(ls);  /* skip RETURN */\n      retstat(ls);\n      break;\n    }\n    case TK_BREAK: {  /* stat -> breakstat */\n      breakstat(ls, line);\n      break;\n    }\n    case TK_GOTO: {  /* stat -> 'goto' NAME */\n      luaX_next(ls);  /* skip 'goto' */\n      gotostat(ls, line);\n      break;\n    }\n#if defined(LUA_COMPAT_GLOBAL)\n    case TK_NAME: {\n      /* compatibility code to parse global keyword when \"global\"\n         is not reserved */\n      if (ls->t.seminfo.ts == ls->glbn) {  /* current = \"global\"? */\n        int lk = luaX_lookahead(ls);\n        if (lk == '<' || lk == TK_NAME || lk == '*' || lk == TK_FUNCTION) {\n          /* 'global <attrib>' or 'global name' or 'global *' or\n             'global function' */\n          globalstatfunc(ls, line);\n          break;\n        }\n      }  /* else... */\n    }\n#endif\n    /* FALLTHROUGH */\n    default: {  /* stat -> func | assignment */\n      exprstat(ls);\n      break;\n    }\n  }\n  lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&\n             ls->fs->freereg >= luaY_nvarstack(ls->fs));\n  ls->fs->freereg = luaY_nvarstack(ls->fs);  /* free registers */\n  leavelevel(ls);\n}\n\n/* }====================================================================== */\n\n/* }====================================================================== */\n\n\n/*\n** compiles the main function, which is a regular vararg function with an\n** upvalue named LUA_ENV\n*/\nstatic void mainfunc (LexState *ls, FuncState *fs) {\n  BlockCnt bl;\n  Upvaldesc *env;\n  open_func(ls, fs, &bl);\n  setvararg(fs);  /* main function is always vararg */\n  env = allocupvalue(fs);  /* ...set environment upvalue */\n  env->instack = 1;\n  env->idx = 0;\n  env->kind = VDKREG;\n  env->name = ls->envn;\n  luaC_objbarrier(ls->L, fs->f, env->name);\n  luaX_next(ls);  /* read first token */\n  statlist(ls);  /* parse main body */\n  check(ls, TK_EOS);\n  close_func(ls);\n}\n\n\nLClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,\n                       Dyndata *dyd, const char *name, int firstchar) {\n  LexState lexstate;\n  FuncState funcstate;\n  LClosure *cl = luaF_newLclosure(L, 1);  /* create main closure */\n  setclLvalue2s(L, L->top.p, cl);  /* anchor it (to avoid being collected) */\n  luaD_inctop(L);\n  lexstate.h = luaH_new(L);  /* create table for scanner */\n  sethvalue2s(L, L->top.p, lexstate.h);  /* anchor it */\n  luaD_inctop(L);\n  funcstate.f = cl->p = luaF_newproto(L);\n  luaC_objbarrier(L, cl, cl->p);\n  funcstate.f->source = luaS_new(L, name);  /* create and anchor TString */\n  luaC_objbarrier(L, funcstate.f, funcstate.f->source);\n  lexstate.buff = buff;\n  lexstate.dyd = dyd;\n  dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;\n  luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);\n  mainfunc(&lexstate, &funcstate);\n  lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);\n  /* all scopes should be correctly finished */\n  lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);\n  L->top.p--;  /* remove scanner's table */\n  return cl;  /* closure is on the stack, too */\n}\n\n"
  },
  {
    "path": "3rd/lua/lparser.h",
    "content": "/*\n** $Id: lparser.h $\n** Lua Parser\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lparser_h\n#define lparser_h\n\n#include \"llimits.h\"\n#include \"lobject.h\"\n#include \"lzio.h\"\n\n\n/*\n** Expression and variable descriptor.\n** Code generation for variables and expressions can be delayed to allow\n** optimizations; An 'expdesc' structure describes a potentially-delayed\n** variable/expression. It has a description of its \"main\" value plus a\n** list of conditional jumps that can also produce its value (generated\n** by short-circuit operators 'and'/'or').\n*/\n\n/* kinds of variables/expressions */\ntypedef enum {\n  VVOID,  /* when 'expdesc' describes the last expression of a list,\n             this kind means an empty list (so, no expression) */\n  VNIL,  /* constant nil */\n  VTRUE,  /* constant true */\n  VFALSE,  /* constant false */\n  VK,  /* constant in 'k'; info = index of constant in 'k' */\n  VKFLT,  /* floating constant; nval = numerical float value */\n  VKINT,  /* integer constant; ival = numerical integer value */\n  VKSTR,  /* string constant; strval = TString address;\n             (string is fixed by the scanner) */\n  VNONRELOC,  /* expression has its value in a fixed register;\n                 info = result register */\n  VLOCAL,  /* local variable; var.ridx = register index;\n              var.vidx = relative index in 'actvar.arr'  */\n  VVARGVAR,  /* vararg parameter; var.ridx = register index;\n              var.vidx = relative index in 'actvar.arr'  */\n  VGLOBAL,  /* global variable;\n               info = relative index in 'actvar.arr' (or -1 for\n                      implicit declaration) */\n  VUPVAL,  /* upvalue variable; info = index of upvalue in 'upvalues' */\n  VCONST,  /* compile-time <const> variable;\n              info = absolute index in 'actvar.arr'  */\n  VINDEXED,  /* indexed variable;\n                ind.t = table register;\n                ind.idx = key's R index;\n                ind.ro = true if it represents a read-only global;\n                ind.keystr = if key is a string, index in 'k' of that string;\n                             -1 if key is not a string */\n  VVARGIND,  /* indexed vararg parameter;\n                ind.* as in VINDEXED */\n  VINDEXUP,  /* indexed upvalue;\n                ind.idx = key's K index;\n                ind.* as in VINDEXED */\n  VINDEXI, /* indexed variable with constant integer;\n                ind.t = table register;\n                ind.idx = key's value */\n  VINDEXSTR, /* indexed variable with literal string;\n                ind.idx = key's K index;\n                ind.* as in VINDEXED */\n  VJMP,  /* expression is a test/comparison;\n            info = pc of corresponding jump instruction */\n  VRELOC,  /* expression can put result in any register;\n              info = instruction pc */\n  VCALL,  /* expression is a function call; info = instruction pc */\n  VVARARG  /* vararg expression; info = instruction pc */\n} expkind;\n\n\n#define vkisvar(k)\t(VLOCAL <= (k) && (k) <= VINDEXSTR)\n#define vkisindexed(k)\t(VINDEXED <= (k) && (k) <= VINDEXSTR)\n\n\ntypedef struct expdesc {\n  expkind k;\n  union {\n    lua_Integer ival;    /* for VKINT */\n    lua_Number nval;  /* for VKFLT */\n    TString *strval;  /* for VKSTR */\n    int info;  /* for generic use */\n    struct {  /* for indexed variables */\n      short idx;  /* index (R or \"long\" K) */\n      lu_byte t;  /* table (register or upvalue) */\n      lu_byte ro;  /* true if variable is read-only */\n      int keystr;  /* index in 'k' of string key, or -1 if not a string */\n    } ind;\n    struct {  /* for local variables */\n      lu_byte ridx;  /* register holding the variable */\n      short vidx;  /* index in 'actvar.arr' */\n    } var;\n  } u;\n  int t;  /* patch list of 'exit when true' */\n  int f;  /* patch list of 'exit when false' */\n} expdesc;\n\n\n/* kinds of variables */\n#define VDKREG\t\t0   /* regular local */\n#define RDKCONST\t1   /* local constant */\n#define RDKVAVAR\t2   /* vararg parameter */\n#define RDKTOCLOSE\t3   /* to-be-closed */\n#define RDKCTC\t\t4   /* local compile-time constant */\n#define GDKREG\t\t5   /* regular global */\n#define GDKCONST\t6   /* global constant */\n\n/* variables that live in registers */\n#define varinreg(v)\t((v)->vd.kind <= RDKTOCLOSE)\n\n/* test for global variables */\n#define varglobal(v)\t((v)->vd.kind >= GDKREG)\n\n\n/* description of an active variable */\ntypedef union Vardesc {\n  struct {\n    TValuefields;  /* constant value (if it is a compile-time constant) */\n    lu_byte kind;\n    lu_byte ridx;  /* register holding the variable */\n    short pidx;  /* index of the variable in the Proto's 'locvars' array */\n    TString *name;  /* variable name */\n  } vd;\n  TValue k;  /* constant value (if any) */\n} Vardesc;\n\n\n\n/* description of pending goto statements and label statements */\ntypedef struct Labeldesc {\n  TString *name;  /* label identifier */\n  int pc;  /* position in code */\n  int line;  /* line where it appeared */\n  short nactvar;  /* number of active variables in that position */\n  lu_byte close;  /* true for goto that escapes upvalues */\n} Labeldesc;\n\n\n/* list of labels or gotos */\ntypedef struct Labellist {\n  Labeldesc *arr;  /* array */\n  int n;  /* number of entries in use */\n  int size;  /* array size */\n} Labellist;\n\n\n/* dynamic structures used by the parser */\ntypedef struct Dyndata {\n  struct {  /* list of all active local variables */\n    Vardesc *arr;\n    int n;\n    int size;\n  } actvar;\n  Labellist gt;  /* list of pending gotos */\n  Labellist label;   /* list of active labels */\n} Dyndata;\n\n\n/* control of blocks */\nstruct BlockCnt;  /* defined in lparser.c */\n\n\n/* state needed to generate code for a given function */\ntypedef struct FuncState {\n  Proto *f;  /* current function header */\n  struct FuncState *prev;  /* enclosing function */\n  struct LexState *ls;  /* lexical state */\n  struct BlockCnt *bl;  /* chain of current blocks */\n  Table *kcache;  /* cache for reusing constants */\n  int pc;  /* next position to code (equivalent to 'ncode') */\n  int lasttarget;   /* 'label' of last 'jump label' */\n  int previousline;  /* last line that was saved in 'lineinfo' */\n  int nk;  /* number of elements in 'k' */\n  int np;  /* number of elements in 'p' */\n  int nabslineinfo;  /* number of elements in 'abslineinfo' */\n  int firstlocal;  /* index of first local var (in Dyndata array) */\n  int firstlabel;  /* index of first label (in 'dyd->label->arr') */\n  short ndebugvars;  /* number of elements in 'f->locvars' */\n  short nactvar;  /* number of active variable declarations */\n  lu_byte nups;  /* number of upvalues */\n  lu_byte freereg;  /* first free register */\n  lu_byte iwthabs;  /* instructions issued since last absolute line info */\n  lu_byte needclose;  /* function needs to close upvalues when returning */\n} FuncState;\n\n\nLUAI_FUNC lu_byte luaY_nvarstack (FuncState *fs);\nLUAI_FUNC void luaY_checklimit (FuncState *fs, int v, int l,\n                                const char *what);\nLUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,\n                                 Dyndata *dyd, const char *name, int firstchar);\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lprefix.h",
    "content": "/*\n** $Id: lprefix.h $\n** Definitions for Lua code that must come before any other header file\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lprefix_h\n#define lprefix_h\n\n\n/*\n** Allows POSIX/XSI stuff\n*/\n#if !defined(LUA_USE_C89)\t/* { */\n\n#if !defined(_XOPEN_SOURCE)\n#define _XOPEN_SOURCE           600\n#elif _XOPEN_SOURCE == 0\n#undef _XOPEN_SOURCE  /* use -D_XOPEN_SOURCE=0 to undefine it */\n#endif\n\n/*\n** Allows manipulation of large files in gcc and some other compilers\n*/\n#if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS)\n#define _LARGEFILE_SOURCE       1\n#define _FILE_OFFSET_BITS       64\n#endif\n\n#endif\t\t\t\t/* } */\n\n\n/*\n** Windows stuff\n*/\n#if defined(_WIN32)\t/* { */\n\n#if !defined(_CRT_SECURE_NO_WARNINGS)\n#define _CRT_SECURE_NO_WARNINGS  /* avoid warnings about ISO C functions */\n#endif\n\n#endif\t\t\t/* } */\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/lstate.c",
    "content": "/*\n** $Id: lstate.c $\n** Global State\n** See Copyright Notice in lua.h\n*/\n\n#define lstate_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <stddef.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lapi.h\"\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lfunc.h\"\n#include \"lgc.h\"\n#include \"llex.h\"\n#include \"lmem.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"ltm.h\"\n\n\n\n#define fromstate(L)\t(cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l)))\n\n\n/*\n** these macros allow user-specific actions when a thread is\n** created/deleted\n*/\n#if !defined(luai_userstateopen)\n#define luai_userstateopen(L)\t\t((void)L)\n#endif\n\n#if !defined(luai_userstateclose)\n#define luai_userstateclose(L)\t\t((void)L)\n#endif\n\n#if !defined(luai_userstatethread)\n#define luai_userstatethread(L,L1)\t((void)L)\n#endif\n\n#if !defined(luai_userstatefree)\n#define luai_userstatefree(L,L1)\t((void)L)\n#endif\n\n\n/*\n** set GCdebt to a new value keeping the real number of allocated\n** objects (GCtotalobjs - GCdebt) invariant and avoiding overflows in\n** 'GCtotalobjs'.\n*/\nvoid luaE_setdebt (global_State *g, l_mem debt) {\n  l_mem tb = gettotalbytes(g);\n  lua_assert(tb > 0);\n  if (debt > MAX_LMEM - tb)\n    debt = MAX_LMEM - tb;  /* will make GCtotalbytes == MAX_LMEM */\n  g->GCtotalbytes = tb + debt;\n  g->GCdebt = debt;\n}\n\n\nCallInfo *luaE_extendCI (lua_State *L) {\n  CallInfo *ci;\n  lua_assert(L->ci->next == NULL);\n  ci = luaM_new(L, CallInfo);\n  lua_assert(L->ci->next == NULL);\n  L->ci->next = ci;\n  ci->previous = L->ci;\n  ci->next = NULL;\n  ci->u.l.trap = 0;\n  L->nci++;\n  return ci;\n}\n\n\n/*\n** free all CallInfo structures not in use by a thread\n*/\nstatic void freeCI (lua_State *L) {\n  CallInfo *ci = L->ci;\n  CallInfo *next = ci->next;\n  ci->next = NULL;\n  while ((ci = next) != NULL) {\n    next = ci->next;\n    luaM_free(L, ci);\n    L->nci--;\n  }\n}\n\n\n/*\n** free half of the CallInfo structures not in use by a thread,\n** keeping the first one.\n*/\nvoid luaE_shrinkCI (lua_State *L) {\n  CallInfo *ci = L->ci->next;  /* first free CallInfo */\n  CallInfo *next;\n  if (ci == NULL)\n    return;  /* no extra elements */\n  while ((next = ci->next) != NULL) {  /* two extra elements? */\n    CallInfo *next2 = next->next;  /* next's next */\n    ci->next = next2;  /* remove next from the list */\n    L->nci--;\n    luaM_free(L, next);  /* free next */\n    if (next2 == NULL)\n      break;  /* no more elements */\n    else {\n      next2->previous = ci;\n      ci = next2;  /* continue */\n    }\n  }\n}\n\n\n/*\n** Called when 'getCcalls(L)' larger or equal to LUAI_MAXCCALLS.\n** If equal, raises an overflow error. If value is larger than\n** LUAI_MAXCCALLS (which means it is handling an overflow) but\n** not much larger, does not report an error (to allow overflow\n** handling to work).\n*/\nvoid luaE_checkcstack (lua_State *L) {\n  if (getCcalls(L) == LUAI_MAXCCALLS)\n    luaG_runerror(L, \"C stack overflow\");\n  else if (getCcalls(L) >= (LUAI_MAXCCALLS / 10 * 11))\n    luaD_errerr(L);  /* error while handling stack error */\n}\n\n\nLUAI_FUNC void luaE_incCstack (lua_State *L) {\n  L->nCcalls++;\n  if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS))\n    luaE_checkcstack(L);\n}\n\n\nstatic void resetCI (lua_State *L) {\n  CallInfo *ci = L->ci = &L->base_ci;\n  ci->func.p = L->stack.p;\n  setnilvalue(s2v(ci->func.p));  /* 'function' entry for basic 'ci' */\n  ci->top.p = ci->func.p + 1 + LUA_MINSTACK;  /* +1 for 'function' entry */\n  ci->u.c.k = NULL;\n  ci->callstatus = CIST_C;\n  L->status = LUA_OK;\n  L->errfunc = 0;  /* stack unwind can \"throw away\" the error function */\n}\n\n\nstatic void stack_init (lua_State *L1, lua_State *L) {\n  int i;\n  /* initialize stack array */\n  L1->stack.p = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, StackValue);\n  L1->tbclist.p = L1->stack.p;\n  for (i = 0; i < BASIC_STACK_SIZE + EXTRA_STACK; i++)\n    setnilvalue(s2v(L1->stack.p + i));  /* erase new stack */\n  L1->stack_last.p = L1->stack.p + BASIC_STACK_SIZE;\n  /* initialize first ci */\n  resetCI(L1);\n  L1->top.p = L1->stack.p + 1;  /* +1 for 'function' entry */\n}\n\n\nstatic void freestack (lua_State *L) {\n  if (L->stack.p == NULL)\n    return;  /* stack not completely built yet */\n  L->ci = &L->base_ci;  /* free the entire 'ci' list */\n  freeCI(L);\n  lua_assert(L->nci == 0);\n  /* free stack */\n  luaM_freearray(L, L->stack.p, cast_sizet(stacksize(L) + EXTRA_STACK));\n}\n\n\n/*\n** Create registry table and its predefined values\n*/\nstatic void init_registry (lua_State *L, global_State *g) {\n  /* create registry */\n  TValue aux;\n  Table *registry = luaH_new(L);\n  sethvalue(L, &g->l_registry, registry);\n  luaH_resize(L, registry, LUA_RIDX_LAST, 0);\n  /* registry[1] = false */\n  setbfvalue(&aux);\n  luaH_setint(L, registry, 1, &aux);\n  /* registry[LUA_RIDX_MAINTHREAD] = L */\n  setthvalue(L, &aux, L);\n  luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &aux);\n  /* registry[LUA_RIDX_GLOBALS] = new table (table of globals) */\n  sethvalue(L, &aux, luaH_new(L));\n  luaH_setint(L, registry, LUA_RIDX_GLOBALS, &aux);\n}\n\n\n/*\n** open parts of the state that may cause memory-allocation errors.\n*/\nstatic void f_luaopen (lua_State *L, void *ud) {\n  global_State *g = G(L);\n  UNUSED(ud);\n  stack_init(L, L);  /* init stack */\n  init_registry(L, g);\n  luaS_init(L);\n  luaT_init(L);\n  luaX_init(L);\n  g->gcstp = 0;  /* allow gc */\n  setnilvalue(&g->nilvalue);  /* now state is complete */\n  luai_userstateopen(L);\n}\n\n\n/*\n** preinitialize a thread with consistent values without allocating\n** any memory (to avoid errors)\n*/\nstatic void preinit_thread (lua_State *L, global_State *g) {\n  G(L) = g;\n  L->stack.p = NULL;\n  L->ci = NULL;\n  L->nci = 0;\n  L->twups = L;  /* thread has no upvalues */\n  L->nCcalls = 0;\n  L->errorJmp = NULL;\n  L->hook = NULL;\n  L->hookmask = 0;\n  L->basehookcount = 0;\n  L->allowhook = 1;\n  resethookcount(L);\n  L->openupval = NULL;\n  L->status = LUA_OK;\n  L->errfunc = 0;\n  L->oldpc = 0;\n  L->base_ci.previous = L->base_ci.next = NULL;\n}\n\n\nlu_mem luaE_threadsize (lua_State *L) {\n  lu_mem sz = cast(lu_mem, sizeof(LX))\n            + cast_uint(L->nci) * sizeof(CallInfo);\n  if (L->stack.p != NULL)\n    sz += cast_uint(stacksize(L) + EXTRA_STACK) * sizeof(StackValue);\n  return sz;\n}\n\n\nstatic void close_state (lua_State *L) {\n  global_State *g = G(L);\n  if (!completestate(g))  /* closing a partially built state? */\n    luaC_freeallobjects(L);  /* just collect its objects */\n  else {  /* closing a fully built state */\n    resetCI(L);\n    luaD_closeprotected(L, 1, LUA_OK);  /* close all upvalues */\n    L->top.p = L->stack.p + 1;  /* empty the stack to run finalizers */\n    luaC_freeallobjects(L);  /* collect all objects */\n    luai_userstateclose(L);\n  }\n  luaM_freearray(L, G(L)->strt.hash, cast_sizet(G(L)->strt.size));\n  freestack(L);\n  lua_assert(gettotalbytes(g) == sizeof(global_State));\n  (*g->frealloc)(g->ud, g, sizeof(global_State), 0);  /* free main block */\n}\n\n\nLUA_API lua_State *lua_newthread (lua_State *L) {\n  global_State *g = G(L);\n  GCObject *o;\n  lua_State *L1;\n  lua_lock(L);\n  luaC_checkGC(L);\n  /* create new thread */\n  o = luaC_newobjdt(L, LUA_TTHREAD, sizeof(LX), offsetof(LX, l));\n  L1 = gco2th(o);\n  /* anchor it on L stack */\n  setthvalue2s(L, L->top.p, L1);\n  api_incr_top(L);\n  preinit_thread(L1, g);\n  L1->hookmask = L->hookmask;\n  L1->basehookcount = L->basehookcount;\n  L1->hook = L->hook;\n  resethookcount(L1);\n  /* initialize L1 extra space */\n  memcpy(lua_getextraspace(L1), lua_getextraspace(mainthread(g)),\n         LUA_EXTRASPACE);\n  luai_userstatethread(L, L1);\n  stack_init(L1, L);  /* init stack */\n  lua_unlock(L);\n  return L1;\n}\n\n\nvoid luaE_freethread (lua_State *L, lua_State *L1) {\n  LX *l = fromstate(L1);\n  luaF_closeupval(L1, L1->stack.p);  /* close all upvalues */\n  lua_assert(L1->openupval == NULL);\n  luai_userstatefree(L, L1);\n  freestack(L1);\n  luaM_free(L, l);\n}\n\n\nTStatus luaE_resetthread (lua_State *L, TStatus status) {\n  resetCI(L);\n  if (status == LUA_YIELD)\n    status = LUA_OK;\n  status = luaD_closeprotected(L, 1, status);\n  if (status != LUA_OK)  /* errors? */\n    luaD_seterrorobj(L, status, L->stack.p + 1);\n  else\n    L->top.p = L->stack.p + 1;\n  luaD_reallocstack(L, cast_int(L->ci->top.p - L->stack.p), 0);\n  return status;\n}\n\n\nLUA_API int lua_closethread (lua_State *L, lua_State *from) {\n  TStatus status;\n  lua_lock(L);\n  L->nCcalls = (from) ? getCcalls(from) : 0;\n  status = luaE_resetthread(L, L->status);\n  if (L == from)  /* closing itself? */\n    luaD_throwbaselevel(L, status);\n  lua_unlock(L);\n  return APIstatus(status);\n}\n\n\nLUA_API lua_State *lua_newstate (lua_Alloc f, void *ud, unsigned seed) {\n  int i;\n  lua_State *L;\n  global_State *g = cast(global_State*,\n                       (*f)(ud, NULL, LUA_TTHREAD, sizeof(global_State)));\n  if (g == NULL) return NULL;\n  L = &g->mainth.l;\n  L->tt = LUA_VTHREAD;\n  g->currentwhite = bitmask(WHITE0BIT);\n  L->marked = luaC_white(g);\n  preinit_thread(L, g);\n  g->allgc = obj2gco(L);  /* by now, only object is the main thread */\n  L->next = NULL;\n  incnny(L);  /* main thread is always non yieldable */\n  g->frealloc = f;\n  g->ud = ud;\n  g->warnf = NULL;\n  g->ud_warn = NULL;\n  g->seed = seed;\n  g->gcstp = GCSTPGC;  /* no GC while building state */\n  g->strt.size = g->strt.nuse = 0;\n  g->strt.hash = NULL;\n  setnilvalue(&g->l_registry);\n  g->panic = NULL;\n  g->gcstate = GCSpause;\n  g->gckind = KGC_INC;\n  g->gcstopem = 0;\n  g->gcemergency = 0;\n  g->finobj = g->tobefnz = g->fixedgc = NULL;\n  g->firstold1 = g->survival = g->old1 = g->reallyold = NULL;\n  g->finobjsur = g->finobjold1 = g->finobjrold = NULL;\n  g->sweepgc = NULL;\n  g->gray = g->grayagain = NULL;\n  g->weak = g->ephemeron = g->allweak = NULL;\n  g->twups = NULL;\n  g->GCtotalbytes = sizeof(global_State);\n  g->GCmarked = 0;\n  g->GCdebt = 0;\n  setivalue(&g->nilvalue, 0);  /* to signal that state is not yet built */\n  setgcparam(g, PAUSE, LUAI_GCPAUSE);\n  setgcparam(g, STEPMUL, LUAI_GCMUL);\n  setgcparam(g, STEPSIZE, LUAI_GCSTEPSIZE);\n  setgcparam(g, MINORMUL, LUAI_GENMINORMUL);\n  setgcparam(g, MINORMAJOR, LUAI_MINORMAJOR);\n  setgcparam(g, MAJORMINOR, LUAI_MAJORMINOR);\n  for (i=0; i < LUA_NUMTYPES; i++) g->mt[i] = NULL;\n  if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {\n    /* memory allocation error: free partial state */\n    close_state(L);\n    L = NULL;\n  }\n  return L;\n}\n\n\nLUA_API void lua_close (lua_State *L) {\n  lua_lock(L);\n  L = mainthread(G(L));  /* only the main thread can be closed */\n  close_state(L);\n}\n\n\nvoid luaE_warning (lua_State *L, const char *msg, int tocont) {\n  lua_WarnFunction wf = G(L)->warnf;\n  if (wf != NULL)\n    wf(G(L)->ud_warn, msg, tocont);\n}\n\n\n/*\n** Generate a warning from an error message\n*/\nvoid luaE_warnerror (lua_State *L, const char *where) {\n  TValue *errobj = s2v(L->top.p - 1);  /* error object */\n  const char *msg = (ttisstring(errobj))\n                  ? getstr(tsvalue(errobj))\n                  : \"error object is not a string\";\n  /* produce warning \"error in %s (%s)\" (where, msg) */\n  luaE_warning(L, \"error in \", 1);\n  luaE_warning(L, where, 1);\n  luaE_warning(L, \" (\", 1);\n  luaE_warning(L, msg, 1);\n  luaE_warning(L, \")\", 0);\n}\n\n"
  },
  {
    "path": "3rd/lua/lstate.h",
    "content": "/*\n** $Id: lstate.h $\n** Global State\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lstate_h\n#define lstate_h\n\n#include \"lua.h\"\n\n\n/* Some header files included here need this definition */\ntypedef struct CallInfo CallInfo;\n\n\n#include \"lobject.h\"\n#include \"ltm.h\"\n#include \"lzio.h\"\n\n\n/*\n** Some notes about garbage-collected objects: All objects in Lua must\n** be kept somehow accessible until being freed, so all objects always\n** belong to one (and only one) of these lists, using field 'next' of\n** the 'CommonHeader' for the link:\n**\n** 'allgc': all objects not marked for finalization;\n** 'finobj': all objects marked for finalization;\n** 'tobefnz': all objects ready to be finalized;\n** 'fixedgc': all objects that are not to be collected (currently\n** only small strings, such as reserved words).\n**\n** For the generational collector, some of these lists have marks for\n** generations. Each mark points to the first element in the list for\n** that particular generation; that generation goes until the next mark.\n**\n** 'allgc' -> 'survival': new objects;\n** 'survival' -> 'old': objects that survived one collection;\n** 'old1' -> 'reallyold': objects that became old in last collection;\n** 'reallyold' -> NULL: objects old for more than one cycle.\n**\n** 'finobj' -> 'finobjsur': new objects marked for finalization;\n** 'finobjsur' -> 'finobjold1': survived   \"\"\"\";\n** 'finobjold1' -> 'finobjrold': just old  \"\"\"\";\n** 'finobjrold' -> NULL: really old       \"\"\"\".\n**\n** All lists can contain elements older than their main ages, due\n** to 'luaC_checkfinalizer' and 'udata2finalize', which move\n** objects between the normal lists and the \"marked for finalization\"\n** lists. Moreover, barriers can age young objects in young lists as\n** OLD0, which then become OLD1. However, a list never contains\n** elements younger than their main ages.\n**\n** The generational collector also uses a pointer 'firstold1', which\n** points to the first OLD1 object in the list. It is used to optimize\n** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc'\n** and 'reallyold', but often the list has no OLD1 objects or they are\n** after 'old1'.) Note the difference between it and 'old1':\n** 'firstold1': no OLD1 objects before this point; there can be all\n**   ages after it.\n** 'old1': no objects younger than OLD1 after this point.\n*/\n\n/*\n** Moreover, there is another set of lists that control gray objects.\n** These lists are linked by fields 'gclist'. (All objects that\n** can become gray have such a field. The field is not the same\n** in all objects, but it always has this name.)  Any gray object\n** must belong to one of these lists, and all objects in these lists\n** must be gray (with two exceptions explained below):\n**\n** 'gray': regular gray objects, still waiting to be visited.\n** 'grayagain': objects that must be revisited at the atomic phase.\n**   That includes\n**   - black objects got in a write barrier;\n**   - all kinds of weak tables during propagation phase;\n**   - all threads.\n** 'weak': tables with weak values to be cleared;\n** 'ephemeron': ephemeron tables with white->white entries;\n** 'allweak': tables with weak keys and/or weak values to be cleared.\n**\n** The exceptions to that \"gray rule\" are:\n** - TOUCHED2 objects in generational mode stay in a gray list (because\n** they must be visited again at the end of the cycle), but they are\n** marked black because assignments to them must activate barriers (to\n** move them back to TOUCHED1).\n** - Open upvalues are kept gray to avoid barriers, but they stay out\n** of gray lists. (They don't even have a 'gclist' field.)\n*/\n\n\n\n/*\n** About 'nCcalls':  This count has two parts: the lower 16 bits counts\n** the number of recursive invocations in the C stack; the higher\n** 16 bits counts the number of non-yieldable calls in the stack.\n** (They are together so that we can change and save both with one\n** instruction.)\n*/\n\n\n/* true if this thread does not have non-yieldable calls in the stack */\n#define yieldable(L)\t\t(((L)->nCcalls & 0xffff0000) == 0)\n\n/* real number of C calls */\n#define getCcalls(L)\t((L)->nCcalls & 0xffff)\n\n\n/* Increment the number of non-yieldable calls */\n#define incnny(L)\t((L)->nCcalls += 0x10000)\n\n/* Decrement the number of non-yieldable calls */\n#define decnny(L)\t((L)->nCcalls -= 0x10000)\n\n/* Non-yieldable call increment */\n#define nyci\t(0x10000 | 1)\n\n\n\n\nstruct lua_longjmp;  /* defined in ldo.c */\n\n\n/*\n** Atomic type (relative to signals) to better ensure that 'lua_sethook'\n** is thread safe\n*/\n#if !defined(l_signalT)\n#include <signal.h>\n#define l_signalT\tsig_atomic_t\n#endif\n\n\n/*\n** Extra stack space to handle TM calls and some other extras. This\n** space is not included in 'stack_last'. It is used only to avoid stack\n** checks, either because the element will be promptly popped or because\n** there will be a stack check soon after the push. Function frames\n** never use this extra space, so it does not need to be kept clean.\n*/\n#define EXTRA_STACK   5\n\n\n/*\n** Size of cache for strings in the API. 'N' is the number of\n** sets (better be a prime) and \"M\" is the size of each set.\n** (M == 1 makes a direct cache.)\n*/\n#if !defined(STRCACHE_N)\n#define STRCACHE_N              53\n#define STRCACHE_M              2\n#endif\n\n\n#define BASIC_STACK_SIZE        (2*LUA_MINSTACK)\n\n#define stacksize(th)\tcast_int((th)->stack_last.p - (th)->stack.p)\n\n\n/* kinds of Garbage Collection */\n#define KGC_INC\t\t0\t/* incremental gc */\n#define KGC_GENMINOR\t1\t/* generational gc in minor (regular) mode */\n#define KGC_GENMAJOR\t2\t/* generational in major mode */\n\n\ntypedef struct stringtable {\n  TString **hash;  /* array of buckets (linked lists of strings) */\n  int nuse;  /* number of elements */\n  int size;  /* number of buckets */\n} stringtable;\n\n\n/*\n** Information about a call.\n** About union 'u':\n** - field 'l' is used only for Lua functions;\n** - field 'c' is used only for C functions.\n** About union 'u2':\n** - field 'funcidx' is used only by C functions while doing a\n** protected call;\n** - field 'nyield' is used only while a function is \"doing\" an\n** yield (from the yield until the next resume);\n** - field 'nres' is used only while closing tbc variables when\n** returning from a function;\n*/\nstruct CallInfo {\n  StkIdRel func;  /* function index in the stack */\n  StkIdRel top;  /* top for this function */\n  struct CallInfo *previous, *next;  /* dynamic call link */\n  union {\n    struct {  /* only for Lua functions */\n      const Instruction *savedpc;\n      volatile l_signalT trap;  /* function is tracing lines/counts */\n      int nextraargs;  /* # of extra arguments in vararg functions */\n    } l;\n    struct {  /* only for C functions */\n      lua_KFunction k;  /* continuation in case of yields */\n      ptrdiff_t old_errfunc;\n      lua_KContext ctx;  /* context info. in case of yields */\n    } c;\n  } u;\n  union {\n    int funcidx;  /* called-function index */\n    int nyield;  /* number of values yielded */\n    int nres;  /* number of values returned */\n  } u2;\n  l_uint32 callstatus;\n};\n\n\n/*\n** Maximum expected number of results from a function\n** (must fit in CIST_NRESULTS).\n*/\n#define MAXRESULTS\t250\n\n\n/*\n** Bits in CallInfo status\n*/\n/* bits 0-7 are the expected number of results from this function + 1 */\n#define CIST_NRESULTS\t0xffu\n\n/* bits 8-11 count call metamethods (and their extra arguments) */\n#define CIST_CCMT\t8  /* the offset, not the mask */\n#define MAX_CCMT\t(0xfu << CIST_CCMT)\n\n/* Bits 12-14 are used for CIST_RECST (see below) */\n#define CIST_RECST\t12  /* the offset, not the mask */\n\n/* call is running a C function (still in first 16 bits) */\n#define CIST_C\t\t(1u << (CIST_RECST + 3))\n/* call is on a fresh \"luaV_execute\" frame */\n#define CIST_FRESH\t(cast(l_uint32, CIST_C) << 1)\n/* function is closing tbc variables */\n#define CIST_CLSRET\t(CIST_FRESH << 1)\n/* function has tbc variables to close */\n#define CIST_TBC\t(CIST_CLSRET << 1)\n/* original value of 'allowhook' */\n#define CIST_OAH\t(CIST_TBC << 1)\n/* call is running a debug hook */\n#define CIST_HOOKED\t(CIST_OAH << 1)\n/* doing a yieldable protected call */\n#define CIST_YPCALL\t(CIST_HOOKED << 1)\n/* call was tail called */\n#define CIST_TAIL\t(CIST_YPCALL << 1)\n/* last hook called yielded */\n#define CIST_HOOKYIELD\t(CIST_TAIL << 1)\n/* function \"called\" a finalizer */\n#define CIST_FIN\t(CIST_HOOKYIELD << 1)\n\n\n#define get_nresults(cs)  (cast_int((cs) & CIST_NRESULTS) - 1)\n\n/*\n** Field CIST_RECST stores the \"recover status\", used to keep the error\n** status while closing to-be-closed variables in coroutines, so that\n** Lua can correctly resume after an yield from a __close method called\n** because of an error.  (Three bits are enough for error status.)\n*/\n#define getcistrecst(ci)     (((ci)->callstatus >> CIST_RECST) & 7)\n#define setcistrecst(ci,st)  \\\n  check_exp(((st) & 7) == (st),   /* status must fit in three bits */  \\\n            ((ci)->callstatus = ((ci)->callstatus & ~(7u << CIST_RECST))  \\\n                                | (cast(l_uint32, st) << CIST_RECST)))\n\n\n/* active function is a Lua function */\n#define isLua(ci)\t(!((ci)->callstatus & CIST_C))\n\n/* call is running Lua code (not a hook) */\n#define isLuacode(ci)\t(!((ci)->callstatus & (CIST_C | CIST_HOOKED)))\n\n\n#define setoah(ci,v)  \\\n  ((ci)->callstatus = ((v) ? (ci)->callstatus | CIST_OAH  \\\n                           : (ci)->callstatus & ~CIST_OAH))\n#define getoah(ci)  (((ci)->callstatus & CIST_OAH) ? 1 : 0)\n\n\n/*\n** 'per thread' state\n*/\nstruct lua_State {\n  CommonHeader;\n  lu_byte allowhook;\n  TStatus status;\n  StkIdRel top;  /* first free slot in the stack */\n  struct global_State *l_G;\n  CallInfo *ci;  /* call info for current function */\n  StkIdRel stack_last;  /* end of stack (last element + 1) */\n  StkIdRel stack;  /* stack base */\n  UpVal *openupval;  /* list of open upvalues in this stack */\n  StkIdRel tbclist;  /* list of to-be-closed variables */\n  GCObject *gclist;\n  struct lua_State *twups;  /* list of threads with open upvalues */\n  struct lua_longjmp *errorJmp;  /* current error recover point */\n  CallInfo base_ci;  /* CallInfo for first level (C host) */\n  volatile lua_Hook hook;\n  ptrdiff_t errfunc;  /* current error handling function (stack index) */\n  l_uint32 nCcalls;  /* number of nested non-yieldable or C calls */\n  int oldpc;  /* last pc traced */\n  int nci;  /* number of items in 'ci' list */\n  int basehookcount;\n  int hookcount;\n  volatile l_signalT hookmask;\n  struct {  /* info about transferred values (for call/return hooks) */\n    int ftransfer;  /* offset of first value transferred */\n    int ntransfer;  /* number of values transferred */\n  } transferinfo;\n};\n\n\n/*\n** thread state + extra space\n*/\ntypedef struct LX {\n  lu_byte extra_[LUA_EXTRASPACE];\n  lua_State l;\n} LX;\n\n\n/*\n** 'global state', shared by all threads of this state\n*/\ntypedef struct global_State {\n  lua_Alloc frealloc;  /* function to reallocate memory */\n  void *ud;         /* auxiliary data to 'frealloc' */\n  l_mem GCtotalbytes;  /* number of bytes currently allocated + debt */\n  l_mem GCdebt;  /* bytes counted but not yet allocated */\n  l_mem GCmarked;  /* number of objects marked in a GC cycle */\n  l_mem GCmajorminor;  /* auxiliary counter to control major-minor shifts */\n  stringtable strt;  /* hash table for strings */\n  TValue l_registry;\n  TValue nilvalue;  /* a nil value */\n  unsigned int seed;  /* randomized seed for hashes */\n  lu_byte gcparams[LUA_GCPN];\n  lu_byte currentwhite;\n  lu_byte gcstate;  /* state of garbage collector */\n  lu_byte gckind;  /* kind of GC running */\n  lu_byte gcstopem;  /* stops emergency collections */\n  lu_byte gcstp;  /* control whether GC is running */\n  lu_byte gcemergency;  /* true if this is an emergency collection */\n  GCObject *allgc;  /* list of all collectable objects */\n  GCObject **sweepgc;  /* current position of sweep in list */\n  GCObject *finobj;  /* list of collectable objects with finalizers */\n  GCObject *gray;  /* list of gray objects */\n  GCObject *grayagain;  /* list of objects to be traversed atomically */\n  GCObject *weak;  /* list of tables with weak values */\n  GCObject *ephemeron;  /* list of ephemeron tables (weak keys) */\n  GCObject *allweak;  /* list of all-weak tables */\n  GCObject *tobefnz;  /* list of userdata to be GC */\n  GCObject *fixedgc;  /* list of objects not to be collected */\n  /* fields for generational collector */\n  GCObject *survival;  /* start of objects that survived one GC cycle */\n  GCObject *old1;  /* start of old1 objects */\n  GCObject *reallyold;  /* objects more than one cycle old (\"really old\") */\n  GCObject *firstold1;  /* first OLD1 object in the list (if any) */\n  GCObject *finobjsur;  /* list of survival objects with finalizers */\n  GCObject *finobjold1;  /* list of old1 objects with finalizers */\n  GCObject *finobjrold;  /* list of really old objects with finalizers */\n  struct lua_State *twups;  /* list of threads with open upvalues */\n  lua_CFunction panic;  /* to be called in unprotected errors */\n  TString *memerrmsg;  /* message for memory-allocation errors */\n  TString *tmname[TM_N];  /* array with tag-method names */\n  struct Table *mt[LUA_NUMTYPES];  /* metatables for basic types */\n  TString *strcache[STRCACHE_N][STRCACHE_M];  /* cache for strings in API */\n  lua_WarnFunction warnf;  /* warning function */\n  void *ud_warn;         /* auxiliary data to 'warnf' */\n  LX mainth;  /* main thread of this state */\n} global_State;\n\n\n#define G(L)\t(L->l_G)\n#define mainthread(G)\t(&(G)->mainth.l)\n\n/*\n** 'g->nilvalue' being a nil value flags that the state was completely\n** build.\n*/\n#define completestate(g)\tttisnil(&g->nilvalue)\n\n\n/*\n** Union of all collectable objects (only for conversions)\n** ISO C99, 6.5.2.3 p.5:\n** \"if a union contains several structures that share a common initial\n** sequence [...], and if the union object currently contains one\n** of these structures, it is permitted to inspect the common initial\n** part of any of them anywhere that a declaration of the complete type\n** of the union is visible.\"\n*/\nunion GCUnion {\n  GCObject gc;  /* common header */\n  struct TString ts;\n  struct Udata u;\n  union Closure cl;\n  struct Table h;\n  struct Proto p;\n  struct lua_State th;  /* thread */\n  struct UpVal upv;\n};\n\n\n/*\n** ISO C99, 6.7.2.1 p.14:\n** \"A pointer to a union object, suitably converted, points to each of\n** its members [...], and vice versa.\"\n*/\n#define cast_u(o)\tcast(union GCUnion *, (o))\n\n/* macros to convert a GCObject into a specific value */\n#define gco2ts(o)  \\\n\tcheck_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))\n#define gco2u(o)  check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))\n#define gco2lcl(o)  check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))\n#define gco2ccl(o)  check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))\n#define gco2cl(o)  \\\n\tcheck_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))\n#define gco2t(o)  check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))\n#define gco2p(o)  check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))\n#define gco2th(o)  check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))\n#define gco2upv(o)\tcheck_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))\n\n\n/*\n** macro to convert a Lua object into a GCObject\n*/\n#define obj2gco(v)  \\\n\tcheck_exp(novariant((v)->tt) >= LUA_TSTRING, &(cast_u(v)->gc))\n\n\n/* actual number of total memory allocated */\n#define gettotalbytes(g)\t((g)->GCtotalbytes - (g)->GCdebt)\n\n\nLUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);\nLUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);\nLUAI_FUNC lu_mem luaE_threadsize (lua_State *L);\nLUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);\nLUAI_FUNC void luaE_shrinkCI (lua_State *L);\nLUAI_FUNC void luaE_checkcstack (lua_State *L);\nLUAI_FUNC void luaE_incCstack (lua_State *L);\nLUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);\nLUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);\nLUAI_FUNC TStatus luaE_resetthread (lua_State *L, TStatus status);\n\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/lstring.c",
    "content": "/*\n** $Id: lstring.c $\n** String table (keeps all strings handled by Lua)\n** See Copyright Notice in lua.h\n*/\n\n#define lstring_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"atomic.h\"\n\nstatic ATOM_SIZET STRID = 0;\n\n/*\n** Maximum size for string table.\n*/\n#define MAXSTRTB\tcast_int(luaM_limitN(INT_MAX, TString*))\n\n/*\n** Initial size for the string table (must be power of 2).\n** The Lua core alone registers ~50 strings (reserved words +\n** metaevent keys + a few others). Libraries would typically add\n** a few dozens more.\n*/\n#if !defined(MINSTRTABSIZE)\n#define MINSTRTABSIZE   128\n#endif\n\n\n/*\n** generic equality for strings\n*/\nint luaS_eqstr (TString *a, TString *b) {\n  size_t len1, len2;\n  const char *s1 = getlstr(a, len1);\n  const char *s2 = getlstr(b, len2);\n  return ((len1 == len2) &&  /* equal length and ... */\n          (memcmp(s1, s2, len1) == 0));  /* equal contents */\n}\n\nint luaS_eqshrstr (TString *a, TString *b) {\n  int r;\n  ls_byte len = a->shrlen;\n  r = len == b->shrlen && (memcmp(getshrstr(a), getshrstr(b), len) == 0);\n  if (r) {\n    if (a->id < b->id) {\n      a->id = b->id;\n    } else {\n      b->id = a->id;\n    }\n  }\n  return r;\n}\n\nvoid luaS_share (TString *ts) {\n  if (ts == NULL || isshared(ts))\n    return;\n  if (ts->tt == LUA_VLNGSTR)\n    luaS_hashlongstr(ts);\n  makeshared(ts);\n  ts->id = ATOM_FDEC(&STRID)-1;\n}\n\nstatic unsigned luaS_hash (const char *str, size_t l, unsigned seed) {\n  unsigned int h = seed ^ cast_uint(l);\n  for (; l > 0; l--)\n    h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1]));\n  return h;\n}\n\n\nunsigned luaS_hashlongstr (TString *ts) {\n  lua_assert(ts->tt == LUA_VLNGSTR);\n  if (ts->extra == 0) {  /* no hash? */\n    size_t len = ts->u.lnglen;\n    ts->hash = luaS_hash(getlngstr(ts), len, ts->hash);\n    ts->extra = 1;  /* now it has its hash */\n  }\n  return ts->hash;\n}\n\n\nstatic void tablerehash (TString **vect, int osize, int nsize) {\n  int i;\n  for (i = osize; i < nsize; i++)  /* clear new elements */\n    vect[i] = NULL;\n  for (i = 0; i < osize; i++) {  /* rehash old part of the array */\n    TString *p = vect[i];\n    vect[i] = NULL;\n    while (p) {  /* for each string in the list */\n      TString *hnext = p->u.hnext;  /* save next */\n      unsigned int h = lmod(p->hash, nsize);  /* new position */\n      p->u.hnext = vect[h];  /* chain it into array */\n      vect[h] = p;\n      p = hnext;\n    }\n  }\n}\n\n\n/*\n** Resize the string table. If allocation fails, keep the current size.\n** (This can degrade performance, but any non-zero size should work\n** correctly.)\n*/\nvoid luaS_resize (lua_State *L, int nsize) {\n  stringtable *tb = &G(L)->strt;\n  int osize = tb->size;\n  TString **newvect;\n  if (nsize < osize)  /* shrinking table? */\n    tablerehash(tb->hash, osize, nsize);  /* depopulate shrinking part */\n  newvect = luaM_reallocvector(L, tb->hash, osize, nsize, TString*);\n  if (l_unlikely(newvect == NULL)) {  /* reallocation failed? */\n    if (nsize < osize)  /* was it shrinking table? */\n      tablerehash(tb->hash, nsize, osize);  /* restore to original size */\n    /* leave table as it was */\n  }\n  else {  /* allocation succeeded */\n    tb->hash = newvect;\n    tb->size = nsize;\n    if (nsize > osize)\n      tablerehash(newvect, osize, nsize);  /* rehash for new size */\n  }\n}\n\n\n/*\n** Clear API string cache. (Entries cannot be empty, so fill them with\n** a non-collectable string.)\n*/\nvoid luaS_clearcache (global_State *g) {\n  int i, j;\n  for (i = 0; i < STRCACHE_N; i++)\n    for (j = 0; j < STRCACHE_M; j++) {\n      if (iswhite(g->strcache[i][j]))  /* will entry be collected? */\n        g->strcache[i][j] = g->memerrmsg;  /* replace it with something fixed */\n    }\n}\n\n\n/*\n** Initialize the string table and the string cache\n*/\nvoid luaS_init (lua_State *L) {\n  global_State *g = G(L);\n  int i, j;\n  stringtable *tb = &G(L)->strt;\n  tb->hash = luaM_newvector(L, MINSTRTABSIZE, TString*);\n  tablerehash(tb->hash, 0, MINSTRTABSIZE);  /* clear array */\n  tb->size = MINSTRTABSIZE;\n  /* pre-create memory-error message */\n  g->memerrmsg = luaS_newliteral(L, MEMERRMSG);\n  luaC_fix(L, obj2gco(g->memerrmsg));  /* it should never be collected */\n  for (i = 0; i < STRCACHE_N; i++)  /* fill cache with valid strings */\n    for (j = 0; j < STRCACHE_M; j++)\n      g->strcache[i][j] = g->memerrmsg;\n}\n\n\nsize_t luaS_sizelngstr (size_t len, int kind) {\n  switch (kind) {\n    case LSTRREG:  /* regular long string */\n      /* don't need 'falloc'/'ud', but need space for content */\n      return offsetof(TString, falloc) + (len + 1) * sizeof(char);\n    case LSTRFIX:  /* fixed external long string */\n      /* don't need 'falloc'/'ud' */\n      return offsetof(TString, falloc);\n    default:  /* external long string with deallocation */\n      lua_assert(kind == LSTRMEM);\n      return sizeof(TString);\n  }\n}\n\n\n/*\n** creates a new string object\n*/\nstatic TString *createstrobj (lua_State *L, size_t totalsize, lu_byte tag,\n                              unsigned h) {\n  TString *ts;\n  GCObject *o;\n  o = luaC_newobj(L, tag, totalsize);\n  ts = gco2ts(o);\n  ts->hash = h;\n  ts->extra = 0;\n  ts->id = 0;\n  return ts;\n}\n\n\nTString *luaS_createlngstrobj (lua_State *L, size_t l) {\n  size_t totalsize = luaS_sizelngstr(l, LSTRREG);\n  TString *ts = createstrobj(L, totalsize, LUA_VLNGSTR, G(L)->seed);\n  ts->u.lnglen = l;\n  ts->shrlen = LSTRREG;  /* signals that it is a regular long string */\n  ts->contents = cast_charp(ts) + offsetof(TString, falloc);\n  ts->contents[l] = '\\0';  /* ending 0 */\n  return ts;\n}\n\n\nvoid luaS_remove (lua_State *L, TString *ts) {\n  stringtable *tb = &G(L)->strt;\n  TString **p = &tb->hash[lmod(ts->hash, tb->size)];\n  while (*p != ts)  /* find previous element */\n    p = &(*p)->u.hnext;\n  *p = (*p)->u.hnext;  /* remove element from its list */\n  tb->nuse--;\n}\n\n\nstatic void growstrtab (lua_State *L, stringtable *tb) {\n  if (l_unlikely(tb->nuse == INT_MAX)) {  /* too many strings? */\n    luaC_fullgc(L, 1);  /* try to free some... */\n    if (tb->nuse == INT_MAX)  /* still too many? */\n      luaM_error(L);  /* cannot even create a message... */\n  }\n  if (tb->size <= MAXSTRTB / 2)  /* can grow string table? */\n    luaS_resize(L, tb->size * 2);\n}\n\n\n/*\n** Checks whether short string exists and reuses it or creates a new one.\n*/\nstatic TString *internshrstr (lua_State *L, const char *str, size_t l) {\n  TString *ts;\n  global_State *g = G(L);\n  stringtable *tb = &g->strt;\n  unsigned int h = luaS_hash(str, l, g->seed);\n  TString **list = &tb->hash[lmod(h, tb->size)];\n  lua_assert(str != NULL);  /* otherwise 'memcmp'/'memcpy' are undefined */\n  for (ts = *list; ts != NULL; ts = ts->u.hnext) {\n    if (l == cast_uint(ts->shrlen) &&\n        (memcmp(str, getshrstr(ts), l * sizeof(char)) == 0)) {\n      /* found! */\n      if (isdead(g, ts))  /* dead (but not collected yet)? */\n        changewhite(ts);  /* resurrect it */\n      return ts;\n    }\n  }\n  /* else must create a new string */\n  if (tb->nuse >= tb->size) {  /* need to grow string table? */\n    growstrtab(L, tb);\n    list = &tb->hash[lmod(h, tb->size)];  /* rehash with new size */\n  }\n  ts = createstrobj(L, sizestrshr(l), LUA_VSHRSTR, h);\n  ts->shrlen = cast(ls_byte, l);\n  getshrstr(ts)[l] = '\\0';  /* ending 0 */\n  memcpy(getshrstr(ts), str, l * sizeof(char));\n  ts->u.hnext = *list;\n  *list = ts;\n  tb->nuse++;\n  return ts;\n}\n\n\n/*\n** new string (with explicit length)\n*/\nTString *luaS_newlstr (lua_State *L, const char *str, size_t l) {\n  if (l <= LUAI_MAXSHORTLEN)  /* short string? */\n    return internshrstr(L, str, l);\n  else {\n    TString *ts;\n    if (l_unlikely(l * sizeof(char) >= (MAX_SIZE - sizeof(TString))))\n      luaM_toobig(L);\n    ts = luaS_createlngstrobj(L, l);\n    memcpy(getlngstr(ts), str, l * sizeof(char));\n    return ts;\n  }\n}\n\n\n/*\n** Create or reuse a zero-terminated string, first checking in the\n** cache (using the string address as a key). The cache can contain\n** only zero-terminated strings, so it is safe to use 'strcmp' to\n** check hits.\n*/\nTString *luaS_new (lua_State *L, const char *str) {\n  unsigned int i = point2uint(str) % STRCACHE_N;  /* hash */\n  int j;\n  TString **p = G(L)->strcache[i];\n  for (j = 0; j < STRCACHE_M; j++) {\n    if (strcmp(str, getstr(p[j])) == 0)  /* hit? */\n      return p[j];  /* that is it */\n  }\n  /* normal route */\n  for (j = STRCACHE_M - 1; j > 0; j--)\n    p[j] = p[j - 1];  /* move out last element */\n  /* new element is first in the list */\n  p[0] = luaS_newlstr(L, str, strlen(str));\n  return p[0];\n}\n\n\nUdata *luaS_newudata (lua_State *L, size_t s, unsigned short nuvalue) {\n  Udata *u;\n  int i;\n  GCObject *o;\n  if (l_unlikely(s > MAX_SIZE - udatamemoffset(nuvalue)))\n    luaM_toobig(L);\n  o = luaC_newobj(L, LUA_VUSERDATA, sizeudata(nuvalue, s));\n  u = gco2u(o);\n  u->len = s;\n  u->nuvalue = nuvalue;\n  u->metatable = NULL;\n  for (i = 0; i < nuvalue; i++)\n    setnilvalue(&u->uv[i].uv);\n  return u;\n}\n\n\nstruct NewExt {\n  ls_byte kind;\n  const char *s;\n   size_t len;\n  TString *ts;  /* output */\n};\n\n\nstatic void f_newext (lua_State *L, void *ud) {\n  struct NewExt *ne = cast(struct NewExt *, ud);\n  size_t size = luaS_sizelngstr(0, ne->kind);\n  ne->ts = createstrobj(L, size, LUA_VLNGSTR, G(L)->seed);\n}\n\n\nTString *luaS_newextlstr (lua_State *L,\n\t          const char *s, size_t len, lua_Alloc falloc, void *ud) {\n  struct NewExt ne;\n  if (!falloc) {\n    ne.kind = LSTRFIX;\n    f_newext(L, &ne);  /* just create header */\n  }\n  else {\n    ne.kind = LSTRMEM;\n    if (luaD_rawrunprotected(L, f_newext, &ne) != LUA_OK) {  /* mem. error? */\n      (*falloc)(ud, cast_voidp(s), len + 1, 0);  /* free external string */\n      luaM_error(L);  /* re-raise memory error */\n    }\n    ne.ts->falloc = falloc;\n    ne.ts->ud = ud;\n  }\n  ne.ts->shrlen = ne.kind;\n  ne.ts->u.lnglen = len;\n  ne.ts->contents = cast_charp(s);\n  return ne.ts;\n}\n\n\n/*\n** Normalize an external string: If it is short, internalize it.\n*/\nTString *luaS_normstr (lua_State *L, TString *ts) {\n  size_t len = ts->u.lnglen;\n  if (len > LUAI_MAXSHORTLEN)\n    return ts;  /* long string; keep the original */\n  else {\n    const char *str = getlngstr(ts);\n    return internshrstr(L, str, len);\n  }\n}\n\n"
  },
  {
    "path": "3rd/lua/lstring.h",
    "content": "/*\n** $Id: lstring.h $\n** String table (keep all strings handled by Lua)\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lstring_h\n#define lstring_h\n\n#include \"lgc.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n\n\n/*\n** Memory-allocation error message must be preallocated (it cannot\n** be created after memory is exhausted)\n*/\n#define MEMERRMSG       \"not enough memory\"\n\n\n/*\n** Maximum length for short strings, that is, strings that are\n** internalized. (Cannot be smaller than reserved words or tags for\n** metamethods, as these strings must be internalized;\n** #(\"function\") = 8, #(\"__newindex\") = 10.)\n*/\n#if !defined(LUAI_MAXSHORTLEN)\n#define LUAI_MAXSHORTLEN\t40\n#endif\n\n\n/*\n** Size of a short TString: Size of the header plus space for the string\n** itself (including final '\\0').\n*/\n#define sizestrshr(l)  \\\n\t(offsetof(TString, contents) + ((l) + 1) * sizeof(char))\n\n\n#define luaS_newliteral(L, s)\t(luaS_newlstr(L, \"\" s, \\\n                                 (sizeof(s)/sizeof(char))-1))\n\n\n/*\n** test whether a string is a reserved word\n*/\n#define isreserved(s)\t(strisshr(s) && (s)->extra > 0)\n\n\n/*\n** equality for short strings, compare id first\n*/\n#define eqshrstr(a,b)\tcheck_exp((a)->tt == LUA_VSHRSTR, (a) == (b) || \\\n       ( ((a)->id == (b)->id) ? ((a)->id != 0) : ((a)->hash == (b)->hash && luaS_eqshrstr(a,b)) ) )\n\nLUAI_FUNC unsigned luaS_hashlongstr (TString *ts);\nLUAI_FUNC int luaS_eqstr (TString *a, TString *b);\nLUAI_FUNC void luaS_resize (lua_State *L, int newsize);\nLUAI_FUNC void luaS_clearcache (global_State *g);\nLUAI_FUNC void luaS_init (lua_State *L);\nLUAI_FUNC void luaS_remove (lua_State *L, TString *ts);\nLUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s,\n                                              unsigned short nuvalue);\nLUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);\nLUAI_FUNC TString *luaS_new (lua_State *L, const char *str);\nLUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l);\nLUAI_FUNC TString *luaS_newextlstr (lua_State *L,\n\t\tconst char *s, size_t len, lua_Alloc falloc, void *ud);\nLUAI_FUNC size_t luaS_sizelngstr (size_t len, int kind);\nLUAI_FUNC TString *luaS_normstr (lua_State *L, TString *ts);\n\nLUAI_FUNC void luaS_share(TString *ts);\nLUAI_FUNC int luaS_eqshrstr (TString *a, TString *b);\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lstrlib.c",
    "content": "/*\n** $Id: lstrlib.c $\n** Standard library for string operations and pattern-matching\n** See Copyright Notice in lua.h\n*/\n\n#define lstrlib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <ctype.h>\n#include <float.h>\n#include <limits.h>\n#include <locale.h>\n#include <math.h>\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\n/*\n** maximum number of captures that a pattern can do during\n** pattern-matching. This limit is arbitrary, but must fit in\n** an unsigned char.\n*/\n#if !defined(LUA_MAXCAPTURES)\n#define LUA_MAXCAPTURES\t\t32\n#endif\n\n\nstatic int str_len (lua_State *L) {\n  size_t l;\n  luaL_checklstring(L, 1, &l);\n  lua_pushinteger(L, (lua_Integer)l);\n  return 1;\n}\n\n\n/*\n** translate a relative initial string position\n** (negative means back from end): clip result to [1, inf).\n** The length of any string in Lua must fit in a lua_Integer,\n** so there are no overflows in the casts.\n** The inverted comparison avoids a possible overflow\n** computing '-pos'.\n*/\nstatic size_t posrelatI (lua_Integer pos, size_t len) {\n  if (pos > 0)\n    return (size_t)pos;\n  else if (pos == 0)\n    return 1;\n  else if (pos < -(lua_Integer)len)  /* inverted comparison */\n    return 1;  /* clip to 1 */\n  else return len + (size_t)pos + 1;\n}\n\n\n/*\n** Gets an optional ending string position from argument 'arg',\n** with default value 'def'.\n** Negative means back from end: clip result to [0, len]\n*/\nstatic size_t getendpos (lua_State *L, int arg, lua_Integer def,\n                         size_t len) {\n  lua_Integer pos = luaL_optinteger(L, arg, def);\n  if (pos > (lua_Integer)len)\n    return len;\n  else if (pos >= 0)\n    return (size_t)pos;\n  else if (pos < -(lua_Integer)len)\n    return 0;\n  else return len + (size_t)pos + 1;\n}\n\n\nstatic int str_sub (lua_State *L) {\n  size_t l;\n  const char *s = luaL_checklstring(L, 1, &l);\n  size_t start = posrelatI(luaL_checkinteger(L, 2), l);\n  size_t end = getendpos(L, 3, -1, l);\n  if (start <= end)\n    lua_pushlstring(L, s + start - 1, (end - start) + 1);\n  else lua_pushliteral(L, \"\");\n  return 1;\n}\n\n\nstatic int str_reverse (lua_State *L) {\n  size_t l, i;\n  luaL_Buffer b;\n  const char *s = luaL_checklstring(L, 1, &l);\n  char *p = luaL_buffinitsize(L, &b, l);\n  for (i = 0; i < l; i++)\n    p[i] = s[l - i - 1];\n  luaL_pushresultsize(&b, l);\n  return 1;\n}\n\n\nstatic int str_lower (lua_State *L) {\n  size_t l;\n  size_t i;\n  luaL_Buffer b;\n  const char *s = luaL_checklstring(L, 1, &l);\n  char *p = luaL_buffinitsize(L, &b, l);\n  for (i=0; i<l; i++)\n    p[i] = cast_char(tolower(cast_uchar(s[i])));\n  luaL_pushresultsize(&b, l);\n  return 1;\n}\n\n\nstatic int str_upper (lua_State *L) {\n  size_t l;\n  size_t i;\n  luaL_Buffer b;\n  const char *s = luaL_checklstring(L, 1, &l);\n  char *p = luaL_buffinitsize(L, &b, l);\n  for (i=0; i<l; i++)\n    p[i] = cast_char(toupper(cast_uchar(s[i])));\n  luaL_pushresultsize(&b, l);\n  return 1;\n}\n\n\n/*\n** MAX_SIZE is limited both by size_t and lua_Integer.\n** When x <= MAX_SIZE, x can be safely cast to size_t or lua_Integer.\n*/\nstatic int str_rep (lua_State *L) {\n  size_t len, lsep;\n  const char *s = luaL_checklstring(L, 1, &len);\n  lua_Integer n = luaL_checkinteger(L, 2);\n  const char *sep = luaL_optlstring(L, 3, \"\", &lsep);\n  if (n <= 0)\n    lua_pushliteral(L, \"\");\n  else if (l_unlikely(len > MAX_SIZE - lsep ||\n               cast_st2S(len + lsep) > cast_st2S(MAX_SIZE) / n))\n    return luaL_error(L, \"resulting string too large\");\n  else {\n    size_t totallen = (cast_sizet(n) * (len + lsep)) - lsep;\n    luaL_Buffer b;\n    char *p = luaL_buffinitsize(L, &b, totallen);\n    while (n-- > 1) {  /* first n-1 copies (followed by separator) */\n      memcpy(p, s, len * sizeof(char)); p += len;\n      if (lsep > 0) {  /* empty 'memcpy' is not that cheap */\n        memcpy(p, sep, lsep * sizeof(char)); p += lsep;\n      }\n    }\n    memcpy(p, s, len * sizeof(char));  /* last copy without separator */\n    luaL_pushresultsize(&b, totallen);\n  }\n  return 1;\n}\n\n\nstatic int str_byte (lua_State *L) {\n  size_t l;\n  const char *s = luaL_checklstring(L, 1, &l);\n  lua_Integer pi = luaL_optinteger(L, 2, 1);\n  size_t posi = posrelatI(pi, l);\n  size_t pose = getendpos(L, 3, pi, l);\n  int n, i;\n  if (posi > pose) return 0;  /* empty interval; return no values */\n  if (l_unlikely(pose - posi >= (size_t)INT_MAX))  /* arithmetic overflow? */\n    return luaL_error(L, \"string slice too long\");\n  n = (int)(pose -  posi) + 1;\n  luaL_checkstack(L, n, \"string slice too long\");\n  for (i=0; i<n; i++)\n    lua_pushinteger(L, cast_uchar(s[posi + cast_uint(i) - 1]));\n  return n;\n}\n\n\nstatic int str_char (lua_State *L) {\n  int n = lua_gettop(L);  /* number of arguments */\n  int i;\n  luaL_Buffer b;\n  char *p = luaL_buffinitsize(L, &b, cast_uint(n));\n  for (i=1; i<=n; i++) {\n    lua_Unsigned c = (lua_Unsigned)luaL_checkinteger(L, i);\n    luaL_argcheck(L, c <= (lua_Unsigned)UCHAR_MAX, i, \"value out of range\");\n    p[i - 1] = cast_char(cast_uchar(c));\n  }\n  luaL_pushresultsize(&b, cast_uint(n));\n  return 1;\n}\n\n\n/*\n** Buffer to store the result of 'string.dump'. It must be initialized\n** after the call to 'lua_dump', to ensure that the function is on the\n** top of the stack when 'lua_dump' is called. ('luaL_buffinit' might\n** push stuff.)\n*/\nstruct str_Writer {\n  int init;  /* true iff buffer has been initialized */\n  luaL_Buffer B;\n};\n\n\nstatic int writer (lua_State *L, const void *b, size_t size, void *ud) {\n  struct str_Writer *state = (struct str_Writer *)ud;\n  if (!state->init) {\n    state->init = 1;\n    luaL_buffinit(L, &state->B);\n  }\n  if (b == NULL) {  /* finishing dump? */\n    luaL_pushresult(&state->B);  /* push result */\n    lua_replace(L, 1);  /* move it to reserved slot */\n  }\n  else\n    luaL_addlstring(&state->B, (const char *)b, size);\n  return 0;\n}\n\n\nstatic int str_dump (lua_State *L) {\n  struct str_Writer state;\n  int strip = lua_toboolean(L, 2);\n  luaL_argcheck(L, lua_type(L, 1) == LUA_TFUNCTION && !lua_iscfunction(L, 1),\n                   1, \"Lua function expected\");\n  /* ensure function is on the top of the stack and vacate slot 1 */\n  lua_pushvalue(L, 1);\n  state.init = 0;\n  lua_dump(L, writer, &state, strip);\n  lua_settop(L, 1);  /* leave final result on top */\n  return 1;\n}\n\n\n\n/*\n** {======================================================\n** METAMETHODS\n** =======================================================\n*/\n\n#if defined(LUA_NOCVTS2N)\t/* { */\n\n/* no coercion from strings to numbers */\n\nstatic const luaL_Reg stringmetamethods[] = {\n  {\"__index\", NULL},  /* placeholder */\n  {NULL, NULL}\n};\n\n#else\t\t/* }{ */\n\nstatic int tonum (lua_State *L, int arg) {\n  if (lua_type(L, arg) == LUA_TNUMBER) {  /* already a number? */\n    lua_pushvalue(L, arg);\n    return 1;\n  }\n  else {  /* check whether it is a numerical string */\n    size_t len;\n    const char *s = lua_tolstring(L, arg, &len);\n    return (s != NULL && lua_stringtonumber(L, s) == len + 1);\n  }\n}\n\n\n/*\n** To be here, either the first operand was a string or the first\n** operand didn't have a corresponding metamethod. (Otherwise, that\n** other metamethod would have been called.) So, if this metamethod\n** doesn't work, the only other option would be for the second\n** operand to have a different metamethod.\n*/\nstatic void trymt (lua_State *L, const char *mtkey, const char *opname) {\n  lua_settop(L, 2);  /* back to the original arguments */\n  if (l_unlikely(lua_type(L, 2) == LUA_TSTRING ||\n                 !luaL_getmetafield(L, 2, mtkey)))\n    luaL_error(L, \"attempt to %s a '%s' with a '%s'\", opname,\n                  luaL_typename(L, -2), luaL_typename(L, -1));\n  lua_insert(L, -3);  /* put metamethod before arguments */\n  lua_call(L, 2, 1);  /* call metamethod */\n}\n\n\nstatic int arith (lua_State *L, int op, const char *mtname) {\n  if (tonum(L, 1) && tonum(L, 2))\n    lua_arith(L, op);  /* result will be on the top */\n  else\n    trymt(L, mtname, mtname + 2);\n  return 1;\n}\n\n\nstatic int arith_add (lua_State *L) {\n  return arith(L, LUA_OPADD, \"__add\");\n}\n\nstatic int arith_sub (lua_State *L) {\n  return arith(L, LUA_OPSUB, \"__sub\");\n}\n\nstatic int arith_mul (lua_State *L) {\n  return arith(L, LUA_OPMUL, \"__mul\");\n}\n\nstatic int arith_mod (lua_State *L) {\n  return arith(L, LUA_OPMOD, \"__mod\");\n}\n\nstatic int arith_pow (lua_State *L) {\n  return arith(L, LUA_OPPOW, \"__pow\");\n}\n\nstatic int arith_div (lua_State *L) {\n  return arith(L, LUA_OPDIV, \"__div\");\n}\n\nstatic int arith_idiv (lua_State *L) {\n  return arith(L, LUA_OPIDIV, \"__idiv\");\n}\n\nstatic int arith_unm (lua_State *L) {\n  return arith(L, LUA_OPUNM, \"__unm\");\n}\n\n\nstatic const luaL_Reg stringmetamethods[] = {\n  {\"__add\", arith_add},\n  {\"__sub\", arith_sub},\n  {\"__mul\", arith_mul},\n  {\"__mod\", arith_mod},\n  {\"__pow\", arith_pow},\n  {\"__div\", arith_div},\n  {\"__idiv\", arith_idiv},\n  {\"__unm\", arith_unm},\n  {\"__index\", NULL},  /* placeholder */\n  {NULL, NULL}\n};\n\n#endif\t\t/* } */\n\n/* }====================================================== */\n\n/*\n** {======================================================\n** PATTERN MATCHING\n** =======================================================\n*/\n\n\n#define CAP_UNFINISHED\t(-1)\n#define CAP_POSITION\t(-2)\n\n\ntypedef struct MatchState {\n  const char *src_init;  /* init of source string */\n  const char *src_end;  /* end ('\\0') of source string */\n  const char *p_end;  /* end ('\\0') of pattern */\n  lua_State *L;\n  int matchdepth;  /* control for recursive depth (to avoid C stack overflow) */\n  int level;  /* total number of captures (finished or unfinished) */\n  struct {\n    const char *init;\n    ptrdiff_t len;  /* length or special value (CAP_*) */\n  } capture[LUA_MAXCAPTURES];\n} MatchState;\n\n\n/* recursive function */\nstatic const char *match (MatchState *ms, const char *s, const char *p);\n\n\n/* maximum recursion depth for 'match' */\n#if !defined(MAXCCALLS)\n#define MAXCCALLS\t200\n#endif\n\n\n#define L_ESC\t\t'%'\n#define SPECIALS\t\"^$*+?.([%-\"\n\n\nstatic int check_capture (MatchState *ms, int l) {\n  l -= '1';\n  if (l_unlikely(l < 0 || l >= ms->level ||\n                 ms->capture[l].len == CAP_UNFINISHED))\n    return luaL_error(ms->L, \"invalid capture index %%%d\", l + 1);\n  return l;\n}\n\n\nstatic int capture_to_close (MatchState *ms) {\n  int level = ms->level;\n  for (level--; level>=0; level--)\n    if (ms->capture[level].len == CAP_UNFINISHED) return level;\n  return luaL_error(ms->L, \"invalid pattern capture\");\n}\n\n\nstatic const char *classend (MatchState *ms, const char *p) {\n  switch (*p++) {\n    case L_ESC: {\n      if (l_unlikely(p == ms->p_end))\n        luaL_error(ms->L, \"malformed pattern (ends with '%%')\");\n      return p+1;\n    }\n    case '[': {\n      if (*p == '^') p++;\n      do {  /* look for a ']' */\n        if (l_unlikely(p == ms->p_end))\n          luaL_error(ms->L, \"malformed pattern (missing ']')\");\n        if (*(p++) == L_ESC && p < ms->p_end)\n          p++;  /* skip escapes (e.g. '%]') */\n      } while (*p != ']');\n      return p+1;\n    }\n    default: {\n      return p;\n    }\n  }\n}\n\n\nstatic int match_class (int c, int cl) {\n  int res;\n  switch (tolower(cl)) {\n    case 'a' : res = isalpha(c); break;\n    case 'c' : res = iscntrl(c); break;\n    case 'd' : res = isdigit(c); break;\n    case 'g' : res = isgraph(c); break;\n    case 'l' : res = islower(c); break;\n    case 'p' : res = ispunct(c); break;\n    case 's' : res = isspace(c); break;\n    case 'u' : res = isupper(c); break;\n    case 'w' : res = isalnum(c); break;\n    case 'x' : res = isxdigit(c); break;\n    case 'z' : res = (c == 0); break;  /* deprecated option */\n    default: return (cl == c);\n  }\n  return (islower(cl) ? res : !res);\n}\n\n\nstatic int matchbracketclass (int c, const char *p, const char *ec) {\n  int sig = 1;\n  if (*(p+1) == '^') {\n    sig = 0;\n    p++;  /* skip the '^' */\n  }\n  while (++p < ec) {\n    if (*p == L_ESC) {\n      p++;\n      if (match_class(c, cast_uchar(*p)))\n        return sig;\n    }\n    else if ((*(p+1) == '-') && (p+2 < ec)) {\n      p+=2;\n      if (cast_uchar(*(p-2)) <= c && c <= cast_uchar(*p))\n        return sig;\n    }\n    else if (cast_uchar(*p) == c) return sig;\n  }\n  return !sig;\n}\n\n\nstatic int singlematch (MatchState *ms, const char *s, const char *p,\n                        const char *ep) {\n  if (s >= ms->src_end)\n    return 0;\n  else {\n    int c = cast_uchar(*s);\n    switch (*p) {\n      case '.': return 1;  /* matches any char */\n      case L_ESC: return match_class(c, cast_uchar(*(p+1)));\n      case '[': return matchbracketclass(c, p, ep-1);\n      default:  return (cast_uchar(*p) == c);\n    }\n  }\n}\n\n\nstatic const char *matchbalance (MatchState *ms, const char *s,\n                                   const char *p) {\n  if (l_unlikely(p >= ms->p_end - 1))\n    luaL_error(ms->L, \"malformed pattern (missing arguments to '%%b')\");\n  if (*s != *p) return NULL;\n  else {\n    int b = *p;\n    int e = *(p+1);\n    int cont = 1;\n    while (++s < ms->src_end) {\n      if (*s == e) {\n        if (--cont == 0) return s+1;\n      }\n      else if (*s == b) cont++;\n    }\n  }\n  return NULL;  /* string ends out of balance */\n}\n\n\nstatic const char *max_expand (MatchState *ms, const char *s,\n                                 const char *p, const char *ep) {\n  ptrdiff_t i = 0;  /* counts maximum expand for item */\n  while (singlematch(ms, s + i, p, ep))\n    i++;\n  /* keeps trying to match with the maximum repetitions */\n  while (i>=0) {\n    const char *res = match(ms, (s+i), ep+1);\n    if (res) return res;\n    i--;  /* else didn't match; reduce 1 repetition to try again */\n  }\n  return NULL;\n}\n\n\nstatic const char *min_expand (MatchState *ms, const char *s,\n                                 const char *p, const char *ep) {\n  for (;;) {\n    const char *res = match(ms, s, ep+1);\n    if (res != NULL)\n      return res;\n    else if (singlematch(ms, s, p, ep))\n      s++;  /* try with one more repetition */\n    else return NULL;\n  }\n}\n\n\nstatic const char *start_capture (MatchState *ms, const char *s,\n                                    const char *p, int what) {\n  const char *res;\n  int level = ms->level;\n  if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, \"too many captures\");\n  ms->capture[level].init = s;\n  ms->capture[level].len = what;\n  ms->level = level+1;\n  if ((res=match(ms, s, p)) == NULL)  /* match failed? */\n    ms->level--;  /* undo capture */\n  return res;\n}\n\n\nstatic const char *end_capture (MatchState *ms, const char *s,\n                                  const char *p) {\n  int l = capture_to_close(ms);\n  const char *res;\n  ms->capture[l].len = s - ms->capture[l].init;  /* close capture */\n  if ((res = match(ms, s, p)) == NULL)  /* match failed? */\n    ms->capture[l].len = CAP_UNFINISHED;  /* undo capture */\n  return res;\n}\n\n\nstatic const char *match_capture (MatchState *ms, const char *s, int l) {\n  size_t len;\n  l = check_capture(ms, l);\n  len = cast_sizet(ms->capture[l].len);\n  if ((size_t)(ms->src_end-s) >= len &&\n      memcmp(ms->capture[l].init, s, len) == 0)\n    return s+len;\n  else return NULL;\n}\n\n\nstatic const char *match (MatchState *ms, const char *s, const char *p) {\n  if (l_unlikely(ms->matchdepth-- == 0))\n    luaL_error(ms->L, \"pattern too complex\");\n  init: /* using goto to optimize tail recursion */\n  if (p != ms->p_end) {  /* end of pattern? */\n    switch (*p) {\n      case '(': {  /* start capture */\n        if (*(p + 1) == ')')  /* position capture? */\n          s = start_capture(ms, s, p + 2, CAP_POSITION);\n        else\n          s = start_capture(ms, s, p + 1, CAP_UNFINISHED);\n        break;\n      }\n      case ')': {  /* end capture */\n        s = end_capture(ms, s, p + 1);\n        break;\n      }\n      case '$': {\n        if ((p + 1) != ms->p_end)  /* is the '$' the last char in pattern? */\n          goto dflt;  /* no; go to default */\n        s = (s == ms->src_end) ? s : NULL;  /* check end of string */\n        break;\n      }\n      case L_ESC: {  /* escaped sequences not in the format class[*+?-]? */\n        switch (*(p + 1)) {\n          case 'b': {  /* balanced string? */\n            s = matchbalance(ms, s, p + 2);\n            if (s != NULL) {\n              p += 4; goto init;  /* return match(ms, s, p + 4); */\n            }  /* else fail (s == NULL) */\n            break;\n          }\n          case 'f': {  /* frontier? */\n            const char *ep; char previous;\n            p += 2;\n            if (l_unlikely(*p != '['))\n              luaL_error(ms->L, \"missing '[' after '%%f' in pattern\");\n            ep = classend(ms, p);  /* points to what is next */\n            previous = (s == ms->src_init) ? '\\0' : *(s - 1);\n            if (!matchbracketclass(cast_uchar(previous), p, ep - 1) &&\n               matchbracketclass(cast_uchar(*s), p, ep - 1)) {\n              p = ep; goto init;  /* return match(ms, s, ep); */\n            }\n            s = NULL;  /* match failed */\n            break;\n          }\n          case '0': case '1': case '2': case '3':\n          case '4': case '5': case '6': case '7':\n          case '8': case '9': {  /* capture results (%0-%9)? */\n            s = match_capture(ms, s, cast_uchar(*(p + 1)));\n            if (s != NULL) {\n              p += 2; goto init;  /* return match(ms, s, p + 2) */\n            }\n            break;\n          }\n          default: goto dflt;\n        }\n        break;\n      }\n      default: dflt: {  /* pattern class plus optional suffix */\n        const char *ep = classend(ms, p);  /* points to optional suffix */\n        /* does not match at least once? */\n        if (!singlematch(ms, s, p, ep)) {\n          if (*ep == '*' || *ep == '?' || *ep == '-') {  /* accept empty? */\n            p = ep + 1; goto init;  /* return match(ms, s, ep + 1); */\n          }\n          else  /* '+' or no suffix */\n            s = NULL;  /* fail */\n        }\n        else {  /* matched once */\n          switch (*ep) {  /* handle optional suffix */\n            case '?': {  /* optional */\n              const char *res;\n              if ((res = match(ms, s + 1, ep + 1)) != NULL)\n                s = res;\n              else {\n                p = ep + 1; goto init;  /* else return match(ms, s, ep + 1); */\n              }\n              break;\n            }\n            case '+':  /* 1 or more repetitions */\n              s++;  /* 1 match already done */\n              /* FALLTHROUGH */\n            case '*':  /* 0 or more repetitions */\n              s = max_expand(ms, s, p, ep);\n              break;\n            case '-':  /* 0 or more repetitions (minimum) */\n              s = min_expand(ms, s, p, ep);\n              break;\n            default:  /* no suffix */\n              s++; p = ep; goto init;  /* return match(ms, s + 1, ep); */\n          }\n        }\n        break;\n      }\n    }\n  }\n  ms->matchdepth++;\n  return s;\n}\n\n\n\nstatic const char *lmemfind (const char *s1, size_t l1,\n                               const char *s2, size_t l2) {\n  if (l2 == 0) return s1;  /* empty strings are everywhere */\n  else if (l2 > l1) return NULL;  /* avoids a negative 'l1' */\n  else {\n    const char *init;  /* to search for a '*s2' inside 's1' */\n    l2--;  /* 1st char will be checked by 'memchr' */\n    l1 = l1-l2;  /* 's2' cannot be found after that */\n    while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {\n      init++;   /* 1st char is already checked */\n      if (memcmp(init, s2+1, l2) == 0)\n        return init-1;\n      else {  /* correct 'l1' and 's1' to try again */\n        l1 -= ct_diff2sz(init - s1);\n        s1 = init;\n      }\n    }\n    return NULL;  /* not found */\n  }\n}\n\n\n/*\n** get information about the i-th capture. If there are no captures\n** and 'i==0', return information about the whole match, which\n** is the range 's'..'e'. If the capture is a string, return\n** its length and put its address in '*cap'. If it is an integer\n** (a position), push it on the stack and return CAP_POSITION.\n*/\nstatic ptrdiff_t get_onecapture (MatchState *ms, int i, const char *s,\n                              const char *e, const char **cap) {\n  if (i >= ms->level) {\n    if (l_unlikely(i != 0))\n      luaL_error(ms->L, \"invalid capture index %%%d\", i + 1);\n    *cap = s;\n    return (e - s);\n  }\n  else {\n    ptrdiff_t capl = ms->capture[i].len;\n    *cap = ms->capture[i].init;\n    if (l_unlikely(capl == CAP_UNFINISHED))\n      luaL_error(ms->L, \"unfinished capture\");\n    else if (capl == CAP_POSITION)\n      lua_pushinteger(ms->L,\n          ct_diff2S(ms->capture[i].init - ms->src_init) + 1);\n    return capl;\n  }\n}\n\n\n/*\n** Push the i-th capture on the stack.\n*/\nstatic void push_onecapture (MatchState *ms, int i, const char *s,\n                                                    const char *e) {\n  const char *cap;\n  ptrdiff_t l = get_onecapture(ms, i, s, e, &cap);\n  if (l != CAP_POSITION)\n    lua_pushlstring(ms->L, cap, cast_sizet(l));\n  /* else position was already pushed */\n}\n\n\nstatic int push_captures (MatchState *ms, const char *s, const char *e) {\n  int i;\n  int nlevels = (ms->level == 0 && s) ? 1 : ms->level;\n  luaL_checkstack(ms->L, nlevels, \"too many captures\");\n  for (i = 0; i < nlevels; i++)\n    push_onecapture(ms, i, s, e);\n  return nlevels;  /* number of strings pushed */\n}\n\n\n/* check whether pattern has no special characters */\nstatic int nospecials (const char *p, size_t l) {\n  size_t upto = 0;\n  do {\n    if (strpbrk(p + upto, SPECIALS))\n      return 0;  /* pattern has a special character */\n    upto += strlen(p + upto) + 1;  /* may have more after \\0 */\n  } while (upto <= l);\n  return 1;  /* no special chars found */\n}\n\n\nstatic void prepstate (MatchState *ms, lua_State *L,\n                       const char *s, size_t ls, const char *p, size_t lp) {\n  ms->L = L;\n  ms->matchdepth = MAXCCALLS;\n  ms->src_init = s;\n  ms->src_end = s + ls;\n  ms->p_end = p + lp;\n}\n\n\nstatic void reprepstate (MatchState *ms) {\n  ms->level = 0;\n  lua_assert(ms->matchdepth == MAXCCALLS);\n}\n\n\nstatic int str_find_aux (lua_State *L, int find) {\n  size_t ls, lp;\n  const char *s = luaL_checklstring(L, 1, &ls);\n  const char *p = luaL_checklstring(L, 2, &lp);\n  size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;\n  if (init > ls) {  /* start after string's end? */\n    luaL_pushfail(L);  /* cannot find anything */\n    return 1;\n  }\n  /* explicit request or no special characters? */\n  if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {\n    /* do a plain search */\n    const char *s2 = lmemfind(s + init, ls - init, p, lp);\n    if (s2) {\n      lua_pushinteger(L, ct_diff2S(s2 - s) + 1);\n      lua_pushinteger(L, cast_st2S(ct_diff2sz(s2 - s) + lp));\n      return 2;\n    }\n  }\n  else {\n    MatchState ms;\n    const char *s1 = s + init;\n    int anchor = (*p == '^');\n    if (anchor) {\n      p++; lp--;  /* skip anchor character */\n    }\n    prepstate(&ms, L, s, ls, p, lp);\n    do {\n      const char *res;\n      reprepstate(&ms);\n      if ((res=match(&ms, s1, p)) != NULL) {\n        if (find) {\n          lua_pushinteger(L, ct_diff2S(s1 - s) + 1);  /* start */\n          lua_pushinteger(L, ct_diff2S(res - s));   /* end */\n          return push_captures(&ms, NULL, 0) + 2;\n        }\n        else\n          return push_captures(&ms, s1, res);\n      }\n    } while (s1++ < ms.src_end && !anchor);\n  }\n  luaL_pushfail(L);  /* not found */\n  return 1;\n}\n\n\nstatic int str_find (lua_State *L) {\n  return str_find_aux(L, 1);\n}\n\n\nstatic int str_match (lua_State *L) {\n  return str_find_aux(L, 0);\n}\n\n\n/* state for 'gmatch' */\ntypedef struct GMatchState {\n  const char *src;  /* current position */\n  const char *p;  /* pattern */\n  const char *lastmatch;  /* end of last match */\n  MatchState ms;  /* match state */\n} GMatchState;\n\n\nstatic int gmatch_aux (lua_State *L) {\n  GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));\n  const char *src;\n  gm->ms.L = L;\n  for (src = gm->src; src <= gm->ms.src_end; src++) {\n    const char *e;\n    reprepstate(&gm->ms);\n    if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {\n      gm->src = gm->lastmatch = e;\n      return push_captures(&gm->ms, src, e);\n    }\n  }\n  return 0;  /* not found */\n}\n\n\nstatic int gmatch (lua_State *L) {\n  size_t ls, lp;\n  const char *s = luaL_checklstring(L, 1, &ls);\n  const char *p = luaL_checklstring(L, 2, &lp);\n  size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;\n  GMatchState *gm;\n  lua_settop(L, 2);  /* keep strings on closure to avoid being collected */\n  gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);\n  if (init > ls)  /* start after string's end? */\n    init = ls + 1;  /* avoid overflows in 's + init' */\n  prepstate(&gm->ms, L, s, ls, p, lp);\n  gm->src = s + init; gm->p = p; gm->lastmatch = NULL;\n  lua_pushcclosure(L, gmatch_aux, 3);\n  return 1;\n}\n\n\nstatic void add_s (MatchState *ms, luaL_Buffer *b, const char *s,\n                                                   const char *e) {\n  size_t l;\n  lua_State *L = ms->L;\n  const char *news = lua_tolstring(L, 3, &l);\n  const char *p;\n  while ((p = (char *)memchr(news, L_ESC, l)) != NULL) {\n    luaL_addlstring(b, news, ct_diff2sz(p - news));\n    p++;  /* skip ESC */\n    if (*p == L_ESC)  /* '%%' */\n      luaL_addchar(b, *p);\n    else if (*p == '0')  /* '%0' */\n        luaL_addlstring(b, s, ct_diff2sz(e - s));\n    else if (isdigit(cast_uchar(*p))) {  /* '%n' */\n      const char *cap;\n      ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap);\n      if (resl == CAP_POSITION)\n        luaL_addvalue(b);  /* add position to accumulated result */\n      else\n        luaL_addlstring(b, cap, cast_sizet(resl));\n    }\n    else\n      luaL_error(L, \"invalid use of '%c' in replacement string\", L_ESC);\n    l -= ct_diff2sz(p + 1 - news);\n    news = p + 1;\n  }\n  luaL_addlstring(b, news, l);\n}\n\n\n/*\n** Add the replacement value to the string buffer 'b'.\n** Return true if the original string was changed. (Function calls and\n** table indexing resulting in nil or false do not change the subject.)\n*/\nstatic int add_value (MatchState *ms, luaL_Buffer *b, const char *s,\n                                      const char *e, int tr) {\n  lua_State *L = ms->L;\n  switch (tr) {\n    case LUA_TFUNCTION: {  /* call the function */\n      int n;\n      lua_pushvalue(L, 3);  /* push the function */\n      n = push_captures(ms, s, e);  /* all captures as arguments */\n      lua_call(L, n, 1);  /* call it */\n      break;\n    }\n    case LUA_TTABLE: {  /* index the table */\n      push_onecapture(ms, 0, s, e);  /* first capture is the index */\n      lua_gettable(L, 3);\n      break;\n    }\n    default: {  /* LUA_TNUMBER or LUA_TSTRING */\n      add_s(ms, b, s, e);  /* add value to the buffer */\n      return 1;  /* something changed */\n    }\n  }\n  if (!lua_toboolean(L, -1)) {  /* nil or false? */\n    lua_pop(L, 1);  /* remove value */\n    luaL_addlstring(b, s, ct_diff2sz(e - s));  /* keep original text */\n    return 0;  /* no changes */\n  }\n  else if (l_unlikely(!lua_isstring(L, -1)))\n    return luaL_error(L, \"invalid replacement value (a %s)\",\n                         luaL_typename(L, -1));\n  else {\n    luaL_addvalue(b);  /* add result to accumulator */\n    return 1;  /* something changed */\n  }\n}\n\n\nstatic int str_gsub (lua_State *L) {\n  size_t srcl, lp;\n  const char *src = luaL_checklstring(L, 1, &srcl);  /* subject */\n  const char *p = luaL_checklstring(L, 2, &lp);  /* pattern */\n  const char *lastmatch = NULL;  /* end of last match */\n  int tr = lua_type(L, 3);  /* replacement type */\n  /* max replacements */\n  lua_Integer max_s = luaL_optinteger(L, 4, cast_st2S(srcl) + 1);\n  int anchor = (*p == '^');\n  lua_Integer n = 0;  /* replacement count */\n  int changed = 0;  /* change flag */\n  MatchState ms;\n  luaL_Buffer b;\n  luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||\n                   tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,\n                      \"string/function/table\");\n  luaL_buffinit(L, &b);\n  if (anchor) {\n    p++; lp--;  /* skip anchor character */\n  }\n  prepstate(&ms, L, src, srcl, p, lp);\n  while (n < max_s) {\n    const char *e;\n    reprepstate(&ms);  /* (re)prepare state for new match */\n    if ((e = match(&ms, src, p)) != NULL && e != lastmatch) {  /* match? */\n      n++;\n      changed = add_value(&ms, &b, src, e, tr) | changed;\n      src = lastmatch = e;\n    }\n    else if (src < ms.src_end)  /* otherwise, skip one character */\n      luaL_addchar(&b, *src++);\n    else break;  /* end of subject */\n    if (anchor) break;\n  }\n  if (!changed)  /* no changes? */\n    lua_pushvalue(L, 1);  /* return original string */\n  else {  /* something changed */\n    luaL_addlstring(&b, src, ct_diff2sz(ms.src_end - src));\n    luaL_pushresult(&b);  /* create and return new string */\n  }\n  lua_pushinteger(L, n);  /* number of substitutions */\n  return 2;\n}\n\n/* }====================================================== */\n\n\n\n/*\n** {======================================================\n** STRING FORMAT\n** =======================================================\n*/\n\n#if !defined(lua_number2strx)\t/* { */\n\n/*\n** Hexadecimal floating-point formatter\n*/\n\n#define SIZELENMOD\t(sizeof(LUA_NUMBER_FRMLEN)/sizeof(char))\n\n\n/*\n** Number of bits that goes into the first digit. It can be any value\n** between 1 and 4; the following definition tries to align the number\n** to nibble boundaries by making what is left after that first digit a\n** multiple of 4.\n*/\n#define L_NBFD\t\t((l_floatatt(MANT_DIG) - 1)%4 + 1)\n\n\n/*\n** Add integer part of 'x' to buffer and return new 'x'\n*/\nstatic lua_Number adddigit (char *buff, unsigned n, lua_Number x) {\n  lua_Number dd = l_mathop(floor)(x);  /* get integer part from 'x' */\n  int d = (int)dd;\n  buff[n] = cast_char(d < 10 ? d + '0' : d - 10 + 'a');  /* add to buffer */\n  return x - dd;  /* return what is left */\n}\n\n\nstatic int num2straux (char *buff, unsigned sz, lua_Number x) {\n  /* if 'inf' or 'NaN', format it like '%g' */\n  if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL)\n    return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x);\n  else if (x == 0) {  /* can be -0... */\n    /* create \"0\" or \"-0\" followed by exponent */\n    return l_sprintf(buff, sz, LUA_NUMBER_FMT \"x0p+0\", (LUAI_UACNUMBER)x);\n  }\n  else {\n    int e;\n    lua_Number m = l_mathop(frexp)(x, &e);  /* 'x' fraction and exponent */\n    unsigned n = 0;  /* character count */\n    if (m < 0) {  /* is number negative? */\n      buff[n++] = '-';  /* add sign */\n      m = -m;  /* make it positive */\n    }\n    buff[n++] = '0'; buff[n++] = 'x';  /* add \"0x\" */\n    m = adddigit(buff, n++, m * (1 << L_NBFD));  /* add first digit */\n    e -= L_NBFD;  /* this digit goes before the radix point */\n    if (m > 0) {  /* more digits? */\n      buff[n++] = lua_getlocaledecpoint();  /* add radix point */\n      do {  /* add as many digits as needed */\n        m = adddigit(buff, n++, m * 16);\n      } while (m > 0);\n    }\n    n += cast_uint(l_sprintf(buff + n, sz - n, \"p%+d\", e));  /* add exponent */\n    lua_assert(n < sz);\n    return cast_int(n);\n  }\n}\n\n\nstatic int lua_number2strx (lua_State *L, char *buff, unsigned sz,\n                            const char *fmt, lua_Number x) {\n  int n = num2straux(buff, sz, x);\n  if (fmt[SIZELENMOD] == 'A') {\n    int i;\n    for (i = 0; i < n; i++)\n      buff[i] = cast_char(toupper(cast_uchar(buff[i])));\n  }\n  else if (l_unlikely(fmt[SIZELENMOD] != 'a'))\n    return luaL_error(L, \"modifiers for format '%%a'/'%%A' not implemented\");\n  return n;\n}\n\n#endif\t\t\t\t/* } */\n\n\n/*\n** Maximum size for items formatted with '%f'. This size is produced\n** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.',\n** and '\\0') + number of decimal digits to represent maxfloat (which\n** is maximum exponent + 1). (99+3+1, adding some extra, 110)\n*/\n#define MAX_ITEMF\t(110 + l_floatatt(MAX_10_EXP))\n\n\n/*\n** All formats except '%f' do not need that large limit.  The other\n** float formats use exponents, so that they fit in the 99 limit for\n** significant digits; 's' for large strings and 'q' add items directly\n** to the buffer; all integer formats also fit in the 99 limit.  The\n** worst case are floats: they may need 99 significant digits, plus\n** '0x', '-', '.', 'e+XXXX', and '\\0'. Adding some extra, 120.\n*/\n#define MAX_ITEM\t120\n\n\n/* valid flags in a format specification */\n#if !defined(L_FMTFLAGSF)\n\n/* valid flags for a, A, e, E, f, F, g, and G conversions */\n#define L_FMTFLAGSF\t\"-+#0 \"\n\n/* valid flags for o, x, and X conversions */\n#define L_FMTFLAGSX\t\"-#0\"\n\n/* valid flags for d and i conversions */\n#define L_FMTFLAGSI\t\"-+0 \"\n\n/* valid flags for u conversions */\n#define L_FMTFLAGSU\t\"-0\"\n\n/* valid flags for c, p, and s conversions */\n#define L_FMTFLAGSC\t\"-\"\n\n#endif\n\n\n/*\n** Maximum size of each format specification (such as \"%-099.99d\"):\n** Initial '%', flags (up to 5), width (2), period, precision (2),\n** length modifier (8), conversion specifier, and final '\\0', plus some\n** extra.\n*/\n#define MAX_FORMAT\t32\n\n\nstatic void addquoted (luaL_Buffer *b, const char *s, size_t len) {\n  luaL_addchar(b, '\"');\n  while (len--) {\n    if (*s == '\"' || *s == '\\\\' || *s == '\\n') {\n      luaL_addchar(b, '\\\\');\n      luaL_addchar(b, *s);\n    }\n    else if (iscntrl(cast_uchar(*s))) {\n      char buff[10];\n      if (!isdigit(cast_uchar(*(s+1))))\n        l_sprintf(buff, sizeof(buff), \"\\\\%d\", (int)cast_uchar(*s));\n      else\n        l_sprintf(buff, sizeof(buff), \"\\\\%03d\", (int)cast_uchar(*s));\n      luaL_addstring(b, buff);\n    }\n    else\n      luaL_addchar(b, *s);\n    s++;\n  }\n  luaL_addchar(b, '\"');\n}\n\n\n/*\n** Serialize a floating-point number in such a way that it can be\n** scanned back by Lua. Use hexadecimal format for \"common\" numbers\n** (to preserve precision); inf, -inf, and NaN are handled separately.\n** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.)\n*/\nstatic int quotefloat (lua_State *L, char *buff, lua_Number n) {\n  const char *s;  /* for the fixed representations */\n  if (n == (lua_Number)HUGE_VAL)  /* inf? */\n    s = \"1e9999\";\n  else if (n == -(lua_Number)HUGE_VAL)  /* -inf? */\n    s = \"-1e9999\";\n  else if (n != n)  /* NaN? */\n    s = \"(0/0)\";\n  else {  /* format number as hexadecimal */\n    int  nb = lua_number2strx(L, buff, MAX_ITEM,\n                                 \"%\" LUA_NUMBER_FRMLEN \"a\", n);\n    /* ensures that 'buff' string uses a dot as the radix character */\n    if (memchr(buff, '.', cast_uint(nb)) == NULL) {  /* no dot? */\n      char point = lua_getlocaledecpoint();  /* try locale point */\n      char *ppoint = (char *)memchr(buff, point, cast_uint(nb));\n      if (ppoint) *ppoint = '.';  /* change it to a dot */\n    }\n    return nb;\n  }\n  /* for the fixed representations */\n  return l_sprintf(buff, MAX_ITEM, \"%s\", s);\n}\n\n\nstatic void addliteral (lua_State *L, luaL_Buffer *b, int arg) {\n  switch (lua_type(L, arg)) {\n    case LUA_TSTRING: {\n      size_t len;\n      const char *s = lua_tolstring(L, arg, &len);\n      addquoted(b, s, len);\n      break;\n    }\n    case LUA_TNUMBER: {\n      char *buff = luaL_prepbuffsize(b, MAX_ITEM);\n      int nb;\n      if (!lua_isinteger(L, arg))  /* float? */\n        nb = quotefloat(L, buff, lua_tonumber(L, arg));\n      else {  /* integers */\n        lua_Integer n = lua_tointeger(L, arg);\n        const char *format = (n == LUA_MININTEGER)  /* corner case? */\n                           ? \"0x%\" LUA_INTEGER_FRMLEN \"x\"  /* use hex */\n                           : LUA_INTEGER_FMT;  /* else use default format */\n        nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);\n      }\n      luaL_addsize(b, cast_uint(nb));\n      break;\n    }\n    case LUA_TNIL: case LUA_TBOOLEAN: {\n      luaL_tolstring(L, arg, NULL);\n      luaL_addvalue(b);\n      break;\n    }\n    default: {\n      luaL_argerror(L, arg, \"value has no literal form\");\n    }\n  }\n}\n\n\nstatic const char *get2digits (const char *s) {\n  if (isdigit(cast_uchar(*s))) {\n    s++;\n    if (isdigit(cast_uchar(*s))) s++;  /* (2 digits at most) */\n  }\n  return s;\n}\n\n\n/*\n** Check whether a conversion specification is valid. When called,\n** first character in 'form' must be '%' and last character must\n** be a valid conversion specifier. 'flags' are the accepted flags;\n** 'precision' signals whether to accept a precision.\n*/\nstatic void checkformat (lua_State *L, const char *form, const char *flags,\n                                       int precision) {\n  const char *spec = form + 1;  /* skip '%' */\n  spec += strspn(spec, flags);  /* skip flags */\n  if (*spec != '0') {  /* a width cannot start with '0' */\n    spec = get2digits(spec);  /* skip width */\n    if (*spec == '.' && precision) {\n      spec++;\n      spec = get2digits(spec);  /* skip precision */\n    }\n  }\n  if (!isalpha(cast_uchar(*spec)))  /* did not go to the end? */\n    luaL_error(L, \"invalid conversion specification: '%s'\", form);\n}\n\n\n/*\n** Get a conversion specification and copy it to 'form'.\n** Return the address of its last character.\n*/\nstatic const char *getformat (lua_State *L, const char *strfrmt,\n                                            char *form) {\n  /* spans flags, width, and precision ('0' is included as a flag) */\n  size_t len = strspn(strfrmt, L_FMTFLAGSF \"123456789.\");\n  len++;  /* adds following character (should be the specifier) */\n  /* still needs space for '%', '\\0', plus a length modifier */\n  if (len >= MAX_FORMAT - 10)\n    luaL_error(L, \"invalid format (too long)\");\n  *(form++) = '%';\n  memcpy(form, strfrmt, len * sizeof(char));\n  *(form + len) = '\\0';\n  return strfrmt + len - 1;\n}\n\n\n/*\n** add length modifier into formats\n*/\nstatic void addlenmod (char *form, const char *lenmod) {\n  size_t l = strlen(form);\n  size_t lm = strlen(lenmod);\n  char spec = form[l - 1];\n  strcpy(form + l - 1, lenmod);\n  form[l + lm - 1] = spec;\n  form[l + lm] = '\\0';\n}\n\n\nstatic int str_format (lua_State *L) {\n  int top = lua_gettop(L);\n  int arg = 1;\n  size_t sfl;\n  const char *strfrmt = luaL_checklstring(L, arg, &sfl);\n  const char *strfrmt_end = strfrmt+sfl;\n  const char *flags;\n  luaL_Buffer b;\n  luaL_buffinit(L, &b);\n  while (strfrmt < strfrmt_end) {\n    if (*strfrmt != L_ESC)\n      luaL_addchar(&b, *strfrmt++);\n    else if (*++strfrmt == L_ESC)\n      luaL_addchar(&b, *strfrmt++);  /* %% */\n    else { /* format item */\n      char form[MAX_FORMAT];  /* to store the format ('%...') */\n      unsigned maxitem = MAX_ITEM;  /* maximum length for the result */\n      char *buff = luaL_prepbuffsize(&b, maxitem);  /* to put result */\n      int nb = 0;  /* number of bytes in result */\n      if (++arg > top)\n        return luaL_argerror(L, arg, \"no value\");\n      strfrmt = getformat(L, strfrmt, form);\n      switch (*strfrmt++) {\n        case 'c': {\n          checkformat(L, form, L_FMTFLAGSC, 0);\n          nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg));\n          break;\n        }\n        case 'd': case 'i':\n          flags = L_FMTFLAGSI;\n          goto intcase;\n        case 'u':\n          flags = L_FMTFLAGSU;\n          goto intcase;\n        case 'o': case 'x': case 'X':\n          flags = L_FMTFLAGSX;\n         intcase: {\n          lua_Integer n = luaL_checkinteger(L, arg);\n          checkformat(L, form, flags, 1);\n          addlenmod(form, LUA_INTEGER_FRMLEN);\n          nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n);\n          break;\n        }\n        case 'a': case 'A':\n          checkformat(L, form, L_FMTFLAGSF, 1);\n          addlenmod(form, LUA_NUMBER_FRMLEN);\n          nb = lua_number2strx(L, buff, maxitem, form,\n                                  luaL_checknumber(L, arg));\n          break;\n        case 'f':\n          maxitem = MAX_ITEMF;  /* extra space for '%f' */\n          buff = luaL_prepbuffsize(&b, maxitem);\n          /* FALLTHROUGH */\n        case 'e': case 'E': case 'g': case 'G': {\n          lua_Number n = luaL_checknumber(L, arg);\n          checkformat(L, form, L_FMTFLAGSF, 1);\n          addlenmod(form, LUA_NUMBER_FRMLEN);\n          nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n);\n          break;\n        }\n        case 'p': {\n          const void *p = lua_topointer(L, arg);\n          checkformat(L, form, L_FMTFLAGSC, 0);\n          if (p == NULL) {  /* avoid calling 'printf' with argument NULL */\n            p = \"(null)\";  /* result */\n            form[strlen(form) - 1] = 's';  /* format it as a string */\n          }\n          nb = l_sprintf(buff, maxitem, form, p);\n          break;\n        }\n        case 'q': {\n          if (form[2] != '\\0')  /* modifiers? */\n            return luaL_error(L, \"specifier '%%q' cannot have modifiers\");\n          addliteral(L, &b, arg);\n          break;\n        }\n        case 's': {\n          size_t l;\n          const char *s = luaL_tolstring(L, arg, &l);\n          if (form[2] == '\\0')  /* no modifiers? */\n            luaL_addvalue(&b);  /* keep entire string */\n          else {\n            luaL_argcheck(L, l == strlen(s), arg, \"string contains zeros\");\n            checkformat(L, form, L_FMTFLAGSC, 1);\n            if (strchr(form, '.') == NULL && l >= 100) {\n              /* no precision and string is too long to be formatted */\n              luaL_addvalue(&b);  /* keep entire string */\n            }\n            else {  /* format the string into 'buff' */\n              nb = l_sprintf(buff, maxitem, form, s);\n              lua_pop(L, 1);  /* remove result from 'luaL_tolstring' */\n            }\n          }\n          break;\n        }\n        default: {  /* also treat cases 'pnLlh' */\n          return luaL_error(L, \"invalid conversion '%s' to 'format'\", form);\n        }\n      }\n      lua_assert(cast_uint(nb) < maxitem);\n      luaL_addsize(&b, cast_uint(nb));\n    }\n  }\n  luaL_pushresult(&b);\n  return 1;\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** PACK/UNPACK\n** =======================================================\n*/\n\n\n/* value used for padding */\n#if !defined(LUAL_PACKPADBYTE)\n#define LUAL_PACKPADBYTE\t\t0x00\n#endif\n\n/* maximum size for the binary representation of an integer */\n#define MAXINTSIZE\t16\n\n/* number of bits in a character */\n#define NB\tCHAR_BIT\n\n/* mask for one character (NB 1's) */\n#define MC\t((1 << NB) - 1)\n\n/* size of a lua_Integer */\n#define SZINT\t((int)sizeof(lua_Integer))\n\n\n/* dummy union to get native endianness */\nstatic const union {\n  int dummy;\n  char little;  /* true iff machine is little endian */\n} nativeendian = {1};\n\n\n/*\n** information to pack/unpack stuff\n*/\ntypedef struct Header {\n  lua_State *L;\n  int islittle;\n  unsigned maxalign;\n} Header;\n\n\n/*\n** options for pack/unpack\n*/\ntypedef enum KOption {\n  Kint,\t\t/* signed integers */\n  Kuint,\t/* unsigned integers */\n  Kfloat,\t/* single-precision floating-point numbers */\n  Knumber,\t/* Lua \"native\" floating-point numbers */\n  Kdouble,\t/* double-precision floating-point numbers */\n  Kchar,\t/* fixed-length strings */\n  Kstring,\t/* strings with prefixed length */\n  Kzstr,\t/* zero-terminated strings */\n  Kpadding,\t/* padding */\n  Kpaddalign,\t/* padding for alignment */\n  Knop\t\t/* no-op (configuration or spaces) */\n} KOption;\n\n\n/*\n** Read an integer numeral from string 'fmt' or return 'df' if\n** there is no numeral\n*/\nstatic int digit (int c) { return '0' <= c && c <= '9'; }\n\nstatic size_t getnum (const char **fmt, size_t df) {\n  if (!digit(**fmt))  /* no number? */\n    return df;  /* return default value */\n  else {\n    size_t a = 0;\n    do {\n      a = a*10 + cast_uint(*((*fmt)++) - '0');\n    } while (digit(**fmt) && a <= (MAX_SIZE - 9)/10);\n    return a;\n  }\n}\n\n\n/*\n** Read an integer numeral and raises an error if it is larger\n** than the maximum size of integers.\n*/\nstatic unsigned getnumlimit (Header *h, const char **fmt, size_t df) {\n  size_t sz = getnum(fmt, df);\n  if (l_unlikely((sz - 1u) >= MAXINTSIZE))\n    return cast_uint(luaL_error(h->L,\n               \"integral size (%d) out of limits [1,%d]\", sz, MAXINTSIZE));\n  return cast_uint(sz);\n}\n\n\n/*\n** Initialize Header\n*/\nstatic void initheader (lua_State *L, Header *h) {\n  h->L = L;\n  h->islittle = nativeendian.little;\n  h->maxalign = 1;\n}\n\n\n/*\n** Read and classify next option. 'size' is filled with option's size.\n*/\nstatic KOption getoption (Header *h, const char **fmt, size_t *size) {\n  /* dummy structure to get native alignment requirements */\n  struct cD { char c; union { LUAI_MAXALIGN; } u; };\n  int opt = *((*fmt)++);\n  *size = 0;  /* default */\n  switch (opt) {\n    case 'b': *size = sizeof(char); return Kint;\n    case 'B': *size = sizeof(char); return Kuint;\n    case 'h': *size = sizeof(short); return Kint;\n    case 'H': *size = sizeof(short); return Kuint;\n    case 'l': *size = sizeof(long); return Kint;\n    case 'L': *size = sizeof(long); return Kuint;\n    case 'j': *size = sizeof(lua_Integer); return Kint;\n    case 'J': *size = sizeof(lua_Integer); return Kuint;\n    case 'T': *size = sizeof(size_t); return Kuint;\n    case 'f': *size = sizeof(float); return Kfloat;\n    case 'n': *size = sizeof(lua_Number); return Knumber;\n    case 'd': *size = sizeof(double); return Kdouble;\n    case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;\n    case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;\n    case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;\n    case 'c':\n      *size = getnum(fmt, cast_sizet(-1));\n      if (l_unlikely(*size == cast_sizet(-1)))\n        luaL_error(h->L, \"missing size for format option 'c'\");\n      return Kchar;\n    case 'z': return Kzstr;\n    case 'x': *size = 1; return Kpadding;\n    case 'X': return Kpaddalign;\n    case ' ': break;\n    case '<': h->islittle = 1; break;\n    case '>': h->islittle = 0; break;\n    case '=': h->islittle = nativeendian.little; break;\n    case '!': {\n      const size_t maxalign = offsetof(struct cD, u);\n      h->maxalign = getnumlimit(h, fmt, maxalign);\n      break;\n    }\n    default: luaL_error(h->L, \"invalid format option '%c'\", opt);\n  }\n  return Knop;\n}\n\n\n/*\n** Read, classify, and fill other details about the next option.\n** 'psize' is filled with option's size, 'notoalign' with its\n** alignment requirements.\n** Local variable 'size' gets the size to be aligned. (Kpadal option\n** always gets its full alignment, other options are limited by\n** the maximum alignment ('maxalign'). Kchar option needs no alignment\n** despite its size.\n*/\nstatic KOption getdetails (Header *h, size_t totalsize, const char **fmt,\n                           size_t *psize, unsigned *ntoalign) {\n  KOption opt = getoption(h, fmt, psize);\n  size_t align = *psize;  /* usually, alignment follows size */\n  if (opt == Kpaddalign) {  /* 'X' gets alignment from following option */\n    if (**fmt == '\\0' || getoption(h, fmt, &align) == Kchar || align == 0)\n      luaL_argerror(h->L, 1, \"invalid next option for option 'X'\");\n  }\n  if (align <= 1 || opt == Kchar)  /* need no alignment? */\n    *ntoalign = 0;\n  else {\n    if (align > h->maxalign)  /* enforce maximum alignment */\n      align = h->maxalign;\n    if (l_unlikely(!ispow2(align))) {  /* not a power of 2? */\n      *ntoalign = 0;  /* to avoid warnings */\n      luaL_argerror(h->L, 1, \"format asks for alignment not power of 2\");\n    }\n    else {\n      /* 'szmoda' = totalsize % align */\n      unsigned szmoda = cast_uint(totalsize & (align - 1));\n      *ntoalign = cast_uint((align - szmoda) & (align - 1));\n    }\n  }\n  return opt;\n}\n\n\n/*\n** Pack integer 'n' with 'size' bytes and 'islittle' endianness.\n** The final 'if' handles the case when 'size' is larger than\n** the size of a Lua integer, correcting the extra sign-extension\n** bytes if necessary (by default they would be zeros).\n*/\nstatic void packint (luaL_Buffer *b, lua_Unsigned n,\n                     int islittle, unsigned size, int neg) {\n  char *buff = luaL_prepbuffsize(b, size);\n  unsigned i;\n  buff[islittle ? 0 : size - 1] = (char)(n & MC);  /* first byte */\n  for (i = 1; i < size; i++) {\n    n >>= NB;\n    buff[islittle ? i : size - 1 - i] = (char)(n & MC);\n  }\n  if (neg && size > SZINT) {  /* negative number need sign extension? */\n    for (i = SZINT; i < size; i++)  /* correct extra bytes */\n      buff[islittle ? i : size - 1 - i] = (char)MC;\n  }\n  luaL_addsize(b, size);  /* add result to buffer */\n}\n\n\n/*\n** Copy 'size' bytes from 'src' to 'dest', correcting endianness if\n** given 'islittle' is different from native endianness.\n*/\nstatic void copywithendian (char *dest, const char *src,\n                            unsigned size, int islittle) {\n  if (islittle == nativeendian.little)\n    memcpy(dest, src, size);\n  else {\n    dest += size - 1;\n    while (size-- != 0)\n      *(dest--) = *(src++);\n  }\n}\n\n\nstatic int str_pack (lua_State *L) {\n  luaL_Buffer b;\n  Header h;\n  const char *fmt = luaL_checkstring(L, 1);  /* format string */\n  int arg = 1;  /* current argument to pack */\n  size_t totalsize = 0;  /* accumulate total size of result */\n  initheader(L, &h);\n  lua_pushnil(L);  /* mark to separate arguments from string buffer */\n  luaL_buffinit(L, &b);\n  while (*fmt != '\\0') {\n    unsigned ntoalign;\n    size_t size;\n    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);\n    luaL_argcheck(L, size + ntoalign <= MAX_SIZE - totalsize, arg,\n                     \"result too long\");\n    totalsize += ntoalign + size;\n    while (ntoalign-- > 0)\n     luaL_addchar(&b, LUAL_PACKPADBYTE);  /* fill alignment */\n    arg++;\n    switch (opt) {\n      case Kint: {  /* signed integers */\n        lua_Integer n = luaL_checkinteger(L, arg);\n        if (size < SZINT) {  /* need overflow check? */\n          lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);\n          luaL_argcheck(L, -lim <= n && n < lim, arg, \"integer overflow\");\n        }\n        packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), (n < 0));\n        break;\n      }\n      case Kuint: {  /* unsigned integers */\n        lua_Integer n = luaL_checkinteger(L, arg);\n        if (size < SZINT)  /* need overflow check? */\n          luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),\n                           arg, \"unsigned overflow\");\n        packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), 0);\n        break;\n      }\n      case Kfloat: {  /* C float */\n        float f = (float)luaL_checknumber(L, arg);  /* get argument */\n        char *buff = luaL_prepbuffsize(&b, sizeof(f));\n        /* move 'f' to final result, correcting endianness if needed */\n        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);\n        luaL_addsize(&b, size);\n        break;\n      }\n      case Knumber: {  /* Lua float */\n        lua_Number f = luaL_checknumber(L, arg);  /* get argument */\n        char *buff = luaL_prepbuffsize(&b, sizeof(f));\n        /* move 'f' to final result, correcting endianness if needed */\n        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);\n        luaL_addsize(&b, size);\n        break;\n      }\n      case Kdouble: {  /* C double */\n        double f = (double)luaL_checknumber(L, arg);  /* get argument */\n        char *buff = luaL_prepbuffsize(&b, sizeof(f));\n        /* move 'f' to final result, correcting endianness if needed */\n        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);\n        luaL_addsize(&b, size);\n        break;\n      }\n      case Kchar: {  /* fixed-size string */\n        size_t len;\n        const char *s = luaL_checklstring(L, arg, &len);\n        luaL_argcheck(L, len <= size, arg, \"string longer than given size\");\n        luaL_addlstring(&b, s, len);  /* add string */\n        if (len < size) {  /* does it need padding? */\n          size_t psize = size - len;  /* pad size */\n          char *buff = luaL_prepbuffsize(&b, psize);\n          memset(buff, LUAL_PACKPADBYTE, psize);\n          luaL_addsize(&b, psize);\n        }\n        break;\n      }\n      case Kstring: {  /* strings with length count */\n        size_t len;\n        const char *s = luaL_checklstring(L, arg, &len);\n        luaL_argcheck(L, size >= sizeof(lua_Unsigned) ||\n                         len < ((lua_Unsigned)1 << (size * NB)),\n                         arg, \"string length does not fit in given size\");\n        /* pack length */\n        packint(&b, (lua_Unsigned)len, h.islittle, cast_uint(size), 0);\n        luaL_addlstring(&b, s, len);\n        totalsize += len;\n        break;\n      }\n      case Kzstr: {  /* zero-terminated string */\n        size_t len;\n        const char *s = luaL_checklstring(L, arg, &len);\n        luaL_argcheck(L, strlen(s) == len, arg, \"string contains zeros\");\n        luaL_addlstring(&b, s, len);\n        luaL_addchar(&b, '\\0');  /* add zero at the end */\n        totalsize += len + 1;\n        break;\n      }\n      case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE);  /* FALLTHROUGH */\n      case Kpaddalign: case Knop:\n        arg--;  /* undo increment */\n        break;\n    }\n  }\n  luaL_pushresult(&b);\n  return 1;\n}\n\n\nstatic int str_packsize (lua_State *L) {\n  Header h;\n  const char *fmt = luaL_checkstring(L, 1);  /* format string */\n  size_t totalsize = 0;  /* accumulate total size of result */\n  initheader(L, &h);\n  while (*fmt != '\\0') {\n    unsigned ntoalign;\n    size_t size;\n    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);\n    luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,\n                     \"variable-length format\");\n    size += ntoalign;  /* total space used by option */\n    luaL_argcheck(L, totalsize <= LUA_MAXINTEGER - size,\n                     1, \"format result too large\");\n    totalsize += size;\n  }\n  lua_pushinteger(L, cast_st2S(totalsize));\n  return 1;\n}\n\n\n/*\n** Unpack an integer with 'size' bytes and 'islittle' endianness.\n** If size is smaller than the size of a Lua integer and integer\n** is signed, must do sign extension (propagating the sign to the\n** higher bits); if size is larger than the size of a Lua integer,\n** it must check the unread bytes to see whether they do not cause an\n** overflow.\n*/\nstatic lua_Integer unpackint (lua_State *L, const char *str,\n                              int islittle, int size, int issigned) {\n  lua_Unsigned res = 0;\n  int i;\n  int limit = (size  <= SZINT) ? size : SZINT;\n  for (i = limit - 1; i >= 0; i--) {\n    res <<= NB;\n    res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];\n  }\n  if (size < SZINT) {  /* real size smaller than lua_Integer? */\n    if (issigned) {  /* needs sign extension? */\n      lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);\n      res = ((res ^ mask) - mask);  /* do sign extension */\n    }\n  }\n  else if (size > SZINT) {  /* must check unread bytes */\n    int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;\n    for (i = limit; i < size; i++) {\n      if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask))\n        luaL_error(L, \"%d-byte integer does not fit into Lua Integer\", size);\n    }\n  }\n  return (lua_Integer)res;\n}\n\n\nstatic int str_unpack (lua_State *L) {\n  Header h;\n  const char *fmt = luaL_checkstring(L, 1);\n  size_t ld;\n  const char *data = luaL_checklstring(L, 2, &ld);\n  size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;\n  int n = 0;  /* number of results */\n  luaL_argcheck(L, pos <= ld, 3, \"initial position out of string\");\n  initheader(L, &h);\n  while (*fmt != '\\0') {\n    unsigned ntoalign;\n    size_t size;\n    KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);\n    luaL_argcheck(L, ntoalign + size <= ld - pos, 2,\n                    \"data string too short\");\n    pos += ntoalign;  /* skip alignment */\n    /* stack space for item + next position */\n    luaL_checkstack(L, 2, \"too many results\");\n    n++;\n    switch (opt) {\n      case Kint:\n      case Kuint: {\n        lua_Integer res = unpackint(L, data + pos, h.islittle,\n                                       cast_int(size), (opt == Kint));\n        lua_pushinteger(L, res);\n        break;\n      }\n      case Kfloat: {\n        float f;\n        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);\n        lua_pushnumber(L, (lua_Number)f);\n        break;\n      }\n      case Knumber: {\n        lua_Number f;\n        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);\n        lua_pushnumber(L, f);\n        break;\n      }\n      case Kdouble: {\n        double f;\n        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);\n        lua_pushnumber(L, (lua_Number)f);\n        break;\n      }\n      case Kchar: {\n        lua_pushlstring(L, data + pos, size);\n        break;\n      }\n      case Kstring: {\n        lua_Unsigned len = (lua_Unsigned)unpackint(L, data + pos,\n                                          h.islittle, cast_int(size), 0);\n        luaL_argcheck(L, len <= ld - pos - size, 2, \"data string too short\");\n        lua_pushlstring(L, data + pos + size, cast_sizet(len));\n        pos += cast_sizet(len);  /* skip string */\n        break;\n      }\n      case Kzstr: {\n        size_t len = strlen(data + pos);\n        luaL_argcheck(L, pos + len < ld, 2,\n                         \"unfinished string for format 'z'\");\n        lua_pushlstring(L, data + pos, len);\n        pos += len + 1;  /* skip string plus final '\\0' */\n        break;\n      }\n      case Kpaddalign: case Kpadding: case Knop:\n        n--;  /* undo increment */\n        break;\n    }\n    pos += size;\n  }\n  lua_pushinteger(L, cast_st2S(pos) + 1);  /* next position */\n  return n + 1;\n}\n\n/* }====================================================== */\n\n\nstatic const luaL_Reg strlib[] = {\n  {\"byte\", str_byte},\n  {\"char\", str_char},\n  {\"dump\", str_dump},\n  {\"find\", str_find},\n  {\"format\", str_format},\n  {\"gmatch\", gmatch},\n  {\"gsub\", str_gsub},\n  {\"len\", str_len},\n  {\"lower\", str_lower},\n  {\"match\", str_match},\n  {\"rep\", str_rep},\n  {\"reverse\", str_reverse},\n  {\"sub\", str_sub},\n  {\"upper\", str_upper},\n  {\"pack\", str_pack},\n  {\"packsize\", str_packsize},\n  {\"unpack\", str_unpack},\n  {NULL, NULL}\n};\n\n\nstatic void createmetatable (lua_State *L) {\n  /* table to be metatable for strings */\n  luaL_newlibtable(L, stringmetamethods);\n  luaL_setfuncs(L, stringmetamethods, 0);\n  lua_pushliteral(L, \"\");  /* dummy string */\n  lua_pushvalue(L, -2);  /* copy table */\n  lua_setmetatable(L, -2);  /* set table as metatable for strings */\n  lua_pop(L, 1);  /* pop dummy string */\n  lua_pushvalue(L, -2);  /* get string library */\n  lua_setfield(L, -2, \"__index\");  /* metatable.__index = string */\n  lua_pop(L, 1);  /* pop metatable */\n}\n\n\n/*\n** Open string library\n*/\nLUAMOD_API int luaopen_string (lua_State *L) {\n  luaL_newlib(L, strlib);\n  createmetatable(L);\n  return 1;\n}\n\n"
  },
  {
    "path": "3rd/lua/ltable.c",
    "content": "/*\n** $Id: ltable.c $\n** Lua tables (hash)\n** See Copyright Notice in lua.h\n*/\n\n#define ltable_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n/*\n** Implementation of tables (aka arrays, objects, or hash tables).\n** Tables keep its elements in two parts: an array part and a hash part.\n** Non-negative integer keys are all candidates to be kept in the array\n** part. The actual size of the array is the largest 'n' such that\n** more than half the slots between 1 and n are in use.\n** Hash uses a mix of chained scatter table with Brent's variation.\n** A main invariant of these tables is that, if an element is not\n** in its main position (i.e. the 'original' position that its hash gives\n** to it), then the colliding element is in its own main position.\n** Hence even when the load factor reaches 100%, performance remains good.\n*/\n\n#include <math.h>\n#include <limits.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lgc.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"lvm.h\"\n\n\n/*\n** Only hash parts with at least 2^LIMFORLAST have a 'lastfree' field\n** that optimizes finding a free slot. That field is stored just before\n** the array of nodes, in the same block. Smaller tables do a complete\n** search when looking for a free slot.\n*/\n#define LIMFORLAST    3  /* log2 of real limit (8) */\n\n/*\n** The union 'Limbox' stores 'lastfree' and ensures that what follows it\n** is properly aligned to store a Node.\n*/\ntypedef struct { Node *dummy; Node follows_pNode; } Limbox_aux;\n\ntypedef union {\n  Node *lastfree;\n  char padding[offsetof(Limbox_aux, follows_pNode)];\n} Limbox;\n\n#define haslastfree(t)     ((t)->lsizenode >= LIMFORLAST)\n#define getlastfree(t)     ((cast(Limbox *, (t)->node) - 1)->lastfree)\n\n\n/*\n** MAXABITS is the largest integer such that 2^MAXABITS fits in an\n** unsigned int.\n*/\n#define MAXABITS\t(l_numbits(int) - 1)\n\n\n/*\n** MAXASIZEB is the maximum number of elements in the array part such\n** that the size of the array fits in 'size_t'.\n*/\n#define MAXASIZEB\t(MAX_SIZET/(sizeof(Value) + 1))\n\n\n/*\n** MAXASIZE is the maximum size of the array part. It is the minimum\n** between 2^MAXABITS and MAXASIZEB.\n*/\n#define MAXASIZE  \\\n    (((1u << MAXABITS) < MAXASIZEB) ? (1u << MAXABITS) : cast_uint(MAXASIZEB))\n\n/*\n** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a\n** signed int.\n*/\n#define MAXHBITS\t(MAXABITS - 1)\n\n\n/*\n** MAXHSIZE is the maximum size of the hash part. It is the minimum\n** between 2^MAXHBITS and the maximum size such that, measured in bytes,\n** it fits in a 'size_t'.\n*/\n#define MAXHSIZE\tluaM_limitN(1 << MAXHBITS, Node)\n\n\n/*\n** When the original hash value is good, hashing by a power of 2\n** avoids the cost of '%'.\n*/\n#define hashpow2(t,n)\t\t(gnode(t, lmod((n), sizenode(t))))\n\n/*\n** for other types, it is better to avoid modulo by power of 2, as\n** they can have many 2 factors.\n*/\n#define hashmod(t,n)\t(gnode(t, ((n) % ((sizenode(t)-1u)|1u))))\n\n\n#define hashstr(t,str)\t\thashpow2(t, (str)->hash)\n#define hashboolean(t,p)\thashpow2(t, p)\n\n\n#define hashpointer(t,p)\thashmod(t, point2uint(p))\n\n\n#define dummynode\t\t(&dummynode_)\n\n/*\n** Common hash part for tables with empty hash parts. That allows all\n** tables to have a hash part, avoiding an extra check (\"is there a hash\n** part?\") when indexing. Its sole node has an empty value and a key\n** (DEADKEY, NULL) that is different from any valid TValue.\n*/\nstatic const Node dummynode_ = {\n  {{NULL}, LUA_VEMPTY,  /* value's value and type */\n   LUA_TDEADKEY, 0, {NULL}}  /* key type, next, and key value */\n};\n\n\nstatic const TValue absentkey = {ABSTKEYCONSTANT};\n\n\n/*\n** Hash for integers. To allow a good hash, use the remainder operator\n** ('%'). If integer fits as a non-negative int, compute an int\n** remainder, which is faster. Otherwise, use an unsigned-integer\n** remainder, which uses all bits and ensures a non-negative result.\n*/\nstatic Node *hashint (const Table *t, lua_Integer i) {\n  lua_Unsigned ui = l_castS2U(i);\n  if (ui <= cast_uint(INT_MAX))\n    return gnode(t, cast_int(ui) % cast_int((sizenode(t)-1) | 1));\n  else\n    return hashmod(t, ui);\n}\n\n\n/*\n** Hash for floating-point numbers.\n** The main computation should be just\n**     n = frexp(n, &i); return (n * INT_MAX) + i\n** but there are some numerical subtleties.\n** In a two-complement representation, INT_MAX may not have an exact\n** representation as a float, but INT_MIN does; because the absolute\n** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the\n** absolute value of the product 'frexp * -INT_MIN' is smaller or equal\n** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when\n** adding 'i'; the use of '~u' (instead of '-u') avoids problems with\n** INT_MIN.\n*/\n#if !defined(l_hashfloat)\nstatic unsigned l_hashfloat (lua_Number n) {\n  int i;\n  lua_Integer ni;\n  n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);\n  if (!lua_numbertointeger(n, &ni)) {  /* is 'n' inf/-inf/NaN? */\n    lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));\n    return 0;\n  }\n  else {  /* normal case */\n    unsigned int u = cast_uint(i) + cast_uint(ni);\n    return (u <= cast_uint(INT_MAX) ? u : ~u);\n  }\n}\n#endif\n\n\n/*\n** returns the 'main' position of an element in a table (that is,\n** the index of its hash value).\n*/\nstatic Node *mainpositionTV (const Table *t, const TValue *key) {\n  switch (ttypetag(key)) {\n    case LUA_VNUMINT: {\n      lua_Integer i = ivalue(key);\n      return hashint(t, i);\n    }\n    case LUA_VNUMFLT: {\n      lua_Number n = fltvalue(key);\n      return hashmod(t, l_hashfloat(n));\n    }\n    case LUA_VSHRSTR: {\n      TString *ts = tsvalue(key);\n      return hashstr(t, ts);\n    }\n    case LUA_VLNGSTR: {\n      TString *ts = tsvalue(key);\n      return hashpow2(t, luaS_hashlongstr(ts));\n    }\n    case LUA_VFALSE:\n      return hashboolean(t, 0);\n    case LUA_VTRUE:\n      return hashboolean(t, 1);\n    case LUA_VLIGHTUSERDATA: {\n      void *p = pvalue(key);\n      return hashpointer(t, p);\n    }\n    case LUA_VLCF: {\n      lua_CFunction f = fvalue(key);\n      return hashpointer(t, f);\n    }\n    default: {\n      GCObject *o = gcvalue(key);\n      return hashpointer(t, o);\n    }\n  }\n}\n\n\nl_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {\n  TValue key;\n  getnodekey(cast(lua_State *, NULL), &key, nd);\n  return mainpositionTV(t, &key);\n}\n\n\n/*\n** Check whether key 'k1' is equal to the key in node 'n2'. This\n** equality is raw, so there are no metamethods. Floats with integer\n** values have been normalized, so integers cannot be equal to\n** floats. It is assumed that 'eqshrstr' is simply pointer equality,\n** so that short strings are handled in the default case.  The flag\n** 'deadok' means to accept dead keys as equal to their original values.\n** (Only collectable objects can produce dead keys.) Note that dead\n** long strings are also compared by identity.  Once a key is dead,\n** its corresponding value may be collected, and then another value\n** can be created with the same address. If this other value is given\n** to 'next', 'equalkey' will signal a false positive. In a regular\n** traversal, this situation should never happen, as all keys given to\n** 'next' came from the table itself, and therefore could not have been\n** collected. Outside a regular traversal, we have garbage in, garbage\n** out. What is relevant is that this false positive does not break\n** anything.  (In particular, 'next' will return some other valid item\n** on the table or nil.)\n*/\nstatic int equalkey (const TValue *k1, const Node *n2, int deadok) {\n  if (rawtt(k1) != keytt(n2)) {  /* not the same variants? */\n    if (keyisshrstr(n2) && ttislngstring(k1)) {\n      /* an external string can be equal to a short-string key */\n      return luaS_eqstr(tsvalue(k1), keystrval(n2));\n    }\n    else if (deadok && keyisdead(n2) && iscollectable(k1)) {\n      /* a collectable value can be equal to a dead key */\n      return gcvalue(k1) == gcvalueraw(keyval(n2));\n   }\n   else\n     return 0;  /* otherwise, different variants cannot be equal */\n  }\n  else {  /* equal variants */\n    switch (keytt(n2)) {\n      case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:\n        return 1;\n      case LUA_VNUMINT:\n        return (ivalue(k1) == keyival(n2));\n      case LUA_VNUMFLT:\n        return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));\n      case LUA_VLIGHTUSERDATA:\n        return pvalue(k1) == pvalueraw(keyval(n2));\n      case LUA_VLCF:\n        return fvalue(k1) == fvalueraw(keyval(n2));\n      case ctb(LUA_VLNGSTR):\n        return luaS_eqstr(tsvalue(k1), keystrval(n2));\n      case ctb(LUA_VSHRSTR):\n        /* short strings can be from other VM */\n        return eqshrstr(tsvalue(k1), keystrval(n2));\n      default:\n        return gcvalue(k1) == gcvalueraw(keyval(n2));\n    }\n  }\n}\n\n\n/*\n** \"Generic\" get version. (Not that generic: not valid for integers,\n** which may be in array part, nor for floats with integral values.)\n** See explanation about 'deadok' in function 'equalkey'.\n*/\nstatic const TValue *getgeneric (Table *t, const TValue *key, int deadok) {\n  Node *n = mainpositionTV(t, key);\n  for (;;) {  /* check whether 'key' is somewhere in the chain */\n    if (equalkey(key, n, deadok))\n      return gval(n);  /* that's it */\n    else {\n      int nx = gnext(n);\n      if (nx == 0)\n        return &absentkey;  /* not found */\n      n += nx;\n    }\n  }\n}\n\n\n/*\n** Return the index 'k' (converted to an unsigned) if it is inside\n** the range [1, limit].\n*/\nstatic unsigned checkrange (lua_Integer k, unsigned limit) {\n  return (l_castS2U(k) - 1u < limit) ? cast_uint(k) : 0;\n}\n\n\n/*\n** Return the index 'k' if 'k' is an appropriate key to live in the\n** array part of a table, 0 otherwise.\n*/\n#define arrayindex(k)\tcheckrange(k, MAXASIZE)\n\n\n/*\n** Check whether an integer key is in the array part of a table and\n** return its index there, or zero.\n*/\n#define ikeyinarray(t,k)\tcheckrange(k, t->asize)\n\n\n/*\n** Check whether a key is in the array part of a table and return its\n** index there, or zero.\n*/\nstatic unsigned keyinarray (Table *t, const TValue *key) {\n  return (ttisinteger(key)) ? ikeyinarray(t, ivalue(key)) : 0;\n}\n\n\n/*\n** returns the index of a 'key' for table traversals. First goes all\n** elements in the array part, then elements in the hash part. The\n** beginning of a traversal is signaled by 0.\n*/\nstatic unsigned findindex (lua_State *L, Table *t, TValue *key,\n                               unsigned asize) {\n  unsigned int i;\n  if (ttisnil(key)) return 0;  /* first iteration */\n  i = keyinarray(t, key);\n  if (i != 0)  /* is 'key' inside array part? */\n    return i;  /* yes; that's the index */\n  else {\n    const TValue *n = getgeneric(t, key, 1);\n    if (l_unlikely(isabstkey(n)))\n      luaG_runerror(L, \"invalid key to 'next'\");  /* key not found */\n    i = cast_uint(nodefromval(n) - gnode(t, 0));  /* key index in hash table */\n    /* hash elements are numbered after array ones */\n    return (i + 1) + asize;\n  }\n}\n\n\nint luaH_next (lua_State *L, Table *t, StkId key) {\n  unsigned int asize = t->asize;\n  unsigned int i = findindex(L, t, s2v(key), asize);  /* find original key */\n  for (; i < asize; i++) {  /* try first array part */\n    lu_byte tag = *getArrTag(t, i);\n    if (!tagisempty(tag)) {  /* a non-empty entry? */\n      setivalue(s2v(key), cast_int(i) + 1);\n      farr2val(t, i, tag, s2v(key + 1));\n      return 1;\n    }\n  }\n  for (i -= asize; i < sizenode(t); i++) {  /* hash part */\n    if (!isempty(gval(gnode(t, i)))) {  /* a non-empty entry? */\n      Node *n = gnode(t, i);\n      getnodekey(L, s2v(key), n);\n      setobj2s(L, key + 1, gval(n));\n      return 1;\n    }\n  }\n  return 0;  /* no more elements */\n}\n\n\n/* Extra space in Node array if it has a lastfree entry */\n#define extraLastfree(t)\t(haslastfree(t) ? sizeof(Limbox) : 0)\n\n/* 'node' size in bytes */\nstatic size_t sizehash (Table *t) {\n  return cast_sizet(sizenode(t)) * sizeof(Node) + extraLastfree(t);\n}\n\n\nstatic void freehash (lua_State *L, Table *t) {\n  if (!isdummy(t)) {\n    /* get pointer to the beginning of Node array */\n    char *arr = cast_charp(t->node) - extraLastfree(t);\n    luaM_freearray(L, arr, sizehash(t));\n  }\n}\n\n\n/*\n** {=============================================================\n** Rehash\n** ==============================================================\n*/\n\nstatic int insertkey (Table *t, const TValue *key, TValue *value);\nstatic void newcheckedkey (Table *t, const TValue *key, TValue *value);\n\n\n/*\n** Structure to count the keys in a table.\n** 'total' is the total number of keys in the table.\n** 'na' is the number of *array indices* in the table (see 'arrayindex').\n** 'deleted' is true if there are deleted nodes in the hash part.\n** 'nums' is a \"count array\" where 'nums[i]' is the number of integer\n** keys between 2^(i - 1) + 1 and 2^i. Note that 'na' is the summation\n** of 'nums'.\n*/\ntypedef struct {\n  unsigned total;\n  unsigned na;\n  int deleted;\n  unsigned nums[MAXABITS + 1];\n} Counters;\n\n\n/*\n** Check whether it is worth to use 'na' array entries instead of 'nh'\n** hash nodes. (A hash node uses ~3 times more memory than an array\n** entry: Two values plus 'next' versus one value.) Evaluate with size_t\n** to avoid overflows.\n*/\n#define arrayXhash(na,nh)\t(cast_sizet(na) <= cast_sizet(nh) * 3)\n\n/*\n** Compute the optimal size for the array part of table 't'.\n** This size maximizes the number of elements going to the array part\n** while satisfying the condition 'arrayXhash' with the use of memory if\n** all those elements went to the hash part.\n** 'ct->na' enters with the total number of array indices in the table\n** and leaves with the number of keys that will go to the array part;\n** return the optimal size for the array part.\n*/\nstatic unsigned computesizes (Counters *ct) {\n  int i;\n  unsigned int twotoi;  /* 2^i (candidate for optimal size) */\n  unsigned int a = 0;  /* number of elements smaller than 2^i */\n  unsigned int na = 0;  /* number of elements to go to array part */\n  unsigned int optimal = 0;  /* optimal size for array part */\n  /* traverse slices while 'twotoi' does not overflow and total of array\n     indices still can satisfy 'arrayXhash' against the array size */\n  for (i = 0, twotoi = 1;\n       twotoi > 0 && arrayXhash(twotoi, ct->na);\n       i++, twotoi *= 2) {\n    unsigned nums = ct->nums[i];\n    a += nums;\n    if (nums > 0 &&  /* grows array only if it gets more elements... */\n        arrayXhash(twotoi, a)) {  /* ...while using \"less memory\" */\n      optimal = twotoi;  /* optimal size (till now) */\n      na = a;  /* all elements up to 'optimal' will go to array part */\n    }\n  }\n  ct->na = na;\n  return optimal;\n}\n\n\nstatic void countint (lua_Integer key, Counters *ct) {\n  unsigned int k = arrayindex(key);\n  if (k != 0) {  /* is 'key' an array index? */\n    ct->nums[luaO_ceillog2(k)]++;  /* count as such */\n    ct->na++;\n  }\n}\n\n\nl_sinline int arraykeyisempty (const Table *t, unsigned key) {\n  int tag = *getArrTag(t, key - 1);\n  return tagisempty(tag);\n}\n\n\n/*\n** Count keys in array part of table 't'.\n*/\nstatic void numusearray (const Table *t, Counters *ct) {\n  int lg;\n  unsigned int ttlg;  /* 2^lg */\n  unsigned int ause = 0;  /* summation of 'nums' */\n  unsigned int i = 1;  /* index to traverse all array keys */\n  unsigned int asize = t->asize;\n  /* traverse each slice */\n  for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {\n    unsigned int lc = 0;  /* counter */\n    unsigned int lim = ttlg;\n    if (lim > asize) {\n      lim = asize;  /* adjust upper limit */\n      if (i > lim)\n        break;  /* no more elements to count */\n    }\n    /* count elements in range (2^(lg - 1), 2^lg] */\n    for (; i <= lim; i++) {\n      if (!arraykeyisempty(t, i))\n        lc++;\n    }\n    ct->nums[lg] += lc;\n    ause += lc;\n  }\n  ct->total += ause;\n  ct->na += ause;\n}\n\n\n/*\n** Count keys in hash part of table 't'. As this only happens during\n** a rehash, all nodes have been used. A node can have a nil value only\n** if it was deleted after being created.\n*/\nstatic void numusehash (const Table *t, Counters *ct) {\n  unsigned i = sizenode(t);\n  unsigned total = 0;\n  while (i--) {\n    Node *n = &t->node[i];\n    if (isempty(gval(n))) {\n      lua_assert(!keyisnil(n));  /* entry was deleted; key cannot be nil */\n      ct->deleted = 1;\n    }\n    else {\n      total++;\n      if (keyisinteger(n))\n        countint(keyival(n), ct);\n    }\n  }\n  ct->total += total;\n}\n\n\n/*\n** Convert an \"abstract size\" (number of slots in an array) to\n** \"concrete size\" (number of bytes in the array).\n*/\nstatic size_t concretesize (unsigned int size) {\n  if (size == 0)\n    return 0;\n  else  /* space for the two arrays plus an unsigned in between */\n    return size * (sizeof(Value) + 1) + sizeof(unsigned);\n}\n\n\n/*\n** Resize the array part of a table. If new size is equal to the old,\n** do nothing. Else, if new size is zero, free the old array. (It must\n** be present, as the sizes are different.) Otherwise, allocate a new\n** array, move the common elements to new proper position, and then\n** frees the old array.\n** We could reallocate the array, but we still would need to move the\n** elements to their new position, so the copy implicit in realloc is a\n** waste. Moreover, most allocators will move the array anyway when the\n** new size is double the old one (the most common case).\n*/\nstatic Value *resizearray (lua_State *L , Table *t,\n                               unsigned oldasize,\n                               unsigned newasize) {\n  if (oldasize == newasize)\n    return t->array;  /* nothing to be done */\n  else if (newasize == 0) {  /* erasing array? */\n    Value *op = t->array - oldasize;  /* original array's real address */\n    luaM_freemem(L, op, concretesize(oldasize));  /* free it */\n    return NULL;\n  }\n  else {\n    size_t newasizeb = concretesize(newasize);\n    Value *np = cast(Value *,\n                  luaM_reallocvector(L, NULL, 0, newasizeb, lu_byte));\n    if (np == NULL)  /* allocation error? */\n      return NULL;\n    np += newasize;  /* shift pointer to the end of value segment */\n    if (oldasize > 0) {\n      /* move common elements to new position */\n      size_t oldasizeb = concretesize(oldasize);\n      Value *op = t->array;  /* original array */\n      unsigned tomove = (oldasize < newasize) ? oldasize : newasize;\n      size_t tomoveb = (oldasize < newasize) ? oldasizeb : newasizeb;\n      lua_assert(tomoveb > 0);\n      memcpy(np - tomove, op - tomove, tomoveb);\n      luaM_freemem(L, op - oldasize, oldasizeb);  /* free old block */\n    }\n    return np;\n  }\n}\n\n\n/*\n** Creates an array for the hash part of a table with the given\n** size, or reuses the dummy node if size is zero.\n** The computation for size overflow is in two steps: the first\n** comparison ensures that the shift in the second one does not\n** overflow.\n*/\nstatic void setnodevector (lua_State *L, Table *t, unsigned size) {\n  if (size == 0) {  /* no elements to hash part? */\n    t->node = cast(Node *, dummynode);  /* use common 'dummynode' */\n    t->lsizenode = 0;\n    setdummy(t);  /* signal that it is using dummy node */\n  }\n  else {\n    int i;\n    int lsize = luaO_ceillog2(size);\n    if (lsize > MAXHBITS || (1 << lsize) > MAXHSIZE)\n      luaG_runerror(L, \"table overflow\");\n    size = twoto(lsize);\n    if (lsize < LIMFORLAST)  /* no 'lastfree' field? */\n      t->node = luaM_newvector(L, size, Node);\n    else {\n      size_t bsize = size * sizeof(Node) + sizeof(Limbox);\n      char *node = luaM_newblock(L, bsize);\n      t->node = cast(Node *, node + sizeof(Limbox));\n      getlastfree(t) = gnode(t, size);  /* all positions are free */\n    }\n    t->lsizenode = cast_byte(lsize);\n    setnodummy(t);\n    for (i = 0; i < cast_int(size); i++) {\n      Node *n = gnode(t, i);\n      gnext(n) = 0;\n      setnilkey(n);\n      setempty(gval(n));\n    }\n  }\n}\n\n\n/*\n** (Re)insert all elements from the hash part of 'ot' into table 't'.\n*/\nstatic void reinserthash (lua_State *L, Table *ot, Table *t) {\n  unsigned j;\n  unsigned size = sizenode(ot);\n  for (j = 0; j < size; j++) {\n    Node *old = gnode(ot, j);\n    if (!isempty(gval(old))) {\n      /* doesn't need barrier/invalidate cache, as entry was\n         already present in the table */\n      TValue k;\n      getnodekey(L, &k, old);\n      newcheckedkey(t, &k, gval(old));\n    }\n  }\n}\n\n\n/*\n** Exchange the hash part of 't1' and 't2'. (In 'flags', only the\n** dummy bit must be exchanged: The 'isrealasize' is not related\n** to the hash part, and the metamethod bits do not change during\n** a resize, so the \"real\" table can keep their values.)\n*/\nstatic void exchangehashpart (Table *t1, Table *t2) {\n  lu_byte lsizenode = t1->lsizenode;\n  Node *node = t1->node;\n  int bitdummy1 = t1->flags & BITDUMMY;\n  t1->lsizenode = t2->lsizenode;\n  t1->node = t2->node;\n  t1->flags = cast_byte((t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY));\n  t2->lsizenode = lsizenode;\n  t2->node = node;\n  t2->flags = cast_byte((t2->flags & NOTBITDUMMY) | bitdummy1);\n}\n\n\n/*\n** Re-insert into the new hash part of a table the elements from the\n** vanishing slice of the array part.\n*/\nstatic void reinsertOldSlice (Table *t, unsigned oldasize,\n                                        unsigned newasize) {\n  unsigned i;\n  for (i = newasize; i < oldasize; i++) {  /* traverse vanishing slice */\n    lu_byte tag = *getArrTag(t, i);\n    if (!tagisempty(tag)) {  /* a non-empty entry? */\n      TValue key, aux;\n      setivalue(&key, l_castU2S(i) + 1);  /* make the key */\n      farr2val(t, i, tag, &aux);  /* copy value into 'aux' */\n      insertkey(t, &key, &aux);  /* insert entry into the hash part */\n    }\n  }\n}\n\n\n/*\n** Clear new slice of the array.\n*/\nstatic void clearNewSlice (Table *t, unsigned oldasize, unsigned newasize) {\n  for (; oldasize < newasize; oldasize++)\n    *getArrTag(t, oldasize) = LUA_VEMPTY;\n}\n\n\n/*\n** Resize table 't' for the new given sizes. Both allocations (for\n** the hash part and for the array part) can fail, which creates some\n** subtleties. If the first allocation, for the hash part, fails, an\n** error is raised and that is it. Otherwise, it copies the elements from\n** the shrinking part of the array (if it is shrinking) into the new\n** hash. Then it reallocates the array part.  If that fails, the table\n** is in its original state; the function frees the new hash part and then\n** raises the allocation error. Otherwise, it sets the new hash part\n** into the table, initializes the new part of the array (if any) with\n** nils and reinserts the elements of the old hash back into the new\n** parts of the table.\n** Note that if the new size for the array part ('newasize') is equal to\n** the old one ('oldasize'), this function will do nothing with that\n** part.\n*/\nvoid luaH_resize (lua_State *L, Table *t, unsigned newasize,\n                                          unsigned nhsize) {\n  Table newt;  /* to keep the new hash part */\n  unsigned oldasize = t->asize;\n  Value *newarray;\n  if (newasize > MAXASIZE)\n    luaG_runerror(L, \"table overflow\");\n  /* create new hash part with appropriate size into 'newt' */\n  newt.flags = 0;\n  setnodevector(L, &newt, nhsize);\n  if (newasize < oldasize) {  /* will array shrink? */\n    /* re-insert into the new hash the elements from vanishing slice */\n    exchangehashpart(t, &newt);  /* pretend table has new hash */\n    reinsertOldSlice(t, oldasize, newasize);\n    exchangehashpart(t, &newt);  /* restore old hash (in case of errors) */\n  }\n  /* allocate new array */\n  newarray = resizearray(L, t, oldasize, newasize);\n  if (l_unlikely(newarray == NULL && newasize > 0)) {  /* allocation failed? */\n    freehash(L, &newt);  /* release new hash part */\n    luaM_error(L);  /* raise error (with array unchanged) */\n  }\n  /* allocation ok; initialize new part of the array */\n  exchangehashpart(t, &newt);  /* 't' has the new hash ('newt' has the old) */\n  t->array = newarray;  /* set new array part */\n  t->asize = newasize;\n  if (newarray != NULL)\n    *lenhint(t) = newasize / 2u;  /* set an initial hint */\n  clearNewSlice(t, oldasize, newasize);\n  /* re-insert elements from old hash part into new parts */\n  reinserthash(L, &newt, t);  /* 'newt' now has the old hash */\n  freehash(L, &newt);  /* free old hash part */\n}\n\n\nvoid luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {\n  unsigned nsize = allocsizenode(t);\n  luaH_resize(L, t, nasize, nsize);\n}\n\n\n/*\n** Rehash a table. First, count its keys. If there are array indices\n** outside the array part, compute the new best size for that part.\n** Then, resize the table.\n*/\nstatic void rehash (lua_State *L, Table *t, const TValue *ek) {\n  unsigned asize;  /* optimal size for array part */\n  Counters ct;\n  unsigned i;\n  unsigned nsize;  /* size for the hash part */\n  /* reset counts */\n  for (i = 0; i <= MAXABITS; i++) ct.nums[i] = 0;\n  ct.na = 0;\n  ct.deleted = 0;\n  ct.total = 1;  /* count extra key */\n  if (ttisinteger(ek))\n    countint(ivalue(ek), &ct);  /* extra key may go to array */\n  numusehash(t, &ct);  /* count keys in hash part */\n  if (ct.na == 0) {\n    /* no new keys to enter array part; keep it with the same size */\n    asize = t->asize;\n  }\n  else {  /* compute best size for array part */\n    numusearray(t, &ct);  /* count keys in array part */\n    asize = computesizes(&ct);  /* compute new size for array part */\n  }\n  /* all keys not in the array part go to the hash part */\n  nsize = ct.total - ct.na;\n  if (ct.deleted) {  /* table has deleted entries? */\n    /* insertion-deletion-insertion: give hash some extra size to\n       avoid repeated resizings */\n    nsize += nsize >> 2;\n  }\n  /* resize the table to new computed sizes */\n  luaH_resize(L, t, asize, nsize);\n}\n\n/*\n** }=============================================================\n*/\n\n\nTable *luaH_new (lua_State *L) {\n  GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));\n  Table *t = gco2t(o);\n  t->metatable = NULL;\n  t->flags = maskflags;  /* table has no metamethod fields */\n  t->array = NULL;\n  t->asize = 0;\n  setnodevector(L, t, 0);\n  return t;\n}\n\n\nlu_mem luaH_size (Table *t) {\n  lu_mem sz = cast(lu_mem, sizeof(Table)) + concretesize(t->asize);\n  if (!isdummy(t))\n    sz += sizehash(t);\n  return sz;\n}\n\n\n/*\n** Frees a table.\n*/\nvoid luaH_free (lua_State *L, Table *t) {\n  freehash(L, t);\n  resizearray(L, t, t->asize, 0);\n  luaM_free(L, t);\n}\n\n\nstatic Node *getfreepos (Table *t) {\n  if (haslastfree(t)) {  /* does it have 'lastfree' information? */\n    /* look for a spot before 'lastfree', updating 'lastfree' */\n    while (getlastfree(t) > t->node) {\n      Node *free = --getlastfree(t);\n      if (keyisnil(free))\n        return free;\n    }\n  }\n  else {  /* no 'lastfree' information */\n    unsigned i = sizenode(t);\n    while (i--) {  /* do a linear search */\n      Node *free = gnode(t, i);\n      if (keyisnil(free))\n        return free;\n    }\n  }\n  return NULL;  /* could not find a free place */\n}\n\n\n\n/*\n** Inserts a new key into a hash table; first, check whether key's main\n** position is free. If not, check whether colliding node is in its main\n** position or not: if it is not, move colliding node to an empty place\n** and put new key in its main position; otherwise (colliding node is in\n** its main position), new key goes to an empty position. Return 0 if\n** could not insert key (could not find a free space).\n*/\nstatic int insertkey (Table *t, const TValue *key, TValue *value) {\n  Node *mp = mainpositionTV(t, key);\n  /* table cannot already contain the key */\n  lua_assert(isabstkey(getgeneric(t, key, 0)));\n  if (!isempty(gval(mp)) || isdummy(t)) {  /* main position is taken? */\n    Node *othern;\n    Node *f = getfreepos(t);  /* get a free place */\n    if (f == NULL)  /* cannot find a free place? */\n      return 0;\n    lua_assert(!isdummy(t));\n    othern = mainpositionfromnode(t, mp);\n    if (othern != mp) {  /* is colliding node out of its main position? */\n      /* yes; move colliding node into free position */\n      while (othern + gnext(othern) != mp)  /* find previous */\n        othern += gnext(othern);\n      gnext(othern) = cast_int(f - othern);  /* rechain to point to 'f' */\n      *f = *mp;  /* copy colliding node into free pos. (mp->next also goes) */\n      if (gnext(mp) != 0) {\n        gnext(f) += cast_int(mp - f);  /* correct 'next' */\n        gnext(mp) = 0;  /* now 'mp' is free */\n      }\n      setempty(gval(mp));\n    }\n    else {  /* colliding node is in its own main position */\n      /* new node will go into free position */\n      if (gnext(mp) != 0)\n        gnext(f) = cast_int((mp + gnext(mp)) - f);  /* chain new position */\n      else lua_assert(gnext(f) == 0);\n      gnext(mp) = cast_int(f - mp);\n      mp = f;\n    }\n  }\n  setnodekey(mp, key);\n  lua_assert(isempty(gval(mp)));\n  setobj2t(cast(lua_State *, 0), gval(mp), value);\n  return 1;\n}\n\n\n/*\n** Insert a key in a table where there is space for that key, the\n** key is valid, and the value is not nil.\n*/\nstatic void newcheckedkey (Table *t, const TValue *key, TValue *value) {\n  unsigned i = keyinarray(t, key);\n  if (i > 0)  /* is key in the array part? */\n    obj2arr(t, i - 1, value);  /* set value in the array */\n  else {\n    int done = insertkey(t, key, value);  /* insert key in the hash part */\n    lua_assert(done);  /* it cannot fail */\n    cast(void, done);  /* to avoid warnings */\n  }\n}\n\n\nstatic void luaH_newkey (lua_State *L, Table *t, const TValue *key,\n                                                 TValue *value) {\n  if (l_unlikely(isshared(t)))\n    luaG_runerror(L, \"attempt to change a shared table\");\n  if (!ttisnil(value)) {  /* do not insert nil values */\n    int done = insertkey(t, key, value);\n    if (!done) {  /* could not find a free place? */\n      rehash(L, t, key);  /* grow table */\n      newcheckedkey(t, key, value);  /* insert key in grown table */\n    }\n    luaC_barrierback(L, obj2gco(t), key);\n    /* for debugging only: any new key may force an emergency collection */\n    condchangemem(L, (void)0, (void)0, 1);\n  }\n}\n\n\nstatic const TValue *getintfromhash (Table *t, lua_Integer key) {\n  Node *n = hashint(t, key);\n  lua_assert(!ikeyinarray(t, key));\n  for (;;) {  /* check whether 'key' is somewhere in the chain */\n    if (keyisinteger(n) && keyival(n) == key)\n      return gval(n);  /* that's it */\n    else {\n      int nx = gnext(n);\n      if (nx == 0) break;\n      n += nx;\n    }\n  }\n  return &absentkey;\n}\n\n\nstatic int hashkeyisempty (Table *t, lua_Unsigned key) {\n  const TValue *val = getintfromhash(t, l_castU2S(key));\n  return isempty(val);\n}\n\n\nstatic lu_byte finishnodeget (const TValue *val, TValue *res) {\n  if (!ttisnil(val)) {\n    setobj(((lua_State*)NULL), res, val);\n  }\n  return ttypetag(val);\n}\n\n\nlu_byte luaH_getint (Table *t, lua_Integer key, TValue *res) {\n  unsigned k = ikeyinarray(t, key);\n  if (k > 0) {\n    lu_byte tag = *getArrTag(t, k - 1);\n    if (!tagisempty(tag))\n      farr2val(t, k - 1, tag, res);\n    return tag;\n  }\n  else\n    return finishnodeget(getintfromhash(t, key), res);\n}\n\n\n/*\n** search function for short strings\n*/\nconst TValue *luaH_Hgetshortstr (Table *t, TString *key) {\n  Node *n = hashstr(t, key);\n  lua_assert(strisshr(key));\n  for (;;) {  /* check whether 'key' is somewhere in the chain */\n    if (keyisshrstr(n) && eqshrstr(keystrval(n), key))\n      return gval(n);  /* that's it */\n    else {\n      int nx = gnext(n);\n      if (nx == 0)\n        return &absentkey;  /* not found */\n      n += nx;\n    }\n  }\n}\n\n\nlu_byte luaH_getshortstr (Table *t, TString *key, TValue *res) {\n  return finishnodeget(luaH_Hgetshortstr(t, key), res);\n}\n\n\nstatic const TValue *Hgetlongstr (Table *t, TString *key) {\n  TValue ko;\n  lua_assert(!strisshr(key));\n  setsvalue(cast(lua_State *, NULL), &ko, key);\n  return getgeneric(t, &ko, 0);  /* for long strings, use generic case */\n}\n\n\nstatic const TValue *Hgetstr (Table *t, TString *key) {\n  if (strisshr(key))\n    return luaH_Hgetshortstr(t, key);\n  else\n    return Hgetlongstr(t, key);\n}\n\n\nlu_byte luaH_getstr (Table *t, TString *key, TValue *res) {\n  return finishnodeget(Hgetstr(t, key), res);\n}\n\n\n/*\n** main search function\n*/\nlu_byte luaH_get (Table *t, const TValue *key, TValue *res) {\n  const TValue *slot;\n  switch (ttypetag(key)) {\n    case LUA_VSHRSTR:\n      slot = luaH_Hgetshortstr(t, tsvalue(key));\n      break;\n    case LUA_VNUMINT:\n      return luaH_getint(t, ivalue(key), res);\n    case LUA_VNIL:\n      slot = &absentkey;\n      break;\n    case LUA_VNUMFLT: {\n      lua_Integer k;\n      if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */\n        return luaH_getint(t, k, res);  /* use specialized version */\n      /* else... */\n    }  /* FALLTHROUGH */\n    default:\n      slot = getgeneric(t, key, 0);\n      break;\n  }\n  return finishnodeget(slot, res);\n}\n\n\n/*\n** When a 'pset' cannot be completed, this function returns an encoding\n** of its result, to be used by 'luaH_finishset'.\n*/\nstatic int retpsetcode (Table *t, const TValue *slot) {\n  if (isabstkey(slot))\n    return HNOTFOUND;  /* no slot with that key */\n  else  /* return node encoded */\n    return cast_int((cast(Node*, slot) - t->node)) + HFIRSTNODE;\n}\n\n\nstatic int finishnodeset (Table *t, const TValue *slot, TValue *val) {\n  if (!ttisnil(slot)) {\n    setobj(((lua_State*)NULL), cast(TValue*, slot), val);\n    return HOK;  /* success */\n  }\n  else\n    return retpsetcode(t, slot);\n}\n\n\nstatic int rawfinishnodeset (const TValue *slot, TValue *val) {\n  if (isabstkey(slot))\n    return 0;  /* no slot with that key */\n  else {\n    setobj(((lua_State*)NULL), cast(TValue*, slot), val);\n    return 1;  /* success */\n  }\n}\n\n\nint luaH_psetint (Table *t, lua_Integer key, TValue *val) {\n  lua_assert(!ikeyinarray(t, key));\n  return finishnodeset(t, getintfromhash(t, key), val);\n}\n\n\nstatic int psetint (Table *t, lua_Integer key, TValue *val) {\n  int hres;\n  luaH_fastseti(t, key, val, hres);\n  return hres;\n}\n\n\n/*\n** This function could be just this:\n**    return finishnodeset(t, luaH_Hgetshortstr(t, key), val);\n** However, it optimizes the common case created by constructors (e.g.,\n** {x=1, y=2}), which creates a key in a table that has no metatable,\n** it is not old/black, and it already has space for the key.\n*/\n\nint luaH_psetshortstr (Table *t, TString *key, TValue *val) {\n  const TValue *slot = luaH_Hgetshortstr(t, key);\n  if (!ttisnil(slot)) {  /* key already has a value? (all too common) */\n    setobj(((lua_State*)NULL), cast(TValue*, slot), val);  /* update it */\n    return HOK;  /* done */\n  }\n  else if (checknoTM(t->metatable, TM_NEWINDEX)) {  /* no metamethod? */\n    if (ttisnil(val))  /* new value is nil? */\n      return HOK;  /* done (value is already nil/absent) */\n    if (isabstkey(slot) &&  /* key is absent? */\n       !(isblack(t) && iswhite(key))) {  /* and don't need barrier? */\n      TValue tk;  /* key as a TValue */\n      setsvalue(cast(lua_State *, NULL), &tk, key);\n      if (insertkey(t, &tk, val)) {  /* insert key, if there is space */\n        invalidateTMcache(t);\n        return HOK;\n      }\n    }\n  }\n  /* Else, either table has new-index metamethod, or it needs barrier,\n     or it needs to rehash for the new key. In any of these cases, the\n     operation cannot be completed here. Return a code for the caller. */\n  return retpsetcode(t, slot);\n}\n\n\nint luaH_psetstr (Table *t, TString *key, TValue *val) {\n  if (strisshr(key))\n    return luaH_psetshortstr(t, key, val);\n  else\n    return finishnodeset(t, Hgetlongstr(t, key), val);\n}\n\n\nint luaH_pset (Table *t, const TValue *key, TValue *val) {\n  switch (ttypetag(key)) {\n    case LUA_VSHRSTR: return luaH_psetshortstr(t, tsvalue(key), val);\n    case LUA_VNUMINT: return psetint(t, ivalue(key), val);\n    case LUA_VNIL: return HNOTFOUND;\n    case LUA_VNUMFLT: {\n      lua_Integer k;\n      if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */\n        return psetint(t, k, val);  /* use specialized version */\n      /* else... */\n    }  /* FALLTHROUGH */\n    default:\n      return finishnodeset(t, getgeneric(t, key, 0), val);\n  }\n}\n\n/*\n** Finish a raw \"set table\" operation, where 'hres' encodes where the\n** value should have been (the result of a previous 'pset' operation).\n** Beware: when using this function the caller probably need to check a\n** GC barrier and invalidate the TM cache.\n*/\nvoid luaH_finishset (lua_State *L, Table *t, const TValue *key,\n                                    TValue *value, int hres) {\n  lua_assert(hres != HOK);\n  if (l_unlikely(isshared(t)))\n    luaG_runerror(L, \"attempt to change a shared table\");\n  if (hres == HNOTFOUND) {\n    TValue aux;\n    if (l_unlikely(ttisnil(key)))\n      luaG_runerror(L, \"table index is nil\");\n    else if (ttisfloat(key)) {\n      lua_Number f = fltvalue(key);\n      lua_Integer k;\n      if (luaV_flttointeger(f, &k, F2Ieq)) {\n        setivalue(&aux, k);  /* key is equal to an integer */\n        key = &aux;  /* insert it as an integer */\n      }\n      else if (l_unlikely(luai_numisnan(f)))\n        luaG_runerror(L, \"table index is NaN\");\n    }\n    else if (isextstr(key)) {  /* external string? */\n      /* If string is short, must internalize it to be used as table key */\n      TString *ts = luaS_normstr(L, tsvalue(key));\n      setsvalue2s(L, L->top.p++, ts);  /* anchor 'ts' (EXTRA_STACK) */\n      luaH_newkey(L, t, s2v(L->top.p - 1), value);\n      L->top.p--;\n      return;\n    }\n    luaH_newkey(L, t, key, value);\n  }\n  else if (hres > 0) {  /* regular Node? */\n    setobj2t(L, gval(gnode(t, hres - HFIRSTNODE)), value);\n  }\n  else {  /* array entry */\n    hres = ~hres;  /* real index */\n    obj2arr(t, cast_uint(hres), value);\n  }\n}\n\n\n/*\n** beware: when using this function you probably need to check a GC\n** barrier and invalidate the TM cache.\n*/\nvoid luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {\n  int hres = luaH_pset(t, key, value);\n  if (hres != HOK)\n    luaH_finishset(L, t, key, value, hres);\n}\n\n\n/*\n** Ditto for a GC barrier. (No need to invalidate the TM cache, as\n** integers cannot be keys to metamethods.)\n*/\nvoid luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {\n  unsigned ik = ikeyinarray(t, key);\n  if (l_unlikely(isshared(t)))\n    luaG_runerror(L, \"attempt to change a shared table\");\n  if (ik > 0)\n    obj2arr(t, ik - 1, value);\n  else {\n    int ok = rawfinishnodeset(getintfromhash(t, key), value);\n    if (!ok) {\n      TValue k;\n      setivalue(&k, key);\n      luaH_newkey(L, t, &k, value);\n    }\n  }\n}\n\n\n/*\n** Try to find a boundary in the hash part of table 't'. From the\n** caller, we know that 'asize + 1' is present. We want to find a larger\n** key that is absent from the table, so that we can do a binary search\n** between the two keys to find a boundary. We keep doubling 'j' until\n** we get an absent index.  If the doubling would overflow, we try\n** LUA_MAXINTEGER. If it is absent, we are ready for the binary search.\n** ('j', being max integer, is larger or equal to 'i', but it cannot be\n** equal because it is absent while 'i' is present.) Otherwise, 'j' is a\n** boundary. ('j + 1' cannot be a present integer key because it is not\n** a valid integer in Lua.)\n** About 'rnd': If we used a fixed algorithm, a bad actor could fill\n** a table with only the keys that would be probed, in such a way that\n** a small table could result in a huge length. To avoid that, we use\n** the state's seed as a source of randomness. For the first probe,\n** we \"randomly double\" 'i' by adding to it a random number roughly its\n** width.\n*/\nstatic lua_Unsigned hash_search (lua_State *L, Table *t, unsigned asize) {\n  lua_Unsigned i = asize + 1;  /* caller ensures t[i] is present */\n  unsigned rnd = G(L)->seed;\n  int n = (asize > 0) ? luaO_ceillog2(asize) : 0;  /* width of 'asize' */\n  unsigned mask = (1u << n) - 1;  /* 11...111 with the width of 'asize' */\n  unsigned incr = (rnd & mask) + 1;  /* first increment (at least 1) */\n  lua_Unsigned j = (incr <= l_castS2U(LUA_MAXINTEGER) - i) ? i + incr : i + 1;\n  rnd >>= n;  /* used 'n' bits from 'rnd' */\n  while (!hashkeyisempty(t, j)) {  /* repeat until an absent t[j] */\n    i = j;  /* 'i' is a present index */\n    if (j <= l_castS2U(LUA_MAXINTEGER)/2 - 1) {\n      j = j*2 + (rnd & 1);  /* try again with 2j or 2j+1 */\n      rnd >>= 1;\n    }\n    else {\n      j = LUA_MAXINTEGER;\n      if (hashkeyisempty(t, j))  /* t[j] not present? */\n        break;  /* 'j' now is an absent index */\n      else  /* weird case */\n        return j;  /* well, max integer is a boundary... */\n    }\n  }\n  /* i < j  &&  t[i] present  &&  t[j] absent */\n  while (j - i > 1u) {  /* do a binary search between them */\n    lua_Unsigned m = (i + j) / 2;\n    if (hashkeyisempty(t, m)) j = m;\n    else i = m;\n  }\n  return i;\n}\n\n\nstatic unsigned int binsearch (Table *array, unsigned int i, unsigned int j) {\n  lua_assert(i <= j);\n  while (j - i > 1u) {  /* binary search */\n    unsigned int m = (i + j) / 2;\n    if (arraykeyisempty(array, m)) j = m;\n    else i = m;\n  }\n  return i;\n}\n\n\n/* return a border, saving it as a hint for next call */\nstatic lua_Unsigned newhint (Table *t, unsigned hint) {\n  lua_assert(hint <= t->asize);\n  *lenhint(t) = hint;\n  return hint;\n}\n\n\n/*\n** Try to find a border in table 't'. (A 'border' is an integer index\n** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent,\n** or 'maxinteger' if t[maxinteger] is present.)\n** If there is an array part, try to find a border there. First try\n** to find it in the vicinity of the previous result (hint), to handle\n** cases like 't[#t + 1] = val' or 't[#t] = nil', that move the border\n** by one entry. Otherwise, do a binary search to find the border.\n** If there is no array part, or its last element is non empty, the\n** border may be in the hash part.\n*/\nlua_Unsigned luaH_getn (lua_State *L, Table *t) {\n  unsigned asize = t->asize;\n  if (asize > 0) {  /* is there an array part? */\n    const unsigned maxvicinity = 4;\n    unsigned limit = *lenhint(t);  /* start with the hint */\n    if (limit == 0)\n      limit = 1;  /* make limit a valid index in the array */\n    if (arraykeyisempty(t, limit)) {  /* t[limit] empty? */\n      /* there must be a border before 'limit' */\n      unsigned i;\n      /* look for a border in the vicinity of the hint */\n      for (i = 0; i < maxvicinity && limit > 1; i++) {\n        limit--;\n        if (!arraykeyisempty(t, limit))\n          return newhint(t, limit);  /* 'limit' is a border */\n      }\n      /* t[limit] still empty; search for a border in [0, limit) */\n      return newhint(t, binsearch(t, 0, limit));\n    }\n    else {  /* 'limit' is present in table; look for a border after it */\n      unsigned i;\n      /* look for a border in the vicinity of the hint */\n      for (i = 0; i < maxvicinity && limit < asize; i++) {\n        limit++;\n        if (arraykeyisempty(t, limit))\n          return newhint(t, limit - 1);  /* 'limit - 1' is a border */\n      }\n      if (arraykeyisempty(t, asize)) {  /* last element empty? */\n        /* t[limit] not empty; search for a border in [limit, asize) */\n        return newhint(t, binsearch(t, limit, asize));\n      }\n    }\n    /* last element non empty; set a hint to speed up finding that again */\n    /* (keys in the hash part cannot be hints) */\n    *lenhint(t) = asize;\n  }\n  /* no array part or t[asize] is not empty; check the hash part */\n  lua_assert(asize == 0 || !arraykeyisempty(t, asize));\n  if (isdummy(t) || hashkeyisempty(t, asize + 1))\n    return asize;  /* 'asize + 1' is empty */\n  else  /* 'asize + 1' is also non empty */\n    return hash_search(L, t, asize);\n}\n\n\n\n#if defined(LUA_DEBUG)\n\n/* export this function for the test library */\n\nNode *luaH_mainposition (const Table *t, const TValue *key) {\n  return mainpositionTV(t, key);\n}\n\n#endif\n"
  },
  {
    "path": "3rd/lua/ltable.h",
    "content": "/*\n** $Id: ltable.h $\n** Lua tables (hash)\n** See Copyright Notice in lua.h\n*/\n\n#ifndef ltable_h\n#define ltable_h\n\n#include \"lobject.h\"\n\n\n#define gnode(t,i)\t(&(t)->node[i])\n#define gval(n)\t\t(&(n)->i_val)\n#define gnext(n)\t((n)->u.next)\n\n\n/*\n** Clear all bits of fast-access metamethods, which means that the table\n** may have any of these metamethods. (First access that fails after the\n** clearing will set the bit again.)\n*/\n#define invalidateTMcache(t)\t((t)->flags &= cast_byte(~maskflags))\n\n\n/*\n** Bit BITDUMMY set in 'flags' means the table is using the dummy node\n** for its hash part.\n*/\n\n#define BITDUMMY\t\t(1 << 6)\n#define NOTBITDUMMY\t\tcast_byte(~BITDUMMY)\n#define isdummy(t)\t\t((t)->flags & BITDUMMY)\n\n#define setnodummy(t)\t\t((t)->flags &= NOTBITDUMMY)\n#define setdummy(t)\t\t((t)->flags |= BITDUMMY)\n\n\n\n/* allocated size for hash nodes */\n#define allocsizenode(t)\t(isdummy(t) ? 0 : sizenode(t))\n\n\n/* returns the Node, given the value of a table entry */\n#define nodefromval(v)\tcast(Node *, (v))\n\n\n\n#define luaH_fastgeti(t,k,res,tag) \\\n  { Table *h = t; lua_Unsigned u = l_castS2U(k) - 1u; \\\n    if ((u < h->asize)) { \\\n      tag = *getArrTag(h, u); \\\n      if (!tagisempty(tag)) { farr2val(h, u, tag, res); }} \\\n    else { tag = luaH_getint(h, (k), res); }}\n\n\n#define luaH_fastseti(t,k,val,hres) \\\n  { Table *h = t; lua_Unsigned u = l_castS2U(k) - 1u; \\\n    if ((u < h->asize)) { \\\n      lu_byte *tag = getArrTag(h, u); \\\n      if (checknoTM(h->metatable, TM_NEWINDEX) || !tagisempty(*tag)) \\\n        { fval2arr(h, u, tag, val); hres = HOK; } \\\n      else hres = ~cast_int(u); } \\\n    else { hres = luaH_psetint(h, k, val); }}\n\n\n/* results from pset */\n#define HOK\t\t0\n#define HNOTFOUND\t1\n#define HNOTATABLE\t2\n#define HFIRSTNODE\t3\n\n/*\n** 'luaH_get*' operations set 'res', unless the value is absent, and\n** return the tag of the result.\n** The 'luaH_pset*' (pre-set) operations set the given value and return\n** HOK, unless the original value is absent. In that case, if the key\n** is really absent, they return HNOTFOUND. Otherwise, if there is a\n** slot with that key but with no value, 'luaH_pset*' return an encoding\n** of where the key is (usually called 'hres'). (pset cannot set that\n** value because there might be a metamethod.) If the slot is in the\n** hash part, the encoding is (HFIRSTNODE + hash index); if the slot is\n** in the array part, the encoding is (~array index), a negative value.\n** The value HNOTATABLE is used by the fast macros to signal that the\n** value being indexed is not a table.\n** (The size for the array part is limited by the maximum power of two\n** that fits in an unsigned integer; that is INT_MAX+1. So, the C-index\n** ranges from 0, which encodes to -1, to INT_MAX, which encodes to\n** INT_MIN. The size of the hash part is limited by the maximum power of\n** two that fits in a signed integer; that is (INT_MAX+1)/2. So, it is\n** safe to add HFIRSTNODE to any index there.)\n*/\n\n\n/*\n** The array part of a table is represented by an inverted array of\n** values followed by an array of tags, to avoid wasting space with\n** padding. In between them there is an unsigned int, explained later.\n** The 'array' pointer points between the two arrays, so that values are\n** indexed with negative indices and tags with non-negative indices.\n\n             Values                              Tags\n  --------------------------------------------------------\n  ...  |   Value 1     |   Value 0     |unsigned|0|1|...\n  --------------------------------------------------------\n                                       ^ t->array\n\n** All accesses to 't->array' should be through the macros 'getArrTag'\n** and 'getArrVal'.\n*/\n\n/* Computes the address of the tag for the abstract C-index 'k' */\n#define getArrTag(t,k)\t(cast(lu_byte*, (t)->array) + sizeof(unsigned) + (k))\n\n/* Computes the address of the value for the abstract C-index 'k' */\n#define getArrVal(t,k)\t((t)->array - 1 - (k))\n\n\n/*\n** The unsigned between the two arrays is used as a hint for #t;\n** see luaH_getn. It is stored there to avoid wasting space in\n** the structure Table for tables with no array part.\n*/\n#define lenhint(t)\tcast(unsigned*, (t)->array)\n\n\n/*\n** Move TValues to/from arrays, using C indices\n*/\n#define arr2obj(h,k,val)  \\\n  ((val)->tt_ = *getArrTag(h,(k)), (val)->value_ = *getArrVal(h,(k)))\n\n#define obj2arr(h,k,val)  \\\n  (*getArrTag(h,(k)) = (val)->tt_, *getArrVal(h,(k)) = (val)->value_)\n\n\n/*\n** Often, we need to check the tag of a value before moving it. The\n** following macros also move TValues to/from arrays, but receive the\n** precomputed tag value or address as an extra argument.\n*/\n#define farr2val(h,k,tag,res)  \\\n  ((res)->tt_ = tag, (res)->value_ = *getArrVal(h,(k)))\n\n#define fval2arr(h,k,tag,val)  \\\n  (*tag = (val)->tt_, *getArrVal(h,(k)) = (val)->value_)\n\n\nLUAI_FUNC lu_byte luaH_get (Table *t, const TValue *key, TValue *res);\nLUAI_FUNC lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res);\nLUAI_FUNC lu_byte luaH_getstr (Table *t, TString *key, TValue *res);\nLUAI_FUNC lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res);\n\n/* Special get for metamethods */\nLUAI_FUNC const TValue *luaH_Hgetshortstr (Table *t, TString *key);\n\nLUAI_FUNC int luaH_psetint (Table *t, lua_Integer key, TValue *val);\nLUAI_FUNC int luaH_psetshortstr (Table *t, TString *key, TValue *val);\nLUAI_FUNC int luaH_psetstr (Table *t, TString *key, TValue *val);\nLUAI_FUNC int luaH_pset (Table *t, const TValue *key, TValue *val);\n\nLUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key,\n                                                    TValue *value);\nLUAI_FUNC void luaH_set (lua_State *L, Table *t, const TValue *key,\n                                                 TValue *value);\n\nLUAI_FUNC void luaH_finishset (lua_State *L, Table *t, const TValue *key,\n                                              TValue *value, int hres);\nLUAI_FUNC Table *luaH_new (lua_State *L);\nLUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned nasize,\n                                                    unsigned nhsize);\nLUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned nasize);\nLUAI_FUNC lu_mem luaH_size (Table *t);\nLUAI_FUNC void luaH_free (lua_State *L, Table *t);\nLUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);\nLUAI_FUNC lua_Unsigned luaH_getn (lua_State *L, Table *t);\n\n\n#if defined(LUA_DEBUG)\nLUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key);\n#endif\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua/ltablib.c",
    "content": "/*\n** $Id: ltablib.c $\n** Library for Table Manipulation\n** See Copyright Notice in lua.h\n*/\n\n#define ltablib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <limits.h>\n#include <stddef.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\n/*\n** Operations that an object must define to mimic a table\n** (some functions only need some of them)\n*/\n#define TAB_R\t1\t\t\t/* read */\n#define TAB_W\t2\t\t\t/* write */\n#define TAB_L\t4\t\t\t/* length */\n#define TAB_RW\t(TAB_R | TAB_W)\t\t/* read/write */\n\n\n#define aux_getn(L,n,w)\t(checktab(L, n, (w) | TAB_L), luaL_len(L, n))\n\n\nstatic int checkfield (lua_State *L, const char *key, int n) {\n  lua_pushstring(L, key);\n  return (lua_rawget(L, -n) != LUA_TNIL);\n}\n\n\n/*\n** Check that 'arg' either is a table or can behave like one (that is,\n** has a metatable with the required metamethods)\n*/\nstatic void checktab (lua_State *L, int arg, int what) {\n  if (lua_type(L, arg) != LUA_TTABLE) {  /* is it not a table? */\n    int n = 1;  /* number of elements to pop */\n    if (lua_getmetatable(L, arg) &&  /* must have metatable */\n        (!(what & TAB_R) || checkfield(L, \"__index\", ++n)) &&\n        (!(what & TAB_W) || checkfield(L, \"__newindex\", ++n)) &&\n        (!(what & TAB_L) || checkfield(L, \"__len\", ++n))) {\n      lua_pop(L, n);  /* pop metatable and tested metamethods */\n    }\n    else\n      luaL_checktype(L, arg, LUA_TTABLE);  /* force an error */\n  }\n}\n\n\nstatic int tcreate (lua_State *L) {\n  lua_Unsigned sizeseq = (lua_Unsigned)luaL_checkinteger(L, 1);\n  lua_Unsigned sizerest = (lua_Unsigned)luaL_optinteger(L, 2, 0);\n  luaL_argcheck(L, sizeseq <= cast_uint(INT_MAX), 1, \"out of range\");\n  luaL_argcheck(L, sizerest <= cast_uint(INT_MAX), 2, \"out of range\");\n  lua_createtable(L, cast_int(sizeseq), cast_int(sizerest));\n  return 1;\n}\n\n\nstatic int tinsert (lua_State *L) {\n  lua_Integer pos;  /* where to insert new element */\n  lua_Integer e = aux_getn(L, 1, TAB_RW);\n  e = luaL_intop(+, e, 1);  /* first empty element */\n  switch (lua_gettop(L)) {\n    case 2: {  /* called with only 2 arguments */\n      pos = e;  /* insert new element at the end */\n      break;\n    }\n    case 3: {\n      lua_Integer i;\n      pos = luaL_checkinteger(L, 2);  /* 2nd argument is the position */\n      /* check whether 'pos' is in [1, e] */\n      luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2,\n                       \"position out of bounds\");\n      for (i = e; i > pos; i--) {  /* move up elements */\n        lua_geti(L, 1, i - 1);\n        lua_seti(L, 1, i);  /* t[i] = t[i - 1] */\n      }\n      break;\n    }\n    default: {\n      return luaL_error(L, \"wrong number of arguments to 'insert'\");\n    }\n  }\n  lua_seti(L, 1, pos);  /* t[pos] = v */\n  return 0;\n}\n\n\nstatic int tremove (lua_State *L) {\n  lua_Integer size = aux_getn(L, 1, TAB_RW);\n  lua_Integer pos = luaL_optinteger(L, 2, size);\n  if (pos != size)  /* validate 'pos' if given */\n    /* check whether 'pos' is in [1, size + 1] */\n    luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 2,\n                     \"position out of bounds\");\n  lua_geti(L, 1, pos);  /* result = t[pos] */\n  for ( ; pos < size; pos++) {\n    lua_geti(L, 1, pos + 1);\n    lua_seti(L, 1, pos);  /* t[pos] = t[pos + 1] */\n  }\n  lua_pushnil(L);\n  lua_seti(L, 1, pos);  /* remove entry t[pos] */\n  return 1;\n}\n\n\n/*\n** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever\n** possible, copy in increasing order, which is better for rehashing.\n** \"possible\" means destination after original range, or smaller\n** than origin, or copying to another table.\n*/\nstatic int tmove (lua_State *L) {\n  lua_Integer f = luaL_checkinteger(L, 2);\n  lua_Integer e = luaL_checkinteger(L, 3);\n  lua_Integer t = luaL_checkinteger(L, 4);\n  int tt = !lua_isnoneornil(L, 5) ? 5 : 1;  /* destination table */\n  checktab(L, 1, TAB_R);\n  checktab(L, tt, TAB_W);\n  if (e >= f) {  /* otherwise, nothing to move */\n    lua_Integer n, i;\n    luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3,\n                  \"too many elements to move\");\n    n = e - f + 1;  /* number of elements to move */\n    luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4,\n                  \"destination wrap around\");\n    if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) {\n      for (i = 0; i < n; i++) {\n        lua_geti(L, 1, f + i);\n        lua_seti(L, tt, t + i);\n      }\n    }\n    else {\n      for (i = n - 1; i >= 0; i--) {\n        lua_geti(L, 1, f + i);\n        lua_seti(L, tt, t + i);\n      }\n    }\n  }\n  lua_pushvalue(L, tt);  /* return destination table */\n  return 1;\n}\n\n\nstatic void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {\n  lua_geti(L, 1, i);\n  if (l_unlikely(!lua_isstring(L, -1)))\n    luaL_error(L, \"invalid value (%s) at index %I in table for 'concat'\",\n                  luaL_typename(L, -1), (LUAI_UACINT)i);\n  luaL_addvalue(b);\n}\n\n\nstatic int tconcat (lua_State *L) {\n  luaL_Buffer b;\n  lua_Integer last = aux_getn(L, 1, TAB_R);\n  size_t lsep;\n  const char *sep = luaL_optlstring(L, 2, \"\", &lsep);\n  lua_Integer i = luaL_optinteger(L, 3, 1);\n  last = luaL_optinteger(L, 4, last);\n  luaL_buffinit(L, &b);\n  for (; i < last; i++) {\n    addfield(L, &b, i);\n    luaL_addlstring(&b, sep, lsep);\n  }\n  if (i == last)  /* add last value (if interval was not empty) */\n    addfield(L, &b, i);\n  luaL_pushresult(&b);\n  return 1;\n}\n\n\n/*\n** {======================================================\n** Pack/unpack\n** =======================================================\n*/\n\nstatic int tpack (lua_State *L) {\n  int i;\n  int n = lua_gettop(L);  /* number of elements to pack */\n  lua_createtable(L, n, 1);  /* create result table */\n  lua_insert(L, 1);  /* put it at index 1 */\n  for (i = n; i >= 1; i--)  /* assign elements */\n    lua_seti(L, 1, i);\n  lua_pushinteger(L, n);\n  lua_setfield(L, 1, \"n\");  /* t.n = number of elements */\n  return 1;  /* return table */\n}\n\n\nstatic int tunpack (lua_State *L) {\n  lua_Unsigned n;\n  lua_Integer i = luaL_optinteger(L, 2, 1);\n  lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));\n  if (i > e) return 0;  /* empty range */\n  n = l_castS2U(e) - l_castS2U(i);  /* number of elements minus 1 */\n  if (l_unlikely(n >= (unsigned int)INT_MAX  ||\n                 !lua_checkstack(L, (int)(++n))))\n    return luaL_error(L, \"too many results to unpack\");\n  for (; i < e; i++) {  /* push arg[i..e - 1] (to avoid overflows) */\n    lua_geti(L, 1, i);\n  }\n  lua_geti(L, 1, e);  /* push last element */\n  return (int)n;\n}\n\n/* }====================================================== */\n\n\n\n/*\n** {======================================================\n** Quicksort\n** (based on 'Algorithms in MODULA-3', Robert Sedgewick;\n**  Addison-Wesley, 1993.)\n** =======================================================\n*/\n\n\n/*\n** Type for array indices. These indices are always limited by INT_MAX,\n** so it is safe to cast them to lua_Integer even for Lua 32 bits.\n*/\ntypedef unsigned int IdxT;\n\n\n/* Versions of lua_seti/lua_geti specialized for IdxT */\n#define geti(L,idt,idx)\tlua_geti(L, idt, l_castU2S(idx))\n#define seti(L,idt,idx)\tlua_seti(L, idt, l_castU2S(idx))\n\n\n/*\n** Produce a \"random\" 'unsigned int' to randomize pivot choice. This\n** macro is used only when 'sort' detects a big imbalance in the result\n** of a partition. (If you don't want/need this \"randomness\", ~0 is a\n** good choice.)\n*/\n#if !defined(l_randomizePivot)\n#define l_randomizePivot(L)\tluaL_makeseed(L)\n#endif\t\t\t\t\t/* } */\n\n\n/* arrays larger than 'RANLIMIT' may use randomized pivots */\n#define RANLIMIT\t100u\n\n\nstatic void set2 (lua_State *L, IdxT i, IdxT j) {\n  seti(L, 1, i);\n  seti(L, 1, j);\n}\n\n\n/*\n** Return true iff value at stack index 'a' is less than the value at\n** index 'b' (according to the order of the sort).\n*/\nstatic int sort_comp (lua_State *L, int a, int b) {\n  if (lua_isnil(L, 2))  /* no function? */\n    return lua_compare(L, a, b, LUA_OPLT);  /* a < b */\n  else {  /* function */\n    int res;\n    lua_pushvalue(L, 2);    /* push function */\n    lua_pushvalue(L, a-1);  /* -1 to compensate function */\n    lua_pushvalue(L, b-2);  /* -2 to compensate function and 'a' */\n    lua_call(L, 2, 1);      /* call function */\n    res = lua_toboolean(L, -1);  /* get result */\n    lua_pop(L, 1);          /* pop result */\n    return res;\n  }\n}\n\n\n/*\n** Does the partition: Pivot P is at the top of the stack.\n** precondition: a[lo] <= P == a[up-1] <= a[up],\n** so it only needs to do the partition from lo + 1 to up - 2.\n** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up]\n** returns 'i'.\n*/\nstatic IdxT partition (lua_State *L, IdxT lo, IdxT up) {\n  IdxT i = lo;  /* will be incremented before first use */\n  IdxT j = up - 1;  /* will be decremented before first use */\n  /* loop invariant: a[lo .. i] <= P <= a[j .. up] */\n  for (;;) {\n    /* next loop: repeat ++i while a[i] < P */\n    while ((void)geti(L, 1, ++i), sort_comp(L, -1, -2)) {\n      if (l_unlikely(i == up - 1))  /* a[up - 1] < P == a[up - 1] */\n        luaL_error(L, \"invalid order function for sorting\");\n      lua_pop(L, 1);  /* remove a[i] */\n    }\n    /* after the loop, a[i] >= P and a[lo .. i - 1] < P  (a) */\n    /* next loop: repeat --j while P < a[j] */\n    while ((void)geti(L, 1, --j), sort_comp(L, -3, -1)) {\n      if (l_unlikely(j < i))  /* j <= i - 1 and a[j] > P, contradicts (a) */\n        luaL_error(L, \"invalid order function for sorting\");\n      lua_pop(L, 1);  /* remove a[j] */\n    }\n    /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */\n    if (j < i) {  /* no elements out of place? */\n      /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */\n      lua_pop(L, 1);  /* pop a[j] */\n      /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */\n      set2(L, up - 1, i);\n      return i;\n    }\n    /* otherwise, swap a[i] - a[j] to restore invariant and repeat */\n    set2(L, i, j);\n  }\n}\n\n\n/*\n** Choose an element in the middle (2nd-3th quarters) of [lo,up]\n** \"randomized\" by 'rnd'\n*/\nstatic IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) {\n  IdxT r4 = (up - lo) / 4;  /* range/4 */\n  IdxT p = (rnd ^ lo ^ up) % (r4 * 2) + (lo + r4);\n  lua_assert(lo + r4 <= p && p <= up - r4);\n  return p;\n}\n\n\n/*\n** Quicksort algorithm (recursive function)\n*/\nstatic void auxsort (lua_State *L, IdxT lo, IdxT up, unsigned rnd) {\n  while (lo < up) {  /* loop for tail recursion */\n    IdxT p;  /* Pivot index */\n    IdxT n;  /* to be used later */\n    /* sort elements 'lo', 'p', and 'up' */\n    geti(L, 1, lo);\n    geti(L, 1, up);\n    if (sort_comp(L, -1, -2))  /* a[up] < a[lo]? */\n      set2(L, lo, up);  /* swap a[lo] - a[up] */\n    else\n      lua_pop(L, 2);  /* remove both values */\n    if (up - lo == 1)  /* only 2 elements? */\n      return;  /* already sorted */\n    if (up - lo < RANLIMIT || rnd == 0)  /* small interval or no randomize? */\n      p = (lo + up)/2;  /* middle element is a good pivot */\n    else  /* for larger intervals, it is worth a random pivot */\n      p = choosePivot(lo, up, rnd);\n    geti(L, 1, p);\n    geti(L, 1, lo);\n    if (sort_comp(L, -2, -1))  /* a[p] < a[lo]? */\n      set2(L, p, lo);  /* swap a[p] - a[lo] */\n    else {\n      lua_pop(L, 1);  /* remove a[lo] */\n      geti(L, 1, up);\n      if (sort_comp(L, -1, -2))  /* a[up] < a[p]? */\n        set2(L, p, up);  /* swap a[up] - a[p] */\n      else\n        lua_pop(L, 2);\n    }\n    if (up - lo == 2)  /* only 3 elements? */\n      return;  /* already sorted */\n    geti(L, 1, p);  /* get middle element (Pivot) */\n    lua_pushvalue(L, -1);  /* push Pivot */\n    geti(L, 1, up - 1);  /* push a[up - 1] */\n    set2(L, p, up - 1);  /* swap Pivot (a[p]) with a[up - 1] */\n    p = partition(L, lo, up);\n    /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */\n    if (p - lo < up - p) {  /* lower interval is smaller? */\n      auxsort(L, lo, p - 1, rnd);  /* call recursively for lower interval */\n      n = p - lo;  /* size of smaller interval */\n      lo = p + 1;  /* tail call for [p + 1 .. up] (upper interval) */\n    }\n    else {\n      auxsort(L, p + 1, up, rnd);  /* call recursively for upper interval */\n      n = up - p;  /* size of smaller interval */\n      up = p - 1;  /* tail call for [lo .. p - 1]  (lower interval) */\n    }\n    if ((up - lo) / 128 > n) /* partition too imbalanced? */\n      rnd = l_randomizePivot(L);  /* try a new randomization */\n  }  /* tail call auxsort(L, lo, up, rnd) */\n}\n\n\nstatic int sort (lua_State *L) {\n  lua_Integer n = aux_getn(L, 1, TAB_RW);\n  if (n > 1) {  /* non-trivial interval? */\n    luaL_argcheck(L, n < INT_MAX, 1, \"array too big\");\n    if (!lua_isnoneornil(L, 2))  /* is there a 2nd argument? */\n      luaL_checktype(L, 2, LUA_TFUNCTION);  /* must be a function */\n    lua_settop(L, 2);  /* make sure there are two arguments */\n    auxsort(L, 1, (IdxT)n, 0);\n  }\n  return 0;\n}\n\n/* }====================================================== */\n\n\nstatic const luaL_Reg tab_funcs[] = {\n  {\"concat\", tconcat},\n  {\"create\", tcreate},\n  {\"insert\", tinsert},\n  {\"pack\", tpack},\n  {\"unpack\", tunpack},\n  {\"remove\", tremove},\n  {\"move\", tmove},\n  {\"sort\", sort},\n  {NULL, NULL}\n};\n\n\nLUAMOD_API int luaopen_table (lua_State *L) {\n  luaL_newlib(L, tab_funcs);\n  return 1;\n}\n\n"
  },
  {
    "path": "3rd/lua/ltests.c",
    "content": "/*\n** $Id: ltests.c $\n** Internal Module for Debugging of the Lua Implementation\n** See Copyright Notice in lua.h\n*/\n\n#define ltests_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <limits.h>\n#include <setjmp.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lapi.h\"\n#include \"lauxlib.h\"\n#include \"lcode.h\"\n#include \"lctype.h\"\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lfunc.h\"\n#include \"lmem.h\"\n#include \"lopcodes.h\"\n#include \"lopnames.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"lualib.h\"\n\n\n\n/*\n** The whole module only makes sense with LUA_DEBUG on\n*/\n#if defined(LUA_DEBUG)\n\n\nvoid *l_Trick = 0;\n\n\n#define obj_at(L,k)\ts2v(L->ci->func.p + (k))\n\n\nstatic int runC (lua_State *L, lua_State *L1, const char *pc);\n\n\nstatic void setnameval (lua_State *L, const char *name, int val) {\n  lua_pushinteger(L, val);\n  lua_setfield(L, -2, name);\n}\n\n\nstatic void pushobject (lua_State *L, const TValue *o) {\n  setobj2s(L, L->top.p, o);\n  api_incr_top(L);\n}\n\n\nstatic void badexit (const char *fmt, const char *s1, const char *s2) {\n  fprintf(stderr, fmt, s1);\n  if (s2)\n    fprintf(stderr, \"extra info: %s\\n\", s2);\n  /* avoid assertion failures when exiting */\n  l_memcontrol.numblocks = l_memcontrol.total = 0;\n  exit(EXIT_FAILURE);\n}\n\n\nstatic int tpanic (lua_State *L) {\n  const char *msg = (lua_type(L, -1) == LUA_TSTRING)\n                  ? lua_tostring(L, -1)\n                  : \"error object is not a string\";\n  return (badexit(\"PANIC: unprotected error in call to Lua API (%s)\\n\",\n                   msg, NULL),\n          0);  /* do not return to Lua */\n}\n\n\n/*\n** Warning function for tests. First, it concatenates all parts of\n** a warning in buffer 'buff'. Then, it has three modes:\n** - 0.normal: messages starting with '#' are shown on standard output;\n** - other messages abort the tests (they represent real warning\n** conditions; the standard tests should not generate these conditions\n** unexpectedly);\n** - 1.allow: all messages are shown;\n** - 2.store: all warnings go to the global '_WARN';\n*/\nstatic void warnf (void *ud, const char *msg, int tocont) {\n  lua_State *L = cast(lua_State *, ud);\n  static char buff[200] = \"\";  /* should be enough for tests... */\n  static int onoff = 0;\n  static int mode = 0;  /* start in normal mode */\n  static int lasttocont = 0;\n  if (!lasttocont && !tocont && *msg == '@') {  /* control message? */\n    if (buff[0] != '\\0')\n      badexit(\"Control warning during warning: %s\\naborting...\\n\", msg, buff);\n    if (strcmp(msg, \"@off\") == 0)\n      onoff = 0;\n    else if (strcmp(msg, \"@on\") == 0)\n      onoff = 1;\n    else if (strcmp(msg, \"@normal\") == 0)\n      mode = 0;\n    else if (strcmp(msg, \"@allow\") == 0)\n      mode = 1;\n    else if (strcmp(msg, \"@store\") == 0)\n      mode = 2;\n    else\n      badexit(\"Invalid control warning in test mode: %s\\naborting...\\n\",\n              msg, NULL);\n    return;\n  }\n  lasttocont = tocont;\n  if (strlen(msg) >= sizeof(buff) - strlen(buff))\n    badexit(\"warnf-buffer overflow (%s)\\n\", msg, buff);\n  strcat(buff, msg);  /* add new message to current warning */\n  if (!tocont) {  /* message finished? */\n    lua_unlock(L);\n    luaL_checkstack(L, 1, \"warn stack space\");\n    lua_getglobal(L, \"_WARN\");\n    if (!lua_toboolean(L, -1))\n      lua_pop(L, 1);  /* ok, no previous unexpected warning */\n    else {\n      badexit(\"Unhandled warning in store mode: %s\\naborting...\\n\",\n              lua_tostring(L, -1), buff);\n    }\n    lua_lock(L);\n    switch (mode) {\n      case 0: {  /* normal */\n        if (buff[0] != '#' && onoff)  /* unexpected warning? */\n          badexit(\"Unexpected warning in test mode: %s\\naborting...\\n\",\n                  buff, NULL);\n      }  /* FALLTHROUGH */\n      case 1: {  /* allow */\n        if (onoff)\n          fprintf(stderr, \"Lua warning: %s\\n\", buff);  /* print warning */\n        break;\n      }\n      case 2: {  /* store */\n        lua_unlock(L);\n        luaL_checkstack(L, 1, \"warn stack space\");\n        lua_pushstring(L, buff);\n        lua_setglobal(L, \"_WARN\");  /* assign message to global '_WARN' */\n        lua_lock(L);\n        break;\n      }\n    }\n    buff[0] = '\\0';  /* prepare buffer for next warning */\n  }\n}\n\n\n/*\n** {======================================================================\n** Controlled version for realloc.\n** =======================================================================\n*/\n\n#define MARK\t\t0x55  /* 01010101 (a nice pattern) */\n\ntypedef union memHeader {\n  LUAI_MAXALIGN;\n  struct {\n    size_t size;\n    int type;\n  } d;\n} memHeader;\n\n\n#if !defined(EXTERNMEMCHECK)\n\n/* full memory check */\n#define MARKSIZE\t16  /* size of marks after each block */\n#define fillmem(mem,size)\tmemset(mem, -MARK, size)\n\n#else\n\n/* external memory check: don't do it twice */\n#define MARKSIZE\t0\n#define fillmem(mem,size)\t/* empty */\n\n#endif\n\n\nMemcontrol l_memcontrol =\n  {0, 0UL, 0UL, 0UL, 0UL, (~0UL),\n   {0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL}};\n\n\nstatic void freeblock (Memcontrol *mc, memHeader *block) {\n  if (block) {\n    size_t size = block->d.size;\n    int i;\n    for (i = 0; i < MARKSIZE; i++)  /* check marks after block */\n      lua_assert(*(cast_charp(block + 1) + size + i) == MARK);\n    mc->objcount[block->d.type]--;\n    fillmem(block, sizeof(memHeader) + size + MARKSIZE);  /* erase block */\n    free(block);  /* actually free block */\n    mc->numblocks--;  /* update counts */\n    mc->total -= size;\n  }\n}\n\n\nvoid *debug_realloc (void *ud, void *b, size_t oldsize, size_t size) {\n  Memcontrol *mc = cast(Memcontrol *, ud);\n  memHeader *block = cast(memHeader *, b);\n  int type;\n  if (mc->memlimit == 0) {  /* first time? */\n    char *limit = getenv(\"MEMLIMIT\");  /* initialize memory limit */\n    mc->memlimit = limit ? strtoul(limit, NULL, 10) : ULONG_MAX;\n  }\n  if (block == NULL) {\n    type = (oldsize < LUA_NUMTYPES) ? cast_int(oldsize) : 0;\n    oldsize = 0;\n  }\n  else {\n    block--;  /* go to real header */\n    type = block->d.type;\n    lua_assert(oldsize == block->d.size);\n  }\n  if (size == 0) {\n    freeblock(mc, block);\n    return NULL;\n  }\n  if (mc->failnext) {\n    mc->failnext = 0;\n    return NULL;  /* fake a single memory allocation error */\n  }\n  if (mc->countlimit != ~0UL && size != oldsize) {  /* count limit in use? */\n    if (mc->countlimit == 0)\n      return NULL;  /* fake a memory allocation error */\n    mc->countlimit--;\n  }\n  if (size > oldsize && mc->total+size-oldsize > mc->memlimit)\n    return NULL;  /* fake a memory allocation error */\n  else {\n    memHeader *newblock;\n    int i;\n    size_t commonsize = (oldsize < size) ? oldsize : size;\n    size_t realsize = sizeof(memHeader) + size + MARKSIZE;\n    if (realsize < size) return NULL;  /* arithmetic overflow! */\n    newblock = cast(memHeader *, malloc(realsize));  /* alloc a new block */\n    if (newblock == NULL)\n      return NULL;  /* really out of memory? */\n    if (block) {\n      memcpy(newblock + 1, block + 1, commonsize);  /* copy old contents */\n      freeblock(mc, block);  /* erase (and check) old copy */\n    }\n    /* initialize new part of the block with something weird */\n    fillmem(cast_charp(newblock + 1) + commonsize, size - commonsize);\n    /* initialize marks after block */\n    for (i = 0; i < MARKSIZE; i++)\n      *(cast_charp(newblock + 1) + size + i) = MARK;\n    newblock->d.size = size;\n    newblock->d.type = type;\n    mc->total += size;\n    if (mc->total > mc->maxmem)\n      mc->maxmem = mc->total;\n    mc->numblocks++;\n    mc->objcount[type]++;\n    return newblock + 1;\n  }\n}\n\n\n/* }====================================================================== */\n\n\n\n/*\n** {=====================================================================\n** Functions to check memory consistency.\n** Most of these checks are done through asserts, so this code does\n** not make sense with asserts off. For this reason, it uses 'assert'\n** directly, instead of 'lua_assert'.\n** ======================================================================\n*/\n\n#include <assert.h>\n\n/*\n** Check GC invariants. For incremental mode, a black object cannot\n** point to a white one. For generational mode, really old objects\n** cannot point to young objects. Both old1 and touched2 objects\n** cannot point to new objects (but can point to survivals).\n** (Threads and open upvalues, despite being marked \"really old\",\n** continue to be visited in all collections, and therefore can point to\n** new objects. They, and only they, are old but gray.)\n*/\nstatic int testobjref1 (global_State *g, GCObject *f, GCObject *t) {\n  if (isdead(g,t)) return 0;\n  if (issweepphase(g))\n    return 1;  /* no invariants */\n  else if (g->gckind != KGC_GENMINOR)\n    return !(isblack(f) && iswhite(t));  /* basic incremental invariant */\n  else {  /* generational mode */\n    if ((getage(f) == G_OLD && isblack(f)) && !isold(t))\n      return 0;\n    if ((getage(f) == G_OLD1 || getage(f) == G_TOUCHED2) &&\n         getage(t) == G_NEW)\n      return 0;\n    return 1;\n  }\n}\n\n\nstatic void printobj (global_State *g, GCObject *o) {\n  printf(\"||%s(%p)-%c%c(%02X)||\",\n           ttypename(novariant(o->tt)), (void *)o,\n           isdead(g,o) ? 'd' : isblack(o) ? 'b' : iswhite(o) ? 'w' : 'g',\n           \"ns01oTt\"[getage(o)], o->marked);\n  if (o->tt == LUA_VSHRSTR || o->tt == LUA_VLNGSTR)\n    printf(\" '%s'\", getstr(gco2ts(o)));\n}\n\n\nvoid lua_printobj (lua_State *L, struct GCObject *o) {\n  printobj(G(L), o);\n}\n\n\nvoid lua_printvalue (TValue *v) {\n  switch (ttypetag(v)) {\n    case LUA_VNUMINT: case LUA_VNUMFLT: {\n      char buff[LUA_N2SBUFFSZ];\n      unsigned len = luaO_tostringbuff(v, buff);\n      buff[len] = '\\0';\n      printf(\"%s\", buff);\n      break;\n    }\n    case LUA_VSHRSTR:\n      printf(\"'%s'\", getstr(tsvalue(v))); break;\n    case LUA_VLNGSTR:\n      printf(\"'%.30s...'\", getstr(tsvalue(v))); break;\n    case LUA_VFALSE:\n      printf(\"%s\", \"false\"); break;\n    case LUA_VTRUE:\n      printf(\"%s\", \"true\"); break;\n    case LUA_VLIGHTUSERDATA:\n      printf(\"light udata: %p\", pvalue(v)); break;\n    case LUA_VUSERDATA:\n      printf(\"full udata: %p\", uvalue(v)); break;\n    case LUA_VNIL:\n      printf(\"nil\"); break;\n    case LUA_VLCF:\n      printf(\"light C function: %p\", fvalue(v)); break;\n    case LUA_VCCL:\n      printf(\"C closure: %p\", clCvalue(v)); break;\n    case LUA_VLCL:\n      printf(\"Lua function: %p\", clLvalue(v)); break;\n    case LUA_VTHREAD:\n      printf(\"thread: %p\", thvalue(v)); break;\n    case LUA_VTABLE:\n      printf(\"table: %p\", hvalue(v)); break;\n    default:\n      lua_assert(0);\n  }\n}\n\n\nstatic int testobjref (global_State *g, GCObject *f, GCObject *t) {\n  int r1 = testobjref1(g, f, t);\n  if (!r1) {\n    printf(\"%d(%02X) - \", g->gcstate, g->currentwhite);\n    printobj(g, f);\n    printf(\"  ->  \");\n    printobj(g, t);\n    printf(\"\\n\");\n  }\n  return r1;\n}\n\n\nstatic void checkobjref (global_State *g, GCObject *f, GCObject *t) {\n    assert(testobjref(g, f, t));\n}\n\n\n/*\n** Version where 't' can be NULL. In that case, it should not apply the\n** macro 'obj2gco' over the object. ('t' may have several types, so this\n** definition must be a macro.)  Most checks need this version, because\n** the check may run while an object is still being created.\n*/\n#define checkobjrefN(g,f,t)\t{ if (t) checkobjref(g,f,obj2gco(t)); }\n\n\nstatic void checkvalref (global_State *g, GCObject *f, const TValue *t) {\n  assert(!iscollectable(t) || (righttt(t) && testobjref(g, f, gcvalue(t))));\n}\n\n\nstatic void checktable (global_State *g, Table *h) {\n  unsigned int i;\n  unsigned int asize = h->asize;\n  Node *n, *limit = gnode(h, sizenode(h));\n  GCObject *hgc = obj2gco(h);\n  checkobjrefN(g, hgc, h->metatable);\n  for (i = 0; i < asize; i++) {\n    TValue aux;\n    arr2obj(h, i, &aux);\n    checkvalref(g, hgc, &aux);\n  }\n  for (n = gnode(h, 0); n < limit; n++) {\n    if (!isempty(gval(n))) {\n      TValue k;\n      getnodekey(mainthread(g), &k, n);\n      assert(!keyisnil(n));\n      checkvalref(g, hgc, &k);\n      checkvalref(g, hgc, gval(n));\n    }\n  }\n}\n\n\nstatic void checkudata (global_State *g, Udata *u) {\n  int i;\n  GCObject *hgc = obj2gco(u);\n  checkobjrefN(g, hgc, u->metatable);\n  for (i = 0; i < u->nuvalue; i++)\n    checkvalref(g, hgc, &u->uv[i].uv);\n}\n\n\nstatic void checkproto (global_State *g, Proto *f) {\n  int i;\n  GCObject *fgc = obj2gco(f);\n  checkobjrefN(g, fgc, f->source);\n  for (i=0; i<f->sizek; i++) {\n    if (iscollectable(f->k + i))\n      checkobjref(g, fgc, gcvalue(f->k + i));\n  }\n  for (i=0; i<f->sizeupvalues; i++)\n    checkobjrefN(g, fgc, f->upvalues[i].name);\n  for (i=0; i<f->sizep; i++)\n    checkobjrefN(g, fgc, f->p[i]);\n  for (i=0; i<f->sizelocvars; i++)\n    checkobjrefN(g, fgc, f->locvars[i].varname);\n}\n\n\nstatic void checkCclosure (global_State *g, CClosure *cl) {\n  GCObject *clgc = obj2gco(cl);\n  int i;\n  for (i = 0; i < cl->nupvalues; i++)\n    checkvalref(g, clgc, &cl->upvalue[i]);\n}\n\n\nstatic void checkLclosure (global_State *g, LClosure *cl) {\n  GCObject *clgc = obj2gco(cl);\n  int i;\n  checkobjrefN(g, clgc, cl->p);\n  for (i=0; i<cl->nupvalues; i++) {\n    UpVal *uv = cl->upvals[i];\n    if (uv) {\n      checkobjrefN(g, clgc, uv);\n      if (!upisopen(uv))\n        checkvalref(g, obj2gco(uv), uv->v.p);\n    }\n  }\n}\n\n\nstatic int lua_checkpc (CallInfo *ci) {\n  if (!isLua(ci)) return 1;\n  else {\n    StkId f = ci->func.p;\n    Proto *p = clLvalue(s2v(f))->p;\n    return p->code <= ci->u.l.savedpc &&\n           ci->u.l.savedpc <= p->code + p->sizecode;\n  }\n}\n\n\nstatic void check_stack (global_State *g, lua_State *L1) {\n  StkId o;\n  CallInfo *ci;\n  UpVal *uv;\n  assert(!isdead(g, L1));\n  if (L1->stack.p == NULL) {  /* incomplete thread? */\n    assert(L1->openupval == NULL && L1->ci == NULL);\n    return;\n  }\n  for (uv = L1->openupval; uv != NULL; uv = uv->u.open.next)\n    assert(upisopen(uv));  /* must be open */\n  assert(L1->top.p <= L1->stack_last.p);\n  assert(L1->tbclist.p <= L1->top.p);\n  for (ci = L1->ci; ci != NULL; ci = ci->previous) {\n    assert(ci->top.p <= L1->stack_last.p);\n    assert(lua_checkpc(ci));\n  }\n  for (o = L1->stack.p; o < L1->stack_last.p; o++)\n    checkliveness(L1, s2v(o));  /* entire stack must have valid values */\n}\n\n\nstatic void checkrefs (global_State *g, GCObject *o) {\n  switch (o->tt) {\n    case LUA_VUSERDATA: {\n      checkudata(g, gco2u(o));\n      break;\n    }\n    case LUA_VUPVAL: {\n      checkvalref(g, o, gco2upv(o)->v.p);\n      break;\n    }\n    case LUA_VTABLE: {\n      checktable(g, gco2t(o));\n      break;\n    }\n    case LUA_VTHREAD: {\n      check_stack(g, gco2th(o));\n      break;\n    }\n    case LUA_VLCL: {\n      checkLclosure(g, gco2lcl(o));\n      break;\n    }\n    case LUA_VCCL: {\n      checkCclosure(g, gco2ccl(o));\n      break;\n    }\n    case LUA_VPROTO: {\n      checkproto(g, gco2p(o));\n      break;\n    }\n    case LUA_VSHRSTR:\n    case LUA_VLNGSTR: {\n      assert(!isgray(o));  /* strings are never gray */\n      break;\n    }\n    default: assert(0);\n  }\n}\n\n\n/*\n** Check consistency of an object:\n** - Dead objects can only happen in the 'allgc' list during a sweep\n** phase (controlled by the caller through 'maybedead').\n** - During pause, all objects must be white.\n** - In generational mode:\n**   * objects must be old enough for their lists ('listage').\n**   * old objects cannot be white.\n**   * old objects must be black, except for 'touched1', 'old0',\n**     threads, and open upvalues.\n**   * 'touched1' objects must be gray.\n*/\nstatic void checkobject (global_State *g, GCObject *o, int maybedead,\n                         int listage) {\n  if (isdead(g, o))\n    assert(maybedead);\n  else {\n    assert(g->gcstate != GCSpause || iswhite(o));\n    if (g->gckind == KGC_GENMINOR) {  /* generational mode? */\n      assert(getage(o) >= listage);\n      if (isold(o)) {\n        assert(!iswhite(o));\n        assert(isblack(o) ||\n        getage(o) == G_TOUCHED1 ||\n        getage(o) == G_OLD0 ||\n        o->tt == LUA_VTHREAD ||\n        (o->tt == LUA_VUPVAL && upisopen(gco2upv(o))));\n      }\n      assert(getage(o) != G_TOUCHED1 || isgray(o));\n    }\n    checkrefs(g, o);\n  }\n}\n\n\nstatic l_mem checkgraylist (global_State *g, GCObject *o) {\n  int total = 0;  /* count number of elements in the list */\n  cast_void(g);  /* better to keep it if we need to print an object */\n  while (o) {\n    assert(!!isgray(o) ^ (getage(o) == G_TOUCHED2));\n    assert(!testbit(o->marked, TESTBIT));\n    if (keepinvariant(g))\n      l_setbit(o->marked, TESTBIT);  /* mark that object is in a gray list */\n    total++;\n    switch (o->tt) {\n      case LUA_VTABLE: o = gco2t(o)->gclist; break;\n      case LUA_VLCL: o = gco2lcl(o)->gclist; break;\n      case LUA_VCCL: o = gco2ccl(o)->gclist; break;\n      case LUA_VTHREAD: o = gco2th(o)->gclist; break;\n      case LUA_VPROTO: o = gco2p(o)->gclist; break;\n      case LUA_VUSERDATA:\n        assert(gco2u(o)->nuvalue > 0);\n        o = gco2u(o)->gclist;\n        break;\n      default: assert(0);  /* other objects cannot be in a gray list */\n    }\n  }\n  return total;\n}\n\n\n/*\n** Check objects in gray lists.\n*/\nstatic l_mem checkgrays (global_State *g) {\n  l_mem total = 0;  /* count number of elements in all lists */\n  if (!keepinvariant(g)) return total;\n  total += checkgraylist(g, g->gray);\n  total += checkgraylist(g, g->grayagain);\n  total += checkgraylist(g, g->weak);\n  total += checkgraylist(g, g->allweak);\n  total += checkgraylist(g, g->ephemeron);\n  return total;\n}\n\n\n/*\n** Check whether 'o' should be in a gray list. If so, increment\n** 'count' and check its TESTBIT. (It must have been previously set by\n** 'checkgraylist'.)\n*/\nstatic void incifingray (global_State *g, GCObject *o, l_mem *count) {\n  if (!keepinvariant(g))\n    return;  /* gray lists not being kept in these phases */\n  if (o->tt == LUA_VUPVAL) {\n    /* only open upvalues can be gray */\n    assert(!isgray(o) || upisopen(gco2upv(o)));\n    return;  /* upvalues are never in gray lists */\n  }\n  /* these are the ones that must be in gray lists */\n  if (isgray(o) || getage(o) == G_TOUCHED2) {\n    (*count)++;\n    assert(testbit(o->marked, TESTBIT));\n    resetbit(o->marked, TESTBIT);  /* prepare for next cycle */\n  }\n}\n\n\nstatic l_mem checklist (global_State *g, int maybedead, int tof,\n  GCObject *newl, GCObject *survival, GCObject *old, GCObject *reallyold) {\n  GCObject *o;\n  l_mem total = 0;  /* number of object that should be in  gray lists */\n  for (o = newl; o != survival; o = o->next) {\n    checkobject(g, o, maybedead, G_NEW);\n    incifingray(g, o, &total);\n    assert(!tof == !tofinalize(o));\n  }\n  for (o = survival; o != old; o = o->next) {\n    checkobject(g, o, 0, G_SURVIVAL);\n    incifingray(g, o, &total);\n    assert(!tof == !tofinalize(o));\n  }\n  for (o = old; o != reallyold; o = o->next) {\n    checkobject(g, o, 0, G_OLD1);\n    incifingray(g, o, &total);\n    assert(!tof == !tofinalize(o));\n  }\n  for (o = reallyold; o != NULL; o = o->next) {\n    checkobject(g, o, 0, G_OLD);\n    incifingray(g, o, &total);\n    assert(!tof == !tofinalize(o));\n  }\n  return total;\n}\n\n\nint lua_checkmemory (lua_State *L) {\n  global_State *g = G(L);\n  GCObject *o;\n  int maybedead;\n  l_mem totalin;  /* total of objects that are in gray lists */\n  l_mem totalshould;  /* total of objects that should be in gray lists */\n  if (keepinvariant(g)) {\n    assert(!iswhite(mainthread(g)));\n    assert(!iswhite(gcvalue(&g->l_registry)));\n  }\n  assert(!isdead(g, gcvalue(&g->l_registry)));\n  assert(g->sweepgc == NULL || issweepphase(g));\n  totalin = checkgrays(g);\n\n  /* check 'fixedgc' list */\n  for (o = g->fixedgc; o != NULL; o = o->next) {\n    assert(o->tt == LUA_VSHRSTR && isgray(o) && getage(o) == G_OLD);\n  }\n\n  /* check 'allgc' list */\n  maybedead = (GCSatomic < g->gcstate && g->gcstate <= GCSswpallgc);\n  totalshould = checklist(g, maybedead, 0, g->allgc,\n                             g->survival, g->old1, g->reallyold);\n\n  /* check 'finobj' list */\n  totalshould += checklist(g, 0, 1, g->finobj,\n                              g->finobjsur, g->finobjold1, g->finobjrold);\n\n  /* check 'tobefnz' list */\n  for (o = g->tobefnz; o != NULL; o = o->next) {\n    checkobject(g, o, 0, G_NEW);\n    incifingray(g, o, &totalshould);\n    assert(tofinalize(o));\n    assert(o->tt == LUA_VUSERDATA || o->tt == LUA_VTABLE);\n  }\n  if (keepinvariant(g))\n    assert(totalin == totalshould);\n  return 0;\n}\n\n/* }====================================================== */\n\n\n\n/*\n** {======================================================\n** Disassembler\n** =======================================================\n*/\n\n\nstatic char *buildop (Proto *p, int pc, char *buff) {\n  char *obuff = buff;\n  Instruction i = p->code[pc];\n  OpCode o = GET_OPCODE(i);\n  const char *name = opnames[o];\n  int line = luaG_getfuncline(p, pc);\n  int lineinfo = (p->lineinfo != NULL) ? p->lineinfo[pc] : 0;\n  if (lineinfo == ABSLINEINFO)\n    buff += sprintf(buff, \"(__\");\n  else\n    buff += sprintf(buff, \"(%2d\", lineinfo);\n  buff += sprintf(buff, \" - %4d) %4d - \", line, pc);\n  switch (getOpMode(o)) {\n    case iABC:\n      sprintf(buff, \"%-12s%4d %4d %4d%s\", name,\n              GETARG_A(i), GETARG_B(i), GETARG_C(i),\n              GETARG_k(i) ? \" (k)\" : \"\");\n      break;\n    case ivABC:\n      sprintf(buff, \"%-12s%4d %4d %4d%s\", name,\n              GETARG_A(i), GETARG_vB(i), GETARG_vC(i),\n              GETARG_k(i) ? \" (k)\" : \"\");\n      break;\n    case iABx:\n      sprintf(buff, \"%-12s%4d %4d\", name, GETARG_A(i), GETARG_Bx(i));\n      break;\n    case iAsBx:\n      sprintf(buff, \"%-12s%4d %4d\", name, GETARG_A(i), GETARG_sBx(i));\n      break;\n    case iAx:\n      sprintf(buff, \"%-12s%4d\", name, GETARG_Ax(i));\n      break;\n    case isJ:\n      sprintf(buff, \"%-12s%4d\", name, GETARG_sJ(i));\n      break;\n  }\n  return obuff;\n}\n\n\n#if 0\nvoid luaI_printcode (Proto *pt, int size) {\n  int pc;\n  for (pc=0; pc<size; pc++) {\n    char buff[100];\n    printf(\"%s\\n\", buildop(pt, pc, buff));\n  }\n  printf(\"-------\\n\");\n}\n\n\nvoid luaI_printinst (Proto *pt, int pc) {\n  char buff[100];\n  printf(\"%s\\n\", buildop(pt, pc, buff));\n}\n#endif\n\n\nstatic int listcode (lua_State *L) {\n  int pc;\n  Proto *p;\n  luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),\n                 1, \"Lua function expected\");\n  p = getproto(obj_at(L, 1));\n  lua_newtable(L);\n  setnameval(L, \"maxstack\", p->maxstacksize);\n  setnameval(L, \"numparams\", p->numparams);\n  for (pc=0; pc<p->sizecode; pc++) {\n    char buff[100];\n    lua_pushinteger(L, pc+1);\n    lua_pushstring(L, buildop(p, pc, buff));\n    lua_settable(L, -3);\n  }\n  return 1;\n}\n\n\nstatic int printcode (lua_State *L) {\n  int pc;\n  Proto *p;\n  luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),\n                 1, \"Lua function expected\");\n  p = getproto(obj_at(L, 1));\n  printf(\"maxstack: %d\\n\", p->maxstacksize);\n  printf(\"numparams: %d\\n\", p->numparams);\n  for (pc=0; pc<p->sizecode; pc++) {\n    char buff[100];\n    printf(\"%s\\n\", buildop(p, pc, buff));\n  }\n  return 0;\n}\n\n\nstatic int listk (lua_State *L) {\n  Proto *p;\n  int i;\n  luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),\n                 1, \"Lua function expected\");\n  p = getproto(obj_at(L, 1));\n  lua_createtable(L, p->sizek, 0);\n  for (i=0; i<p->sizek; i++) {\n    pushobject(L, p->k+i);\n    lua_rawseti(L, -2, i+1);\n  }\n  return 1;\n}\n\n\nstatic int listabslineinfo (lua_State *L) {\n  Proto *p;\n  int i;\n  luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),\n                 1, \"Lua function expected\");\n  p = getproto(obj_at(L, 1));\n  luaL_argcheck(L, p->abslineinfo != NULL, 1, \"function has no debug info\");\n  lua_createtable(L, 2 * p->sizeabslineinfo, 0);\n  for (i=0; i < p->sizeabslineinfo; i++) {\n    lua_pushinteger(L, p->abslineinfo[i].pc);\n    lua_rawseti(L, -2, 2 * i + 1);\n    lua_pushinteger(L, p->abslineinfo[i].line);\n    lua_rawseti(L, -2, 2 * i + 2);\n  }\n  return 1;\n}\n\n\nstatic int listlocals (lua_State *L) {\n  Proto *p;\n  int pc = cast_int(luaL_checkinteger(L, 2)) - 1;\n  int i = 0;\n  const char *name;\n  luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),\n                 1, \"Lua function expected\");\n  p = getproto(obj_at(L, 1));\n  while ((name = luaF_getlocalname(p, ++i, pc)) != NULL)\n    lua_pushstring(L, name);\n  return i-1;\n}\n\n/* }====================================================== */\n\n\n\nvoid lua_printstack (lua_State *L) {\n  int i;\n  int n = lua_gettop(L);\n  printf(\"stack: >>\\n\");\n  for (i = 1; i <= n; i++) {\n    printf(\"%3d: \", i);\n    lua_printvalue(s2v(L->ci->func.p + i));\n    printf(\"\\n\");\n  }\n  printf(\"<<\\n\");\n}\n\n\nint lua_printallstack (lua_State *L) {\n  StkId p;\n  int i = 1;\n  CallInfo *ci = &L->base_ci;\n  printf(\"stack: >>\\n\");\n  for (p = L->stack.p; p < L->top.p; p++) {\n    if (ci != NULL && p == ci->func.p) {\n      printf(\"  ---\\n\");\n      if (ci == L->ci)\n        ci = NULL;  /* printed last frame */\n      else\n        ci = ci->next;\n    }\n    printf(\"%3d: \", i++);\n    lua_printvalue(s2v(p));\n    printf(\"\\n\");\n  }\n  printf(\"<<\\n\");\n  return 0;\n}\n\n\nstatic int get_limits (lua_State *L) {\n  lua_createtable(L, 0, 5);\n  setnameval(L, \"IS32INT\", LUAI_IS32INT);\n  setnameval(L, \"MAXARG_Ax\", MAXARG_Ax);\n  setnameval(L, \"MAXARG_Bx\", MAXARG_Bx);\n  setnameval(L, \"OFFSET_sBx\", OFFSET_sBx);\n  setnameval(L, \"NUM_OPCODES\", NUM_OPCODES);\n  return 1;\n}\n\n\nstatic int get_sizes (lua_State *L) {\n  lua_newtable(L);\n  setnameval(L, \"Lua state\", sizeof(lua_State));\n  setnameval(L, \"global state\", sizeof(global_State));\n  setnameval(L, \"TValue\", sizeof(TValue));\n  setnameval(L, \"Node\", sizeof(Node));\n  setnameval(L, \"stack Value\", sizeof(StackValue));\n  return 1;\n}\n\n\nstatic int mem_query (lua_State *L) {\n  if (lua_isnone(L, 1)) {\n    lua_pushinteger(L, cast_Integer(l_memcontrol.total));\n    lua_pushinteger(L, cast_Integer(l_memcontrol.numblocks));\n    lua_pushinteger(L, cast_Integer(l_memcontrol.maxmem));\n    return 3;\n  }\n  else if (lua_isnumber(L, 1)) {\n    unsigned long limit = cast(unsigned long, luaL_checkinteger(L, 1));\n    if (limit == 0) limit = ULONG_MAX;\n    l_memcontrol.memlimit = limit;\n    return 0;\n  }\n  else {\n    const char *t = luaL_checkstring(L, 1);\n    int i;\n    for (i = LUA_NUMTYPES - 1; i >= 0; i--) {\n      if (strcmp(t, ttypename(i)) == 0) {\n        lua_pushinteger(L, cast_Integer(l_memcontrol.objcount[i]));\n        return 1;\n      }\n    }\n    return luaL_error(L, \"unknown type '%s'\", t);\n  }\n}\n\n\nstatic int alloc_count (lua_State *L) {\n  if (lua_isnone(L, 1))\n    l_memcontrol.countlimit = cast(unsigned long, ~0L);\n  else\n    l_memcontrol.countlimit = cast(unsigned long, luaL_checkinteger(L, 1));\n  return 0;\n}\n\n\nstatic int alloc_failnext (lua_State *L) {\n  UNUSED(L);\n  l_memcontrol.failnext = 1;\n  return 0;\n}\n\n\nstatic int settrick (lua_State *L) {\n  if (ttisnil(obj_at(L, 1)))\n    l_Trick = NULL;\n  else\n    l_Trick = gcvalue(obj_at(L, 1));\n  return 0;\n}\n\n\nstatic int gc_color (lua_State *L) {\n  TValue *o;\n  luaL_checkany(L, 1);\n  o = obj_at(L, 1);\n  if (!iscollectable(o))\n    lua_pushstring(L, \"no collectable\");\n  else {\n    GCObject *obj = gcvalue(o);\n    lua_pushstring(L, isdead(G(L), obj) ? \"dead\" :\n                      iswhite(obj) ? \"white\" :\n                      isblack(obj) ? \"black\" : \"gray\");\n  }\n  return 1;\n}\n\n\nstatic int gc_age (lua_State *L) {\n  TValue *o;\n  luaL_checkany(L, 1);\n  o = obj_at(L, 1);\n  if (!iscollectable(o))\n    lua_pushstring(L, \"no collectable\");\n  else {\n    static const char *gennames[] = {\"new\", \"survival\", \"old0\", \"old1\",\n                                     \"old\", \"touched1\", \"touched2\"};\n    GCObject *obj = gcvalue(o);\n    lua_pushstring(L, gennames[getage(obj)]);\n  }\n  return 1;\n}\n\n\nstatic int gc_printobj (lua_State *L) {\n  TValue *o;\n  luaL_checkany(L, 1);\n  o = obj_at(L, 1);\n  if (!iscollectable(o))\n    printf(\"no collectable\\n\");\n  else {\n    GCObject *obj = gcvalue(o);\n    printobj(G(L), obj);\n    printf(\"\\n\");\n  }\n  return 0;\n}\n\n\nstatic const char *const statenames[] = {\n  \"propagate\", \"enteratomic\", \"atomic\", \"sweepallgc\", \"sweepfinobj\",\n  \"sweeptobefnz\", \"sweepend\", \"callfin\", \"pause\", \"\"};\n\nstatic int gc_state (lua_State *L) {\n  static const int states[] = {\n    GCSpropagate, GCSenteratomic, GCSatomic, GCSswpallgc, GCSswpfinobj,\n    GCSswptobefnz, GCSswpend, GCScallfin, GCSpause, -1};\n  int option = states[luaL_checkoption(L, 1, \"\", statenames)];\n  global_State *g = G(L);\n  if (option == -1) {\n    lua_pushstring(L, statenames[g->gcstate]);\n    return 1;\n  }\n  else {\n    if (g->gckind != KGC_INC)\n      luaL_error(L, \"cannot change states in generational mode\");\n    lua_lock(L);\n    if (option < g->gcstate) {  /* must cross 'pause'? */\n      luaC_runtilstate(L, GCSpause, 1);  /* run until pause */\n    }\n    luaC_runtilstate(L, option, 0);  /* do not skip propagation state */\n    lua_assert(g->gcstate == option);\n    lua_unlock(L);\n    return 0;\n  }\n}\n\n\nstatic int tracinggc = 0;\nvoid luai_tracegctest (lua_State *L, int first) {\n  if (!tracinggc) return;\n  else {\n    global_State *g = G(L);\n    lua_unlock(L);\n    g->gcstp = GCSTPGC;\n    lua_checkstack(L, 10);\n    lua_getfield(L, LUA_REGISTRYINDEX, \"tracegc\");\n    lua_pushboolean(L, first);\n    lua_call(L, 1, 0);\n    g->gcstp = 0;\n    lua_lock(L);\n  }\n}\n\n\nstatic int tracegc (lua_State *L) {\n  if (lua_isnil(L, 1))\n    tracinggc = 0;\n  else {\n    tracinggc = 1;\n    lua_setfield(L, LUA_REGISTRYINDEX, \"tracegc\");\n  }\n  return 0;\n}\n\n\nstatic int hash_query (lua_State *L) {\n  if (lua_isnone(L, 2)) {\n    TString *ts;\n    luaL_argcheck(L, lua_type(L, 1) == LUA_TSTRING, 1, \"string expected\");\n    ts = tsvalue(obj_at(L, 1));\n    if (ts->tt == LUA_VLNGSTR)\n      luaS_hashlongstr(ts);  /* make sure long string has a hash */\n    lua_pushinteger(L, cast_int(ts->hash));\n  }\n  else {\n    TValue *o = obj_at(L, 1);\n    Table *t;\n    luaL_checktype(L, 2, LUA_TTABLE);\n    t = hvalue(obj_at(L, 2));\n    lua_pushinteger(L, cast_Integer(luaH_mainposition(t, o) - t->node));\n  }\n  return 1;\n}\n\n\nstatic int stacklevel (lua_State *L) {\n  int a = 0;\n  lua_pushinteger(L, cast_Integer(L->top.p - L->stack.p));\n  lua_pushinteger(L, stacksize(L));\n  lua_pushinteger(L, cast_Integer(L->nCcalls));\n  lua_pushinteger(L, L->nci);\n  lua_pushinteger(L, (lua_Integer)(size_t)&a);\n  return 5;\n}\n\n\nstatic int table_query (lua_State *L) {\n  const Table *t;\n  int i = cast_int(luaL_optinteger(L, 2, -1));\n  unsigned int asize;\n  luaL_checktype(L, 1, LUA_TTABLE);\n  t = hvalue(obj_at(L, 1));\n  asize = t->asize;\n  if (i == -1) {\n    lua_pushinteger(L, cast_Integer(asize));\n    lua_pushinteger(L, cast_Integer(allocsizenode(t)));\n    lua_pushinteger(L, cast_Integer(asize > 0 ? *lenhint(t) : 0));\n    return 3;\n  }\n  else if (cast_uint(i) < asize) {\n    lua_pushinteger(L, i);\n    if (!tagisempty(*getArrTag(t, i)))\n      arr2obj(t, cast_uint(i), s2v(L->top.p));\n    else\n      setnilvalue(s2v(L->top.p));\n    api_incr_top(L);\n    lua_pushnil(L);\n  }\n  else if (cast_uint(i -= cast_int(asize)) < sizenode(t)) {\n    TValue k;\n    getnodekey(L, &k, gnode(t, i));\n    if (!isempty(gval(gnode(t, i))) ||\n        ttisnil(&k) ||\n        ttisnumber(&k)) {\n      pushobject(L, &k);\n    }\n    else\n      lua_pushliteral(L, \"<undef>\");\n    if (!isempty(gval(gnode(t, i))))\n      pushobject(L, gval(gnode(t, i)));\n    else\n      lua_pushnil(L);\n    lua_pushinteger(L, gnext(&t->node[i]));\n  }\n  return 3;\n}\n\n\nstatic int gc_query (lua_State *L) {\n  global_State *g = G(L);\n  lua_pushstring(L, g->gckind == KGC_INC ? \"inc\"\n                  : g->gckind == KGC_GENMAJOR ? \"genmajor\"\n                  : \"genminor\");\n  lua_pushstring(L, statenames[g->gcstate]);\n  lua_pushinteger(L, cast_st2S(gettotalbytes(g)));\n  lua_pushinteger(L, cast_st2S(g->GCdebt));\n  lua_pushinteger(L, cast_st2S(g->GCmarked));\n  lua_pushinteger(L, cast_st2S(g->GCmajorminor));\n  return 6;\n}\n\n\nstatic int test_codeparam (lua_State *L) {\n  lua_Integer p = luaL_checkinteger(L, 1);\n  lua_pushinteger(L, luaO_codeparam(cast_uint(p)));\n  return 1;\n}\n\n\nstatic int test_applyparam (lua_State *L) {\n  lua_Integer p = luaL_checkinteger(L, 1);\n  lua_Integer x = luaL_checkinteger(L, 2);\n  lua_pushinteger(L, cast_Integer(luaO_applyparam(cast_byte(p), x)));\n  return 1;\n}\n\n\nstatic int string_query (lua_State *L) {\n  stringtable *tb = &G(L)->strt;\n  int s = cast_int(luaL_optinteger(L, 1, 0)) - 1;\n  if (s == -1) {\n    lua_pushinteger(L ,tb->size);\n    lua_pushinteger(L ,tb->nuse);\n    return 2;\n  }\n  else if (s < tb->size) {\n    TString *ts;\n    int n = 0;\n    for (ts = tb->hash[s]; ts != NULL; ts = ts->u.hnext) {\n      setsvalue2s(L, L->top.p, ts);\n      api_incr_top(L);\n      n++;\n    }\n    return n;\n  }\n  else return 0;\n}\n\n\nstatic int getreftable (lua_State *L) {\n  if (lua_istable(L, 2))  /* is there a table as second argument? */\n    return 2;  /* use it as the table */\n  else\n    return LUA_REGISTRYINDEX;  /* default is to use the register */\n}\n\n\nstatic int tref (lua_State *L) {\n  int t = getreftable(L);\n  int level = lua_gettop(L);\n  luaL_checkany(L, 1);\n  lua_pushvalue(L, 1);\n  lua_pushinteger(L, luaL_ref(L, t));\n  cast_void(level);  /* to avoid warnings */\n  lua_assert(lua_gettop(L) == level+1);  /* +1 for result */\n  return 1;\n}\n\n\nstatic int getref (lua_State *L) {\n  int t = getreftable(L);\n  int level = lua_gettop(L);\n  lua_rawgeti(L, t, luaL_checkinteger(L, 1));\n  cast_void(level);  /* to avoid warnings */\n  lua_assert(lua_gettop(L) == level+1);\n  return 1;\n}\n\nstatic int unref (lua_State *L) {\n  int t = getreftable(L);\n  int level = lua_gettop(L);\n  luaL_unref(L, t, cast_int(luaL_checkinteger(L, 1)));\n  cast_void(level);  /* to avoid warnings */\n  lua_assert(lua_gettop(L) == level);\n  return 0;\n}\n\n\nstatic int upvalue (lua_State *L) {\n  int n = cast_int(luaL_checkinteger(L, 2));\n  luaL_checktype(L, 1, LUA_TFUNCTION);\n  if (lua_isnone(L, 3)) {\n    const char *name = lua_getupvalue(L, 1, n);\n    if (name == NULL) return 0;\n    lua_pushstring(L, name);\n    return 2;\n  }\n  else {\n    const char *name = lua_setupvalue(L, 1, n);\n    lua_pushstring(L, name);\n    return 1;\n  }\n}\n\n\nstatic int newuserdata (lua_State *L) {\n  size_t size = cast_sizet(luaL_optinteger(L, 1, 0));\n  int nuv = cast_int(luaL_optinteger(L, 2, 0));\n  char *p = cast_charp(lua_newuserdatauv(L, size, nuv));\n  while (size--) *p++ = '\\0';\n  return 1;\n}\n\n\nstatic int pushuserdata (lua_State *L) {\n  lua_Integer u = luaL_checkinteger(L, 1);\n  lua_pushlightuserdata(L, cast_voidp(cast_sizet(u)));\n  return 1;\n}\n\n\nstatic int udataval (lua_State *L) {\n  lua_pushinteger(L, cast_st2S(cast_sizet(lua_touserdata(L, 1))));\n  return 1;\n}\n\n\nstatic int doonnewstack (lua_State *L) {\n  lua_State *L1 = lua_newthread(L);\n  size_t l;\n  const char *s = luaL_checklstring(L, 1, &l);\n  int status = luaL_loadbuffer(L1, s, l, s);\n  if (status == LUA_OK)\n    status = lua_pcall(L1, 0, 0, 0);\n  lua_pushinteger(L, status);\n  return 1;\n}\n\n\nstatic int s2d (lua_State *L) {\n  lua_pushnumber(L, cast_num(*cast(const double *, luaL_checkstring(L, 1))));\n  return 1;\n}\n\n\nstatic int d2s (lua_State *L) {\n  double d = cast(double, luaL_checknumber(L, 1));\n  lua_pushlstring(L, cast_charp(&d), sizeof(d));\n  return 1;\n}\n\n\nstatic int num2int (lua_State *L) {\n  lua_pushinteger(L, lua_tointeger(L, 1));\n  return 1;\n}\n\n\nstatic int makeseed (lua_State *L) {\n  lua_pushinteger(L, cast_Integer(luaL_makeseed(L)));\n  return 1;\n}\n\n\nstatic int newstate (lua_State *L) {\n  void *ud;\n  lua_Alloc f = lua_getallocf(L, &ud);\n  lua_State *L1 = lua_newstate(f, ud, 0);\n  if (L1) {\n    lua_atpanic(L1, tpanic);\n    lua_pushlightuserdata(L, L1);\n  }\n  else\n    lua_pushnil(L);\n  return 1;\n}\n\n\nstatic lua_State *getstate (lua_State *L) {\n  lua_State *L1 = cast(lua_State *, lua_touserdata(L, 1));\n  luaL_argcheck(L, L1 != NULL, 1, \"state expected\");\n  return L1;\n}\n\n\nstatic int loadlib (lua_State *L) {\n  lua_State *L1 = getstate(L);\n  int load = cast_int(luaL_checkinteger(L, 2));\n  int preload = cast_int(luaL_checkinteger(L, 3));\n  luaL_openselectedlibs(L1, load, preload);\n  luaL_requiref(L1, \"T\", luaB_opentests, 0);\n  lua_assert(lua_type(L1, -1) == LUA_TTABLE);\n  /* 'requiref' should not reload module already loaded... */\n  luaL_requiref(L1, \"T\", NULL, 1);  /* seg. fault if it reloads */\n  /* ...but should return the same module */\n  lua_assert(lua_compare(L1, -1, -2, LUA_OPEQ));\n  return 0;\n}\n\nstatic int closestate (lua_State *L) {\n  lua_State *L1 = getstate(L);\n  lua_close(L1);\n  return 0;\n}\n\nstatic int doremote (lua_State *L) {\n  lua_State *L1 = getstate(L);\n  size_t lcode;\n  const char *code = luaL_checklstring(L, 2, &lcode);\n  int status;\n  lua_settop(L1, 0);\n  status = luaL_loadbuffer(L1, code, lcode, code);\n  if (status == LUA_OK)\n    status = lua_pcall(L1, 0, LUA_MULTRET, 0);\n  if (status != LUA_OK) {\n    lua_pushnil(L);\n    lua_pushstring(L, lua_tostring(L1, -1));\n    lua_pushinteger(L, status);\n    return 3;\n  }\n  else {\n    int i = 0;\n    while (!lua_isnone(L1, ++i))\n      lua_pushstring(L, lua_tostring(L1, i));\n    lua_pop(L1, i-1);\n    return i-1;\n  }\n}\n\n\nstatic int log2_aux (lua_State *L) {\n  unsigned int x = (unsigned int)luaL_checkinteger(L, 1);\n  lua_pushinteger(L, luaO_ceillog2(x));\n  return 1;\n}\n\n\nstruct Aux { jmp_buf jb; const char *paniccode; lua_State *L; };\n\n/*\n** does a long-jump back to \"main program\".\n*/\nstatic int panicback (lua_State *L) {\n  struct Aux *b;\n  lua_checkstack(L, 1);  /* open space for 'Aux' struct */\n  lua_getfield(L, LUA_REGISTRYINDEX, \"_jmpbuf\");  /* get 'Aux' struct */\n  b = (struct Aux *)lua_touserdata(L, -1);\n  lua_pop(L, 1);  /* remove 'Aux' struct */\n  runC(b->L, L, b->paniccode);  /* run optional panic code */\n  longjmp(b->jb, 1);\n  return 1;  /* to avoid warnings */\n}\n\nstatic int checkpanic (lua_State *L) {\n  struct Aux b;\n  void *ud;\n  lua_State *L1;\n  const char *code = luaL_checkstring(L, 1);\n  lua_Alloc f = lua_getallocf(L, &ud);\n  b.paniccode = luaL_optstring(L, 2, \"\");\n  b.L = L;\n  L1 = lua_newstate(f, ud, 0);  /* create new state */\n  if (L1 == NULL) {  /* error? */\n    lua_pushstring(L, MEMERRMSG);\n    return 1;\n  }\n  lua_atpanic(L1, panicback);  /* set its panic function */\n  lua_pushlightuserdata(L1, &b);\n  lua_setfield(L1, LUA_REGISTRYINDEX, \"_jmpbuf\");  /* store 'Aux' struct */\n  if (setjmp(b.jb) == 0) {  /* set jump buffer */\n    runC(L, L1, code);  /* run code unprotected */\n    lua_pushliteral(L, \"no errors\");\n  }\n  else {  /* error handling */\n    /* move error message to original state */\n    lua_pushstring(L, lua_tostring(L1, -1));\n  }\n  lua_close(L1);\n  return 1;\n}\n\n\nstatic int externKstr (lua_State *L) {\n  size_t len;\n  const char *s = luaL_checklstring(L, 1, &len);\n  lua_pushexternalstring(L, s, len, NULL, NULL);\n  return 1;\n}\n\n\n/*\n** Create a buffer with the content of a given string and then\n** create an external string using that buffer. Use the allocation\n** function from Lua to create and free the buffer.\n*/\nstatic int externstr (lua_State *L) {\n  size_t len;\n  const char *s = luaL_checklstring(L, 1, &len);\n  void *ud;\n  lua_Alloc allocf = lua_getallocf(L, &ud);  /* get allocation function */\n  /* create the buffer */\n  char *buff = cast_charp((*allocf)(ud, NULL, 0, len + 1));\n  if (buff == NULL) {  /* memory error? */\n    lua_pushliteral(L, \"not enough memory\");\n    lua_error(L);  /* raise a memory error */\n  }\n  /* copy string content to buffer, including ending 0 */\n  memcpy(buff, s, (len + 1) * sizeof(char));\n  /* create external string */\n  lua_pushexternalstring(L, buff, len, allocf, ud);\n  return 1;\n}\n\n\n/*\n** {====================================================================\n** function to test the API with C. It interprets a kind of assembler\n** language with calls to the API, so the test can be driven by Lua code\n** =====================================================================\n*/\n\n\nstatic void sethookaux (lua_State *L, int mask, int count, const char *code);\n\nstatic const char *const delimits = \" \\t\\n,;\";\n\nstatic void skip (const char **pc) {\n  for (;;) {\n    if (**pc != '\\0' && strchr(delimits, **pc)) (*pc)++;\n    else if (**pc == '#') {  /* comment? */\n      while (**pc != '\\n' && **pc != '\\0') (*pc)++;  /* until end-of-line */\n    }\n    else break;\n  }\n}\n\nstatic int getnum_aux (lua_State *L, lua_State *L1, const char **pc) {\n  int res = 0;\n  int sig = 1;\n  skip(pc);\n  if (**pc == '.') {\n    res = cast_int(lua_tointeger(L1, -1));\n    lua_pop(L1, 1);\n    (*pc)++;\n    return res;\n  }\n  else if (**pc == '*') {\n    res = lua_gettop(L1);\n    (*pc)++;\n    return res;\n  }\n  else if (**pc == '!') {\n    (*pc)++;\n    if (**pc == 'G')\n      res = LUA_RIDX_GLOBALS;\n    else if (**pc == 'M')\n      res = LUA_RIDX_MAINTHREAD;\n    else lua_assert(0);\n    (*pc)++;\n    return res;\n  }\n  else if (**pc == '-') {\n    sig = -1;\n    (*pc)++;\n  }\n  if (!lisdigit(cast_uchar(**pc)))\n    luaL_error(L, \"number expected (%s)\", *pc);\n  while (lisdigit(cast_uchar(**pc))) res = res*10 + (*(*pc)++) - '0';\n  return sig*res;\n}\n\nstatic const char *getstring_aux (lua_State *L, char *buff, const char **pc) {\n  int i = 0;\n  skip(pc);\n  if (**pc == '\"' || **pc == '\\'') {  /* quoted string? */\n    int quote = *(*pc)++;\n    while (**pc != quote) {\n      if (**pc == '\\0') luaL_error(L, \"unfinished string in C script\");\n      buff[i++] = *(*pc)++;\n    }\n    (*pc)++;\n  }\n  else {\n    while (**pc != '\\0' && !strchr(delimits, **pc))\n      buff[i++] = *(*pc)++;\n  }\n  buff[i] = '\\0';\n  return buff;\n}\n\n\nstatic int getindex_aux (lua_State *L, lua_State *L1, const char **pc) {\n  skip(pc);\n  switch (*(*pc)++) {\n    case 'R': return LUA_REGISTRYINDEX;\n    case 'U': return lua_upvalueindex(getnum_aux(L, L1, pc));\n    default: {\n      int n;\n      (*pc)--;  /* to read again */\n      n = getnum_aux(L, L1, pc);\n      if (n == 0) return 0;\n      else return lua_absindex(L1, n);\n    }\n  }\n}\n\n\nstatic const char *const statcodes[] = {\"OK\", \"YIELD\", \"ERRRUN\",\n    \"ERRSYNTAX\", MEMERRMSG, \"ERRERR\"};\n\n/*\n** Avoid these stat codes from being collected, to avoid possible\n** memory error when pushing them.\n*/\nstatic void regcodes (lua_State *L) {\n  unsigned int i;\n  for (i = 0; i < sizeof(statcodes) / sizeof(statcodes[0]); i++) {\n    lua_pushboolean(L, 1);\n    lua_setfield(L, LUA_REGISTRYINDEX, statcodes[i]);\n  }\n}\n\n\n#define EQ(s1)\t(strcmp(s1, inst) == 0)\n\n#define getnum\t\t(getnum_aux(L, L1, &pc))\n#define getstring\t(getstring_aux(L, buff, &pc))\n#define getindex\t(getindex_aux(L, L1, &pc))\n\n\nstatic int testC (lua_State *L);\nstatic int Cfunck (lua_State *L, int status, lua_KContext ctx);\n\n/*\n** arithmetic operation encoding for 'arith' instruction\n** LUA_OPIDIV  -> \\\n** LUA_OPSHL   -> <\n** LUA_OPSHR   -> >\n** LUA_OPUNM   -> _\n** LUA_OPBNOT  -> !\n*/\nstatic const char ops[] = \"+-*%^/\\\\&|~<>_!\";\n\nstatic int runC (lua_State *L, lua_State *L1, const char *pc) {\n  char buff[300];\n  int status = 0;\n  if (pc == NULL) return luaL_error(L, \"attempt to runC null script\");\n  for (;;) {\n    const char *inst = getstring;\n    if EQ(\"\") return 0;\n    else if EQ(\"absindex\") {\n      lua_pushinteger(L1, getindex);\n    }\n    else if EQ(\"append\") {\n      int t = getindex;\n      int i = cast_int(lua_rawlen(L1, t));\n      lua_rawseti(L1, t, i + 1);\n    }\n    else if EQ(\"arith\") {\n      int op;\n      skip(&pc);\n      op = cast_int(strchr(ops, *pc++) - ops);\n      lua_arith(L1, op);\n    }\n    else if EQ(\"call\") {\n      int narg = getnum;\n      int nres = getnum;\n      lua_call(L1, narg, nres);\n    }\n    else if EQ(\"callk\") {\n      int narg = getnum;\n      int nres = getnum;\n      int i = getindex;\n      lua_callk(L1, narg, nres, i, Cfunck);\n    }\n    else if EQ(\"checkstack\") {\n      int sz = getnum;\n      const char *msg = getstring;\n      if (*msg == '\\0')\n        msg = NULL;  /* to test 'luaL_checkstack' with no message */\n      luaL_checkstack(L1, sz, msg);\n    }\n    else if EQ(\"rawcheckstack\") {\n      int sz = getnum;\n      lua_pushboolean(L1, lua_checkstack(L1, sz));\n    }\n    else if EQ(\"compare\") {\n      const char *opt = getstring;  /* EQ, LT, or LE */\n      int op = (opt[0] == 'E') ? LUA_OPEQ\n                               : (opt[1] == 'T') ? LUA_OPLT : LUA_OPLE;\n      int a = getindex;\n      int b = getindex;\n      lua_pushboolean(L1, lua_compare(L1, a, b, op));\n    }\n    else if EQ(\"concat\") {\n      lua_concat(L1, getnum);\n    }\n    else if EQ(\"copy\") {\n      int f = getindex;\n      lua_copy(L1, f, getindex);\n    }\n    else if EQ(\"func2num\") {\n      lua_CFunction func = lua_tocfunction(L1, getindex);\n      lua_pushinteger(L1, cast_st2S(cast_sizet(func)));\n    }\n    else if EQ(\"getfield\") {\n      int t = getindex;\n      int tp = lua_getfield(L1, t, getstring);\n      lua_assert(tp == lua_type(L1, -1));\n    }\n    else if EQ(\"getglobal\") {\n      lua_getglobal(L1, getstring);\n    }\n    else if EQ(\"getmetatable\") {\n      if (lua_getmetatable(L1, getindex) == 0)\n        lua_pushnil(L1);\n    }\n    else if EQ(\"gettable\") {\n      int tp = lua_gettable(L1, getindex);\n      lua_assert(tp == lua_type(L1, -1));\n    }\n    else if EQ(\"gettop\") {\n      lua_pushinteger(L1, lua_gettop(L1));\n    }\n    else if EQ(\"gsub\") {\n      int a = getnum; int b = getnum; int c = getnum;\n      luaL_gsub(L1, lua_tostring(L1, a),\n                    lua_tostring(L1, b),\n                    lua_tostring(L1, c));\n    }\n    else if EQ(\"insert\") {\n      lua_insert(L1, getnum);\n    }\n    else if EQ(\"iscfunction\") {\n      lua_pushboolean(L1, lua_iscfunction(L1, getindex));\n    }\n    else if EQ(\"isfunction\") {\n      lua_pushboolean(L1, lua_isfunction(L1, getindex));\n    }\n    else if EQ(\"isnil\") {\n      lua_pushboolean(L1, lua_isnil(L1, getindex));\n    }\n    else if EQ(\"isnull\") {\n      lua_pushboolean(L1, lua_isnone(L1, getindex));\n    }\n    else if EQ(\"isnumber\") {\n      lua_pushboolean(L1, lua_isnumber(L1, getindex));\n    }\n    else if EQ(\"isstring\") {\n      lua_pushboolean(L1, lua_isstring(L1, getindex));\n    }\n    else if EQ(\"istable\") {\n      lua_pushboolean(L1, lua_istable(L1, getindex));\n    }\n    else if EQ(\"isudataval\") {\n      lua_pushboolean(L1, lua_islightuserdata(L1, getindex));\n    }\n    else if EQ(\"isuserdata\") {\n      lua_pushboolean(L1, lua_isuserdata(L1, getindex));\n    }\n    else if EQ(\"len\") {\n      lua_len(L1, getindex);\n    }\n    else if EQ(\"Llen\") {\n      lua_pushinteger(L1, luaL_len(L1, getindex));\n    }\n    else if EQ(\"loadfile\") {\n      luaL_loadfile(L1, luaL_checkstring(L1, getnum));\n    }\n    else if EQ(\"loadstring\") {\n      size_t slen;\n      const char *s = luaL_checklstring(L1, getnum, &slen);\n      const char *name = getstring;\n      const char *mode = getstring;\n      luaL_loadbufferx(L1, s, slen, name, mode);\n    }\n    else if EQ(\"newmetatable\") {\n      lua_pushboolean(L1, luaL_newmetatable(L1, getstring));\n    }\n    else if EQ(\"newtable\") {\n      lua_newtable(L1);\n    }\n    else if EQ(\"newthread\") {\n      lua_newthread(L1);\n    }\n    else if EQ(\"resetthread\") {\n      lua_pushinteger(L1, lua_resetthread(L1));  /* deprecated */\n    }\n    else if EQ(\"newuserdata\") {\n      lua_newuserdata(L1, cast_sizet(getnum));\n    }\n    else if EQ(\"next\") {\n      lua_next(L1, -2);\n    }\n    else if EQ(\"objsize\") {\n      lua_pushinteger(L1, l_castU2S(lua_rawlen(L1, getindex)));\n    }\n    else if EQ(\"pcall\") {\n      int narg = getnum;\n      int nres = getnum;\n      status = lua_pcall(L1, narg, nres, getnum);\n    }\n    else if EQ(\"pcallk\") {\n      int narg = getnum;\n      int nres = getnum;\n      int i = getindex;\n      status = lua_pcallk(L1, narg, nres, 0, i, Cfunck);\n    }\n    else if EQ(\"pop\") {\n      lua_pop(L1, getnum);\n    }\n    else if EQ(\"printstack\") {\n      int n = getnum;\n      if (n != 0) {\n        lua_printvalue(s2v(L->ci->func.p + n));\n        printf(\"\\n\");\n      }\n      else lua_printstack(L1);\n    }\n    else if EQ(\"print\") {\n      const char *msg = getstring;\n      printf(\"%s\\n\", msg);\n    }\n    else if EQ(\"warningC\") {\n      const char *msg = getstring;\n      lua_warning(L1, msg, 1);\n    }\n    else if EQ(\"warning\") {\n      const char *msg = getstring;\n      lua_warning(L1, msg, 0);\n    }\n    else if EQ(\"pushbool\") {\n      lua_pushboolean(L1, getnum);\n    }\n    else if EQ(\"pushcclosure\") {\n      lua_pushcclosure(L1, testC, getnum);\n    }\n    else if EQ(\"pushint\") {\n      lua_pushinteger(L1, getnum);\n    }\n    else if EQ(\"pushnil\") {\n      lua_pushnil(L1);\n    }\n    else if EQ(\"pushnum\") {\n      lua_pushnumber(L1, (lua_Number)getnum);\n    }\n    else if EQ(\"pushstatus\") {\n      lua_pushstring(L1, statcodes[status]);\n    }\n    else if EQ(\"pushstring\") {\n      lua_pushstring(L1, getstring);\n    }\n    else if EQ(\"pushupvalueindex\") {\n      lua_pushinteger(L1, lua_upvalueindex(getnum));\n    }\n    else if EQ(\"pushvalue\") {\n      lua_pushvalue(L1, getindex);\n    }\n    else if EQ(\"pushfstringI\") {\n      lua_pushfstring(L1, lua_tostring(L, -2), (int)lua_tointeger(L, -1));\n    }\n    else if EQ(\"pushfstringS\") {\n      lua_pushfstring(L1, lua_tostring(L, -2), lua_tostring(L, -1));\n    }\n    else if EQ(\"pushfstringP\") {\n      lua_pushfstring(L1, lua_tostring(L, -2), lua_topointer(L, -1));\n    }\n    else if EQ(\"rawget\") {\n      int t = getindex;\n      lua_rawget(L1, t);\n    }\n    else if EQ(\"rawgeti\") {\n      int t = getindex;\n      lua_rawgeti(L1, t, getnum);\n    }\n    else if EQ(\"rawgetp\") {\n      int t = getindex;\n      lua_rawgetp(L1, t, cast_voidp(cast_sizet(getnum)));\n    }\n    else if EQ(\"rawset\") {\n      int t = getindex;\n      lua_rawset(L1, t);\n    }\n    else if EQ(\"rawseti\") {\n      int t = getindex;\n      lua_rawseti(L1, t, getnum);\n    }\n    else if EQ(\"rawsetp\") {\n      int t = getindex;\n      lua_rawsetp(L1, t, cast_voidp(cast_sizet(getnum)));\n    }\n    else if EQ(\"remove\") {\n      lua_remove(L1, getnum);\n    }\n    else if EQ(\"replace\") {\n      lua_replace(L1, getindex);\n    }\n    else if EQ(\"resume\") {\n      int i = getindex;\n      int nres;\n      status = lua_resume(lua_tothread(L1, i), L, getnum, &nres);\n    }\n    else if EQ(\"traceback\") {\n      const char *msg = getstring;\n      int level = getnum;\n      luaL_traceback(L1, L1, msg, level);\n    }\n    else if EQ(\"threadstatus\") {\n      lua_pushstring(L1, statcodes[lua_status(L1)]);\n    }\n    else if EQ(\"alloccount\") {\n      l_memcontrol.countlimit = cast_uint(getnum);\n    }\n    else if EQ(\"return\") {\n      int n = getnum;\n      if (L1 != L) {\n        int i;\n        for (i = 0; i < n; i++) {\n          int idx = -(n - i);\n          switch (lua_type(L1, idx)) {\n            case LUA_TBOOLEAN:\n              lua_pushboolean(L, lua_toboolean(L1, idx));\n              break;\n            default:\n              lua_pushstring(L, lua_tostring(L1, idx));\n              break;\n          }\n        }\n      }\n      return n;\n    }\n    else if EQ(\"rotate\") {\n      int i = getindex;\n      lua_rotate(L1, i, getnum);\n    }\n    else if EQ(\"setfield\") {\n      int t = getindex;\n      const char *s = getstring;\n      lua_setfield(L1, t, s);\n    }\n    else if EQ(\"seti\") {\n      int t = getindex;\n      lua_seti(L1, t, getnum);\n    }\n    else if EQ(\"setglobal\") {\n      const char *s = getstring;\n      lua_setglobal(L1, s);\n    }\n    else if EQ(\"sethook\") {\n      int mask = getnum;\n      int count = getnum;\n      const char *s = getstring;\n      sethookaux(L1, mask, count, s);\n    }\n    else if EQ(\"setmetatable\") {\n      int idx = getindex;\n      lua_setmetatable(L1, idx);\n    }\n    else if EQ(\"settable\") {\n      lua_settable(L1, getindex);\n    }\n    else if EQ(\"settop\") {\n      lua_settop(L1, getnum);\n    }\n    else if EQ(\"testudata\") {\n      int i = getindex;\n      lua_pushboolean(L1, luaL_testudata(L1, i, getstring) != NULL);\n    }\n    else if EQ(\"error\") {\n      lua_error(L1);\n    }\n    else if EQ(\"abort\") {\n      abort();\n    }\n    else if EQ(\"throw\") {\n#if defined(__cplusplus)\nstatic struct X { int x; } x;\n      throw x;\n#else\n      luaL_error(L1, \"C++\");\n#endif\n      break;\n    }\n    else if EQ(\"tobool\") {\n      lua_pushboolean(L1, lua_toboolean(L1, getindex));\n    }\n    else if EQ(\"tocfunction\") {\n      lua_pushcfunction(L1, lua_tocfunction(L1, getindex));\n    }\n    else if EQ(\"tointeger\") {\n      lua_pushinteger(L1, lua_tointeger(L1, getindex));\n    }\n    else if EQ(\"tonumber\") {\n      lua_pushnumber(L1, lua_tonumber(L1, getindex));\n    }\n    else if EQ(\"topointer\") {\n      lua_pushlightuserdata(L1, cast_voidp(lua_topointer(L1, getindex)));\n    }\n    else if EQ(\"touserdata\") {\n      lua_pushlightuserdata(L1, lua_touserdata(L1, getindex));\n    }\n    else if EQ(\"tostring\") {\n      const char *s = lua_tostring(L1, getindex);\n      const char *s1 = lua_pushstring(L1, s);\n      cast_void(s1);  /* to avoid warnings */\n      lua_longassert((s == NULL && s1 == NULL) || strcmp(s, s1) == 0);\n    }\n    else if EQ(\"Ltolstring\") {\n      luaL_tolstring(L1, getindex, NULL);\n    }\n    else if EQ(\"type\") {\n      lua_pushstring(L1, luaL_typename(L1, getnum));\n    }\n    else if EQ(\"xmove\") {\n      int f = getindex;\n      int t = getindex;\n      lua_State *fs = (f == 0) ? L1 : lua_tothread(L1, f);\n      lua_State *ts = (t == 0) ? L1 : lua_tothread(L1, t);\n      int n = getnum;\n      if (n == 0) n = lua_gettop(fs);\n      lua_xmove(fs, ts, n);\n    }\n    else if EQ(\"isyieldable\") {\n      lua_pushboolean(L1, lua_isyieldable(lua_tothread(L1, getindex)));\n    }\n    else if EQ(\"yield\") {\n      return lua_yield(L1, getnum);\n    }\n    else if EQ(\"yieldk\") {\n      int nres = getnum;\n      int i = getindex;\n      return lua_yieldk(L1, nres, i, Cfunck);\n    }\n    else if EQ(\"toclose\") {\n      lua_toclose(L1, getnum);\n    }\n    else if EQ(\"closeslot\") {\n      lua_closeslot(L1, getnum);\n    }\n    else if EQ(\"argerror\") {\n      int arg = getnum;\n      luaL_argerror(L1, arg, getstring);\n    }\n    else luaL_error(L, \"unknown instruction %s\", buff);\n  }\n  return 0;\n}\n\n\nstatic int testC (lua_State *L) {\n  lua_State *L1;\n  const char *pc;\n  if (lua_isuserdata(L, 1)) {\n    L1 = getstate(L);\n    pc = luaL_checkstring(L, 2);\n  }\n  else if (lua_isthread(L, 1)) {\n    L1 = lua_tothread(L, 1);\n    pc = luaL_checkstring(L, 2);\n  }\n  else {\n    L1 = L;\n    pc = luaL_checkstring(L, 1);\n  }\n  return runC(L, L1, pc);\n}\n\n\nstatic int Cfunc (lua_State *L) {\n  return runC(L, L, lua_tostring(L, lua_upvalueindex(1)));\n}\n\n\nstatic int Cfunck (lua_State *L, int status, lua_KContext ctx) {\n  lua_pushstring(L, statcodes[status]);\n  lua_setglobal(L, \"status\");\n  lua_pushinteger(L, cast_Integer(ctx));\n  lua_setglobal(L, \"ctx\");\n  return runC(L, L, lua_tostring(L, cast_int(ctx)));\n}\n\n\nstatic int makeCfunc (lua_State *L) {\n  luaL_checkstring(L, 1);\n  lua_pushcclosure(L, Cfunc, lua_gettop(L));\n  return 1;\n}\n\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** tests for C hooks\n** =======================================================\n*/\n\n/*\n** C hook that runs the C script stored in registry.C_HOOK[L]\n*/\nstatic void Chook (lua_State *L, lua_Debug *ar) {\n  const char *scpt;\n  const char *const events [] = {\"call\", \"ret\", \"line\", \"count\", \"tailcall\"};\n  lua_getfield(L, LUA_REGISTRYINDEX, \"C_HOOK\");\n  lua_pushlightuserdata(L, L);\n  lua_gettable(L, -2);  /* get C_HOOK[L] (script saved by sethookaux) */\n  scpt = lua_tostring(L, -1);  /* not very religious (string will be popped) */\n  lua_pop(L, 2);  /* remove C_HOOK and script */\n  lua_pushstring(L, events[ar->event]);  /* may be used by script */\n  lua_pushinteger(L, ar->currentline);  /* may be used by script */\n  runC(L, L, scpt);  /* run script from C_HOOK[L] */\n}\n\n\n/*\n** sets 'registry.C_HOOK[L] = scpt' and sets 'Chook' as a hook\n*/\nstatic void sethookaux (lua_State *L, int mask, int count, const char *scpt) {\n  if (*scpt == '\\0') {  /* no script? */\n    lua_sethook(L, NULL, 0, 0);  /* turn off hooks */\n    return;\n  }\n  lua_getfield(L, LUA_REGISTRYINDEX, \"C_HOOK\");  /* get C_HOOK table */\n  if (!lua_istable(L, -1)) {  /* no hook table? */\n    lua_pop(L, 1);  /* remove previous value */\n    lua_newtable(L);  /* create new C_HOOK table */\n    lua_pushvalue(L, -1);\n    lua_setfield(L, LUA_REGISTRYINDEX, \"C_HOOK\");  /* register it */\n  }\n  lua_pushlightuserdata(L, L);\n  lua_pushstring(L, scpt);\n  lua_settable(L, -3);  /* C_HOOK[L] = script */\n  lua_sethook(L, Chook, mask, count);\n}\n\n\nstatic int sethook (lua_State *L) {\n  if (lua_isnoneornil(L, 1))\n    lua_sethook(L, NULL, 0, 0);  /* turn off hooks */\n  else {\n    const char *scpt = luaL_checkstring(L, 1);\n    const char *smask = luaL_checkstring(L, 2);\n    int count = cast_int(luaL_optinteger(L, 3, 0));\n    int mask = 0;\n    if (strchr(smask, 'c')) mask |= LUA_MASKCALL;\n    if (strchr(smask, 'r')) mask |= LUA_MASKRET;\n    if (strchr(smask, 'l')) mask |= LUA_MASKLINE;\n    if (count > 0) mask |= LUA_MASKCOUNT;\n    sethookaux(L, mask, count, scpt);\n  }\n  return 0;\n}\n\n\nstatic int coresume (lua_State *L) {\n  int status, nres;\n  lua_State *co = lua_tothread(L, 1);\n  luaL_argcheck(L, co, 1, \"coroutine expected\");\n  status = lua_resume(co, L, 0, &nres);\n  if (status != LUA_OK && status != LUA_YIELD) {\n    lua_pushboolean(L, 0);\n    lua_insert(L, -2);\n    return 2;  /* return false + error message */\n  }\n  else {\n    lua_pushboolean(L, 1);\n    return 1;\n  }\n}\n\n#if !defined(LUA_USE_POSIX)\n\n#define nonblock\tNULL\n\n#else\n\n#include <unistd.h>\n#include <fcntl.h>\n\nstatic int nonblock (lua_State *L) {\n  FILE *f = cast(luaL_Stream*, luaL_checkudata(L, 1, LUA_FILEHANDLE))->f;\n  int fd = fileno(f);\n  int flags = fcntl(fd, F_GETFL, 0);\n  flags |= O_NONBLOCK;\n  fcntl(fd, F_SETFL, flags);\n  return 0;\n}\n#endif\n\n/* }====================================================== */\n\n\n\nstatic const struct luaL_Reg tests_funcs[] = {\n  {\"checkmemory\", lua_checkmemory},\n  {\"closestate\", closestate},\n  {\"d2s\", d2s},\n  {\"doonnewstack\", doonnewstack},\n  {\"doremote\", doremote},\n  {\"gccolor\", gc_color},\n  {\"gcage\", gc_age},\n  {\"gcstate\", gc_state},\n  {\"tracegc\", tracegc},\n  {\"pobj\", gc_printobj},\n  {\"getref\", getref},\n  {\"hash\", hash_query},\n  {\"log2\", log2_aux},\n  {\"limits\", get_limits},\n  {\"listcode\", listcode},\n  {\"printcode\", printcode},\n  {\"printallstack\", lua_printallstack},\n  {\"listk\", listk},\n  {\"listabslineinfo\", listabslineinfo},\n  {\"listlocals\", listlocals},\n  {\"loadlib\", loadlib},\n  {\"checkpanic\", checkpanic},\n  {\"newstate\", newstate},\n  {\"newuserdata\", newuserdata},\n  {\"num2int\", num2int},\n  {\"makeseed\", makeseed},\n  {\"pushuserdata\", pushuserdata},\n  {\"gcquery\", gc_query},\n  {\"querystr\", string_query},\n  {\"querytab\", table_query},\n  {\"codeparam\", test_codeparam},\n  {\"applyparam\", test_applyparam},\n  {\"ref\", tref},\n  {\"resume\", coresume},\n  {\"s2d\", s2d},\n  {\"sethook\", sethook},\n  {\"stacklevel\", stacklevel},\n  {\"sizes\", get_sizes},\n  {\"testC\", testC},\n  {\"makeCfunc\", makeCfunc},\n  {\"totalmem\", mem_query},\n  {\"alloccount\", alloc_count},\n  {\"allocfailnext\", alloc_failnext},\n  {\"trick\", settrick},\n  {\"udataval\", udataval},\n  {\"unref\", unref},\n  {\"upvalue\", upvalue},\n  {\"externKstr\", externKstr},\n  {\"externstr\", externstr},\n  {\"nonblock\", nonblock},\n  {NULL, NULL}\n};\n\n\nstatic void checkfinalmem (void) {\n  lua_assert(l_memcontrol.numblocks == 0);\n  lua_assert(l_memcontrol.total == 0);\n}\n\n\nint luaB_opentests (lua_State *L) {\n  void *ud;\n  lua_Alloc f = lua_getallocf(L, &ud);\n  lua_atpanic(L, &tpanic);\n  lua_setwarnf(L, &warnf, L);\n  lua_pushboolean(L, 0);\n  lua_setglobal(L, \"_WARN\");  /* _WARN = false */\n  regcodes(L);\n  atexit(checkfinalmem);\n  lua_assert(f == debug_realloc && ud == cast_voidp(&l_memcontrol));\n  lua_setallocf(L, f, ud);  /* exercise this function */\n  luaL_newlib(L, tests_funcs);\n  return 1;\n}\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/ltests.h",
    "content": "/*\n** $Id: ltests.h $\n** Internal Header for Debugging of the Lua Implementation\n** See Copyright Notice in lua.h\n*/\n\n#ifndef ltests_h\n#define ltests_h\n\n\n#include <stdio.h>\n#include <stdlib.h>\n\n/* test Lua with compatibility code */\n#define LUA_COMPAT_MATHLIB\n#undef LUA_COMPAT_GLOBAL\n\n\n#define LUA_DEBUG\n\n\n/* turn on assertions */\n#define LUAI_ASSERT\n\n\n/* to avoid warnings, and to make sure value is really unused */\n#define UNUSED(x)       (x=0, (void)(x))\n\n\n/* test for sizes in 'l_sprintf' (make sure whole buffer is available) */\n#undef l_sprintf\n#if !defined(LUA_USE_C89)\n#define l_sprintf(s,sz,f,i)\t(memset(s,0xAB,sz), snprintf(s,sz,f,i))\n#else\n#define l_sprintf(s,sz,f,i)\t(memset(s,0xAB,sz), sprintf(s,f,i))\n#endif\n\n\n/* get a chance to test code without jump tables */\n#define LUA_USE_JUMPTABLE\t0\n\n\n/* use 32-bit integers in random generator */\n#define LUA_RAND32\n\n\n/* test stack reallocation without strict address use */\n#define LUAI_STRICT_ADDRESS\t0\n\n\n/* memory-allocator control variables */\ntypedef struct Memcontrol {\n  int failnext;\n  unsigned long numblocks;\n  unsigned long total;\n  unsigned long maxmem;\n  unsigned long memlimit;\n  unsigned long countlimit;\n  unsigned long objcount[LUA_NUMTYPES];\n} Memcontrol;\n\nLUA_API Memcontrol l_memcontrol;\n\n\n#define luai_tracegc(L,f)\t\tluai_tracegctest(L, f)\nextern void luai_tracegctest (lua_State *L, int first);\n\n\n/*\n** generic variable for debug tricks\n*/\nextern void *l_Trick;\n\n\n/*\n** Function to traverse and check all memory used by Lua\n*/\nextern int lua_checkmemory (lua_State *L);\n\n/*\n** Function to print an object GC-friendly\n*/\nstruct GCObject;\nextern void lua_printobj (lua_State *L, struct GCObject *o);\n\n\n/*\n** Function to print a value\n*/\nstruct TValue;\nextern void lua_printvalue (struct TValue *v);\n\n/*\n** Function to print the stack\n*/\nextern void lua_printstack (lua_State *L);\nextern int lua_printallstack (lua_State *L);\n\n\n/* test for lock/unlock */\n\nstruct L_EXTRA { int lock; int *plock; };\n#undef LUA_EXTRASPACE\n#define LUA_EXTRASPACE\tsizeof(struct L_EXTRA)\n#define getlock(l)\tcast(struct L_EXTRA*, lua_getextraspace(l))\n#define luai_userstateopen(l)  \\\n\t(getlock(l)->lock = 0, getlock(l)->plock = &(getlock(l)->lock))\n#define luai_userstateclose(l)  \\\n  lua_assert(getlock(l)->lock == 1 && getlock(l)->plock == &(getlock(l)->lock))\n#define luai_userstatethread(l,l1) \\\n  lua_assert(getlock(l1)->plock == getlock(l)->plock)\n#define luai_userstatefree(l,l1) \\\n  lua_assert(getlock(l)->plock == getlock(l1)->plock)\n#define lua_lock(l)     lua_assert((*getlock(l)->plock)++ == 0)\n#define lua_unlock(l)   lua_assert(--(*getlock(l)->plock) == 0)\n\n\n\nLUA_API int luaB_opentests (lua_State *L);\n\nLUA_API void *debug_realloc (void *ud, void *block,\n                             size_t osize, size_t nsize);\n\n\n#define luaL_newstate()  \\\n\tlua_newstate(debug_realloc, &l_memcontrol, luaL_makeseed(NULL))\n#define luai_openlibs(L)  \\\n  {  luaL_openlibs(L); \\\n     luaL_requiref(L, \"T\", luaB_opentests, 1); \\\n     lua_pop(L, 1); }\n\n\n\n\n/* change some sizes to give some bugs a chance */\n\n#undef LUAL_BUFFERSIZE\n#define LUAL_BUFFERSIZE\t\t23\n#define MINSTRTABSIZE\t\t2\n#define MAXIWTHABS\t\t3\n\n#define STRCACHE_N\t23\n#define STRCACHE_M\t5\n\n#define MAXINDEXRK\t1\n\n\n/*\n** Reduce maximum stack size to make stack-overflow tests run faster.\n** (But value is still large enough to overflow smaller integers.)\n*/\n#define LUAI_MAXSTACK   68000\n\n\n/* test mode uses more stack space */\n#undef LUAI_MAXCCALLS\n#define LUAI_MAXCCALLS\t180\n\n\n/* force Lua to use its own implementations */\n#undef lua_strx2number\n#undef lua_number2strx\n\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/ltm.c",
    "content": "/*\n** $Id: ltm.c $\n** Tag methods\n** See Copyright Notice in lua.h\n*/\n\n#define ltm_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lgc.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"ltm.h\"\n#include \"lvm.h\"\n\n\nstatic const char udatatypename[] = \"userdata\";\n\nLUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTYPES] = {\n  \"no value\",\n  \"nil\", \"boolean\", udatatypename, \"number\",\n  \"string\", \"table\", \"function\", udatatypename, \"thread\",\n  \"upvalue\", \"proto\" /* these last cases are used for tests only */\n};\n\n\nvoid luaT_init (lua_State *L) {\n  static const char *const luaT_eventname[] = {  /* ORDER TM */\n    \"__index\", \"__newindex\",\n    \"__gc\", \"__mode\", \"__len\", \"__eq\",\n    \"__add\", \"__sub\", \"__mul\", \"__mod\", \"__pow\",\n    \"__div\", \"__idiv\",\n    \"__band\", \"__bor\", \"__bxor\", \"__shl\", \"__shr\",\n    \"__unm\", \"__bnot\", \"__lt\", \"__le\",\n    \"__concat\", \"__call\", \"__close\"\n  };\n  int i;\n  for (i=0; i<TM_N; i++) {\n    G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);\n    luaC_fix(L, obj2gco(G(L)->tmname[i]));  /* never collect these names */\n  }\n}\n\n\n/*\n** function to be used with macro \"fasttm\": optimized for absence of\n** tag methods\n*/\nconst TValue *luaT_gettm (Table *events, TMS event, TString *ename) {\n  const TValue *tm = luaH_Hgetshortstr(events, ename);\n  lua_assert(event <= TM_EQ);\n  if (notm(tm)) {  /* no tag method? */\n    events->flags |= cast_byte(1u<<event);  /* cache this fact */\n    return NULL;\n  }\n  else return tm;\n}\n\n\nconst TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {\n  Table *mt;\n  switch (ttype(o)) {\n    case LUA_TTABLE:\n      mt = hvalue(o)->metatable;\n      break;\n    case LUA_TUSERDATA:\n      mt = uvalue(o)->metatable;\n      break;\n    default:\n      mt = G(L)->mt[ttype(o)];\n  }\n  return (mt ? luaH_Hgetshortstr(mt, G(L)->tmname[event]) : &G(L)->nilvalue);\n}\n\n\n/*\n** Return the name of the type of an object. For tables and userdata\n** with metatable, use their '__name' metafield, if present.\n*/\nconst char *luaT_objtypename (lua_State *L, const TValue *o) {\n  Table *mt;\n  if ((ttistable(o) && (mt = hvalue(o)->metatable) != NULL) ||\n      (ttisfulluserdata(o) && (mt = uvalue(o)->metatable) != NULL)) {\n    const TValue *name = luaH_Hgetshortstr(mt, luaS_new(L, \"__name\"));\n    if (ttisstring(name))  /* is '__name' a string? */\n      return getstr(tsvalue(name));  /* use it as type name */\n  }\n  return ttypename(ttype(o));  /* else use standard type name */\n}\n\n\nvoid luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,\n                  const TValue *p2, const TValue *p3) {\n  StkId func = L->top.p;\n  setobj2s(L, func, f);  /* push function (assume EXTRA_STACK) */\n  setobj2s(L, func + 1, p1);  /* 1st argument */\n  setobj2s(L, func + 2, p2);  /* 2nd argument */\n  setobj2s(L, func + 3, p3);  /* 3rd argument */\n  L->top.p = func + 4;\n  /* metamethod may yield only when called from Lua code */\n  if (isLuacode(L->ci))\n    luaD_call(L, func, 0);\n  else\n    luaD_callnoyield(L, func, 0);\n}\n\n\nlu_byte luaT_callTMres (lua_State *L, const TValue *f, const TValue *p1,\n                        const TValue *p2, StkId res) {\n  ptrdiff_t result = savestack(L, res);\n  StkId func = L->top.p;\n  setobj2s(L, func, f);  /* push function (assume EXTRA_STACK) */\n  setobj2s(L, func + 1, p1);  /* 1st argument */\n  setobj2s(L, func + 2, p2);  /* 2nd argument */\n  L->top.p += 3;\n  /* metamethod may yield only when called from Lua code */\n  if (isLuacode(L->ci))\n    luaD_call(L, func, 1);\n  else\n    luaD_callnoyield(L, func, 1);\n  res = restorestack(L, result);\n  setobjs2s(L, res, --L->top.p);  /* move result to its place */\n  return ttypetag(s2v(res));  /* return tag of the result */\n}\n\n\nstatic int callbinTM (lua_State *L, const TValue *p1, const TValue *p2,\n                      StkId res, TMS event) {\n  const TValue *tm = luaT_gettmbyobj(L, p1, event);  /* try first operand */\n  if (notm(tm))\n    tm = luaT_gettmbyobj(L, p2, event);  /* try second operand */\n  if (notm(tm))\n    return -1;  /* tag method not found */\n  else  /* call tag method and return the tag of the result */\n    return luaT_callTMres(L, tm, p1, p2, res);\n}\n\n\nvoid luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,\n                    StkId res, TMS event) {\n  if (l_unlikely(callbinTM(L, p1, p2, res, event) < 0)) {\n    switch (event) {\n      case TM_BAND: case TM_BOR: case TM_BXOR:\n      case TM_SHL: case TM_SHR: case TM_BNOT: {\n        if (ttisnumber(p1) && ttisnumber(p2))\n          luaG_tointerror(L, p1, p2);\n        else\n          luaG_opinterror(L, p1, p2, \"perform bitwise operation on\");\n      }\n      /* calls never return, but to avoid warnings: *//* FALLTHROUGH */\n      default:\n        luaG_opinterror(L, p1, p2, \"perform arithmetic on\");\n    }\n  }\n}\n\n\n/*\n** The use of 'p1' after 'callbinTM' is safe because, when a tag\n** method is not found, 'callbinTM' cannot change the stack.\n*/\nvoid luaT_tryconcatTM (lua_State *L) {\n  StkId p1 = L->top.p - 2;  /* first argument */\n  if (l_unlikely(callbinTM(L, s2v(p1), s2v(p1 + 1), p1, TM_CONCAT) < 0))\n    luaG_concaterror(L, s2v(p1), s2v(p1 + 1));\n}\n\n\nvoid luaT_trybinassocTM (lua_State *L, const TValue *p1, const TValue *p2,\n                                       int flip, StkId res, TMS event) {\n  if (flip)\n    luaT_trybinTM(L, p2, p1, res, event);\n  else\n    luaT_trybinTM(L, p1, p2, res, event);\n}\n\n\nvoid luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2,\n                                   int flip, StkId res, TMS event) {\n  TValue aux;\n  setivalue(&aux, i2);\n  luaT_trybinassocTM(L, p1, &aux, flip, res, event);\n}\n\n\n/*\n** Calls an order tag method.\n*/\nint luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2,\n                      TMS event) {\n  int tag = callbinTM(L, p1, p2, L->top.p, event);  /* try original event */\n  if (tag >= 0)  /* found tag method? */\n    return !tagisfalse(tag);\n  luaG_ordererror(L, p1, p2);  /* no metamethod found */\n  return 0;  /* to avoid warnings */\n}\n\n\nint luaT_callorderiTM (lua_State *L, const TValue *p1, int v2,\n                       int flip, int isfloat, TMS event) {\n  TValue aux; const TValue *p2;\n  if (isfloat) {\n    setfltvalue(&aux, cast_num(v2));\n  }\n  else\n    setivalue(&aux, v2);\n  if (flip) {  /* arguments were exchanged? */\n    p2 = p1; p1 = &aux;  /* correct them */\n  }\n  else\n    p2 = &aux;\n  return luaT_callorderTM(L, p1, p2, event);\n}\n\n\n/*\n** Create a vararg table at the top of the stack, with 'n' elements\n** starting at 'f'.\n*/\nstatic void createvarargtab (lua_State *L, StkId f, int n) {\n  int i;\n  TValue key, value;\n  Table *t = luaH_new(L);\n  sethvalue(L, s2v(L->top.p), t);\n  L->top.p++;\n  luaH_resize(L, t, cast_uint(n), 1);\n  setsvalue(L, &key, luaS_new(L, \"n\"));  /* key is \"n\" */\n  setivalue(&value, n);  /* value is n */\n  /* No need to anchor the key: Due to the resize, the next operation\n     cannot trigger a garbage collection */\n  luaH_set(L, t, &key, &value);  /* t.n = n */\n  for (i = 0; i < n; i++)\n    luaH_setint(L, t, i + 1, s2v(f + i));\n  luaC_checkGC(L);\n}\n\n\n/*\n** initial stack:  func arg1 ... argn extra1 ...\n**                 ^ ci->func                    ^ L->top\n** final stack: func nil ... nil extra1 ... func arg1 ... argn\n**                                          ^ ci->func\n*/\nstatic void buildhiddenargs (lua_State *L, CallInfo *ci, const Proto *p,\n                             int totalargs, int nfixparams, int nextra) {\n  int i;\n  ci->u.l.nextraargs = nextra;\n  luaD_checkstack(L, p->maxstacksize + 1);\n  /* copy function to the top of the stack, after extra arguments */\n  setobjs2s(L, L->top.p++, ci->func.p);\n  /* move fixed parameters to after the copied function */\n  for (i = 1; i <= nfixparams; i++) {\n    setobjs2s(L, L->top.p++, ci->func.p + i);\n    setnilvalue(s2v(ci->func.p + i));  /* erase original parameter (for GC) */\n  }\n  ci->func.p += totalargs + 1;  /* 'func' now lives after hidden arguments */\n  ci->top.p += totalargs + 1;\n}\n\n\nvoid luaT_adjustvarargs (lua_State *L, CallInfo *ci, const Proto *p) {\n  int totalargs = cast_int(L->top.p - ci->func.p) - 1;\n  int nfixparams = p->numparams;\n  int nextra = totalargs - nfixparams;  /* number of extra arguments */\n  if (p->flag & PF_VATAB) {  /* does it need a vararg table? */\n    lua_assert(!(p->flag & PF_VAHID));\n    createvarargtab(L, ci->func.p + nfixparams + 1, nextra);\n    /* move table to proper place (last parameter) */\n    setobjs2s(L, ci->func.p + nfixparams + 1, L->top.p - 1);\n  }\n  else {  /* no table */\n    lua_assert(p->flag & PF_VAHID);\n    buildhiddenargs(L, ci, p, totalargs, nfixparams, nextra);\n    /* set vararg parameter to nil */\n    setnilvalue(s2v(ci->func.p + nfixparams + 1));\n    lua_assert(L->top.p <= ci->top.p && ci->top.p <= L->stack_last.p);\n  }\n}\n\n\nvoid luaT_getvararg (CallInfo *ci, StkId ra, TValue *rc) {\n  int nextra = ci->u.l.nextraargs;\n  lua_Integer n;\n  if (tointegerns(rc, &n)) {  /* integral value? */\n    if (l_castS2U(n) - 1 < cast_uint(nextra)) {\n      StkId slot = ci->func.p - nextra + cast_int(n) - 1;\n      setobjs2s(((lua_State*)NULL), ra, slot);\n      return;\n    }\n  }\n  else if (ttisstring(rc)) {  /* string value? */\n    size_t len;\n    const char *s = getlstr(tsvalue(rc), len);\n    if (len == 1 && s[0] == 'n') {  /* key is \"n\"? */\n      setivalue(s2v(ra), nextra);\n      return;\n    }\n  }\n  setnilvalue(s2v(ra));  /* else produce nil */\n}\n\n\n/*\n** Get the number of extra arguments in a vararg function. If vararg\n** table has been optimized away, that number is in the call info.\n** Otherwise, get the field 'n' from the vararg table and check that it\n** has a proper value (non-negative integer not larger than the stack\n** limit).\n*/\nstatic int getnumargs (lua_State *L, CallInfo *ci, Table *h) {\n  if (h == NULL)  /* no vararg table? */\n    return ci->u.l.nextraargs;\n  else {\n    TValue res;\n    if (luaH_getshortstr(h, luaS_new(L, \"n\"), &res) != LUA_VNUMINT ||\n        l_castS2U(ivalue(&res)) > cast_uint(INT_MAX/2))\n      luaG_runerror(L, \"vararg table has no proper 'n'\");\n    return cast_int(ivalue(&res));\n  }\n}\n\n\n/*\n** Get 'wanted' vararg arguments and put them in 'where'. 'vatab' is\n** the register of the vararg table or -1 if there is no vararg table.\n*/\nvoid luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted,\n                                    int vatab) {\n  Table *h = (vatab < 0) ? NULL : hvalue(s2v(ci->func.p + vatab + 1));\n  int nargs = getnumargs(L, ci, h);  /* number of available vararg args. */\n  int i, touse;  /* 'touse' is minimum between 'wanted' and 'nargs' */\n  if (wanted < 0) {\n    touse = wanted = nargs;  /* get all extra arguments available */\n    checkstackp(L, nargs, where);  /* ensure stack space */\n    L->top.p = where + nargs;  /* next instruction will need top */\n  }\n  else\n    touse = (nargs > wanted) ? wanted : nargs;\n  if (h == NULL) {  /* no vararg table? */\n    for (i = 0; i < touse; i++)  /* get vararg values from the stack */\n      setobjs2s(L, where + i, ci->func.p - nargs + i);\n  }\n  else {  /* get vararg values from vararg table */\n    for (i = 0; i < touse; i++) {\n      lu_byte tag = luaH_getint(h, i + 1, s2v(where + i));\n      if (tagisempty(tag))\n       setnilvalue(s2v(where + i));\n    }\n  }\n  for (; i < wanted; i++)   /* complete required results with nil */\n    setnilvalue(s2v(where + i));\n}\n\n"
  },
  {
    "path": "3rd/lua/ltm.h",
    "content": "/*\n** $Id: ltm.h $\n** Tag methods\n** See Copyright Notice in lua.h\n*/\n\n#ifndef ltm_h\n#define ltm_h\n\n\n#include \"lobject.h\"\n\n\n/*\n* WARNING: if you change the order of this enumeration,\n* grep \"ORDER TM\" and \"ORDER OP\"\n*/\ntypedef enum {\n  TM_INDEX,\n  TM_NEWINDEX,\n  TM_GC,\n  TM_MODE,\n  TM_LEN,\n  TM_EQ,  /* last tag method with fast access */\n  TM_ADD,\n  TM_SUB,\n  TM_MUL,\n  TM_MOD,\n  TM_POW,\n  TM_DIV,\n  TM_IDIV,\n  TM_BAND,\n  TM_BOR,\n  TM_BXOR,\n  TM_SHL,\n  TM_SHR,\n  TM_UNM,\n  TM_BNOT,\n  TM_LT,\n  TM_LE,\n  TM_CONCAT,\n  TM_CALL,\n  TM_CLOSE,\n  TM_N\t\t/* number of elements in the enum */\n} TMS;\n\n\n/*\n** Mask with 1 in all fast-access methods. A 1 in any of these bits\n** in the flag of a (meta)table means the metatable does not have the\n** corresponding metamethod field. (Bit 6 of the flag indicates that\n** the table is using the dummy node; bit 7 is used for 'isrealasize'.)\n*/\n#define maskflags\tcast_byte(~(~0u << (TM_EQ + 1)))\n\n\n/*\n** Test whether there is no tagmethod.\n** (Because tagmethods use raw accesses, the result may be an \"empty\" nil.)\n*/\n#define notm(tm)\tttisnil(tm)\n\n#define checknoTM(mt,e)\t((mt) == NULL || (mt)->flags & (1u<<(e)))\n\n#define gfasttm(g,mt,e)  \\\n  (checknoTM(mt, e) ? NULL : luaT_gettm(mt, e, (g)->tmname[e]))\n\n#define fasttm(l,mt,e)\tgfasttm(G(l), mt, e)\n\n#define ttypename(x)\tluaT_typenames_[(x) + 1]\n\nLUAI_DDEC(const char *const luaT_typenames_[LUA_TOTALTYPES];)\n\n\nLUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o);\n\nLUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);\nLUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o,\n                                                       TMS event);\nLUAI_FUNC void luaT_init (lua_State *L);\n\nLUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,\n                            const TValue *p2, const TValue *p3);\nLUAI_FUNC lu_byte luaT_callTMres (lua_State *L, const TValue *f,\n                               const TValue *p1, const TValue *p2, StkId p3);\nLUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,\n                              StkId res, TMS event);\nLUAI_FUNC void luaT_tryconcatTM (lua_State *L);\nLUAI_FUNC void luaT_trybinassocTM (lua_State *L, const TValue *p1,\n       const TValue *p2, int inv, StkId res, TMS event);\nLUAI_FUNC void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2,\n                               int inv, StkId res, TMS event);\nLUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1,\n                                const TValue *p2, TMS event);\nLUAI_FUNC int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2,\n                                 int inv, int isfloat, TMS event);\n\nLUAI_FUNC void luaT_adjustvarargs (lua_State *L, struct CallInfo *ci,\n                                                 const Proto *p);\nLUAI_FUNC void luaT_getvararg (CallInfo *ci, StkId ra, TValue *rc);\nLUAI_FUNC void luaT_getvarargs (lua_State *L, struct CallInfo *ci, StkId where,\n                                              int wanted, int vatab);\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lua.c",
    "content": "/*\n** $Id: lua.c $\n** Lua stand-alone interpreter\n** See Copyright Notice in lua.h\n*/\n\n#define lua_c\n\n#include \"lprefix.h\"\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <signal.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\n#if !defined(LUA_PROGNAME)\n#define LUA_PROGNAME\t\t\"lua\"\n#endif\n\n#if !defined(LUA_INIT_VAR)\n#define LUA_INIT_VAR\t\t\"LUA_INIT\"\n#endif\n\n#define LUA_INITVARVERSION\tLUA_INIT_VAR LUA_VERSUFFIX\n\n\nstatic lua_State *globalL = NULL;\n\nstatic const char *progname = LUA_PROGNAME;\n\n\n#if defined(LUA_USE_POSIX)   /* { */\n\n/*\n** Use 'sigaction' when available.\n*/\nstatic void setsignal (int sig, void (*handler)(int)) {\n  struct sigaction sa;\n  sa.sa_handler = handler;\n  sa.sa_flags = 0;\n  sigemptyset(&sa.sa_mask);  /* do not mask any signal */\n  sigaction(sig, &sa, NULL);\n}\n\n#else           /* }{ */\n\n#define setsignal            signal\n\n#endif                               /* } */\n\n\n/*\n** Hook set by signal function to stop the interpreter.\n*/\nstatic void lstop (lua_State *L, lua_Debug *ar) {\n  (void)ar;  /* unused arg. */\n  lua_sethook(L, NULL, 0, 0);  /* reset hook */\n  luaL_error(L, \"interrupted!\");\n}\n\n\n/*\n** Function to be called at a C signal. Because a C signal cannot\n** just change a Lua state (as there is no proper synchronization),\n** this function only sets a hook that, when called, will stop the\n** interpreter.\n*/\nstatic void laction (int i) {\n  int flag = LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT;\n  setsignal(i, SIG_DFL); /* if another SIGINT happens, terminate process */\n  lua_sethook(globalL, lstop, flag, 1);\n}\n\n\nstatic void print_usage (const char *badoption) {\n  lua_writestringerror(\"%s: \", progname);\n  if (badoption[1] == 'e' || badoption[1] == 'l')\n    lua_writestringerror(\"'%s' needs argument\\n\", badoption);\n  else\n    lua_writestringerror(\"unrecognized option '%s'\\n\", badoption);\n  lua_writestringerror(\n  \"usage: %s [options] [script [args]]\\n\"\n  \"Available options are:\\n\"\n  \"  -e stat   execute string 'stat'\\n\"\n  \"  -i        enter interactive mode after executing 'script'\\n\"\n  \"  -l mod    require library 'mod' into global 'mod'\\n\"\n  \"  -l g=mod  require library 'mod' into global 'g'\\n\"\n  \"  -v        show version information\\n\"\n  \"  -E        ignore environment variables\\n\"\n  \"  -W        turn warnings on\\n\"\n  \"  --        stop handling options\\n\"\n  \"  -         stop handling options and execute stdin\\n\"\n  ,\n  progname);\n}\n\n\n/*\n** Prints an error message, adding the program name in front of it\n** (if present)\n*/\nstatic void l_message (const char *pname, const char *msg) {\n  if (pname) lua_writestringerror(\"%s: \", pname);\n  lua_writestringerror(\"%s\\n\", msg);\n}\n\n\n/*\n** Check whether 'status' is not OK and, if so, prints the error\n** message on the top of the stack.\n*/\nstatic int report (lua_State *L, int status) {\n  if (status != LUA_OK) {\n    const char *msg = lua_tostring(L, -1);\n    if (msg == NULL)\n      msg = \"(error message not a string)\";\n    l_message(progname, msg);\n    lua_pop(L, 1);  /* remove message */\n  }\n  return status;\n}\n\n\n/*\n** Message handler used to run all chunks\n*/\nstatic int msghandler (lua_State *L) {\n  const char *msg = lua_tostring(L, 1);\n  if (msg == NULL) {  /* is error object not a string? */\n    if (luaL_callmeta(L, 1, \"__tostring\") &&  /* does it have a metamethod */\n        lua_type(L, -1) == LUA_TSTRING)  /* that produces a string? */\n      return 1;  /* that is the message */\n    else\n      msg = lua_pushfstring(L, \"(error object is a %s value)\",\n                               luaL_typename(L, 1));\n  }\n  luaL_traceback(L, L, msg, 1);  /* append a standard traceback */\n  return 1;  /* return the traceback */\n}\n\n\n/*\n** Interface to 'lua_pcall', which sets appropriate message function\n** and C-signal handler. Used to run all chunks.\n*/\nstatic int docall (lua_State *L, int narg, int nres) {\n  int status;\n  int base = lua_gettop(L) - narg;  /* function index */\n  lua_pushcfunction(L, msghandler);  /* push message handler */\n  lua_insert(L, base);  /* put it under function and args */\n  globalL = L;  /* to be available to 'laction' */\n  setsignal(SIGINT, laction);  /* set C-signal handler */\n  status = lua_pcall(L, narg, nres, base);\n  setsignal(SIGINT, SIG_DFL); /* reset C-signal handler */\n  lua_remove(L, base);  /* remove message handler from the stack */\n  return status;\n}\n\n\nstatic void print_version (void) {\n  lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));\n  lua_writeline();\n}\n\n\n/*\n** Create the 'arg' table, which stores all arguments from the\n** command line ('argv'). It should be aligned so that, at index 0,\n** it has 'argv[script]', which is the script name. The arguments\n** to the script (everything after 'script') go to positive indices;\n** other arguments (before the script name) go to negative indices.\n** If there is no script name, assume interpreter's name as base.\n** (If there is no interpreter's name either, 'script' is -1, so\n** table sizes are zero.)\n*/\nstatic void createargtable (lua_State *L, char **argv, int argc, int script) {\n  int i, narg;\n  narg = argc - (script + 1);  /* number of positive indices */\n  lua_createtable(L, narg, script + 1);\n  for (i = 0; i < argc; i++) {\n    lua_pushstring(L, argv[i]);\n    lua_rawseti(L, -2, i - script);\n  }\n  lua_setglobal(L, \"arg\");\n}\n\n\nstatic int dochunk (lua_State *L, int status) {\n  if (status == LUA_OK) status = docall(L, 0, 0);\n  return report(L, status);\n}\n\n\nstatic int dofile (lua_State *L, const char *name) {\n  return dochunk(L, luaL_loadfile(L, name));\n}\n\n\nstatic int dostring (lua_State *L, const char *s, const char *name) {\n  return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name));\n}\n\n\n/*\n** Receives 'globname[=modname]' and runs 'globname = require(modname)'.\n** If there is no explicit modname and globname contains a '-', cut\n** the suffix after '-' (the \"version\") to make the global name.\n*/\nstatic int dolibrary (lua_State *L, char *globname) {\n  int status;\n  char *suffix = NULL;\n  char *modname = strchr(globname, '=');\n  if (modname == NULL) {  /* no explicit name? */\n    modname = globname;  /* module name is equal to global name */\n    suffix = strchr(modname, *LUA_IGMARK);  /* look for a suffix mark */\n  }\n  else {\n    *modname = '\\0';  /* global name ends here */\n    modname++;  /* module name starts after the '=' */\n  }\n  lua_getglobal(L, \"require\");\n  lua_pushstring(L, modname);\n  status = docall(L, 1, 1);  /* call 'require(modname)' */\n  if (status == LUA_OK) {\n    if (suffix != NULL)  /* is there a suffix mark? */\n      *suffix = '\\0';  /* remove suffix from global name */\n    lua_setglobal(L, globname);  /* globname = require(modname) */\n  }\n  return report(L, status);\n}\n\n\n/*\n** Push on the stack the contents of table 'arg' from 1 to #arg\n*/\nstatic int pushargs (lua_State *L) {\n  int i, n;\n  if (lua_getglobal(L, \"arg\") != LUA_TTABLE)\n    luaL_error(L, \"'arg' is not a table\");\n  n = (int)luaL_len(L, -1);\n  luaL_checkstack(L, n + 3, \"too many arguments to script\");\n  for (i = 1; i <= n; i++)\n    lua_rawgeti(L, -i, i);\n  lua_remove(L, -i);  /* remove table from the stack */\n  return n;\n}\n\n\nstatic int handle_script (lua_State *L, char **argv) {\n  int status;\n  const char *fname = argv[0];\n  if (strcmp(fname, \"-\") == 0 && strcmp(argv[-1], \"--\") != 0)\n    fname = NULL;  /* stdin */\n  status = luaL_loadfile(L, fname);\n  if (status == LUA_OK) {\n    int n = pushargs(L);  /* push arguments to script */\n    status = docall(L, n, LUA_MULTRET);\n  }\n  return report(L, status);\n}\n\n\n/* bits of various argument indicators in 'args' */\n#define has_error\t1\t/* bad option */\n#define has_i\t\t2\t/* -i */\n#define has_v\t\t4\t/* -v */\n#define has_e\t\t8\t/* -e */\n#define has_E\t\t16\t/* -E */\n\n\n/*\n** Traverses all arguments from 'argv', returning a mask with those\n** needed before running any Lua code or an error code if it finds any\n** invalid argument. In case of error, 'first' is the index of the bad\n** argument.  Otherwise, 'first' is -1 if there is no program name,\n** 0 if there is no script name, or the index of the script name.\n*/\nstatic int collectargs (char **argv, int *first) {\n  int args = 0;\n  int i;\n  if (argv[0] != NULL) {  /* is there a program name? */\n    if (argv[0][0])  /* not empty? */\n      progname = argv[0];  /* save it */\n  }\n  else {  /* no program name */\n    *first = -1;\n    return 0;\n  }\n  for (i = 1; argv[i] != NULL; i++) {  /* handle arguments */\n    *first = i;\n    if (argv[i][0] != '-')  /* not an option? */\n        return args;  /* stop handling options */\n    switch (argv[i][1]) {  /* else check option */\n      case '-':  /* '--' */\n        if (argv[i][2] != '\\0')  /* extra characters after '--'? */\n          return has_error;  /* invalid option */\n        /* if there is a script name, it comes after '--' */\n        *first = (argv[i + 1] != NULL) ? i + 1 : 0;\n        return args;\n      case '\\0':  /* '-' */\n        return args;  /* script \"name\" is '-' */\n      case 'E':\n        if (argv[i][2] != '\\0')  /* extra characters? */\n          return has_error;  /* invalid option */\n        args |= has_E;\n        break;\n      case 'W':\n        if (argv[i][2] != '\\0')  /* extra characters? */\n          return has_error;  /* invalid option */\n        break;\n      case 'i':\n        args |= has_i;  /* (-i implies -v) *//* FALLTHROUGH */\n      case 'v':\n        if (argv[i][2] != '\\0')  /* extra characters? */\n          return has_error;  /* invalid option */\n        args |= has_v;\n        break;\n      case 'e':\n        args |= has_e;  /* FALLTHROUGH */\n      case 'l':  /* both options need an argument */\n        if (argv[i][2] == '\\0') {  /* no concatenated argument? */\n          i++;  /* try next 'argv' */\n          if (argv[i] == NULL || argv[i][0] == '-')\n            return has_error;  /* no next argument or it is another option */\n        }\n        break;\n      default:  /* invalid option */\n        return has_error;\n    }\n  }\n  *first = 0;  /* no script name */\n  return args;\n}\n\n\n/*\n** Processes options 'e' and 'l', which involve running Lua code, and\n** 'W', which also affects the state.\n** Returns 0 if some code raises an error.\n*/\nstatic int runargs (lua_State *L, char **argv, int n) {\n  int i;\n  lua_warning(L, \"@off\", 0);  /* by default, Lua stand-alone has warnings off */\n  for (i = 1; i < n; i++) {\n    int option = argv[i][1];\n    lua_assert(argv[i][0] == '-');  /* already checked */\n    switch (option) {\n      case 'e':  case 'l': {\n        int status;\n        char *extra = argv[i] + 2;  /* both options need an argument */\n        if (*extra == '\\0') extra = argv[++i];\n        lua_assert(extra != NULL);\n        status = (option == 'e')\n                 ? dostring(L, extra, \"=(command line)\")\n                 : dolibrary(L, extra);\n        if (status != LUA_OK) return 0;\n        break;\n      }\n      case 'W':\n        lua_warning(L, \"@on\", 0);  /* warnings on */\n        break;\n    }\n  }\n  return 1;\n}\n\n\nstatic int handle_luainit (lua_State *L) {\n  const char *name = \"=\" LUA_INITVARVERSION;\n  const char *init = getenv(name + 1);\n  if (init == NULL) {\n    name = \"=\" LUA_INIT_VAR;\n    init = getenv(name + 1);  /* try alternative name */\n  }\n  if (init == NULL) return LUA_OK;\n  else if (init[0] == '@')\n    return dofile(L, init+1);\n  else\n    return dostring(L, init, name);\n}\n\n\n/*\n** {==================================================================\n** Read-Eval-Print Loop (REPL)\n** ===================================================================\n*/\n\n#if !defined(LUA_PROMPT)\n#define LUA_PROMPT\t\t\"> \"\n#define LUA_PROMPT2\t\t\">> \"\n#endif\n\n#if !defined(LUA_MAXINPUT)\n#define LUA_MAXINPUT\t\t512\n#endif\n\n\n/*\n** lua_stdin_is_tty detects whether the standard input is a 'tty' (that\n** is, whether we're running lua interactively).\n*/\n#if !defined(lua_stdin_is_tty)\t/* { */\n\n#if defined(LUA_USE_POSIX)\t/* { */\n\n#include <unistd.h>\n#define lua_stdin_is_tty()\tisatty(0)\n\n#elif defined(LUA_USE_WINDOWS)\t/* }{ */\n\n#include <io.h>\n#include <windows.h>\n\n#define lua_stdin_is_tty()\t_isatty(_fileno(stdin))\n\n#else\t\t\t\t/* }{ */\n\n/* ISO C definition */\n#define lua_stdin_is_tty()\t1  /* assume stdin is a tty */\n\n#endif\t\t\t\t/* } */\n\n#endif\t\t\t\t/* } */\n\n\n/*\n** * lua_initreadline initializes the readline system.\n** * lua_readline defines how to show a prompt and then read a line from\n**   the standard input.\n** * lua_saveline defines how to \"save\" a read line in a \"history\".\n** * lua_freeline defines how to free a line read by lua_readline.\n*/\n\n#if !defined(lua_readline)\t/* { */\n/* Otherwise, all previously listed functions should be defined. */\n\n#if defined(LUA_USE_READLINE)\t/* { */\n/* Lua will be linked with '-lreadline' */\n\n#include <readline/readline.h>\n#include <readline/history.h>\n\n#define lua_initreadline(L)\t((void)L, rl_readline_name=\"lua\")\n#define lua_readline(buff,prompt)\t((void)buff, readline(prompt))\n#define lua_saveline(line)\tadd_history(line)\n#define lua_freeline(line)\tfree(line)\n\n#else\t\t/* }{ */\n/* use dynamically loaded readline (or nothing) */\n\n/* pointer to 'readline' function (if any) */\ntypedef char *(*l_readlineT) (const char *prompt);\nstatic l_readlineT l_readline = NULL;\n\n/* pointer to 'add_history' function (if any) */\ntypedef void (*l_addhistT) (const char *string);\nstatic l_addhistT l_addhist = NULL;\n\n\nstatic char *lua_readline (char *buff, const char *prompt) {\n  if (l_readline != NULL)  /* is there a 'readline'? */\n    return (*l_readline)(prompt);  /* use it */\n  else {  /* emulate 'readline' over 'buff' */\n    fputs(prompt, stdout);\n    fflush(stdout);  /* show prompt */\n    return fgets(buff, LUA_MAXINPUT, stdin);  /* read line */\n  }\n}\n\n\nstatic void lua_saveline (const char *line) {\n  if (l_addhist != NULL)  /* is there an 'add_history'? */\n    (*l_addhist)(line);  /* use it */\n  /* else nothing to be done */\n}\n\n\nstatic void lua_freeline (char *line) {\n  if (l_readline != NULL)  /* is there a 'readline'? */\n    free(line);  /* free line created by it */\n  /* else 'lua_readline' used an automatic buffer; nothing to free */\n}\n\n\n#if defined(LUA_USE_DLOPEN) && defined(LUA_READLINELIB)\t\t/* { */\n/* try to load 'readline' dynamically */\n\n#include <dlfcn.h>\n\nstatic void lua_initreadline (lua_State *L) {\n  void *lib = dlopen(LUA_READLINELIB, RTLD_NOW | RTLD_LOCAL);\n  if (lib == NULL)\n    lua_warning(L, \"library '\" LUA_READLINELIB \"' not found\", 0);\n  else {\n    const char **name = cast(const char**, dlsym(lib, \"rl_readline_name\"));\n    if (name != NULL)\n      *name = \"lua\";\n    l_readline = cast(l_readlineT, cast_func(dlsym(lib, \"readline\")));\n    l_addhist = cast(l_addhistT, cast_func(dlsym(lib, \"add_history\")));\n    if (l_readline == NULL)\n      lua_warning(L, \"unable to load 'readline'\", 0);\n  }\n}\n\n#else\t\t/* }{ */\n/* no dlopen or LUA_READLINELIB undefined */\n\n/* Leave pointers with NULL */\n#define lua_initreadline(L)\t((void)L)\n\n#endif\t\t/* } */\n\n#endif\t\t\t\t/* } */\n\n#endif\t\t\t\t/* } */\n\n\n/*\n** Return the string to be used as a prompt by the interpreter. Leave\n** the string (or nil, if using the default value) on the stack, to keep\n** it anchored.\n*/\nstatic const char *get_prompt (lua_State *L, int firstline) {\n  if (lua_getglobal(L, firstline ? \"_PROMPT\" : \"_PROMPT2\") == LUA_TNIL)\n    return (firstline ? LUA_PROMPT : LUA_PROMPT2);  /* use the default */\n  else {  /* apply 'tostring' over the value */\n    const char *p = luaL_tolstring(L, -1, NULL);\n    lua_remove(L, -2);  /* remove original value */\n    return p;\n  }\n}\n\n/* mark in error messages for incomplete statements */\n#define EOFMARK\t\t\"<eof>\"\n#define marklen\t\t(sizeof(EOFMARK)/sizeof(char) - 1)\n\n\n/*\n** Check whether 'status' signals a syntax error and the error\n** message at the top of the stack ends with the above mark for\n** incomplete statements.\n*/\nstatic int incomplete (lua_State *L, int status) {\n  if (status == LUA_ERRSYNTAX) {\n    size_t lmsg;\n    const char *msg = lua_tolstring(L, -1, &lmsg);\n    if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0)\n      return 1;\n  }\n  return 0;  /* else... */\n}\n\n\n/*\n** Prompt the user, read a line, and push it into the Lua stack.\n*/\nstatic int pushline (lua_State *L, int firstline) {\n  char buffer[LUA_MAXINPUT];\n  size_t l;\n  const char *prmt = get_prompt(L, firstline);\n  char *b = lua_readline(buffer, prmt);\n  lua_pop(L, 1);  /* remove prompt */\n  if (b == NULL)\n    return 0;  /* no input */\n  l = strlen(b);\n  if (l > 0 && b[l-1] == '\\n')  /* line ends with newline? */\n    b[--l] = '\\0';  /* remove it */\n  lua_pushlstring(L, b, l);\n  lua_freeline(b);\n  return 1;\n}\n\n\n/*\n** Try to compile line on the stack as 'return <line>;'; on return, stack\n** has either compiled chunk or original line (if compilation failed).\n*/\nstatic int addreturn (lua_State *L) {\n  const char *line = lua_tostring(L, -1);  /* original line */\n  const char *retline = lua_pushfstring(L, \"return %s;\", line);\n  int status = luaL_loadbuffer(L, retline, strlen(retline), \"=stdin\");\n  if (status == LUA_OK)\n    lua_remove(L, -2);  /* remove modified line */\n  else\n    lua_pop(L, 2);  /* pop result from 'luaL_loadbuffer' and modified line */\n  return status;\n}\n\n\nstatic void checklocal (const char *line) {\n  static const size_t szloc = sizeof(\"local\") - 1;\n  static const char space[] = \" \\t\";\n  line += strspn(line, space);  /* skip spaces */\n  if (strncmp(line, \"local\", szloc) == 0 &&  /* \"local\"? */\n      strchr(space, *(line + szloc)) != NULL) {  /* followed by a space? */\n    lua_writestringerror(\"%s\\n\",\n      \"warning: locals do not survive across lines in interactive mode\");\n  }\n}\n\n\n/*\n** Read multiple lines until a complete Lua statement or an error not\n** for an incomplete statement. Start with first line already read in\n** the stack.\n*/\nstatic int multiline (lua_State *L) {\n  size_t len;\n  const char *line = lua_tolstring(L, 1, &len);  /* get first line */\n  checklocal(line);\n  for (;;) {  /* repeat until gets a complete statement */\n    int status = luaL_loadbuffer(L, line, len, \"=stdin\");  /* try it */\n    if (!incomplete(L, status) || !pushline(L, 0))\n      return status;  /* should not or cannot try to add continuation line */\n    lua_remove(L, -2);  /* remove error message (from incomplete line) */\n    lua_pushliteral(L, \"\\n\");  /* add newline... */\n    lua_insert(L, -2);  /* ...between the two lines */\n    lua_concat(L, 3);  /* join them */\n    line = lua_tolstring(L, 1, &len);  /* get what is has */\n  }\n}\n\n\n/*\n** Read a line and try to load (compile) it first as an expression (by\n** adding \"return \" in front of it) and second as a statement. Return\n** the final status of load/call with the resulting function (if any)\n** in the top of the stack.\n*/\nstatic int loadline (lua_State *L) {\n  const char *line;\n  int status;\n  lua_settop(L, 0);\n  if (!pushline(L, 1))\n    return -1;  /* no input */\n  if ((status = addreturn(L)) != LUA_OK)  /* 'return ...' did not work? */\n    status = multiline(L);  /* try as command, maybe with continuation lines */\n  line = lua_tostring(L, 1);\n  if (line[0] != '\\0')  /* non empty? */\n    lua_saveline(line);  /* keep history */\n  lua_remove(L, 1);  /* remove line from the stack */\n  lua_assert(lua_gettop(L) == 1);\n  return status;\n}\n\n\n/*\n** Prints (calling the Lua 'print' function) any values on the stack\n*/\nstatic void l_print (lua_State *L) {\n  int n = lua_gettop(L);\n  if (n > 0) {  /* any result to be printed? */\n    luaL_checkstack(L, LUA_MINSTACK, \"too many results to print\");\n    lua_getglobal(L, \"print\");\n    lua_insert(L, 1);\n    if (lua_pcall(L, n, 0, 0) != LUA_OK)\n      l_message(progname, lua_pushfstring(L, \"error calling 'print' (%s)\",\n                                             lua_tostring(L, -1)));\n  }\n}\n\n\n/*\n** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and\n** print any results.\n*/\nstatic void doREPL (lua_State *L) {\n  int status;\n  const char *oldprogname = progname;\n  progname = NULL;  /* no 'progname' on errors in interactive mode */\n  lua_initreadline(L);\n  while ((status = loadline(L)) != -1) {\n    if (status == LUA_OK)\n      status = docall(L, 0, LUA_MULTRET);\n    if (status == LUA_OK) l_print(L);\n    else report(L, status);\n  }\n  lua_settop(L, 0);  /* clear stack */\n  lua_writeline();\n  progname = oldprogname;\n}\n\n/* }================================================================== */\n\n#if !defined(luai_openlibs)\n#define luai_openlibs(L)\tluaL_openselectedlibs(L, ~0, 0)\n#endif\n\n\n/*\n** Main body of stand-alone interpreter (to be called in protected mode).\n** Reads the options and handles them all.\n*/\nstatic int pmain (lua_State *L) {\n  int argc = (int)lua_tointeger(L, 1);\n  char **argv = (char **)lua_touserdata(L, 2);\n  int script;\n  int args = collectargs(argv, &script);\n  int optlim = (script > 0) ? script : argc; /* first argv not an option */\n  luaL_checkversion(L);  /* check that interpreter has correct version */\n  if (args == has_error) {  /* bad arg? */\n    print_usage(argv[script]);  /* 'script' has index of bad arg. */\n    return 0;\n  }\n  if (args & has_v)  /* option '-v'? */\n    print_version();\n  if (args & has_E) {  /* option '-E'? */\n    lua_pushboolean(L, 1);  /* signal for libraries to ignore env. vars. */\n    lua_setfield(L, LUA_REGISTRYINDEX, \"LUA_NOENV\");\n  }\n  luai_openlibs(L);  /* open standard libraries */\n  createargtable(L, argv, argc, script);  /* create table 'arg' */\n  lua_gc(L, LUA_GCRESTART);  /* start GC... */\n  lua_gc(L, LUA_GCGEN);  /* ...in generational mode */\n  if (!(args & has_E)) {  /* no option '-E'? */\n    if (handle_luainit(L) != LUA_OK)  /* run LUA_INIT */\n      return 0;  /* error running LUA_INIT */\n  }\n  if (!runargs(L, argv, optlim))  /* execute arguments -e, -l, and -W */\n    return 0;  /* something failed */\n  if (script > 0) {  /* execute main script (if there is one) */\n    if (handle_script(L, argv + script) != LUA_OK)\n      return 0;  /* interrupt in case of error */\n  }\n  if (args & has_i)  /* -i option? */\n    doREPL(L);  /* do read-eval-print loop */\n  else if (script < 1 && !(args & (has_e | has_v))) { /* no active option? */\n    if (lua_stdin_is_tty()) {  /* running in interactive mode? */\n      print_version();\n      doREPL(L);  /* do read-eval-print loop */\n    }\n    else dofile(L, NULL);  /* executes stdin as a file */\n  }\n  lua_pushboolean(L, 1);  /* signal no errors */\n  return 1;\n}\n\n\nint main (int argc, char **argv) {\n  int status, result;\n  lua_State *L = luaL_newstate();  /* create state */\n  if (L == NULL) {\n    l_message(argv[0], \"cannot create state: not enough memory\");\n    return EXIT_FAILURE;\n  }\n  lua_gc(L, LUA_GCSTOP);  /* stop GC while building state */\n  lua_pushcfunction(L, &pmain);  /* to call 'pmain' in protected mode */\n  lua_pushinteger(L, argc);  /* 1st argument */\n  lua_pushlightuserdata(L, argv); /* 2nd argument */\n  status = lua_pcall(L, 2, 1, 0);  /* do the call */\n  result = lua_toboolean(L, -1);  /* get result */\n  report(L, status);\n  lua_close(L);\n  return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;\n}\n\n"
  },
  {
    "path": "3rd/lua/lua.h",
    "content": "/*\n** $Id: lua.h $\n** Lua - A Scripting Language\n** Lua.org, PUC-Rio, Brazil (www.lua.org)\n** See Copyright Notice at the end of this file\n*/\n\n\n#ifndef lua_h\n#define lua_h\n\n#include <stdarg.h>\n#include <stddef.h>\n\n\n#define LUA_COPYRIGHT\tLUA_RELEASE \"  Copyright (C) 1994-2025 Lua.org, PUC-Rio\"\n#define LUA_AUTHORS\t\"R. Ierusalimschy, L. H. de Figueiredo, W. Celes\"\n\n\n#define LUA_VERSION_MAJOR_N\t5\n#define LUA_VERSION_MINOR_N\t5\n#define LUA_VERSION_RELEASE_N\t0\n\n#define LUA_VERSION_NUM  (LUA_VERSION_MAJOR_N * 100 + LUA_VERSION_MINOR_N)\n#define LUA_VERSION_RELEASE_NUM  (LUA_VERSION_NUM * 100 + LUA_VERSION_RELEASE_N)\n\n\n#include \"luaconf.h\"\n\n\n/* mark for precompiled code ('<esc>Lua') */\n#define LUA_SIGNATURE\t\"\\x1bLua\"\n\n/* option for multiple returns in 'lua_pcall' and 'lua_call' */\n#define LUA_MULTRET\t(-1)\n\n\n/*\n** Pseudo-indices\n** (The stack size is limited to INT_MAX/2; we keep some free empty\n** space after that to help overflow detection.)\n*/\n#define LUA_REGISTRYINDEX\t(-(INT_MAX/2 + 1000))\n#define lua_upvalueindex(i)\t(LUA_REGISTRYINDEX - (i))\n\n\n/* thread status */\n#define LUA_OK\t\t0\n#define LUA_YIELD\t1\n#define LUA_ERRRUN\t2\n#define LUA_ERRSYNTAX\t3\n#define LUA_ERRMEM\t4\n#define LUA_ERRERR\t5\n\n\ntypedef struct lua_State lua_State;\n\n\n/*\n** basic types\n*/\n#define LUA_TNONE\t\t(-1)\n\n#define LUA_TNIL\t\t0\n#define LUA_TBOOLEAN\t\t1\n#define LUA_TLIGHTUSERDATA\t2\n#define LUA_TNUMBER\t\t3\n#define LUA_TSTRING\t\t4\n#define LUA_TTABLE\t\t5\n#define LUA_TFUNCTION\t\t6\n#define LUA_TUSERDATA\t\t7\n#define LUA_TTHREAD\t\t8\n\n#define LUA_NUMTYPES\t\t9\n\n\n\n/* minimum Lua stack available to a C function */\n#define LUA_MINSTACK\t20\n\n\n/* predefined values in the registry */\n/* index 1 is reserved for the reference mechanism */\n#define LUA_RIDX_GLOBALS\t2\n#define LUA_RIDX_MAINTHREAD\t3\n#define LUA_RIDX_LAST\t\t3\n\n\n/* type of numbers in Lua */\ntypedef LUA_NUMBER lua_Number;\n\n\n/* type for integer functions */\ntypedef LUA_INTEGER lua_Integer;\n\n/* unsigned integer type */\ntypedef LUA_UNSIGNED lua_Unsigned;\n\n/* type for continuation-function contexts */\ntypedef LUA_KCONTEXT lua_KContext;\n\n\n/*\n** Type for C functions registered with Lua\n*/\ntypedef int (*lua_CFunction) (lua_State *L);\n\n/*\n** Type for continuation functions\n*/\ntypedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);\n\n\n/*\n** Type for functions that read/write blocks when loading/dumping Lua chunks\n*/\ntypedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);\n\ntypedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud);\n\n\n/*\n** Type for memory-allocation functions\n*/\ntypedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);\n\n\n/*\n** Type for warning functions\n*/\ntypedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);\n\n\n/*\n** Type used by the debug API to collect debug information\n*/\ntypedef struct lua_Debug lua_Debug;\n\n\n/*\n** Functions to be called by the debugger in specific events\n*/\ntypedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);\n\n\n/*\n** generic extra include file\n*/\n#if defined(LUA_USER_H)\n#include LUA_USER_H\n#endif\n\n\n/*\n** RCS ident string\n*/\nextern const char lua_ident[];\n\n\n/*\n** state manipulation\n*/\nLUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud, unsigned seed);\nLUA_API void       (lua_close) (lua_State *L);\nLUA_API lua_State *(lua_newthread) (lua_State *L);\nLUA_API int        (lua_closethread) (lua_State *L, lua_State *from);\n\nLUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf);\n\n\nLUA_API lua_Number (lua_version) (lua_State *L);\n\n\n/*\n** basic stack manipulation\n*/\nLUA_API int   (lua_absindex) (lua_State *L, int idx);\nLUA_API int   (lua_gettop) (lua_State *L);\nLUA_API void  (lua_settop) (lua_State *L, int idx);\nLUA_API void  (lua_pushvalue) (lua_State *L, int idx);\nLUA_API void  (lua_rotate) (lua_State *L, int idx, int n);\nLUA_API void  (lua_copy) (lua_State *L, int fromidx, int toidx);\nLUA_API int   (lua_checkstack) (lua_State *L, int n);\n\nLUA_API void  (lua_xmove) (lua_State *from, lua_State *to, int n);\n\n\n/*\n** access functions (stack -> C)\n*/\n\nLUA_API int             (lua_isnumber) (lua_State *L, int idx);\nLUA_API int             (lua_isstring) (lua_State *L, int idx);\nLUA_API int             (lua_iscfunction) (lua_State *L, int idx);\nLUA_API int             (lua_isinteger) (lua_State *L, int idx);\nLUA_API int             (lua_isuserdata) (lua_State *L, int idx);\nLUA_API int             (lua_type) (lua_State *L, int idx);\nLUA_API const char     *(lua_typename) (lua_State *L, int tp);\n\nLUA_API lua_Number      (lua_tonumberx) (lua_State *L, int idx, int *isnum);\nLUA_API lua_Integer     (lua_tointegerx) (lua_State *L, int idx, int *isnum);\nLUA_API int             (lua_toboolean) (lua_State *L, int idx);\nLUA_API const char     *(lua_tolstring) (lua_State *L, int idx, size_t *len);\nLUA_API lua_Unsigned    (lua_rawlen) (lua_State *L, int idx);\nLUA_API lua_CFunction   (lua_tocfunction) (lua_State *L, int idx);\nLUA_API void\t       *(lua_touserdata) (lua_State *L, int idx);\nLUA_API lua_State      *(lua_tothread) (lua_State *L, int idx);\nLUA_API const void     *(lua_topointer) (lua_State *L, int idx);\n\n\n/*\n** Comparison and arithmetic functions\n*/\n\n#define LUA_OPADD\t0\t/* ORDER TM, ORDER OP */\n#define LUA_OPSUB\t1\n#define LUA_OPMUL\t2\n#define LUA_OPMOD\t3\n#define LUA_OPPOW\t4\n#define LUA_OPDIV\t5\n#define LUA_OPIDIV\t6\n#define LUA_OPBAND\t7\n#define LUA_OPBOR\t8\n#define LUA_OPBXOR\t9\n#define LUA_OPSHL\t10\n#define LUA_OPSHR\t11\n#define LUA_OPUNM\t12\n#define LUA_OPBNOT\t13\n\nLUA_API void  (lua_arith) (lua_State *L, int op);\n\n#define LUA_OPEQ\t0\n#define LUA_OPLT\t1\n#define LUA_OPLE\t2\n\nLUA_API int   (lua_rawequal) (lua_State *L, int idx1, int idx2);\nLUA_API int   (lua_compare) (lua_State *L, int idx1, int idx2, int op);\n\n\n/*\n** push functions (C -> stack)\n*/\nLUA_API void        (lua_pushnil) (lua_State *L);\nLUA_API void        (lua_pushnumber) (lua_State *L, lua_Number n);\nLUA_API void        (lua_pushinteger) (lua_State *L, lua_Integer n);\nLUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len);\nLUA_API const char *(lua_pushexternalstring) (lua_State *L,\n\t\tconst char *s, size_t len, lua_Alloc falloc, void *ud);\nLUA_API const char *(lua_pushstring) (lua_State *L, const char *s);\nLUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt,\n                                                      va_list argp);\nLUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...);\nLUA_API void  (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n);\nLUA_API void  (lua_pushboolean) (lua_State *L, int b);\nLUA_API void  (lua_pushlightuserdata) (lua_State *L, void *p);\nLUA_API int   (lua_pushthread) (lua_State *L);\n\nLUA_API void  (lua_clonefunction) (lua_State *L, const void * fp);\nLUA_API void  (lua_sharefunction) (lua_State *L, int index);\nLUA_API void  (lua_sharestring) (lua_State *L, int index);\nLUA_API void  (lua_clonetable) (lua_State *L, const void * t);\n\n/*\n** get functions (Lua -> stack)\n*/\nLUA_API int (lua_getglobal) (lua_State *L, const char *name);\nLUA_API int (lua_gettable) (lua_State *L, int idx);\nLUA_API int (lua_getfield) (lua_State *L, int idx, const char *k);\nLUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n);\nLUA_API int (lua_rawget) (lua_State *L, int idx);\nLUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n);\nLUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p);\n\nLUA_API void  (lua_createtable) (lua_State *L, int narr, int nrec);\nLUA_API void *(lua_newuserdatauv) (lua_State *L, size_t sz, int nuvalue);\nLUA_API int   (lua_getmetatable) (lua_State *L, int objindex);\nLUA_API int  (lua_getiuservalue) (lua_State *L, int idx, int n);\n\n\n/*\n** set functions (stack -> Lua)\n*/\nLUA_API void  (lua_setglobal) (lua_State *L, const char *name);\nLUA_API void  (lua_settable) (lua_State *L, int idx);\nLUA_API void  (lua_setfield) (lua_State *L, int idx, const char *k);\nLUA_API void  (lua_seti) (lua_State *L, int idx, lua_Integer n);\nLUA_API void  (lua_rawset) (lua_State *L, int idx);\nLUA_API void  (lua_rawseti) (lua_State *L, int idx, lua_Integer n);\nLUA_API void  (lua_rawsetp) (lua_State *L, int idx, const void *p);\nLUA_API int   (lua_setmetatable) (lua_State *L, int objindex);\nLUA_API int   (lua_setiuservalue) (lua_State *L, int idx, int n);\n\n\n/*\n** 'load' and 'call' functions (load and run Lua code)\n*/\nLUA_API void  (lua_callk) (lua_State *L, int nargs, int nresults,\n                           lua_KContext ctx, lua_KFunction k);\n#define lua_call(L,n,r)\t\tlua_callk(L, (n), (r), 0, NULL)\n\nLUA_API int   (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,\n                            lua_KContext ctx, lua_KFunction k);\n#define lua_pcall(L,n,r,f)\tlua_pcallk(L, (n), (r), (f), 0, NULL)\n\nLUA_API int   (lua_load) (lua_State *L, lua_Reader reader, void *dt,\n                          const char *chunkname, const char *mode);\n\nLUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip);\n\n\n/*\n** coroutine functions\n*/\nLUA_API int  (lua_yieldk)     (lua_State *L, int nresults, lua_KContext ctx,\n                               lua_KFunction k);\nLUA_API int  (lua_resume)     (lua_State *L, lua_State *from, int narg,\n                               int *nres);\nLUA_API int  (lua_status)     (lua_State *L);\nLUA_API int (lua_isyieldable) (lua_State *L);\n\n#define lua_yield(L,n)\t\tlua_yieldk(L, (n), 0, NULL)\n\n\n/*\n** Warning-related functions\n*/\nLUA_API void (lua_setwarnf) (lua_State *L, lua_WarnFunction f, void *ud);\nLUA_API void (lua_warning)  (lua_State *L, const char *msg, int tocont);\n\n\n/*\n** garbage-collection options\n*/\n\n#define LUA_GCSTOP\t\t0\n#define LUA_GCRESTART\t\t1\n#define LUA_GCCOLLECT\t\t2\n#define LUA_GCCOUNT\t\t3\n#define LUA_GCCOUNTB\t\t4\n#define LUA_GCSTEP\t\t5\n#define LUA_GCISRUNNING\t\t6\n#define LUA_GCGEN\t\t7\n#define LUA_GCINC\t\t8\n#define LUA_GCPARAM\t\t9\n\n\n/*\n** garbage-collection parameters\n*/\n/* parameters for generational mode */\n#define LUA_GCPMINORMUL\t\t0  /* control minor collections */\n#define LUA_GCPMAJORMINOR\t1  /* control shift major->minor */\n#define LUA_GCPMINORMAJOR\t2  /* control shift minor->major */\n\n/* parameters for incremental mode */\n#define LUA_GCPPAUSE\t\t3  /* size of pause between successive GCs */\n#define LUA_GCPSTEPMUL\t\t4  /* GC \"speed\" */\n#define LUA_GCPSTEPSIZE\t\t5  /* GC granularity */\n\n/* number of parameters */\n#define LUA_GCPN\t\t6\n\n\nLUA_API int (lua_gc) (lua_State *L, int what, ...);\n\n\n/*\n** miscellaneous functions\n*/\n\nLUA_API int   (lua_error) (lua_State *L);\n\nLUA_API int   (lua_next) (lua_State *L, int idx);\n\nLUA_API void  (lua_concat) (lua_State *L, int n);\nLUA_API void  (lua_len)    (lua_State *L, int idx);\n\n#define LUA_N2SBUFFSZ\t64\nLUA_API unsigned  (lua_numbertocstring) (lua_State *L, int idx, char *buff);\nLUA_API size_t  (lua_stringtonumber) (lua_State *L, const char *s);\n\nLUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);\nLUA_API void      (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);\n\nLUA_API void (lua_toclose) (lua_State *L, int idx);\nLUA_API void (lua_closeslot) (lua_State *L, int idx);\n\n\n/*\n** {==============================================================\n** some useful macros\n** ===============================================================\n*/\n\n#define lua_getextraspace(L)\t((void *)((char *)(L) - LUA_EXTRASPACE))\n\n#define lua_tonumber(L,i)\tlua_tonumberx(L,(i),NULL)\n#define lua_tointeger(L,i)\tlua_tointegerx(L,(i),NULL)\n\n#define lua_pop(L,n)\t\tlua_settop(L, -(n)-1)\n\n#define lua_newtable(L)\t\tlua_createtable(L, 0, 0)\n\n#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))\n\n#define lua_pushcfunction(L,f)\tlua_pushcclosure(L, (f), 0)\n\n#define lua_isfunction(L,n)\t(lua_type(L, (n)) == LUA_TFUNCTION)\n#define lua_istable(L,n)\t(lua_type(L, (n)) == LUA_TTABLE)\n#define lua_islightuserdata(L,n)\t(lua_type(L, (n)) == LUA_TLIGHTUSERDATA)\n#define lua_isnil(L,n)\t\t(lua_type(L, (n)) == LUA_TNIL)\n#define lua_isboolean(L,n)\t(lua_type(L, (n)) == LUA_TBOOLEAN)\n#define lua_isthread(L,n)\t(lua_type(L, (n)) == LUA_TTHREAD)\n#define lua_isnone(L,n)\t\t(lua_type(L, (n)) == LUA_TNONE)\n#define lua_isnoneornil(L, n)\t(lua_type(L, (n)) <= 0)\n\n#define lua_pushliteral(L, s)\tlua_pushstring(L, \"\" s)\n\n#define lua_pushglobaltable(L)  \\\n\t((void)lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS))\n\n#define lua_tostring(L,i)\tlua_tolstring(L, (i), NULL)\n\n\n#define lua_insert(L,idx)\tlua_rotate(L, (idx), 1)\n\n#define lua_remove(L,idx)\t(lua_rotate(L, (idx), -1), lua_pop(L, 1))\n\n#define lua_replace(L,idx)\t(lua_copy(L, -1, (idx)), lua_pop(L, 1))\n\n/* }============================================================== */\n\n\n/*\n** {==============================================================\n** compatibility macros\n** ===============================================================\n*/\n\n#define lua_newuserdata(L,s)\tlua_newuserdatauv(L,s,1)\n#define lua_getuservalue(L,idx)\tlua_getiuservalue(L,idx,1)\n#define lua_setuservalue(L,idx)\tlua_setiuservalue(L,idx,1)\n\n#define lua_resetthread(L)\tlua_closethread(L,NULL)\n\n/* }============================================================== */\n\n/*\n** {======================================================================\n** Debug API\n** =======================================================================\n*/\n\n\n/*\n** Event codes\n*/\n#define LUA_HOOKCALL\t0\n#define LUA_HOOKRET\t1\n#define LUA_HOOKLINE\t2\n#define LUA_HOOKCOUNT\t3\n#define LUA_HOOKTAILCALL 4\n\n\n/*\n** Event masks\n*/\n#define LUA_MASKCALL\t(1 << LUA_HOOKCALL)\n#define LUA_MASKRET\t(1 << LUA_HOOKRET)\n#define LUA_MASKLINE\t(1 << LUA_HOOKLINE)\n#define LUA_MASKCOUNT\t(1 << LUA_HOOKCOUNT)\n\n\nLUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar);\nLUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar);\nLUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n);\nLUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n);\nLUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n);\nLUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n);\n\nLUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n);\nLUA_API void  (lua_upvaluejoin) (lua_State *L, int fidx1, int n1,\n                                               int fidx2, int n2);\n\nLUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count);\nLUA_API lua_Hook (lua_gethook) (lua_State *L);\nLUA_API int (lua_gethookmask) (lua_State *L);\nLUA_API int (lua_gethookcount) (lua_State *L);\n\n\nstruct lua_Debug {\n  int event;\n  const char *name;\t/* (n) */\n  const char *namewhat;\t/* (n) 'global', 'local', 'field', 'method' */\n  const char *what;\t/* (S) 'Lua', 'C', 'main', 'tail' */\n  const char *source;\t/* (S) */\n  size_t srclen;\t/* (S) */\n  int currentline;\t/* (l) */\n  int linedefined;\t/* (S) */\n  int lastlinedefined;\t/* (S) */\n  unsigned char nups;\t/* (u) number of upvalues */\n  unsigned char nparams;/* (u) number of parameters */\n  char isvararg;        /* (u) */\n  unsigned char extraargs;  /* (t) number of extra arguments */\n  char istailcall;\t/* (t) */\n  int ftransfer;   /* (r) index of first value transferred */\n  int ntransfer;   /* (r) number of transferred values */\n  char short_src[LUA_IDSIZE]; /* (S) */\n  /* private part */\n  struct CallInfo *i_ci;  /* active function */\n};\n\n/* }====================================================================== */\n\n\n#define LUAI_TOSTRAUX(x)\t#x\n#define LUAI_TOSTR(x)\t\tLUAI_TOSTRAUX(x)\n\n#define LUA_VERSION_MAJOR\tLUAI_TOSTR(LUA_VERSION_MAJOR_N)\n#define LUA_VERSION_MINOR\tLUAI_TOSTR(LUA_VERSION_MINOR_N)\n#define LUA_VERSION_RELEASE\tLUAI_TOSTR(LUA_VERSION_RELEASE_N)\n\n#define LUA_VERSION\t\"Lua \" LUA_VERSION_MAJOR \".\" LUA_VERSION_MINOR\n#define LUA_RELEASE\tLUA_VERSION \".\" LUA_VERSION_RELEASE\n\n\n/******************************************************************************\n* Copyright (C) 1994-2025 Lua.org, PUC-Rio.\n*\n* Permission is hereby granted, free of charge, to any person obtaining\n* a copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without limitation the rights to use, copy, modify, merge, publish,\n* distribute, sublicense, and/or sell copies of the Software, and to\n* permit persons to whom the Software is furnished to do so, subject to\n* the following conditions:\n*\n* The above copyright notice and this permission notice shall be\n* included in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n******************************************************************************/\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lua.hpp",
    "content": "// lua.hpp\n// Lua header files for C++\n// 'extern \"C\" not supplied automatically in lua.h and other headers\n// because Lua also compiles as C++\n\nextern \"C\" {\n#include \"lua.h\"\n#include \"lualib.h\"\n#include \"lauxlib.h\"\n}\n"
  },
  {
    "path": "3rd/lua/luac.c",
    "content": "/*\n** $Id: luac.c $\n** Lua compiler (saves bytecodes to files; also lists bytecodes)\n** See Copyright Notice in lua.h\n*/\n\n#define luac_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n#include <ctype.h>\n#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n#include \"lauxlib.h\"\n\n#include \"lapi.h\"\n#include \"ldebug.h\"\n#include \"lobject.h\"\n#include \"lopcodes.h\"\n#include \"lopnames.h\"\n#include \"lstate.h\"\n#include \"lundump.h\"\n\nstatic void PrintFunction(const Proto* f, int full);\n#define luaU_print\tPrintFunction\n\n#define PROGNAME\t\"luac\"\t\t/* default program name */\n#define OUTPUT\t\tPROGNAME \".out\"\t/* default output file */\n\nstatic int listing=0;\t\t\t/* list bytecodes? */\nstatic int dumping=1;\t\t\t/* dump bytecodes? */\nstatic int stripping=0;\t\t\t/* strip debug information? */\nstatic char Output[]={ OUTPUT };\t/* default output file name */\nstatic const char* output=Output;\t/* actual output file name */\nstatic const char* progname=PROGNAME;\t/* actual program name */\nstatic TString **tmname;\n\nstatic void fatal(const char* message)\n{\n fprintf(stderr,\"%s: %s\\n\",progname,message);\n exit(EXIT_FAILURE);\n}\n\nstatic void cannot(const char* what)\n{\n fprintf(stderr,\"%s: cannot %s %s: %s\\n\",progname,what,output,strerror(errno));\n exit(EXIT_FAILURE);\n}\n\nstatic void usage(const char* message)\n{\n if (*message=='-')\n  fprintf(stderr,\"%s: unrecognized option '%s'\\n\",progname,message);\n else\n  fprintf(stderr,\"%s: %s\\n\",progname,message);\n fprintf(stderr,\n  \"usage: %s [options] [filenames]\\n\"\n  \"Available options are:\\n\"\n  \"  -l       list (use -l -l for full listing)\\n\"\n  \"  -o name  output to file 'name' (default is \\\"%s\\\")\\n\"\n  \"  -p       parse only\\n\"\n  \"  -s       strip debug information\\n\"\n  \"  -v       show version information\\n\"\n  \"  --       stop handling options\\n\"\n  \"  -        stop handling options and process stdin\\n\"\n  ,progname,Output);\n exit(EXIT_FAILURE);\n}\n\n#define IS(s)\t(strcmp(argv[i],s)==0)\n\nstatic int doargs(int argc, char* argv[])\n{\n int i;\n int version=0;\n if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0];\n for (i=1; i<argc; i++)\n {\n  if (*argv[i]!='-')\t\t\t/* end of options; keep it */\n   break;\n  else if (IS(\"--\"))\t\t\t/* end of options; skip it */\n  {\n   ++i;\n   if (version) ++version;\n   break;\n  }\n  else if (IS(\"-\"))\t\t\t/* end of options; use stdin */\n   break;\n  else if (IS(\"-l\"))\t\t\t/* list */\n   ++listing;\n  else if (IS(\"-o\"))\t\t\t/* output file */\n  {\n   output=argv[++i];\n   if (output==NULL || *output==0 || (*output=='-' && output[1]!=0))\n    usage(\"'-o' needs argument\");\n   if (IS(\"-\")) output=NULL;\n  }\n  else if (IS(\"-p\"))\t\t\t/* parse only */\n   dumping=0;\n  else if (IS(\"-s\"))\t\t\t/* strip debug information */\n   stripping=1;\n  else if (IS(\"-v\"))\t\t\t/* show version */\n   ++version;\n  else\t\t\t\t\t/* unknown option */\n   usage(argv[i]);\n }\n if (i==argc && (listing || !dumping))\n {\n  dumping=0;\n  argv[--i]=Output;\n }\n if (version)\n {\n  printf(\"%s\\n\",LUA_COPYRIGHT);\n  if (version==argc-1) exit(EXIT_SUCCESS);\n }\n return i;\n}\n\n#define FUNCTION \"(function()end)();\\n\"\n\nstatic const char* reader(lua_State* L, void* ud, size_t* size)\n{\n UNUSED(L);\n if ((*(int*)ud)--)\n {\n  *size=sizeof(FUNCTION)-1;\n  return FUNCTION;\n }\n else\n {\n  *size=0;\n  return NULL;\n }\n}\n\n#define toproto(L,i) getproto(s2v(L->top.p+(i)))\n\nstatic const Proto* combine(lua_State* L, int n)\n{\n if (n==1)\n  return toproto(L,-1);\n else\n {\n  Proto* f;\n  int i=n;\n  if (lua_load(L,reader,&i,\"=(\" PROGNAME \")\",NULL)!=LUA_OK) fatal(lua_tostring(L,-1));\n  f=toproto(L,-1);\n  for (i=0; i<n; i++)\n  {\n   f->p[i]=toproto(L,i-n-1);\n   if (f->p[i]->sizeupvalues>0) f->p[i]->upvalues[0].instack=0;\n  }\n  return f;\n }\n}\n\nstatic int writer(lua_State* L, const void* p, size_t size, void* u)\n{\n UNUSED(L);\n return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0);\n}\n\nstatic int pmain(lua_State* L)\n{\n int argc=(int)lua_tointeger(L,1);\n char** argv=(char**)lua_touserdata(L,2);\n const Proto* f;\n int i;\n tmname=G(L)->tmname;\n if (!lua_checkstack(L,argc)) fatal(\"too many input files\");\n for (i=0; i<argc; i++)\n {\n  const char* filename=IS(\"-\") ? NULL : argv[i];\n  if (luaL_loadfile(L,filename)!=LUA_OK) fatal(lua_tostring(L,-1));\n }\n f=combine(L,argc);\n if (listing) luaU_print(f,listing>1);\n if (dumping)\n {\n  FILE* D= (output==NULL) ? stdout : fopen(output,\"wb\");\n  if (D==NULL) cannot(\"open\");\n  lua_lock(L);\n  luaU_dump(L,f,writer,D,stripping);\n  lua_unlock(L);\n  if (ferror(D)) cannot(\"write\");\n  if (fclose(D)) cannot(\"close\");\n }\n return 0;\n}\n\nint main(int argc, char* argv[])\n{\n lua_State* L;\n int i=doargs(argc,argv);\n argc-=i; argv+=i;\n if (argc<=0) usage(\"no input files given\");\n L=luaL_newstate();\n if (L==NULL) fatal(\"cannot create state: not enough memory\");\n lua_pushcfunction(L,&pmain);\n lua_pushinteger(L,argc);\n lua_pushlightuserdata(L,argv);\n if (lua_pcall(L,2,0,0)!=LUA_OK) fatal(lua_tostring(L,-1));\n lua_close(L);\n return EXIT_SUCCESS;\n}\n\n/*\n** print bytecodes\n*/\n\n#define UPVALNAME(x) ((f->upvalues[x].name) ? getstr(f->upvalues[x].name) : \"-\")\n#define VOID(p) ((const void*)(p))\n#define eventname(i) (getstr(tmname[i]))\n\nstatic void PrintString(const TString* ts)\n{\n const char* s=getstr(ts);\n size_t i,n=tsslen(ts);\n printf(\"\\\"\");\n for (i=0; i<n; i++)\n {\n  int c=(int)(unsigned char)s[i];\n  switch (c)\n  {\n   case '\"':\n\tprintf(\"\\\\\\\"\");\n\tbreak;\n   case '\\\\':\n\tprintf(\"\\\\\\\\\");\n\tbreak;\n   case '\\a':\n\tprintf(\"\\\\a\");\n\tbreak;\n   case '\\b':\n\tprintf(\"\\\\b\");\n\tbreak;\n   case '\\f':\n\tprintf(\"\\\\f\");\n\tbreak;\n   case '\\n':\n\tprintf(\"\\\\n\");\n\tbreak;\n   case '\\r':\n\tprintf(\"\\\\r\");\n\tbreak;\n   case '\\t':\n\tprintf(\"\\\\t\");\n\tbreak;\n   case '\\v':\n\tprintf(\"\\\\v\");\n\tbreak;\n   default:\n\tif (isprint(c)) printf(\"%c\",c); else printf(\"\\\\%03d\",c);\n\tbreak;\n  }\n }\n printf(\"\\\"\");\n}\n\nstatic void PrintType(const Proto* f, int i)\n{\n const TValue* o=&f->k[i];\n switch (ttypetag(o))\n {\n  case LUA_VNIL:\n\tprintf(\"N\");\n\tbreak;\n  case LUA_VFALSE:\n  case LUA_VTRUE:\n\tprintf(\"B\");\n\tbreak;\n  case LUA_VNUMFLT:\n\tprintf(\"F\");\n\tbreak;\n  case LUA_VNUMINT:\n\tprintf(\"I\");\n\tbreak;\n  case LUA_VSHRSTR:\n  case LUA_VLNGSTR:\n\tprintf(\"S\");\n\tbreak;\n  default:\t\t\t\t/* cannot happen */\n\tprintf(\"?%d\",ttypetag(o));\n\tbreak;\n }\n printf(\"\\t\");\n}\n\nstatic void PrintConstant(const Proto* f, int i)\n{\n const TValue* o=&f->k[i];\n switch (ttypetag(o))\n {\n  case LUA_VNIL:\n\tprintf(\"nil\");\n\tbreak;\n  case LUA_VFALSE:\n\tprintf(\"false\");\n\tbreak;\n  case LUA_VTRUE:\n\tprintf(\"true\");\n\tbreak;\n  case LUA_VNUMFLT:\n\t{\n\tchar buff[100];\n\tsprintf(buff,LUA_NUMBER_FMT,fltvalue(o));\n\tprintf(\"%s\",buff);\n\tif (buff[strspn(buff,\"-0123456789\")]=='\\0') printf(\".0\");\n\tbreak;\n\t}\n  case LUA_VNUMINT:\n\tprintf(LUA_INTEGER_FMT,ivalue(o));\n\tbreak;\n  case LUA_VSHRSTR:\n  case LUA_VLNGSTR:\n\tPrintString(tsvalue(o));\n\tbreak;\n  default:\t\t\t\t/* cannot happen */\n\tprintf(\"?%d\",ttypetag(o));\n\tbreak;\n }\n}\n\n#define COMMENT\t\t\"\\t; \"\n#define EXTRAARG\tGETARG_Ax(code[pc+1])\n#define EXTRAARGC\t(EXTRAARG*(MAXARG_C+1))\n#define ISK\t\t(isk ? \"k\" : \"\")\n\nstatic void PrintCode(const Proto* f)\n{\n const Instruction* code=f->code;\n int pc,n=f->sizecode;\n for (pc=0; pc<n; pc++)\n {\n  Instruction i=code[pc];\n  OpCode o=GET_OPCODE(i);\n  int a=GETARG_A(i);\n  int b=GETARG_B(i);\n  int c=GETARG_C(i);\n  int ax=GETARG_Ax(i);\n  int bx=GETARG_Bx(i);\n  int sb=GETARG_sB(i);\n  int sc=GETARG_sC(i);\n  int vb=GETARG_vB(i);\n  int vc=GETARG_vC(i);\n  int sbx=GETARG_sBx(i);\n  int isk=GETARG_k(i);\n  int line=luaG_getfuncline(f,pc);\n  printf(\"\\t%d\\t\",pc+1);\n  if (line>0) printf(\"[%d]\\t\",line); else printf(\"[-]\\t\");\n  printf(\"%-9s\\t\",opnames[o]);\n  switch (o)\n  {\n   case OP_MOVE:\n\tprintf(\"%d %d\",a,b);\n\tbreak;\n   case OP_LOADI:\n\tprintf(\"%d %d\",a,sbx);\n\tbreak;\n   case OP_LOADF:\n\tprintf(\"%d %d\",a,sbx);\n\tbreak;\n   case OP_LOADK:\n\tprintf(\"%d %d\",a,bx);\n\tprintf(COMMENT); PrintConstant(f,bx);\n\tbreak;\n   case OP_LOADKX:\n\tprintf(\"%d\",a);\n\tprintf(COMMENT); PrintConstant(f,EXTRAARG);\n\tbreak;\n   case OP_LOADFALSE:\n\tprintf(\"%d\",a);\n\tbreak;\n   case OP_LFALSESKIP:\n\tprintf(\"%d\",a);\n\tbreak;\n   case OP_LOADTRUE:\n\tprintf(\"%d\",a);\n\tbreak;\n   case OP_LOADNIL:\n\tprintf(\"%d %d\",a,b);\n\tprintf(COMMENT \"%d out\",b+1);\n\tbreak;\n   case OP_GETUPVAL:\n\tprintf(\"%d %d\",a,b);\n\tprintf(COMMENT \"%s\",UPVALNAME(b));\n\tbreak;\n   case OP_SETUPVAL:\n\tprintf(\"%d %d\",a,b);\n\tprintf(COMMENT \"%s\",UPVALNAME(b));\n\tbreak;\n   case OP_GETTABUP:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT \"%s\",UPVALNAME(b));\n\tprintf(\" \"); PrintConstant(f,c);\n\tbreak;\n   case OP_GETTABLE:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_GETI:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_GETFIELD:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_SETTABUP:\n\tprintf(\"%d %d %d%s\",a,b,c,ISK);\n\tprintf(COMMENT \"%s\",UPVALNAME(a));\n\tprintf(\" \"); PrintConstant(f,b);\n\tif (isk) { printf(\" \"); PrintConstant(f,c); }\n\tbreak;\n   case OP_SETTABLE:\n\tprintf(\"%d %d %d%s\",a,b,c,ISK);\n\tif (isk) { printf(COMMENT); PrintConstant(f,c); }\n\tbreak;\n   case OP_SETI:\n\tprintf(\"%d %d %d%s\",a,b,c,ISK);\n\tif (isk) { printf(COMMENT); PrintConstant(f,c); }\n\tbreak;\n   case OP_SETFIELD:\n\tprintf(\"%d %d %d%s\",a,b,c,ISK);\n\tprintf(COMMENT); PrintConstant(f,b);\n\tif (isk) { printf(\" \"); PrintConstant(f,c); }\n\tbreak;\n   case OP_NEWTABLE:\n\tprintf(\"%d %d %d%s\",a,vb,vc,ISK);\n\tprintf(COMMENT \"%d\",vc+EXTRAARGC);\n\tbreak;\n   case OP_SELF:\n\tprintf(\"%d %d %d%s\",a,b,c,ISK);\n\tif (isk) { printf(COMMENT); PrintConstant(f,c); }\n\tbreak;\n   case OP_ADDI:\n\tprintf(\"%d %d %d\",a,b,sc);\n\tbreak;\n   case OP_ADDK:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_SUBK:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_MULK:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_MODK:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_POWK:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_DIVK:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_IDIVK:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_BANDK:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_BORK:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_BXORK:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT); PrintConstant(f,c);\n\tbreak;\n   case OP_SHLI:\n\tprintf(\"%d %d %d\",a,b,sc);\n\tbreak;\n   case OP_SHRI:\n\tprintf(\"%d %d %d\",a,b,sc);\n\tbreak;\n   case OP_ADD:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_SUB:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_MUL:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_MOD:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_POW:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_DIV:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_IDIV:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_BAND:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_BOR:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_BXOR:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_SHL:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_SHR:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_MMBIN:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT \"%s\",eventname(c));\n\tbreak;\n   case OP_MMBINI:\n\tprintf(\"%d %d %d %d\",a,sb,c,isk);\n\tprintf(COMMENT \"%s\",eventname(c));\n\tif (isk) printf(\" flip\");\n\tbreak;\n   case OP_MMBINK:\n\tprintf(\"%d %d %d %d\",a,b,c,isk);\n\tprintf(COMMENT \"%s \",eventname(c)); PrintConstant(f,b);\n\tif (isk) printf(\" flip\");\n\tbreak;\n   case OP_UNM:\n\tprintf(\"%d %d\",a,b);\n\tbreak;\n   case OP_BNOT:\n\tprintf(\"%d %d\",a,b);\n\tbreak;\n   case OP_NOT:\n\tprintf(\"%d %d\",a,b);\n\tbreak;\n   case OP_LEN:\n\tprintf(\"%d %d\",a,b);\n\tbreak;\n   case OP_CONCAT:\n\tprintf(\"%d %d\",a,b);\n\tbreak;\n   case OP_CLOSE:\n\tprintf(\"%d\",a);\n\tbreak;\n   case OP_TBC:\n\tprintf(\"%d\",a);\n\tbreak;\n   case OP_JMP:\n\tprintf(\"%d\",GETARG_sJ(i));\n\tprintf(COMMENT \"to %d\",GETARG_sJ(i)+pc+2);\n\tbreak;\n   case OP_EQ:\n\tprintf(\"%d %d %d\",a,b,isk);\n\tbreak;\n   case OP_LT:\n\tprintf(\"%d %d %d\",a,b,isk);\n\tbreak;\n   case OP_LE:\n\tprintf(\"%d %d %d\",a,b,isk);\n\tbreak;\n   case OP_EQK:\n\tprintf(\"%d %d %d\",a,b,isk);\n\tprintf(COMMENT); PrintConstant(f,b);\n\tbreak;\n   case OP_EQI:\n\tprintf(\"%d %d %d\",a,sb,isk);\n\tbreak;\n   case OP_LTI:\n\tprintf(\"%d %d %d\",a,sb,isk);\n\tbreak;\n   case OP_LEI:\n\tprintf(\"%d %d %d\",a,sb,isk);\n\tbreak;\n   case OP_GTI:\n\tprintf(\"%d %d %d\",a,sb,isk);\n\tbreak;\n   case OP_GEI:\n\tprintf(\"%d %d %d\",a,sb,isk);\n\tbreak;\n   case OP_TEST:\n\tprintf(\"%d %d\",a,isk);\n\tbreak;\n   case OP_TESTSET:\n\tprintf(\"%d %d %d\",a,b,isk);\n\tbreak;\n   case OP_CALL:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT);\n\tif (b==0) printf(\"all in \"); else printf(\"%d in \",b-1);\n\tif (c==0) printf(\"all out\"); else printf(\"%d out\",c-1);\n\tbreak;\n   case OP_TAILCALL:\n\tprintf(\"%d %d %d%s\",a,b,c,ISK);\n\tprintf(COMMENT \"%d in\",b-1);\n\tbreak;\n   case OP_RETURN:\n\tprintf(\"%d %d %d%s\",a,b,c,ISK);\n\tprintf(COMMENT);\n\tif (b==0) printf(\"all out\"); else printf(\"%d out\",b-1);\n\tbreak;\n   case OP_RETURN0:\n\tbreak;\n   case OP_RETURN1:\n\tprintf(\"%d\",a);\n\tbreak;\n   case OP_FORLOOP:\n\tprintf(\"%d %d\",a,bx);\n\tprintf(COMMENT \"to %d\",pc-bx+2);\n\tbreak;\n   case OP_FORPREP:\n\tprintf(\"%d %d\",a,bx);\n\tprintf(COMMENT \"exit to %d\",pc+bx+3);\n\tbreak;\n   case OP_TFORPREP:\n\tprintf(\"%d %d\",a,bx);\n\tprintf(COMMENT \"to %d\",pc+bx+2);\n\tbreak;\n   case OP_TFORCALL:\n\tprintf(\"%d %d\",a,c);\n\tbreak;\n   case OP_TFORLOOP:\n\tprintf(\"%d %d\",a,bx);\n\tprintf(COMMENT \"to %d\",pc-bx+2);\n\tbreak;\n   case OP_SETLIST:\n\tprintf(\"%d %d %d%s\",a,vb,vc,ISK);\n\tif (isk) printf(COMMENT \"%d\",c+EXTRAARGC);\n\tbreak;\n   case OP_CLOSURE:\n\tprintf(\"%d %d\",a,bx);\n\tprintf(COMMENT \"%p\",VOID(f->p[bx]));\n\tbreak;\n   case OP_VARARG:\n\tprintf(\"%d %d %d%s\",a,b,c,ISK);\n\tprintf(COMMENT);\n\tif (c==0) printf(\"all out\"); else printf(\"%d out\",c-1);\n\tbreak;\n   case OP_GETVARG:\n\tprintf(\"%d %d %d\",a,b,c);\n\tbreak;\n   case OP_ERRNNIL:\n\tprintf(\"%d %d\",a,bx);\n\tprintf(COMMENT);\n\tif (bx==0) printf(\"?\"); else PrintConstant(f,bx-1);\n\tbreak;\n   case OP_VARARGPREP:\n\tprintf(\"%d\",a);\n\tbreak;\n   case OP_EXTRAARG:\n\tprintf(\"%d\",ax);\n\tbreak;\n#if 0\n   default:\n\tprintf(\"%d %d %d\",a,b,c);\n\tprintf(COMMENT \"not handled\");\n\tbreak;\n#endif\n  }\n  printf(\"\\n\");\n }\n}\n\n#define SS(x)\t((x==1)?\"\":\"s\")\n#define S(x)\t(int)(x),SS(x)\n\nstatic void PrintHeader(const Proto* f)\n{\n const char* s=f->source ? getstr(f->source) : \"=?\";\n if (*s=='@' || *s=='=')\n  s++;\n else if (*s==LUA_SIGNATURE[0])\n  s=\"(bstring)\";\n else\n  s=\"(string)\";\n printf(\"\\n%s <%s:%d,%d> (%d instruction%s at %p)\\n\",\n\t(f->linedefined==0)?\"main\":\"function\",s,\n\tf->linedefined,f->lastlinedefined,\n\tS(f->sizecode),VOID(f));\n printf(\"%d%s param%s, %d slot%s, %d upvalue%s, \",\n\t(int)(f->numparams),isvararg(f)?\"+\":\"\",SS(f->numparams),\n\tS(f->maxstacksize),S(f->sizeupvalues));\n printf(\"%d local%s, %d constant%s, %d function%s\\n\",\n\tS(f->sizelocvars),S(f->sizek),S(f->sizep));\n}\n\nstatic void PrintDebug(const Proto* f)\n{\n int i,n;\n n=f->sizek;\n printf(\"constants (%d) for %p:\\n\",n,VOID(f));\n for (i=0; i<n; i++)\n {\n  printf(\"\\t%d\\t\",i);\n  PrintType(f,i);\n  PrintConstant(f,i);\n  printf(\"\\n\");\n }\n n=f->sizelocvars;\n printf(\"locals (%d) for %p:\\n\",n,VOID(f));\n for (i=0; i<n; i++)\n {\n  printf(\"\\t%d\\t%s\\t%d\\t%d\\n\",\n  i,getstr(f->locvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1);\n }\n n=f->sizeupvalues;\n printf(\"upvalues (%d) for %p:\\n\",n,VOID(f));\n for (i=0; i<n; i++)\n {\n  printf(\"\\t%d\\t%s\\t%d\\t%d\\n\",\n  i,UPVALNAME(i),f->upvalues[i].instack,f->upvalues[i].idx);\n }\n}\n\nstatic void PrintFunction(const Proto* f, int full)\n{\n int i,n=f->sizep;\n PrintHeader(f);\n PrintCode(f);\n if (full) PrintDebug(f);\n for (i=0; i<n; i++) PrintFunction(f->p[i],full);\n}\n"
  },
  {
    "path": "3rd/lua/luaconf.h",
    "content": "/*\n** $Id: luaconf.h $\n** Configuration file for Lua\n** See Copyright Notice in lua.h\n*/\n\n\n#ifndef luaconf_h\n#define luaconf_h\n\n#include <limits.h>\n#include <stddef.h>\n\n\n/*\n** ===================================================================\n** General Configuration File for Lua\n**\n** Some definitions here can be changed externally, through the compiler\n** (e.g., with '-D' options): They are commented out or protected\n** by '#if !defined' guards. However, several other definitions\n** should be changed directly here, either because they affect the\n** Lua ABI (by making the changes here, you ensure that all software\n** connected to Lua, such as C libraries, will be compiled with the same\n** configuration); or because they are seldom changed.\n**\n** Search for \"@@\" to find all configurable definitions.\n** ===================================================================\n*/\n\n\n/*\n** {====================================================================\n** System Configuration: macros to adapt (if needed) Lua to some\n** particular platform, for instance restricting it to C89.\n** =====================================================================\n*/\n\n/*\n@@ LUA_USE_C89 controls the use of non-ISO-C89 features.\n** Define it if you want Lua to avoid the use of a few C99 features\n** or Windows-specific features on Windows.\n*/\n/* #define LUA_USE_C89 */\n\n\n/*\n** By default, Lua on Windows use (some) specific Windows features\n*/\n#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE)\n#define LUA_USE_WINDOWS  /* enable goodies for regular Windows */\n#endif\n\n\n#if defined(LUA_USE_WINDOWS)\n#define LUA_DL_DLL\t/* enable support for DLL */\n#define LUA_USE_C89\t/* broadly, Windows is C89 */\n#endif\n\n\n/*\n** When POSIX DLL ('LUA_USE_DLOPEN') is enabled, the Lua stand-alone\n** application will try to dynamically link a 'readline' facility\n** for its REPL.  In that case, LUA_READLINELIB is the name of the\n** library it will look for those facilities.  If lua.c cannot open\n** the specified library, it will generate a warning and then run\n** without 'readline'.  If that macro is not defined, lua.c will not\n** use 'readline'.\n*/\n#if defined(LUA_USE_LINUX)\n#define LUA_USE_POSIX\n#define LUA_USE_DLOPEN\t\t/* needs an extra library: -ldl */\n#define LUA_READLINELIB\t\t\"libreadline.so\"\n#endif\n\n\n#if defined(LUA_USE_MACOSX)\n#define LUA_USE_POSIX\n#define LUA_USE_DLOPEN\t\t/* macOS does not need -ldl */\n#define LUA_READLINELIB\t\t\"libedit.dylib\"\n#endif\n\n\n#if defined(LUA_USE_IOS)\n#define LUA_USE_POSIX\n#define LUA_USE_DLOPEN\n#endif\n\n\n#if defined(LUA_USE_C89) && defined(LUA_USE_POSIX)\n#error \"POSIX is not compatible with C89\"\n#endif\n\n\n/*\n@@ LUAI_IS32INT is true iff 'int' has (at least) 32 bits.\n*/\n#define LUAI_IS32INT\t((UINT_MAX >> 30) >= 3)\n\n/* }================================================================== */\n\n\n\n/*\n** {==================================================================\n** Configuration for Number types. These options should not be\n** set externally, because any other code connected to Lua must\n** use the same configuration.\n** ===================================================================\n*/\n\n/*\n@@ LUA_INT_TYPE defines the type for Lua integers.\n@@ LUA_FLOAT_TYPE defines the type for Lua floats.\n** Lua should work fine with any mix of these options supported\n** by your C compiler. The usual configurations are 64-bit integers\n** and 'double' (the default), 32-bit integers and 'float' (for\n** restricted platforms), and 'long'/'double' (for C compilers not\n** compliant with C99, which may not have support for 'long long').\n*/\n\n/* predefined options for LUA_INT_TYPE */\n#define LUA_INT_INT\t\t1\n#define LUA_INT_LONG\t\t2\n#define LUA_INT_LONGLONG\t3\n\n/* predefined options for LUA_FLOAT_TYPE */\n#define LUA_FLOAT_FLOAT\t\t1\n#define LUA_FLOAT_DOUBLE\t2\n#define LUA_FLOAT_LONGDOUBLE\t3\n\n\n/* Default configuration ('long long' and 'double', for 64-bit Lua) */\n#define LUA_INT_DEFAULT\t\tLUA_INT_LONGLONG\n#define LUA_FLOAT_DEFAULT\tLUA_FLOAT_DOUBLE\n\n\n/*\n@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats.\n*/\n/* #define LUA_32BITS */\n\n\n/*\n@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for\n** C89 ('long' and 'double'); Windows always has '__int64', so it does\n** not need to use this case.\n*/\n#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS)\n#define LUA_C89_NUMBERS\t\t1\n#else\n#define LUA_C89_NUMBERS\t\t0\n#endif\n\n\n#if defined(LUA_32BITS)\t/* { */\n/*\n** 32-bit integers and 'float'\n*/\n#if LUAI_IS32INT  /* use 'int' if big enough */\n#define LUA_INT_TYPE\tLUA_INT_INT\n#else  /* otherwise use 'long' */\n#define LUA_INT_TYPE\tLUA_INT_LONG\n#endif\n#define LUA_FLOAT_TYPE\tLUA_FLOAT_FLOAT\n\n#elif LUA_C89_NUMBERS\t/* }{ */\n/*\n** largest types available for C89 ('long' and 'double')\n*/\n#define LUA_INT_TYPE\tLUA_INT_LONG\n#define LUA_FLOAT_TYPE\tLUA_FLOAT_DOUBLE\n\n#else\t\t/* }{ */\n/* use defaults */\n\n#define LUA_INT_TYPE\tLUA_INT_DEFAULT\n#define LUA_FLOAT_TYPE\tLUA_FLOAT_DEFAULT\n\n#endif\t\t\t\t/* } */\n\n\n/* }================================================================== */\n\n\n\n/*\n** {==================================================================\n** Configuration for Paths.\n** ===================================================================\n*/\n\n/*\n** LUA_PATH_SEP is the character that separates templates in a path.\n** LUA_PATH_MARK is the string that marks the substitution points in a\n** template.\n** LUA_EXEC_DIR in a Windows path is replaced by the executable's\n** directory.\n*/\n#define LUA_PATH_SEP            \";\"\n#define LUA_PATH_MARK           \"?\"\n#define LUA_EXEC_DIR            \"!\"\n\n\n/*\n@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for\n** Lua libraries.\n@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for\n** C libraries.\n** CHANGE them if your machine has a non-conventional directory\n** hierarchy or if you want to install your libraries in\n** non-conventional directories.\n*/\n\n#define LUA_VDIR\tLUA_VERSION_MAJOR \".\" LUA_VERSION_MINOR\n#if defined(_WIN32)\t/* { */\n/*\n** In Windows, any exclamation mark ('!') in the path is replaced by the\n** path of the directory of the executable file of the current process.\n*/\n#define LUA_LDIR\t\"!\\\\lua\\\\\"\n#define LUA_CDIR\t\"!\\\\\"\n#define LUA_SHRDIR\t\"!\\\\..\\\\share\\\\lua\\\\\" LUA_VDIR \"\\\\\"\n\n#if !defined(LUA_PATH_DEFAULT)\n#define LUA_PATH_DEFAULT  \\\n\t\tLUA_LDIR\"?.lua;\"  LUA_LDIR\"?\\\\init.lua;\" \\\n\t\tLUA_CDIR\"?.lua;\"  LUA_CDIR\"?\\\\init.lua;\" \\\n\t\tLUA_SHRDIR\"?.lua;\" LUA_SHRDIR\"?\\\\init.lua;\" \\\n\t\t\".\\\\?.lua;\" \".\\\\?\\\\init.lua\"\n#endif\n\n#if !defined(LUA_CPATH_DEFAULT)\n#define LUA_CPATH_DEFAULT \\\n\t\tLUA_CDIR\"?.dll;\" \\\n\t\tLUA_CDIR\"..\\\\lib\\\\lua\\\\\" LUA_VDIR \"\\\\?.dll;\" \\\n\t\tLUA_CDIR\"loadall.dll;\" \".\\\\?.dll\"\n#endif\n\n#else\t\t\t/* }{ */\n\n#define LUA_ROOT\t\"/usr/local/\"\n#define LUA_LDIR\tLUA_ROOT \"share/lua/\" LUA_VDIR \"/\"\n#define LUA_CDIR\tLUA_ROOT \"lib/lua/\" LUA_VDIR \"/\"\n\n#if !defined(LUA_PATH_DEFAULT)\n#define LUA_PATH_DEFAULT  \\\n\t\tLUA_LDIR\"?.lua;\"  LUA_LDIR\"?/init.lua;\" \\\n\t\tLUA_CDIR\"?.lua;\"  LUA_CDIR\"?/init.lua;\" \\\n\t\t\"./?.lua;\" \"./?/init.lua\"\n#endif\n\n#if !defined(LUA_CPATH_DEFAULT)\n#define LUA_CPATH_DEFAULT \\\n\t\tLUA_CDIR\"?.so;\" LUA_CDIR\"loadall.so;\" \"./?.so\"\n#endif\n\n#endif\t\t\t/* } */\n\n\n/*\n@@ LUA_DIRSEP is the directory separator (for submodules).\n** CHANGE it if your machine does not use \"/\" as the directory separator\n** and is not Windows. (On Windows Lua automatically uses \"\\\".)\n*/\n#if !defined(LUA_DIRSEP)\n\n#if defined(_WIN32)\n#define LUA_DIRSEP\t\"\\\\\"\n#else\n#define LUA_DIRSEP\t\"/\"\n#endif\n\n#endif\n\n\n/*\n** LUA_IGMARK is a mark to ignore all after it when building the\n** module name (e.g., used to build the luaopen_ function name).\n** Typically, the suffix after the mark is the module version,\n** as in \"mod-v1.2.so\".\n*/\n#define LUA_IGMARK\t\t\"-\"\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Marks for exported symbols in the C code\n** ===================================================================\n*/\n\n/*\n@@ LUA_API is a mark for all core API functions.\n@@ LUALIB_API is a mark for all auxiliary library functions.\n@@ LUAMOD_API is a mark for all standard library opening functions.\n** CHANGE them if you need to define those functions in some special way.\n** For instance, if you want to create one Windows DLL with the core and\n** the libraries, you may want to use the following definition (define\n** LUA_BUILD_AS_DLL to get it).\n*/\n#if defined(LUA_BUILD_AS_DLL)\t/* { */\n\n#if defined(LUA_CORE) || defined(LUA_LIB)\t/* { */\n#define LUA_API __declspec(dllexport)\n#else\t\t\t\t\t\t/* }{ */\n#define LUA_API __declspec(dllimport)\n#endif\t\t\t\t\t\t/* } */\n\n#else\t\t\t\t/* }{ */\n\n#define LUA_API\t\textern\n\n#endif\t\t\t\t/* } */\n\n\n/*\n** More often than not the libs go together with the core.\n*/\n#define LUALIB_API\tLUA_API\n\n#if defined(__cplusplus)\n/* Lua uses the \"C name\" when calling open functions */\n#define LUAMOD_API\textern \"C\"\n#else\n#define LUAMOD_API\tLUA_API\n#endif\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Compatibility with previous versions\n** ===================================================================\n*/\n\n/*\n@@ LUA_COMPAT_GLOBAL avoids 'global' being a reserved word\n*/\n#define LUA_COMPAT_GLOBAL\n\n\n/*\n@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated\n** functions in the mathematical library.\n** (These functions were already officially removed in 5.3;\n** nevertheless they are still available here.)\n*/\n/* #define LUA_COMPAT_MATHLIB */\n\n\n/*\n@@ The following macros supply trivial compatibility for some\n** changes in the API. The macros themselves document how to\n** change your code to avoid using them.\n** (Once more, these macros were officially removed in 5.3, but they are\n** still available here.)\n*/\n#define lua_strlen(L,i)\t\tlua_rawlen(L, (i))\n\n#define lua_objlen(L,i)\t\tlua_rawlen(L, (i))\n\n#define lua_equal(L,idx1,idx2)\t\tlua_compare(L,(idx1),(idx2),LUA_OPEQ)\n#define lua_lessthan(L,idx1,idx2)\tlua_compare(L,(idx1),(idx2),LUA_OPLT)\n\n/* }================================================================== */\n\n\n\n/*\n** {==================================================================\n** Configuration for Numbers (low-level part).\n** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_*\n** satisfy your needs.\n** ===================================================================\n*/\n\n/*\n@@ LUAI_UACNUMBER is the result of a 'default argument promotion'\n@@ over a floating number.\n@@ l_floatatt(x) corrects float attribute 'x' to the proper float type\n** by prefixing it with one of FLT/DBL/LDBL.\n@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats.\n@@ LUA_NUMBER_FMT is the format for writing floats with the maximum\n** number of digits that respects tostring(tonumber(numeral)) == numeral.\n** (That would be floor(log10(2^n)), where n is the number of bits in\n** the float mantissa.)\n@@ LUA_NUMBER_FMT_N is the format for writing floats with the minimum\n** number of digits that ensures tonumber(tostring(number)) == number.\n** (That would be LUA_NUMBER_FMT+2.)\n@@ l_mathop allows the addition of an 'l' or 'f' to all math operations.\n@@ l_floor takes the floor of a float.\n@@ lua_str2number converts a decimal numeral to a number.\n*/\n\n\n/* The following definition is good for most cases here */\n\n#define l_floor(x)\t\t(l_mathop(floor)(x))\n\n\n/* now the variable definitions */\n\n#if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT\t\t/* { single float */\n\n#define LUA_NUMBER\tfloat\n\n#define l_floatatt(n)\t\t(FLT_##n)\n\n#define LUAI_UACNUMBER\tdouble\n\n#define LUA_NUMBER_FRMLEN\t\"\"\n#define LUA_NUMBER_FMT\t\t\"%.7g\"\n#define LUA_NUMBER_FMT_N\t\"%.9g\"\n\n#define l_mathop(op)\t\top##f\n\n#define lua_str2number(s,p)\tstrtof((s), (p))\n\n\n#elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE\t/* }{ long double */\n\n#define LUA_NUMBER\tlong double\n\n#define l_floatatt(n)\t\t(LDBL_##n)\n\n#define LUAI_UACNUMBER\tlong double\n\n#define LUA_NUMBER_FRMLEN\t\"L\"\n#define LUA_NUMBER_FMT\t\t\"%.19Lg\"\n#define LUA_NUMBER_FMT_N\t\"%.21Lg\"\n\n#define l_mathop(op)\t\top##l\n\n#define lua_str2number(s,p)\tstrtold((s), (p))\n\n#elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE\t/* }{ double */\n\n#define LUA_NUMBER\tdouble\n\n#define l_floatatt(n)\t\t(DBL_##n)\n\n#define LUAI_UACNUMBER\tdouble\n\n#define LUA_NUMBER_FRMLEN\t\"\"\n#define LUA_NUMBER_FMT\t\t\"%.15g\"\n#define LUA_NUMBER_FMT_N\t\"%.17g\"\n\n#define l_mathop(op)\t\top\n\n#define lua_str2number(s,p)\tstrtod((s), (p))\n\n#else\t\t\t\t\t\t/* }{ */\n\n#error \"numeric float type not defined\"\n\n#endif\t\t\t\t\t/* } */\n\n\n\n/*\n@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER.\n@@ LUAI_UACINT is the result of a 'default argument promotion'\n@@ over a LUA_INTEGER.\n@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers.\n@@ LUA_INTEGER_FMT is the format for writing integers.\n@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER.\n@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER.\n@@ LUA_MAXUNSIGNED is the maximum value for a LUA_UNSIGNED.\n@@ lua_integer2str converts an integer to a string.\n*/\n\n\n/* The following definitions are good for most cases here */\n\n#define LUA_INTEGER_FMT\t\t\"%\" LUA_INTEGER_FRMLEN \"d\"\n\n#define LUAI_UACINT\t\tLUA_INTEGER\n\n#define lua_integer2str(s,sz,n)  \\\n\tl_sprintf((s), sz, LUA_INTEGER_FMT, (LUAI_UACINT)(n))\n\n/*\n** use LUAI_UACINT here to avoid problems with promotions (which\n** can turn a comparison between unsigneds into a signed comparison)\n*/\n#define LUA_UNSIGNED\t\tunsigned LUAI_UACINT\n\n\n/* now the variable definitions */\n\n#if LUA_INT_TYPE == LUA_INT_INT\t\t/* { int */\n\n#define LUA_INTEGER\t\tint\n#define LUA_INTEGER_FRMLEN\t\"\"\n\n#define LUA_MAXINTEGER\t\tINT_MAX\n#define LUA_MININTEGER\t\tINT_MIN\n\n#define LUA_MAXUNSIGNED\t\tUINT_MAX\n\n#elif LUA_INT_TYPE == LUA_INT_LONG\t/* }{ long */\n\n#define LUA_INTEGER\t\tlong\n#define LUA_INTEGER_FRMLEN\t\"l\"\n\n#define LUA_MAXINTEGER\t\tLONG_MAX\n#define LUA_MININTEGER\t\tLONG_MIN\n\n#define LUA_MAXUNSIGNED\t\tULONG_MAX\n\n#elif LUA_INT_TYPE == LUA_INT_LONGLONG\t/* }{ long long */\n\n/* use presence of macro LLONG_MAX as proxy for C99 compliance */\n#if defined(LLONG_MAX)\t\t/* { */\n/* use ISO C99 stuff */\n\n#define LUA_INTEGER\t\tlong long\n#define LUA_INTEGER_FRMLEN\t\"ll\"\n\n#define LUA_MAXINTEGER\t\tLLONG_MAX\n#define LUA_MININTEGER\t\tLLONG_MIN\n\n#define LUA_MAXUNSIGNED\t\tULLONG_MAX\n\n#elif defined(LUA_USE_WINDOWS) /* }{ */\n/* in Windows, can use specific Windows types */\n\n#define LUA_INTEGER\t\t__int64\n#define LUA_INTEGER_FRMLEN\t\"I64\"\n\n#define LUA_MAXINTEGER\t\t_I64_MAX\n#define LUA_MININTEGER\t\t_I64_MIN\n\n#define LUA_MAXUNSIGNED\t\t_UI64_MAX\n\n#else\t\t\t\t/* }{ */\n\n#error \"Compiler does not support 'long long'. Use option '-DLUA_32BITS' \\\n  or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)\"\n\n#endif\t\t\t\t/* } */\n\n#else\t\t\t\t/* }{ */\n\n#error \"numeric integer type not defined\"\n\n#endif\t\t\t\t/* } */\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Dependencies with C99 and other C details\n** ===================================================================\n*/\n\n/*\n@@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89.\n** (All uses in Lua have only one format item.)\n*/\n#if !defined(LUA_USE_C89)\n#define l_sprintf(s,sz,f,i)\tsnprintf(s,sz,f,i)\n#else\n#define l_sprintf(s,sz,f,i)\t((void)(sz), sprintf(s,f,i))\n#endif\n\n\n/*\n@@ lua_strx2number converts a hexadecimal numeral to a number.\n** In C99, 'strtod' does that conversion. Otherwise, you can\n** leave 'lua_strx2number' undefined and Lua will provide its own\n** implementation.\n*/\n#if !defined(LUA_USE_C89)\n#define lua_strx2number(s,p)\t\tlua_str2number(s,p)\n#endif\n\n\n/*\n@@ lua_pointer2str converts a pointer to a readable string in a\n** non-specified way.\n*/\n#define lua_pointer2str(buff,sz,p)\tl_sprintf(buff,sz,\"%p\",p)\n\n\n/*\n@@ lua_number2strx converts a float to a hexadecimal numeral.\n** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that.\n** Otherwise, you can leave 'lua_number2strx' undefined and Lua will\n** provide its own implementation.\n*/\n#if !defined(LUA_USE_C89)\n#define lua_number2strx(L,b,sz,f,n)  \\\n\t((void)L, l_sprintf(b,sz,f,(LUAI_UACNUMBER)(n)))\n#endif\n\n\n/*\n** 'strtof' and 'opf' variants for math functions are not valid in\n** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the\n** availability of these variants. ('math.h' is already included in\n** all files that use these macros.)\n*/\n#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF))\n#undef l_mathop  /* variants not available */\n#undef lua_str2number\n#define l_mathop(op)\t\t(lua_Number)op  /* no variant */\n#define lua_str2number(s,p)\t((lua_Number)strtod((s), (p)))\n#endif\n\n\n/*\n@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation\n** functions.  It must be a numerical type; Lua will use 'intptr_t' if\n** available, otherwise it will use 'ptrdiff_t' (the nearest thing to\n** 'intptr_t' in C89)\n*/\n#define LUA_KCONTEXT\tptrdiff_t\n\n#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \\\n    __STDC_VERSION__ >= 199901L\n#include <stdint.h>\n#if defined(INTPTR_MAX)  /* even in C99 this type is optional */\n#undef LUA_KCONTEXT\n#define LUA_KCONTEXT\tintptr_t\n#endif\n#endif\n\n\n/*\n@@ lua_getlocaledecpoint gets the locale \"radix character\" (decimal point).\n** Change that if you do not want to use C locales. (Code using this\n** macro must include the header 'locale.h'.)\n*/\n#if !defined(lua_getlocaledecpoint)\n#define lua_getlocaledecpoint()\t\t(localeconv()->decimal_point[0])\n#endif\n\n\n/*\n** macros to improve jump prediction, used mostly for error handling\n** and debug facilities. (Some macros in the Lua API use these macros.\n** Define LUA_NOBUILTIN if you do not want '__builtin_expect' in your\n** code.)\n*/\n#if !defined(luai_likely)\n\n#if defined(__GNUC__) && !defined(LUA_NOBUILTIN)\n#define luai_likely(x)\t\t(__builtin_expect(((x) != 0), 1))\n#define luai_unlikely(x)\t(__builtin_expect(((x) != 0), 0))\n#else\n#define luai_likely(x)\t\t(x)\n#define luai_unlikely(x)\t(x)\n#endif\n\n#endif\n\n\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Language Variations\n** =====================================================================\n*/\n\n/*\n@@ LUA_NOCVTN2S/LUA_NOCVTS2N control how Lua performs some\n** coercions. Define LUA_NOCVTN2S to turn off automatic coercion from\n** numbers to strings. Define LUA_NOCVTS2N to turn off automatic\n** coercion from strings to numbers.\n*/\n/* #define LUA_NOCVTN2S */\n/* #define LUA_NOCVTS2N */\n\n\n/*\n@@ LUA_USE_APICHECK turns on several consistency checks on the C API.\n** Define it as a help when debugging C code.\n*/\n/* #define LUA_USE_APICHECK */\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Macros that affect the API and must be stable (that is, must be the\n** same when you compile Lua and when you compile code that links to\n** Lua).\n** =====================================================================\n*/\n\n/*\n@@ LUA_EXTRASPACE defines the size of a raw memory area associated with\n** a Lua state with very fast access.\n** CHANGE it if you need a different size.\n*/\n#define LUA_EXTRASPACE\t\t(sizeof(void *))\n\n\n/*\n@@ LUA_IDSIZE gives the maximum size for the description of the source\n** of a function in debug information.\n** CHANGE it if you want a different size.\n*/\n#define LUA_IDSIZE\t60\n\n\n/*\n@@ LUAL_BUFFERSIZE is the initial buffer size used by the lauxlib\n** buffer system.\n*/\n#define LUAL_BUFFERSIZE   ((int)(16 * sizeof(void*) * sizeof(lua_Number)))\n\n\n/*\n@@ LUAI_MAXALIGN defines fields that, when used in a union, ensure\n** maximum alignment for the other items in that union.\n*/\n#define LUAI_MAXALIGN  lua_Number n; double u; void *s; lua_Integer i; long l\n\n/* }================================================================== */\n\n\n\n\n\n/* =================================================================== */\n\n/*\n** Local configuration. You can use this space to add your redefinitions\n** without modifying the main part of the file.\n*/\n\n\n\n#endif\n\n"
  },
  {
    "path": "3rd/lua/lualib.h",
    "content": "/*\n** $Id: lualib.h $\n** Lua standard libraries\n** See Copyright Notice in lua.h\n*/\n\n\n#ifndef lualib_h\n#define lualib_h\n\n#include \"lua.h\"\n\n\n/* version suffix for environment variable names */\n#define LUA_VERSUFFIX          \"_\" LUA_VERSION_MAJOR \"_\" LUA_VERSION_MINOR\n\n#define LUA_GLIBK\t\t1\nLUAMOD_API int (luaopen_base) (lua_State *L);\n\n#define LUA_LOADLIBNAME\t\"package\"\n#define LUA_LOADLIBK\t(LUA_GLIBK << 1)\nLUAMOD_API int (luaopen_package) (lua_State *L);\n\n#define LUA_CACHELIB\nLUAMOD_API int (luaopen_cache) (lua_State *L);\nLUALIB_API void (luaL_initcodecache) (void);\n\n#define LUA_COLIBNAME\t\"coroutine\"\n#define LUA_COLIBK\t(LUA_LOADLIBK << 1)\nLUAMOD_API int (luaopen_coroutine) (lua_State *L);\n\n#define LUA_DBLIBNAME\t\"debug\"\n#define LUA_DBLIBK\t(LUA_COLIBK << 1)\nLUAMOD_API int (luaopen_debug) (lua_State *L);\n\n#define LUA_IOLIBNAME\t\"io\"\n#define LUA_IOLIBK\t(LUA_DBLIBK << 1)\nLUAMOD_API int (luaopen_io) (lua_State *L);\n\n#define LUA_MATHLIBNAME\t\"math\"\n#define LUA_MATHLIBK\t(LUA_IOLIBK << 1)\nLUAMOD_API int (luaopen_math) (lua_State *L);\n\n#define LUA_OSLIBNAME\t\"os\"\n#define LUA_OSLIBK\t(LUA_MATHLIBK << 1)\nLUAMOD_API int (luaopen_os) (lua_State *L);\n\n#define LUA_STRLIBNAME\t\"string\"\n#define LUA_STRLIBK\t(LUA_OSLIBK << 1)\nLUAMOD_API int (luaopen_string) (lua_State *L);\n\n#define LUA_TABLIBNAME\t\"table\"\n#define LUA_TABLIBK\t(LUA_STRLIBK << 1)\nLUAMOD_API int (luaopen_table) (lua_State *L);\n\n#define LUA_UTF8LIBNAME\t\"utf8\"\n#define LUA_UTF8LIBK\t(LUA_TABLIBK << 1)\nLUAMOD_API int (luaopen_utf8) (lua_State *L);\n\n\n/* open selected libraries */\nLUALIB_API void (luaL_openselectedlibs) (lua_State *L, int load, int preload);\n\n/* open all libraries */\n#define luaL_openlibs(L)\tluaL_openselectedlibs(L, ~0, 0)\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lundump.c",
    "content": "/*\n** $Id: lundump.c $\n** load precompiled Lua chunks\n** See Copyright Notice in lua.h\n*/\n\n#define lundump_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <limits.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lfunc.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"lundump.h\"\n#include \"lzio.h\"\n\n\n#if !defined(luai_verifycode)\n#define luai_verifycode(L,f)  /* empty */\n#endif\n\n\ntypedef struct {\n  lua_State *L;\n  ZIO *Z;\n  const char *name;\n  Table *h;  /* list for string reuse */\n  size_t offset;  /* current position relative to beginning of dump */\n  lua_Unsigned nstr;  /* number of strings in the list */\n  lu_byte fixed;  /* dump is fixed in memory */\n} LoadState;\n\n\nstatic l_noret error (LoadState *S, const char *why) {\n  luaO_pushfstring(S->L, \"%s: bad binary format (%s)\", S->name, why);\n  luaD_throw(S->L, LUA_ERRSYNTAX);\n}\n\n\n/*\n** All high-level loads go through loadVector; you can change it to\n** adapt to the endianness of the input\n*/\n#define loadVector(S,b,n)\tloadBlock(S,b,cast_sizet(n)*sizeof((b)[0]))\n\nstatic void loadBlock (LoadState *S, void *b, size_t size) {\n  if (luaZ_read(S->Z, b, size) != 0)\n    error(S, \"truncated chunk\");\n  S->offset += size;\n}\n\n\nstatic void loadAlign (LoadState *S, unsigned align) {\n  unsigned padding = align - cast_uint(S->offset % align);\n  if (padding < align) {  /* (padding == align) means no padding */\n    lua_Integer paddingContent;\n    loadBlock(S, &paddingContent, padding);\n    lua_assert(S->offset % align == 0);\n  }\n}\n\n\n#define getaddr(S,n,t)\tcast(t *, getaddr_(S,cast_sizet(n) * sizeof(t)))\n\nstatic const void *getaddr_ (LoadState *S, size_t size) {\n  const void *block = luaZ_getaddr(S->Z, size);\n  S->offset += size;\n  if (block == NULL)\n    error(S, \"truncated fixed buffer\");\n  return block;\n}\n\n\n#define loadVar(S,x)\t\tloadVector(S,&x,1)\n\n\nstatic lu_byte loadByte (LoadState *S) {\n  int b = zgetc(S->Z);\n  if (b == EOZ)\n    error(S, \"truncated chunk\");\n  S->offset++;\n  return cast_byte(b);\n}\n\n\nstatic lua_Unsigned loadVarint (LoadState *S, lua_Unsigned limit) {\n  lua_Unsigned x = 0;\n  int b;\n  limit >>= 7;\n  do {\n    b = loadByte(S);\n    if (x > limit)\n      error(S, \"integer overflow\");\n    x = (x << 7) | (b & 0x7f);\n  } while ((b & 0x80) != 0);\n  return x;\n}\n\n\nstatic size_t loadSize (LoadState *S) {\n  return cast_sizet(loadVarint(S, MAX_SIZE));\n}\n\n\nstatic int loadInt (LoadState *S) {\n  return cast_int(loadVarint(S, cast_sizet(INT_MAX)));\n}\n\n\n\nstatic lua_Number loadNumber (LoadState *S) {\n  lua_Number x;\n  loadVar(S, x);\n  return x;\n}\n\n\nstatic lua_Integer loadInteger (LoadState *S) {\n  lua_Unsigned cx = loadVarint(S, LUA_MAXUNSIGNED);\n  /* decode unsigned to signed */\n  if ((cx & 1) != 0)\n    return l_castU2S(~(cx >> 1));\n  else\n    return l_castU2S(cx >> 1);\n}\n\n\n/*\n** Load a nullable string into slot 'sl' from prototype 'p'. The\n** assignment to the slot and the barrier must be performed before any\n** possible GC activity, to anchor the string. (Both 'loadVector' and\n** 'luaH_setint' can call the GC.)\n*/\nstatic void loadString (LoadState *S, Proto *p, TString **sl) {\n  lua_State *L = S->L;\n  TString *ts;\n  TValue sv;\n  size_t size = loadSize(S);\n  if (size == 0) {  /* previously saved string? */\n    lua_Unsigned idx = loadVarint(S, LUA_MAXUNSIGNED);  /* get its index */\n    TValue stv;\n    if (idx == 0) {  /* no string? */\n      lua_assert(*sl == NULL);  /* must be prefilled */\n      return;\n    }\n    if (novariant(luaH_getint(S->h, l_castU2S(idx), &stv)) != LUA_TSTRING)\n      error(S, \"invalid string index\");\n    *sl = ts = tsvalue(&stv);  /* get its value */\n    luaC_objbarrier(L, p, ts);\n    return;  /* do not save it again */\n  }\n  else if ((size -= 1) <= LUAI_MAXSHORTLEN) {  /* short string? */\n    char buff[LUAI_MAXSHORTLEN + 1];  /* extra space for '\\0' */\n    loadVector(S, buff, size + 1);  /* load string into buffer */\n    *sl = ts = luaS_newlstr(L, buff, size);  /* create string */\n    luaC_objbarrier(L, p, ts);\n  }\n  else if (S->fixed) {  /* for a fixed buffer, use a fixed string */\n    const char *s = getaddr(S, size + 1, char);  /* get content address */\n    *sl = ts = luaS_newextlstr(L, s, size, NULL, NULL);\n    luaC_objbarrier(L, p, ts);\n  }\n  else {  /* create internal copy */\n    *sl = ts = luaS_createlngstrobj(L, size);  /* create string */\n    luaC_objbarrier(L, p, ts);\n    loadVector(S, getlngstr(ts), size + 1);  /* load directly in final place */\n  }\n  /* add string to list of saved strings */\n  S->nstr++;\n  setsvalue(L, &sv, ts);\n  luaH_setint(L, S->h, l_castU2S(S->nstr), &sv);\n  luaC_objbarrierback(L, obj2gco(S->h), ts);\n}\n\n\nstatic void loadCode (LoadState *S, Proto *f) {\n  int n = loadInt(S);\n  loadAlign(S, sizeof(f->code[0]));\n  if (S->fixed) {\n    f->code = getaddr(S, n, Instruction);\n    f->sizecode = n;\n  }\n  else {\n    f->code = luaM_newvectorchecked(S->L, n, Instruction);\n    f->sizecode = n;\n    loadVector(S, f->code, n);\n  }\n}\n\n\nstatic void loadFunction(LoadState *S, Proto *f);\n\n\nstatic void loadConstants (LoadState *S, Proto *f) {\n  int i;\n  int n = loadInt(S);\n  f->k = luaM_newvectorchecked(S->L, n, TValue);\n  f->sizek = n;\n  for (i = 0; i < n; i++)\n    setnilvalue(&f->k[i]);\n  for (i = 0; i < n; i++) {\n    TValue *o = &f->k[i];\n    int t = loadByte(S);\n    switch (t) {\n      case LUA_VNIL:\n        setnilvalue(o);\n        break;\n      case LUA_VFALSE:\n        setbfvalue(o);\n        break;\n      case LUA_VTRUE:\n        setbtvalue(o);\n        break;\n      case LUA_VNUMFLT:\n        setfltvalue(o, loadNumber(S));\n        break;\n      case LUA_VNUMINT:\n        setivalue(o, loadInteger(S));\n        break;\n      case LUA_VSHRSTR:\n      case LUA_VLNGSTR: {\n        lua_assert(f->source == NULL);\n        loadString(S, f, &f->source);  /* use 'source' to anchor string */\n        if (f->source == NULL)\n          error(S, \"bad format for constant string\");\n        setsvalue2n(S->L, o, f->source);  /* save it in the right place */\n        f->source = NULL;\n        break;\n      }\n      default: error(S, \"invalid constant\");\n    }\n  }\n}\n\n\nstatic void loadProtos (LoadState *S, Proto *f) {\n  int i;\n  int n = loadInt(S);\n  f->p = luaM_newvectorchecked(S->L, n, Proto *);\n  f->sizep = n;\n  for (i = 0; i < n; i++)\n    f->p[i] = NULL;\n  for (i = 0; i < n; i++) {\n    f->p[i] = luaF_newproto(S->L);\n    luaC_objbarrier(S->L, f, f->p[i]);\n    loadFunction(S, f->p[i]);\n  }\n}\n\n\n/*\n** Load the upvalues for a function. The names must be filled first,\n** because the filling of the other fields can raise read errors and\n** the creation of the error message can call an emergency collection;\n** in that case all prototypes must be consistent for the GC.\n*/\nstatic void loadUpvalues (LoadState *S, Proto *f) {\n  int i;\n  int n = loadInt(S);\n  f->upvalues = luaM_newvectorchecked(S->L, n, Upvaldesc);\n  f->sizeupvalues = n;\n  for (i = 0; i < n; i++)  /* make array valid for GC */\n    f->upvalues[i].name = NULL;\n  for (i = 0; i < n; i++) {  /* following calls can raise errors */\n    f->upvalues[i].instack = loadByte(S);\n    f->upvalues[i].idx = loadByte(S);\n    f->upvalues[i].kind = loadByte(S);\n  }\n}\n\n\nstatic void loadDebug (LoadState *S, Proto *f) {\n  int i;\n  int n = loadInt(S);\n  if (S->fixed) {\n    f->lineinfo = getaddr(S, n, ls_byte);\n    f->sizelineinfo = n;\n  }\n  else {\n    f->lineinfo = luaM_newvectorchecked(S->L, n, ls_byte);\n    f->sizelineinfo = n;\n    loadVector(S, f->lineinfo, n);\n  }\n  n = loadInt(S);\n  if (n > 0) {\n    loadAlign(S, sizeof(int));\n    if (S->fixed) {\n      f->abslineinfo = getaddr(S, n, AbsLineInfo);\n      f->sizeabslineinfo = n;\n    }\n    else {\n      f->abslineinfo = luaM_newvectorchecked(S->L, n, AbsLineInfo);\n      f->sizeabslineinfo = n;\n      loadVector(S, f->abslineinfo, n);\n    }\n  }\n  n = loadInt(S);\n  f->locvars = luaM_newvectorchecked(S->L, n, LocVar);\n  f->sizelocvars = n;\n  for (i = 0; i < n; i++)\n    f->locvars[i].varname = NULL;\n  for (i = 0; i < n; i++) {\n    loadString(S, f, &f->locvars[i].varname);\n    f->locvars[i].startpc = loadInt(S);\n    f->locvars[i].endpc = loadInt(S);\n  }\n  n = loadInt(S);\n  if (n != 0)  /* does it have debug information? */\n    n = f->sizeupvalues;  /* must be this many */\n  for (i = 0; i < n; i++)\n    loadString(S, f, &f->upvalues[i].name);\n}\n\n\nstatic void loadFunction (LoadState *S, Proto *f) {\n  f->linedefined = loadInt(S);\n  f->lastlinedefined = loadInt(S);\n  f->numparams = loadByte(S);\n  /* get only the meaningful flags */\n  f->flag = cast_byte(loadByte(S) & ~PF_FIXED);\n  if (S->fixed)\n    f->flag |= PF_FIXED;  /* signal that code is fixed */\n  f->maxstacksize = loadByte(S);\n  loadCode(S, f);\n  loadConstants(S, f);\n  loadUpvalues(S, f);\n  loadProtos(S, f);\n  loadString(S, f, &f->source);\n  loadDebug(S, f);\n}\n\n\nstatic void checkliteral (LoadState *S, const char *s, const char *msg) {\n  char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */\n  size_t len = strlen(s);\n  loadVector(S, buff, len);\n  if (memcmp(s, buff, len) != 0)\n    error(S, msg);\n}\n\n\nstatic l_noret numerror (LoadState *S, const char *what, const char *tname) {\n  const char *msg = luaO_pushfstring(S->L, \"%s %s mismatch\", tname, what);\n  error(S, msg);\n}\n\n\nstatic void checknumsize (LoadState *S, int size, const char *tname) {\n  if (size != loadByte(S))\n    numerror(S, \"size\", tname);\n}\n\n\nstatic void checknumformat (LoadState *S, int eq, const char *tname) {\n  if (!eq)\n    numerror(S, \"format\", tname);\n}\n\n\n#define checknum(S,tvar,value,tname)  \\\n  { tvar i; checknumsize(S, sizeof(i), tname); \\\n    loadVar(S, i); \\\n    checknumformat(S, i == value, tname); }\n\n\nstatic void checkHeader (LoadState *S) {\n  /* skip 1st char (already read and checked) */\n  checkliteral(S, &LUA_SIGNATURE[1], \"not a binary chunk\");\n  if (loadByte(S) != LUAC_VERSION)\n    error(S, \"version mismatch\");\n  if (loadByte(S) != LUAC_FORMAT)\n    error(S, \"format mismatch\");\n  checkliteral(S, LUAC_DATA, \"corrupted chunk\");\n  checknum(S, int, LUAC_INT, \"int\");\n  checknum(S, Instruction, LUAC_INST, \"instruction\");\n  checknum(S, lua_Integer, LUAC_INT, \"Lua integer\");\n  checknum(S, lua_Number, LUAC_NUM, \"Lua number\");\n}\n\n\n/*\n** Load precompiled chunk.\n*/\nLClosure *luaU_undump (lua_State *L, ZIO *Z, const char *name, int fixed) {\n  LoadState S;\n  LClosure *cl;\n  if (*name == '@' || *name == '=')\n    name = name + 1;\n  else if (*name == LUA_SIGNATURE[0])\n    name = \"binary string\";\n  S.name = name;\n  S.L = L;\n  S.Z = Z;\n  S.fixed = cast_byte(fixed);\n  S.offset = 1;  /* fist byte was already read */\n  checkHeader(&S);\n  cl = luaF_newLclosure(L, loadByte(&S));\n  setclLvalue2s(L, L->top.p, cl);\n  luaD_inctop(L);\n  S.h = luaH_new(L);  /* create list of saved strings */\n  S.nstr = 0;\n  sethvalue2s(L, L->top.p, S.h);  /* anchor it */\n  luaD_inctop(L);\n  cl->p = luaF_newproto(L);\n  luaC_objbarrier(L, cl, cl->p);\n  loadFunction(&S, cl->p);\n  if (cl->nupvalues != cl->p->sizeupvalues)\n    error(&S, \"corrupted chunk\");\n  luai_verifycode(L, cl->p);\n  L->top.p--;  /* pop table */\n  return cl;\n}\n\n"
  },
  {
    "path": "3rd/lua/lundump.h",
    "content": "/*\n** $Id: lundump.h $\n** load precompiled Lua chunks\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lundump_h\n#define lundump_h\n\n#include <limits.h>\n\n#include \"llimits.h\"\n#include \"lobject.h\"\n#include \"lzio.h\"\n\n\n/* data to catch conversion errors */\n#define LUAC_DATA\t\"\\x19\\x93\\r\\n\\x1a\\n\"\n\n#define LUAC_INT\t-0x5678\n#define LUAC_INST\t0x12345678\n#define LUAC_NUM\tcast_num(-370.5)\n\n/*\n** Encode major-minor version in one byte, one nibble for each\n*/\n#define LUAC_VERSION\t(LUA_VERSION_MAJOR_N*16+LUA_VERSION_MINOR_N)\n\n#define LUAC_FORMAT\t0\t/* this is the official format */\n\n\n/* load one chunk; from lundump.c */\nLUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, const char* name,\n                                               int fixed);\n\n/* dump one chunk; from ldump.c */\nLUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w,\n                         void* data, int strip);\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lutf8lib.c",
    "content": "/*\n** $Id: lutf8lib.c $\n** Standard library for UTF-8 manipulation\n** See Copyright Notice in lua.h\n*/\n\n#define lutf8lib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include <limits.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#include \"llimits.h\"\n\n\n#define MAXUNICODE\t0x10FFFFu\n\n#define MAXUTF\t\t0x7FFFFFFFu\n\n\n#define MSGInvalid\t\"invalid UTF-8 code\"\n\n\n#define iscont(c)\t(((c) & 0xC0) == 0x80)\n#define iscontp(p)\tiscont(*(p))\n\n\n/* from strlib */\n/* translate a relative string position: negative means back from end */\nstatic lua_Integer u_posrelat (lua_Integer pos, size_t len) {\n  if (pos >= 0) return pos;\n  else if (0u - (size_t)pos > len) return 0;\n  else return (lua_Integer)len + pos + 1;\n}\n\n\n/*\n** Decode one UTF-8 sequence, returning NULL if byte sequence is\n** invalid.  The array 'limits' stores the minimum value for each\n** sequence length, to check for overlong representations. Its first\n** entry forces an error for non-ASCII bytes with no continuation\n** bytes (count == 0).\n*/\nstatic const char *utf8_decode (const char *s, l_uint32 *val, int strict) {\n  static const l_uint32 limits[] =\n        {~(l_uint32)0, 0x80, 0x800, 0x10000u, 0x200000u, 0x4000000u};\n  unsigned int c = (unsigned char)s[0];\n  l_uint32 res = 0;  /* final result */\n  if (c < 0x80)  /* ASCII? */\n    res = c;\n  else {\n    int count = 0;  /* to count number of continuation bytes */\n    for (; c & 0x40; c <<= 1) {  /* while it needs continuation bytes... */\n      unsigned int cc = (unsigned char)s[++count];  /* read next byte */\n      if (!iscont(cc))  /* not a continuation byte? */\n        return NULL;  /* invalid byte sequence */\n      res = (res << 6) | (cc & 0x3F);  /* add lower 6 bits from cont. byte */\n    }\n    res |= ((l_uint32)(c & 0x7F) << (count * 5));  /* add first byte */\n    if (count > 5 || res > MAXUTF || res < limits[count])\n      return NULL;  /* invalid byte sequence */\n    s += count;  /* skip continuation bytes read */\n  }\n  if (strict) {\n    /* check for invalid code points; too large or surrogates */\n    if (res > MAXUNICODE || (0xD800u <= res && res <= 0xDFFFu))\n      return NULL;\n  }\n  if (val) *val = res;\n  return s + 1;  /* +1 to include first byte */\n}\n\n\n/*\n** utf8len(s [, i [, j [, lax]]]) --> number of characters that\n** start in the range [i,j], or nil + current position if 's' is not\n** well formed in that interval\n*/\nstatic int utflen (lua_State *L) {\n  lua_Integer n = 0;  /* counter for the number of characters */\n  size_t len;  /* string length in bytes */\n  const char *s = luaL_checklstring(L, 1, &len);\n  lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);\n  lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len);\n  int lax = lua_toboolean(L, 4);\n  luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,\n                   \"initial position out of bounds\");\n  luaL_argcheck(L, --posj < (lua_Integer)len, 3,\n                   \"final position out of bounds\");\n  while (posi <= posj) {\n    const char *s1 = utf8_decode(s + posi, NULL, !lax);\n    if (s1 == NULL) {  /* conversion error? */\n      luaL_pushfail(L);  /* return fail ... */\n      lua_pushinteger(L, posi + 1);  /* ... and current position */\n      return 2;\n    }\n    posi = ct_diff2S(s1 - s);\n    n++;\n  }\n  lua_pushinteger(L, n);\n  return 1;\n}\n\n\n/*\n** codepoint(s, [i, [j [, lax]]]) -> returns codepoints for all\n** characters that start in the range [i,j]\n*/\nstatic int codepoint (lua_State *L) {\n  size_t len;\n  const char *s = luaL_checklstring(L, 1, &len);\n  lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);\n  lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len);\n  int lax = lua_toboolean(L, 4);\n  int n;\n  const char *se;\n  luaL_argcheck(L, posi >= 1, 2, \"out of bounds\");\n  luaL_argcheck(L, pose <= (lua_Integer)len, 3, \"out of bounds\");\n  if (posi > pose) return 0;  /* empty interval; return no values */\n  if (pose - posi >= INT_MAX)  /* (lua_Integer -> int) overflow? */\n    return luaL_error(L, \"string slice too long\");\n  n = (int)(pose -  posi) + 1;  /* upper bound for number of returns */\n  luaL_checkstack(L, n, \"string slice too long\");\n  n = 0;  /* count the number of returns */\n  se = s + pose;  /* string end */\n  for (s += posi - 1; s < se;) {\n    l_uint32 code;\n    s = utf8_decode(s, &code, !lax);\n    if (s == NULL)\n      return luaL_error(L, MSGInvalid);\n    lua_pushinteger(L, l_castU2S(code));\n    n++;\n  }\n  return n;\n}\n\n\nstatic void pushutfchar (lua_State *L, int arg) {\n  lua_Unsigned code = (lua_Unsigned)luaL_checkinteger(L, arg);\n  luaL_argcheck(L, code <= MAXUTF, arg, \"value out of range\");\n  lua_pushfstring(L, \"%U\", (long)code);\n}\n\n\n/*\n** utfchar(n1, n2, ...)  -> char(n1)..char(n2)...\n*/\nstatic int utfchar (lua_State *L) {\n  int n = lua_gettop(L);  /* number of arguments */\n  if (n == 1)  /* optimize common case of single char */\n    pushutfchar(L, 1);\n  else {\n    int i;\n    luaL_Buffer b;\n    luaL_buffinit(L, &b);\n    for (i = 1; i <= n; i++) {\n      pushutfchar(L, i);\n      luaL_addvalue(&b);\n    }\n    luaL_pushresult(&b);\n  }\n  return 1;\n}\n\n\n/*\n** offset(s, n, [i])  -> indices where n-th character counting from\n**   position 'i' starts and ends; 0 means character at 'i'.\n*/\nstatic int byteoffset (lua_State *L) {\n  size_t len;\n  const char *s = luaL_checklstring(L, 1, &len);\n  lua_Integer n  = luaL_checkinteger(L, 2);\n  lua_Integer posi = (n >= 0) ? 1 : cast_st2S(len) + 1;\n  posi = u_posrelat(luaL_optinteger(L, 3, posi), len);\n  luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3,\n                   \"position out of bounds\");\n  if (n == 0) {\n    /* find beginning of current byte sequence */\n    while (posi > 0 && iscontp(s + posi)) posi--;\n  }\n  else {\n    if (iscontp(s + posi))\n      return luaL_error(L, \"initial position is a continuation byte\");\n    if (n < 0) {\n      while (n < 0 && posi > 0) {  /* move back */\n        do {  /* find beginning of previous character */\n          posi--;\n        } while (posi > 0 && iscontp(s + posi));\n        n++;\n      }\n    }\n    else {\n      n--;  /* do not move for 1st character */\n      while (n > 0 && posi < (lua_Integer)len) {\n        do {  /* find beginning of next character */\n          posi++;\n        } while (iscontp(s + posi));  /* (cannot pass final '\\0') */\n        n--;\n      }\n    }\n  }\n  if (n != 0) {  /* did not find given character? */\n    luaL_pushfail(L);\n    return 1;\n  }\n  lua_pushinteger(L, posi + 1);  /* initial position */\n  if ((s[posi] & 0x80) != 0) {  /* multi-byte character? */\n    if (iscont(s[posi]))\n      return luaL_error(L, \"initial position is a continuation byte\");\n    while (iscontp(s + posi + 1))\n      posi++;  /* skip to last continuation byte */\n  }\n  /* else one-byte character: final position is the initial one */\n  lua_pushinteger(L, posi + 1);  /* 'posi' now is the final position */\n  return 2;\n}\n\n\nstatic int iter_aux (lua_State *L, int strict) {\n  size_t len;\n  const char *s = luaL_checklstring(L, 1, &len);\n  lua_Unsigned n = (lua_Unsigned)lua_tointeger(L, 2);\n  if (n < len) {\n    while (iscontp(s + n)) n++;  /* go to next character */\n  }\n  if (n >= len)  /* (also handles original 'n' being negative) */\n    return 0;  /* no more codepoints */\n  else {\n    l_uint32 code;\n    const char *next = utf8_decode(s + n, &code, strict);\n    if (next == NULL || iscontp(next))\n      return luaL_error(L, MSGInvalid);\n    lua_pushinteger(L, l_castU2S(n + 1));\n    lua_pushinteger(L, l_castU2S(code));\n    return 2;\n  }\n}\n\n\nstatic int iter_auxstrict (lua_State *L) {\n  return iter_aux(L, 1);\n}\n\nstatic int iter_auxlax (lua_State *L) {\n  return iter_aux(L, 0);\n}\n\n\nstatic int iter_codes (lua_State *L) {\n  int lax = lua_toboolean(L, 2);\n  const char *s = luaL_checkstring(L, 1);\n  luaL_argcheck(L, !iscontp(s), 1, MSGInvalid);\n  lua_pushcfunction(L, lax ? iter_auxlax : iter_auxstrict);\n  lua_pushvalue(L, 1);\n  lua_pushinteger(L, 0);\n  return 3;\n}\n\n\n/* pattern to match a single UTF-8 character */\n#define UTF8PATT\t\"[\\0-\\x7F\\xC2-\\xFD][\\x80-\\xBF]*\"\n\n\nstatic const luaL_Reg funcs[] = {\n  {\"offset\", byteoffset},\n  {\"codepoint\", codepoint},\n  {\"char\", utfchar},\n  {\"len\", utflen},\n  {\"codes\", iter_codes},\n  /* placeholders */\n  {\"charpattern\", NULL},\n  {NULL, NULL}\n};\n\n\nLUAMOD_API int luaopen_utf8 (lua_State *L) {\n  luaL_newlib(L, funcs);\n  lua_pushlstring(L, UTF8PATT, sizeof(UTF8PATT)/sizeof(char) - 1);\n  lua_setfield(L, -2, \"charpattern\");\n  return 1;\n}\n\n"
  },
  {
    "path": "3rd/lua/lvm.c",
    "content": "/*\n** $Id: lvm.c $\n** Lua virtual machine\n** See Copyright Notice in lua.h\n*/\n\n#define lvm_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n#include <float.h>\n#include <limits.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lapi.h\"\n#include \"ldebug.h\"\n#include \"ldo.h\"\n#include \"lfunc.h\"\n#include \"lgc.h\"\n#include \"lobject.h\"\n#include \"lopcodes.h\"\n#include \"lstate.h\"\n#include \"lstring.h\"\n#include \"ltable.h\"\n#include \"ltm.h\"\n#include \"lvm.h\"\n\n\n/*\n** By default, use jump tables in the main interpreter loop on gcc\n** and compatible compilers.\n*/\n#if !defined(LUA_USE_JUMPTABLE)\n#if defined(__GNUC__)\n#define LUA_USE_JUMPTABLE\t1\n#else\n#define LUA_USE_JUMPTABLE\t0\n#endif\n#endif\n\n\n\n/* limit for table tag-method chains (to avoid infinite loops) */\n#define MAXTAGLOOP\t2000\n\n\n/*\n** 'l_intfitsf' checks whether a given integer is in the range that\n** can be converted to a float without rounding. Used in comparisons.\n*/\n\n/* number of bits in the mantissa of a float */\n#define NBM\t\t(l_floatatt(MANT_DIG))\n\n/*\n** Check whether some integers may not fit in a float, testing whether\n** (maxinteger >> NBM) > 0. (That implies (1 << NBM) <= maxinteger.)\n** (The shifts are done in parts, to avoid shifting by more than the size\n** of an integer. In a worst case, NBM == 113 for long double and\n** sizeof(long) == 32.)\n*/\n#if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \\\n\t>> (NBM - (3 * (NBM / 4))))  >  0\n\n/* limit for integers that fit in a float */\n#define MAXINTFITSF\t((lua_Unsigned)1 << NBM)\n\n/* check whether 'i' is in the interval [-MAXINTFITSF, MAXINTFITSF] */\n#define l_intfitsf(i)\t((MAXINTFITSF + l_castS2U(i)) <= (2 * MAXINTFITSF))\n\n#else  /* all integers fit in a float precisely */\n\n#define l_intfitsf(i)\t1\n\n#endif\n\n\n/*\n** Try to convert a value from string to a number value.\n** If the value is not a string or is a string not representing\n** a valid numeral (or if coercions from strings to numbers\n** are disabled via macro 'cvt2num'), do not modify 'result'\n** and return 0.\n*/\nstatic int l_strton (const TValue *obj, TValue *result) {\n  lua_assert(obj != result);\n  if (!cvt2num(obj))  /* is object not a string? */\n    return 0;\n  else {\n    TString *st = tsvalue(obj);\n    size_t stlen;\n    const char *s = getlstr(st, stlen);\n    return (luaO_str2num(s, result) == stlen + 1);\n  }\n}\n\n\n/*\n** Try to convert a value to a float. The float case is already handled\n** by the macro 'tonumber'.\n*/\nint luaV_tonumber_ (const TValue *obj, lua_Number *n) {\n  TValue v;\n  if (ttisinteger(obj)) {\n    *n = cast_num(ivalue(obj));\n    return 1;\n  }\n  else if (l_strton(obj, &v)) {  /* string coercible to number? */\n    *n = nvalue(&v);  /* convert result of 'luaO_str2num' to a float */\n    return 1;\n  }\n  else\n    return 0;  /* conversion failed */\n}\n\n\n/*\n** try to convert a float to an integer, rounding according to 'mode'.\n*/\nint luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode) {\n  lua_Number f = l_floor(n);\n  if (n != f) {  /* not an integral value? */\n    if (mode == F2Ieq) return 0;  /* fails if mode demands integral value */\n    else if (mode == F2Iceil)  /* needs ceiling? */\n      f += 1;  /* convert floor to ceiling (remember: n != f) */\n  }\n  return lua_numbertointeger(f, p);\n}\n\n\n/*\n** try to convert a value to an integer, rounding according to 'mode',\n** without string coercion.\n** (\"Fast track\" handled by macro 'tointegerns'.)\n*/\nint luaV_tointegerns (const TValue *obj, lua_Integer *p, F2Imod mode) {\n  if (ttisfloat(obj))\n    return luaV_flttointeger(fltvalue(obj), p, mode);\n  else if (ttisinteger(obj)) {\n    *p = ivalue(obj);\n    return 1;\n  }\n  else\n    return 0;\n}\n\n\n/*\n** try to convert a value to an integer.\n*/\nint luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode) {\n  TValue v;\n  if (l_strton(obj, &v))  /* does 'obj' point to a numerical string? */\n    obj = &v;  /* change it to point to its corresponding number */\n  return luaV_tointegerns(obj, p, mode);\n}\n\n\n/*\n** Try to convert a 'for' limit to an integer, preserving the semantics\n** of the loop. Return true if the loop must not run; otherwise, '*p'\n** gets the integer limit.\n** (The following explanation assumes a positive step; it is valid for\n** negative steps mutatis mutandis.)\n** If the limit is an integer or can be converted to an integer,\n** rounding down, that is the limit.\n** Otherwise, check whether the limit can be converted to a float. If\n** the float is too large, clip it to LUA_MAXINTEGER.  If the float\n** is too negative, the loop should not run, because any initial\n** integer value is greater than such limit; so, the function returns\n** true to signal that. (For this latter case, no integer limit would be\n** correct; even a limit of LUA_MININTEGER would run the loop once for\n** an initial value equal to LUA_MININTEGER.)\n*/\nstatic int forlimit (lua_State *L, lua_Integer init, const TValue *lim,\n                                   lua_Integer *p, lua_Integer step) {\n  if (!luaV_tointeger(lim, p, (step < 0 ? F2Iceil : F2Ifloor))) {\n    /* not coercible to in integer */\n    lua_Number flim;  /* try to convert to float */\n    if (!tonumber(lim, &flim)) /* cannot convert to float? */\n      luaG_forerror(L, lim, \"limit\");\n    /* else 'flim' is a float out of integer bounds */\n    if (luai_numlt(0, flim)) {  /* if it is positive, it is too large */\n      if (step < 0) return 1;  /* initial value must be less than it */\n      *p = LUA_MAXINTEGER;  /* truncate */\n    }\n    else {  /* it is less than min integer */\n      if (step > 0) return 1;  /* initial value must be greater than it */\n      *p = LUA_MININTEGER;  /* truncate */\n    }\n  }\n  return (step > 0 ? init > *p : init < *p);  /* not to run? */\n}\n\n\n/*\n** Prepare a numerical for loop (opcode OP_FORPREP).\n** Before execution, stack is as follows:\n**   ra     : initial value\n**   ra + 1 : limit\n**   ra + 2 : step\n** Return true to skip the loop. Otherwise,\n** after preparation, stack will be as follows:\n**   ra     : loop counter (integer loops) or limit (float loops)\n**   ra + 1 : step\n**   ra + 2 : control variable\n*/\nstatic int forprep (lua_State *L, StkId ra) {\n  TValue *pinit = s2v(ra);\n  TValue *plimit = s2v(ra + 1);\n  TValue *pstep = s2v(ra + 2);\n  if (ttisinteger(pinit) && ttisinteger(pstep)) { /* integer loop? */\n    lua_Integer init = ivalue(pinit);\n    lua_Integer step = ivalue(pstep);\n    lua_Integer limit;\n    if (step == 0)\n      luaG_runerror(L, \"'for' step is zero\");\n    if (forlimit(L, init, plimit, &limit, step))\n      return 1;  /* skip the loop */\n    else {  /* prepare loop counter */\n      lua_Unsigned count;\n      if (step > 0) {  /* ascending loop? */\n        count = l_castS2U(limit) - l_castS2U(init);\n        if (step != 1)  /* avoid division in the too common case */\n          count /= l_castS2U(step);\n      }\n      else {  /* step < 0; descending loop */\n        count = l_castS2U(init) - l_castS2U(limit);\n        /* 'step+1' avoids negating 'mininteger' */\n        count /= l_castS2U(-(step + 1)) + 1u;\n      }\n      /* use 'chgivalue' for places that for sure had integers */\n      chgivalue(s2v(ra), l_castU2S(count));  /* change init to count */\n      setivalue(s2v(ra + 1), step);  /* change limit to step */\n      chgivalue(s2v(ra + 2), init);  /* change step to init */\n    }\n  }\n  else {  /* try making all values floats */\n    lua_Number init; lua_Number limit; lua_Number step;\n    if (l_unlikely(!tonumber(plimit, &limit)))\n      luaG_forerror(L, plimit, \"limit\");\n    if (l_unlikely(!tonumber(pstep, &step)))\n      luaG_forerror(L, pstep, \"step\");\n    if (l_unlikely(!tonumber(pinit, &init)))\n      luaG_forerror(L, pinit, \"initial value\");\n    if (step == 0)\n      luaG_runerror(L, \"'for' step is zero\");\n    if (luai_numlt(0, step) ? luai_numlt(limit, init)\n                            : luai_numlt(init, limit))\n      return 1;  /* skip the loop */\n    else {\n      /* make sure all values are floats */\n      setfltvalue(s2v(ra), limit);\n      setfltvalue(s2v(ra + 1), step);\n      setfltvalue(s2v(ra + 2), init);  /* control variable */\n    }\n  }\n  return 0;\n}\n\n\n/*\n** Execute a step of a float numerical for loop, returning\n** true iff the loop must continue. (The integer case is\n** written online with opcode OP_FORLOOP, for performance.)\n*/\nstatic int floatforloop (StkId ra) {\n  lua_Number step = fltvalue(s2v(ra + 1));\n  lua_Number limit = fltvalue(s2v(ra));\n  lua_Number idx = fltvalue(s2v(ra + 2));  /* control variable */\n  idx = luai_numadd(L, idx, step);  /* increment index */\n  if (luai_numlt(0, step) ? luai_numle(idx, limit)\n                          : luai_numle(limit, idx)) {\n    chgfltvalue(s2v(ra + 2), idx);  /* update control variable */\n    return 1;  /* jump back */\n  }\n  else\n    return 0;  /* finish the loop */\n}\n\n\n/*\n** Finish the table access 'val = t[key]' and return the tag of the result.\n*/\nlu_byte luaV_finishget (lua_State *L, const TValue *t, TValue *key,\n                                      StkId val, lu_byte tag) {\n  int loop;  /* counter to avoid infinite loops */\n  const TValue *tm;  /* metamethod */\n  for (loop = 0; loop < MAXTAGLOOP; loop++) {\n    if (tag == LUA_VNOTABLE) {  /* 't' is not a table? */\n      lua_assert(!ttistable(t));\n      tm = luaT_gettmbyobj(L, t, TM_INDEX);\n      if (l_unlikely(notm(tm)))\n        luaG_typeerror(L, t, \"index\");  /* no metamethod */\n      /* else will try the metamethod */\n    }\n    else {  /* 't' is a table */\n      tm = fasttm(L, hvalue(t)->metatable, TM_INDEX);  /* table's metamethod */\n      if (tm == NULL) {  /* no metamethod? */\n        setnilvalue(s2v(val));  /* result is nil */\n        return LUA_VNIL;\n      }\n      /* else will try the metamethod */\n    }\n    if (ttisfunction(tm)) {  /* is metamethod a function? */\n      tag = luaT_callTMres(L, tm, t, key, val);  /* call it */\n      return tag;  /* return tag of the result */\n    }\n    t = tm;  /* else try to access 'tm[key]' */\n    luaV_fastget(t, key, s2v(val), luaH_get, tag);\n    if (!tagisempty(tag))\n      return tag;  /* done */\n    /* else repeat (tail call 'luaV_finishget') */\n  }\n  luaG_runerror(L, \"'__index' chain too long; possible loop\");\n  return 0;  /* to avoid warnings */\n}\n\n\n/*\n** Finish a table assignment 't[key] = val'.\n** About anchoring the table before the call to 'luaH_finishset':\n** This call may trigger an emergency collection. When loop>0,\n** the table being accessed is a field in some metatable. If this\n** metatable is weak and the table is not anchored, this collection\n** could collect that table while it is being updated.\n*/\nvoid luaV_finishset (lua_State *L, const TValue *t, TValue *key,\n                      TValue *val, int hres) {\n  int loop;  /* counter to avoid infinite loops */\n  for (loop = 0; loop < MAXTAGLOOP; loop++) {\n    const TValue *tm;  /* '__newindex' metamethod */\n    if (hres != HNOTATABLE) {  /* is 't' a table? */\n      Table *h = hvalue(t);  /* save 't' table */\n      if (isshared(h))\n        luaG_typeerror(L, t, \"change\");\n      tm = fasttm(L, h->metatable, TM_NEWINDEX);  /* get metamethod */\n      if (tm == NULL) {  /* no metamethod? */\n        sethvalue2s(L, L->top.p, h);  /* anchor 't' */\n        L->top.p++;  /* assume EXTRA_STACK */\n        luaH_finishset(L, h, key, val, hres);  /* set new value */\n        L->top.p--;\n        invalidateTMcache(h);\n        luaC_barrierback(L, obj2gco(h), val);\n        return;\n      }\n      /* else will try the metamethod */\n    }\n    else {  /* not a table; check metamethod */\n      tm = luaT_gettmbyobj(L, t, TM_NEWINDEX);\n      if (l_unlikely(notm(tm)))\n        luaG_typeerror(L, t, \"index\");\n    }\n    /* try the metamethod */\n    if (ttisfunction(tm)) {\n      luaT_callTM(L, tm, t, key, val);\n      return;\n    }\n    t = tm;  /* else repeat assignment over 'tm' */\n    luaV_fastset(t, key, val, hres, luaH_pset);\n    if (hres == HOK) {\n      luaV_finishfastset(L, t, val);\n      return;  /* done */\n    }\n    /* else 'return luaV_finishset(L, t, key, val, slot)' (loop) */\n  }\n  luaG_runerror(L, \"'__newindex' chain too long; possible loop\");\n}\n\n\n/*\n** Function to be used for 0-terminated string order comparison\n*/\n#if !defined(l_strcoll)\n#define l_strcoll\tstrcoll\n#endif\n\n\n/*\n** Compare two strings 'ts1' x 'ts2', returning an integer less-equal-\n** -greater than zero if 'ts1' is less-equal-greater than 'ts2'.\n** The code is a little tricky because it allows '\\0' in the strings\n** and it uses 'strcoll' (to respect locales) for each segment\n** of the strings. Note that segments can compare equal but still\n** have different lengths.\n*/\nstatic int l_strcmp (const TString *ts1, const TString *ts2) {\n  size_t rl1;  /* real length */\n  const char *s1 = getlstr(ts1, rl1);\n  size_t rl2;\n  const char *s2 = getlstr(ts2, rl2);\n  for (;;) {  /* for each segment */\n    int temp = l_strcoll(s1, s2);\n    if (temp != 0)  /* not equal? */\n      return temp;  /* done */\n    else {  /* strings are equal up to a '\\0' */\n      size_t zl1 = strlen(s1);  /* index of first '\\0' in 's1' */\n      size_t zl2 = strlen(s2);  /* index of first '\\0' in 's2' */\n      if (zl2 == rl2)  /* 's2' is finished? */\n        return (zl1 == rl1) ? 0 : 1;  /* check 's1' */\n      else if (zl1 == rl1)  /* 's1' is finished? */\n        return -1;  /* 's1' is less than 's2' ('s2' is not finished) */\n      /* both strings longer than 'zl'; go on comparing after the '\\0' */\n      zl1++; zl2++;\n      s1 += zl1; rl1 -= zl1; s2 += zl2; rl2 -= zl2;\n    }\n  }\n}\n\n\n/*\n** Check whether integer 'i' is less than float 'f'. If 'i' has an\n** exact representation as a float ('l_intfitsf'), compare numbers as\n** floats. Otherwise, use the equivalence 'i < f <=> i < ceil(f)'.\n** If 'ceil(f)' is out of integer range, either 'f' is greater than\n** all integers or less than all integers.\n** (The test with 'l_intfitsf' is only for performance; the else\n** case is correct for all values, but it is slow due to the conversion\n** from float to int.)\n** When 'f' is NaN, comparisons must result in false.\n*/\nl_sinline int LTintfloat (lua_Integer i, lua_Number f) {\n  if (l_intfitsf(i))\n    return luai_numlt(cast_num(i), f);  /* compare them as floats */\n  else {  /* i < f <=> i < ceil(f) */\n    lua_Integer fi;\n    if (luaV_flttointeger(f, &fi, F2Iceil))  /* fi = ceil(f) */\n      return i < fi;   /* compare them as integers */\n    else  /* 'f' is either greater or less than all integers */\n      return f > 0;  /* greater? */\n  }\n}\n\n\n/*\n** Check whether integer 'i' is less than or equal to float 'f'.\n** See comments on previous function.\n*/\nl_sinline int LEintfloat (lua_Integer i, lua_Number f) {\n  if (l_intfitsf(i))\n    return luai_numle(cast_num(i), f);  /* compare them as floats */\n  else {  /* i <= f <=> i <= floor(f) */\n    lua_Integer fi;\n    if (luaV_flttointeger(f, &fi, F2Ifloor))  /* fi = floor(f) */\n      return i <= fi;   /* compare them as integers */\n    else  /* 'f' is either greater or less than all integers */\n      return f > 0;  /* greater? */\n  }\n}\n\n\n/*\n** Check whether float 'f' is less than integer 'i'.\n** See comments on previous function.\n*/\nl_sinline int LTfloatint (lua_Number f, lua_Integer i) {\n  if (l_intfitsf(i))\n    return luai_numlt(f, cast_num(i));  /* compare them as floats */\n  else {  /* f < i <=> floor(f) < i */\n    lua_Integer fi;\n    if (luaV_flttointeger(f, &fi, F2Ifloor))  /* fi = floor(f) */\n      return fi < i;   /* compare them as integers */\n    else  /* 'f' is either greater or less than all integers */\n      return f < 0;  /* less? */\n  }\n}\n\n\n/*\n** Check whether float 'f' is less than or equal to integer 'i'.\n** See comments on previous function.\n*/\nl_sinline int LEfloatint (lua_Number f, lua_Integer i) {\n  if (l_intfitsf(i))\n    return luai_numle(f, cast_num(i));  /* compare them as floats */\n  else {  /* f <= i <=> ceil(f) <= i */\n    lua_Integer fi;\n    if (luaV_flttointeger(f, &fi, F2Iceil))  /* fi = ceil(f) */\n      return fi <= i;   /* compare them as integers */\n    else  /* 'f' is either greater or less than all integers */\n      return f < 0;  /* less? */\n  }\n}\n\n\n/*\n** Return 'l < r', for numbers.\n*/\nl_sinline int LTnum (const TValue *l, const TValue *r) {\n  lua_assert(ttisnumber(l) && ttisnumber(r));\n  if (ttisinteger(l)) {\n    lua_Integer li = ivalue(l);\n    if (ttisinteger(r))\n      return li < ivalue(r);  /* both are integers */\n    else  /* 'l' is int and 'r' is float */\n      return LTintfloat(li, fltvalue(r));  /* l < r ? */\n  }\n  else {\n    lua_Number lf = fltvalue(l);  /* 'l' must be float */\n    if (ttisfloat(r))\n      return luai_numlt(lf, fltvalue(r));  /* both are float */\n    else  /* 'l' is float and 'r' is int */\n      return LTfloatint(lf, ivalue(r));\n  }\n}\n\n\n/*\n** Return 'l <= r', for numbers.\n*/\nl_sinline int LEnum (const TValue *l, const TValue *r) {\n  lua_assert(ttisnumber(l) && ttisnumber(r));\n  if (ttisinteger(l)) {\n    lua_Integer li = ivalue(l);\n    if (ttisinteger(r))\n      return li <= ivalue(r);  /* both are integers */\n    else  /* 'l' is int and 'r' is float */\n      return LEintfloat(li, fltvalue(r));  /* l <= r ? */\n  }\n  else {\n    lua_Number lf = fltvalue(l);  /* 'l' must be float */\n    if (ttisfloat(r))\n      return luai_numle(lf, fltvalue(r));  /* both are float */\n    else  /* 'l' is float and 'r' is int */\n      return LEfloatint(lf, ivalue(r));\n  }\n}\n\n\n/*\n** return 'l < r' for non-numbers.\n*/\nstatic int lessthanothers (lua_State *L, const TValue *l, const TValue *r) {\n  lua_assert(!ttisnumber(l) || !ttisnumber(r));\n  if (ttisstring(l) && ttisstring(r))  /* both are strings? */\n    return l_strcmp(tsvalue(l), tsvalue(r)) < 0;\n  else\n    return luaT_callorderTM(L, l, r, TM_LT);\n}\n\n\n/*\n** Main operation less than; return 'l < r'.\n*/\nint luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {\n  if (ttisnumber(l) && ttisnumber(r))  /* both operands are numbers? */\n    return LTnum(l, r);\n  else return lessthanothers(L, l, r);\n}\n\n\n/*\n** return 'l <= r' for non-numbers.\n*/\nstatic int lessequalothers (lua_State *L, const TValue *l, const TValue *r) {\n  lua_assert(!ttisnumber(l) || !ttisnumber(r));\n  if (ttisstring(l) && ttisstring(r))  /* both are strings? */\n    return l_strcmp(tsvalue(l), tsvalue(r)) <= 0;\n  else\n    return luaT_callorderTM(L, l, r, TM_LE);\n}\n\n\n/*\n** Main operation less than or equal to; return 'l <= r'.\n*/\nint luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {\n  if (ttisnumber(l) && ttisnumber(r))  /* both operands are numbers? */\n    return LEnum(l, r);\n  else return lessequalothers(L, l, r);\n}\n\n\n/*\n** Main operation for equality of Lua values; return 't1 == t2'.\n** L == NULL means raw equality (no metamethods)\n*/\nint luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) {\n  const TValue *tm;\n  if (ttype(t1) != ttype(t2))  /* not the same type? */\n    return 0;\n  else if (ttypetag(t1) != ttypetag(t2)) {\n    switch (ttypetag(t1)) {\n      case LUA_VNUMINT: {  /* integer == float? */\n        /* integer and float can only be equal if float has an integer\n           value equal to the integer */\n        lua_Integer i2;\n        return (luaV_flttointeger(fltvalue(t2), &i2, F2Ieq) &&\n                ivalue(t1) == i2);\n      }\n      case LUA_VNUMFLT: {  /* float == integer? */\n        lua_Integer i1;  /* see comment in previous case */\n        return (luaV_flttointeger(fltvalue(t1), &i1, F2Ieq) &&\n                i1 == ivalue(t2));\n      }\n      case LUA_VSHRSTR: case LUA_VLNGSTR: {\n        /* compare two strings with different variants: they can be\n           equal when one string is a short string and the other is\n           an external string  */\n        return luaS_eqstr(tsvalue(t1), tsvalue(t2));\n      }\n      default:\n        /* only numbers (integer/float) and strings (long/short) can have\n           equal values with different variants */\n        return 0;\n    }\n  }\n  else {  /* equal variants */\n    switch (ttypetag(t1)) {\n      case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:\n        return 1;\n      case LUA_VNUMINT:\n        return (ivalue(t1) == ivalue(t2));\n      case LUA_VNUMFLT:\n        return (fltvalue(t1) == fltvalue(t2));\n      case LUA_VLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);\n      case LUA_VSHRSTR:\n        return eqshrstr(tsvalue(t1), tsvalue(t2));\n      case LUA_VLNGSTR:\n        return luaS_eqstr(tsvalue(t1), tsvalue(t2));\n      case LUA_VUSERDATA: {\n        if (uvalue(t1) == uvalue(t2)) return 1;\n        else if (L == NULL) return 0;\n        tm = fasttm(L, uvalue(t1)->metatable, TM_EQ);\n        if (tm == NULL)\n          tm = fasttm(L, uvalue(t2)->metatable, TM_EQ);\n        break;  /* will try TM */\n      }\n      case LUA_VTABLE: {\n        if (hvalue(t1) == hvalue(t2)) return 1;\n        else if (L == NULL) return 0;\n        tm = fasttm(L, hvalue(t1)->metatable, TM_EQ);\n        if (tm == NULL)\n          tm = fasttm(L, hvalue(t2)->metatable, TM_EQ);\n        break;  /* will try TM */\n      }\n      case LUA_VLCF:\n        return (fvalue(t1) == fvalue(t2));\n      default:  /* functions and threads */\n        return (gcvalue(t1) == gcvalue(t2));\n    }\n    if (tm == NULL)  /* no TM? */\n      return 0;  /* objects are different */\n    else {\n      int tag = luaT_callTMres(L, tm, t1, t2, L->top.p);  /* call TM */\n      return !tagisfalse(tag);\n    }\n  }\n}\n\n\n/* macro used by 'luaV_concat' to ensure that element at 'o' is a string */\n#define tostring(L,o)  \\\n\t(ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1)))\n\n/*\n** Check whether object is a short empty string to optimize concatenation.\n** (External strings can be empty too; they will be concatenated like\n** non-empty ones.)\n*/\n#define isemptystr(o)\t(ttisshrstring(o) && tsvalue(o)->shrlen == 0)\n\n/* copy strings in stack from top - n up to top - 1 to buffer */\nstatic void copy2buff (StkId top, int n, char *buff) {\n  size_t tl = 0;  /* size already copied */\n  do {\n    TString *st = tsvalue(s2v(top - n));\n    size_t l;  /* length of string being copied */\n    const char *s = getlstr(st, l);\n    memcpy(buff + tl, s, l * sizeof(char));\n    tl += l;\n  } while (--n > 0);\n}\n\n\n/*\n** Main operation for concatenation: concat 'total' values in the stack,\n** from 'L->top.p - total' up to 'L->top.p - 1'.\n*/\nvoid luaV_concat (lua_State *L, int total) {\n  if (total == 1)\n    return;  /* \"all\" values already concatenated */\n  do {\n    StkId top = L->top.p;\n    int n = 2;  /* number of elements handled in this pass (at least 2) */\n    if (!(ttisstring(s2v(top - 2)) || cvt2str(s2v(top - 2))) ||\n        !tostring(L, s2v(top - 1)))\n      luaT_tryconcatTM(L);  /* may invalidate 'top' */\n    else if (isemptystr(s2v(top - 1)))  /* second operand is empty? */\n      cast_void(tostring(L, s2v(top - 2)));  /* result is first operand */\n    else if (isemptystr(s2v(top - 2))) {  /* first operand is empty string? */\n      setobjs2s(L, top - 2, top - 1);  /* result is second op. */\n    }\n    else {\n      /* at least two string values; get as many as possible */\n      size_t tl = tsslen(tsvalue(s2v(top - 1)));  /* total length */\n      TString *ts;\n      /* collect total length and number of strings */\n      for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) {\n        size_t l = tsslen(tsvalue(s2v(top - n - 1)));\n        if (l_unlikely(l >= MAX_SIZE - sizeof(TString) - tl)) {\n          L->top.p = top - total;  /* pop strings to avoid wasting stack */\n          luaG_runerror(L, \"string length overflow\");\n        }\n        tl += l;\n      }\n      if (tl <= LUAI_MAXSHORTLEN) {  /* is result a short string? */\n        char buff[LUAI_MAXSHORTLEN];\n        copy2buff(top, n, buff);  /* copy strings to buffer */\n        ts = luaS_newlstr(L, buff, tl);\n      }\n      else {  /* long string; copy strings directly to final result */\n        ts = luaS_createlngstrobj(L, tl);\n        copy2buff(top, n, getlngstr(ts));\n      }\n      setsvalue2s(L, top - n, ts);  /* create result */\n    }\n    total -= n - 1;  /* got 'n' strings to create one new */\n    L->top.p -= n - 1;  /* popped 'n' strings and pushed one */\n  } while (total > 1);  /* repeat until only 1 result left */\n}\n\n\n/*\n** Main operation 'ra = #rb'.\n*/\nvoid luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {\n  const TValue *tm;\n  switch (ttypetag(rb)) {\n    case LUA_VTABLE: {\n      Table *h = hvalue(rb);\n      tm = fasttm(L, h->metatable, TM_LEN);\n      if (tm) break;  /* metamethod? break switch to call it */\n      setivalue(s2v(ra), l_castU2S(luaH_getn(L, h)));  /* else primitive len */\n      return;\n    }\n    case LUA_VSHRSTR: {\n      setivalue(s2v(ra), tsvalue(rb)->shrlen);\n      return;\n    }\n    case LUA_VLNGSTR: {\n      setivalue(s2v(ra), cast_st2S(tsvalue(rb)->u.lnglen));\n      return;\n    }\n    default: {  /* try metamethod */\n      tm = luaT_gettmbyobj(L, rb, TM_LEN);\n      if (l_unlikely(notm(tm)))  /* no metamethod? */\n        luaG_typeerror(L, rb, \"get length of\");\n      break;\n    }\n  }\n  luaT_callTMres(L, tm, rb, rb, ra);\n}\n\n\n/*\n** Integer division; return 'm // n', that is, floor(m/n).\n** C division truncates its result (rounds towards zero).\n** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer,\n** otherwise 'floor(q) == trunc(q) - 1'.\n*/\nlua_Integer luaV_idiv (lua_State *L, lua_Integer m, lua_Integer n) {\n  if (l_unlikely(l_castS2U(n) + 1u <= 1u)) {  /* special cases: -1 or 0 */\n    if (n == 0)\n      luaG_runerror(L, \"attempt to divide by zero\");\n    return intop(-, 0, m);   /* n==-1; avoid overflow with 0x80000...//-1 */\n  }\n  else {\n    lua_Integer q = m / n;  /* perform C division */\n    if ((m ^ n) < 0 && m % n != 0)  /* 'm/n' would be negative non-integer? */\n      q -= 1;  /* correct result for different rounding */\n    return q;\n  }\n}\n\n\n/*\n** Integer modulus; return 'm % n'. (Assume that C '%' with\n** negative operands follows C99 behavior. See previous comment\n** about luaV_idiv.)\n*/\nlua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) {\n  if (l_unlikely(l_castS2U(n) + 1u <= 1u)) {  /* special cases: -1 or 0 */\n    if (n == 0)\n      luaG_runerror(L, \"attempt to perform 'n%%0'\");\n    return 0;   /* m % -1 == 0; avoid overflow with 0x80000...%-1 */\n  }\n  else {\n    lua_Integer r = m % n;\n    if (r != 0 && (r ^ n) < 0)  /* 'm/n' would be non-integer negative? */\n      r += n;  /* correct result for different rounding */\n    return r;\n  }\n}\n\n\n/*\n** Float modulus\n*/\nlua_Number luaV_modf (lua_State *L, lua_Number m, lua_Number n) {\n  lua_Number r;\n  luai_nummod(L, m, n, r);\n  return r;\n}\n\n\n/* number of bits in an integer */\n#define NBITS\tl_numbits(lua_Integer)\n\n\n/*\n** Shift left operation. (Shift right just negates 'y'.)\n*/\nlua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) {\n  if (y < 0) {  /* shift right? */\n    if (y <= -NBITS) return 0;\n    else return intop(>>, x, -y);\n  }\n  else {  /* shift left */\n    if (y >= NBITS) return 0;\n    else return intop(<<, x, y);\n  }\n}\n\n\n/*\n** create a new Lua closure, push it in the stack, and initialize\n** its upvalues.\n*/\nstatic void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,\n                         StkId ra) {\n  int nup = p->sizeupvalues;\n  Upvaldesc *uv = p->upvalues;\n  int i;\n  LClosure *ncl = luaF_newLclosure(L, nup);\n  ncl->p = p;\n  setclLvalue2s(L, ra, ncl);  /* anchor new closure in stack */\n  for (i = 0; i < nup; i++) {  /* fill in its upvalues */\n    if (uv[i].instack)  /* upvalue refers to local variable? */\n      ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx);\n    else  /* get upvalue from enclosing function */\n      ncl->upvals[i] = encup[uv[i].idx];\n    luaC_objbarrier(L, ncl, ncl->upvals[i]);\n  }\n}\n\n\n/*\n** finish execution of an opcode interrupted by a yield\n*/\nvoid luaV_finishOp (lua_State *L) {\n  CallInfo *ci = L->ci;\n  StkId base = ci->func.p + 1;\n  Instruction inst = *(ci->u.l.savedpc - 1);  /* interrupted instruction */\n  OpCode op = GET_OPCODE(inst);\n  switch (op) {  /* finish its execution */\n    case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {\n      setobjs2s(L, base + GETARG_A(*(ci->u.l.savedpc - 2)), --L->top.p);\n      break;\n    }\n    case OP_UNM: case OP_BNOT: case OP_LEN:\n    case OP_GETTABUP: case OP_GETTABLE: case OP_GETI:\n    case OP_GETFIELD: case OP_SELF: {\n      setobjs2s(L, base + GETARG_A(inst), --L->top.p);\n      break;\n    }\n    case OP_LT: case OP_LE:\n    case OP_LTI: case OP_LEI:\n    case OP_GTI: case OP_GEI:\n    case OP_EQ: {  /* note that 'OP_EQI'/'OP_EQK' cannot yield */\n      int res = !l_isfalse(s2v(L->top.p - 1));\n      L->top.p--;\n      lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP);\n      if (res != GETARG_k(inst))  /* condition failed? */\n        ci->u.l.savedpc++;  /* skip jump instruction */\n      break;\n    }\n    case OP_CONCAT: {\n      StkId top = L->top.p - 1;  /* top when 'luaT_tryconcatTM' was called */\n      int a = GETARG_A(inst);      /* first element to concatenate */\n      int total = cast_int(top - 1 - (base + a));  /* yet to concatenate */\n      setobjs2s(L, top - 2, top);  /* put TM result in proper position */\n      L->top.p = top - 1;  /* top is one after last element (at top-2) */\n      luaV_concat(L, total);  /* concat them (may yield again) */\n      break;\n    }\n    case OP_CLOSE: {  /* yielded closing variables */\n      ci->u.l.savedpc--;  /* repeat instruction to close other vars. */\n      break;\n    }\n    case OP_RETURN: {  /* yielded closing variables */\n      StkId ra = base + GETARG_A(inst);\n      /* adjust top to signal correct number of returns, in case the\n         return is \"up to top\" ('isIT') */\n      L->top.p = ra + ci->u2.nres;\n      /* repeat instruction to close other vars. and complete the return */\n      ci->u.l.savedpc--;\n      break;\n    }\n    default: {\n      /* only these other opcodes can yield */\n      lua_assert(op == OP_TFORCALL || op == OP_CALL ||\n           op == OP_TAILCALL || op == OP_SETTABUP || op == OP_SETTABLE ||\n           op == OP_SETI || op == OP_SETFIELD);\n      break;\n    }\n  }\n}\n\n\n\n\n/*\n** {==================================================================\n** Macros for arithmetic/bitwise/comparison opcodes in 'luaV_execute'\n**\n** All these macros are to be used exclusively inside the main\n** iterpreter loop (function luaV_execute) and may access directly\n** the local variables of that function (L, i, pc, ci, etc.).\n** ===================================================================\n*/\n\n#define l_addi(L,a,b)\tintop(+, a, b)\n#define l_subi(L,a,b)\tintop(-, a, b)\n#define l_muli(L,a,b)\tintop(*, a, b)\n#define l_band(a,b)\tintop(&, a, b)\n#define l_bor(a,b)\tintop(|, a, b)\n#define l_bxor(a,b)\tintop(^, a, b)\n\n#define l_lti(a,b)\t(a < b)\n#define l_lei(a,b)\t(a <= b)\n#define l_gti(a,b)\t(a > b)\n#define l_gei(a,b)\t(a >= b)\n\n\n/*\n** Arithmetic operations with immediate operands. 'iop' is the integer\n** operation, 'fop' is the float operation.\n*/\n#define op_arithI(L,iop,fop) {  \\\n  TValue *ra = vRA(i); \\\n  TValue *v1 = vRB(i);  \\\n  int imm = GETARG_sC(i);  \\\n  if (ttisinteger(v1)) {  \\\n    lua_Integer iv1 = ivalue(v1);  \\\n    pc++; setivalue(ra, iop(L, iv1, imm));  \\\n  }  \\\n  else if (ttisfloat(v1)) {  \\\n    lua_Number nb = fltvalue(v1);  \\\n    lua_Number fimm = cast_num(imm);  \\\n    pc++; setfltvalue(ra, fop(L, nb, fimm)); \\\n  }}\n\n\n/*\n** Auxiliary function for arithmetic operations over floats and others\n** with two operands.\n*/\n#define op_arithf_aux(L,v1,v2,fop) {  \\\n  lua_Number n1; lua_Number n2;  \\\n  if (tonumberns(v1, n1) && tonumberns(v2, n2)) {  \\\n    StkId ra = RA(i);  \\\n    pc++; setfltvalue(s2v(ra), fop(L, n1, n2));  \\\n  }}\n\n\n/*\n** Arithmetic operations over floats and others with register operands.\n*/\n#define op_arithf(L,fop) {  \\\n  TValue *v1 = vRB(i);  \\\n  TValue *v2 = vRC(i);  \\\n  op_arithf_aux(L, v1, v2, fop); }\n\n\n/*\n** Arithmetic operations with K operands for floats.\n*/\n#define op_arithfK(L,fop) {  \\\n  TValue *v1 = vRB(i);  \\\n  TValue *v2 = KC(i); lua_assert(ttisnumber(v2));  \\\n  op_arithf_aux(L, v1, v2, fop); }\n\n\n/*\n** Arithmetic operations over integers and floats.\n*/\n#define op_arith_aux(L,v1,v2,iop,fop) {  \\\n  if (ttisinteger(v1) && ttisinteger(v2)) {  \\\n    StkId ra = RA(i); \\\n    lua_Integer i1 = ivalue(v1); lua_Integer i2 = ivalue(v2);  \\\n    pc++; setivalue(s2v(ra), iop(L, i1, i2));  \\\n  }  \\\n  else op_arithf_aux(L, v1, v2, fop); }\n\n\n/*\n** Arithmetic operations with register operands.\n*/\n#define op_arith(L,iop,fop) {  \\\n  TValue *v1 = vRB(i);  \\\n  TValue *v2 = vRC(i);  \\\n  op_arith_aux(L, v1, v2, iop, fop); }\n\n\n/*\n** Arithmetic operations with K operands.\n*/\n#define op_arithK(L,iop,fop) {  \\\n  TValue *v1 = vRB(i);  \\\n  TValue *v2 = KC(i); lua_assert(ttisnumber(v2));  \\\n  op_arith_aux(L, v1, v2, iop, fop); }\n\n\n/*\n** Bitwise operations with constant operand.\n*/\n#define op_bitwiseK(L,op) {  \\\n  TValue *v1 = vRB(i);  \\\n  TValue *v2 = KC(i);  \\\n  lua_Integer i1;  \\\n  lua_Integer i2 = ivalue(v2);  \\\n  if (tointegerns(v1, &i1)) {  \\\n    StkId ra = RA(i); \\\n    pc++; setivalue(s2v(ra), op(i1, i2));  \\\n  }}\n\n\n/*\n** Bitwise operations with register operands.\n*/\n#define op_bitwise(L,op) {  \\\n  TValue *v1 = vRB(i);  \\\n  TValue *v2 = vRC(i);  \\\n  lua_Integer i1; lua_Integer i2;  \\\n  if (tointegerns(v1, &i1) && tointegerns(v2, &i2)) {  \\\n    StkId ra = RA(i); \\\n    pc++; setivalue(s2v(ra), op(i1, i2));  \\\n  }}\n\n\n/*\n** Order operations with register operands. 'opn' actually works\n** for all numbers, but the fast track improves performance for\n** integers.\n*/\n#define op_order(L,opi,opn,other) {  \\\n  TValue *ra = vRA(i); \\\n  int cond;  \\\n  TValue *rb = vRB(i);  \\\n  if (ttisinteger(ra) && ttisinteger(rb)) {  \\\n    lua_Integer ia = ivalue(ra);  \\\n    lua_Integer ib = ivalue(rb);  \\\n    cond = opi(ia, ib);  \\\n  }  \\\n  else if (ttisnumber(ra) && ttisnumber(rb))  \\\n    cond = opn(ra, rb);  \\\n  else  \\\n    Protect(cond = other(L, ra, rb));  \\\n  docondjump(); }\n\n\n/*\n** Order operations with immediate operand. (Immediate operand is\n** always small enough to have an exact representation as a float.)\n*/\n#define op_orderI(L,opi,opf,inv,tm) {  \\\n  TValue *ra = vRA(i); \\\n  int cond;  \\\n  int im = GETARG_sB(i);  \\\n  if (ttisinteger(ra))  \\\n    cond = opi(ivalue(ra), im);  \\\n  else if (ttisfloat(ra)) {  \\\n    lua_Number fa = fltvalue(ra);  \\\n    lua_Number fim = cast_num(im);  \\\n    cond = opf(fa, fim);  \\\n  }  \\\n  else {  \\\n    int isf = GETARG_C(i);  \\\n    Protect(cond = luaT_callorderiTM(L, ra, im, inv, isf, tm));  \\\n  }  \\\n  docondjump(); }\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Function 'luaV_execute': main interpreter loop\n** ===================================================================\n*/\n\n/*\n** some macros for common tasks in 'luaV_execute'\n*/\n\n\n#define RA(i)\t(base+GETARG_A(i))\n#define vRA(i)\ts2v(RA(i))\n#define RB(i)\t(base+GETARG_B(i))\n#define vRB(i)\ts2v(RB(i))\n#define KB(i)\t(k+GETARG_B(i))\n#define RC(i)\t(base+GETARG_C(i))\n#define vRC(i)\ts2v(RC(i))\n#define KC(i)\t(k+GETARG_C(i))\n#define RKC(i)\t((TESTARG_k(i)) ? k + GETARG_C(i) : s2v(base + GETARG_C(i)))\n\n\n\n#define updatetrap(ci)  (trap = ci->u.l.trap)\n\n#define updatebase(ci)\t(base = ci->func.p + 1)\n\n\n#define updatestack(ci)  \\\n\t{ if (l_unlikely(trap)) { updatebase(ci); ra = RA(i); } }\n\n\n/*\n** Execute a jump instruction. The 'updatetrap' allows signals to stop\n** tight loops. (Without it, the local copy of 'trap' could never change.)\n*/\n#define dojump(ci,i,e)\t{ pc += GETARG_sJ(i) + e; updatetrap(ci); }\n\n\n/* for test instructions, execute the jump instruction that follows it */\n#define donextjump(ci)\t{ Instruction ni = *pc; dojump(ci, ni, 1); }\n\n/*\n** do a conditional jump: skip next instruction if 'cond' is not what\n** was expected (parameter 'k'), else do next instruction, which must\n** be a jump.\n*/\n#define docondjump()\tif (cond != GETARG_k(i)) pc++; else donextjump(ci);\n\n\n/*\n** Correct global 'pc'.\n*/\n#define savepc(ci)\t(ci->u.l.savedpc = pc)\n\n\n/*\n** Whenever code can raise errors, the global 'pc' and the global\n** 'top' must be correct to report occasional errors.\n*/\n#define savestate(L,ci)\t\t(savepc(ci), L->top.p = ci->top.p)\n\n\n/*\n** Protect code that, in general, can raise errors, reallocate the\n** stack, and change the hooks.\n*/\n#define Protect(exp)  (savestate(L,ci), (exp), updatetrap(ci))\n\n/* special version that does not change the top */\n#define ProtectNT(exp)  (savepc(ci), (exp), updatetrap(ci))\n\n/*\n** Protect code that can only raise errors. (That is, it cannot change\n** the stack or hooks.)\n*/\n#define halfProtect(exp)  (savestate(L,ci), (exp))\n\n/*\n** macro executed during Lua functions at points where the\n** function can yield.\n*/\n#if !defined(luai_threadyield)\n#define luai_threadyield(L)\t{lua_unlock(L); lua_lock(L);}\n#endif\n\n/* 'c' is the limit of live values in the stack */\n#define checkGC(L,c)  \\\n\t{ luaC_condGC(L, (savepc(ci), L->top.p = (c)), \\\n                         updatetrap(ci)); \\\n           luai_threadyield(L); }\n\n\n/* fetch an instruction and prepare its execution */\n#define vmfetch()\t{ \\\n  if (l_unlikely(trap)) {  /* stack reallocation or hooks? */ \\\n    trap = luaG_traceexec(L, pc);  /* handle hooks */ \\\n    updatebase(ci);  /* correct stack */ \\\n  } \\\n  i = *(pc++); \\\n}\n\n#define vmdispatch(o)\tswitch(o)\n#define vmcase(l)\tcase l:\n#define vmbreak\t\tbreak\n\n\nvoid luaV_execute (lua_State *L, CallInfo *ci) {\n  LClosure *cl;\n  TValue *k;\n  StkId base;\n  const Instruction *pc;\n  int trap;\n#if LUA_USE_JUMPTABLE\n#include \"ljumptab.h\"\n#endif\n startfunc:\n  trap = L->hookmask;\n returning:  /* trap already set */\n  cl = ci_func(ci);\n  k = cl->p->k;\n  pc = ci->u.l.savedpc;\n  if (l_unlikely(trap))\n    trap = luaG_tracecall(L);\n  base = ci->func.p + 1;\n  /* main loop of interpreter */\n  for (;;) {\n    Instruction i;  /* instruction being executed */\n    vmfetch();\n    #if 0\n    { /* low-level line tracing for debugging Lua */\n      #include \"lopnames.h\"\n      int pcrel = pcRel(pc, cl->p);\n      printf(\"line: %d; %s (%d)\\n\", luaG_getfuncline(cl->p, pcrel),\n             opnames[GET_OPCODE(i)], pcrel);\n    }\n    #endif\n    lua_assert(base == ci->func.p + 1);\n    lua_assert(base <= L->top.p && L->top.p <= L->stack_last.p);\n    /* for tests, invalidate top for instructions not expecting it */\n    lua_assert(luaP_isIT(i) || (cast_void(L->top.p = base), 1));\n    vmdispatch (GET_OPCODE(i)) {\n      vmcase(OP_MOVE) {\n        StkId ra = RA(i);\n        setobjs2s(L, ra, RB(i));\n        vmbreak;\n      }\n      vmcase(OP_LOADI) {\n        StkId ra = RA(i);\n        lua_Integer b = GETARG_sBx(i);\n        setivalue(s2v(ra), b);\n        vmbreak;\n      }\n      vmcase(OP_LOADF) {\n        StkId ra = RA(i);\n        int b = GETARG_sBx(i);\n        setfltvalue(s2v(ra), cast_num(b));\n        vmbreak;\n      }\n      vmcase(OP_LOADK) {\n        StkId ra = RA(i);\n        TValue *rb = k + GETARG_Bx(i);\n        setobj2s(L, ra, rb);\n        vmbreak;\n      }\n      vmcase(OP_LOADKX) {\n        StkId ra = RA(i);\n        TValue *rb;\n        rb = k + GETARG_Ax(*pc); pc++;\n        setobj2s(L, ra, rb);\n        vmbreak;\n      }\n      vmcase(OP_LOADFALSE) {\n        StkId ra = RA(i);\n        setbfvalue(s2v(ra));\n        vmbreak;\n      }\n      vmcase(OP_LFALSESKIP) {\n        StkId ra = RA(i);\n        setbfvalue(s2v(ra));\n        pc++;  /* skip next instruction */\n        vmbreak;\n      }\n      vmcase(OP_LOADTRUE) {\n        StkId ra = RA(i);\n        setbtvalue(s2v(ra));\n        vmbreak;\n      }\n      vmcase(OP_LOADNIL) {\n        StkId ra = RA(i);\n        int b = GETARG_B(i);\n        do {\n          setnilvalue(s2v(ra++));\n        } while (b--);\n        vmbreak;\n      }\n      vmcase(OP_GETUPVAL) {\n        StkId ra = RA(i);\n        int b = GETARG_B(i);\n        setobj2s(L, ra, cl->upvals[b]->v.p);\n        vmbreak;\n      }\n      vmcase(OP_SETUPVAL) {\n        StkId ra = RA(i);\n        UpVal *uv = cl->upvals[GETARG_B(i)];\n        setobj(L, uv->v.p, s2v(ra));\n        luaC_barrier(L, uv, s2v(ra));\n        vmbreak;\n      }\n      vmcase(OP_GETTABUP) {\n        StkId ra = RA(i);\n        TValue *upval = cl->upvals[GETARG_B(i)]->v.p;\n        TValue *rc = KC(i);\n        TString *key = tsvalue(rc);  /* key must be a short string */\n        lu_byte tag;\n        luaV_fastget(upval, key, s2v(ra), luaH_getshortstr, tag);\n        if (tagisempty(tag))\n          Protect(luaV_finishget(L, upval, rc, ra, tag));\n        vmbreak;\n      }\n      vmcase(OP_GETTABLE) {\n        StkId ra = RA(i);\n        TValue *rb = vRB(i);\n        TValue *rc = vRC(i);\n        lu_byte tag;\n        if (ttisinteger(rc)) {  /* fast track for integers? */\n          luaV_fastgeti(rb, ivalue(rc), s2v(ra), tag);\n        }\n        else\n          luaV_fastget(rb, rc, s2v(ra), luaH_get, tag);\n        if (tagisempty(tag))\n          Protect(luaV_finishget(L, rb, rc, ra, tag));\n        vmbreak;\n      }\n      vmcase(OP_GETI) {\n        StkId ra = RA(i);\n        TValue *rb = vRB(i);\n        int c = GETARG_C(i);\n        lu_byte tag;\n        luaV_fastgeti(rb, c, s2v(ra), tag);\n        if (tagisempty(tag)) {\n          TValue key;\n          setivalue(&key, c);\n          Protect(luaV_finishget(L, rb, &key, ra, tag));\n        }\n        vmbreak;\n      }\n      vmcase(OP_GETFIELD) {\n        StkId ra = RA(i);\n        TValue *rb = vRB(i);\n        TValue *rc = KC(i);\n        TString *key = tsvalue(rc);  /* key must be a short string */\n        lu_byte tag;\n        luaV_fastget(rb, key, s2v(ra), luaH_getshortstr, tag);\n        if (tagisempty(tag))\n          Protect(luaV_finishget(L, rb, rc, ra, tag));\n        vmbreak;\n      }\n      vmcase(OP_SETTABUP) {\n        int hres;\n        TValue *upval = cl->upvals[GETARG_A(i)]->v.p;\n        TValue *rb = KB(i);\n        TValue *rc = RKC(i);\n        TString *key = tsvalue(rb);  /* key must be a short string */\n        luaV_fastset(upval, key, rc, hres, luaH_psetshortstr);\n        if (hres == HOK)\n          luaV_finishfastset(L, upval, rc);\n        else\n          Protect(luaV_finishset(L, upval, rb, rc, hres));\n        vmbreak;\n      }\n      vmcase(OP_SETTABLE) {\n        StkId ra = RA(i);\n        int hres;\n        TValue *rb = vRB(i);  /* key (table is in 'ra') */\n        TValue *rc = RKC(i);  /* value */\n        if (ttisinteger(rb)) {  /* fast track for integers? */\n          luaV_fastseti(s2v(ra), ivalue(rb), rc, hres);\n        }\n        else {\n          luaV_fastset(s2v(ra), rb, rc, hres, luaH_pset);\n        }\n        if (hres == HOK)\n          luaV_finishfastset(L, s2v(ra), rc);\n        else\n          Protect(luaV_finishset(L, s2v(ra), rb, rc, hres));\n        vmbreak;\n      }\n      vmcase(OP_SETI) {\n        StkId ra = RA(i);\n        int hres;\n        int b = GETARG_B(i);\n        TValue *rc = RKC(i);\n        luaV_fastseti(s2v(ra), b, rc, hres);\n        if (hres == HOK)\n          luaV_finishfastset(L, s2v(ra), rc);\n        else {\n          TValue key;\n          setivalue(&key, b);\n          Protect(luaV_finishset(L, s2v(ra), &key, rc, hres));\n        }\n        vmbreak;\n      }\n      vmcase(OP_SETFIELD) {\n        StkId ra = RA(i);\n        int hres;\n        TValue *rb = KB(i);\n        TValue *rc = RKC(i);\n        TString *key = tsvalue(rb);  /* key must be a short string */\n        luaV_fastset(s2v(ra), key, rc, hres, luaH_psetshortstr);\n        if (hres == HOK)\n          luaV_finishfastset(L, s2v(ra), rc);\n        else\n          Protect(luaV_finishset(L, s2v(ra), rb, rc, hres));\n        vmbreak;\n      }\n      vmcase(OP_NEWTABLE) {\n        StkId ra = RA(i);\n        unsigned b = cast_uint(GETARG_vB(i));  /* log2(hash size) + 1 */\n        unsigned c = cast_uint(GETARG_vC(i));  /* array size */\n        Table *t;\n        if (b > 0)\n          b = 1u << (b - 1);  /* hash size is 2^(b - 1) */\n        if (TESTARG_k(i)) {  /* non-zero extra argument? */\n          lua_assert(GETARG_Ax(*pc) != 0);\n          /* add it to array size */\n          c += cast_uint(GETARG_Ax(*pc)) * (MAXARG_vC + 1);\n        }\n        pc++;  /* skip extra argument */\n        L->top.p = ra + 1;  /* correct top in case of emergency GC */\n        t = luaH_new(L);  /* memory allocation */\n        sethvalue2s(L, ra, t);\n        if (b != 0 || c != 0)\n          luaH_resize(L, t, c, b);  /* idem */\n        checkGC(L, ra + 1);\n        vmbreak;\n      }\n      vmcase(OP_SELF) {\n        StkId ra = RA(i);\n        lu_byte tag;\n        TValue *rb = vRB(i);\n        TValue *rc = KC(i);\n        TString *key = tsvalue(rc);  /* key must be a short string */\n        setobj2s(L, ra + 1, rb);\n        luaV_fastget(rb, key, s2v(ra), luaH_getshortstr, tag);\n        if (tagisempty(tag))\n          Protect(luaV_finishget(L, rb, rc, ra, tag));\n        vmbreak;\n      }\n      vmcase(OP_ADDI) {\n        op_arithI(L, l_addi, luai_numadd);\n        vmbreak;\n      }\n      vmcase(OP_ADDK) {\n        op_arithK(L, l_addi, luai_numadd);\n        vmbreak;\n      }\n      vmcase(OP_SUBK) {\n        op_arithK(L, l_subi, luai_numsub);\n        vmbreak;\n      }\n      vmcase(OP_MULK) {\n        op_arithK(L, l_muli, luai_nummul);\n        vmbreak;\n      }\n      vmcase(OP_MODK) {\n        savestate(L, ci);  /* in case of division by 0 */\n        op_arithK(L, luaV_mod, luaV_modf);\n        vmbreak;\n      }\n      vmcase(OP_POWK) {\n        op_arithfK(L, luai_numpow);\n        vmbreak;\n      }\n      vmcase(OP_DIVK) {\n        op_arithfK(L, luai_numdiv);\n        vmbreak;\n      }\n      vmcase(OP_IDIVK) {\n        savestate(L, ci);  /* in case of division by 0 */\n        op_arithK(L, luaV_idiv, luai_numidiv);\n        vmbreak;\n      }\n      vmcase(OP_BANDK) {\n        op_bitwiseK(L, l_band);\n        vmbreak;\n      }\n      vmcase(OP_BORK) {\n        op_bitwiseK(L, l_bor);\n        vmbreak;\n      }\n      vmcase(OP_BXORK) {\n        op_bitwiseK(L, l_bxor);\n        vmbreak;\n      }\n      vmcase(OP_SHLI) {\n        StkId ra = RA(i);\n        TValue *rb = vRB(i);\n        int ic = GETARG_sC(i);\n        lua_Integer ib;\n        if (tointegerns(rb, &ib)) {\n          pc++; setivalue(s2v(ra), luaV_shiftl(ic, ib));\n        }\n        vmbreak;\n      }\n      vmcase(OP_SHRI) {\n        StkId ra = RA(i);\n        TValue *rb = vRB(i);\n        int ic = GETARG_sC(i);\n        lua_Integer ib;\n        if (tointegerns(rb, &ib)) {\n          pc++; setivalue(s2v(ra), luaV_shiftl(ib, -ic));\n        }\n        vmbreak;\n      }\n      vmcase(OP_ADD) {\n        op_arith(L, l_addi, luai_numadd);\n        vmbreak;\n      }\n      vmcase(OP_SUB) {\n        op_arith(L, l_subi, luai_numsub);\n        vmbreak;\n      }\n      vmcase(OP_MUL) {\n        op_arith(L, l_muli, luai_nummul);\n        vmbreak;\n      }\n      vmcase(OP_MOD) {\n        savestate(L, ci);  /* in case of division by 0 */\n        op_arith(L, luaV_mod, luaV_modf);\n        vmbreak;\n      }\n      vmcase(OP_POW) {\n        op_arithf(L, luai_numpow);\n        vmbreak;\n      }\n      vmcase(OP_DIV) {  /* float division (always with floats) */\n        op_arithf(L, luai_numdiv);\n        vmbreak;\n      }\n      vmcase(OP_IDIV) {  /* floor division */\n        savestate(L, ci);  /* in case of division by 0 */\n        op_arith(L, luaV_idiv, luai_numidiv);\n        vmbreak;\n      }\n      vmcase(OP_BAND) {\n        op_bitwise(L, l_band);\n        vmbreak;\n      }\n      vmcase(OP_BOR) {\n        op_bitwise(L, l_bor);\n        vmbreak;\n      }\n      vmcase(OP_BXOR) {\n        op_bitwise(L, l_bxor);\n        vmbreak;\n      }\n      vmcase(OP_SHL) {\n        op_bitwise(L, luaV_shiftl);\n        vmbreak;\n      }\n      vmcase(OP_SHR) {\n        op_bitwise(L, luaV_shiftr);\n        vmbreak;\n      }\n      vmcase(OP_MMBIN) {\n        StkId ra = RA(i);\n        Instruction pi = *(pc - 2);  /* original arith. expression */\n        TValue *rb = vRB(i);\n        TMS tm = (TMS)GETARG_C(i);\n        StkId result = RA(pi);\n        lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR);\n        Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm));\n        vmbreak;\n      }\n      vmcase(OP_MMBINI) {\n        StkId ra = RA(i);\n        Instruction pi = *(pc - 2);  /* original arith. expression */\n        int imm = GETARG_sB(i);\n        TMS tm = (TMS)GETARG_C(i);\n        int flip = GETARG_k(i);\n        StkId result = RA(pi);\n        Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm));\n        vmbreak;\n      }\n      vmcase(OP_MMBINK) {\n        StkId ra = RA(i);\n        Instruction pi = *(pc - 2);  /* original arith. expression */\n        TValue *imm = KB(i);\n        TMS tm = (TMS)GETARG_C(i);\n        int flip = GETARG_k(i);\n        StkId result = RA(pi);\n        Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm));\n        vmbreak;\n      }\n      vmcase(OP_UNM) {\n        StkId ra = RA(i);\n        TValue *rb = vRB(i);\n        lua_Number nb;\n        if (ttisinteger(rb)) {\n          lua_Integer ib = ivalue(rb);\n          setivalue(s2v(ra), intop(-, 0, ib));\n        }\n        else if (tonumberns(rb, nb)) {\n          setfltvalue(s2v(ra), luai_numunm(L, nb));\n        }\n        else\n          Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));\n        vmbreak;\n      }\n      vmcase(OP_BNOT) {\n        StkId ra = RA(i);\n        TValue *rb = vRB(i);\n        lua_Integer ib;\n        if (tointegerns(rb, &ib)) {\n          setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib));\n        }\n        else\n          Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));\n        vmbreak;\n      }\n      vmcase(OP_NOT) {\n        StkId ra = RA(i);\n        TValue *rb = vRB(i);\n        if (l_isfalse(rb))\n          setbtvalue(s2v(ra));\n        else\n          setbfvalue(s2v(ra));\n        vmbreak;\n      }\n      vmcase(OP_LEN) {\n        StkId ra = RA(i);\n        Protect(luaV_objlen(L, ra, vRB(i)));\n        vmbreak;\n      }\n      vmcase(OP_CONCAT) {\n        StkId ra = RA(i);\n        int n = GETARG_B(i);  /* number of elements to concatenate */\n        L->top.p = ra + n;  /* mark the end of concat operands */\n        ProtectNT(luaV_concat(L, n));\n        checkGC(L, L->top.p); /* 'luaV_concat' ensures correct top */\n        vmbreak;\n      }\n      vmcase(OP_CLOSE) {\n        StkId ra = RA(i);\n        lua_assert(!GETARG_B(i));  /* 'close must be alive */\n        Protect(luaF_close(L, ra, LUA_OK, 1));\n        vmbreak;\n      }\n      vmcase(OP_TBC) {\n        StkId ra = RA(i);\n        /* create new to-be-closed upvalue */\n        halfProtect(luaF_newtbcupval(L, ra));\n        vmbreak;\n      }\n      vmcase(OP_JMP) {\n        dojump(ci, i, 0);\n        vmbreak;\n      }\n      vmcase(OP_EQ) {\n        StkId ra = RA(i);\n        int cond;\n        TValue *rb = vRB(i);\n        Protect(cond = luaV_equalobj(L, s2v(ra), rb));\n        docondjump();\n        vmbreak;\n      }\n      vmcase(OP_LT) {\n        op_order(L, l_lti, LTnum, lessthanothers);\n        vmbreak;\n      }\n      vmcase(OP_LE) {\n        op_order(L, l_lei, LEnum, lessequalothers);\n        vmbreak;\n      }\n      vmcase(OP_EQK) {\n        StkId ra = RA(i);\n        TValue *rb = KB(i);\n        /* basic types do not use '__eq'; we can use raw equality */\n        int cond = luaV_rawequalobj(s2v(ra), rb);\n        docondjump();\n        vmbreak;\n      }\n      vmcase(OP_EQI) {\n        StkId ra = RA(i);\n        int cond;\n        int im = GETARG_sB(i);\n        if (ttisinteger(s2v(ra)))\n          cond = (ivalue(s2v(ra)) == im);\n        else if (ttisfloat(s2v(ra)))\n          cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im));\n        else\n          cond = 0;  /* other types cannot be equal to a number */\n        docondjump();\n        vmbreak;\n      }\n      vmcase(OP_LTI) {\n        op_orderI(L, l_lti, luai_numlt, 0, TM_LT);\n        vmbreak;\n      }\n      vmcase(OP_LEI) {\n        op_orderI(L, l_lei, luai_numle, 0, TM_LE);\n        vmbreak;\n      }\n      vmcase(OP_GTI) {\n        op_orderI(L, l_gti, luai_numgt, 1, TM_LT);\n        vmbreak;\n      }\n      vmcase(OP_GEI) {\n        op_orderI(L, l_gei, luai_numge, 1, TM_LE);\n        vmbreak;\n      }\n      vmcase(OP_TEST) {\n        StkId ra = RA(i);\n        int cond = !l_isfalse(s2v(ra));\n        docondjump();\n        vmbreak;\n      }\n      vmcase(OP_TESTSET) {\n        StkId ra = RA(i);\n        TValue *rb = vRB(i);\n        if (l_isfalse(rb) == GETARG_k(i))\n          pc++;\n        else {\n          setobj2s(L, ra, rb);\n          donextjump(ci);\n        }\n        vmbreak;\n      }\n      vmcase(OP_CALL) {\n        StkId ra = RA(i);\n        CallInfo *newci;\n        int b = GETARG_B(i);\n        int nresults = GETARG_C(i) - 1;\n        if (b != 0)  /* fixed number of arguments? */\n          L->top.p = ra + b;  /* top signals number of arguments */\n        /* else previous instruction set top */\n        savepc(ci);  /* in case of errors */\n        if ((newci = luaD_precall(L, ra, nresults)) == NULL)\n          updatetrap(ci);  /* C call; nothing else to be done */\n        else {  /* Lua call: run function in this same C frame */\n          ci = newci;\n          goto startfunc;\n        }\n        vmbreak;\n      }\n      vmcase(OP_TAILCALL) {\n        StkId ra = RA(i);\n        int b = GETARG_B(i);  /* number of arguments + 1 (function) */\n        int n;  /* number of results when calling a C function */\n        int nparams1 = GETARG_C(i);\n        /* delta is virtual 'func' - real 'func' (vararg functions) */\n        int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0;\n        if (b != 0)\n          L->top.p = ra + b;\n        else  /* previous instruction set top */\n          b = cast_int(L->top.p - ra);\n        savepc(ci);  /* several calls here can raise errors */\n        if (TESTARG_k(i)) {\n          luaF_closeupval(L, base);  /* close upvalues from current call */\n          lua_assert(L->tbclist.p < base);  /* no pending tbc variables */\n          lua_assert(base == ci->func.p + 1);\n        }\n        if ((n = luaD_pretailcall(L, ci, ra, b, delta)) < 0)  /* Lua function? */\n          goto startfunc;  /* execute the callee */\n        else {  /* C function? */\n          ci->func.p -= delta;  /* restore 'func' (if vararg) */\n          luaD_poscall(L, ci, n);  /* finish caller */\n          updatetrap(ci);  /* 'luaD_poscall' can change hooks */\n          goto ret;  /* caller returns after the tail call */\n        }\n      }\n      vmcase(OP_RETURN) {\n        StkId ra = RA(i);\n        int n = GETARG_B(i) - 1;  /* number of results */\n        int nparams1 = GETARG_C(i);\n        if (n < 0)  /* not fixed? */\n          n = cast_int(L->top.p - ra);  /* get what is available */\n        savepc(ci);\n        if (TESTARG_k(i)) {  /* may there be open upvalues? */\n          ci->u2.nres = n;  /* save number of returns */\n          if (L->top.p < ci->top.p)\n            L->top.p = ci->top.p;\n          luaF_close(L, base, CLOSEKTOP, 1);\n          updatetrap(ci);\n          updatestack(ci);\n        }\n        if (nparams1)  /* vararg function? */\n          ci->func.p -= ci->u.l.nextraargs + nparams1;\n        L->top.p = ra + n;  /* set call for 'luaD_poscall' */\n        luaD_poscall(L, ci, n);\n        updatetrap(ci);  /* 'luaD_poscall' can change hooks */\n        goto ret;\n      }\n      vmcase(OP_RETURN0) {\n        if (l_unlikely(L->hookmask)) {\n          StkId ra = RA(i);\n          L->top.p = ra;\n          savepc(ci);\n          luaD_poscall(L, ci, 0);  /* no hurry... */\n          trap = 1;\n        }\n        else {  /* do the 'poscall' here */\n          int nres = get_nresults(ci->callstatus);\n          L->ci = ci->previous;  /* back to caller */\n          L->top.p = base - 1;\n          for (; l_unlikely(nres > 0); nres--)\n            setnilvalue(s2v(L->top.p++));  /* all results are nil */\n        }\n        goto ret;\n      }\n      vmcase(OP_RETURN1) {\n        if (l_unlikely(L->hookmask)) {\n          StkId ra = RA(i);\n          L->top.p = ra + 1;\n          savepc(ci);\n          luaD_poscall(L, ci, 1);  /* no hurry... */\n          trap = 1;\n        }\n        else {  /* do the 'poscall' here */\n          int nres = get_nresults(ci->callstatus);\n          L->ci = ci->previous;  /* back to caller */\n          if (nres == 0)\n            L->top.p = base - 1;  /* asked for no results */\n          else {\n            StkId ra = RA(i);\n            setobjs2s(L, base - 1, ra);  /* at least this result */\n            L->top.p = base;\n            for (; l_unlikely(nres > 1); nres--)\n              setnilvalue(s2v(L->top.p++));  /* complete missing results */\n          }\n        }\n       ret:  /* return from a Lua function */\n        if (ci->callstatus & CIST_FRESH)\n          return;  /* end this frame */\n        else {\n          ci = ci->previous;\n          goto returning;  /* continue running caller in this frame */\n        }\n      }\n      vmcase(OP_FORLOOP) {\n        StkId ra = RA(i);\n        if (ttisinteger(s2v(ra + 1))) {  /* integer loop? */\n          lua_Unsigned count = l_castS2U(ivalue(s2v(ra)));\n          if (count > 0) {  /* still more iterations? */\n            lua_Integer step = ivalue(s2v(ra + 1));\n            lua_Integer idx = ivalue(s2v(ra + 2));  /* control variable */\n            chgivalue(s2v(ra), l_castU2S(count - 1));  /* update counter */\n            idx = intop(+, idx, step);  /* add step to index */\n            chgivalue(s2v(ra + 2), idx);  /* update control variable */\n            pc -= GETARG_Bx(i);  /* jump back */\n          }\n        }\n        else if (floatforloop(ra))  /* float loop */\n          pc -= GETARG_Bx(i);  /* jump back */\n        updatetrap(ci);  /* allows a signal to break the loop */\n        vmbreak;\n      }\n      vmcase(OP_FORPREP) {\n        StkId ra = RA(i);\n        savestate(L, ci);  /* in case of errors */\n        if (forprep(L, ra))\n          pc += GETARG_Bx(i) + 1;  /* skip the loop */\n        vmbreak;\n      }\n      vmcase(OP_TFORPREP) {\n       /* before: 'ra' has the iterator function, 'ra + 1' has the state,\n          'ra + 2' has the initial value for the control variable, and\n          'ra + 3' has the closing variable. This opcode then swaps the\n          control and the closing variables and marks the closing variable\n          as to-be-closed.\n       */\n       StkId ra = RA(i);\n       TValue temp;  /* to swap control and closing variables */\n       setobj(L, &temp, s2v(ra + 3));\n       setobjs2s(L, ra + 3, ra + 2);\n       setobj2s(L, ra + 2, &temp);\n        /* create to-be-closed upvalue (if closing var. is not nil) */\n        halfProtect(luaF_newtbcupval(L, ra + 2));\n        pc += GETARG_Bx(i);  /* go to end of the loop */\n        i = *(pc++);  /* fetch next instruction */\n        lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i));\n        goto l_tforcall;\n      }\n      vmcase(OP_TFORCALL) {\n       l_tforcall: {\n        /* 'ra' has the iterator function, 'ra + 1' has the state,\n           'ra + 2' has the closing variable, and 'ra + 3' has the control\n           variable. The call will use the stack starting at 'ra + 3',\n           so that it preserves the first three values, and the first\n           return will be the new value for the control variable.\n        */\n        StkId ra = RA(i);\n        setobjs2s(L, ra + 5, ra + 3);  /* copy the control variable */\n        setobjs2s(L, ra + 4, ra + 1);  /* copy state */\n        setobjs2s(L, ra + 3, ra);  /* copy function */\n        L->top.p = ra + 3 + 3;\n        ProtectNT(luaD_call(L, ra + 3, GETARG_C(i)));  /* do the call */\n        updatestack(ci);  /* stack may have changed */\n        i = *(pc++);  /* go to next instruction */\n        lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i));\n        goto l_tforloop;\n      }}\n      vmcase(OP_TFORLOOP) {\n       l_tforloop: {\n        StkId ra = RA(i);\n        if (!ttisnil(s2v(ra + 3)))  /* continue loop? */\n          pc -= GETARG_Bx(i);  /* jump back */\n        vmbreak;\n      }}\n      vmcase(OP_SETLIST) {\n        StkId ra = RA(i);\n        unsigned n = cast_uint(GETARG_vB(i));\n        unsigned last = cast_uint(GETARG_vC(i));\n        Table *h = hvalue(s2v(ra));\n        if (n == 0)\n          n = cast_uint(L->top.p - ra) - 1;  /* get up to the top */\n        else\n          L->top.p = ci->top.p;  /* correct top in case of emergency GC */\n        last += n;\n        if (TESTARG_k(i)) {\n          last += cast_uint(GETARG_Ax(*pc)) * (MAXARG_vC + 1);\n          pc++;\n        }\n        /* when 'n' is known, table should have proper size */\n        if (last > h->asize) {  /* needs more space? */\n          /* fixed-size sets should have space preallocated */\n          lua_assert(GETARG_vB(i) == 0);\n          luaH_resizearray(L, h, last);  /* preallocate it at once */\n        }\n        for (; n > 0; n--) {\n          TValue *val = s2v(ra + n);\n          obj2arr(h, last - 1, val);\n          last--;\n          luaC_barrierback(L, obj2gco(h), val);\n        }\n        vmbreak;\n      }\n      vmcase(OP_CLOSURE) {\n        StkId ra = RA(i);\n        Proto *p = cl->p->p[GETARG_Bx(i)];\n        halfProtect(pushclosure(L, p, cl->upvals, base, ra));\n        checkGC(L, ra + 1);\n        vmbreak;\n      }\n      vmcase(OP_VARARG) {\n        StkId ra = RA(i);\n        int n = GETARG_C(i) - 1;  /* required results (-1 means all) */\n        int vatab = GETARG_k(i) ? GETARG_B(i) : -1;\n        Protect(luaT_getvarargs(L, ci, ra, n, vatab));\n        vmbreak;\n      }\n      vmcase(OP_GETVARG) {\n        StkId ra = RA(i);\n        TValue *rc = vRC(i);\n        luaT_getvararg(ci, ra, rc);\n        vmbreak;\n      }\n      vmcase(OP_ERRNNIL) {\n        TValue *ra = vRA(i);\n        if (!ttisnil(ra))\n          halfProtect(luaG_errnnil(L, cl, GETARG_Bx(i)));\n        vmbreak;\n      }\n      vmcase(OP_VARARGPREP) {\n        ProtectNT(luaT_adjustvarargs(L, ci, cl->p));\n        if (l_unlikely(trap)) {  /* previous \"Protect\" updated trap */\n          luaD_hookcall(L, ci);\n          L->oldpc = 1;  /* next opcode will be seen as a \"new\" line */\n        }\n        updatebase(ci);  /* function has new base after adjustment */\n        vmbreak;\n      }\n      vmcase(OP_EXTRAARG) {\n        lua_assert(0);\n        vmbreak;\n      }\n    }\n  }\n}\n\n/* }================================================================== */\n"
  },
  {
    "path": "3rd/lua/lvm.h",
    "content": "/*\n** $Id: lvm.h $\n** Lua virtual machine\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lvm_h\n#define lvm_h\n\n\n#include \"ldo.h\"\n#include \"lobject.h\"\n#include \"ltm.h\"\n\n\n#if !defined(LUA_NOCVTN2S)\n#define cvt2str(o)\tttisnumber(o)\n#else\n#define cvt2str(o)\t0\t/* no conversion from numbers to strings */\n#endif\n\n\n#if !defined(LUA_NOCVTS2N)\n#define cvt2num(o)\tttisstring(o)\n#else\n#define cvt2num(o)\t0\t/* no conversion from strings to numbers */\n#endif\n\n\n/*\n** You can define LUA_FLOORN2I if you want to convert floats to integers\n** by flooring them (instead of raising an error if they are not\n** integral values)\n*/\n#if !defined(LUA_FLOORN2I)\n#define LUA_FLOORN2I\t\tF2Ieq\n#endif\n\n\n/*\n** Rounding modes for float->integer coercion\n */\ntypedef enum {\n  F2Ieq,     /* no rounding; accepts only integral values */\n  F2Ifloor,  /* takes the floor of the number */\n  F2Iceil    /* takes the ceiling of the number */\n} F2Imod;\n\n\n/* convert an object to a float (including string coercion) */\n#define tonumber(o,n) \\\n\t(ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n))\n\n\n/* convert an object to a float (without string coercion) */\n#define tonumberns(o,n) \\\n\t(ttisfloat(o) ? ((n) = fltvalue(o), 1) : \\\n\t(ttisinteger(o) ? ((n) = cast_num(ivalue(o)), 1) : 0))\n\n\n/* convert an object to an integer (including string coercion) */\n#define tointeger(o,i) \\\n  (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \\\n                          : luaV_tointeger(o,i,LUA_FLOORN2I))\n\n\n/* convert an object to an integer (without string coercion) */\n#define tointegerns(o,i) \\\n  (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \\\n                          : luaV_tointegerns(o,i,LUA_FLOORN2I))\n\n\n#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2))\n\n#define luaV_rawequalobj(t1,t2)\t\tluaV_equalobj(NULL,t1,t2)\n\n\n/*\n** fast track for 'gettable'\n*/\n#define luaV_fastget(t,k,res,f, tag) \\\n  (tag = (!ttistable(t) ? LUA_VNOTABLE : f(hvalue(t), k, res)))\n\n\n/*\n** Special case of 'luaV_fastget' for integers, inlining the fast case\n** of 'luaH_getint'.\n*/\n#define luaV_fastgeti(t,k,res,tag) \\\n  if (!ttistable(t)) tag = LUA_VNOTABLE; \\\n  else { luaH_fastgeti(hvalue(t), k, res, tag); }\n\n\n#define luaV_fastset(t,k,val,hres,f) \\\n  (hres = ((!ttistable(t) || isshared(hvalue(t))) ? HNOTATABLE : f(hvalue(t), k, val)))\n\n#define luaV_fastseti(t,k,val,hres) \\\n  if (!ttistable(t) || isshared(hvalue(t))) hres = HNOTATABLE; \\\n  else { luaH_fastseti(hvalue(t), k, val, hres); }\n\n\n/*\n** Finish a fast set operation (when fast set succeeds).\n*/\n#define luaV_finishfastset(L,t,v)\tluaC_barrierback(L, gcvalue(t), v)\n\n\n/*\n** Shift right is the same as shift left with a negative 'y'\n*/\n#define luaV_shiftr(x,y)\tluaV_shiftl(x,intop(-, 0, y))\n\n\n\nLUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2);\nLUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);\nLUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);\nLUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n);\nLUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode);\nLUAI_FUNC int luaV_tointegerns (const TValue *obj, lua_Integer *p,\n                                F2Imod mode);\nLUAI_FUNC int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode);\nLUAI_FUNC lu_byte luaV_finishget (lua_State *L, const TValue *t, TValue *key,\n                                                StkId val, lu_byte tag);\nLUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key,\n                                             TValue *val, int aux);\nLUAI_FUNC void luaV_finishOp (lua_State *L);\nLUAI_FUNC void luaV_execute (lua_State *L, CallInfo *ci);\nLUAI_FUNC void luaV_concat (lua_State *L, int total);\nLUAI_FUNC lua_Integer luaV_idiv (lua_State *L, lua_Integer x, lua_Integer y);\nLUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y);\nLUAI_FUNC lua_Number luaV_modf (lua_State *L, lua_Number x, lua_Number y);\nLUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y);\nLUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb);\n\n#endif\n"
  },
  {
    "path": "3rd/lua/lzio.c",
    "content": "/*\n** $Id: lzio.c $\n** Buffered streams\n** See Copyright Notice in lua.h\n*/\n\n#define lzio_c\n#define LUA_CORE\n\n#include \"lprefix.h\"\n\n\n#include <string.h>\n\n#include \"lua.h\"\n\n#include \"lapi.h\"\n#include \"llimits.h\"\n#include \"lmem.h\"\n#include \"lstate.h\"\n#include \"lzio.h\"\n\n\nint luaZ_fill (ZIO *z) {\n  size_t size;\n  lua_State *L = z->L;\n  const char *buff;\n  lua_unlock(L);\n  buff = z->reader(L, z->data, &size);\n  lua_lock(L);\n  if (buff == NULL || size == 0)\n    return EOZ;\n  z->n = size - 1;  /* discount char being returned */\n  z->p = buff;\n  return cast_uchar(*(z->p++));\n}\n\n\nvoid luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {\n  z->L = L;\n  z->reader = reader;\n  z->data = data;\n  z->n = 0;\n  z->p = NULL;\n}\n\n\n/* --------------------------------------------------------------- read --- */\n\nstatic int checkbuffer (ZIO *z) {\n  if (z->n == 0) {  /* no bytes in buffer? */\n    if (luaZ_fill(z) == EOZ)  /* try to read more */\n      return 0;  /* no more input */\n    else {\n      z->n++;  /* luaZ_fill consumed first byte; put it back */\n      z->p--;\n    }\n  }\n  return 1;  /* now buffer has something */\n}\n\n\nsize_t luaZ_read (ZIO *z, void *b, size_t n) {\n  while (n) {\n    size_t m;\n    if (!checkbuffer(z))\n      return n;  /* no more input; return number of missing bytes */\n    m = (n <= z->n) ? n : z->n;  /* min. between n and z->n */\n    memcpy(b, z->p, m);\n    z->n -= m;\n    z->p += m;\n    b = (char *)b + m;\n    n -= m;\n  }\n  return 0;\n}\n\n\nconst void *luaZ_getaddr (ZIO* z, size_t n) {\n  const void *res;\n  if (!checkbuffer(z))\n    return NULL;  /* no more input */\n  if (z->n < n)  /* not enough bytes? */\n    return NULL;  /* block not whole; cannot give an address */\n  res = z->p;  /* get block address */\n  z->n -= n;  /* consume these bytes */\n  z->p += n;\n  return res;\n}\n"
  },
  {
    "path": "3rd/lua/lzio.h",
    "content": "/*\n** $Id: lzio.h $\n** Buffered streams\n** See Copyright Notice in lua.h\n*/\n\n\n#ifndef lzio_h\n#define lzio_h\n\n#include \"lua.h\"\n\n#include \"lmem.h\"\n\n\n#define EOZ\t(-1)\t\t\t/* end of stream */\n\ntypedef struct Zio ZIO;\n\n#define zgetc(z)  (((z)->n--)>0 ?  cast_uchar(*(z)->p++) : luaZ_fill(z))\n\n\ntypedef struct Mbuffer {\n  char *buffer;\n  size_t n;\n  size_t buffsize;\n} Mbuffer;\n\n#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0)\n\n#define luaZ_buffer(buff)\t((buff)->buffer)\n#define luaZ_sizebuffer(buff)\t((buff)->buffsize)\n#define luaZ_bufflen(buff)\t((buff)->n)\n\n#define luaZ_buffremove(buff,i)\t((buff)->n -= cast_sizet(i))\n#define luaZ_resetbuffer(buff) ((buff)->n = 0)\n\n\n#define luaZ_resizebuffer(L, buff, size) \\\n\t((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \\\n\t\t\t\t(buff)->buffsize, size), \\\n\t(buff)->buffsize = size)\n\n#define luaZ_freebuffer(L, buff)\tluaZ_resizebuffer(L, buff, 0)\n\n\nLUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,\n                                        void *data);\nLUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n);\t/* read next n bytes */\n\nLUAI_FUNC const void *luaZ_getaddr (ZIO* z, size_t n);\n\n\n/* --------- Private Part ------------------ */\n\nstruct Zio {\n  size_t n;\t\t\t/* bytes still unread */\n  const char *p;\t\t/* current position in buffer */\n  lua_Reader reader;\t\t/* reader function */\n  void *data;\t\t\t/* additional data */\n  lua_State *L;\t\t\t/* Lua state (for reader) */\n};\n\n\nLUAI_FUNC int luaZ_fill (ZIO *z);\n\n#endif\n"
  },
  {
    "path": "3rd/lua/makefile",
    "content": "# Makefile for building Lua\n# See ../doc/readme.html for installation and customization instructions.\n\n# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================\n\n# Your platform. See PLATS for possible values.\nPLAT= guess\n\nCC= gcc -std=gnu99\nCFLAGS= -O2 -Wall -Wextra $(SYSCFLAGS) $(MYCFLAGS)\nLDFLAGS= $(SYSLDFLAGS) $(MYLDFLAGS)\nLIBS= -lm $(SYSLIBS) $(MYLIBS)\n\nAR= ar rcu\nRANLIB= ranlib\nRM= rm -f\nUNAME= uname\n\nSYSCFLAGS=\nSYSLDFLAGS=\nSYSLIBS=\n\nMYCFLAGS= -I../../skynet-src -g\nMYLDFLAGS=\nMYLIBS=\nMYOBJS=\n\n# Special flags for compiler modules; -Os reduces code size.\nCMCFLAGS= \n\n# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======\n\nPLATS= guess aix bsd c89 freebsd generic ios linux macosx mingw posix solaris\n\nLUA_A=\tliblua.a\nCORE_O=\tlapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o\nLIB_O=\tlauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o\nBASE_O= $(CORE_O) $(LIB_O) $(MYOBJS)\n\nLUA_T=\tlua\nLUA_O=\tlua.o\n\nLUAC_T=\tluac\nLUAC_O=\tluac.o\n\nALL_O= $(BASE_O) $(LUA_O) $(LUAC_O)\nALL_T= $(LUA_A) $(LUA_T) $(LUAC_T)\nALL_A= $(LUA_A)\n\n# Targets start here.\ndefault: $(PLAT)\n\nall:\t$(ALL_T)\n\no:\t$(ALL_O)\n\na:\t$(ALL_A)\n\n$(LUA_A): $(BASE_O)\n\t$(AR) $@ $(BASE_O)\n\t$(RANLIB) $@\n\n$(LUA_T): $(LUA_O) $(LUA_A)\n\t$(CC) -o $@ $(LDFLAGS) $(LUA_O) $(LUA_A) $(LIBS)\n\n$(LUAC_T): $(LUAC_O) $(LUA_A)\n\t$(CC) -o $@ $(LDFLAGS) $(LUAC_O) $(LUA_A) $(LIBS)\n\ntest:\n\t./$(LUA_T) -v\n\nclean:\n\t$(RM) $(ALL_T) $(ALL_O)\n\ndepend:\n\t@$(CC) $(CFLAGS) -MM l*.c\n\necho:\n\t@echo \"PLAT= $(PLAT)\"\n\t@echo \"CC= $(CC)\"\n\t@echo \"CFLAGS= $(CFLAGS)\"\n\t@echo \"LDFLAGS= $(LDFLAGS)\"\n\t@echo \"LIBS= $(LIBS)\"\n\t@echo \"AR= $(AR)\"\n\t@echo \"RANLIB= $(RANLIB)\"\n\t@echo \"RM= $(RM)\"\n\t@echo \"UNAME= $(UNAME)\"\n\n# Convenience targets for popular platforms.\nALL= all\n\nhelp:\n\t@echo \"Do 'make PLATFORM' where PLATFORM is one of these:\"\n\t@echo \"   $(PLATS)\"\n\t@echo \"See doc/readme.html for complete instructions.\"\n\nguess:\n\t@echo Guessing `$(UNAME)`\n\t@$(MAKE) `$(UNAME)`\n\nAIX aix:\n\t$(MAKE) $(ALL) CC=\"xlc\" CFLAGS=\"-O2 -DLUA_USE_POSIX -DLUA_USE_DLOPEN\" SYSLIBS=\"-ldl\" SYSLDFLAGS=\"-brtl -bexpall\"\n\nbsd:\n\t$(MAKE) $(ALL) SYSCFLAGS=\"-DLUA_USE_POSIX -DLUA_USE_DLOPEN\" SYSLIBS=\"-Wl,-E\"\n\nc89:\n\t$(MAKE) $(ALL) SYSCFLAGS=\"-DLUA_USE_C89\" CC=\"gcc -std=c89\"\n\t@echo ''\n\t@echo '*** C89 does not guarantee 64-bit integers for Lua.'\n\t@echo '*** Make sure to compile all external Lua libraries'\n\t@echo '*** with LUA_USE_C89 to ensure consistency'\n\t@echo ''\n\nFreeBSD NetBSD OpenBSD freebsd:\n\t$(MAKE) $(ALL) SYSCFLAGS=\"-DLUA_USE_LINUX -DLUA_USE_READLINE -I/usr/include/edit\" SYSLIBS=\"-Wl,-E -ledit\" CC=\"cc\"\n\ngeneric: $(ALL)\n\nios:\n\t$(MAKE) $(ALL) SYSCFLAGS=\"-DLUA_USE_IOS\"\n\nLinux linux:\n\t$(MAKE) $(ALL) SYSCFLAGS=\"-DLUA_USE_LINUX\" SYSLIBS=\"-Wl,-E -ldl\"\n\nDarwin macos macosx:\n\t$(MAKE) $(ALL) SYSCFLAGS=\"-DLUA_USE_MACOSX -DLUA_USE_READLINE\" SYSLIBS=\"-lreadline\"\n\nmingw:\n\t$(MAKE) \"LUA_A=lua54.dll\" \"LUA_T=lua.exe\" \\\n\t\"AR=$(CC) -shared -o\" \"RANLIB=strip --strip-unneeded\" \\\n\t\"SYSCFLAGS=-DLUA_BUILD_AS_DLL\" \"SYSLIBS=\" \"SYSLDFLAGS=-s\" lua.exe\n\t$(MAKE) \"LUAC_T=luac.exe\" luac.exe\n\nposix:\n\t$(MAKE) $(ALL) SYSCFLAGS=\"-DLUA_USE_POSIX\"\n\nSunOS solaris:\n\t$(MAKE) $(ALL) SYSCFLAGS=\"-DLUA_USE_POSIX -DLUA_USE_DLOPEN -D_REENTRANT\" SYSLIBS=\"-ldl\"\n\n# Targets that do not create files (not all makes understand .PHONY).\n.PHONY: all $(PLATS) help test clean default o a depend echo\n\n# Compiler modules may use special flags.\nllex.o:\n\t$(CC) $(CFLAGS) $(CMCFLAGS) -c llex.c\n\nlparser.o:\n\t$(CC) $(CFLAGS) $(CMCFLAGS) -c lparser.c\n\nlcode.o:\n\t$(CC) $(CFLAGS) $(CMCFLAGS) -c lcode.c\n\n# DO NOT DELETE\n\nlapi.o: lapi.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \\\n lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h \\\n ltable.h lundump.h lvm.h\nlauxlib.o: lauxlib.c lprefix.h lua.h luaconf.h lauxlib.h llimits.h\nlbaselib.o: lbaselib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \\\n llimits.h\nlcode.o: lcode.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \\\n llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \\\n ldo.h lgc.h lstring.h ltable.h lvm.h lopnames.h\nlcorolib.o: lcorolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \\\n llimits.h\nlctype.o: lctype.c lprefix.h lctype.h lua.h luaconf.h llimits.h\nldblib.o: ldblib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h llimits.h\nldebug.o: ldebug.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \\\n lobject.h ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h \\\n ldebug.h ldo.h lfunc.h lstring.h lgc.h ltable.h lvm.h\nldo.o: ldo.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \\\n lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h \\\n lparser.h lstring.h ltable.h lundump.h lvm.h\nldump.o: ldump.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \\\n lobject.h ltm.h lzio.h lmem.h lgc.h ltable.h lundump.h\nlfunc.o: lfunc.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \\\n llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h\nlgc.o: lgc.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \\\n llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h\nlinit.o: linit.c lprefix.h lua.h luaconf.h lualib.h lauxlib.h llimits.h\nliolib.o: liolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h llimits.h\nllex.o: llex.c lprefix.h lua.h luaconf.h lctype.h llimits.h ldebug.h \\\n lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lgc.h llex.h lparser.h \\\n lstring.h ltable.h\nlmathlib.o: lmathlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \\\n llimits.h\nlmem.o: lmem.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \\\n llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h\nloadlib.o: loadlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \\\n llimits.h\nlobject.o: lobject.c lprefix.h lua.h luaconf.h lctype.h llimits.h \\\n ldebug.h lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h \\\n lvm.h\nlopcodes.o: lopcodes.c lprefix.h lopcodes.h llimits.h lua.h luaconf.h \\\n lobject.h\nloslib.o: loslib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h llimits.h\nlparser.o: lparser.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \\\n llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \\\n ldo.h lfunc.h lstring.h lgc.h ltable.h\nlstate.o: lstate.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \\\n lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h \\\n lstring.h ltable.h\nlstring.o: lstring.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \\\n lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h\nlstrlib.o: lstrlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \\\n llimits.h\nltable.o: ltable.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \\\n llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h\nltablib.o: ltablib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \\\n llimits.h\nltm.o: ltm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \\\n llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h\nlua.o: lua.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h llimits.h\nluac.o: luac.c lprefix.h lua.h luaconf.h lauxlib.h lapi.h llimits.h \\\n lstate.h lobject.h ltm.h lzio.h lmem.h ldebug.h lopcodes.h lopnames.h \\\n lundump.h\nlundump.o: lundump.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \\\n lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h \\\n ltable.h lundump.h\nlutf8lib.o: lutf8lib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \\\n llimits.h\nlvm.o: lvm.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \\\n lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h \\\n lstring.h ltable.h lvm.h ljumptab.h\nlzio.o: lzio.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \\\n lobject.h ltm.h lzio.h lmem.h\n\n# (end of Makefile)\n"
  },
  {
    "path": "3rd/lua/onelua.c",
    "content": "/*\n** Lua core, libraries, and interpreter in a single file.\n** Compiling just this file generates a complete Lua stand-alone\n** program:\n**\n** $ gcc -O2 -std=c99 -o lua onelua.c -lm\n**\n** or (for C89)\n**\n** $ gcc -O2 -std=c89 -DLUA_USE_C89 -o lua onelua.c -lm\n**\n** or (for Linux)\n**\n** gcc -O2 -o lua -DLUA_USE_LINUX -Wl,-E onelua.c -lm -ldl\n**\n*/\n\n/* default is to build the full interpreter */\n#ifndef MAKE_LIB\n#ifndef MAKE_LUAC\n#ifndef MAKE_LUA\n#define MAKE_LUA\n#endif\n#endif\n#endif\n\n\n/*\n** Choose suitable platform-specific features. Default is no\n** platform-specific features. Some of these options may need extra\n** libraries such as -ldl -lreadline -lncurses\n*/\n#if 0\n#define LUA_USE_LINUX\n#define LUA_USE_MACOSX\n#define LUA_USE_POSIX\n#endif\n\n\n/*\n** Other specific features\n*/\n#if 0\n#define LUA_32BITS\n#define LUA_USE_C89\n#endif\n\n\n/* no need to change anything below this line ----------------------------- */\n\n#include \"lprefix.h\"\n\n#include <assert.h>\n#include <ctype.h>\n#include <errno.h>\n#include <float.h>\n#include <limits.h>\n#include <locale.h>\n#include <math.h>\n#include <setjmp.h>\n#include <signal.h>\n#include <stdarg.h>\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\n/* setup for luaconf.h */\n#define LUA_CORE\n#define LUA_LIB\n\n#include \"luaconf.h\"\n\n/* do not export internal symbols */\n#undef LUAI_FUNC\n#undef LUAI_DDEC\n#undef LUAI_DDEF\n#define LUAI_FUNC\tstatic\n#define LUAI_DDEC(def)\t/* empty */\n#define LUAI_DDEF\tstatic\n\n/* core -- used by all */\n#include \"lzio.c\"\n#include \"lctype.c\"\n#include \"lopcodes.c\"\n#include \"lmem.c\"\n#include \"lundump.c\"\n#include \"ldump.c\"\n#include \"lstate.c\"\n#include \"lgc.c\"\n#include \"llex.c\"\n#include \"lcode.c\"\n#include \"lparser.c\"\n#include \"ldebug.c\"\n#include \"lfunc.c\"\n#include \"lobject.c\"\n#include \"ltm.c\"\n#include \"lstring.c\"\n#include \"ltable.c\"\n#include \"ldo.c\"\n#include \"lvm.c\"\n#include \"lapi.c\"\n\n/* auxiliary library -- used by all */\n#include \"lauxlib.c\"\n\n/* standard library  -- not used by luac */\n#ifndef MAKE_LUAC\n#include \"lbaselib.c\"\n#include \"lcorolib.c\"\n#include \"ldblib.c\"\n#include \"liolib.c\"\n#include \"lmathlib.c\"\n#include \"loadlib.c\"\n#include \"loslib.c\"\n#include \"lstrlib.c\"\n#include \"ltablib.c\"\n#include \"lutf8lib.c\"\n#include \"linit.c\"\n#endif\n\n/* test library -- used only for internal development */\n#if defined(LUA_DEBUG)\n#include \"ltests.c\"\n#endif\n\n/* lua */\n#ifdef MAKE_LUA\n#include \"lua.c\"\n#endif\n\n/* luac */\n#ifdef MAKE_LUAC\n#include \"luac.c\"\n#endif\n"
  },
  {
    "path": "3rd/lua-md5/README",
    "content": "MD5 - Cryptographic Library for Lua\nCopyright 2003 PUC-Rio\nhttp://www.keplerproject.org/md5\n\nMD5 offers basic cryptographic facilities for Lua 5.1: a hash (digest)\nfunction, a pair crypt/decrypt based on MD5 and CFB, and a pair crypt/decrypt based\non DES with 56-bit keys.\n\nMD5 current version is 1.1.2.\n\nThis version is copy from https://github.com/keplerproject/md5\n\n"
  },
  {
    "path": "3rd/lua-md5/compat-5.2.c",
    "content": "#include \"lua.h\"\n#include \"lauxlib.h\"\n#include \"compat-5.2.h\"\n\n#if !defined LUA_VERSION_NUM || LUA_VERSION_NUM==501\n/*\n** Adapted from Lua 5.2.0\n*/\nvoid luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {\n  luaL_checkstack(L, nup+1, \"too many upvalues\");\n  for (; l->name != NULL; l++) {  /* fill the table with given functions */\n    int i;\n    lua_pushstring(L, l->name);\n    for (i = 0; i < nup; i++)  /* copy upvalues to the top */\n      lua_pushvalue(L, -(nup + 1));\n    lua_pushcclosure(L, l->func, nup);  /* closure with those upvalues */\n    lua_settable(L, -(nup + 3)); /* table must be below the upvalues, the name and the closure */\n  }\n  lua_pop(L, nup);  /* remove upvalues */\n}\n#endif\n"
  },
  {
    "path": "3rd/lua-md5/compat-5.2.h",
    "content": "#if !defined LUA_VERSION_NUM\n/* Lua 5.0 */\n#define luaL_Reg luaL_reg\n\n#define luaL_addchar(B,c) \\\n  ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \\\n   (*(B)->p++ = (char)(c)))\n#endif\n\n#if LUA_VERSION_NUM==501\n/* Lua 5.1 */\n#define lua_rawlen lua_objlen\n#endif\n\nvoid luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);\n"
  },
  {
    "path": "3rd/lua-md5/md5.c",
    "content": "/**\n*  $Id: md5.c,v 1.2 2008/03/24 20:59:12 mascarenhas Exp $\n*  Hash function MD5\n*  @author  Marcela Ozorio Suarez, Roberto I.\n*/\n\n\n#include <string.h>\n\n#include \"md5.h\"\n\n\n#define WORD 32\n#define MASK 0xFFFFFFFF\n#if __STDC_VERSION__ >= 199901L\n#include <stdint.h>\ntypedef uint32_t WORD32;\n#else\ntypedef unsigned int WORD32;\n#endif\n\n\n/**\n*  md5 hash function.\n*  @param message: aribtary string.\n*  @param len: message length.\n*  @param output: buffer to receive the hash value. Its size must be\n*  (at least) HASHSIZE.\n*/\nvoid md5 (const char *message, long len, char *output);\n\n\n\n/*\n** Realiza a rotacao no sentido horario dos bits da variavel 'D' do tipo WORD32.\n** Os bits sao deslocados de 'num' posicoes\n*/\n#define rotate(D, num)  (D<<num) | (D>>(WORD-num))\n\n/*Macros que definem operacoes relizadas pelo algoritmo  md5 */\n#define F(x, y, z) (((x) & (y)) | ((~(x)) & (z)))\n#define G(x, y, z) (((x) & (z)) | ((y) & (~(z))))\n#define H(x, y, z) ((x) ^ (y) ^ (z))\n#define I(x, y, z) ((y) ^ ((x) | (~(z))))\n\n\n/*vetor de numeros utilizados pelo algoritmo md5 para embaralhar bits */\nstatic const WORD32 T[64]={\n                     0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,\n                     0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\n                     0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,\n                     0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\n                     0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,\n                     0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\n                     0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,\n                     0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\n                     0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,\n                     0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\n                     0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,\n                     0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\n                     0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,\n                     0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n                     0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,\n                     0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391\n};\n\n\nstatic void word32tobytes (const WORD32 *input, char *output) {\n  int j = 0;\n  while (j<4*4) {\n    WORD32 v = *input++;\n    output[j++] = (char)(v & 0xff); v >>= 8;\n    output[j++] = (char)(v & 0xff); v >>= 8;\n    output[j++] = (char)(v & 0xff); v >>= 8;\n    output[j++] = (char)(v & 0xff);\n  }\n}\n\n\nstatic void inic_digest(WORD32 *d) {\n  d[0] = 0x67452301;\n  d[1] = 0xEFCDAB89;\n  d[2] = 0x98BADCFE;\n  d[3] = 0x10325476;\n}\n\n\n/*funcao que implemeta os quatro passos principais do algoritmo MD5 */\nstatic void digest(const WORD32 *m, WORD32 *d) {\n  int j;\n  /*MD5 PASSO1 */\n  for (j=0; j<4*4; j+=4) {\n    d[0] = d[0]+ F(d[1], d[2], d[3])+ m[j] + T[j];       d[0]=rotate(d[0], 7);\n    d[0]+=d[1];\n    d[3] = d[3]+ F(d[0], d[1], d[2])+ m[(j)+1] + T[j+1]; d[3]=rotate(d[3], 12);\n    d[3]+=d[0];\n    d[2] = d[2]+ F(d[3], d[0], d[1])+ m[(j)+2] + T[j+2]; d[2]=rotate(d[2], 17);\n    d[2]+=d[3];\n    d[1] = d[1]+ F(d[2], d[3], d[0])+ m[(j)+3] + T[j+3]; d[1]=rotate(d[1], 22);\n    d[1]+=d[2];\n  }\n  /*MD5 PASSO2 */\n  for (j=0; j<4*4; j+=4) {\n    d[0] = d[0]+ G(d[1], d[2], d[3])+ m[(5*j+1)&0x0f] + T[(j-1)+17];\n    d[0] = rotate(d[0],5);\n    d[0]+=d[1];\n    d[3] = d[3]+ G(d[0], d[1], d[2])+ m[((5*(j+1)+1)&0x0f)] + T[(j+0)+17];\n    d[3] = rotate(d[3], 9);\n    d[3]+=d[0];\n    d[2] = d[2]+ G(d[3], d[0], d[1])+ m[((5*(j+2)+1)&0x0f)] + T[(j+1)+17];\n    d[2] = rotate(d[2], 14);\n    d[2]+=d[3];\n    d[1] = d[1]+ G(d[2], d[3], d[0])+ m[((5*(j+3)+1)&0x0f)] + T[(j+2)+17];\n    d[1] = rotate(d[1], 20);\n    d[1]+=d[2];\n  }\n  /*MD5 PASSO3 */\n  for (j=0; j<4*4; j+=4) {\n    d[0] = d[0]+ H(d[1], d[2], d[3])+ m[(3*j+5)&0x0f] + T[(j-1)+33];\n    d[0] = rotate(d[0], 4);\n    d[0]+=d[1];\n    d[3] = d[3]+ H(d[0], d[1], d[2])+ m[(3*(j+1)+5)&0x0f] + T[(j+0)+33];\n    d[3] = rotate(d[3], 11);\n    d[3]+=d[0];\n    d[2] = d[2]+ H(d[3], d[0], d[1])+ m[(3*(j+2)+5)&0x0f] + T[(j+1)+33];\n    d[2] = rotate(d[2], 16);\n    d[2]+=d[3];\n    d[1] = d[1]+ H(d[2], d[3], d[0])+ m[(3*(j+3)+5)&0x0f] + T[(j+2)+33];\n    d[1] = rotate(d[1], 23);\n    d[1]+=d[2];\n  }\n  /*MD5 PASSO4 */\n  for (j=0; j<4*4; j+=4) {\n    d[0] = d[0]+ I(d[1], d[2], d[3])+ m[(7*j)&0x0f] + T[(j-1)+49];\n    d[0] = rotate(d[0], 6);\n    d[0]+=d[1];\n    d[3] = d[3]+ I(d[0], d[1], d[2])+ m[(7*(j+1))&0x0f] + T[(j+0)+49];\n    d[3] = rotate(d[3], 10);\n    d[3]+=d[0];\n    d[2] = d[2]+ I(d[3], d[0], d[1])+ m[(7*(j+2))&0x0f] + T[(j+1)+49];\n    d[2] = rotate(d[2], 15);\n    d[2]+=d[3];\n    d[1] = d[1]+ I(d[2], d[3], d[0])+ m[(7*(j+3))&0x0f] + T[(j+2)+49];\n    d[1] = rotate(d[1], 21);\n    d[1]+=d[2];\n  }\n}\n\n\nstatic void bytestoword32 (WORD32 *x, const char *pt) {\n  int i;\n  for (i=0; i<16; i++) {\n    int j=i*4;\n    x[i] = (((WORD32)(unsigned char)pt[j+3] << 8 |\n           (WORD32)(unsigned char)pt[j+2]) << 8 |\n           (WORD32)(unsigned char)pt[j+1]) << 8 |\n           (WORD32)(unsigned char)pt[j];\n  }\n\n}\n\n\nstatic void put_length(WORD32 *x, long len) {\n  /* in bits! */\n  x[14] = (WORD32)((len<<3) & MASK);\n  x[15] = (WORD32)(len>>(32-3) & 0x7);\n}\n\n\n/*\n** returned status:\n*  0 - normal message (full 64 bytes)\n*  1 - enough room for 0x80, but not for message length (two 4-byte words)\n*  2 - enough room for 0x80 plus message length (at least 9 bytes free)\n*/\nstatic int converte (WORD32 *x, const char *pt, int num, int old_status) {\n  int new_status = 0;\n  char buff[64];\n  if (num<64) {\n    memcpy(buff, pt, num);  /* to avoid changing original string */\n    memset(buff+num, 0, 64-num);\n    if (old_status == 0)\n      buff[num] = '\\200';\n    new_status = 1;\n    pt = buff;\n  }\n  bytestoword32(x, pt);\n  if (num <= (64 - 9))\n    new_status = 2;\n  return new_status;\n}\n\n\n\nvoid md5 (const char *message, long len, char *output) {\n  WORD32 d[4];\n  int status = 0;\n  long i = 0;\n  inic_digest(d);\n  while (status != 2) {\n    WORD32 d_old[4];\n    WORD32 wbuff[16];\n    int numbytes = (len-i >= 64) ? 64 : len-i;\n    /*salva os valores do vetor digest*/\n    d_old[0]=d[0]; d_old[1]=d[1]; d_old[2]=d[2]; d_old[3]=d[3];\n    status = converte(wbuff, message+i, numbytes, status);\n    if (status == 2) put_length(wbuff, len);\n    digest(wbuff, d);\n    d[0]+=d_old[0]; d[1]+=d_old[1]; d[2]+=d_old[2]; d[3]+=d_old[3];\n    i += numbytes;\n  }\n  word32tobytes(d, output);\n}\n\n"
  },
  {
    "path": "3rd/lua-md5/md5.h",
    "content": "/**\n*  $Id: md5.h,v 1.2 2006/03/03 15:04:49 tomas Exp $\n*  Cryptographic module for Lua.\n*  @author  Roberto Ierusalimschy\n*/\n\n\n#ifndef md5_h\n#define md5_h\n\n#include <lua.h>\n\n\n#define HASHSIZE       16\n\nvoid md5 (const char *message, long len, char *output);\nint luaopen_md5_core (lua_State *L);\n\n\n#endif\n"
  },
  {
    "path": "3rd/lua-md5/md5lib.c",
    "content": "/**\n*  $Id: md5lib.c,v 1.10 2008/05/12 20:51:27 carregal Exp $\n*  Cryptographic and Hash functions for Lua\n*  @author  Roberto Ierusalimschy\n*/\n\n\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\n#include <lua.h>\n#include <lauxlib.h>\n\n#include \"md5.h\"\n#include \"compat-5.2.h\"\n\n\n/**\n*  Hash function. Returns a hash for a given string.\n*  @param message: arbitrary binary string.\n*  @return  A 128-bit hash string.\n*/\nstatic int lmd5 (lua_State *L) {\n  char buff[16];\n  size_t l;\n  const char *message = luaL_checklstring(L, 1, &l);\n  md5(message, l, buff);\n  lua_pushlstring(L, buff, 16L);\n  return 1;\n}\n\n\n/**\n*  X-Or. Does a bit-a-bit exclusive-or of two strings.\n*  @param s1: arbitrary binary string.\n*  @param s2: arbitrary binary string with same length as s1.\n*  @return  a binary string with same length as s1 and s2,\n*   where each bit is the exclusive-or of the corresponding bits in s1-s2.\n*/\nstatic int ex_or (lua_State *L) {\n  size_t l1, l2;\n  const char *s1 = luaL_checklstring(L, 1, &l1);\n  const char *s2 = luaL_checklstring(L, 2, &l2);\n  luaL_Buffer b;\n  luaL_argcheck( L, l1 == l2, 2, \"lengths must be equal\" );\n  luaL_buffinit(L, &b);\n  while (l1--) luaL_addchar(&b, (*s1++)^(*s2++));\n  luaL_pushresult(&b);\n  return 1;\n}\n\n\nstatic void checkseed (lua_State *L) {\n  if (lua_isnone(L, 3)) {  /* no seed? */\n    time_t tm = time(NULL);  /* for `random' seed */\n    lua_pushlstring(L, (char *)&tm, sizeof(tm));\n  }\n}\n\n\n#define MAXKEY\t256\n#define BLOCKSIZE\t16\n\n\n\nstatic int initblock (lua_State *L, const char *seed, int lseed, char *block) {\n  size_t lkey;\n  const char *key = luaL_checklstring(L, 2, &lkey);\n  if (lkey > MAXKEY)\n    luaL_error(L, \"key too long (> %d)\", MAXKEY);\n  memset(block, 0, BLOCKSIZE);\n  memcpy(block, seed, lseed);\n  memcpy(block+BLOCKSIZE, key, lkey);\n  return (int)lkey+BLOCKSIZE;\n}\n\n\nstatic void codestream (lua_State *L, const char *msg, size_t lmsg,\n                                      char *block, int lblock) {\n  luaL_Buffer b;\n  luaL_buffinit(L, &b);\n  while (lmsg > 0) {\n    char code[BLOCKSIZE];\n    int i;\n    md5(block, lblock, code);\n    for (i=0; i<BLOCKSIZE && lmsg > 0; i++, lmsg--)\n      code[i] ^= *msg++;\n    luaL_addlstring(&b, code, i); \n    memcpy(block, code, i); /* update seed */\n  }\n  luaL_pushresult(&b);\n}\n\n\nstatic void decodestream (lua_State *L, const char *cypher, size_t lcypher,\n                          char *block, int lblock) {\n  luaL_Buffer b;\n  luaL_buffinit(L, &b);\n  while (lcypher > 0) {\n    char code[BLOCKSIZE];\n    int i;\n    md5(block, lblock, code);  /* update seed */\n    for (i=0; i<BLOCKSIZE && lcypher > 0; i++, lcypher--)\n      code[i] ^= *cypher++;\n    luaL_addlstring(&b, code, i); \n    memcpy(block, cypher-i, i);\n  }\n  luaL_pushresult(&b);\n}\n\n\n/**\n*  Encrypts a string. Uses the hash function md5 in CFB (Cipher-feedback\n*  mode).\n*  @param message: arbitrary binary string to be encrypted.\n*  @param key: arbitrary binary string to be used as a key.\n*  @param [seed]: optional arbitrary binary string to be used as a seed.\n*  if no seed is provided, the function uses the result of\n*  <code>time()</code> as a seed.  \n*  @return  The cyphertext (as a binary string).\n*/\nstatic int crypt (lua_State *L) {\n  size_t lmsg;\n  const char *msg = luaL_checklstring(L, 1, &lmsg);\n  size_t lseed;\n  const char *seed;\n  int lblock;\n  char block[BLOCKSIZE+MAXKEY];\n  checkseed(L);\n  seed = luaL_checklstring(L, 3, &lseed);\n  if (lseed > BLOCKSIZE)\n    luaL_error(L, \"seed too long (> %d)\", BLOCKSIZE);\n  /* put seed and seed length at the beginning of result */\n  block[0] = (char)lseed;\n  memcpy(block+1, seed, lseed);\n  lua_pushlstring(L, block, lseed+1);  /* to concat with result */\n  lblock = initblock(L, seed, lseed, block);\n  codestream(L, msg, lmsg, block, lblock);\n  lua_concat(L, 2);\n  return 1;\n}\n\n\n/**\n*  Decrypts a string. For any message, key, and seed, we have that\n*  <code>decrypt(crypt(msg, key, seed), key) == msg</code>.\n*  @param cyphertext: message to be decrypted (this must be the result of\n   a previous call to <code>crypt</code>.\n*  @param key: arbitrary binary string to be used as a key.\n*  @return  The plaintext.\n*/\nstatic int decrypt (lua_State *L) {\n  size_t lcyphertext;\n  const char *cyphertext = luaL_checklstring(L, 1, &lcyphertext);\n  size_t lseed = cyphertext[0];\n  const char *seed = cyphertext+1;\n  int lblock;\n  char block[BLOCKSIZE+MAXKEY];\n  luaL_argcheck(L, lcyphertext >= lseed+1 && lseed <= BLOCKSIZE, 1,\n                 \"invalid cyphered string\");\n  cyphertext += lseed+1;\n  lcyphertext -= lseed+1;\n  lblock = initblock(L, seed, lseed, block);\n  decodestream(L, cyphertext, lcyphertext, block, lblock);\n  return 1;\n}\n\n\n/*\n** Assumes the table is on top of the stack.\n*/\nstatic void set_info (lua_State *L) {\n\tlua_pushliteral (L, \"_COPYRIGHT\");\n\tlua_pushliteral (L, \"Copyright (C) 2003-2013 PUC-Rio\");\n\tlua_settable (L, -3);\n\tlua_pushliteral (L, \"_DESCRIPTION\");\n\tlua_pushliteral (L, \"Basic cryptographic facilities\");\n\tlua_settable (L, -3);\n\tlua_pushliteral (L, \"_VERSION\");\n\tlua_pushliteral (L, \"MD5 1.2\");\n\tlua_settable (L, -3);\n}\n\n\nstatic struct luaL_Reg md5lib[] = {\n  {\"sum\", lmd5},\n  {\"exor\", ex_or},\n  {\"crypt\", crypt},\n  {\"decrypt\", decrypt},\n  {NULL, NULL}\n};\n\n\nint luaopen_md5_core (lua_State *L) {\n  lua_newtable(L);\n  luaL_setfuncs(L, md5lib, 0);\n  set_info (L);\n  return 1;\n}\n"
  },
  {
    "path": "HISTORY.md",
    "content": "v1.8.0 (2025-1-14)\n-----------\n* Update Lua to 5.4.7\n* service sessions can be rewind\n* Improve: udp (ipv6 support)\n* Improve: debug console\n* Improve: http\n* Improve: mongo driver\n* Improve: mysql driver\n* Bugfix: socketchannel\n* Bugfix: cluster\n* Bugfix: ssl\n* Bugfix: websocket\n* Bugfix: redis cluster driver\n\nv1.7.0 (2023-11-13)\n-----------\n* Update Lua to 5.4.6\n* Update lpeg to 1.1.0\n* Improve mongo driver\n* Fix service session rewind issue\n* Add websocket.is_closed\n\nv1.6.0 (2022-11-16)\n-----------\n* Update Lua to 5.4.4 (github Nov 8, 2022)\n* Update jemalloc to 5.3.0\n* Update lpeg to 1.0.2 (For sproto)\n* Update mongo driver to support the newest wire protocol\n* socket.listen()/cluster.open() returns ip address and port\n* Add service.close()\n\nv1.5.0 (2021-11-9)\n-----------\n* Update Lua to 5.4.3\n* Fix socket half close issues\n* Fix TLS issues\n* Improve websocket support\n* Improve redis support\n* Rework skynet.init/skynet.require\n* Add socket.onclose\n* Add httpc.request_stream\n\nv1.4.0 (2020-11-16)\n-----------\n* Update Lua to 5.4.2\n* Add skynet.select\n* Improve mysql driver (@zero-rp @xiaojin @yxt945)\n* Improve websocket and ssl (@lvzixun)\n* Improve sproto (double @lvzixun map @t0350)\n* Add padding mode PKCS7 for DES\n* Add jmem in debug console\n* Add skynet_socket_pause for net traffic control\n* Add timestamp to default logger\n\nv1.3.0 (2019-11-19)\n-----------\n* Improve mysql driver (@yxt945)\n* Improve cluster\n* Improve lua shared proto (@hongling0)\n* Improve socket.write\n* Add lua sharetable\n* Add https support (@lvzixun)\n* Add websocket support (@lvzixun)\n* Fix bug in dns\n* Fix some memory leaks\n* jemalloc update to 5.2.1\n\nv1.2.0 (2018-11-6)\n-----------\n* Improve cluster support\n* Improve mongodb driver\n* Improve redis driver\n* Improve socket concurrent write\n* Improve socket channel\n* Improve service gate\n* Improve udp support\n* Add skynet.ignoreret\n* Add skynet.trace\n* Add skynet.context\n* Improve skynet.wait/wakeup\n* Add socket.netstat\n* Add socketchannel.overload\n* Fix memory leak for dead service\n* lua update to 5.3.5\n* jemalloc update to 5.1.0\n\nv1.1.0 (2017-10-31)\n-----------\n* add socket.disconnected()\n* fix bugs : see comments for detail\n\nv1.1.0-rc (2017-7-18)\n-----------\n* config file : support include\n* debug console : User config binding IP\n* debug console : Add call command\n* debug console : Report error message of inject code\n* debug console : Change response message\n* sharedata : Add sharedata.flush\n* sharedata : Add sharedata.deepcopy\n* cluster : Add cluster.send\n* cluster : Add API to update config table\n* skynet : Add skynet.state\n* skynet : Keep the order of skynet.wakeup\n* skynet : Add a MEMORY_CHECK macro for debugging\n* httpc : Add httpc.timeout\n* mongo driver : sort support multi-key\n* bson : Check utf8 string\n* bson : No longer support numeric key \n* daemon mode: Can output the error messages\n* sproto : Support decimal number\n* sproto: Support binary type\n* sproto: Support response nil\n* crypt: Add crypt.hmac64_md5\n* redis: Add redis-cluster support\n* socket server : Optimize socket write (Try direct write from worker thread first)\n* Add prefix skynet to all skynet lua modules\n* datasheet : New module for replacement of sharedata\n* jemalloc : Update to 5.0.1\n* lua : Update to 5.3.4\n* lpeg : Update to 1.0.1\n\nv1.0.0 (2016-7-11)\n-----------\n* Version 1.0.0 Released\n\nv1.0.0-rc5 (2016-7-4)\n-----------\n* MongoDB : Support auth_scram_sha1\n* MongoDB : Auto determine primary host\n* Bugfix : memory leak in multicast\n* Bugfix : Lua 5.3.3\n* Bson : support meta array\n\nv1.0.0-rc4 (2016-6-13)\n-----------\n* Update lua to 5.3.3\n* Update jemalloc to 4.2.1\n* Add debug console command ping\n* Lua bson support __pairs\n* Add mongo.createIndexes and fix bug in old mongo.createIndex\n* Handle signal HUP to reopen log file (for logrotate)\n\nv1.0.0-rc3 (2016-5-9)\n-----------\n* Update jemalloc 4.1.1\n* Update lua 5.3.3 rc1\n* Update sproto to support encoding empty table\n* Make skynet.init stable (keep order)\n* skynet.getenv can return empty string\n* Add lua VM memory warning\n* lua VM support memory limit\n* skynet.pcall support varargs\n* Bugfix : Global name query\n* Bugfix : snax.queryglobal\n\nv1.0.0-rc2 (2016-3-7)\n-----------\n* Fix a bug in lua 5.3.2\n* Update sproto (fix bugs and add ud for package)\n* Fix a bug in http\n* Fix a bug in harbor\n* Fix a bug in socket channel\n* Enhance remote debugger\n\nv1.0.0-rc (2015-12-28)\n-----------\n* Update to lua 5.3.2\n* Add skynet.coroutine lib\n* Add new debug api to show c memory used\n* httpc can use async dns query\n* Redis driver support pipeline\n* socket.send support string table, and rewrite redis driver\n* socket.shutdown would abandon unsend buffer\n* Improve some sproto api\n* c memory doesn't count the memory allocated by lua vm\n* some other bugfix (In multicast, socketchannel, etc)\n\nv1.0.0-beta (2015-11-10)\n-----------\n* Improve and fix bug for sproto\n* Add global short string pool for lua vm\n* Add code cache mode\n* Add a callback for mysql auth\n* Add hmac_md5\n* Sharedata support filename as a string\n* Fix a bug in socket.httpc\n* Fix a lua stack overflow bug in lua bson\n* Fix a socketchannel bug may block the data steam\n* Avoid dead loop when sending message to the service exiting\n* Fix memory leak in netpack\n* Improve DH key exchange implement\n* Minor fix for socket\n* Minor fix for multicast\n* Update jemalloc to 4.0.4\n* Update lpeg to 1.0.0\n\nv1.0.0-alpha10 (2015-8-17)\n-----------\n* Remove the size limit of cluster RPC message.\n* Remove the size limit of local message.\n* Add cluster.query and clsuter.register.\n* Add an option of pthread mutex lock.\n* Add skynet.core.intcommand to optimize skynet.sleep etc.\n* Fix a memory leak bug in lua shared proto.\n* snax.msgserver use string instead of lightuserdata/size.\n* Remove some unused api in netpack.\n* Raise error when skynet.send to 0.\n\nv1.0.0-alpha9 (2015-8-10)\n-----------\n* Improve lua serialization , support pairs metamethod.\n* Bugfix : sproto (See commits log of sproto)\n* Add user log service support (In config)\n* Other minor bugfix (See commits log)\n\nv1.0.0-alpha8 (2015-6-29)\n-----------\n* Update lua 5.3.1\n* Bugfix: skynet exit issue\n* Bugfix: timer race condition\n* Use atom increment in bson object id\n* remove assert when write to a listen fd\n* sproto encode doesn't use raw table api\n\nv1.0.0-alpha7 (2015-6-8)\n-----------\n* console support launch snax service\n* Add cluster.snax\n* Add nodelay in clusterd\n* Merge sproto bugfix patch\n* Move some skynet api into skynet.manager\n* DNS support underscore\n* Add logservice in config file for user defined log service\n* skynet.fork returns coroutine\n* Fix a few of bugs , see the commits log\n\nv1.0.0-alpha6 (2015-5-18)\n-----------\n* bugfix: httpc.get\n* bugfix: seri lib stack overflow\n* bugfix: udp send\n* bugfix: udp address\n* bugfix: sproto dump\n* add: sproto default\n* improve: skynet.wakeup (can wakeup skynet.call by raise an error)\n* improve: skynet.exit (raise error when uncall response)\n* remove: task overload warning\n* move: some skynet api move into skynet.manager\n\nv1.0.0-alpha5 (2015-4-27)\n-----------\n* merge lua 5.3 official bugfix \n* improve sproto rpc api\n* fix a deadlock bug when service retire\n* improve cluster config reload\n* add skynet.pcall for calling a function with `require`\n* better error log in loginserver\n\nv1.0.0-alpha4 (2015-4-13)\n-----------\n* sproto can share c struct between states\n* udp api changed (use lua string now)\n* fix memory leak in dns module\n\nv1.0.0-alpha3 (2015-3-30)\n-----------\n* Update sproto (bugfix)\n* Add async dns query\n* improve httpc\n\nv1.0.0-alpha2 (2015-3-16)\n-----------\n* Update examples client to lua 5.3\n* Patch lua 5.3 to interrupt the dead loop (for debug)\n* Update sproto (fix some bugs and support unordered map)\n\nv1.0.0-alpha (2015-3-9)\n-----------\n* Update lua from 5.2 to 5.3\n* Add an online lua debugger\n* Add sharemap as an example use case of stm\n* Improve sproto for multi-state\n* Improve mongodb driver\n* Fix known bugs\n\nv0.9.3 (2015-1-5)\n-----------\n* Add : mongo createIndex\n* Update : sproto\n* bugfix : sharedata check dirty flag when len/pairs metamethod\n* bugfix : multicast\n\nv0.9.2 (2014-12-8)\n-----------\n* Simplify the message queue\n* Add create_index in mongo driver\n* Fix a bug in big-endian architecture (sproto)\n\nv0.9.0 / v0.9.1 (2014-11-17)\n-----------\n* Add UDP support\n* Add IPv6 support\n* socket send package can define a release method\n* dispatch read before write in epoll\n* remove snax queue mode\n* Fix a bug in big-endian architecture\n\nv0.8.1 (2014-11-3)\n-----------\n* Send to an invalid remote service will raise an error\n* Bugifx: socket open address string\n* Remove sha1 from mysqlaux\n* merge lua and sproto bugfix , use crypt lib instead\n* Fix a memory leak in socket\n* minor bugfix in http module\n\nv0.8.0 (2014-10-27)\n-----------\n* Add mysql client driver\n* Bugfix : skynet.queue\n\nv0.7.4 (2014-10-13)\n-----------\n* Bugfix : clear coroutine pool when GC\n* hotfix : A bug introduce by 0.7.3 \n\nv0.7.3 (2014-10-13)\n-----------\n* Add some logs (warning) when overload\n* Bugfix: crash on exit\n\nv0.7.2 (2014-9-29)\n-----------\n* Bugfix : datacenter.wait\n* Bugfix : error in forker coroutine\n* Add skynet.term\n* Accept socket report port\n* sharedata can be update more than once\n\nv0.7.1 (2014-9-22)\n-----------\n* bugfix: wakeup sleep should return BREAK\n* bugfix: sharedatad load string\n* bugfix: dataserver forward error msg\n\nv0.7.0 (2014-9-8)\n-----------\n* Use sproto instead of cjson\n* Add message logger\n* Add hmac-sha1\n* Some minor bugfix\n\nv0.6.2 (2014-9-1)\n-----------\n* bugfix: only skynet.call response PTYPE_ERROR\n\nv0.6.1 (2014-8-25)\n-----------\n* bugfix: datacenter.wakeup\n* change struct msg name to avoid conflict in mac\n* improve seri library\n\nv0.6.0 (2014-8-18)\n-----------\n* add sharedata\n* bugfix: service exit before init would not report back\n* add skynet.response and check multicall skynet.ret\n* skynet.newservice throw error when lanuch failed\n* Don't check imported function in snax.hotfix\n* snax service add change SERVICE_PATH and add it to package.path\n* skynet.redirect support string address\n* bugfix: skynet.harbor.link may block\n* add skynet.harbor.queryname to query globalname\n* add cluster.proxy \n* add DEBUG command exit (send a message to lua service by DEBUG)\n* add DEBUG command run (debug_console command inject)\n* bugfix : socketchannel connect once\n* bugfix : mongo driver\n\nv0.5.2 (2014-8-11)\n-----------\n* Bugfix : httpd request\n* Bugifx : http chunked mode\n* Add : httpc\n* timer support more than 497 days\n\nv0.5.1 (2014-8-4)\n-----------\n* Bugfix : http module\n* Bugfix : multicast local channel delete\n* Bugfix : socket.read(fd)\n\nv0.5.0 (2014-7-28)\n-----------\n* skynet.exit will quit service immediately.\n* Add snax.gateserver, snax.loginserver, snax.msgserver\n* Simplify clientsocket lib\n* mongo driver support replica set\n* config file support read from ENV\n* add simple httpd (see examples/simpleweb.lua)\n\nv0.4.2 (2014-7-14)\n-----------\n* Bugfix : invalid negative socket id \n* Add optional TCP_NODELAY support\n* Add worker thread weight\n* Add skynet.queue\n* Bugfix: socketchannel\n* cluster can throw error\n* Add readline and writeline to clientsocket lib\n* Add cluster.reload to reload config file\n* Add datacenter.wait\n\nv0.4.1 (2014-7-7)\n-----------\n* Add SERVICE_NAME in loader\n* Throw error back when skynet.error\n* Add skynet.task\n* Bugfix for last version (harbor service bugs)\n\nv0.4.0 (2014-6-30)\n-----------\n* Optimize redis driver `compose_message`.\n* Add module skynet.harbor for monitor harbor connect/disconnect, see test/testharborlink.lua .\n* cluster.open support cluster name.\n* Add new api skynet.packstring , and skynet.unpack support lua string\n* socket.listen support put port into address. (address:port)\n* Redesign harbor/master/dummy, remove lots of C code and rewrite in lua.\n* Remove block connect api, queue sending message during connecting now.\n* Add skynet.time()\n\nv0.3.2 (2014-6-23)\n----------\n* Bugfix : cluster (double free).\n* Add socket.header() to decode big-endian package header (and fix the bug in cluster).\n\nv0.3.1 (2014-6-16)\n-----------\n* Bugfix: lua mongo driver . Hold reply string before decode bson data.\n* More check in bson decoding.\n* Use big-endian for encoding bson objectid.\n\nv0.3.0 (2014-6-2)\n-----------\n* Add cluster support\n* Add single node mode\n* Add daemon mode\n* Bugfix: update lua-bson (signed 32bit int bug / check string length)\n* Optimize timer\n* Simplify message queue and optimize message dispatch\n* Use jemalloc release 3.6.0\n\nv0.2.1 (2014-5-19)\n-----------\n* Bugfix: check all the events already read after socket close\n* Bugfix: socket data in gate service \n* Bugfix: boundary problem in harbor service\n* Bugfix: stdin handle is 0\n\nv0.2.0 (2014-5-12)\n-----------\n\n* Rewrite malloc hook , use `pthread_getspecific` instead of `__thread` to get current service handle.\n* Optimize global unique service query, rewrite `service_mgr` .\n* Add some snax api, snax.uniqueservice (etc.) , use independent protocol `PTYPE_SNAX` .\n* Add bootstrap lua script , remove some code in C .\n* Use a lua loader to load lua service code (and set the lua environment), remove some code in C.\n* Support preload a file before each lua service start.\n* Add datacenter service.\n* Add multicast api.\n* Remove skynet.blockcall , simplify the implement of message queue.\n* When dropping message queue (at service exit) , dispatcher will post an error back to the source of each message.\n* Remove skynet.watch , monitor is not necessary for watching skynet.call . so simplemonitor.lua is move to examples.\n* Remove the limit of global queue size (64K actived service limit before).\n* Refactoring `skynet_command`.\n\nv0.1.1 (2014-4-28)\n------------------\n\n* Socket channel should clear request queue when reconnect.\n* Fix the issue that socket close may block the coroutine.\n* Fix the issue that jemalloc api may crash on macosx (disable jemalloc on macosx).\n\nv0.1.0 (2014-4-23)\n------------------\n\n* First release version.\n\nFirst public version (2012-8-1)\n------------------\n\n* Make skynet from a private project to public.\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2012-2025 codingnow.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "Makefile",
    "content": "include platform.mk\n\nLUA_CLIB_PATH ?= luaclib\nCSERVICE_PATH ?= cservice\n\nSKYNET_BUILD_PATH ?= .\n\nCFLAGS = -g -O2 -Wall -I$(LUA_INC) $(MYCFLAGS)\n# CFLAGS += -DUSE_PTHREAD_LOCK\n\n# lua\n\nLUA_STATICLIB := 3rd/lua/liblua.a\nLUA_LIB ?= $(LUA_STATICLIB)\nLUA_INC ?= 3rd/lua\n\n$(LUA_STATICLIB) :\n\tcd 3rd/lua && $(MAKE) CC='$(CC) -std=gnu99' $(PLAT)\n\n# https : turn on TLS_MODULE to add https support\n\n# TLS_MODULE=ltls\nTLS_LIB=\nTLS_INC=\n\n# jemalloc\n\nJEMALLOC_STATICLIB := 3rd/jemalloc/lib/libjemalloc_pic.a\nJEMALLOC_INC := 3rd/jemalloc/include/jemalloc\n\nall : jemalloc\n\n.PHONY : jemalloc update3rd\n\nMALLOC_STATICLIB := $(JEMALLOC_STATICLIB)\n\n$(JEMALLOC_STATICLIB) : 3rd/jemalloc/Makefile\n\tcd 3rd/jemalloc && $(MAKE) CC=$(CC)\n\n3rd/jemalloc/autogen.sh :\n\tgit submodule update --init\n\n3rd/jemalloc/Makefile : | 3rd/jemalloc/autogen.sh\n\tcd 3rd/jemalloc && ./autogen.sh --with-jemalloc-prefix=je_ --enable-prof\n\njemalloc : $(MALLOC_STATICLIB)\n\nupdate3rd :\n\trm -rf 3rd/jemalloc && git submodule update --init\n\n# skynet\n\nCSERVICE = snlua logger gate harbor\nLUA_CLIB = skynet \\\n  client \\\n  bson md5 sproto lpeg $(TLS_MODULE)\n\nLUA_CLIB_SKYNET = \\\n  lua-skynet.c lua-seri.c \\\n  lua-socket.c \\\n  lua-mongo.c \\\n  lua-netpack.c \\\n  lua-memory.c \\\n  lua-multicast.c \\\n  lua-cluster.c \\\n  lua-crypt.c lsha1.c \\\n  lua-sharedata.c \\\n  lua-stm.c \\\n  lua-debugchannel.c \\\n  lua-datasheet.c \\\n  lua-sharetable.c \\\n  \\\n\nSKYNET_SRC = skynet_main.c skynet_handle.c skynet_module.c skynet_mq.c \\\n  skynet_server.c skynet_start.c skynet_timer.c skynet_error.c \\\n  skynet_harbor.c skynet_env.c skynet_monitor.c skynet_socket.c socket_server.c \\\n  mem_info.c malloc_hook.c skynet_daemon.c skynet_log.c\n\nall : \\\n  $(SKYNET_BUILD_PATH)/skynet \\\n  $(foreach v, $(CSERVICE), $(CSERVICE_PATH)/$(v).so) \\\n  $(foreach v, $(LUA_CLIB), $(LUA_CLIB_PATH)/$(v).so)\n\n$(SKYNET_BUILD_PATH)/skynet : $(foreach v, $(SKYNET_SRC), skynet-src/$(v)) $(LUA_LIB) $(MALLOC_STATICLIB)\n\t$(CC) $(CFLAGS) -o $@ $^ -Iskynet-src -I$(JEMALLOC_INC) $(LDFLAGS) $(EXPORT) $(SKYNET_LIBS) $(SKYNET_DEFINES)\n\n$(LUA_CLIB_PATH) :\n\tmkdir $(LUA_CLIB_PATH)\n\n$(CSERVICE_PATH) :\n\tmkdir $(CSERVICE_PATH)\n\ndefine CSERVICE_TEMP\n  $$(CSERVICE_PATH)/$(1).so : service-src/service_$(1).c | $$(CSERVICE_PATH)\n\t$$(CC) $$(CFLAGS) $$(SHARED) $$< -o $$@ -Iskynet-src\nendef\n\n$(foreach v, $(CSERVICE), $(eval $(call CSERVICE_TEMP,$(v))))\n\n$(LUA_CLIB_PATH)/skynet.so : $(addprefix lualib-src/,$(LUA_CLIB_SKYNET)) | $(LUA_CLIB_PATH)\n\t$(CC) $(CFLAGS) $(SHARED) $^ -o $@ -Iskynet-src -Iservice-src -Ilualib-src\n\n$(LUA_CLIB_PATH)/bson.so : lualib-src/lua-bson.c | $(LUA_CLIB_PATH)\n\t$(CC) $(CFLAGS) $(SHARED) -Iskynet-src $^ -o $@\n\n$(LUA_CLIB_PATH)/md5.so : 3rd/lua-md5/md5.c 3rd/lua-md5/md5lib.c 3rd/lua-md5/compat-5.2.c | $(LUA_CLIB_PATH)\n\t$(CC) $(CFLAGS) $(SHARED) -I3rd/lua-md5 $^ -o $@\n\n$(LUA_CLIB_PATH)/client.so : lualib-src/lua-clientsocket.c lualib-src/lua-crypt.c lualib-src/lsha1.c | $(LUA_CLIB_PATH)\n\t$(CC) $(CFLAGS) $(SHARED) $^ -o $@ -lpthread\n\n$(LUA_CLIB_PATH)/sproto.so : lualib-src/sproto/sproto.c lualib-src/sproto/lsproto.c | $(LUA_CLIB_PATH)\n\t$(CC) $(CFLAGS) $(SHARED) -Ilualib-src/sproto $^ -o $@\n\n$(LUA_CLIB_PATH)/ltls.so : lualib-src/ltls.c | $(LUA_CLIB_PATH)\n\t$(CC) $(CFLAGS) $(SHARED) -Iskynet-src -L$(TLS_LIB) -I$(TLS_INC) $^ -o $@ -lssl -lcrypto\n\n$(LUA_CLIB_PATH)/lpeg.so : 3rd/lpeg/lpcap.c 3rd/lpeg/lpcode.c 3rd/lpeg/lpprint.c 3rd/lpeg/lptree.c 3rd/lpeg/lpvm.c 3rd/lpeg/lpcset.c | $(LUA_CLIB_PATH)\n\t$(CC) $(CFLAGS) $(SHARED) -I3rd/lpeg $^ -o $@\n\nclean :\n\trm -f $(SKYNET_BUILD_PATH)/skynet $(CSERVICE_PATH)/*.so $(LUA_CLIB_PATH)/*.so && \\\n  rm -rf $(SKYNET_BUILD_PATH)/*.dSYM $(CSERVICE_PATH)/*.dSYM $(LUA_CLIB_PATH)/*.dSYM\n\t$(MAKE) clean -f mingw.mk\n\ncleanall: clean\nifneq (,$(wildcard 3rd/jemalloc/Makefile))\n\tcd 3rd/jemalloc && $(MAKE) clean && rm Makefile\nendif\n\tcd 3rd/lua && $(MAKE) clean\n\trm -f $(LUA_STATICLIB)\n\t$(MAKE) cleanall -f mingw.mk"
  },
  {
    "path": "README.md",
    "content": "## ![skynet logo](https://github.com/cloudwu/skynet/wiki/image/skynet_metro.jpg)\n\nSkynet is a multi-user Lua framework supporting the actor model, often used in games.\n\n[It is heavily used in the Chinese game industry](https://github.com/cloudwu/skynet/wiki/Uses), but is also now spreading to other industries, and to English-centric developers. To visit related sites, visit the Chinese pages using something like Google or Deepl translate.\n\nThe community is friendly and almost all contributors can speak English, so English speakers are welcome to ask questions in [Discussion](https://github.com/cloudwu/skynet/discussions), or submit issues in English.\n\n## Build\n\nFor Linux, install autoconf first for jemalloc:\n\n```\ngit clone https://github.com/cloudwu/skynet.git\ncd skynet\nmake 'PLATFORM'  # PLATFORM can be linux, macosx, freebsd now\n```\n\nOr:\n\n```\nexport PLAT=linux\nmake\n```\n\nFor FreeBSD , use gmake instead of make.\n\n## Test\n\nRun these in different consoles:\n\n```\n./skynet examples/config\t# Launch first skynet node  (Gate server) and a skynet-master (see config for standalone option)\n./3rd/lua/lua examples/client.lua \t# Launch a client, and try to input hello.\n```\n\n## About Lua version\n\nSkynet now uses a modified version of lua 5.5.0 ( https://github.com/ejoy/lua/tree/skynet55 ) for multiple lua states.\n\nOfficial Lua versions can also be used as long as the Makefile is edited.\n\n## How To Use\n\n* Read Wiki for documents https://github.com/cloudwu/skynet/wiki (Written in both English and Chinese)\n* The FAQ in wiki https://github.com/cloudwu/skynet/wiki/FAQ (In Chinese, but you can visit them using something like Google or Deepl translate.)\n"
  },
  {
    "path": "examples/abort.lua",
    "content": "local skynet = require \"skynet\"\nrequire \"skynet.manager\"\t-- import skynet.abort\n\nskynet.abort()\n"
  },
  {
    "path": "examples/agent.lua",
    "content": "local skynet = require \"skynet\"\nlocal socket = require \"skynet.socket\"\nlocal sproto = require \"sproto\"\nlocal sprotoloader = require \"sprotoloader\"\n\nlocal WATCHDOG\nlocal host\nlocal send_request\n\nlocal CMD = {}\nlocal REQUEST = {}\nlocal client_fd\n\nfunction REQUEST:get()\n\tprint(\"get\", self.what)\n\tlocal r = skynet.call(\"SIMPLEDB\", \"lua\", \"get\", self.what)\n\treturn { result = r }\nend\n\nfunction REQUEST:set()\n\tprint(\"set\", self.what, self.value)\n\tlocal r = skynet.call(\"SIMPLEDB\", \"lua\", \"set\", self.what, self.value)\nend\n\nfunction REQUEST:handshake()\n\treturn { msg = \"Welcome to skynet, I will send heartbeat every 5 sec.\" }\nend\n\nfunction REQUEST:quit()\n\tskynet.call(WATCHDOG, \"lua\", \"close\", client_fd)\nend\n\nlocal function request(name, args, response)\n\tlocal f = assert(REQUEST[name])\n\tlocal r = f(args)\n\tif response then\n\t\treturn response(r)\n\tend\nend\n\nlocal function send_package(pack)\n\tlocal package = string.pack(\">s2\", pack)\n\tsocket.write(client_fd, package)\nend\n\nskynet.register_protocol {\n\tname = \"client\",\n\tid = skynet.PTYPE_CLIENT,\n\tunpack = function (msg, sz)\n\t\treturn host:dispatch(msg, sz)\n\tend,\n\tdispatch = function (fd, _, type, ...)\n\t\tassert(fd == client_fd)\t-- You can use fd to reply message\n\t\tskynet.ignoreret()\t-- session is fd, don't call skynet.ret\n\t\tskynet.trace()\n\t\tif type == \"REQUEST\" then\n\t\t\tlocal ok, result  = pcall(request, ...)\n\t\t\tif ok then\n\t\t\t\tif result then\n\t\t\t\t\tsend_package(result)\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tskynet.error(result)\n\t\t\tend\n\t\telse\n\t\t\tassert(type == \"RESPONSE\")\n\t\t\terror \"This example doesn't support request client\"\n\t\tend\n\tend\n}\n\nfunction CMD.start(conf)\n\tlocal fd = conf.client\n\tlocal gate = conf.gate\n\tWATCHDOG = conf.watchdog\n\t-- slot 1,2 set at main.lua\n\thost = sprotoloader.load(1):host \"package\"\n\tsend_request = host:attach(sprotoloader.load(2))\n\tskynet.fork(function()\n\t\twhile true do\n\t\t\tsend_package(send_request \"heartbeat\")\n\t\t\tskynet.sleep(500)\n\t\tend\n\tend)\n\n\tclient_fd = fd\n\tskynet.call(gate, \"lua\", \"forward\", fd)\nend\n\nfunction CMD.disconnect()\n\t-- todo: do something before exit\n\tskynet.exit()\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(_,_, command, ...)\n\t\tskynet.trace()\n\t\tlocal f = CMD[command]\n\t\tskynet.ret(skynet.pack(f(...)))\n\tend)\nend)\n"
  },
  {
    "path": "examples/checkdeadloop.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal list = {}\n\nlocal function timeout_check(ti)\n\tif not next(list) then\n\t\treturn\n\tend\n\tskynet.sleep(ti)\t-- sleep 10 sec\n\tfor k,v in pairs(list) do\n\t\tskynet.error(\"timeout\",ti,k,v)\n\tend\nend\n\nskynet.start(function()\n\tskynet.error(\"ping all\")\n\tlocal list_ret = skynet.call(\".launcher\", \"lua\", \"LIST\")\n\tfor addr, desc in pairs(list_ret) do\n\t\tlist[addr] = desc\n\t\tskynet.fork(function()\n\t\t\tskynet.call(addr,\"debug\",\"INFO\")\n\t\t\tlist[addr] = nil\n\t\tend)\n\tend\n\tskynet.sleep(0)\n\ttimeout_check(100)\n\ttimeout_check(400)\n\ttimeout_check(500)\n\tskynet.exit()\nend)\n"
  },
  {
    "path": "examples/client.lua",
    "content": "package.cpath = \"luaclib/?.so\"\npackage.path = \"lualib/?.lua;examples/?.lua\"\n\nif _VERSION ~= \"Lua 5.4\" then\n\terror \"Use lua 5.4\"\nend\n\nlocal socket = require \"client.socket\"\nlocal proto = require \"proto\"\nlocal sproto = require \"sproto\"\n\nlocal host = sproto.new(proto.s2c):host \"package\"\nlocal request = host:attach(sproto.new(proto.c2s))\n\nlocal fd = assert(socket.connect(\"127.0.0.1\", 8888))\n\nlocal function send_package(fd, pack)\n\tlocal package = string.pack(\">s2\", pack)\n\tsocket.send(fd, package)\nend\n\nlocal function unpack_package(text)\n\tlocal size = #text\n\tif size < 2 then\n\t\treturn nil, text\n\tend\n\tlocal s = text:byte(1) * 256 + text:byte(2)\n\tif size < s+2 then\n\t\treturn nil, text\n\tend\n\n\treturn text:sub(3,2+s), text:sub(3+s)\nend\n\nlocal function recv_package(last)\n\tlocal result\n\tresult, last = unpack_package(last)\n\tif result then\n\t\treturn result, last\n\tend\n\tlocal r = socket.recv(fd)\n\tif not r then\n\t\treturn nil, last\n\tend\n\tif r == \"\" then\n\t\terror \"Server closed\"\n\tend\n\treturn recv_package(last .. r)\nend\n\nlocal session = 0\n\nlocal function send_request(name, args)\n\tsession = session + 1\n\tlocal str = request(name, args, session)\n\tsend_package(fd, str)\n\tprint(\"Request:\", session)\nend\n\nlocal last = \"\"\n\nlocal function print_request(name, args)\n\tprint(\"REQUEST\", name)\n\tif args then\n\t\tfor k,v in pairs(args) do\n\t\t\tprint(k,v)\n\t\tend\n\tend\nend\n\nlocal function print_response(session, args)\n\tprint(\"RESPONSE\", session)\n\tif args then\n\t\tfor k,v in pairs(args) do\n\t\t\tprint(k,v)\n\t\tend\n\tend\nend\n\nlocal function print_package(t, ...)\n\tif t == \"REQUEST\" then\n\t\tprint_request(...)\n\telse\n\t\tassert(t == \"RESPONSE\")\n\t\tprint_response(...)\n\tend\nend\n\nlocal function dispatch_package()\n\twhile true do\n\t\tlocal v\n\t\tv, last = recv_package(last)\n\t\tif not v then\n\t\t\tbreak\n\t\tend\n\n\t\tprint_package(host:dispatch(v))\n\tend\nend\n\nsend_request(\"handshake\")\nsend_request(\"set\", { what = \"hello\", value = \"world\" })\nwhile true do\n\tdispatch_package()\n\tlocal cmd = socket.readstdin()\n\tif cmd then\n\t\tif cmd == \"quit\" then\n\t\t\tsend_request(\"quit\")\n\t\telse\n\t\t\tsend_request(\"get\", { what = cmd })\n\t\tend\n\telse\n\t\tsocket.usleep(100)\n\tend\nend\n"
  },
  {
    "path": "examples/cluster1.lua",
    "content": "local skynet = require \"skynet\"\nlocal cluster = require \"skynet.cluster\"\nlocal snax = require \"skynet.snax\"\n\nskynet.start(function()\n\tcluster.reload {\n\t\tdb = \"127.0.0.1:2528\",\n\t\tdb2 = \"127.0.0.1:2529\",\n\t}\n\n\tlocal sdb = skynet.newservice(\"simpledb\")\n\t-- register name \"sdb\" for simpledb, you can use cluster.query() later.\n\t-- See cluster2.lua\n\tcluster.register(\"sdb\", sdb)\n\tcluster.unregister(\"sdb\")\n\tcluster.register(\"sdb\", sdb)\n\n\tprint(skynet.call(sdb, \"lua\", \"SET\", \"a\", \"foobar\"))\n\tprint(skynet.call(sdb, \"lua\", \"SET\", \"b\", \"foobar2\"))\n\tprint(skynet.call(sdb, \"lua\", \"GET\", \"a\"))\n\tprint(skynet.call(sdb, \"lua\", \"GET\", \"b\"))\n\tcluster.open \"db\"\n\tcluster.open \"db2\"\n\t-- unique snax service\n\tsnax.uniqueservice \"pingserver\"\nend)\n"
  },
  {
    "path": "examples/cluster2.lua",
    "content": "local skynet = require \"skynet\"\nlocal cluster = require \"skynet.cluster\"\n\nskynet.start(function()\n\tlocal proxy = cluster.proxy \"db@sdb\"\t-- cluster.proxy(\"db\", \"@sdb\")\n\tlocal largekey = string.rep(\"X\", 128*1024)\n\tlocal largevalue = string.rep(\"R\", 100 * 1024)\n\tskynet.call(proxy, \"lua\", \"SET\", largekey, largevalue)\n\tlocal v = skynet.call(proxy, \"lua\", \"GET\", largekey)\n\tassert(largevalue == v)\n\tskynet.send(proxy, \"lua\", \"PING\", \"proxy\")\n\n\tskynet.fork(function()\n\t\tskynet.trace(\"cluster\")\n\t\tprint(cluster.call(\"db\", \"@sdb\", \"GET\", \"a\"))\n\t\tprint(cluster.call(\"db2\", \"@sdb\", \"GET\", \"b\"))\n\t\tcluster.send(\"db2\", \"@sdb\", \"PING\", \"db2:longstring\" .. largevalue)\n\tend)\n\n\t-- test snax service\n\tskynet.timeout(300,function()\n\t\tcluster.reload {\n\t\t\tdb = false,\t-- db is down\n\t\t\tdb3 = \"127.0.0.1:2529\"\n\t\t}\n\t\tprint(pcall(cluster.call, \"db\", \"@sdb\", \"GET\", \"a\"))\t-- db is down\n\tend)\n\tcluster.reload { __nowaiting = false }\n\tlocal pingserver = cluster.snax(\"db3\", \"pingserver\")\n\tprint(pingserver.req.ping \"hello\")\nend)\n"
  },
  {
    "path": "examples/clustername.lua",
    "content": "__nowaiting = true\t-- If you turn this flag off, cluster.call would block when node name is absent\n\ndb = \"127.0.0.1:2528\"\ndb2 = \"127.0.0.1:2529\"\n"
  },
  {
    "path": "examples/config",
    "content": "include \"config.path\"\n\n-- preload = \"./examples/preload.lua\"\t-- run preload.lua before every lua service run\nthread = 8\nlogger = nil\nlogpath = \".\"\nharbor = 1\naddress = \"127.0.0.1:2526\"\nmaster = \"127.0.0.1:2013\"\nstart = \"main\"\t-- main script\nbootstrap = \"snlua bootstrap\"\t-- The service for bootstrap\nstandalone = \"0.0.0.0:2013\"\n-- snax_interface_g = \"snax_g\"\ncpath = root..\"cservice/?.so\"\n-- daemon = \"./skynet.pid\"\n"
  },
  {
    "path": "examples/config.c1",
    "content": "thread = 8\nlogger = nil\nharbor = 0\nstart = \"cluster1\"\nbootstrap = \"snlua bootstrap\"\t-- The service for bootstrap\nluaservice = \"./service/?.lua;./test/?.lua;./examples/?.lua\"\nlualoader = \"lualib/loader.lua\"\ncpath = \"./cservice/?.so\"\n-- use cluster.reload instead, see cluster1.lua\n-- cluster = \"./examples/clustername.lua\"\nsnax = \"./test/?.lua\"\n"
  },
  {
    "path": "examples/config.c2",
    "content": "thread = 8\nlogger = nil\nharbor = 0\nstart = \"cluster2\"\nbootstrap = \"snlua bootstrap\"\t-- The service for bootstrap\nluaservice = \"./service/?.lua;./test/?.lua;./examples/?.lua\"\nlualoader = \"lualib/loader.lua\"\ncpath = \"./cservice/?.so\"\ncluster = \"./examples/clustername.lua\"\nsnax = \"./test/?.lua\"\n"
  },
  {
    "path": "examples/config.handle",
    "content": "include \"config.path\"\n\nthread = 8\nlogger = \"skynet.log\"\nlogpath = \".\"\nharbor = 0\nstart = \"testhandle\"\t-- main script\nbootstrap = \"snlua bootstrap\"\t-- The service for bootstrap\ncpath = root..\"cservice/?.so\"\n--daemon = \"./skynet.pid\"\n"
  },
  {
    "path": "examples/config.login",
    "content": "thread = 8\nlogger = nil\nharbor = 0\nstart = \"main\"\nbootstrap = \"snlua bootstrap\"\t-- The service for bootstrap\nluaservice = \"./service/?.lua;./examples/login/?.lua\"\nlualoader = \"lualib/loader.lua\"\ncpath = \"./cservice/?.so\"\n"
  },
  {
    "path": "examples/config.mc",
    "content": "root = \"./\"\nthread = 8\nlogger = nil\nharbor = 2\naddress = \"127.0.0.1:2527\"\nmaster = \"127.0.0.1:2013\"\nstart = \"testmulticast2\"\t-- main script\nbootstrap = \"snlua bootstrap\"\t-- The service for bootstrap\n--standalone = \"0.0.0.0:2013\"\nluaservice = root..\"service/?.lua;\"..root..\"test/?.lua;\"..root..\"examples/?.lua\"\nlualoader = \"lualib/loader.lua\"\n-- preload = \"./examples/preload.lua\"\t-- run preload.lua before every lua service run\nsnax = root..\"examples/?.lua;\"..root..\"test/?.lua\"\ncpath = root..\"cservice/?.so\"\n"
  },
  {
    "path": "examples/config.mongodb",
    "content": "root = \"./\"\nthread = 8\nlogger = nil\nharbor = 0\nstart = \"main_mongodb\"\t-- main script\nbootstrap = \"snlua bootstrap\"\t-- The service for bootstrap\nluaservice = root..\"service/?.lua;\"..root..\"test/?.lua;\"..root..\"examples/?.lua\"\nlualoader = \"lualib/loader.lua\"\nsnax = root..\"examples/?.lua;\"..root..\"test/?.lua\"\ncpath = root..\"cservice/?.so\"\n-- daemon = \"./skynet.pid\"\n"
  },
  {
    "path": "examples/config.mysql",
    "content": "root = \"./\"\nthread = 8\nlogger = nil\nharbor = 0\nstart = \"main_mysql\"\t-- main script\nbootstrap = \"snlua bootstrap\"\t-- The service for bootstrap\nluaservice = root..\"service/?.lua;\"..root..\"test/?.lua;\"..root..\"examples/?.lua\"\nlualoader = \"lualib/loader.lua\"\nsnax = root..\"examples/?.lua;\"..root..\"test/?.lua\"\ncpath = root..\"cservice/?.so\"\n-- daemon = \"./skynet.pid\"\n"
  },
  {
    "path": "examples/config.path",
    "content": "root = \"./\"\nluaservice = root..\"service/?.lua;\"..root..\"test/?.lua;\"..root..\"examples/?.lua;\"..root..\"test/?/init.lua\"\nlualoader = root .. \"lualib/loader.lua\"\nlua_path = root..\"lualib/?.lua;\"..root..\"lualib/?/init.lua\"\nlua_cpath = root .. \"luaclib/?.so\"\nsnax = root..\"examples/?.lua;\"..root..\"test/?.lua\"\n"
  },
  {
    "path": "examples/config.userlog",
    "content": "root = \"./\"\nthread = 8\nlogger = \"userlog\"\nlogservice = \"snlua\"\nlogpath = \".\"\nharbor = 0\nstart = \"main\"\t-- main script\nbootstrap = \"snlua bootstrap\"\t-- The service for bootstrap\nluaservice = root..\"service/?.lua;\"..root..\"test/?.lua;\"..root..\"examples/?.lua\"\nlualoader = \"lualib/loader.lua\"\n-- preload = \"./examples/preload.lua\"\t-- run preload.lua before every lua service run\nsnax = root..\"examples/?.lua;\"..root..\"test/?.lua\"\n-- snax_interface_g = \"snax_g\"\ncpath = root..\"cservice/?.so\"\n-- daemon = \"./skynet.pid\"\n"
  },
  {
    "path": "examples/config_log",
    "content": "thread = 8\nmqueue = 256\ncpath = \"./cservice/?.so\"\nlogger = nil\nharbor = 2\naddress = \"127.0.0.1:2527\"\nmaster = \"127.0.0.1:2013\"\nstart = \"main_log\"\nluaservice =\"./service/?.lua;./test/?.lua;./examples/?.lua\"\nsnax = \"./examples/?.lua;./test/?.lua\"\n"
  },
  {
    "path": "examples/globallog.lua",
    "content": "local skynet = require \"skynet\"\nrequire \"skynet.manager\"\t-- import skynet.register\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(session, address, ...)\n\t\tprint(\"[GLOBALLOG]\", skynet.address(address), ...)\n\tend)\n\tskynet.register \".log\"\n\tskynet.register \"LOG\"\nend)\n"
  },
  {
    "path": "examples/injectlaunch.lua",
    "content": "if not _P then\n\tprint[[\nThis file is examples to show how to inject code into lua service.\nIt is used to inject into launcher service to change the command.LAUNCH to command.LOGLAUNCH.\ntelnet the debug_console service (nc 127.0.0.1 8000), and run:\ninject 3 examples/injectlaunch.lua\t-- 3 means launcher service\n]]\n\treturn\nend\nlocal command = _P.lua.command\n\nif command.RAWLAUNCH then\n\tcommand.LAUNCH, command.RAWLAUNCH = command.RAWLAUNCH\n\tprint \"restore command.LAUNCH\"\nelse\n\tcommand.RAWLAUNCH = command.LAUNCH\n\tcommand.LAUNCH = command.LOGLAUNCH\n\tprint \"replace command.LAUNCH\"\nend\n"
  },
  {
    "path": "examples/login/client.lua",
    "content": "package.cpath = \"luaclib/?.so\"\n\nlocal socket = require \"client.socket\"\nlocal crypt = require \"client.crypt\"\n\nif _VERSION ~= \"Lua 5.4\" then\n\terror \"Use lua 5.4\"\nend\n\nlocal fd = assert(socket.connect(\"127.0.0.1\", 8001))\n\nlocal function writeline(fd, text)\n\tsocket.send(fd, text .. \"\\n\")\nend\n\nlocal function unpack_line(text)\n\tlocal from = text:find(\"\\n\", 1, true)\n\tif from then\n\t\treturn text:sub(1, from-1), text:sub(from+1)\n\tend\n\treturn nil, text\nend\n\nlocal last = \"\"\n\nlocal function unpack_f(f)\n\tlocal function try_recv(fd, last)\n\t\tlocal result\n\t\tresult, last = f(last)\n\t\tif result then\n\t\t\treturn result, last\n\t\tend\n\t\tlocal r = socket.recv(fd)\n\t\tif not r then\n\t\t\treturn nil, last\n\t\tend\n\t\tif r == \"\" then\n\t\t\terror \"Server closed\"\n\t\tend\n\t\treturn f(last .. r)\n\tend\n\n\treturn function()\n\t\twhile true do\n\t\t\tlocal result\n\t\t\tresult, last = try_recv(fd, last)\n\t\t\tif result then\n\t\t\t\treturn result\n\t\t\tend\n\t\t\tsocket.usleep(100)\n\t\tend\n\tend\nend\n\nlocal readline = unpack_f(unpack_line)\n\nlocal challenge = crypt.base64decode(readline())\n\nlocal clientkey = crypt.randomkey()\nwriteline(fd, crypt.base64encode(crypt.dhexchange(clientkey)))\nlocal secret = crypt.dhsecret(crypt.base64decode(readline()), clientkey)\n\nprint(\"sceret is \", crypt.hexencode(secret))\n\nlocal hmac = crypt.hmac64(challenge, secret)\nwriteline(fd, crypt.base64encode(hmac))\n\nlocal token = {\n\tserver = \"sample\",\n\tuser = \"hello\",\n\tpass = \"password\",\n}\n\nlocal function encode_token(token)\n\treturn string.format(\"%s@%s:%s\",\n\t\tcrypt.base64encode(token.user),\n\t\tcrypt.base64encode(token.server),\n\t\tcrypt.base64encode(token.pass))\nend\n\nlocal etoken = crypt.desencode(secret, encode_token(token))\nwriteline(fd, crypt.base64encode(etoken))\n\nlocal result = readline()\nprint(result)\nlocal code = tonumber(string.sub(result, 1, 3))\nassert(code == 200)\nsocket.close(fd)\n\nlocal subid = crypt.base64decode(string.sub(result, 5))\n\nprint(\"login ok, subid=\", subid)\n\n----- connect to game server\n\nlocal function send_request(v, session)\n\tlocal size = #v + 4\n\tlocal package = string.pack(\">I2\", size)..v..string.pack(\">I4\", session)\n\tsocket.send(fd, package)\n\treturn v, session\nend\n\nlocal function recv_response(v)\n\tlocal size = #v - 5\n\tlocal content, ok, session = string.unpack(\"c\"..tostring(size)..\"B>I4\", v)\n\treturn ok ~=0 , content, session\nend\n\nlocal function unpack_package(text)\n\tlocal size = #text\n\tif size < 2 then\n\t\treturn nil, text\n\tend\n\tlocal s = text:byte(1) * 256 + text:byte(2)\n\tif size < s+2 then\n\t\treturn nil, text\n\tend\n\n\treturn text:sub(3,2+s), text:sub(3+s)\nend\n\nlocal readpackage = unpack_f(unpack_package)\n\nlocal function send_package(fd, pack)\n\tlocal package = string.pack(\">s2\", pack)\n\tsocket.send(fd, package)\nend\n\nlocal text = \"echo\"\nlocal index = 1\n\nprint(\"connect\")\nfd = assert(socket.connect(\"127.0.0.1\", 8888))\nlast = \"\"\n\nlocal handshake = string.format(\"%s@%s#%s:%d\", crypt.base64encode(token.user), crypt.base64encode(token.server),crypt.base64encode(subid) , index)\nlocal hmac = crypt.hmac64(crypt.hashkey(handshake), secret)\n\n\nsend_package(fd, handshake .. \":\" .. crypt.base64encode(hmac))\n\nprint(readpackage())\nprint(\"===>\",send_request(text,0))\n-- don't recv response\n-- print(\"<===\",recv_response(readpackage()))\n\nprint(\"disconnect\")\nsocket.close(fd)\n\nindex = index + 1\n\nprint(\"connect again\")\nfd = assert(socket.connect(\"127.0.0.1\", 8888))\nlast = \"\"\n\nlocal handshake = string.format(\"%s@%s#%s:%d\", crypt.base64encode(token.user), crypt.base64encode(token.server),crypt.base64encode(subid) , index)\nlocal hmac = crypt.hmac64(crypt.hashkey(handshake), secret)\n\nsend_package(fd, handshake .. \":\" .. crypt.base64encode(hmac))\n\nprint(readpackage())\nprint(\"===>\",send_request(\"fake\",0))\t-- request again (use last session 0, so the request message is fake)\nprint(\"===>\",send_request(\"again\",1))\t-- request again (use new session)\nprint(\"<===\",recv_response(readpackage()))\nprint(\"<===\",recv_response(readpackage()))\n\n\nprint(\"disconnect\")\nsocket.close(fd)\n\n"
  },
  {
    "path": "examples/login/gated.lua",
    "content": "local msgserver = require \"snax.msgserver\"\nlocal crypt = require \"skynet.crypt\"\nlocal skynet = require \"skynet\"\n\nlocal loginservice = tonumber(...)\n\nlocal server = {}\nlocal users = {}\nlocal username_map = {}\nlocal internal_id = 0\n\n-- login server disallow multi login, so login_handler never be reentry\n-- call by login server\nfunction server.login_handler(uid, secret)\n\tif users[uid] then\n\t\terror(string.format(\"%s is already login\", uid))\n\tend\n\n\tinternal_id = internal_id + 1\n\tlocal id = internal_id\t-- don't use internal_id directly\n\tlocal username = msgserver.username(uid, id, servername)\n\n\t-- you can use a pool to alloc new agent\n\tlocal agent = skynet.newservice \"msgagent\"\n\tlocal u = {\n\t\tusername = username,\n\t\tagent = agent,\n\t\tuid = uid,\n\t\tsubid = id,\n\t}\n\n\t-- trash subid (no used)\n\tskynet.call(agent, \"lua\", \"login\", uid, id, secret)\n\n\tusers[uid] = u\n\tusername_map[username] = u\n\n\tmsgserver.login(username, secret)\n\n\t-- you should return unique subid\n\treturn id\nend\n\n-- call by agent\nfunction server.logout_handler(uid, subid)\n\tlocal u = users[uid]\n\tif u then\n\t\tlocal username = msgserver.username(uid, subid, servername)\n\t\tassert(u.username == username)\n\t\tmsgserver.logout(u.username)\n\t\tusers[uid] = nil\n\t\tusername_map[u.username] = nil\n\t\tskynet.call(loginservice, \"lua\", \"logout\",uid, subid)\n\tend\nend\n\n-- call by login server\nfunction server.kick_handler(uid, subid)\n\tlocal u = users[uid]\n\tif u then\n\t\tlocal username = msgserver.username(uid, subid, servername)\n\t\tassert(u.username == username)\n\t\t-- NOTICE: logout may call skynet.exit, so you should use pcall.\n\t\tpcall(skynet.call, u.agent, \"lua\", \"logout\")\n\tend\nend\n\n-- call by self (when socket disconnect)\nfunction server.disconnect_handler(username)\n\tlocal u = username_map[username]\n\tif u then\n\t\tskynet.call(u.agent, \"lua\", \"afk\")\n\tend\nend\n\n-- call by self (when recv a request from client)\nfunction server.request_handler(username, msg)\n\tlocal u = username_map[username]\n\treturn skynet.tostring(skynet.rawcall(u.agent, \"client\", msg))\nend\n\n-- call by self (when gate open)\nfunction server.register_handler(name)\n\tservername = name\n\tskynet.call(loginservice, \"lua\", \"register_gate\", servername, skynet.self())\nend\n\nmsgserver.start(server)\n\n"
  },
  {
    "path": "examples/login/logind.lua",
    "content": "local login = require \"snax.loginserver\"\nlocal crypt = require \"skynet.crypt\"\nlocal skynet = require \"skynet\"\n\nlocal server = {\n\thost = \"127.0.0.1\",\n\tport = 8001,\n\tmultilogin = false,\t-- disallow multilogin\n\tname = \"login_master\",\n}\n\nlocal server_list = {}\nlocal user_online = {}\nlocal user_login = {}\n\nfunction server.auth_handler(token)\n\t-- the token is base64(user)@base64(server):base64(password)\n\tlocal user, server, password = token:match(\"([^@]+)@([^:]+):(.+)\")\n\tuser = crypt.base64decode(user)\n\tserver = crypt.base64decode(server)\n\tpassword = crypt.base64decode(password)\n\tassert(password == \"password\", \"Invalid password\")\n\treturn server, user\nend\n\nfunction server.login_handler(server, uid, secret)\n\tprint(string.format(\"%s@%s is login, secret is %s\", uid, server, crypt.hexencode(secret)))\n\tlocal gameserver = assert(server_list[server], \"Unknown server\")\n\t-- only one can login, because disallow multilogin\n\tlocal last = user_online[uid]\n\tif last then\n\t\tskynet.call(last.address, \"lua\", \"kick\", uid, last.subid)\n\tend\n\tif user_online[uid] then\n\t\terror(string.format(\"user %s is already online\", uid))\n\tend\n\n\tlocal subid = tostring(skynet.call(gameserver, \"lua\", \"login\", uid, secret))\n\tuser_online[uid] = { address = gameserver, subid = subid , server = server}\n\treturn subid\nend\n\nlocal CMD = {}\n\nfunction CMD.register_gate(server, address)\n\tserver_list[server] = address\nend\n\nfunction CMD.logout(uid, subid)\n\tlocal u = user_online[uid]\n\tif u then\n\t\tprint(string.format(\"%s@%s is logout\", uid, u.server))\n\t\tuser_online[uid] = nil\n\tend\nend\n\nfunction server.command_handler(command, ...)\n\tlocal f = assert(CMD[command])\n\treturn f(...)\nend\n\nlogin(server)\n"
  },
  {
    "path": "examples/login/main.lua",
    "content": "local skynet = require \"skynet\"\n\nskynet.start(function()\n\tlocal loginserver = skynet.newservice(\"logind\")\n\tlocal gate = skynet.newservice(\"gated\", loginserver)\n\n\tskynet.call(gate, \"lua\", \"open\" , {\n\t\tport = 8888,\n\t\tmaxclient = 64,\n\t\tservername = \"sample\",\n\t})\nend)\n"
  },
  {
    "path": "examples/login/msgagent.lua",
    "content": "local skynet = require \"skynet\"\n\nskynet.register_protocol {\n\tname = \"client\",\n\tid = skynet.PTYPE_CLIENT,\n\tunpack = skynet.tostring,\n}\n\nlocal gate\nlocal userid, subid\n\nlocal CMD = {}\n\nfunction CMD.login(source, uid, sid, secret)\n\t-- you may use secret to make a encrypted data stream\n\tskynet.error(string.format(\"%s is login\", uid))\n\tgate = source\n\tuserid = uid\n\tsubid = sid\n\t-- you may load user data from database\nend\n\nlocal function logout()\n\tif gate then\n\t\tskynet.call(gate, \"lua\", \"logout\", userid, subid)\n\tend\n\tskynet.exit()\nend\n\nfunction CMD.logout(source)\n\t-- NOTICE: The logout MAY be reentry\n\tskynet.error(string.format(\"%s is logout\", userid))\n\tlogout()\nend\n\nfunction CMD.afk(source)\n\t-- the connection is broken, but the user may back\n\tskynet.error(string.format(\"AFK\"))\nend\n\nskynet.start(function()\n\t-- If you want to fork a work thread , you MUST do it in CMD.login\n\tskynet.dispatch(\"lua\", function(session, source, command, ...)\n\t\tlocal f = assert(CMD[command])\n\t\tskynet.ret(skynet.pack(f(source, ...)))\n\tend)\n\n\tskynet.dispatch(\"client\", function(_,_, msg)\n\t\t-- the simple echo service\n\t\tskynet.sleep(10)\t-- sleep a while\n\t\tskynet.ret(msg)\n\tend)\nend)\n"
  },
  {
    "path": "examples/main.lua",
    "content": "local skynet = require \"skynet\"\nlocal sprotoloader = require \"sprotoloader\"\n\nlocal max_client = 64\n\nskynet.start(function()\n\tskynet.error(\"Server start\")\n\tskynet.uniqueservice(\"protoloader\")\n\tif not skynet.getenv \"daemon\" then\n\t\tlocal console = skynet.newservice(\"console\")\n\tend\n\tskynet.newservice(\"debug_console\",8000)\n\tskynet.newservice(\"simpledb\")\n\tlocal watchdog = skynet.newservice(\"watchdog\")\n\tlocal addr,port = skynet.call(watchdog, \"lua\", \"start\", {\n\t\tport = 8888,\n\t\tmaxclient = max_client,\n\t\tnodelay = true,\n\t})\n\tskynet.error(\"Watchdog listen on \" .. addr .. \":\" .. port)\n\tskynet.exit()\nend)\n"
  },
  {
    "path": "examples/main_log.lua",
    "content": "local skynet = require \"skynet\"\nlocal harbor = require \"skynet.harbor\"\nrequire \"skynet.manager\"\t-- import skynet.monitor\n\nlocal function monitor_master()\n\tharbor.linkmaster()\n\tprint(\"master is down\")\n\tskynet.exit()\nend\n\nskynet.start(function()\n\tprint(\"Log server start\")\n\tskynet.monitor \"simplemonitor\"\n\tlocal log = skynet.newservice(\"globallog\")\n\tskynet.fork(monitor_master)\nend)\n\n"
  },
  {
    "path": "examples/main_mongodb.lua",
    "content": "local skynet = require \"skynet\"\n\n\nskynet.start(function()\n\tprint(\"Main Server start\")\n\tlocal console = skynet.newservice(\n\t\t\"testmongodb\", \"127.0.0.1\", 27017, \"testdb\", \"test\", \"test\"\n\t)\n\t\n\tprint(\"Main Server exit\")\n\tskynet.exit()\nend)\n"
  },
  {
    "path": "examples/main_mysql.lua",
    "content": "local skynet = require \"skynet\"\n\n\nskynet.start(function()\n\tprint(\"Main Server start\")\n\tlocal console = skynet.newservice(\"testmysql\")\n\t\n\tprint(\"Main Server exit\")\n\tskynet.exit()\nend)\n"
  },
  {
    "path": "examples/preload.lua",
    "content": "-- This file will execute before every lua service start\n-- See config\n\nprint(\"PRELOAD\", ...)\n\n"
  },
  {
    "path": "examples/proto.lua",
    "content": "local sprotoparser = require \"sprotoparser\"\n\nlocal proto = {}\n\nproto.c2s = sprotoparser.parse [[\n.package {\n\ttype 0 : integer\n\tsession 1 : integer\n}\n\nhandshake 1 {\n\tresponse {\n\t\tmsg 0  : string\n\t}\n}\n\nget 2 {\n\trequest {\n\t\twhat 0 : string\n\t}\n\tresponse {\n\t\tresult 0 : string\n\t}\n}\n\nset 3 {\n\trequest {\n\t\twhat 0 : string\n\t\tvalue 1 : string\n\t}\n}\n\nquit 4 {}\n\n]]\n\nproto.s2c = sprotoparser.parse [[\n.package {\n\ttype 0 : integer\n\tsession 1 : integer\n}\n\nheartbeat 1 {}\n]]\n\nreturn proto\n"
  },
  {
    "path": "examples/protoloader.lua",
    "content": "-- module proto as examples/proto.lua\npackage.path = \"./examples/?.lua;\" .. package.path\n\nlocal skynet = require \"skynet\"\nlocal sprotoparser = require \"sprotoparser\"\nlocal sprotoloader = require \"sprotoloader\"\nlocal proto = require \"proto\"\n\nskynet.start(function()\n\tsprotoloader.save(proto.c2s, 1)\n\tsprotoloader.save(proto.s2c, 2)\n\t-- don't call skynet.exit() , because sproto.core may unload and the global slot become invalid\nend)\n"
  },
  {
    "path": "examples/share.lua",
    "content": "local skynet = require \"skynet\"\nlocal sharedata = require \"skynet.sharedata\"\n\nlocal mode = ...\n\nif mode == \"host\" then\n\nskynet.start(function()\n\tskynet.error(\"new foobar\")\n\tsharedata.new(\"foobar\", { a=1, b= { \"hello\",  \"world\" } })\n\n\tskynet.fork(function()\n\t\tskynet.sleep(200)\t-- sleep 2s\n\t\tskynet.error(\"update foobar a = 2\")\n\t\tsharedata.update(\"foobar\", { a =2 })\n\t\tskynet.sleep(200)\t-- sleep 2s\n\t\tskynet.error(\"update foobar a = 3\")\n\t\tsharedata.update(\"foobar\", { a = 3, b = { \"change\" } })\n\t\tskynet.sleep(100)\n\t\tskynet.error(\"delete foobar\")\n\t\tsharedata.delete \"foobar\"\n\tend)\nend)\n\nelse\n\n\nskynet.start(function()\n\tskynet.newservice(SERVICE_NAME, \"host\")\n\n\tlocal obj = sharedata.query \"foobar\"\n\n\tlocal b = obj.b\n\tskynet.error(string.format(\"a=%d\", obj.a))\n\n\tfor k,v in ipairs(b) do\n\t\tskynet.error(string.format(\"b[%d]=%s\", k,v))\n\tend\n\n\t-- test lua serialization\n\tlocal s = skynet.packstring(obj)\n\tlocal nobj = skynet.unpack(s)\n\tfor k,v in pairs(nobj) do\n\t\tskynet.error(string.format(\"nobj[%s]=%s\", k,v))\n\tend\n\tfor k,v in ipairs(nobj.b) do\n\t\tskynet.error(string.format(\"nobj.b[%d]=%s\", k,v))\n\tend\n\n\tfor i = 1, 5 do\n\t\tskynet.sleep(100)\n\t\tskynet.error(\"second \" ..i)\n\t\tfor k,v in pairs(obj) do\n\t\t\tskynet.error(string.format(\"%s = %s\", k , tostring(v)))\n\t\tend\n\tend\n\n\tlocal ok, err = pcall(function()\n\t\tlocal tmp = { b[1], b[2] }\t-- b is invalid , so pcall should failed\n\tend)\n\n\tif not ok then\n\t\tskynet.error(err)\n\tend\n\n\t-- obj. b is not the same with local b\n\tfor k,v in ipairs(obj.b) do\n\t\tskynet.error(string.format(\"b[%d] = %s\", k , tostring(v)))\n\tend\n\n\tcollectgarbage()\n\tskynet.error(\"sleep\")\n\tskynet.sleep(100)\n\tb = nil\n\tcollectgarbage()\n\tskynet.error(\"sleep\")\n\tskynet.sleep(100)\n\n\tskynet.exit()\nend)\n\nend\n"
  },
  {
    "path": "examples/simpledb.lua",
    "content": "local skynet = require \"skynet\"\nrequire \"skynet.manager\"\t-- import skynet.register\nlocal db = {}\n\nlocal command = {}\n\nfunction command.GET(key)\n\treturn db[key]\nend\n\nfunction command.SET(key, value)\n\tlocal last = db[key]\n\tdb[key] = value\n\treturn last\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(session, address, cmd, ...)\n\t\tcmd = cmd:upper()\n\t\tif cmd == \"PING\" then\n\t\t\tassert(session == 0)\n\t\t\tlocal str = (...)\n\t\t\tif #str > 20 then\n\t\t\t\tstr = str:sub(1,20) .. \"...(\" .. #str .. \")\"\n\t\t\tend\n\t\t\tskynet.error(string.format(\"%s ping %s\", skynet.address(address), str))\n\t\t\treturn\n\t\tend\n\t\tlocal f = command[cmd]\n\t\tif f then\n\t\t\tskynet.ret(skynet.pack(f(...)))\n\t\telse\n\t\t\terror(string.format(\"Unknown command %s\", tostring(cmd)))\n\t\tend\n\tend)\n--\tskynet.traceproto(\"lua\", false)\t-- true off tracelog\n\tskynet.register \"SIMPLEDB\"\nend)\n"
  },
  {
    "path": "examples/simplemonitor.lua",
    "content": "local skynet = require \"skynet\"\n\n-- It's a simple service exit monitor, you can do something more when a service exit.\n\nlocal service_map = {}\n\nskynet.register_protocol {\n\tname = \"client\",\n\tid = skynet.PTYPE_CLIENT,\t-- PTYPE_CLIENT = 3\n\tunpack = function() end,\n\tdispatch = function(_, address)\n\t\tlocal w = service_map[address]\n\t\tif w then\n\t\t\tfor watcher in pairs(w) do\n\t\t\t\tskynet.redirect(watcher, address, \"error\", 0, \"\")\n\t\t\tend\n\t\t\tservice_map[address] = false\n\t\tend\n\tend\n}\n\nlocal function monitor(session, watcher, command, service)\n\tassert(command, \"WATCH\")\n\tlocal w = service_map[service]\n\tif not w then\n\t\tif w == false then\n\t\t\tskynet.ret(skynet.pack(false))\n\t\t\treturn\n\t\tend\n\t\tw = {}\n\t\tservice_map[service] = w\n\tend\n\tw[watcher] = true\n\tskynet.ret(skynet.pack(true))\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", monitor)\nend)\n"
  },
  {
    "path": "examples/simpleweb.lua",
    "content": "local skynet = require \"skynet\"\nlocal socket = require \"skynet.socket\"\nlocal httpd = require \"http.httpd\"\nlocal sockethelper = require \"http.sockethelper\"\nlocal urllib = require \"http.url\"\nlocal table = table\nlocal string = string\n\nlocal mode, protocol = ...\nprotocol = protocol or \"http\"\n\nif mode == \"agent\" then\n\nlocal function response(id, write, ...)\n\tlocal ok, err = httpd.write_response(write, ...)\n\tif not ok then\n\t\t-- if err == sockethelper.socket_error , that means socket closed.\n\t\tskynet.error(string.format(\"fd = %d, %s\", id, err))\n\tend\nend\n\n\nlocal SSLCTX_SERVER = nil\nlocal function gen_interface(protocol, fd)\n\tif protocol == \"http\" then\n\t\treturn {\n\t\t\tinit = nil,\n\t\t\tclose = nil,\n\t\t\tread = sockethelper.readfunc(fd),\n\t\t\twrite = sockethelper.writefunc(fd),\n\t\t}\n\telseif protocol == \"https\" then\n\t\tlocal tls = require \"http.tlshelper\"\n\t\tif not SSLCTX_SERVER then\n\t\t\tSSLCTX_SERVER = tls.newctx()\n\t\t\t-- gen cert and key\n\t\t\t-- openssl req -x509 -newkey rsa:2048 -days 3650 -nodes -keyout server-key.pem -out server-cert.pem\n\t\t\tlocal certfile = skynet.getenv(\"certfile\") or \"./server-cert.pem\"\n\t\t\tlocal keyfile = skynet.getenv(\"keyfile\") or \"./server-key.pem\"\n\t\t\tprint(certfile, keyfile)\n\t\t\tSSLCTX_SERVER:set_cert(certfile, keyfile)\n\t\tend\n\t\tlocal tls_ctx = tls.newtls(\"server\", SSLCTX_SERVER)\n\t\treturn {\n\t\t\tinit = tls.init_responsefunc(fd, tls_ctx),\n\t\t\tclose = tls.closefunc(tls_ctx),\n\t\t\tread = tls.readfunc(fd, tls_ctx),\n\t\t\twrite = tls.writefunc(fd, tls_ctx),\n\t\t}\n\telse\n\t\terror(string.format(\"Invalid protocol: %s\", protocol))\n\tend\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function (_,_,id)\n\t\tsocket.start(id)\n\t\tlocal interface = gen_interface(protocol, id)\n\t\tif interface.init then\n\t\t\tinterface.init()\n\t\tend\n\t\t-- limit request body size to 8192 (you can pass nil to unlimit)\n\t\tlocal code, url, method, header, body = httpd.read_request(interface.read, 8192)\n\t\tif code then\n\t\t\tif code ~= 200 then\n\t\t\t\tresponse(id, interface.write, code)\n\t\t\telse\n\t\t\t\tlocal tmp = {}\n\t\t\t\tif header.host then\n\t\t\t\t\ttable.insert(tmp, string.format(\"host: %s\", header.host))\n\t\t\t\tend\n\t\t\t\tlocal path, query = urllib.parse(url)\n\t\t\t\ttable.insert(tmp, string.format(\"path: %s\", path))\n\t\t\t\tif query then\n\t\t\t\t\tlocal q = urllib.parse_query(query)\n\t\t\t\t\tfor k, v in pairs(q) do\n\t\t\t\t\t\ttable.insert(tmp, string.format(\"query: %s= %s\", k,v))\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\ttable.insert(tmp, \"-----header----\")\n\t\t\t\tfor k,v in pairs(header) do\n\t\t\t\t\ttable.insert(tmp, string.format(\"%s = %s\",k,v))\n\t\t\t\tend\n\t\t\t\ttable.insert(tmp, \"-----body----\\n\" .. body)\n\t\t\t\tresponse(id, interface.write, code, table.concat(tmp,\"\\n\"))\n\t\t\tend\n\t\telse\n\t\t\tif url == sockethelper.socket_error then\n\t\t\t\tskynet.error(\"socket closed\")\n\t\t\telse\n\t\t\t\tskynet.error(url)\n\t\t\tend\n\t\tend\n\t\tsocket.close(id)\n\t\tif interface.close then\n\t\t\tinterface.close()\n\t\tend\n\tend)\nend)\n\nelse\n\nskynet.start(function()\n\tlocal agent = {}\n\tlocal protocol = \"http\"\n\tfor i= 1, 20 do\n\t\tagent[i] = skynet.newservice(SERVICE_NAME, \"agent\", protocol)\n\tend\n\tlocal balance = 1\n\tlocal id = socket.listen(\"0.0.0.0\", 8001)\n\tskynet.error(string.format(\"Listen web port 8001 protocol:%s\", protocol))\n\tsocket.start(id , function(id, addr)\n\t\tskynet.error(string.format(\"%s connected, pass it to agent :%08x\", addr, agent[balance]))\n\t\tskynet.send(agent[balance], \"lua\", id)\n\t\tbalance = balance + 1\n\t\tif balance > #agent then\n\t\t\tbalance = 1\n\t\tend\n\tend)\nend)\n\nend"
  },
  {
    "path": "examples/simplewebsocket.lua",
    "content": "local skynet = require \"skynet\"\nlocal socket = require \"skynet.socket\"\nlocal service = require \"skynet.service\"\nlocal websocket = require \"http.websocket\"\n\nlocal handle = {}\nlocal MODE = ...\n\nif MODE == \"agent\" then\n    function handle.connect(id)\n        print(\"ws connect from: \" .. tostring(id))\n    end\n\n    function handle.handshake(id, header, url)\n        local addr = websocket.addrinfo(id)\n        print(\"ws handshake from: \" .. tostring(id), \"url\", url, \"addr:\", addr)\n        print(\"----header-----\")\n        for k,v in pairs(header) do\n            print(k,v)\n        end\n        print(\"--------------\")\n    end\n\n    function handle.message(id, msg, msg_type)\n        assert(msg_type == \"binary\" or msg_type == \"text\")\n        websocket.write(id, msg)\n    end\n\n    function handle.ping(id)\n        print(\"ws ping from: \" .. tostring(id) .. \"\\n\")\n    end\n\n    function handle.pong(id)\n        print(\"ws pong from: \" .. tostring(id))\n    end\n\n    function handle.close(id, code, reason)\n        print(\"ws close from: \" .. tostring(id), code, reason)\n    end\n\n    function handle.error(id)\n        print(\"ws error from: \" .. tostring(id))\n    end\n\n    skynet.start(function ()\n        skynet.dispatch(\"lua\", function (_,_, id, protocol, addr)\n            local ok, err = websocket.accept(id, handle, protocol, addr)\n            if not ok then\n                print(err)\n            end\n        end)\n    end)\n\nelse\n    local function simple_echo_client_service(protocol)\n        local skynet = require \"skynet\"\n        local websocket = require \"http.websocket\"\n        local url = string.format(\"%s://127.0.0.1:9948/test_websocket\", protocol)\n        local ws_id = websocket.connect(url)\n        while true do\n            local msg = \"hello world!\"\n            websocket.write(ws_id, msg)\n            print(\">: \" .. msg)\n            local resp, close_reason = websocket.read(ws_id)\n            print(\"<: \" .. (resp and resp or \"[Close] \" .. close_reason))\n            if not resp then\n                print(\"echo server close.\")\n                break\n            end\n            websocket.ping(ws_id)\n            skynet.sleep(100)\n        end\n    end\n\n    skynet.start(function ()\n        local agent = {}\n        for i= 1, 20 do\n            agent[i] = skynet.newservice(SERVICE_NAME, \"agent\")\n        end\n        local balance = 1\n        local protocol = \"ws\"\n        local id = socket.listen(\"0.0.0.0\", 9948)\n        skynet.error(string.format(\"Listen websocket port 9948 protocol:%s\", protocol))\n        socket.start(id, function(id, addr)\n            print(string.format(\"accept client socket_id: %s addr:%s\", id, addr))\n            skynet.send(agent[balance], \"lua\", id, protocol, addr)\n            balance = balance + 1\n            if balance > #agent then\n                balance = 1\n            end\n        end)\n        -- test echo client\n        service.new(\"websocket_echo_client\", simple_echo_client_service, protocol)\n    end)\nend"
  },
  {
    "path": "examples/userlog.lua",
    "content": "local skynet = require \"skynet\"\nrequire \"skynet.manager\"\n\n-- register protocol text before skynet.start would be better.\nskynet.register_protocol {\n\tname = \"text\",\n\tid = skynet.PTYPE_TEXT,\n\tunpack = skynet.tostring,\n\tdispatch = function(_, address, msg)\n\t\tprint(string.format(\":%08x(%.2f): %s\", address, skynet.time(), msg))\n\tend\n}\n\nskynet.register_protocol {\n\tname = \"SYSTEM\",\n\tid = skynet.PTYPE_SYSTEM,\n\tunpack = function(...) return ... end,\n\tdispatch = function()\n\t\t-- reopen signal\n\t\tprint(\"SIGHUP\")\n\tend\n}\n\nskynet.start(function()\nend)"
  },
  {
    "path": "examples/watchdog.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal CMD = {}\nlocal SOCKET = {}\nlocal gate\nlocal agent = {}\n\nfunction SOCKET.open(fd, addr)\n\tskynet.error(\"New client from : \" .. addr)\n\tagent[fd] = skynet.newservice(\"agent\")\n\tskynet.call(agent[fd], \"lua\", \"start\", { gate = gate, client = fd, watchdog = skynet.self() })\nend\n\nlocal function close_agent(fd)\n\tlocal a = agent[fd]\n\tagent[fd] = nil\n\tif a then\n\t\tskynet.call(gate, \"lua\", \"kick\", fd)\n\t\t-- disconnect never return\n\t\tskynet.send(a, \"lua\", \"disconnect\")\n\tend\nend\n\nfunction SOCKET.close(fd)\n\tprint(\"socket close\",fd)\n\tclose_agent(fd)\nend\n\nfunction SOCKET.error(fd, msg)\n\tprint(\"socket error\",fd, msg)\n\tclose_agent(fd)\nend\n\nfunction SOCKET.warning(fd, size)\n\t-- size K bytes havn't send out in fd\n\tprint(\"socket warning\", fd, size)\nend\n\nfunction SOCKET.data(fd, msg)\nend\n\nfunction CMD.start(conf)\n\treturn skynet.call(gate, \"lua\", \"open\" , conf)\nend\n\nfunction CMD.close(fd)\n\tclose_agent(fd)\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(session, source, cmd, subcmd, ...)\n\t\tif cmd == \"socket\" then\n\t\t\tlocal f = SOCKET[subcmd]\n\t\t\tf(...)\n\t\t\t-- socket api don't need return\n\t\telse\n\t\t\tlocal f = assert(CMD[cmd])\n\t\t\tskynet.ret(skynet.pack(f(subcmd, ...)))\n\t\tend\n\tend)\n\n\tgate = skynet.newservice(\"gate\")\nend)\n"
  },
  {
    "path": "lualib/compat10/cluster.lua",
    "content": "return require \"skynet.cluster\""
  },
  {
    "path": "lualib/compat10/crypt.lua",
    "content": "return require \"skynet.crypt\""
  },
  {
    "path": "lualib/compat10/datacenter.lua",
    "content": "return require \"skynet.datacenter\""
  },
  {
    "path": "lualib/compat10/dns.lua",
    "content": "return require \"skynet.dns\""
  },
  {
    "path": "lualib/compat10/memory.lua",
    "content": "return require \"skynet.memory\""
  },
  {
    "path": "lualib/compat10/mongo.lua",
    "content": "return require \"skynet.db.mongo\""
  },
  {
    "path": "lualib/compat10/mqueue.lua",
    "content": "return require \"skynet.mqueue\""
  },
  {
    "path": "lualib/compat10/multicast.lua",
    "content": "return require \"skynet.multicast\""
  },
  {
    "path": "lualib/compat10/mysql.lua",
    "content": "return require \"skynet.db.mysql\""
  },
  {
    "path": "lualib/compat10/netpack.lua",
    "content": "return require \"skynet.netpack\""
  },
  {
    "path": "lualib/compat10/profile.lua",
    "content": "return require \"skynet.profile\""
  },
  {
    "path": "lualib/compat10/redis.lua",
    "content": "return require \"skynet.db.redis\""
  },
  {
    "path": "lualib/compat10/sharedata.lua",
    "content": "return require \"skynet.sharedata\""
  },
  {
    "path": "lualib/compat10/sharemap.lua",
    "content": "return require \"skynet.sharemap\""
  },
  {
    "path": "lualib/compat10/snax.lua",
    "content": "return require \"skynet.snax\""
  },
  {
    "path": "lualib/compat10/socket.lua",
    "content": "return require \"skynet.socket\""
  },
  {
    "path": "lualib/compat10/socketchannel.lua",
    "content": "return require \"skynet.socketchannel\""
  },
  {
    "path": "lualib/compat10/socketdriver.lua",
    "content": "return require \"skynet.socketdriver\""
  },
  {
    "path": "lualib/compat10/stm.lua",
    "content": "return require \"skynet.stm\""
  },
  {
    "path": "lualib/http/httpc.lua",
    "content": "local skynet = require \"skynet\"\nlocal socket = require \"http.sockethelper\"\nlocal internal = require \"http.internal\"\nlocal dns = require \"skynet.dns\"\n\nlocal string = string\nlocal table = table\nlocal pcall = pcall\nlocal error = error\nlocal pairs = pairs\n\nlocal httpc = {}\n\nlocal async_dns\n\nfunction httpc.dns(server,port)\n\tasync_dns = true\n\tdns.server(server,port)\nend\n\nlocal default_port = {\n\thttp = 80,\n\thttps = 443,\n}\n\nlocal function hostname_port(host)\n\tif host:find \".*:.*:\" then\n\t\t-- If host contains 2 or more \":\", it's ipv6 address\n\t\tlocal ipv6, port = host:match \"^%[(.-)%]:(%d+)$\"\n\t\tif ipv6 then\n\t\t\treturn ipv6, port\n\t\telse\n\t\t\treturn host\n\t\tend\n\tend\n\tlocal hostname, port = host:match \"(.-):(%d+)$\"\n\tif hostname then\n\t\treturn hostname, port\n\tend\n\treturn host\nend\n\nlocal function check_protocol(host)\n\tlocal protocol, hostname = host:match \"^(%a+)://(.*)\"\n\tif protocol then\n\t\tprotocol = string.lower(protocol)\n\telse\n\t\tprotocol = \"http\"\n\t\thostname = host\n\tend\n\thostname, port = hostname_port(hostname)\n\treturn protocol, hostname, port or default_port[protocol] or error(\"Invalid protocol: \" .. protocol)\nend\n\nlocal SSLCTX_CLIENT = nil\nlocal function gen_interface(protocol, fd, hostname)\n\tif protocol == \"http\" then\n\t\treturn {\n\t\t\tinit = nil,\n\t\t\tclose = nil,\n\t\t\tread = socket.readfunc(fd),\n\t\t\twrite = socket.writefunc(fd),\n\t\t\treadall = function ()\n\t\t\t\treturn socket.readall(fd)\n\t\t\tend,\n\t\t}\n\telseif protocol == \"https\" then\n\t\tlocal tls = require \"http.tlshelper\"\n\t\tSSLCTX_CLIENT = SSLCTX_CLIENT or tls.newctx()\n\t\tlocal tls_ctx = tls.newtls(\"client\", SSLCTX_CLIENT, hostname)\n\t\treturn {\n\t\t\tinit = tls.init_requestfunc(fd, tls_ctx),\n\t\t\tclose = tls.closefunc(tls_ctx),\n\t\t\tread = tls.readfunc(fd, tls_ctx),\n\t\t\twrite = tls.writefunc(fd, tls_ctx),\n\t\t\treadall = tls.readallfunc(fd, tls_ctx),\n\t\t}\n\telse\n\t\terror(string.format(\"Invalid protocol: %s\", protocol))\n\tend\nend\n\nlocal function connect(host, timeout)\n\tlocal protocol, host, port = check_protocol(host)\n\tlocal hostaddr = host\n\tlocal hostname\n\tif host:find \"^[^:]-%D$\" then\n\t\t-- it's a hostname (not ip address), because\n\t\t--   ipv6 contains colons\n\t\t--   ipv4 end with a digit\n\t\thostname = host\n\t\tif async_dns then\n\t\t\tlocal msg\n\t\t\thostaddr, msg = dns.resolve(host)\n\t\t\tif not hostaddr then\n\t\t\t\terror(string.format(\"%s dns resolve failed msg:%s\", host, msg))\n\t\t\tend\n\t\tend\n\tend\n\n\tlocal fd = socket.connect(hostaddr, port, timeout)\n\tif not fd then\n\t\terror(string.format(\"%s connect error host:%s, port:%s, timeout:%s\", protocol, host, port, timeout))\n\tend\n\tlocal interface = gen_interface(protocol, fd, hostname)\n\tif timeout then\n\t\tskynet.timeout(timeout, function()\n\t\t\tif not interface.finish then\n\t\t\t\tsocket.shutdown(fd)\t-- shutdown the socket fd, need close later.\n\t\t\tend\n\t\tend)\n\tend\n\tif interface.init then\n\t\tinterface.init(host)\n\tend\n\treturn fd, interface, host\nend\n\nlocal function close_interface(interface, fd)\n\tinterface.finish = true\n\tsocket.close(fd)\n\tif interface.close then\n\t\tinterface.close()\n\t\tinterface.close = nil\n\tend\nend\n\nfunction httpc.request(method, hostname, url, recvheader, header, content)\n\tlocal fd, interface, host = connect(hostname, httpc.timeout)\n\tlocal ok , statuscode, body , header = pcall(internal.request, interface, method, host, url, recvheader, header, content)\n\tif ok then\n\t\tok, body = pcall(internal.response, interface, statuscode, body, header)\n\tend\n\tclose_interface(interface, fd)\n\tif ok then\n\t\treturn statuscode, body\n\telse\n\t\terror(body or statuscode)\n\tend\nend\n\nfunction httpc.head(hostname, url, recvheader, header, content)\n\tlocal fd, interface, host = connect(hostname, httpc.timeout)\n\tlocal ok , statuscode = pcall(internal.request, interface, \"HEAD\", host, url, recvheader, header, content)\n\tclose_interface(interface, fd)\n\tif ok then\n\t\treturn statuscode\n\telse\n\t\terror(statuscode)\n\tend\nend\n\nfunction httpc.request_stream(method, hostname, url, recvheader, header, content)\n\tlocal fd, interface, host = connect(hostname, httpc.timeout)\n\tlocal ok , statuscode, body , header = pcall(internal.request, interface, method, host, url, recvheader, header, content)\n\tinterface.finish = true -- don't shutdown fd in timeout\n\tlocal function close_fd()\n\t\tclose_interface(interface, fd)\n\tend\n\tif not ok then\n\t\tclose_fd()\n\t\terror(statuscode)\n\tend\n\t-- todo: stream support timeout\n\tlocal stream = internal.response_stream(interface, statuscode, body, header)\n\tstream._onclose = close_fd\n\treturn stream\nend\n\nfunction httpc.get(...)\n\treturn httpc.request(\"GET\", ...)\nend\n\nlocal function escape(s)\n\treturn (string.gsub(s, \"([^A-Za-z0-9_])\", function(c)\n\t\treturn string.format(\"%%%02X\", string.byte(c))\n\tend))\nend\n\nfunction httpc.post(host, url, form, recvheader)\n\tlocal header = {\n\t\t[\"content-type\"] = \"application/x-www-form-urlencoded\"\n\t}\n\tlocal body = {}\n\tfor k,v in pairs(form) do\n\t\ttable.insert(body, string.format(\"%s=%s\",escape(k),escape(v)))\n\tend\n\n\treturn httpc.request(\"POST\", host, url, recvheader, header, table.concat(body , \"&\"))\nend\n\nreturn httpc\n"
  },
  {
    "path": "lualib/http/httpd.lua",
    "content": "local internal = require \"http.internal\"\n\nlocal string = string\nlocal type = type\nlocal assert = assert\nlocal tonumber = tonumber\nlocal pcall = pcall\nlocal ipairs = ipairs\nlocal pairs = pairs\n\nlocal httpd = {}\n\nlocal http_status_msg = {\n\t[100] = \"Continue\",\n\t[101] = \"Switching Protocols\",\n\t[200] = \"OK\",\n\t[201] = \"Created\",\n\t[202] = \"Accepted\",\n\t[203] = \"Non-Authoritative Information\",\n\t[204] = \"No Content\",\n\t[205] = \"Reset Content\",\n\t[206] = \"Partial Content\",\n\t[300] = \"Multiple Choices\",\n\t[301] = \"Moved Permanently\",\n\t[302] = \"Found\",\n\t[303] = \"See Other\",\n\t[304] = \"Not Modified\",\n\t[305] = \"Use Proxy\",\n\t[307] = \"Temporary Redirect\",\n\t[400] = \"Bad Request\",\n\t[401] = \"Unauthorized\",\n\t[402] = \"Payment Required\",\n\t[403] = \"Forbidden\",\n\t[404] = \"Not Found\",\n\t[405] = \"Method Not Allowed\",\n\t[406] = \"Not Acceptable\",\n\t[407] = \"Proxy Authentication Required\",\n\t[408] = \"Request Time-out\",\n\t[409] = \"Conflict\",\n\t[410] = \"Gone\",\n\t[411] = \"Length Required\",\n\t[412] = \"Precondition Failed\",\n\t[413] = \"Request Entity Too Large\",\n\t[414] = \"Request-URI Too Large\",\n\t[415] = \"Unsupported Media Type\",\n\t[416] = \"Requested range not satisfiable\",\n\t[417] = \"Expectation Failed\",\n\t[500] = \"Internal Server Error\",\n\t[501] = \"Not Implemented\",\n\t[502] = \"Bad Gateway\",\n\t[503] = \"Service Unavailable\",\n\t[504] = \"Gateway Time-out\",\n\t[505] = \"HTTP Version not supported\",\n}\n\nlocal function readall(readbytes, bodylimit)\n\tlocal tmpline = {}\n\tlocal body = internal.recvheader(readbytes, tmpline, \"\")\n\tif not body then\n\t\treturn 413\t-- Request Entity Too Large\n\tend\n\tlocal request = assert(tmpline[1])\n\tlocal method, url, httpver = request:match \"^(%a+)%s+(.-)%s+HTTP/([%d%.]+)$\"\n\tassert(method and url and httpver)\n\thttpver = assert(tonumber(httpver))\n\tif httpver < 1.0 or httpver > 1.1 then\n\t\treturn 505\t-- HTTP Version not supported\n\tend\n\tlocal header = internal.parseheader(tmpline,2,{})\n\tif not header then\n\t\treturn 400\t-- Bad request\n\tend\n\tlocal length = header[\"content-length\"]\n\tif length then\n\t\tlength = tonumber(length)\n\tend\n\tlocal mode = header[\"transfer-encoding\"]\n\tif mode then\n\t\tif mode ~= \"identity\" and mode ~= \"chunked\" then\n\t\t\treturn 501\t-- Not Implemented\n\t\tend\n\tend\n\n\tif mode == \"chunked\" then\n\t\tbody, header = internal.recvchunkedbody(readbytes, bodylimit, header, body)\n\t\tif not body then\n\t\t\treturn 413\n\t\tend\n\telse\n\t\t-- identity mode\n\t\tif length then\n\t\t\tif bodylimit and length > bodylimit then\n\t\t\t\treturn 413\n\t\t\tend\n\t\t\tif #body >= length then\n\t\t\t\tbody = body:sub(1,length)\n\t\t\telse\n\t\t\t\tlocal padding = readbytes(length - #body)\n\t\t\t\tbody = body .. padding\n\t\t\tend\n\t\tend\n\tend\n\n\treturn 200, url, method, header, body\nend\n\nfunction httpd.read_request(...)\n\tlocal ok, code, url, method, header, body = pcall(readall, ...)\n\tif ok then\n\t\treturn code, url, method, header, body\n\telse\n\t\treturn nil, code\n\tend\nend\n\nlocal function writeall(writefunc, statuscode, bodyfunc, header)\n\tlocal statusline = string.format(\"HTTP/1.1 %03d %s\\r\\n\", statuscode, http_status_msg[statuscode] or \"\")\n\twritefunc(statusline)\n\tif header then\n\t\tfor k,v in pairs(header) do\n\t\t\tif type(v) == \"table\" then\n\t\t\t\tfor _,v in ipairs(v) do\n\t\t\t\t\twritefunc(string.format(\"%s: %s\\r\\n\", k,v))\n\t\t\t\tend\n\t\t\telse\n\t\t\t\twritefunc(string.format(\"%s: %s\\r\\n\", k,v))\n\t\t\tend\n\t\tend\n\tend\n\tlocal t = type(bodyfunc)\n\tif t == \"string\" then\n\t\twritefunc(string.format(\"content-length: %d\\r\\n\\r\\n\", #bodyfunc))\n\t\twritefunc(bodyfunc)\n\telseif t == \"function\" then\n\t\twritefunc(\"transfer-encoding: chunked\\r\\n\")\n\t\twhile true do\n\t\t\tlocal s = bodyfunc()\n\t\t\tif s then\n\t\t\t\tif s ~= \"\" then\n\t\t\t\t\twritefunc(string.format(\"\\r\\n%x\\r\\n\", #s))\n\t\t\t\t\twritefunc(s)\n\t\t\t\tend\n\t\t\telse\n\t\t\t\twritefunc(\"\\r\\n0\\r\\n\\r\\n\")\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\telse\n\t\tassert(t == \"nil\")\n\t\twritefunc(\"\\r\\n\")\n\tend\nend\n\nfunction httpd.write_response(...)\n\treturn pcall(writeall, ...)\nend\n\nreturn httpd\n"
  },
  {
    "path": "lualib/http/internal.lua",
    "content": "local table = table\nlocal type = type\nlocal string = string\nlocal tonumber = tonumber\nlocal pcall = pcall\nlocal assert = assert\nlocal error = error\nlocal pairs = pairs\n\nlocal M = {}\n\nlocal LIMIT = 8192\n\nlocal function chunksize(readbytes, body)\n\twhile true do\n\t\tlocal f,e = body:find(\"\\r\\n\",1,true)\n\t\tif f then\n\t\t\treturn tonumber(body:sub(1,f-1),16), body:sub(e+1)\n\t\tend\n\t\tif #body > 128 then\n\t\t\t-- pervent the attacker send very long stream without \\r\\n\n\t\t\treturn\n\t\tend\n\t\tbody = body .. readbytes()\n\tend\nend\n\nlocal function readcrln(readbytes, body)\n\tif #body >= 2 then\n\t\tif body:sub(1,2) ~= \"\\r\\n\" then\n\t\t\treturn\n\t\tend\n\t\treturn body:sub(3)\n\telse\n\t\tbody = body .. readbytes(2-#body)\n\t\tif body ~= \"\\r\\n\" then\n\t\t\treturn\n\t\tend\n\t\treturn \"\"\n\tend\nend\n\nfunction M.recvheader(readbytes, lines, header)\n\tif #header >= 2 then\n\t\tif header:find \"^\\r\\n\" then\n\t\t\treturn header:sub(3)\n\t\tend\n\tend\n\tlocal result\n\tlocal e = header:find(\"\\r\\n\\r\\n\", 1, true)\n\tif e then\n\t\tresult = header:sub(e+4)\n\telse\n\t\twhile true do\n\t\t\tlocal bytes = readbytes()\n\t\t\theader = header .. bytes\n\t\t\te = header:find(\"\\r\\n\\r\\n\", -#bytes-3, true)\n\t\t\tif e then\n\t\t\t\tresult = header:sub(e+4)\n\t\t\t\tbreak\n\t\t\tend\n\t\t\tif header:find \"^\\r\\n\" then\n\t\t\t\treturn header:sub(3)\n\t\t\tend\n\t\t\tif #header > LIMIT then\n\t\t\t\treturn\n\t\t\tend\n\t\tend\n\tend\n\tfor v in header:gmatch(\"(.-)\\r\\n\") do\n\t\tif v == \"\" then\n\t\t\tbreak\n\t\tend\n\t\ttable.insert(lines, v)\n\tend\n\treturn result\nend\n\nfunction M.parseheader(lines, from, header)\n\tlocal name, value\n\tfor i=from,#lines do\n\t\tlocal line = lines[i]\n\t\tif line:byte(1) == 9 then\t-- tab, append last line\n\t\t\tif name == nil then\n\t\t\t\treturn\n\t\t\tend\n\t\t\theader[name] = header[name] .. line:sub(2)\n\t\telse\n\t\t\tname, value = line:match \"^(.-):%s*(.*)\"\n\t\t\tif name == nil or value == nil then\n\t\t\t\treturn\n\t\t\tend\n\t\t\tname = name:lower()\n\t\t\tif header[name] then\n\t\t\t\tlocal v = header[name]\n\t\t\t\tif type(v) == \"table\" then\n\t\t\t\t\ttable.insert(v, value)\n\t\t\t\telse\n\t\t\t\t\theader[name] = { v , value }\n\t\t\t\tend\n\t\t\telse\n\t\t\t\theader[name] = value\n\t\t\tend\n\t\tend\n\tend\n\treturn header\nend\n\nfunction M.recvchunkedbody(readbytes, bodylimit, header, body)\n\tlocal result = \"\"\n\tlocal size = 0\n\n\twhile true do\n\t\tlocal sz\n\t\tsz , body = chunksize(readbytes, body)\n\t\tif not sz then\n\t\t\treturn\n\t\tend\n\t\tif sz == 0 then\n\t\t\tbreak\n\t\tend\n\t\tsize = size + sz\n\t\tif bodylimit and size > bodylimit then\n\t\t\treturn\n\t\tend\n\t\tif #body >= sz then\n\t\t\tresult = result .. body:sub(1,sz)\n\t\t\tbody = body:sub(sz+1)\n\t\telse\n\t\t\tresult = result .. body .. readbytes(sz - #body)\n\t\t\tbody = \"\"\n\t\tend\n\t\tbody = readcrln(readbytes, body)\n\t\tif not body then\n\t\t\treturn\n\t\tend\n\tend\n\n\tlocal tmpline = {}\n\tbody = M.recvheader(readbytes, tmpline, body)\n\tif not body then\n\t\treturn\n\tend\n\n\theader = M.parseheader(tmpline,1,header)\n\n\treturn result, header\nend\n\nlocal function recvbody(interface, code, header, body)\n\tlocal length = header[\"content-length\"]\n\tif length then\n\t\tlength = tonumber(length)\n\tend\n\tif length then\n\t\tif #body >= length then\n\t\t\tbody = body:sub(1,length)\n\t\telse\n\t\t\tlocal padding = interface.read(length - #body)\n\t\t\tbody = body .. padding\n\t\tend\n\telseif code == 204 or code == 304 or code < 200 then\n\t\tbody = \"\"\n\t\t-- See https://stackoverflow.com/questions/15991173/is-the-content-length-header-required-for-a-http-1-0-response\n\telse\n\t\t-- no content-length, read all\n\t\tbody = body .. interface.readall()\n\tend\n\treturn body\nend\n\nfunction M.request(interface, method, host, url, recvheader, header, content)\n\tlocal read = interface.read\n\tlocal write = interface.write\n\tlocal header_content = \"\"\n\tif header then\n\t\tif not header.Host then\n\t\t\theader.Host = host\n\t\tend\n\t\tfor k,v in pairs(header) do\n\t\t\theader_content = string.format(\"%s%s:%s\\r\\n\", header_content, k, v)\n\t\tend\n\telse\n\t\theader_content = string.format(\"host:%s\\r\\n\",host)\n\tend\n\n\tif content then\n\t\tlocal data\n\t\tif header and header[\"transfer-encoding\"] == \"chunked\" then\n\t\t\tdata = string.format(\"%s %s HTTP/1.1\\r\\n%s\\r\\n\", method, url, header_content)\n\t\telse\n\t\t\tdata = string.format(\"%s %s HTTP/1.1\\r\\n%sContent-length:%d\\r\\n\\r\\n\", method, url, header_content, #content)\n\t\tend\n\t\twrite(data)\n\t\twrite(content)\n\telse\n\t\tlocal request_header = string.format(\"%s %s HTTP/1.1\\r\\n%sContent-length:0\\r\\n\\r\\n\", method, url, header_content)\n\t\twrite(request_header)\n\tend\n\n\tlocal tmpline = {}\n\tlocal body = M.recvheader(read, tmpline, \"\")\n\tif not body then\n\t\terror(\"Recv header failed\")\n\tend\n\n\tlocal statusline = tmpline[1]\n\tlocal code, info = statusline:match \"HTTP/[%d%.]+%s+([%d]+)%s+(.*)$\"\n\tcode = assert(tonumber(code))\n\n\tlocal header = M.parseheader(tmpline,2,recvheader or {})\n\tif not header then\n\t\terror(\"Invalid HTTP response header\")\n\tend\n\treturn code, body, header\nend\n\nfunction M.response(interface, code, body, header)\n\tlocal mode = header[\"transfer-encoding\"]\n\tif mode then\n\t\tif mode ~= \"identity\" and mode ~= \"chunked\" then\n\t\t\terror (\"Unsupport transfer-encoding\")\n\t\tend\n\tend\n\n\tif mode == \"chunked\" then\n\t\tbody, header = M.recvchunkedbody(interface.read, nil, header, body)\n\t\tif not body then\n\t\t\terror(\"Invalid response body\")\n\t\tend\n\telse\n\t\t-- identity mode\n\t\tbody = recvbody(interface, code, header, body)\n\tend\n\n\treturn body\nend\n\nlocal stream = {}; stream.__index = stream\n\nfunction stream:close()\n\tif self._onclose then\n\t\tself._onclose(self)\n\t\tself._onclose = nil\n\tend\nend\n\nfunction stream:padding()\n\treturn self._reading(self), self\nend\n\nstream.__close = stream.close\nstream.__call = stream.padding\n\nlocal function stream_nobody(stream)\n\tstream._reading = stream.close\n\tstream.connected = nil\n\treturn \"\"\nend\n\nlocal function stream_length(length)\n\treturn function(stream)\n\t\tlocal body = stream._body\n\t\tif body == nil then\n\t\t\tlocal ret, padding = stream._interface.read()\n\t\t\tif not ret then\n\t\t\t\t-- disconnected\n\t\t\t\tbody = padding\n\t\t\t\tstream.connected = false\n\t\t\telse\n\t\t\t\tbody = ret\n\t\t\tend\n\t\tend\n\t\tlocal n = #body\n\t\tif n >= length then\n\t\t\tstream._reading = stream.close\n\t\t\tstream.connected = nil\n\t\t\treturn (body:sub(1,length))\n\t\telse\n\t\t\tlength = length - n\n\t\t\tstream._body = nil\n\t\t\tif not stream.connected then\n\t\t\t\tstream._reading = stream.close\n\t\t\tend\n\t\t\treturn body\n\t\tend\n\tend\nend\n\nlocal function stream_read(stream)\n\tlocal ret, padding = stream._interface.read()\n\tif ret == \"\" or not ret then\n\t\tstream.connected = nil\n\t\tstream:close()\n\t\tif padding == \"\" then\n\t\t\treturn\n\t\tend\n\t\treturn padding\n\tend\n\treturn ret\nend\n\nlocal function stream_all(stream)\n\tlocal body = stream._body\n\tstream._body = nil\n\tstream._reading = stream_read\n\treturn body\nend\n\nlocal function stream_chunked(stream)\n\tlocal read = stream._interface.read\n\tlocal sz, body = chunksize(read, stream._body)\n\tif not sz then\n\t\tstream.connected = false\n\t\tstream:close()\n\t\treturn\n\tend\n\n\tif sz == 0 then\n\t\t-- last chunk\n\t\tlocal tmpline = {}\n\t\tbody = M.recvheader(read, tmpline, body)\n\t\tif not body then\n\t\t\tstream.connected = false\n\t\t\tstream:close()\n\t\t\treturn\n\t\tend\n\n\t\tM.parseheader(tmpline,1, stream.header)\n\n\t\tstream._reading = stream.close\n\t\tstream.connected = nil\n\t\treturn \"\"\n\tend\n\n\tlocal n = #body\n\tlocal remain\n\n\tif n >= sz then\n\t\tremain = body:sub(sz+1)\n\t\tbody = body:sub(1,sz)\n\telse\n\t\tbody = body .. read(sz - n)\n\t\tremain = \"\"\n\tend\n\tremain = readcrln(read, remain)\n\tif not remain then\n\t\tstream.connected = false\n\t\tstream:close()\n\t\treturn\n\tend\n\tstream._body = remain\n\treturn body\nend\n\nfunction M.response_stream(interface, code, body, header)\n\tlocal mode = header[\"transfer-encoding\"]\n\tif mode then\n\t\tif mode ~= \"identity\" and mode ~= \"chunked\" then\n\t\t\terror (\"Unsupport transfer-encoding\")\n\t\tend\n\tend\n\n\tlocal read_func\n\n\tif mode == \"chunked\" then\n\t\tread_func = stream_chunked\n\telse\n\t\t-- identity mode\n\t\tlocal length = header[\"content-length\"]\n\t\tif length then\n\t\t\tlength = tonumber(length)\n\t\tend\n\t\tif length then\n\t\t\tread_func = stream_length(length)\n\t\telseif code == 204 or code == 304 or code < 200 then\n\t\t\tread_func = stream_nobody\n\t\telse\n\t\t\tread_func = stream_all\n\t\tend\n\tend\n\n\t-- todo: timeout\n\n\treturn setmetatable({\n\t\tstatus = code,\n\t\t_body = body,\n\t\t_interface = interface,\n\t\t_reading = read_func,\n\t\theader = header,\n\t\tconnected = true,\n\t}, stream)\nend\n\nreturn M\n"
  },
  {
    "path": "lualib/http/sockethelper.lua",
    "content": "local socket = require \"skynet.socket\"\nlocal skynet = require \"skynet\"\n\nlocal coroutine = coroutine\nlocal error = error\nlocal tostring = tostring\n\nlocal readbytes = socket.read\nlocal writebytes = socket.write\n\nlocal sockethelper = {}\nlocal socket_error = setmetatable({} , { \n\t__tostring = function(self)\n\t\tlocal info = self.err_info\n\t\tself.err_info = nil\n\t\treturn info or \"[Socket Error]\"\n\tend,\n\n\t__call = function (self, info)\n\t\tself.err_info = \"[Socket Error] : \" .. tostring(info)\n\t\treturn self\n\tend\n})\n\nsockethelper.socket_error = socket_error\n\nlocal function preread(fd, str)\n\treturn function (sz)\n\t\tif str then\n\t\t\tif sz == #str or sz == nil then\n\t\t\t\tlocal ret = str\n\t\t\t\tstr = nil\n\t\t\t\treturn ret\n\t\t\telse\n\t\t\t\tif sz < #str then\n\t\t\t\t\tlocal ret = str:sub(1,sz)\n\t\t\t\t\tstr = str:sub(sz + 1)\n\t\t\t\t\treturn ret\n\t\t\t\telse\n\t\t\t\t\tsz = sz - #str\n\t\t\t\t\tlocal ret = readbytes(fd, sz)\n\t\t\t\t\tif ret then\n\t\t\t\t\t\treturn str .. ret\n\t\t\t\t\telse\n\t\t\t\t\t\terror(socket_error(\"read failed fd = \" .. fd))\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tlocal ret = readbytes(fd, sz)\n\t\t\tif ret then\n\t\t\t\treturn ret\n\t\t\telse\n\t\t\t\terror(socket_error(\"read failed fd = \" .. fd))\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction sockethelper.readfunc(fd, pre)\n\tif pre then\n\t\treturn preread(fd, pre)\n\tend\n\treturn function (sz)\n\t\tlocal ret = readbytes(fd, sz)\n\t\tif ret then\n\t\t\treturn ret\n\t\telse\n\t\t\terror(socket_error(\"read failed fd = \" .. fd))\n\t\tend\n\tend\nend\n\nsockethelper.readall = socket.readall\n\nfunction sockethelper.writefunc(fd)\n\treturn function(content)\n\t\tlocal ok = writebytes(fd, content)\n\t\tif not ok then\n\t\t\terror(socket_error(\"write failed fd = \" .. fd))\n\t\tend\n\tend\nend\n\nfunction sockethelper.connect(host, port, timeout)\n\tlocal fd, err\n\tlocal is_time_out = false\n\tif timeout then\n\t\tis_time_out = true\n\t\tlocal drop_fd\n\t\tlocal co = coroutine.running()\n\t\t-- asynchronous connect\n\t\tskynet.fork(function()\n\t\t\tfd, err = socket.open(host, port)\n\t\t\tif drop_fd then\n\t\t\t\t-- sockethelper.connect already return, and raise socket_error\n\t\t\t\tsocket.close(fd)\n\t\t\telse\n\t\t\t\t-- socket.open before sleep, wakeup.\n\t\t\t\tis_time_out = false\n\t\t\t\tskynet.wakeup(co)\n\t\t\tend\n\t\tend)\n\t\tskynet.sleep(timeout)\n\t\tif not fd then\n\t\t\t-- not connect yet\n\t\t\tdrop_fd = true\n\t\tend\n\telse\n\t\tis_time_out = false\n\t\t-- block connect\n\t\tfd = socket.open(host, port)\n\tend\n\tif fd then\n\t\treturn fd\n\tend\n\terror(socket_error(\"connect failed host = \" .. host .. ' port = '.. port .. ' timeout = ' .. tostring(timeout) .. ' err = ' .. tostring(err) .. ' is_time_out = '.. tostring(is_time_out)))\nend\n\nfunction sockethelper.close(fd)\n\tsocket.close(fd)\nend\n\nfunction sockethelper.shutdown(fd)\n\tsocket.shutdown(fd)\nend\n\nreturn sockethelper\n"
  },
  {
    "path": "lualib/http/tlshelper.lua",
    "content": "local socket = require \"http.sockethelper\"\nlocal c = require \"ltls.c\"\n\nlocal tlshelper = {}\n\nfunction tlshelper.init_requestfunc(fd, tls_ctx)\n    local readfunc = socket.readfunc(fd)\n    local writefunc = socket.writefunc(fd)\n    return function (hostname)\n        tls_ctx:set_ext_host_name(hostname)\n        local ds1 = tls_ctx:handshake()\n        writefunc(ds1)\n        while not tls_ctx:finished() do\n            local ds2 = readfunc()\n            local ds3 = tls_ctx:handshake(ds2)\n            if ds3 then\n                writefunc(ds3)\n            end\n        end\n    end\nend\n\n\nfunction tlshelper.init_responsefunc(fd, tls_ctx)\n    local readfunc = socket.readfunc(fd)\n    local writefunc = socket.writefunc(fd)\n    return function ()\n        while not tls_ctx:finished() do\n            local ds1 = readfunc()\n            local ds2 = tls_ctx:handshake(ds1)\n            if ds2 then\n                writefunc(ds2)\n            end\n        end\n        local ds3 = tls_ctx:write()\n        writefunc(ds3)\n    end\nend\n\nfunction tlshelper.closefunc(tls_ctx)\n    return function ()\n        tls_ctx:close()\n    end\nend\n\nfunction tlshelper.readfunc(fd, tls_ctx)\n    local function readfunc()\n        readfunc = socket.readfunc(fd)\n        return \"\"\n    end\n    local read_buff = \"\"\n    return function (sz)\n        if not sz then\n            local s = \"\"\n            if #read_buff == 0 then\n                local ds = readfunc()\n                s = tls_ctx:read(ds)\n            end\n            s = read_buff .. s\n            read_buff = \"\"\n            return s\n        else\n            while #read_buff < sz do\n                local ds = readfunc()\n                local s = tls_ctx:read(ds)\n                read_buff = read_buff .. s\n            end\n            local  s = string.sub(read_buff, 1, sz)\n            read_buff = string.sub(read_buff, sz+1, #read_buff)\n            return s\n        end\n    end\nend\n\nfunction tlshelper.writefunc(fd, tls_ctx)\n    local writefunc = socket.writefunc(fd)\n    return function (s)\n        local ds = tls_ctx:write(s)\n        return writefunc(ds)\n    end\nend\n\nfunction tlshelper.readallfunc(fd, tls_ctx)\n    return function ()\n        local ds = socket.readall(fd)\n        local s = tls_ctx:read(ds)\n        return s\n    end\nend\n\nfunction tlshelper.newctx()\n    return c.newctx()\nend\n\nfunction tlshelper.newtls(method, ssl_ctx, hostname)\n    return c.newtls(method, ssl_ctx, hostname)\nend\n\nreturn tlshelper"
  },
  {
    "path": "lualib/http/url.lua",
    "content": "local url = {}\n\nlocal function decode_func(c)\n\treturn string.char(tonumber(c, 16))\nend\n\nlocal function decode(str)\n\tlocal str = str:gsub('+', ' ')\n\treturn str:gsub(\"%%(..)\", decode_func)\nend\n\nfunction url.parse(u)\n\tlocal path,query = u:match \"([^?]*)%??(.*)\"\n\tif path then\n\t\tpath = decode(path)\n\tend\n\treturn path, query\nend\n\nfunction url.parse_query(q)\n\tlocal r = {}\n\tfor k,v in q:gmatch \"(.-)=([^&]*)&?\" do\n\t\tlocal dk, dv = decode(k), decode(v)\n\t\tlocal oldv = r[dk]\n\t\tif oldv then\n\t\t\tif type(oldv) ~= \"table\" then\n\t\t\t\tr[dk] = {oldv, dv}\n\t\t\telse\n\t\t\t\toldv[#oldv+1] = dv\n\t\t\tend\n\t\telse\n\t\t\tr[dk] = dv\n\t\tend\n\tend\n\treturn r\nend\n\nreturn url\n"
  },
  {
    "path": "lualib/http/websocket.lua",
    "content": "local internal = require \"http.internal\"\nlocal socket = require \"skynet.socket\"\nlocal crypt = require \"skynet.crypt\"\nlocal httpd = require \"http.httpd\"\nlocal skynet = require \"skynet\"\nlocal sockethelper = require \"http.sockethelper\"\nlocal socket_error = sockethelper.socket_error\n\nlocal GLOBAL_GUID = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\"\nlocal MAX_FRAME_SIZE = 256 * 1024 -- max frame is 256K\n\nlocal assert = assert\nlocal pairs = pairs\nlocal error = error\nlocal string = string\nlocal xpcall = xpcall\nlocal pcall = pcall\nlocal debug = debug\nlocal table = table\nlocal tonumber = tonumber\n\nlocal M = {}\n\n\nlocal ws_pool = {}\nlocal function _close_websocket(ws_obj)\n    local id = ws_obj.id\n    assert(ws_pool[id] == ws_obj)\n    ws_pool[id] = nil\n    ws_obj.close()\nend\n\nlocal function _isws_closed(id)\n    return not ws_pool[id]\nend\n\nlocal function reader_with_payload(self, payload)\n    local sz_payload = #payload\n    if sz_payload == 0 then\n        return\n    end\n    local read = self.read\n    function self.read (sz)\n        if sz == nil or sz == sz_payload then\n            self.read = read\n            return payload\n        end\n        if sz < sz_payload then\n            local ret = payload:sub(1, sz)\n            payload = payload:sub(sz + 1)\n            sz_payload = #payload\n            return ret\n        end\n        self.read = read\n        return payload .. read(sz - sz_payload)\n    end\nend\n\nlocal function write_handshake(self, host, url, header)\n    local key = crypt.base64encode(crypt.randomkey()..crypt.randomkey())\n    local request_header = {\n        [\"Upgrade\"] = \"websocket\",\n        [\"Connection\"] = \"Upgrade\",\n        [\"Sec-WebSocket-Version\"] = \"13\",\n        [\"Sec-WebSocket-Key\"] = key\n    }\n    if header then\n        for k,v in pairs(header) do\n            assert(request_header[k] == nil, k)\n            request_header[k] = v\n        end\n    end\n\n    local recvheader = {}\n    local code, payload = internal.request(self, \"GET\", host, url, recvheader, request_header)\n    if code ~= 101 then\n        error(string.format(\"websocket handshake error: code[%s] info:%s\", code, payload))\n    end\n    reader_with_payload(self, payload)\n\n    if not recvheader[\"upgrade\"] or recvheader[\"upgrade\"]:lower() ~= \"websocket\" then\n        error(\"websocket handshake upgrade must websocket\")\n    end\n\n    if not recvheader[\"connection\"] or recvheader[\"connection\"]:lower() ~= \"upgrade\" then\n        error(\"websocket handshake connection must upgrade\")\n    end\n\n    local sw_key = recvheader[\"sec-websocket-accept\"]\n    if not sw_key then\n        error(\"websocket handshake need Sec-WebSocket-Accept\")\n    end\n\n    local guid = self.guid\n    sw_key = crypt.base64decode(sw_key)\n    if sw_key ~= crypt.sha1(key .. guid) then\n        error(\"websocket handshake invalid Sec-WebSocket-Accept\")\n    end\nend\n\nlocal function read_handshake(self, upgrade_ops)\n    local header, method, url\n    if upgrade_ops then\n        header, method, url = upgrade_ops.header, upgrade_ops.method, upgrade_ops.url\n    else\n        local tmpline = {}\n        local payload = internal.recvheader(self.read, tmpline, \"\")\n        if not payload then\n            return 413\n        end\n        reader_with_payload(self, payload)\n\n        local request = assert(tmpline[1])\n        local httpver\n        method, url, httpver = request:match \"^(%a+)%s+(.-)%s+HTTP/([%d%.]+)$\"\n        assert(method and url and httpver)\n        if method ~= \"GET\" then\n            return 400, \"need GET method\"\n        end\n\n        httpver = assert(tonumber(httpver))\n        if httpver < 1.1 then\n            return 505  -- HTTP Version not supported\n        end\n        header = internal.parseheader(tmpline, 2, {})\n    end\n\n    if not header then\n        return 400  -- Bad request\n    end\n    if not header[\"upgrade\"] or header[\"upgrade\"]:lower() ~= \"websocket\" then\n        return 426, \"Upgrade Required\"\n    end\n\n    if not header[\"host\"] then\n        return 400, \"host Required\"\n    end\n\n    if not header[\"connection\"] or not header[\"connection\"]:lower():find(\"upgrade\", 1,true) then\n        return 400, \"Connection must Upgrade\"\n    end\n\n    local sw_key = header[\"sec-websocket-key\"]\n    if not sw_key then\n        return 400, \"Sec-WebSocket-Key Required\"\n    else\n        local raw_key = crypt.base64decode(sw_key)\n        if #raw_key ~= 16 then\n            return 400, \"Sec-WebSocket-Key invalid\"\n        end\n    end\n\n    if not header[\"sec-websocket-version\"] or header[\"sec-websocket-version\"] ~= \"13\" then\n        return 400, \"Sec-WebSocket-Version must 13\"\n    end\n\n    local sw_protocol = header[\"sec-websocket-protocol\"]\n    local sub_pro = \"\"\n    if sw_protocol then\n        local has_chat = false\n        for sub_protocol in string.gmatch(sw_protocol, \"[^%s,]+\") do\n            if sub_protocol == \"chat\" then\n                sub_pro = \"Sec-WebSocket-Protocol: chat\\r\\n\"\n                has_chat = true\n                break\n            end\n        end\n        if not has_chat then\n            return 400, \"Sec-WebSocket-Protocol need include chat\"\n        end\n    end\n\n    -- read 'x-real-ip' header from nginx\n    self.real_ip = header[\"x-real-ip\"]\n\n    -- response handshake\n    local accept = crypt.base64encode(crypt.sha1(sw_key .. self.guid))\n    local resp = \"HTTP/1.1 101 Switching Protocols\\r\\n\"..\n                 \"Upgrade: websocket\\r\\n\"..\n                 \"Connection: Upgrade\\r\\n\"..\n    string.format(\"Sec-WebSocket-Accept: %s\\r\\n\", accept)..\n                  sub_pro ..\n                  \"\\r\\n\"\n    self.write(resp)\n    return nil, header, url\nend\n\nlocal function try_handle(self, method, ...)\n    local handle = self.handle\n    local f = handle and handle[method]\n    if f then\n        f(self.id, ...)\n    end\nend\n\nlocal op_code = {\n    [\"frame\"]  = 0x00,\n    [\"text\"]   = 0x01,\n    [\"binary\"] = 0x02,\n    [\"close\"]  = 0x08,\n    [\"ping\"]   = 0x09,\n    [\"pong\"]   = 0x0A,\n    [0x00]     = \"frame\",\n    [0x01]     = \"text\",\n    [0x02]     = \"binary\",\n    [0x08]     = \"close\",\n    [0x09]     = \"ping\",\n    [0x0A]     = \"pong\",\n}\n\nlocal function write_frame(self, op, payload_data, masking_key)\n    payload_data = payload_data or \"\"\n    local payload_len = #payload_data\n    local op_v = assert(op_code[op])\n    local v1 = 0x80 | op_v -- fin is 1 with opcode\n    local s\n    local mask = masking_key and 0x80 or 0x00\n    -- mask set to 0\n    if payload_len < 126 then\n        s = string.pack(\"I1I1\", v1, mask | payload_len)\n    elseif payload_len <= 0xffff then\n        s = string.pack(\"I1I1>I2\", v1, mask | 126, payload_len)\n    else\n        s = string.pack(\"I1I1>I8\", v1, mask | 127, payload_len)\n    end\n    self.write(s)\n\n    -- write masking_key\n    if masking_key then\n        s = string.pack(\">I4\", masking_key)\n        self.write(s)\n        payload_data = crypt.xor_str(payload_data, s)\n    end\n\n    if payload_len > 0 then\n        self.write(payload_data)\n    end\nend\n\n\nlocal function read_close(payload_data)\n    local code, reason\n    local payload_len = #payload_data\n    if payload_len > 2 then\n        local fmt = string.format(\">I2c%d\", payload_len - 2)\n        code, reason = string.unpack(fmt, payload_data)\n    end\n    return code, reason\nend\n\n\nlocal function read_frame(self)\n    local s = self.read(2)\n    local v1, v2 = string.unpack(\"I1I1\", s)\n    local fin  = (v1 & 0x80) ~= 0\n    -- unused flag\n    -- local rsv1 = (v1 & 0x40) ~= 0\n    -- local rsv2 = (v1 & 0x20) ~= 0\n    -- local rsv3 = (v1 & 0x10) ~= 0\n    local op   =  v1 & 0x0f\n    local mask = (v2 & 0x80) ~= 0\n    local payload_len = (v2 & 0x7f)\n    if payload_len == 126 then\n        s = self.read(2)\n        payload_len = string.unpack(\">I2\", s)\n    elseif payload_len == 127 then\n        s = self.read(8)\n        payload_len = string.unpack(\">I8\", s)\n    end\n\n    if self.mode == \"server\" and payload_len > MAX_FRAME_SIZE then\n        error(\"payload_len is too large\")\n    end\n\n    -- print(string.format(\"fin:%s, op:%s, mask:%s, payload_len:%s\", fin, op_code[op], mask, payload_len))\n    local masking_key = mask and self.read(4) or false\n    local payload_data = payload_len>0 and self.read(payload_len) or \"\"\n    payload_data = masking_key and crypt.xor_str(payload_data, masking_key) or payload_data\n    return fin, assert(op_code[op]), payload_data\nend\n\n\nlocal function resolve_accept(self, options)\n    try_handle(self, \"connect\")\n    local code, err, url = read_handshake(self, options and options.upgrade)\n    if code then\n        local ok, s = httpd.write_response(self.write, code, err)\n        if not ok then\n            error(s)\n        end\n        try_handle(self, \"close\")\n        return\n    end\n\n    local header = err\n    try_handle(self, \"handshake\", header, url)\n    local recv_count = 0\n    local recv_buf = {}\n    local first_op\n    while true do\n        if _isws_closed(self.id) then\n            try_handle(self, \"close\")\n            return\n        end\n        local fin, op, payload_data = read_frame(self)\n        if op == \"close\" then\n            local code, reason = read_close(payload_data)\n            write_frame(self, \"close\")\n            try_handle(self, \"close\", code, reason)\n            break\n        elseif op == \"ping\" then\n            write_frame(self, \"pong\", payload_data)\n            try_handle(self, \"ping\")\n        elseif op == \"pong\" then\n            try_handle(self, \"pong\")\n        else\n            if fin and #recv_buf == 0 then\n                try_handle(self, \"message\", payload_data, op)\n            else\n                recv_buf[#recv_buf+1] = payload_data\n                recv_count = recv_count + #payload_data\n                if recv_count > MAX_FRAME_SIZE then\n                    error(\"payload_len is too large\")\n                end\n                first_op = first_op or op\n                if fin then\n                    local s = table.concat(recv_buf)\n                    try_handle(self, \"message\", s, first_op)\n                    recv_buf = {}  -- clear recv_buf\n                    recv_count = 0\n                    first_op = nil\n                end\n            end\n        end\n    end\nend\n\n\nlocal SSLCTX_CLIENT = nil\nlocal function _new_client_ws(socket_id, protocol, hostname)\n    local obj\n    if protocol == \"ws\" then\n        obj = {\n            close = function ()\n                socket.close(socket_id)\n            end,\n            read = sockethelper.readfunc(socket_id),\n            write = sockethelper.writefunc(socket_id),\n            readall = function ()\n                return socket.readall(socket_id)\n            end,\n        }\n    elseif protocol == \"wss\" then\n        local tls = require \"http.tlshelper\"\n        SSLCTX_CLIENT = SSLCTX_CLIENT or tls.newctx()\n        local tls_ctx = tls.newtls(\"client\", SSLCTX_CLIENT, hostname)\n        local init = tls.init_requestfunc(socket_id, tls_ctx)\n        init()\n        obj = {\n            close = function ()\n                socket.close(socket_id)\n                tls.closefunc(tls_ctx)()\n            end,\n            read = tls.readfunc(socket_id, tls_ctx),\n            write = tls.writefunc(socket_id, tls_ctx),\n            readall = tls.readallfunc(socket_id, tls_ctx),\n        }\n    else\n        error(string.format(\"invalid websocket protocol:%s\", tostring(protocol)))\n    end\n\n    obj.mode = \"client\"\n    obj.id = assert(socket_id)\n    obj.guid = GLOBAL_GUID\n    ws_pool[socket_id] = obj\n    return obj\nend\n\n\nlocal SSLCTX_SERVER = nil\nlocal function _new_server_ws(socket_id, handle, protocol)\n    local obj\n    if protocol == \"ws\" then\n        obj = {\n            close = function ()\n                socket.close(socket_id)\n            end,\n            read = sockethelper.readfunc(socket_id),\n            write = sockethelper.writefunc(socket_id),\n        }\n\n    elseif protocol == \"wss\" then\n        local tls = require \"http.tlshelper\"\n        if not SSLCTX_SERVER then\n            SSLCTX_SERVER = tls.newctx()\n            -- gen cert and key\n            -- openssl req -x509 -newkey rsa:2048 -days 3650 -nodes -keyout server-key.pem -out server-cert.pem\n            local certfile = skynet.getenv(\"certfile\") or \"./server-cert.pem\"\n            local keyfile = skynet.getenv(\"keyfile\") or \"./server-key.pem\"\n            SSLCTX_SERVER:set_cert(certfile, keyfile)\n        end\n        local tls_ctx = tls.newtls(\"server\", SSLCTX_SERVER)\n        local init = tls.init_responsefunc(socket_id, tls_ctx)\n        init()\n        obj = {\n            close = function ()\n                socket.close(socket_id)\n                tls.closefunc(tls_ctx)()\n            end,\n            read = tls.readfunc(socket_id, tls_ctx),\n            write = tls.writefunc(socket_id, tls_ctx),\n        }\n\n    else\n        error(string.format(\"invalid websocket protocol:%s\", tostring(protocol)))\n    end\n\n    obj.mode = \"server\"\n    obj.id = assert(socket_id)\n    obj.handle = handle\n    obj.guid = GLOBAL_GUID\n    ws_pool[socket_id] = obj\n    return obj\nend\n\n\n-- handle interface\n-- connect / handshake / message / ping / pong / close / error\nfunction M.accept(socket_id, handle, protocol, addr, options)\n    if not (options and options.upgrade) then\n        local isok, err = socket.start(socket_id)\n        if not isok then\n            return false, err\n        end\n    end\n    protocol = protocol or \"ws\"\n    local ws_obj = _new_server_ws(socket_id, handle, protocol)\n    ws_obj.addr = addr\n    local on_warning = handle and handle[\"warning\"]\n    if on_warning then\n        local isok = pcall(socket.warning, socket_id, function(id, sz)\n            on_warning(ws_obj, sz)\n        end)\n        if not isok then\n            if not _isws_closed(socket_id) then\n                _close_websocket(ws_obj)\n            end\n            return false, \"connect is closed \" .. socket_id\n        end\n    end\n\n    local ok, err = xpcall(resolve_accept, debug.traceback, ws_obj, options)\n    local closed = _isws_closed(socket_id)\n    if not closed then\n        _close_websocket(ws_obj)\n    end\n    if not ok then\n        if err == socket_error then\n            if closed then\n                try_handle(ws_obj, \"close\")\n            else\n                try_handle(ws_obj, \"error\", err)\n            end\n        else\n            -- error(err)\n            return false, err\n        end\n    end\n    return true\nend\n\n\nfunction M.connect(url, header, timeout)\n    local protocol, host, uri = string.match(url, \"^(wss?)://([^/]+)(.*)$\")\n    if protocol ~= \"wss\" and protocol ~= \"ws\" then\n        error(string.format(\"invalid protocol: %s\", protocol))\n    end\n\n    assert(host)\n    local host_addr, host_port = string.match(host, \"^([^:]+):?(%d*)$\")\n    assert(host_addr and host_port)\n    if host_port == \"\" then\n        host_port = protocol == \"ws\" and 80 or 443\n    end\n    local hostname\n    if not host_addr:match(\".*%d+$\") then\n        hostname = host_addr\n    end\n\n    uri = uri == \"\" and \"/\" or uri\n    local socket_id = sockethelper.connect(host_addr, host_port, timeout)\n    local ws_obj = _new_client_ws(socket_id, protocol, hostname)\n    ws_obj.addr = host\n    \n    local is_ok,err = pcall(write_handshake, ws_obj, host_addr, uri, header)\n    if not is_ok then\n        _close_websocket(ws_obj)\n        error(err)\n    end\n    return socket_id\nend\n\n\nfunction M.read(id)\n    local ws_obj = assert(ws_pool[id])\n    local recv_buf\n    while true do\n        local fin, op, payload_data = read_frame(ws_obj)\n        if op == \"close\" then\n            _close_websocket(ws_obj)\n            return false, payload_data\n        elseif op == \"ping\" then\n            write_frame(ws_obj, \"pong\", payload_data)\n        elseif op ~= \"pong\" then  -- op is frame, text binary\n            if fin and not recv_buf then\n                return payload_data\n            else\n                recv_buf = recv_buf or {}\n                recv_buf[#recv_buf+1] = payload_data\n                if fin then\n                    local s = table.concat(recv_buf)\n                    return s\n                end\n            end\n        end\n    end\nend\n\n\nfunction M.write(id, data, fmt, masking_key)\n    local ws_obj = assert(ws_pool[id])\n    fmt = fmt or \"text\"\n    assert(fmt == \"text\" or fmt == \"binary\")\n    write_frame(ws_obj, fmt, data, masking_key)\nend\n\n\nfunction M.ping(id)\n    local ws_obj = assert(ws_pool[id])\n    write_frame(ws_obj, \"ping\")\nend\n\nfunction M.addrinfo(id)\n    local ws_obj = assert(ws_pool[id])\n    return ws_obj.addr\nend\n\nfunction M.real_ip(id)\n    local ws_obj = assert(ws_pool[id])\n    return ws_obj.real_ip\nend\n\nfunction M.close(id, code ,reason)\n    local ws_obj = ws_pool[id]\n    if not ws_obj then\n        return\n    end\n\n    local ok, err = xpcall(function ()\n        reason = reason or \"\"\n        local payload_data\n        if code then\n            local fmt =string.format(\">I2c%d\", #reason)\n            payload_data = string.pack(fmt, code, reason)\n        end\n        write_frame(ws_obj, \"close\", payload_data)\n    end, debug.traceback)\n    _close_websocket(ws_obj)\n    if not ok then\n        skynet.error(err)\n    end\nend\n\nM.is_close = _isws_closed\n\nreturn M\n"
  },
  {
    "path": "lualib/loader.lua",
    "content": "local args = {}\nfor word in string.gmatch(..., \"%S+\") do\n\ttable.insert(args, word)\nend\n\nSERVICE_NAME = args[1]\n\nlocal main, pattern\n\nlocal err = {}\nfor pat in string.gmatch(LUA_SERVICE, \"([^;]+);*\") do\n\tlocal filename = string.gsub(pat, \"?\", SERVICE_NAME)\n\tlocal f, msg = loadfile(filename)\n\tif not f then\n\t\ttable.insert(err, msg)\n\telse\n\t\tpattern = pat\n\t\tmain = f\n\t\tbreak\n\tend\nend\n\nif not main then\n\terror(table.concat(err, \"\\n\"))\nend\n\nLUA_SERVICE = nil\npackage.path , LUA_PATH = LUA_PATH, nil\npackage.cpath , LUA_CPATH = LUA_CPATH, nil\n\nlocal service_path = string.match(pattern, \"(.*/)[^/?]+$\")\n\nif service_path then\n\tservice_path = string.gsub(service_path, \"?\", args[1])\n\tpackage.path = service_path .. \"?.lua;\" .. package.path\n\tSERVICE_PATH = service_path\nelse\n\tlocal p = string.match(pattern, \"(.*/).+$\")\n\tSERVICE_PATH = p\nend\n\nif LUA_PRELOAD then\n\tlocal f = assert(loadfile(LUA_PRELOAD))\n\tf(table.unpack(args))\n\tLUA_PRELOAD = nil\nend\n\n_G.require = (require \"skynet.require\").require\n\nmain(select(2, table.unpack(args)))\n"
  },
  {
    "path": "lualib/md5.lua",
    "content": "----------------------------------------------------------------------------\n-- Modify version from https://github.com/keplerproject/md5\n----------------------------------------------------------------------------\n\nlocal core = require \"md5.core\"\n\n----------------------------------------------------------------------------\n-- @param k String with original message.\n-- @return String with the md5 hash value converted to hexadecimal digits\n\nfunction core.sumhexa (k)\n\tk = core.sum(k)\n\treturn (string.gsub(k, \".\", function (c)\n\t\t   return string.format(\"%02x\", string.byte(c))\n\t\t end))\nend\n\nlocal function get_ipad(c)\n\treturn string.char(c:byte() ~ 0x36)\nend\n\nlocal function get_opad(c)\n\treturn string.char(c:byte() ~ 0x5c)\nend\n\nfunction core.hmacmd5(data,key)\n\tif #key>64 then\n\t\tkey=core.sum(key)\n\t\tkey=key:sub(1,16)\n\tend\n\tlocal ipad_s=key:gsub(\".\", get_ipad)..string.rep(\"6\",64-#key)\n\tlocal opad_s=key:gsub(\".\", get_opad)..string.rep(\"\\\\\",64-#key)\n\tlocal istr=core.sum(ipad_s..data)\n\tlocal ostr=core.sumhexa(opad_s..istr)\n\treturn ostr\nend\n\nreturn core\n"
  },
  {
    "path": "lualib/skynet/cluster.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal clusterd\nlocal cluster = {}\nlocal sender = {}\nlocal task_queue = {}\n\nlocal function repack(address, ...)\n\treturn address, skynet.pack(...)\nend\n\nlocal function request_sender(q, node)\n\tlocal ok, c = pcall(skynet.call, clusterd, \"lua\", \"sender\", node)\n\tif not ok then\n\t\tskynet.error(c)\n\t\tc = nil\n\tend\n\t-- run tasks in queue\n\tlocal confirm = coroutine.running()\n\tq.confirm = confirm\n\tq.sender = c\n\tfor _, task in ipairs(q) do\n\t\tif type(task) == \"string\" then\n\t\t\tif c then\n\t\t\t\tskynet.send(c, \"lua\", \"push\", repack(skynet.unpack(task)))\n\t\t\tend\n\t\telse\n\t\t\tskynet.wakeup(task)\n\t\t\tskynet.wait(confirm)\n\t\tend\n\tend\n\ttask_queue[node] = nil\n\tsender[node] = c\nend\n\nlocal function get_queue(t, node)\n\tlocal q = {}\n\tt[node] = q\n\tskynet.fork(request_sender, q, node)\n\treturn q\nend\n\nsetmetatable(task_queue, { __index = get_queue } )\n\nlocal function get_sender(node)\n\tlocal s = sender[node]\n\tif not s then\n\t\tlocal q = task_queue[node]\n\t\tlocal task = coroutine.running()\n\t\ttable.insert(q, task)\n\t\tskynet.wait(task)\n\t\tskynet.wakeup(q.confirm)\n\t\treturn q.sender\n\tend\n\treturn s\nend\n\ncluster.get_sender = get_sender\n\nfunction cluster.call(node, address, ...)\n\t-- skynet.pack(...) will free by cluster.core.packrequest\n\tlocal s = sender[node]\n\tif not s then\n\t\tlocal task = skynet.packstring(address, ...)\n\t\treturn skynet.call(get_sender(node), \"lua\", \"req\", repack(skynet.unpack(task)))\n\tend\n\treturn skynet.call(s, \"lua\", \"req\", address, skynet.pack(...))\nend\n\nfunction cluster.send(node, address, ...)\n\t-- push is the same with req, but no response\n\tlocal s = sender[node]\n\tif not s then\n\t\ttable.insert(task_queue[node], skynet.packstring(address, ...))\n\telse\n\t\tskynet.send(sender[node], \"lua\", \"push\", address, skynet.pack(...))\n\tend\nend\n\nfunction cluster.open(port, maxclient)\n\tif type(port) == \"string\" then\n\t\treturn skynet.call(clusterd, \"lua\", \"listen\", port, nil, maxclient)\n\telse\n\t\treturn skynet.call(clusterd, \"lua\", \"listen\", \"0.0.0.0\", port, maxclient)\n\tend\nend\n\nfunction cluster.reload(config)\n\tskynet.call(clusterd, \"lua\", \"reload\", config)\nend\n\nfunction cluster.proxy(node, name)\n\treturn skynet.call(clusterd, \"lua\", \"proxy\", node, name)\nend\n\nfunction cluster.snax(node, name, address)\n\tlocal snax = require \"skynet.snax\"\n\tif not address then\n\t\taddress = cluster.call(node, \".service\", \"QUERY\", \"snaxd\" , name)\n\tend\n\tlocal handle = skynet.call(clusterd, \"lua\", \"proxy\", node, address)\n\treturn snax.bind(handle, name)\nend\n\nfunction cluster.register(name, addr)\n\tassert(type(name) == \"string\")\n\tassert(addr == nil or type(addr) == \"number\")\n\treturn skynet.call(clusterd, \"lua\", \"register\", name, addr)\nend\n\nfunction cluster.unregister(name)\n\tassert(type(name) == \"string\")\n\treturn skynet.call(clusterd, \"lua\", \"unregister\", name)\nend\n\nfunction cluster.query(node, name)\n\treturn skynet.call(get_sender(node), \"lua\", \"req\", 0, skynet.pack(name))\nend\n\nskynet.init(function()\n\tclusterd = skynet.uniqueservice(\"clusterd\")\nend)\n\nreturn cluster\n"
  },
  {
    "path": "lualib/skynet/coroutine.lua",
    "content": "-- You should use this module (skynet.coroutine) instead of origin lua coroutine in skynet framework\n\nlocal coroutine = coroutine\n-- origin lua coroutine module\nlocal coroutine_resume = coroutine.resume\nlocal coroutine_yield = coroutine.yield\nlocal coroutine_status = coroutine.status\nlocal coroutine_running = coroutine.running\nlocal coroutine_close = coroutine.close\n\nlocal select = select\nlocal skynetco = {}\n\nskynetco.isyieldable = coroutine.isyieldable\nskynetco.running = coroutine.running\nskynetco.status = coroutine.status\n\nlocal skynet_coroutines = setmetatable({}, { __mode = \"kv\" })\n-- true : skynet coroutine\n-- false : skynet suspend\n-- nil : exit\n\nfunction skynetco.create(f)\n\tlocal co = coroutine.create(f)\n\t-- mark co as a skynet coroutine\n\tskynet_coroutines[co] = true\n\treturn co\nend\n\ndo -- begin skynetco.resume\n\tlocal function unlock(co, ...)\n\t\tskynet_coroutines[co] = true\n\t\treturn ...\n\tend\n\n\tlocal function skynet_yielding(co, ...)\n\t\tskynet_coroutines[co] = false\n\t\treturn unlock(co, coroutine_resume(co, coroutine_yield(...)))\n\tend\n\n\tlocal function resume(co, ok, ...)\n\t\tif not ok then\n\t\t\treturn ok, ...\n\t\telseif coroutine_status(co) == \"dead\" then\n\t\t\t-- the main function exit\n\t\t\tskynet_coroutines[co] = nil\n\t\t\treturn true, ...\n\t\telseif (...) == \"USER\" then\n\t\t\treturn true, select(2, ...)\n\t\telse\n\t\t\t-- blocked in skynet framework, so raise the yielding message\n\t\t\treturn resume(co, skynet_yielding(co, ...))\n\t\tend\n\tend\n\n\t-- record the root of coroutine caller (It should be a skynet thread)\n\tlocal coroutine_caller = setmetatable({} , { __mode = \"kv\" })\n\n\tfunction skynetco.resume(co, ...)\n\t\tlocal co_status = skynet_coroutines[co]\n\t\tif not co_status then\n\t\t\tif co_status == false then\n\t\t\t\t-- is running\n\t\t\t\treturn false, \"cannot resume a skynet coroutine suspend by skynet framework\"\n\t\t\tend\n\t\t\tif coroutine_status(co) == \"dead\" then\n\t\t\t\t-- always return false, \"cannot resume dead coroutine\"\n\t\t\t\treturn coroutine_resume(co, ...)\n\t\t\telse\n\t\t\t\treturn false, \"cannot resume none skynet coroutine\"\n\t\t\tend\n\t\tend\n\t\tlocal from = coroutine_running()\n\t\tlocal caller = coroutine_caller[from] or from\n\t\tcoroutine_caller[co] = caller\n\t\treturn resume(co, coroutine_resume(co, ...))\n\tend\n\n\tfunction skynetco.thread(co)\n\t\tco = co or coroutine_running()\n\t\tif skynet_coroutines[co] ~= nil then\n\t\t\treturn coroutine_caller[co] , false\n\t\telse\n\t\t\treturn co, true\n\t\tend\n\tend\n\nend -- end of skynetco.resume\n\nfunction skynetco.status(co)\n\tlocal status = coroutine_status(co)\n\tif status == \"suspended\" then\n\t\tif skynet_coroutines[co] == false then\n\t\t\treturn \"blocked\"\n\t\telse\n\t\t\treturn \"suspended\"\n\t\tend\n\telse\n\t\treturn status\n\tend\nend\n\nfunction skynetco.yield(...)\n\treturn coroutine_yield(\"USER\", ...)\nend\n\ndo -- begin skynetco.wrap\n\n\tlocal function wrap_co(ok, ...)\n\t\tif ok then\n\t\t\treturn ...\n\t\telse\n\t\t\terror(...)\n\t\tend\n\tend\n\nfunction skynetco.wrap(f)\n\tlocal co = skynetco.create(function(...)\n\t\treturn f(...)\n\tend)\n\treturn function(...)\n\t\treturn wrap_co(skynetco.resume(co, ...))\n\tend\nend\n\nend\t-- end of skynetco.wrap\n\nfunction skynetco.close(co)\n\tskynet_coroutines[co] = nil\n\treturn coroutine_close(co)\nend\n\nreturn skynetco\n"
  },
  {
    "path": "lualib/skynet/datacenter.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal datacenter = {}\n\nfunction datacenter.get(...)\n\treturn skynet.call(\"DATACENTER\", \"lua\", \"QUERY\", ...)\nend\n\nfunction datacenter.set(...)\n\treturn skynet.call(\"DATACENTER\", \"lua\", \"UPDATE\", ...)\nend\n\nfunction datacenter.wait(...)\n\treturn skynet.call(\"DATACENTER\", \"lua\", \"WAIT\", ...)\nend\n\nreturn datacenter\n\n"
  },
  {
    "path": "lualib/skynet/datasheet/builder.lua",
    "content": "local skynet = require \"skynet\"\nlocal dump = require \"skynet.datasheet.dump\"\nlocal core = require \"skynet.datasheet.core\"\nlocal service = require \"skynet.service\"\n\nlocal builder = {}\n\nlocal cache = {}\nlocal dataset = {}\nlocal address\n\nlocal unique_id = 0\nlocal function unique_string(str)\n\tunique_id = unique_id + 1\n\treturn str .. tostring(unique_id)\nend\n\nlocal function monitor(pointer)\n\tskynet.fork(function()\n\t\tskynet.call(address, \"lua\", \"collect\", pointer)\n\t\tfor k,v in pairs(cache) do\n\t\t\tif v == pointer then\n\t\t\t\tcache[k] = nil\n\t\t\t\treturn\n\t\t\tend\n\t\tend\n\tend)\nend\n\nlocal function dumpsheet(v)\n\tif type(v) == \"string\" then\n\t\treturn v\n\telse\n\t\treturn dump.dump(v)\n\tend\nend\n\nfunction builder.new(name, v)\n\tassert(dataset[name] == nil)\n\tlocal datastring = unique_string(dumpsheet(v))\n\tlocal pointer = core.stringpointer(datastring)\n\tskynet.call(address, \"lua\", \"update\", name, pointer)\n\tcache[datastring] = pointer\n\tdataset[name] = datastring\n\tmonitor(pointer)\nend\n\nfunction builder.update(name, v)\n\tlocal lastversion = assert(dataset[name])\n\tlocal newversion = dumpsheet(v)\n\tlocal diff = unique_string(dump.diff(lastversion, newversion))\n\tlocal pointer = core.stringpointer(diff)\n\tskynet.call(address, \"lua\", \"update\", name, pointer)\n\tcache[diff] = pointer\n\tlocal lp = assert(cache[lastversion])\n\tskynet.send(address, \"lua\", \"release\", lp)\n\tdataset[name] = diff\n\tmonitor(pointer)\nend\n\nfunction builder.compile(v)\n\treturn dump.dump(v)\nend\n\nlocal function datasheet_service()\n\nlocal skynet = require \"skynet\"\n\nlocal datasheet = {}\nlocal handles = {}\t-- handle:{ ref:count , name:name , collect:resp }\nlocal dataset = {}\t-- name:{ handle:handle, monitor:{monitors queue} }\nlocal customers = {} -- source: { handle:true }\n\nsetmetatable(customers, { __index = function(c, source)\n\tlocal v = {}\n\tc[source] = v\n\treturn v\nend } )\n\nlocal function releasehandle(source, handle)\n\tlocal h = handles[handle]\n\th.ref = h.ref - 1\n\tif h.ref == 0 and h.collect then\n\t\th.collect(true)\n\t\th.collect = nil\n\t\thandles[handle] = nil\n\tend\n\tlocal t=dataset[h.name]\n\tt.monitor[source]=nil\nend\n\n-- from builder, create or update handle\nfunction datasheet.update(source, name, handle)\n\tlocal t = dataset[name]\n\tif not t then\n\t\t-- new datasheet\n\t\tt = { handle = handle, monitor = {} }\n\t\tdataset[name] = t\n\t\thandles[handle] = { ref = 1, name = name }\n\telse\n\t\t-- report update to customers\n\t\thandles[handle] = { ref = handles[t.handle].ref, name = name }\n\t\tt.handle = handle\n\n\t\tfor k,v in pairs(t.monitor) do\n\t\t\tv(true, handle)\n\t\t\tt.monitor[k] = nil\n\t\tend\n\tend\n\tskynet.ret()\nend\n\n-- from customers\nfunction datasheet.query(source, name)\n\tlocal t = assert(dataset[name], \"create data first\")\n\tlocal handle = t.handle\n\tlocal h = handles[handle]\n\th.ref = h.ref + 1\n\tcustomers[source][handle] = true\n\tskynet.ret(skynet.pack(handle))\nend\n\n-- from customers, monitor handle change\nfunction datasheet.monitor(source, handle)\n\tlocal h = assert(handles[handle], \"Invalid data handle\")\n\tlocal t = dataset[h.name]\n\tif t.handle ~= handle then\t-- already changes\n\t\tcustomers[source][t.handle] = true\n\t\tskynet.ret(skynet.pack(t.handle))\n\telse\n\t\tassert(not t.monitor[source])\n\t\tlocal resp = skynet.response()\n\t\tt.monitor[source]= function(ok, handle)\n\t\t\tif ok then\n\t\t\t\tcustomers[source][handle] = true\n\t\t\tend\n\t\t\tresp(ok, handle)\n\t\tend\n\tend\nend\n\n-- from customers, release handle , ref count - 1\nfunction datasheet.release(source, handle)\n\t-- send message, don't ret\n\tcustomers[source][handle] = nil\n\treleasehandle(source, handle)\nend\n\n-- customer closed, clear all handles it queried\nfunction datasheet.close(source)\n\tfor handle in pairs(customers[source]) do\n\t\treleasehandle(source, handle)\n\tend\n\tcustomers[source] = nil\nend\n\n-- from builder, monitor handle release\nfunction datasheet.collect(source, handle)\n\tlocal h = assert(handles[handle], \"Invalid data handle\")\n\tif h.ref == 0 then\n\t\thandles[handle] = nil\n\t\tskynet.ret()\n\telse\n\t\tassert(h.collect == nil, \"Only one collect allows\")\n\t\th.collect = skynet.response()\n\tend\nend\n\nskynet.dispatch(\"lua\", function(_,source,cmd,...)\n\tdatasheet[cmd](source,...)\nend)\n\nskynet.info_func(function()\n\tlocal info = {}\n\tlocal tmp = {}\n\tfor k,v in pairs(handles) do\n\t\ttmp[k] = v\n\tend\n\tfor k,v in pairs(dataset) do\n\t\tlocal h = handles[v.handle]\n\t\ttmp[v.handle] = nil\n\t\tinfo[k] = {\n\t\t\thandle = v.handle,\n\t\t\tmonitors = h.ref,\n\t\t}\n\tend\n\tfor k,v in pairs(tmp) do\n\t\tinfo[k] = v.ref\n\tend\n\n\treturn info\nend)\n\nend\n\nskynet.init(function()\n\taddress=service.new(\"datasheet\", datasheet_service)\nend)\n\nreturn builder\n"
  },
  {
    "path": "lualib/skynet/datasheet/dump.lua",
    "content": "--[[ file format\ndocument :\n  int32 strtbloffset\n  int32 n\n  int32*n index table\n  table*n\n  strings\n\ntable:\n  int32 array\n  int32 dict\n  int8*(array+dict) type (align 4)\n  value*array\n  kvpair*dict\n\nkvpair:\n  string k\n  value v\n\nvalue: (union)\n  int32 integer\n  float real\n  int32 boolean\n  int32 table index\n  int32 string offset\n\ntype: (enum)\n  0 nil\n  1 integer\n  2 real\n  3 boolean\n  4 table\n  5 string\n]]\n\nlocal ctd = {}\nlocal math = math\nlocal table = table\nlocal string = string\n\nfunction ctd.dump(root)\n\tlocal doc = {\n\t\ttable_n = 0,\n\t\ttable = {},\n\t\tstrings = {},\n\t\toffset = 0,\n\t}\n\tlocal function dump_table(t)\n\t\tlocal index = doc.table_n + 1\n\t\tdoc.table_n = index\n\t\tdoc.table[index] = false\t-- place holder\n\t\tlocal array_n = 0\n\t\tlocal array = {}\n\t\tlocal kvs = {}\n\t\tlocal types = {}\n\t\tlocal function encode(v)\n\t\t\tlocal t = type(v)\n\t\t\tif t == \"table\" then\n\t\t\t\tlocal index = dump_table(v)\n\t\t\t\treturn '\\4', string.pack(\"<i4\", index-1)\n\t\t\telseif t == \"number\" then\n\t\t\t\tif math.tointeger(v) and v <= 0x7FFFFFFF and v >= -(0x7FFFFFFF+1) then\n\t\t\t\t\treturn '\\1', string.pack(\"<i4\", v)\n\t\t\t\telse\n\t\t\t\t\treturn '\\2', string.pack(\"<f\",v)\n\t\t\t\tend\n\t\t\telseif t == \"boolean\" then\n\t\t\t\tif v then\n\t\t\t\t\treturn '\\3', \"\\0\\0\\0\\1\"\n\t\t\t\telse\n\t\t\t\t\treturn '\\3', \"\\0\\0\\0\\0\"\n\t\t\t\tend\n\t\t\telseif t == \"string\" then\n\t\t\t\tlocal offset = doc.strings[v]\n\t\t\t\tif not offset then\n\t\t\t\t\toffset = doc.offset\n\t\t\t\t\tdoc.offset = offset + #v + 1\n\t\t\t\t\tdoc.strings[v] = offset\n\t\t\t\t\ttable.insert(doc.strings, v)\n\t\t\t\tend\n\t\t\t\treturn '\\5', string.pack(\"<I4\", offset)\n\t\t\telse\n\t\t\t\terror (\"Unsupport value \" .. tostring(v))\n\t\t\tend\n\t\tend\n\t\tfor i,v in ipairs(t) do\n\t\t\ttypes[i], array[i] = encode(v)\n\t\t\tarray_n = i\n\t\tend\n\t\tfor k,v in pairs(t) do\n\t\t\tif type(k) == \"string\" then\n\t\t\t\tlocal _, kv = encode(k)\n\t\t\t\tlocal tv, ev = encode(v)\n\t\t\t\ttable.insert(types, tv)\n\t\t\t\ttable.insert(kvs, kv .. ev)\n\t\t\telse\n\t\t\t\tlocal ik = math.tointeger(k)\n\t\t\t\tassert(ik and ik > 0 and ik <= array_n)\n\t\t\tend\n\t\tend\n\t\t-- encode table\n\t\tlocal typeset = table.concat(types)\n\t\tlocal align = string.rep(\"\\0\", (4 - #typeset & 3) & 3)\n\t\tlocal tmp = {\n\t\t\tstring.pack(\"<i4i4\", array_n, #kvs),\n\t\t\ttypeset,\n\t\t\talign,\n\t\t\ttable.concat(array),\n\t\t\ttable.concat(kvs),\n\t\t}\n\t\tdoc.table[index] = table.concat(tmp)\n\t\treturn index\n\tend\n\tdump_table(root)\n\t-- encode document\n\tlocal index = {}\n\tlocal offset = 0\n\tfor i, v in ipairs(doc.table) do\n\t\tindex[i] = string.pack(\"<I4\", offset)\n\t\toffset = offset + #v\n\tend\n\tlocal tmp = {\n\t\tstring.pack(\"<I4\", 4 + 4 + 4 * doc.table_n + offset),\n\t\tstring.pack(\"<I4\", doc.table_n),\n\t\ttable.concat(index),\n\t\ttable.concat(doc.table),\n\t\ttable.concat(doc.strings, \"\\0\"),\n\t\t\"\\0\",\n\t}\n\treturn table.concat(tmp)\nend\n\nfunction ctd.undump(v)\n\tlocal stringtbl, n = string.unpack(\"<I4I4\",v)\n\tlocal index = { string.unpack(\"<\" .. string.rep(\"I4\", n), v, 9) }\n\tlocal header = 4 + 4 + 4 * n + 1\n\tstringtbl = stringtbl + 1\n\tlocal tblidx = {}\n\tlocal function decode(n)\n\t\tlocal toffset = index[n+1] + header\n\t\tlocal array, dict = string.unpack(\"<I4I4\", v, toffset)\n\t\tlocal types = { string.unpack(string.rep(\"B\", (array+dict)), v, toffset + 8) }\n\t\tlocal offset = ((array + dict + 8 + 3) & ~3) + toffset\n\t\tlocal result = {}\n\t\tlocal function value(t)\n\t\t\tlocal off = offset\n\t\t\toffset = offset + 4\n\t\t\tif t == 1 then\t-- integer\n\t\t\t\treturn (string.unpack(\"<i4\", v, off))\n\t\t\telseif t == 2 then -- float\n\t\t\t\treturn (string.unpack(\"<f\", v, off))\n\t\t\telseif t == 3 then -- boolean\n\t\t\t\treturn string.unpack(\"<i4\", v, off) ~= 0\n\t\t\telseif t == 4 then -- table\n\t\t\t\tlocal tindex = (string.unpack(\"<I4\", v, off))\n\t\t\t\treturn decode(tindex)\n\t\t\telseif t == 5 then -- string\n\t\t\t\tlocal sindex = string.unpack(\"<I4\", v, off)\n\t\t\t\treturn (string.unpack(\"z\", v, stringtbl + sindex))\n\t\t\telse\n\t\t\t\terror (string.format(\"Invalid data at %d (%d)\", off, t))\n\t\t\tend\n\t\tend\n\t\tfor i=1,array do\n\t\t\ttable.insert(result, value(types[i]))\n\t\tend\n\t\tfor i=1,dict do\n\t\t\tlocal sindex = string.unpack(\"<I4\", v, offset)\n\t\t\toffset = offset + 4\n\t\t\tlocal key = string.unpack(\"z\", v, stringtbl + sindex)\n\t\t\tresult[key] = value(types[array + i])\n\t\tend\n\t\ttblidx[result] = n\n\t\treturn result\n\tend\n\treturn decode(0), tblidx\nend\n\nlocal function diffmap(last, current)\n\tlocal lastv, lasti = ctd.undump(last)\n\tlocal curv, curi = ctd.undump(current)\n\tlocal map = {}\t-- new(current index):old(last index)\n\tlocal function comp(lastr, curr)\n\t\tlocal old = lasti[lastr]\n\t\tlocal new = curi[curr]\n\t\tmap[new] = old\n\t\tfor k,v in pairs(lastr) do\n\t\t\tif type(v) == \"table\" then\n\t\t\t\tlocal newv = curr[k]\n\t\t\t\tif type(newv) == \"table\" then\n\t\t\t\t\tcomp(v, newv)\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\tcomp(lastv, curv)\n\treturn map\nend\n\nfunction ctd.diff(last, current)\n\tlocal map = diffmap(last, current)\n\tlocal stringtbl, n = string.unpack(\"<I4I4\",current)\n\tlocal _, lastn = string.unpack(\"<I4I4\",last)\n\tlocal existn = 0\n\tfor k,v in pairs(map) do\n\t\texistn = existn + 1\n\tend\n\tlocal newn = lastn\n\tfor i = 0, n-1 do\n\t\tif not map[i] then\n\t\t\tmap[i] = newn\n\t\t\tnewn = newn + 1\n\t\tend\n\tend\n\t-- remap current\n\tlocal index = { string.unpack(\"<\" .. string.rep(\"I4\", n), current, 9) }\n\tlocal header = 4 + 4 + 4 * n + 1\n\tlocal function remap(n)\n\t\tlocal toffset = index[n+1] + header\n\t\tlocal array, dict = string.unpack(\"<I4I4\", current, toffset)\n\t\tlocal types = { string.unpack(string.rep(\"B\", (array+dict)), current, toffset + 8) }\n\t\tlocal hlen = (array + dict + 8 + 3) & ~3\n\t\tlocal hastable = false\n\t\tfor _, v in ipairs(types) do\n\t\t\tif v == 4 then -- table\n\t\t\t\thastable = true\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\t\tif not hastable then\n\t\t\treturn string.sub(current, toffset, toffset + hlen + (array + dict * 2) * 4 - 1)\n\t\tend\n\t\tlocal offset = hlen + toffset\n\t\tlocal pat = \"<\" .. string.rep(\"I4\", array + dict * 2)\n\t\tlocal values = { string.unpack(pat, current, offset) }\n\t\tfor i = 1, array do\n\t\t\tif types[i] == 4 then\t-- table\n\t\t\t\tvalues[i] = map[values[i]]\n\t\t\tend\n\t\tend\n\t\tfor i = 1, dict do\n\t\t\tif types[i + array] == 4 then -- table\n\t\t\t\tvalues[array + i * 2] = map[values[array + i * 2]]\n\t\t\tend\n\t\tend\n\t\treturn string.sub(current, toffset, toffset + hlen - 1) ..\n\t\t\tstring.pack(pat, table.unpack(values))\n\tend\n\t-- rebuild\n\tlocal oldindex = { string.unpack(\"<\" .. string.rep(\"I4\", n), current, 9) }\n\tlocal index = {}\n\tfor i = 1, newn do\n\t\tindex[i] = 0xffffffff\n\tend\n\tfor i = 0, #map do\n\t\tindex[map[i]+1] = oldindex[i+1]\n\tend\n\n\tlocal tmp = {\n\t\tstring.pack(\"<I4I4\", stringtbl + (newn - n) * 4, newn), -- expand index table\n\t\tstring.pack(\"<\" .. string.rep(\"I4\", newn), table.unpack(index)),\n\t}\n\tfor i = 0, n - 1 do\n\t\ttable.insert(tmp, remap(i))\n\tend\n\ttable.insert(tmp, string.sub(current, stringtbl+1))\n\n\treturn table.concat(tmp)\nend\n\nreturn ctd\n"
  },
  {
    "path": "lualib/skynet/datasheet/init.lua",
    "content": "local skynet = require \"skynet\"\nlocal service = require \"skynet.service\"\nlocal core = require \"skynet.datasheet.core\"\n\nlocal datasheet_svr\n\nskynet.init(function()\n\tdatasheet_svr = service.query \"datasheet\"\nend)\n\nlocal datasheet = {}\nlocal sheets = setmetatable({}, {\n\t__gc = function(t)\n\t\tskynet.send(datasheet_svr, \"lua\", \"close\")\n\tend,\n})\n\nlocal function querysheet(name)\n\treturn skynet.call(datasheet_svr, \"lua\", \"query\", name)\nend\n\nlocal function updateobject(name)\n\tlocal t = sheets[name]\n\tif not t.object then\n\t\tt.object = core.new(t.handle)\n\tend\n\tlocal function monitor()\n\t\tlocal handle = t.handle\n\t\tlocal newhandle = skynet.call(datasheet_svr, \"lua\", \"monitor\", handle)\n\t\tcore.update(t.object, newhandle)\n\t\tt.handle = newhandle\n\t\tskynet.send(datasheet_svr, \"lua\", \"release\", handle)\n\t\treturn monitor()\n\tend\n\tskynet.fork(monitor)\nend\n\nfunction datasheet.query(name)\n\tlocal t = sheets[name]\n\tif not t then\n\t\tt = {}\n\t\tsheets[name] = t\n\tend\n\tif t.error then\n\t\terror(t.error)\n\tend\n\tif t.object then\n\t\treturn t.object\n\tend\n\tif t.queue then\n\t\tlocal co = coroutine.running()\n\t\ttable.insert(t.queue, co)\n\t\tskynet.wait(co)\n\telse\n\t\tt.queue = {}\t-- create wait queue for other query\n\t\tlocal ok, handle = pcall(querysheet, name)\n\t\tif ok then\n\t\t\tt.handle = handle\n\t\t\tupdateobject(name)\n\t\telse\n\t\t\tt.error = handle\n\t\tend\n\t\tlocal q = t.queue\n\t\tt.queue = nil\n\t\tfor _, co in ipairs(q) do\n\t\t\tskynet.wakeup(co)\n\t\tend\n\tend\n\tif t.error then\n\t\terror(t.error)\n\tend\n\treturn t.object\nend\n\nreturn datasheet\n"
  },
  {
    "path": "lualib/skynet/db/mongo/transaction.lua",
    "content": "--[[\nmongo会话事务接口支持子模块，可根据需要引入：\nlocal mongo = require \"mongo\"\nmongo.enable(\"transaction\")\n]]\nlocal bson = require \"bson\"\nlocal driver = require \"skynet.mongo.driver\"\nlocal assert = assert\nlocal table = table\nlocal mongo = require \"mongo\"\n\nlocal bson_encode =\tbson.encode\nlocal bson_encode_order\t= bson.encode_order\nlocal bson_decode =\tbson.decode\nlocal bson_int64 = bson.int64\nlocal empty_bson = bson_encode {}\n\nlocal M = {}\n\nlocal function werror(r)\n\tlocal ok = (r.ok == 1 and not r.writeErrors and not r.writeConcernError and not r.errmsg)\n\n\tlocal err\n\tif not ok then\n\t\tif r.writeErrors then\n\t\t\terr = r.writeErrors[1].errmsg\n\t\telseif r.writeConcernError then\n\t\t\terr = r.writeConcernError.errmsg\n\t\telse\n\t\t\terr = r.errmsg\n\t\tend\n\tend\n\treturn ok, err, r\nend\n\nfunction M.init(depend)\n\t--[[\n\t要使用mongodb事务的前提是需要先将mongodb配置为副本集，否则报错：Transaction numbers are only allowed on a replica set member or mongos\n\t比如修改配置文件/etc/mongod.conf中：\n\t replication:\n\t   replSetName: \"rs0\"\n\t然后重启monogod服务\n\t以下带下划线结尾的接口为内部私有接口，目前不宜应用层直接调用\n\t]]\n\t-- {\n\t--   id = {\n\t--     id = \"000504301FB085921E4FF58C38E3F270922FFF\",\n\t--   },\n\t--   timeoutMinutes = 30,\n\t--   ok = 1.0,\n\t-- }\n\tlocal mongo_db = depend.mongo_db\n\tassert(\"table\" == type(mongo_db))\n\t---@return table\n\tfunction mongo_db:startSession_()\n\t\treturn self:runCommand(\"startSession\") -- 由mongo服务器生成，避免自产生的id相同的冲突\n\tend\n\n\t---@param session_id table\n\tfunction mongo_db:endSessions_(session_id)\n\t\treturn self:runCommand(\"endSessions\", {bson_encode(session_id)})\n\tend\n\n\tlocal transaction_id = 0\n\t---@return integer\n\tlocal function startTransaction_()\n\t\ttransaction_id = transaction_id + 1\n\t\tif transaction_id > 9999999 then\n\t\t\ttransaction_id = 1\n\t\tend\n\t\treturn transaction_id\n\tend\n\n\t---@param session_id table\n\t---@param transaction_id integer\n\tlocal function genTransactionParams(session_id, transaction_id, startTransaction)\n\t\treturn \"lsid\", bson_encode(session_id),\n\t\t\t\"txnNumber\", bson_int64(transaction_id)       -- 这是此会话中的第一个事务，故从1开始 -- BSON field 'OperationSessionInfo.txnNumber' is the wrong type 'int', expected type 'long'\n\t\t\t,\"autocommit\", false\n\t\t\t, startTransaction and \"startTransaction\" or nil, startTransaction and startTransaction or nil\n\tend\n\t-- 原始裸接口备用，考虑是否需要开放支持跨协程事务，但每个更新操作需手动额外调用runCommand来辅助实现，而不能调用原有相关接口(如safe_insert)\n\t-- ---@param session_id table\n\t-- ---@param transaction_id integer\n\t-- function mongo_client:commitTransaction_(session_id, transaction_id) -- commitTransaction may only be run against the admin database.\n\t-- \treturn self:runCommand(\"commitTransaction\", 1, \"lsid\", bson_encode(session_id), \"txnNumber\", bson_int64(transaction_id), \"autocommit\", false)\n\t-- end\n\t-- ---@param session_id table\n\t-- ---@param transaction_id integer\n\t-- function mongo_client:abortTransaction_(session_id, transaction_id)\n\t-- \treturn self:runCommand(\"abortTransaction\", 1, \"lsid\", bson_encode(session_id), \"txnNumber\", bson_int64(transaction_id), \"autocommit\", false) -- 如果不设置autocommit则报错：txnNumber may only be provided for multi-document transactions and retryable write commands. autocommit:false was not provided, and abortTransaction is not a retryable write command.\n\t-- end\n\tlocal cur_coroutine = coroutine.running\n\tlocal transaction = {}\n\tlocal function is_in_transaction()\n\t\treturn transaction[cur_coroutine()]\n\tend\n\tlocal function get_cur_transaction_params()\n\t\tlocal TransactionParams = transaction[cur_coroutine()]\n\t\tassert(TransactionParams)\n\t\treturn table.unpack(TransactionParams)\n\tend\n\tlocal function set_transaction_params(params)\n\t\tlocal TransactionParams = transaction[cur_coroutine()]\n\t\tassert(TransactionParams)\n\t\ttable.move(TransactionParams, 1, #TransactionParams, #params + 1, params)\n\t\t-- startTransaction只设置一次为true\n\t\twhile #TransactionParams > 6 do\n\t\t\ttable.remove(TransactionParams)\n\t\tend\n\t\t-- table.insert(params, \"writeConcern\") -- writeConcern is not allowed within a multi-statement transaction\n\t\t-- table.insert(params, bson_encode({w=0}))\n\t\treturn params\n\tend\n\n\tlocal debug_traceback = debug.traceback\n\t-- 只支持同协程事务接口，兼容老接口\n\t---@param fun_transaction fun() 包含多个更新语句，这些语句要么全部成功，要么全部取消，目前同时支持run和send机制，但send接口会自动去掉writeConcern选项\n\t---@return any failed error info | nil ok\n\tfunction mongo_db:run_transaction(fun_transaction)\n\t\tlocal ret = self:startSession_()\n\t\ttransaction[cur_coroutine()] = {genTransactionParams(ret.id, startTransaction_(), true)}\n\t\tlocal ok, err = xpcall(fun_transaction, debug_traceback)\n\t\tlocal r\n\t\tif ok then\n\t\t\tr = self:commit_transaction_() -- 不能报异常，否则后续transaction无法清理\n\t\telse\n\t\t\tr = self:abort_transaction_() -- 不能报异常，否则后续transaction无法清理\n\t\t\t-- error(err, 0)\n\t\tend\n\t\ttransaction[cur_coroutine()] = nil -- 这个位置很关键，必须在commit_transaction和abort_transaction之后，因为其仍依赖本数据\n\t\tself:endSessions_(ret.id) -- 这个不是本事务的关键，所以不处理其返回结果\n\t\tif not err then\n\t\t\tlocal _\n\t\t\t_, err = werror(r)\n\t\tend\n\t\treturn err -- 如果成功err应该为nil\n\tend\n\n\tfunction mongo_db:commit_transaction_()\n\t\t-- local TransactionParams = transaction[cur_coroutine()]\n\t\t-- assert(TransactionParams)\n\t\t-- transaction[cur_coroutine()] = nil\n\t\t-- return self.connection:runCommand(\"commitTransaction\", 1, table.unpack(TransactionParams))\n\t\tlocal ok, r = pcall(function()\n\t\t\treturn self.connection:runCommand(\"commitTransaction\")\n\t\tend)\n\t\t-- transaction[cur_coroutine()] = nil\n\t\tif not ok then\n\t\t\tr = { errmsg = r } -- 模拟mongo风格错误\n\t\tend\n\t\treturn r\n\tend\n\n\tfunction mongo_db:abort_transaction_()\n\t\t-- local TransactionParams = transaction[cur_coroutine()]\n\t\t-- assert(TransactionParams)\n\t\t-- transaction[cur_coroutine()] = nil\n\t\t-- return self.connection:runCommand(\"abortTransaction\", 1, table.unpack(TransactionParams))\n\t\tlocal ok, r = pcall(function()\n\t\t\treturn self.connection:runCommand(\"abortTransaction\")\n\t\tend)\n\t\t-- transaction[cur_coroutine()] = nil\n\t\tif not ok then\n\t\t\tr = { errmsg = r } -- 模拟mongo风格错误\n\t\tend\n\t\treturn r\n\tend\n\tlocal old_runCommand = mongo_db.runCommand\n\tlocal old_send_command = mongo_db.send_command\n\tfunction mongo_db:runCommand(cmd,cmd_v,...)\n\t\tif is_in_transaction() then\n\t\t\tcmd_v = cmd_v or 1\n\t\t\tlocal params = {cmd,cmd_v,...}\n\t\t\treturn old_runCommand(self, table.unpack(set_transaction_params(params)))\n\t\tend\n\t\treturn old_runCommand(self, cmd,cmd_v,...)\n\tend\n\tfunction mongo_db:send_command(cmd,cmd_v,...)\n\t\tif is_in_transaction() then\n\t\t\tcmd_v = cmd_v or 1\n\t\t\tlocal params = {...} -- {cmd,cmd_v,...} 这里要去掉下面重复的cmd和cmd_v\n\t\t\t-- return old_send_command(self, table.unpack(set_transaction_params(params)))\n\t\t\t-- 这里我要需要将writeConcern选项去掉，因为MongoDB 不允许在事务中使用 writeConcern\n\t\t\tlocal conn = self.connection\n\t\t\tlocal request_id = conn:genId()\n\t\t\tlocal sock = conn.__sock\n\t\t\tlocal bson_cmd\n\t\t\tif not cmd_v then\n\t\t\t\t-- ensure cmd remains in first place\n\t\t\t\tbson_cmd = bson_encode_order(cmd, 1, \"$db\", self.name, table.unpack(set_transaction_params(params)))\n\t\t\telse\n\t\t\t\tbson_cmd = bson_encode_order(cmd, cmd_v, \"$db\", self.name, table.unpack(set_transaction_params(params)))\n\t\t\tend\n\n\t\t\tlocal pack = driver.op_msg(request_id, 2, bson_cmd)\n\t\t\tsock:request(pack)\n\t\t\treturn {ok=1} -- fake successful response\n\t\tend\n\t\treturn old_send_command(self, cmd,cmd_v,...)\n\tend\n\n\t-- 测试及使用示例\n\tfunction mongo_db:test_transaction_()\n\t\tlocal tb_name = \"tb_test\"\n\t\tself[tb_name]:drop() -- Transaction numbers are only allowed on a replica set member or mongos\n\t\tlocal db = self[tb_name]\n\t\tprint(self:run_transaction(function()\n\t\t\tprint(\"-----------------------1\")\n\t\t\tprint(db:safe_insert({_id = bson.objectid(), key = 1, d = 1})) -- Only servers in a sharded cluster can start a new transaction at the active transaction number\n\t\t\tprint(\"-----------------------2\")\n\t\t\tprint(db:safe_insert({_id = bson.objectid(), key = 2, d = 2}))\n\t\t\tprint(db:insert({_id = bson.objectid(), key = 4, d = 4, by = \"send\"})) -- 测试send_command接口混用\n\t\t\t-- error(\"err\") -- 如果报错，上面的更新将自动回滚\n\t\t\tprint(\"-----------------------3\")\n\t\t\tprint(db:safe_insert({_id = bson.objectid(), key = 3, d = 3}))\n\t\tend))\n\tend\nend\n\nreturn M"
  },
  {
    "path": "lualib/skynet/db/mongo.lua",
    "content": "local bson = require \"bson\"\n\nrequire \"skynet.socket\"\n\nlocal socketchannel\t= require \"skynet.socketchannel\"\nlocal skynet = require \"skynet\"\nlocal driver = require \"skynet.mongo.driver\"\nlocal md5 =\trequire\t\"md5\"\nlocal crypt = require \"skynet.crypt\"\nlocal rawget = rawget\nlocal assert = assert\nlocal table = table\n\nlocal bson_encode =\tbson.encode\nlocal bson_encode_order\t= bson.encode_order\nlocal bson_decode =\tbson.decode\nlocal bson_int64 = bson.int64\nlocal empty_bson = bson_encode {}\n\nlocal mongo\t= {}\nmongo.null = assert(bson.null)\nmongo.maxkey = assert(bson.maxkey)\nmongo.minkey = assert(bson.minkey)\nmongo.type = assert(bson.type)\n\nlocal mongo_cursor = {}\nlocal cursor_meta =\t{\n\t__index\t= mongo_cursor,\n}\n\nlocal aggregate_cursor = {}\nlocal aggregate_cursor_meta = {\n\t__index\t= aggregate_cursor,\n}\n\nlocal mongo_client = {}\n\nlocal client_meta =\t{\n\t__index\t= function(self, key)\n\t\treturn rawget(mongo_client,\tkey) or\tself:getDB(key)\n\tend,\n\t__tostring = function (self)\n\t\tlocal port_string\n\t\tif self.port then\n\t\t\tport_string\t= \":\" .. tostring(self.port)\n\t\telse\n\t\t\tport_string\t= \"\"\n\t\tend\n\n\t\treturn \"[mongo client :\t\" .. self.host .. port_string ..\"]\"\n\tend,\n\t-- DO NOT need disconnect, because channel will\tshutdown during\tgc\n}\n\nlocal mongo_db = {}\n\nlocal db_meta =\t{\n\t__index\t= function (self, key)\n\t\treturn rawget(mongo_db,\tkey) or\tself:getCollection(key)\n\tend,\n\t__tostring = function (self)\n\t\treturn \"[mongo db :\t\" .. self.name .. \"]\"\n\tend\n}\n\nlocal mongo_collection = {}\nlocal collection_meta =\t{\n\t__index\t= function(self, key)\n\t\treturn rawget(mongo_collection,\tkey) or\tself:getCollection(key)\n\tend\t,\n\t__tostring = function (self)\n\t\treturn \"[mongo collection :\t\" .. self.full_name\t.. \"]\"\n\tend\n}\n\nlocal function dispatch_reply(so)\n\tlocal len_reply\t= so:read(4)\n\tlocal reply\t= so:read(driver.length(len_reply))\n\tlocal result = {}\n\tlocal succ,\treply_id, document = driver.reply(reply)\n\tresult.document\t= document\n\tresult.data\t= reply\n\treturn reply_id, succ, result\nend\n\nlocal function __parse_addr(addr)\n\tlocal host,\tport = string.match(addr, \"([^:]+):(.+)\")\n\treturn host, tonumber(port)\nend\n\nlocal function werror(r)\n    local ok = (r.ok == 1 and not r.writeErrors and not r.writeConcernError and not r.errmsg)\n\n    local err\n    if not ok then\n        if r.writeErrors then\n            err = r.writeErrors[1].errmsg\n        elseif r.writeConcernError then\n            err = r.writeConcernError.errmsg\n        else\n            err = r.errmsg\n        end\n    end\n    return ok, err, r\nend\n\nlocal function wbulkerror(r)\n    local ok, err = werror(r)\n    local cursor\n    if (r.nErrors and r.nErrors ~= 0) and r.cursor then\n        cursor = {}\n        err = err and err .. \";\" or \"\"\n        for i, v in ipairs(r.cursor.firstBatch) do\n            if v.ok ~= 1 then\n                cursor[#cursor+1] = i\n                err = err .. v.errmsg .. \";\"\n            end\n        end\n    end\n    return ok, err, r, cursor\nend\n\nlocal auth_method = {}\n\nlocal function mongo_auth(mongoc)\n\tlocal user = rawget(mongoc,\t\"username\")\n\tlocal pass = rawget(mongoc,\t\"password\")\n\tlocal authmod = rawget(mongoc, \"authmod\") or \"scram_sha1\"\n\tauthmod = \"auth_\" ..  authmod\n\tlocal authdb = rawget(mongoc, \"authdb\")\n\tif authdb then\n\t\tauthdb = mongo_client.getDB(mongoc, authdb)\t-- mongoc has not set metatable yet\n\tend\n\n\treturn function()\n\t\tif user\t~= nil and pass\t~= nil then\n\t\t\t-- autmod can be \"mongodb_cr\" or \"scram_sha1\"\n\t\t\tlocal auth_func = auth_method[authmod]\n\t\t\tassert(auth_func , \"Invalid authmod\")\n\t\t\tassert(auth_func(authdb or mongoc, user, pass))\n\t\tend\n\t\tlocal rs_data =\tmongoc:runCommand(\"ismaster\")\n\t\tif rs_data.ok == 1 then\n\t\t\tif rs_data.hosts then\n\t\t\t\tlocal backup = {}\n\t\t\t\tfor\t_, v in\tipairs(rs_data.hosts) do\n\t\t\t\t\tlocal host,\tport = __parse_addr(v)\n\t\t\t\t\ttable.insert(backup, {host = host, port\t= port})\n\t\t\t\tend\n\t\t\t\tmongoc.__sock:changebackup(backup)\n\t\t\tend\n\t\t\tif rs_data.ismaster\tthen\n\t\t\t\treturn\n\t\t\telseif rs_data.primary then\n\t\t\t\tlocal host,\tport = __parse_addr(rs_data.primary)\n\t\t\t\tmongoc.host\t= host\n\t\t\t\tmongoc.port\t= port\n\t\t\t\tmongoc.__sock:changehost(host, port)\n\t\t\telse\n\t\t\t\t-- socketchannel would try the next host in backup list\n\t\t\t\terror (\"No primary return : \" .. tostring(rs_data.me))\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction mongo.client( conf\t)\n\tlocal first\t= conf\n\tlocal backup = nil\n\tif conf.rs then\n\t\tfirst =\tconf.rs[1]\n\t\tbackup = conf.rs\n\tend\n\tlocal obj =\t{\n\t\thost = first.host,\n\t\tport = first.port or 27017,\n\t\tusername = first.username,\n\t\tpassword = first.password,\n\t\tauthmod = first.authmod,\n\t\tauthdb = first.authdb,\n\t}\n\n\tobj.__id = 0\n\tobj.__sock = socketchannel.channel {\n\t\thost = obj.host,\n\t\tport = obj.port,\n\t\tresponse = dispatch_reply,\n\t\tauth = mongo_auth(obj),\n\t\tbackup = backup,\n\t\tnodelay = true,\n\t\toverload = conf.overload,\n\t}\n\tsetmetatable(obj, client_meta)\n\tobj.__sock:connect(true)\t-- try connect only\tonce\n\treturn obj\nend\n\nfunction mongo_client:getDB(dbname)\n\tlocal db = {\n\t\tconnection = self,\n\t\tname = dbname,\n\t\tfull_name =\tdbname,\n\t\tdatabase = false,\n\t\t__cmd =\tdbname .. \".\" .. \"$cmd\",\n\t}\n\tdb.database\t= db\n\n\treturn setmetatable(db,\tdb_meta)\nend\n\nfunction mongo_client:disconnect()\n\tif self.__sock then\n\t\tlocal so = self.__sock\n\t\tself.__sock\t= false\n\t\tso:close()\n\tend\nend\n\nfunction mongo_client:genId()\n\tlocal id = self.__id + 1\n\tself.__id =\tid\n\treturn id\nend\n\nfunction mongo_client:runCommand(...)\n\tif not self.admin then\n\t\tself.admin = self:getDB\t\"admin\"\n\tend\n\treturn self.admin:runCommand(...)\nend\n\nlocal function filter(tbl, key, value)\n    if value == nil then return end\n    tbl[#tbl+1] = key\n    tbl[#tbl+1] = type(value) == \"table\" and bson_encode(value) or value\nend\n\nlocal bulkWrite = {}\nbulkWrite.insert = function(nsindex, doc)\n    return bson_encode_order(\"insert\", nsindex, \"document\", bson_encode(doc.insert))\nend\n\nbulkWrite.delete = function(nsindex, doc)\n    local args = {\"delete\", nsindex, \"filter\", bson_encode(doc.filter), \"multi\", doc.multi or false}\n    filter(args, \"hit\", doc.hit)\n    filter(args, \"collation\", doc.collation)\n    return bson_encode_order(table.unpack(args))\nend\n\n--update仅支持原子操作更新/聚合管道更新 详情阅读官方文档\n--arrayFilters 过滤方式需要遍历encode 暂时不支持\nbulkWrite.update = function(nsindex, doc)\n    local args = {\"update\", nsindex, \"filter\", bson_encode(doc.filter), \"updateMods\", bson_encode(doc.update),\n        \"multi\", doc.multi or false, \"upsert\", doc.upsert or false}\n    filter(args, \"hit\", doc.hit)\n    filter(args, \"constants\", doc.constants)\n    filter(args, \"collation\", doc.collation)\n    return bson_encode_order(table.unpack(args))\nend\n\n--bulkWrite 依赖 mongo8.0x\n--忽略let,cursor,writeConcern 参数\n---@param datas table 待写入数据\n---       - op string 写入数据方式 参见：bulkWrite\n---       - collection string 数据写入目标, 用于构建nsInfo； 注意：采用 空间.集合方式\n---       - ... 操作具体参数 insert采用：insert填充document, update采用 update 填充updateMods\n---       示例：{op = \"insert\", collection = \"log.online\", insert = {count=0}}\n---             {op = \"update\", collection = \"log.online\", update = {[\"$set\"] = {count = 2}}, upsert = true}}\nfunction mongo_client:bulkWrite(datas, comment, ordered, verify, errorsOnly)\n    local ops, ns, map = {}, {}, {}\n    for i, v in ipairs(datas) do\n        if not map[v.collection] then\n            map[v.collection] = #ns  --ops 索引从0开始\n            ns[#ns+1] = bson_encode({ns = v.collection})\n        end\n        local f = assert(bulkWrite[v.op], v.op)\n        ops[i] = f(map[v.collection], v)\n    end\n    local args = {\"bulkWrite\", 1, \"ops\", ops, \"nsInfo\", ns}\n    filter(args, \"ordered\", ordered) --是否有序执行 默认有序\n    filter(args, \"bypassDocumentValidation\", verify) --是否验证 默认验证\n    filter(args, \"comment\", comment) --日志跟踪注释\n    filter(args, \"errorsOnly\",errorsOnly) -- 仅返回错误信息\n    return wbulkerror(self:runCommand(table.unpack(args)))\nend\n\nfunction auth_method:auth_mongodb_cr(user,password)\n\tlocal password = md5.sumhexa(string.format(\"%s:mongo:%s\",user,password))\n\tlocal result= self:runCommand \"getnonce\"\n\tif result.ok ~=1 then\n\t\treturn false\n\tend\n\n\tlocal key =\tmd5.sumhexa(string.format(\"%s%s%s\",result.nonce,user,password))\n\tlocal result= self:runCommand (\"authenticate\",1,\"user\",user,\"nonce\",result.nonce,\"key\",key)\n\treturn result.ok ==\t1\nend\n\nlocal function salt_password(password, salt, iter)\n\tsalt = salt .. \"\\0\\0\\0\\1\"\n\tlocal output = crypt.hmac_sha1(password, salt)\n\tlocal inter = output\n\tfor i=2,iter do\n\t\tinter = crypt.hmac_sha1(password, inter)\n\t\toutput = crypt.xor_str(output, inter)\n\tend\n\treturn output\nend\n\nfunction auth_method:auth_scram_sha1(username,password)\n\tlocal user = string.gsub(string.gsub(username, '=', '=3D'), ',' , '=2C')\n\tlocal nonce = crypt.base64encode(crypt.randomkey())\n\tlocal first_bare = \"n=\"  .. user .. \",r=\"  .. nonce\n\tlocal sasl_start_payload = crypt.base64encode(\"n,,\" .. first_bare)\n\tlocal r\n\n\tr = self:runCommand(\"saslStart\",1,\"autoAuthorize\",1,\"mechanism\",\"SCRAM-SHA-1\",\"payload\",sasl_start_payload)\n\tif r.ok ~= 1 then\n\t\treturn false\n\tend\n\n\tlocal conversationId = r['conversationId']\n\tlocal server_first = r['payload']\n\tlocal parsed_s = crypt.base64decode(server_first)\n\tlocal parsed_t = {}\n\tfor k, v in string.gmatch(parsed_s, \"(%w+)=([^,]*)\") do\n\t\tparsed_t[k] = v\n\tend\n\tlocal iterations = tonumber(parsed_t['i'])\n\tlocal salt = parsed_t['s']\n\tlocal rnonce = parsed_t['r']\n\n\tif string.sub(rnonce, 1, 12) ~= nonce then\n\t\tskynet.error(\"Server returned an invalid nonce.\")\n\t\treturn false\n\tend\n\tlocal without_proof = \"c=biws,r=\" .. rnonce\n\tlocal pbkdf2_key = md5.sumhexa(string.format(\"%s:mongo:%s\",username,password))\n\tlocal salted_pass = salt_password(pbkdf2_key, crypt.base64decode(salt), iterations)\n\tlocal client_key = crypt.hmac_sha1(salted_pass, \"Client Key\")\n\tlocal stored_key = crypt.sha1(client_key)\n\tlocal auth_msg = first_bare .. ',' .. parsed_s .. ',' .. without_proof\n\tlocal client_sig = crypt.hmac_sha1(stored_key, auth_msg)\n\tlocal client_key_xor_sig = crypt.xor_str(client_key, client_sig)\n\tlocal client_proof = \"p=\" .. crypt.base64encode(client_key_xor_sig)\n\tlocal client_final = crypt.base64encode(without_proof .. ',' .. client_proof)\n\tlocal server_key = crypt.hmac_sha1(salted_pass, \"Server Key\")\n\tlocal server_sig = crypt.base64encode(crypt.hmac_sha1(server_key, auth_msg))\n\n\tr = self:runCommand(\"saslContinue\",1,\"conversationId\",conversationId,\"payload\",client_final)\n\tif r.ok ~= 1 then\n\t\treturn false\n\tend\n\tparsed_s = crypt.base64decode(r['payload'])\n\tparsed_t = {}\n\tfor k, v in string.gmatch(parsed_s, \"(%w+)=([^,]*)\") do\n\t\tparsed_t[k] = v\n\tend\n\tif parsed_t['v'] ~= server_sig then\n\t\tskynet.error(\"Server returned an invalid signature.\")\n\t\treturn false\n\tend\n\tif not r.done then\n\t\tr = self:runCommand(\"saslContinue\",1,\"conversationId\",conversationId,\"payload\",\"\")\n\t\tif r.ok ~= 1 then\n\t\t\treturn false\n\t\tend\n\t\tif not r.done then\n\t\t\tskynet.error(\"SASL conversation failed to complete.\")\n\t\t\treturn false\n\t\tend\n\tend\n\treturn true\nend\n\nfunction mongo_client:logout()\n\tlocal result = self:runCommand \"logout\"\n\treturn result.ok ==\t1\nend\n\nfunction mongo_db:auth(user, pass)\n\tlocal authmod = rawget(self.connection, \"authmod\") or \"scram_sha1\"\n\tlocal auth_func = auth_method[\"auth_\" .. authmod]\n\tassert(auth_func , \"Invalid authmod\")\n\treturn auth_func(self, user, pass)\nend\n\nfunction mongo_db:runCommand(cmd,cmd_v,...)\n\tlocal conn = self.connection\n\tlocal request_id = conn:genId()\n\tlocal sock = conn.__sock\n\tlocal bson_cmd\n\tif not cmd_v then\n\t\t-- ensure cmd remains in first place\n\t\tbson_cmd = bson_encode_order(cmd,1, \"$db\", self.name)\n\telse\n\t\tbson_cmd = bson_encode_order(cmd,cmd_v, \"$db\", self.name, ...)\n\tend\n\n\tlocal pack = driver.op_msg(request_id, 0, bson_cmd)\n\t-- we must hold\treq\t(req.data),\tbecause\treq.document is\ta lightuserdata, it's a\tpointer\tto the string (req.data)\n\tlocal req =\tsock:request(pack, request_id)\n\tlocal doc =\treq.document\n\treturn bson_decode(doc)\nend\n\n--- send command without response\nfunction mongo_db:send_command(cmd, cmd_v, ...)\n\tlocal conn = self.connection\n\tlocal request_id = conn:genId()\n\tlocal sock = conn.__sock\n\tlocal bson_cmd\n\tif not cmd_v then\n\t\t-- ensure cmd remains in first place\n\t\tbson_cmd = bson_encode_order(cmd, 1, \"$db\", self.name, \"writeConcern\", {w=0})\n\telse\n\t\tbson_cmd = bson_encode_order(cmd, cmd_v, \"$db\", self.name, \"writeConcern\", {w=0}, ...)\n\tend\n\n\tlocal pack = driver.op_msg(request_id, 2, bson_cmd)\n\tsock:request(pack)\n\treturn {ok=1} -- fake successful response\nend\n\nfunction mongo_db:getCollection(collection)\n\tlocal col =\t{\n\t\tconnection = self.connection,\n\t\tname = collection,\n\t\tfull_name =\tself.full_name .. \".\" .. collection,\n\t\tdatabase = self.database,\n\t}\n\tself[collection] = setmetatable(col, collection_meta)\n\treturn col\nend\n\nmongo_collection.getCollection = mongo_db.getCollection\n\nfunction mongo_collection:insert(doc)\n\tif doc._id == nil then\n\t\tdoc._id\t= bson.objectid()\n\tend\n\tself.database:send_command(\"insert\", self.name, \"documents\", {bson_encode(doc)})\nend\n\nfunction mongo_collection:safe_insert(doc)\n\tlocal r = self.database:runCommand(\"insert\", self.name, \"documents\", {bson_encode(doc)})\n\treturn werror(r)\nend\n\nfunction mongo_collection:raw_safe_insert(doc)\n\tlocal r = self.database:runCommand(\"insert\", self.name, \"documents\", {doc})\n\treturn werror(r)\nend\n\nfunction mongo_collection:batch_insert(docs)\n\tfor\ti=1,#docs do\n\t\tif docs[i]._id == nil then\n\t\t\tdocs[i]._id\t= bson.objectid()\n\t\tend\n\t\tdocs[i]\t= bson_encode(docs[i])\n\tend\n\n\tself.database:send_command(\"insert\", self.name, \"documents\", docs)\nend\n\nmongo_collection.insert_many = mongo_collection.batch_insert\n\nfunction mongo_collection:safe_batch_insert(docs)\n\tfor i = 1, #docs do\n\t\tif docs[i]._id == nil then\n\t\t\tdocs[i]._id = bson.objectid()\n\t\tend\n\t\tdocs[i] = bson_encode(docs[i])\n\tend\n\n\tlocal r = self.database:runCommand(\"insert\", self.name, \"documents\", docs)\n\treturn werror(r)\nend\n\nmongo_collection.safe_insert_many = mongo_collection.safe_batch_insert\n\nfunction mongo_collection:update(query,update,upsert,multi)\n\tself.database:send_command(\"update\", self.name, \"updates\", {bson_encode({\n\t\tq = query,\n\t\tu = update,\n\t\tupsert = upsert,\n\t\tmulti = multi\n\t})})\nend\n\nfunction mongo_collection:safe_update(query, update, upsert, multi)\n\tlocal r = self.database:runCommand(\"update\", self.name, \"updates\", {bson_encode({\n\t\tq = query,\n\t\tu = update,\n\t\tupsert = upsert,\n\t\tmulti = multi,\n\t})})\n\treturn werror(r)\nend\n\nfunction mongo_collection:batch_update(updates)\n\tlocal updates_tb = {}\n\tfor i = 1, #updates do\n\t\tupdates_tb[i] = bson_encode({\n\t\t\tq = updates[i].query,\n\t\t\tu = updates[i].update,\n\t\t\tupsert = updates[i].upsert,\n\t\t\tmulti = updates[i].multi,\n\t\t})\n\tend\n\n\tself.database:send_command(\"update\", self.name, \"updates\", updates_tb)\nend\n\nfunction mongo_collection:safe_batch_update(updates)\n\tlocal updates_tb = {}\n\tfor i = 1, #updates do\n\t\tupdates_tb[i] = bson_encode({\n\t\t\tq = updates[i].query,\n\t\t\tu = updates[i].update,\n\t\t\tupsert = updates[i].upsert,\n\t\t\tmulti = updates[i].multi,\n\t\t})\n\tend\n\n\tlocal r = self.database:runCommand(\"update\", self.name, \"updates\", updates_tb)\n\treturn werror(r)\nend\n\nfunction mongo_collection:raw_safe_update(update)\n\tlocal r = self.database:runCommand(\"update\", self.name, \"updates\", {update})\n\treturn werror(r)\nend\n\nfunction mongo_collection:delete(query, single)\n\tself.database:send_command(\"delete\", self.name, \"deletes\", {bson_encode({\n\t\tq = query,\n\t\tlimit = single and 1 or 0,\n\t})})\nend\n\nfunction mongo_collection:safe_delete(query, single)\n\tlocal r = self.database:runCommand(\"delete\", self.name, \"deletes\", {bson_encode({\n\t\tq = query,\n\t\tlimit = single and 1 or 0,\n\t})})\n\treturn werror(r)\nend\n\nfunction mongo_collection:safe_batch_delete(deletes, single)\n\tlocal delete_tb = {}\n\tfor i = 1, #deletes do\n\t\tdelete_tb[i] = bson_encode({\n\t\t\tq = deletes[i],\n\t\t\tlimit = single and 1 or 0,\n\t\t})\n\tend\n\tlocal r = self.database:runCommand(\"delete\", self.name, \"deletes\", delete_tb)\n\treturn werror(r)\nend\n\nfunction mongo_collection:raw_safe_delete(delete)\n\tlocal r = self.database:runCommand(\"delete\", self.name, \"deletes\", {delete})\n\treturn werror(r)\nend\n\nfunction mongo_collection:findOne(query, projection)\n\tlocal r = self.database:runCommand(\"find\", self.name, \"filter\", query and bson_encode(query) or empty_bson,\n\t\t\"limit\", 1, \"projection\", projection and bson_encode(projection) or empty_bson)\n\tif r.ok ~= 1 then\n\t\terror(r.errmsg or \"Reply from mongod error\")\n\tend\n\treturn r.cursor.firstBatch[1]\nend\n\nfunction mongo_collection:find(query, projection)\n\treturn setmetatable( {\n\t\t__collection = self,\n\t\t__query\t= query\tand\tbson_encode(query) or empty_bson,\n\t\t__projection = projection and bson_encode(projection) or empty_bson,\n\t\t__ptr =\tnil,\n\t\t__data = nil,\n\t\t__cursor = nil,\n\t\t__document = {},\n\t\t__sort = empty_bson\n\t} ,\tcursor_meta)\nend\n\nlocal function unfold(list, key, ...)\n\tif key == nil then\n\t\treturn list\n\tend\n\tlocal next_func, t = pairs(key)\n\tlocal k, v = next_func(t)\t-- The first key pair\n\ttable.insert(list, k)\n\ttable.insert(list, v)\n\treturn unfold(list, ...)\nend\n\n-- cursor:sort { key = 1 } or cursor:sort( {key1 = 1}, {key2 = -1})\nfunction mongo_cursor:sort(key, key_v, ...)\n\tif key_v then\n\t\tlocal key_list = unfold({}, key, key_v , ...)\n\t\tkey = bson_encode_order(table.unpack(key_list))\n\tend\n\tself.__sort = key\n\treturn self\nend\n\nfunction mongo_cursor:skip(amount)\n\tself.__skip = amount\n\treturn self\nend\n\nfunction mongo_cursor:limit(amount)\n\tself.__limit = amount\n\treturn self\nend\n\nfunction mongo_cursor:hint(indexName)\n\tself.__hint = indexName\n\treturn self\nend\n\nfunction mongo_cursor:maxTimeMS(ms)\n\tself.__maxTimeMS = ms\n\treturn self\nend\n\nlocal opt_func = {}\n\nlocal function opt_define(name)\n\tlocal key = \"__\" .. name\n\topt_func[name] = function (self, ...)\n\t\tlocal v = self[key]\n\t\tif v ~= nil then\n\t\t\treturn name, v, ...\n\t\telse\n\t\t\treturn ...\n\t\tend\n\tend\nend\n\nopt_define \"skip\"\nopt_define \"limit\"\nopt_define \"hint\"\nopt_define \"maxTimeMS\"\n\nlocal function add_opt(self, opt, ...)\n\tif opt == nil then\n\t\treturn\n\tend\n\treturn opt_func[opt](self, add_opt(self, ...))\nend\n\nfunction mongo_cursor:count(with_limit_and_skip)\n\tlocal ret\n\tif with_limit_and_skip then\n\t\tret = self.__collection.database:runCommand('count', self.__collection.name, 'query', self.__query,\n\t\t\tadd_opt(self, \"skip\", \"limit\", \"hint\", \"maxTimeMS\"))\n\telse\n\t\tret = self.__collection.database:runCommand('count', self.__collection.name, 'query', self.__query,\n\t\t\tadd_opt(self, \"hint\", \"maxTimeMS\"))\n\tend\n\tassert(ret.ok == 1, ret.errmsg)\n\treturn ret.n\nend\n\n\n-- For compatibility.\n-- collection:createIndex({username = 1}, {unique = true})\nlocal function createIndex_onekey(self, key, option)\n\tlocal doc = {}\n\tfor k,v in pairs(option) do\n\t\tdoc[k] = v\n\tend\n\tlocal k,v = next(key)\t-- support only one key\n\tassert(next(key,k) == nil, \"Use new api for multi-keys\")\n\tdoc.name = doc.name or (k .. \"_\" .. v)\n\tdoc.key = key\n\n\treturn self.database:runCommand(\"createIndexes\", self.name, \"indexes\", {doc})\nend\n\n\nlocal function IndexModel(option)\n\tlocal doc = {}\n\tfor k,v in pairs(option) do\n\t\tif type(k) == \"string\" then\n\t\t\tdoc[k] = v\n\t\tend\n\tend\n\n\tlocal keys = {}\n\tlocal name\n\tfor _, kv in ipairs(option) do\n\t\tlocal k,v\n\t\tif type(kv) == \"string\" then\n\t\t\tk = kv\n\t\t\tv = 1\n\t\telse\n\t\t\tk,v = next(kv)\n\t\tend\n\t\ttable.insert(keys, k)\n\t\ttable.insert(keys, v)\n\t\tname = (name == nil) and k or (name .. \"_\" .. k)\n\t\tname = name  .. \"_\" .. v\n\tend\n\tassert(name, \"Need keys\")\n\n\tdoc.name = doc.name or name\n\tdoc.key = bson_encode_order(table.unpack(keys))\n\n\treturn doc\nend\n\n-- collection:createIndex { { key1 = 1}, { key2 = 1 },  unique = true }\n-- or collection:createIndex { \"key1\", \"key2\",  unique = true }\n-- or collection:createIndex( { key1 = 1} , { unique = true } )\t-- For compatibility\nfunction mongo_collection:createIndex(arg1 , arg2)\n\tif arg2 then\n\t\treturn createIndex_onekey(self, arg1, arg2)\n\telse\n\t\treturn self.database:runCommand(\"createIndexes\", self.name, \"indexes\", { IndexModel(arg1) })\n\tend\nend\n\nfunction mongo_collection:createIndexes(...)\n\tlocal idx = { ... }\n\tfor k,v in ipairs(idx) do\n\t\tidx[k] = IndexModel(v)\n\tend\n\treturn self.database:runCommand(\"createIndexes\", self.name, \"indexes\", idx)\nend\n\nmongo_collection.ensureIndex = mongo_collection.createIndex\n\nfunction mongo_collection:drop()\n\treturn self.database:runCommand(\"drop\", self.name)\nend\n\n-- collection:dropIndex(\"age_1\")\n-- collection:dropIndex(\"*\")\nfunction mongo_collection:dropIndex(indexName)\n\treturn self.database:runCommand(\"dropIndexes\", self.name, \"index\", indexName)\nend\n\n-- collection:findAndModify({query = {name = \"userid\"}, update = {[\"$inc\"] = {nextid = 1}}, })\n-- keys, value type\n-- query, table\n-- sort, table\n-- remove, bool\n-- update, table\n-- new, bool\n-- fields, bool\n-- upsert, boolean\nfunction mongo_collection:findAndModify(doc)\n\tassert(doc.query)\n\tassert(doc.update or doc.remove)\n\n\tlocal cmd = {\"findAndModify\", self.name};\n\tfor k, v in pairs(doc) do\n\t\ttable.insert(cmd, k)\n\t\ttable.insert(cmd, v)\n\tend\n\treturn self.database:runCommand(table.unpack(cmd))\nend\n\n-- https://docs.mongodb.com/manual/reference/command/aggregate/\n-- collection:aggregate({ { [\"$project\"] = {tags = 1} } }, {cursor={}})\n-- @param pipeline: array\n-- @param options: map\n-- @return\nfunction mongo_collection:aggregate(pipeline, options)\n\tassert(pipeline)\n\tlocal options_cmd\n\tif options then\n\t\toptions_cmd = {}\n\t\tfor k, v in pairs(options) do\n\t\t\ttable.insert(options_cmd, k)\n\t\t\ttable.insert(options_cmd, v)\n\t\tend\n\tend\n\tlocal len = #pipeline\n\treturn setmetatable( {\n\t\t__collection = self,\n\t\t__pipeline =  table.move(pipeline, 1, len, 1, {}),\n\t\t__pipeline_len = len,\n\t\t__options = options_cmd,\n\t\t__ptr =\tnil,\n\t\t__data = nil,\n\t\t__cursor = nil,\n\t\t__document = {},\n\t\t__skip = 0,\n\t\t__limit = 0,\n\t} ,\taggregate_cursor_meta)\nend\n\nfunction mongo_cursor:hasNext()\n\tif self.__ptr == nil then\n\t\tif self.__document == nil then\n\t\t\treturn false\n\t\tend\n\t\tlocal response\n\n\t\tlocal database = self.__collection.database\n\t\tif self.__data == nil then\n\t\t\tlocal name = self.__collection.name\n\t\t\tresponse = database:runCommand(\"find\", name, \"filter\", self.__query, \"sort\", self.__sort,\n\t\t\t\t\"projection\", self.__projection, add_opt(self, \"skip\", \"limit\", \"hint\", \"maxTimeMS\"))\n\t\telse\n\t\t\tif self.__cursor  and self.__cursor > 0 then\n\t\t\t\tlocal name = self.__collection.name\n\t\t\t\tresponse = database:runCommand(\"getMore\", bson_int64(self.__cursor), \"collection\", name)\n\t\t\telse\n\t\t\t\t-- no more\n\t\t\t\tself.__document\t= nil\n\t\t\t\tself.__data\t= nil\n\t\t\t\treturn false\n\t\t\tend\n\t\tend\n\n\t\tif response.ok ~= 1 then\n\t\t\tself.__document\t= nil\n\t\t\tself.__data\t= nil\n\t\t\tself.__cursor =\tnil\n\t\t\terror(response[\"errmsg\"] or \"Reply from mongod error\")\n\t\tend\n\n\t\tlocal cursor = response.cursor\n\t\tself.__document = cursor.firstBatch or cursor.nextBatch\n\t\tself.__data = response\n\t\tself.__ptr = 1\n\t\tself.__cursor = cursor.id\n\n\t\tlocal limit = self.__limit\n\t\tif limit and limit > 0 and cursor.id > 0 then\n\t\t\tlimit = limit - #self.__document\n\t\t\tif limit <= 0 then\n\t\t\t\t-- reach limit\n\t\t\t\tself:close()\n\t\t\tend\n\n\t\t\tself.__limit = limit\n\t\tend\n\n\t\tif cursor.id == 0 and #self.__document == 0 then -- nomore\n\t\t\treturn false\n\t\tend\n\n\t\treturn true\n\tend\n\n\treturn true\nend\n\nfunction mongo_cursor:next()\n\tif self.__ptr == nil then\n\t\terror \"Call\thasNext\tfirst\"\n\tend\n\tlocal r\t= self.__document[self.__ptr]\n\tself.__ptr = self.__ptr\t+ 1\n\tif self.__ptr >\t#self.__document then\n\t\tself.__ptr = nil\n\tend\n\n\treturn r\nend\n\nfunction mongo_cursor:close()\n\tif self.__cursor and self.__cursor > 0 then\n\t\tlocal coll = self.__collection\n\t\tcoll.database:send_command(\"killCursors\", coll.name, \"cursors\", {bson_int64(self.__cursor)})\n\t\tself.__cursor = nil\n\tend\nend\n\nlocal sort_stage = { [\"$sort\"] = true }\nlocal skip_stage = { [\"$skip\"] = 0 }\nlocal limit_stage = { [\"$limit\"] = 0 }\nlocal count_stage = { [\"$count\"] = \"__count\" }\nlocal function format_pipeline(self, with_limit_and_skip, is_count)\n\tlocal len = self.__pipeline_len\n\tif self.__sort and not is_count then\n\t\tlen = len + 1\n\t\tsort_stage[\"$sort\"] = self.__sort\n\t\tself.__pipeline[len] = sort_stage\n\tend\n\tif with_limit_and_skip then\n\t\tif self.__skip > 0 then\n\t\t\tlen = len + 1\n\t\t\tskip_stage[\"$skip\"] = self.__skip\n\t\t\tself.__pipeline[len] = skip_stage\n\t\tend\n\t\tif self.__limit > 0 then\n\t\t\tlen = len + 1\n\t\t\tlimit_stage[\"$limit\"]  = self.__limit\n\t\t\tself.__pipeline[len] = limit_stage\n\t\tend\n\tend\n\tif is_count then\n\t\tlen = len + 1\n\t\tself.__pipeline[len] = count_stage\n\tend\n\tfor i = 1, 2 do self.__pipeline[len + i] = nil end\n\treturn self.__pipeline\nend\n\nfunction aggregate_cursor:count(with_limit_and_skip)\n\tlocal ret\n\tlocal name = self.__collection.name\n\tlocal database = self.__collection.database\n\tif self.__options then\n\t\tret = database:runCommand(\"aggregate\", name, \"pipeline\", format_pipeline(self, with_limit_and_skip, true),\n\t\t\ttable.unpack(self.__options))\n\telse\n\t\tret = database:runCommand(\"aggregate\", name, \"pipeline\", format_pipeline(self, with_limit_and_skip, true),\n\t\t\t\"cursor\", empty_bson)\n\tend\n\tif ret.ok ~= 1 then\n\t\terror(ret[\"errmsg\"] or \"Reply from mongod error\")\n\tend\n\treturn ret.cursor.firstBatch[1].__count\nend\n\nfunction aggregate_cursor:hasNext()\n\tif self.__ptr == nil then\n\t\tif self.__document == nil then\n\t\t\treturn false\n\t\tend\n\t\tlocal ret\n\t\tlocal name = self.__collection.name\n\t\tlocal database = self.__collection.database\n\t\tif self.__data == nil then\n\t\t\tif self.__options then\n\t\t\t\tret = database:runCommand(\"aggregate\", name, \"pipeline\", format_pipeline(self, true), table.unpack(self.__options))\n\t\t\telse\n\t\t\t\tret = database:runCommand(\"aggregate\", name, \"pipeline\", format_pipeline(self, true), \"cursor\", empty_bson)\n\t\t\tend\n\t\telse\n\t\t\tif self.__cursor  and self.__cursor > 0 then\n\t\t\t\tret = database:runCommand(\"getMore\", bson_int64(self.__cursor), \"collection\", name)\n\t\t\telse\n\t\t\t\t-- no more\n\t\t\t\tself.__document\t= nil\n\t\t\t\tself.__data\t= nil\n\t\t\t\treturn false\n\t\t\tend\n\t\tend\n\n\t\tif ret.ok ~= 1 then\n\t\t\tself.__document\t= nil\n\t\t\tself.__data\t= nil\n\t\t\tself.__cursor =\tnil\n\t\t\terror(ret[\"errmsg\"] or \"Reply from mongod error\")\n\t\tend\n\n\t\tlocal cursor = ret.cursor\n\t\tself.__document = cursor.firstBatch or cursor.nextBatch\n\t\tself.__data = ret\n\t\tself.__ptr = 1\n\t\tself.__cursor = cursor.id\n\n\t\tlocal limit = self.__limit\n\t\tif cursor.id > 0 and limit > 0 then\n\t\t\tlimit = limit - #self.__document\n\t\t\tif limit <= 0 then\n\t\t\t\t-- reach limit\n\t\t\t\tself:close()\n\t\t\tend\n\n\t\t\tself.__limit = limit\n\t\tend\n\n\t\tif cursor.id == 0 and #self.__document == 0 then -- nomore\n\t\t\treturn false\n\t\tend\n\n\t\treturn true\n\tend\n\n\treturn true\nend\n\naggregate_cursor.sort =  mongo_cursor.sort\naggregate_cursor.skip = mongo_cursor.skip\naggregate_cursor.limit = mongo_cursor.limit\naggregate_cursor.next = mongo_cursor.next\naggregate_cursor.close = mongo_cursor.close\n\n--[[\n支持插件式扩展模式\n比如要添加mongo会话事务接口支持功能可在事务接口使用前执行以下代码：\nlocal mongo = require \"mongo\"\nmongo.enable(\"transaction\")\n]]\nlocal inited_modules = {} -- 确保每个子模块仅能初始化一次\nfunction mongo.enable(name)\n\tif inited_modules[name] then\n\t\treturn\n\tend\n\tinited_modules[name] = true\n\tlocal m = require(\"skynet.db.mongo.\" .. name)\n\tm.init({ mongo_db = mongo_db }) -- 后续可增加更多的扩展模块支持\nend\n\nreturn mongo\n"
  },
  {
    "path": "lualib/skynet/db/mysql.lua",
    "content": "-- Copyright (C) 2012 Yichun Zhang (agentzh)\n-- Copyright (C) 2014 Chang Feng\n-- This file is modified version from https://github.com/openresty/lua-resty-mysql\n-- The license is under the BSD license.\n-- Modified by Cloud Wu (remove bit32 for lua 5.3)\n\n-- protocol detail: https://mariadb.com/kb/en/clientserver-protocol/\n\nlocal socketchannel = require \"skynet.socketchannel\"\nlocal crypt = require \"skynet.crypt\"\n\nlocal sub = string.sub\nlocal strgsub = string.gsub\nlocal strformat = string.format\nlocal strbyte = string.byte\nlocal strchar = string.char\nlocal strrep = string.rep\nlocal strunpack = string.unpack\nlocal strpack = string.pack\nlocal sha1 = crypt.sha1\nlocal setmetatable = setmetatable\nlocal error = error\nlocal tonumber = tonumber\nlocal tointeger = math.tointeger\n\nlocal _M = {_VERSION = \"0.14\"}\n\n-- the following charset map is generated from the following mysql query:\n--   SELECT CHARACTER_SET_NAME, ID\n--   FROM information_schema.collations\n--   WHERE IS_DEFAULT = 'Yes' ORDER BY id;\nlocal CHARSET_MAP = {\n    _default  = 0,\n    big5      = 1,\n    dec8      = 3,\n    cp850     = 4,\n    hp8       = 6,\n    koi8r     = 7,\n    latin1    = 8,\n    latin2    = 9,\n    swe7      = 10,\n    ascii     = 11,\n    ujis      = 12,\n    sjis      = 13,\n    hebrew    = 16,\n    tis620    = 18,\n    euckr     = 19,\n    koi8u     = 22,\n    gb2312    = 24,\n    greek     = 25,\n    cp1250    = 26,\n    gbk       = 28,\n    latin5    = 30,\n    armscii8  = 32,\n    utf8      = 33,\n    ucs2      = 35,\n    cp866     = 36,\n    keybcs2   = 37,\n    macce     = 38,\n    macroman  = 39,\n    cp852     = 40,\n    latin7    = 41,\n    utf8mb4   = 45,\n    cp1251    = 51,\n    utf16     = 54,\n    utf16le   = 56,\n    cp1256    = 57,\n    cp1257    = 59,\n    utf32     = 60,\n    binary    = 63,\n    geostd8   = 92,\n    cp932     = 95,\n    eucjpms   = 97,\n    gb18030   = 248\n}\n\n-- constants\nlocal COM_QUERY = \"\\x03\"\nlocal COM_PING = \"\\x0e\"\nlocal COM_STMT_PREPARE = \"\\x16\"\nlocal COM_STMT_EXECUTE = \"\\x17\"\nlocal COM_STMT_CLOSE = \"\\x19\"\nlocal COM_STMT_RESET = \"\\x1a\"\nlocal CURSOR_TYPE_NO_CURSOR = 0x00\nlocal SERVER_MORE_RESULTS_EXISTS = 8\n\nlocal mt = {__index = _M}\n\n-- mysql field value type converters\nlocal converters = {}\n\nfor i = 0x01, 0x05 do\n    -- tiny, short, long, float, double\n    converters[i] = tonumber\nend\nconverters[0x08] = tonumber -- long long\nconverters[0x09] = tonumber -- int24\nconverters[0x0d] = tonumber -- year\nconverters[0xf6] = tonumber -- newdecimal\n\nlocal function _get_byte1(data, i)\n    return strbyte(data, i), i + 1\nend\n\nlocal function _get_int1(data, i, is_signed)\n    if not is_signed then\n        return strunpack(\"<I1\", data, i)\n    end\n    return strunpack(\"<i1\", data, i)\nend\n\nlocal function _get_byte2(data, i)\n    return strunpack(\"<I2\", data, i)\nend\n\nlocal function _get_int2(data, i, is_signed)\n    if not is_signed then\n        return strunpack(\"<I2\", data, i)\n    end\n    return strunpack(\"<i2\", data, i)\nend\n\nlocal function _get_byte3(data, i)\n    return strunpack(\"<I3\", data, i)\nend\n\nlocal function _get_int3(data, i, is_signed)\n    if not is_signed then\n        return strunpack(\"<I3\", data, i)\n    end\n    return strunpack(\"<i3\", data, i)\nend\n\nlocal function _get_byte4(data, i)\n    return strunpack(\"<I4\", data, i)\nend\n\nlocal function _get_int4(data, i, is_signed)\n    if not is_signed then\n        return strunpack(\"<I4\", data, i)\n    end\n    return strunpack(\"<i4\", data, i)\nend\n\nlocal function _get_byte8(data, i)\n    return strunpack(\"<I8\", data, i)\nend\n\nlocal function _get_int8(data, i, is_signed)\n    if not is_signed then\n        return strunpack(\"<I8\", data, i)\n    end\n    return strunpack(\"<i8\", data, i)\nend\n\nlocal function _get_float(data, i)\n    return strunpack(\"<f\", data, i)\nend\n\nlocal function _get_double(data, i)\n    return strunpack(\"<d\", data, i)\nend\n\nlocal function _set_byte2(n)\n    return strpack(\"<I2\", n)\nend\n\n-- local function _set_byte3(n)\n--     return strpack(\"<I3\", n)\n-- end\n\n-- local function _set_byte4(n)\n--     return strpack(\"<I4\", n)\n-- end\n\n-- local function _set_byte8(n)\n--     return strpack(\"<I8\", n)\n-- end\n\nlocal function _set_int8(n)\n    return strpack(\"<i8\", n)\nend\n\n-- local function _set_float(n)\n--     return strpack(\"<f\", n)\n-- end\n\nlocal function _set_double(n)\n    return strpack(\"<d\", n)\nend\n\nlocal function _from_cstring(data, i)\n    return strunpack(\"z\", data, i)\nend\n\n-- local function _dumphex(bytes)\n--     return strgsub(bytes, \".\",\n--         function(x)\n--             return strformat(\"%02x \", strbyte(x))\n--         end)\n-- end\n\nlocal function _compute_token(password, scramble)\n    if password == \"\" then\n        return \"\"\n    end\n    --_dumphex(scramble)\n\n    local stage1 = sha1(password)\n    --print(\"stage1:\", _dumphex(stage1) )\n    local stage2 = sha1(stage1)\n    local stage3 = sha1(scramble .. stage2)\n\n    local i = 0\n    return strgsub(stage3, \".\",\n        function(x)\n            i = i + 1\n            -- ~ is xor in lua 5.3\n            return strchar(strbyte(x) ~ strbyte(stage1, i))\n        end\n    )\nend\n\nlocal function _compose_packet(self, req)\n    self.packet_no = self.packet_no + 1\n    local size = #req\n    return strpack(\"<I3Bc\" .. size, size, self.packet_no, req)\nend\n\nlocal function _recv_packet(self, sock)\n    local data = sock:read(4)\n    if not data then\n        return nil, nil, \"failed to receive packet header: \"\n    end\n\n    local len, pos = _get_byte3(data, 1)\n    if len == 0 then\n        return nil, nil, \"empty packet\"\n    end\n\n    self.packet_no = strbyte(data, pos)\n\n    data = sock:read(len)\n    if not data then\n        return nil, nil, \"failed to read packet content: \"\n    end\n\n    local field_count = strbyte(data, 1)\n    local typ\n    if field_count == 0x00 then\n        typ = \"OK\"\n    elseif field_count == 0xff then\n        typ = \"ERR\"\n    elseif field_count == 0xfe then\n        typ = \"EOF\"\n    else\n        typ = \"DATA\"\n    end\n\n    return data, typ\nend\n\nlocal function _from_length_coded_bin(data, pos)\n    local first = strbyte(data, pos)\n\n    if not first then\n        return nil, pos\n    end\n\n    if first >= 0 and first <= 250 then\n        return first, pos + 1\n    end\n\n    if first == 251 then\n        return nil, pos + 1\n    end\n\n    if first == 252 then\n        pos = pos + 1\n        return _get_byte2(data, pos)\n    end\n\n    if first == 253 then\n        pos = pos + 1\n        return _get_byte3(data, pos)\n    end\n\n    if first == 254 then\n        pos = pos + 1\n        return _get_byte8(data, pos)\n    end\n\n    return false, pos + 1\nend\n\nlocal function _set_length_coded_bin(n)\n    if n < 251 then\n        return strchar(n)\n    end\n\n    if n < (1 << 16) then\n        return strpack(\"<BI2\", 0xfc, n)\n    end\n\n    if n < (1 << 24) then\n        return strpack(\"<BI3\", 0xfd, n)\n    end\n\n    return strpack(\"<BI8\", 0xfe, n)\nend\n\nlocal function _from_length_coded_str(data, pos)\n    local len\n    len, pos = _from_length_coded_bin(data, pos)\n    if len == nil then\n        return nil, pos\n    end\n    return sub(data, pos, pos + len - 1), pos + len\nend\n\nlocal function _parse_ok_packet(packet)\n    local res = {}\n    local pos\n\n    res.affected_rows, pos = _from_length_coded_bin(packet, 2)\n    res.insert_id, pos = _from_length_coded_bin(packet, pos)\n    res.server_status, pos = _get_byte2(packet, pos)\n    res.warning_count, pos = _get_byte2(packet, pos)\n\n    local message = sub(packet, pos)\n    if message and message ~= \"\" then\n        res.message = message\n    end\n    return res\nend\n\nlocal function _parse_eof_packet(packet)\n    local pos = 2\n    local warning_count, pos = _get_byte2(packet, pos)\n    local status_flags = _get_byte2(packet, pos)\n    return warning_count, status_flags\nend\n\nlocal function _parse_err_packet(packet)\n    local errno, pos = _get_byte2(packet, 2)\n    local marker = sub(packet, pos, pos)\n    local sqlstate\n    if marker == '#' then\n        -- with sqlstate\n        pos = pos + 1\n        sqlstate = sub(packet, pos, pos + 5 - 1)\n        pos = pos + 5\n    end\n    local message = sub(packet, pos)\n    return errno, message, sqlstate\nend\n\nlocal function _parse_result_set_header_packet(packet)\n    local field_count, pos = _from_length_coded_bin(packet, 1)\n    return field_count, _from_length_coded_bin(packet, pos)\nend\n\nlocal function _parse_field_packet(data)\n    local col = {}\n    local catalog, db, table, orig_table, orig_name, charsetnr, length\n    local pos\n\n    catalog, pos = _from_length_coded_str(data, 1)\n    db, pos = _from_length_coded_str(data, pos)\n    table, pos = _from_length_coded_str(data, pos)\n    orig_table, pos = _from_length_coded_str(data, pos)\n    col.name, pos = _from_length_coded_str(data, pos)\n    orig_name, pos = _from_length_coded_str(data, pos)\n    pos = pos + 1 -- ignore the filler\n    charsetnr, pos = _get_byte2(data, pos)\n    length, pos = _get_byte4(data, pos)\n    col.type = strbyte(data, pos)\n    pos = pos + 1\n    local flags, pos = _get_byte2(data, pos)\n    if flags & 0x20 == 0 then -- https://mariadb.com/kb/en/resultset/\n        col.is_signed = true\n    end\n\n    --[[\n    col.decimals = strbyte(data, pos)\n    pos = pos + 1\n    local default = sub(data, pos + 2)\n    if default and default ~= \"\" then\n        col.default = default\n    end\n    --]]\n    return col\nend\n\nlocal function _parse_row_data_packet(data, cols, compact)\n    local value, col, conv\n    local pos = 1\n    local ncols = #cols\n    local row = {}\n\n    for i = 1, ncols do\n        value, pos = _from_length_coded_str(data, pos)\n        col = cols[i]\n\n        if value ~= nil then\n            conv = converters[col.type]\n            if conv then\n                value = conv(value)\n            end\n        end\n\n        if compact then\n            row[i] = value\n        else\n            row[col.name] = value\n        end\n    end\n\n    return row\nend\n\nlocal function _recv_field_packet(self, sock)\n    local packet, typ, err = _recv_packet(self, sock)\n    if not packet then\n        return nil, err\n    end\n\n    if typ == \"ERR\" then\n        local errno, msg, sqlstate = _parse_err_packet(packet)\n        return nil, msg, errno, sqlstate\n    end\n\n    if typ ~= \"DATA\" then\n        return nil, \"bad field packet type: \" .. typ\n    end\n\n    -- typ == 'DATA'\n\n    return _parse_field_packet(packet)\nend\n\nlocal function _recv_decode_packet_resp(self)\n    return function(sock)\n        local packet, typ, err = _recv_packet(self, sock)\n        if not packet then\n            return false, \"failed to receive the result packet\" .. err\n        end\n\n        if typ == \"ERR\" then\n            local errno, msg, sqlstate = _parse_err_packet(packet)\n            return false, strformat(\"errno:%d, msg:%s,sqlstate:%s\", errno, msg, sqlstate)\n        end\n\n        if typ == \"EOF\" then\n            return false, \"old pre-4.1 authentication protocol not supported\"\n        end\n\n        return true, packet\n    end\nend\n\nlocal function _mysql_login(self, user, password, charset, database, on_connect)\n    return function(sockchannel)\n        local dispatch_resp = _recv_decode_packet_resp(self)\n        local packet = sockchannel:response(dispatch_resp)\n\n        self.protocol_ver = strbyte(packet)\n\n        local server_ver, pos = _from_cstring(packet, 2)\n        if not server_ver then\n            error \"bad handshake initialization packet: bad server version\"\n        end\n\n        self._server_ver = server_ver\n\n        local thread_id, pos = _get_byte4(packet, pos)\n        local scramble1 = sub(packet, pos, pos + 8 - 1)\n        if not scramble1 then\n            error \"1st part of scramble not found\"\n        end\n\n        pos = pos + 9 -- skip filler\n\n        -- two lower bytes\n        self._server_capabilities, pos = _get_byte2(packet, pos)\n        self._server_lang = strbyte(packet, pos)\n        pos = pos + 1\n        self._server_status, pos = _get_byte2(packet, pos)\n\n        local more_capabilities\n        more_capabilities, pos = _get_byte2(packet, pos)\n\n        self._server_capabilities = self._server_capabilities | more_capabilities << 16\n\n        local len = 21 - 8 - 1\n        pos = pos + 1 + 10\n\n        local scramble_part2 = sub(packet, pos, pos + len - 1)\n        if not scramble_part2 then\n            error \"2nd part of scramble not found\"\n        end\n\n        local scramble = scramble1 .. scramble_part2\n        local token = _compute_token(password, scramble)\n        local client_flags = 260047\n        local req = strpack(\"<I4I4c1c23zs1z\",\n            client_flags,\n            self._max_packet_size,\n            strchar(charset),\n            strrep(\"\\0\", 23),\n            user,\n            token,\n            database\n        )\n        local authpacket = _compose_packet(self, req)\n        sockchannel:request(authpacket, dispatch_resp)\n        if on_connect then\n            on_connect(self)\n        end\n    end\nend\n\n-- 构造ping数据包\nlocal function _compose_ping(self)\n    self.packet_no = -1\n    return _compose_packet(self, COM_PING)\nend\n\nlocal function _compose_query(self, query)\n    self.packet_no = -1\n    local cmd_packet = COM_QUERY .. query\n    return _compose_packet(self, cmd_packet)\nend\n\nlocal function _compose_stmt_prepare(self, query)\n    self.packet_no = -1\n    local cmd_packet = COM_STMT_PREPARE .. query\n    return _compose_packet(self, cmd_packet)\nend\n\n--参数字段类型转换\nlocal store_types = {\n    number = function(v)\n        if not tointeger(v) then\n            return _set_byte2(0x05), _set_double(v)\n        else\n            return _set_byte2(0x08), _set_int8(v)\n        end\n    end,\n    string = function(v)\n        return _set_byte2(0x0f), _set_length_coded_bin(#v) .. v\n    end,\n    --bool转换为0,1\n    boolean = function(v)\n        if v then\n            return _set_byte2(0x01), strchar(1)\n        else\n            return _set_byte2(0x01), strchar(0)\n        end\n    end\n}\n\nstore_types[\"nil\"] = function(v)\n    return _set_byte2(0x06), \"\"\nend\n\nlocal function _compose_stmt_execute(self, stmt, cursor_type, args)\n    local arg_num = args.n\n    if arg_num ~= stmt.param_count then\n        error(\"require stmt.param_count \" .. stmt.param_count .. \" get arg_num \" .. arg_num)\n    end\n\n    self.packet_no = -1\n\n    local cmd_packet = strpack(\"<c1I4BI4\", COM_STMT_EXECUTE, stmt.prepare_id, cursor_type, 0x01)\n    if arg_num > 0 then\n        local f, ts, vs\n        local types_buf = \"\"\n        local values_buf = \"\"\n        --生成NULL位图\n        local null_count = (arg_num + 7) // 8\n        local null_map = \"\"\n        local field_index = 1\n        for i = 1, null_count do\n            local byte = 0\n            for j = 0, 7 do\n                if field_index <= arg_num then\n                    if args[field_index] == nil then\n                        byte = byte | (1 << j)\n                    else\n                        byte = byte | (0 << j)\n                    end\n                end\n                field_index = field_index + 1\n            end\n            null_map = null_map .. strchar(byte)\n        end\n        for i = 1, arg_num do\n            local v = args[i]\n            f = store_types[type(v)]\n            if not f then\n                error(\"invalid parameter type \" .. type(v))\n            end\n            ts, vs = f(v)\n            types_buf = types_buf .. ts\n            values_buf = values_buf .. vs\n        end\n        cmd_packet = cmd_packet .. null_map .. strchar(0x01) .. types_buf .. values_buf\n    end\n\n    return _compose_packet(self, cmd_packet)\nend\n\nlocal function read_result(self, sock)\n    local packet, typ, err = _recv_packet(self, sock)\n    if not packet then\n        return nil, err\n        --error( err )\n    end\n\n    if typ == \"ERR\" then\n        local errno, msg, sqlstate = _parse_err_packet(packet)\n        return nil, msg, errno, sqlstate\n        --error( strformat(\"errno:%d, msg:%s,sqlstate:%s\",errno,msg,sqlstate))\n    end\n\n    if typ == \"OK\" then\n        local res = _parse_ok_packet(packet)\n        if res and res.server_status & SERVER_MORE_RESULTS_EXISTS ~= 0 then\n            return res, \"again\"\n        end\n        return res\n    end\n\n    if typ ~= \"DATA\" then\n        return nil, \"packet type \" .. typ .. \" not supported\"\n        --error( \"packet type \" .. typ .. \" not supported\" )\n    end\n\n    -- typ == 'DATA'\n\n    local field_count, extra = _parse_result_set_header_packet(packet)\n    local cols = {}\n    for i = 1, field_count do\n        local col, err, errno, sqlstate = _recv_field_packet(self, sock)\n        if not col then\n            return nil, err, errno, sqlstate\n            --error( strformat(\"errno:%d, msg:%s,sqlstate:%s\",errno,msg,sqlstate))\n        end\n        cols[i] = col\n    end\n\n    local packet, typ, err = _recv_packet(self, sock)\n    if not packet then\n        --error( err)\n        return nil, err\n    end\n\n    if typ ~= \"EOF\" then\n        --error ( \"unexpected packet type \" .. typ .. \" while eof packet is \".. \"expected\" )\n        return nil, \"unexpected packet type \" .. typ .. \" while eof packet is \" .. \"expected\"\n    end\n\n    -- typ == 'EOF'\n\n    local compact = self.compact\n    local rows = {}\n    local i = 0\n    while true do\n        packet, typ, err = _recv_packet(self, sock)\n        if not packet then\n            --error (err)\n            return nil, err\n        end\n\n        if typ == \"EOF\" then\n            local warning_count, status_flags = _parse_eof_packet(packet)\n            if status_flags & SERVER_MORE_RESULTS_EXISTS ~= 0 then\n                return rows, \"again\"\n            end\n            break\n        end\n\n        -- if typ ~= 'DATA' then\n        --     return nil, 'bad row packet type: ' .. typ\n        -- end\n\n        -- typ == 'DATA'\n\n        i = i + 1\n        rows[i] = _parse_row_data_packet(packet, cols, compact)\n    end\n\n    return rows\nend\n\nlocal function _query_resp(self)\n    return function(sock)\n        local res, err, errno, sqlstate = read_result(self, sock)\n        if not res then\n            local badresult = {}\n            badresult.badresult = true\n            badresult.err = err\n            badresult.errno = errno\n            badresult.sqlstate = sqlstate\n            return true, badresult\n        end\n        if err ~= \"again\" then\n            return true, res\n        end\n        local multiresultset = {res}\n        multiresultset.multiresultset = true\n        local i = 2\n        while err == \"again\" do\n            res, err, errno, sqlstate = read_result(self, sock)\n            if not res then\n                multiresultset.badresult = true\n                multiresultset.err = err\n                multiresultset.errno = errno\n                multiresultset.sqlstate = sqlstate\n                return true, multiresultset\n            end\n            multiresultset[i] = res\n            i = i + 1\n        end\n        return true, multiresultset\n    end\nend\n\nfunction _M.connect(opts)\n    local self = setmetatable({}, mt)\n\n    local max_packet_size = opts.max_packet_size\n    if not max_packet_size then\n        max_packet_size = 1024 * 1024 -- default 1 MB\n    end\n    self._max_packet_size = max_packet_size\n    self.compact = opts.compact_arrays\n\n    local database = opts.database or \"\"\n    local user = opts.user or \"\"\n    local password = opts.password or \"\"\n    local charset = CHARSET_MAP[opts.charset or \"_default\"]\n    local channel =\n        socketchannel.channel {\n        host = opts.host,\n        port = opts.port or 3306,\n        auth = _mysql_login(self, user, password, charset, database, opts.on_connect),\n        overload = opts.overload\n    }\n    self.sockchannel = channel\n    -- try connect first only once\n    channel:connect(true)\n\n    return self\nend\n\nfunction _M.disconnect(self)\n    self.sockchannel:close()\n    setmetatable(self, nil)\nend\n\nfunction _M.query(self, query)\n    local querypacket = _compose_query(self, query)\n    local sockchannel = self.sockchannel\n    if not self.query_resp then\n        self.query_resp = _query_resp(self)\n    end\n    return sockchannel:request(querypacket, self.query_resp)\nend\n\nlocal function read_prepare_result(self, sock)\n    local resp = {}\n    local packet, typ, err = _recv_packet(self, sock)\n    if not packet then\n        resp.badresult = true\n        resp.errno = 300101\n        resp.err = err\n        return false, resp\n    end\n\n    if typ == \"ERR\" then\n        local errno, msg, sqlstate = _parse_err_packet(packet)\n        resp.badresult = true\n        resp.errno = errno\n        resp.err = msg\n        resp.sqlstate = sqlstate\n        return true, resp\n    end\n\n    --第一节只能是OK\n    if typ ~= \"OK\" then\n        resp.badresult = true\n        resp.errno = 300201\n        resp.err = \"first typ must be OK,now\" .. typ\n        return false, resp\n    end\n    resp.prepare_id, resp.field_count, resp.param_count, resp.warning_count = strunpack(\"<I4I2I2xI2\", packet, 2)\n\n    resp.params = {}\n    resp.fields = {}\n\n    if resp.param_count > 0 then\n        local param = _recv_field_packet(self, sock)\n        while param do\n            table.insert(resp.params, param)\n            param = _recv_field_packet(self, sock)\n        end\n    end\n    if resp.field_count > 0 then\n        local field = _recv_field_packet(self, sock)\n        while field do\n            table.insert(resp.fields, field)\n            field = _recv_field_packet(self, sock)\n        end\n    end\n\n    return true, resp\nend\n\nlocal function _prepare_resp(self, sql)\n    return function(sock)\n        return read_prepare_result(self, sock)\n    end\nend\n\n-- 注册预处理语句\nfunction _M.prepare(self, sql)\n    local querypacket = _compose_stmt_prepare(self, sql)\n    local sockchannel = self.sockchannel\n    if not self.prepare_resp then\n        self.prepare_resp = _prepare_resp(self)\n    end\n    return sockchannel:request(querypacket, self.prepare_resp)\nend\n\nlocal function _get_datetime(data, pos)\n    local len, year, month, day, hour, minute, second\n    local value\n    len, pos = _from_length_coded_bin(data, pos)\n    if len == 7 then\n        year, month, day, hour, minute, second, pos = string.unpack(\"<I2BBBBB\", data, pos)\n        value = strformat(\"%04d-%02d-%02d %02d:%02d:%02d\", year, month, day, hour, minute, second)\n    elseif len == 4 then\n        year, month, day, pos = string.unpack(\"<I2BB\", data, pos)\n        value = strformat(\"%04d-%02d-%02d %02d:%02d:%02d\", year, month, day, 0, 0, 0)\n    else\n        value = \"2017-09-09 20:08:09\"\n        --unsupported format\n        pos = pos + len\n    end\n    return value, pos\nend\n\nlocal function _get_date(data, pos)\n    local len, year, month, day\n    local value\n    len, pos = _from_length_coded_bin(data, pos)\n    if len == 4 then\n        year, month, day, pos = string.unpack(\"<I2BB\", data, pos)\n        value = strformat(\"%04d-%02d-%02d\", year, month, day)\n    else\n        --unsupported format\n        error(\"_get_date()error,unsupported date format, len is \" .. len)\n    end\n    return value, pos\nend\n\n-- 字段类型参考 https://dev.mysql.com/doc/dev/mysql-server/8.0.12/binary__log__types_8h.html enum_field_types 枚举类型定义\nlocal _binary_parser = {\n    [0x01] = _get_int1,\n    [0x02] = _get_int2,\n    [0x03] = _get_int4,\n    [0x04] = _get_float,\n    [0x05] = _get_double,\n    [0x07] = _get_datetime,\n    [0x08] = _get_int8,\n    [0x09] = _get_int3,\n    [0x0a] = _get_date,\n    [0x0c] = _get_datetime,\n    [0x0f] = _from_length_coded_str,\n    [0x10] = _from_length_coded_str,\n    [0xf5] = _from_length_coded_str,\n    [0xf9] = _from_length_coded_str,\n    [0xfa] = _from_length_coded_str,\n    [0xfb] = _from_length_coded_str,\n    [0xfc] = _from_length_coded_str,\n    [0xfd] = _from_length_coded_str,\n    [0xfe] = _from_length_coded_str\n}\n\nlocal function _parse_row_data_binary(data, cols, compact)\n    local ncols = #cols\n    -- 空位图,前两个bit系统保留 (列数量 + 7 + 2) / 8\n    local null_count = (ncols + 9) // 8\n    local pos = 2 + null_count\n    local value\n\n    --空字段表\n    local null_fields = {}\n    local field_index = 1\n    local byte\n    for i = 2, pos - 1 do\n        byte = strbyte(data, i)\n        for j = 0, 7 do\n            if field_index > 2 then\n                if byte & (1 << j) == 0 then\n                    null_fields[field_index - 2] = false\n                else\n                    null_fields[field_index - 2] = true\n                end\n            end\n            field_index = field_index + 1\n        end\n    end\n\n    local row = {}\n    local parser\n    for i = 1, ncols do\n        local col = cols[i]\n        local typ = col.type\n        local name = col.name\n        if not null_fields[i] then\n            parser = _binary_parser[typ]\n            if not parser then\n                error(\"_parse_row_data_binary()error,unsupported field type \" .. typ)\n            end\n            value, pos = parser(data, pos, col.is_signed)\n            if compact then\n                row[i] = value\n            else\n                row[name] = value\n            end\n        end\n    end\n\n    return row\nend\n\nlocal function read_execute_result(self, sock)\n    local packet, typ, err = _recv_packet(self, sock)\n    if not packet then\n        return nil, err\n        --error( err )\n    end\n\n    if typ == \"ERR\" then\n        local errno, msg, sqlstate = _parse_err_packet(packet)\n        return nil, msg, errno, sqlstate\n        --error( strformat(\"errno:%d, msg:%s,sqlstate:%s\",errno,msg,sqlstate))\n    end\n\n    if typ == \"OK\" then\n        local res = _parse_ok_packet(packet)\n        if res and res.server_status & SERVER_MORE_RESULTS_EXISTS ~= 0 then\n            return res, \"again\"\n        end\n        return res\n    end\n\n    if typ ~= \"DATA\" then\n        return nil, \"packet type \" .. typ .. \" not supported\"\n        --error( \"packet type \" .. typ .. \" not supported\" )\n    end\n\n    -- typ == 'DATA'\n\n    -- local field_count, extra = _parse_result_set_header_packet(packet)\n\n    local cols = {}\n    local col\n    while true do\n        packet, typ, err = _recv_packet(self, sock)\n        if typ == \"EOF\" then\n            local warning_count, status_flags = _parse_eof_packet(packet)\n            break\n        end\n        col = _parse_field_packet(packet)\n        if not col then\n            break\n            --error( strformat(\"errno:%d, msg:%s,sqlstate:%s\",errno,msg,sqlstate))\n        end\n        table.insert(cols, col)\n    end\n\n    --没有记录集返回\n    if #cols < 1 then\n        return {}\n    end\n\n    local compact = self.compact\n    local rows = {}\n    local row\n    while true do\n        packet, typ, err = _recv_packet(self, sock)\n        if typ == \"EOF\" then\n            local warning_count, status_flags = _parse_eof_packet(packet)\n            if status_flags & SERVER_MORE_RESULTS_EXISTS ~= 0 then\n                return rows, \"again\"\n            end\n            break\n        end\n        row = _parse_row_data_binary(packet, cols, compact)\n        if not col then\n            break\n        end\n        table.insert(rows, row)\n    end\n\n    return rows\nend\n\nlocal function _execute_resp(self)\n    return function(sock)\n        local res, err, errno, sqlstate = read_execute_result(self, sock)\n        if not res then\n            local badresult = {}\n            badresult.badresult = true\n            badresult.err = err\n            badresult.errno = errno\n            badresult.sqlstate = sqlstate\n            return true, badresult\n        end\n        if err ~= \"again\" then\n            return true, res\n        end\n        local mulitresultset = {res}\n        mulitresultset.mulitresultset = true\n        local i = 2\n        while err == \"again\" do\n            res, err, errno, sqlstate = read_execute_result(self, sock)\n            if not res then\n                mulitresultset.badresult = true\n                mulitresultset.err = err\n                mulitresultset.errno = errno\n                mulitresultset.sqlstate = sqlstate\n                return true, mulitresultset\n            end\n            mulitresultset[i] = res\n            i = i + 1\n        end\n        return true, mulitresultset\n    end\nend\n\n--[[\n    执行预处理语句\n    失败返回字段\n        errno\n        badresult\n        sqlstate\n        err\n]]\nfunction _M.execute(self, stmt, ...)\n    local querypacket, er = _compose_stmt_execute(self, stmt, CURSOR_TYPE_NO_CURSOR, table.pack(...))\n    if not querypacket then\n        return {\n            badresult = true,\n            errno = 30902,\n            err = er\n        }\n    end\n    local sockchannel = self.sockchannel\n    if not self.execute_resp then\n        self.execute_resp = _execute_resp(self)\n    end\n    return sockchannel:request(querypacket, self.execute_resp)\nend\n\nlocal function _compose_stmt_reset(self, stmt)\n    self.packet_no = -1\n\n    local cmd_packet = strpack(\"c1<I4\", COM_STMT_RESET, stmt.prepare_id)\n    return _compose_packet(self, cmd_packet)\nend\n\n--重置预处理句柄\nfunction _M.stmt_reset(self, stmt)\n    local querypacket = _compose_stmt_reset(self, stmt)\n    local sockchannel = self.sockchannel\n        if not self.query_resp then\n        self.query_resp = _query_resp(self)\n    end\n    return sockchannel:request(querypacket, self.query_resp)\nend\n\nlocal function _compose_stmt_close(self, stmt)\n    self.packet_no = -1\n\n    local cmd_packet = strpack(\"c1<I4\", COM_STMT_CLOSE, stmt.prepare_id)\n    return _compose_packet(self, cmd_packet)\nend\n\n--关闭预处理句柄\nfunction _M.stmt_close(self, stmt)\n    local querypacket = _compose_stmt_close(self, stmt)\n    local sockchannel = self.sockchannel\n    return sockchannel:request(querypacket)\nend\n\n\nfunction _M.ping(self)\n    local querypacket, er = _compose_ping(self)\n    if not querypacket then\n        return {\n            badresult = true,\n            errno = 30902,\n            err = er\n        }\n    end\n    local sockchannel = self.sockchannel\n    if not self.query_resp then\n        self.query_resp = _query_resp(self)\n    end\n    return sockchannel:request(querypacket, self.query_resp)\nend\n\nfunction _M.server_ver(self)\n    return self._server_ver\nend\n\nlocal escape_map = {\n    ['\\0'] = \"\\\\0\",\n    ['\\b'] = \"\\\\b\",\n    ['\\n'] = \"\\\\n\",\n    ['\\r'] = \"\\\\r\",\n    ['\\t'] = \"\\\\t\",\n    ['\\26'] = \"\\\\Z\",\n    ['\\\\'] = \"\\\\\\\\\",\n    [\"'\"] = \"\\\\'\",\n    ['\"'] = '\\\\\"',\n}\n\nfunction _M.quote_sql_str( str)\n    return strformat(\"'%s'\", strgsub(str, \"[\\0\\b\\n\\r\\t\\26\\\\\\'\\\"]\", escape_map))\nend\n\nfunction _M.set_compact_arrays(self, value)\n    self.compact = value\nend\n\nreturn _M\n"
  },
  {
    "path": "lualib/skynet/db/redis/cluster.lua",
    "content": "-- a simple redis-cluster client\n-- rewrite from https://github.com/antirez/redis-rb-cluster\n\nlocal skynet = require \"skynet\"\nlocal redis = require \"skynet.db.redis\"\nlocal crc16 = require \"skynet.db.redis.crc16\"\n\nlocal RedisClusterHashSlots = 16384\nlocal RedisClusterRequestTTL = 16\n\nlocal sync = {\n\tonce = {\n\t\ttasks = {},\n\t}\n}\n\nfunction sync.once.Do(id,func,...)\n\tlocal tasks = sync.once.tasks\n\tlocal task = tasks[id]\n\tif not task then\n\t\ttask = {\n\t\t\twaiting = {},\n\t\t\tresult = nil,\n\t\t}\n\t\ttasks[id] = task\n\t\tlocal rettbl = table.pack(xpcall(func,debug.traceback,...))\n\t\ttask.result = rettbl\n\t\tlocal waiting = task.waiting\n\t\ttasks[id] = nil\n\t\tif next(waiting) then\n\t\t\tfor i,co in ipairs(waiting) do\n\t\t\t\tskynet.wakeup(co)\n\t\t\tend\n\t\tend\n\t\treturn table.unpack(task.result,1,task.result.n)\n\telse\n\t\tlocal co = coroutine.running()\n\t\ttable.insert(task.waiting,co)\n\t\tskynet.wait(co)\n\t\treturn table.unpack(task.result,1,task.result.n)\n\tend\nend\n\n\nlocal _M = {}\n\nlocal rediscluster = {}\nrediscluster.__index = rediscluster\n\nfunction _M.new(startup_nodes,opt,onmessage)\n\tif #startup_nodes == 0 then\n\t\tstartup_nodes = {startup_nodes,}\n\tend\n\topt = opt or {}\n\tlocal self = {\n\t\tstartup_nodes = startup_nodes,\n\t\tmax_connections = opt.max_connections or 256,\n\t\tconnections = {},\n\t\topt = opt,\n\t\trefresh_table_asap = false,\n\n\t\t-- for subscribe/publish\n\t\t__onmessage = onmessage,\n\t\t__watching = {},\n\t}\n\tsetmetatable(self,rediscluster)\n\tself:initialize_slots_cache()\n\treturn self\nend\n\nlocal function nodename(node)\n\treturn string.format(\"%s:%d\",node.host,node.port)\nend\n\nfunction rediscluster:get_redis_link(node)\n\tlocal conf = {\n\t\thost = node.host,\n\t\tport = node.port,\n\t\tauth = self.opt.auth,\n\t\tdb = self.opt.db or 0,\n\t}\n\treturn redis.connect(conf)\nend\n \n-- Given a node (that is just a Ruby hash) give it a name just\n-- concatenating the host and port. We use the node name as a key\n-- to cache connections to that node.\nfunction rediscluster:set_node_name(node)\n\tif not node.name then\n\t\tnode.name = nodename(node)\n\tend\nend\n\n-- Contact the startup nodes and try to fetch the hash slots -> instances\n-- map in order to initialize the @slots hash.\nfunction rediscluster:initialize_slots_cache()\n\tself.slots = {}\n\tself.nodes = {}\n\tfor _,startup_node in ipairs(self.startup_nodes) do\n\t\tlocal ok = pcall(function ()\n\t\t\tlocal conn = self:get_connection(startup_node)\n\t\t\tlocal list = conn:cluster(\"slots\")\n\t\t\tfor _,result in ipairs(list) do\n\t\t\t\tlocal ip,port = table.unpack(result[3])\n\t\t\t\tassert(ip)\n\t\t\t\tport = assert(tonumber(port))\n\t\t\t\tlocal master_node = {\n\t\t\t\t\thost = ip,\n\t\t\t\t\tport = port,\n\t\t\t\t\tslaves = {},\n\t\t\t\t}\n\t\t\t\tself:set_node_name(master_node)\n\t\t\t\tfor i=4,#result do\n\t\t\t\t\tlocal ip,port = table.unpack(result[i])\n\t\t\t\t\tassert(ip)\n\t\t\t\t\tport = assert(tonumber(port))\n\t\t\t\t\tlocal slave_node = {\n\t\t\t\t\t\thost = ip,\n\t\t\t\t\t\tport = port,\n\t\t\t\t\t}\n\t\t\t\t\tself:set_node_name(slave_node)\n\t\t\t\t\ttable.insert(master_node.slaves,slave_node)\n\t\t\t\tend\n\t\t\t\ttable.insert(self.nodes,master_node)\n\t\t\t\tfor slot=tonumber(result[1]),tonumber(result[2]) do\n\t\t\t\t\tself.slots[slot] = master_node\n\t\t\t\tend\n\t\t\tend\n\t\t\tself.refresh_table_asap = false\n\t\tend)\n\t\t-- Exit the loop as long as the first node replies\n\t\tif ok then\n\t\t\tbreak\n\t\tend\n\tend\nend\n\n-- Flush the cache, mostly useful for debugging when we want to force\n-- redirection.\nfunction rediscluster:flush_slots_cache()\n\tself.slots = {}\nend\n\n-- Return the hash slot from the key.\nfunction rediscluster:keyslot(key)\n\t-- Only hash what is inside {...} if there is such a pattern in the key.\n\t-- Note that the specification requires the content that is between\n\t-- the first { and the first } after the first {. If we found {} without\n\t-- nothing in the middle, the whole key is hashed as usually.\n\tlocal startpos = string.find(key,\"{\",1,true)\n\tif startpos then\n\t\tlocal endpos = string.find(key,\"}\",startpos+1,true)\n\t\tif endpos and endpos ~= startpos + 1 then\n\t\t\tkey = string.sub(key,startpos+1,endpos-1)\n\t\tend\n\tend\n\treturn crc16(key) % RedisClusterHashSlots\nend\n\n-- Return the first key in the command arguments.\n--\n-- Currently we just return argv[1], that is, the first argument\n-- after the command name.\n--\n-- This is indeed the key for most commands, and when it is not true\n-- the cluster redirection will point us to the right node anyway.\n--\n-- For commands we want to explicitly bad as they don't make sense\n-- in the context of cluster, nil is returned.\nfunction rediscluster:get_key_from_command(cmd, argv)\n\tlocal key = argv[2] -- argv[1] is cmd\n\tif cmd == \"info\" or\n\t\tcmd == \"multi\" or\n\t\tcmd == \"exec\" or\n\t\tcmd == \"slaveof\" or\n\t\tcmd == \"config\" or\n\t\tcmd == \"shutdown\" then\n\t\treturn nil\n\tend\n\tif cmd == \"eval\" or cmd == \"evalsha\" then\n\t\t-- eval script numkeys key [key...] arg [arg...]\n\t\tlocal numkeys = argv[3]\n\t\tlocal firstkey_slot = nil\n\t\tfor i=4,4+numkeys-1 do\n\t\t\tlocal slot = self:keyslot(argv[i])\n\t\t\tif not firstkey_slot then\n\t\t\t\tfirstkey_slot = slot\n\t\t\telseif firstkey_slot ~= slot then\n\t\t\t\terror(string.format(\"%s - all keys must map to the same key slot\",cmd))\n\t\t\tend\n\t\tend\n\t\t-- numkeys <=0 will return nil\n\t\treturn argv[4]\n\tend\n\t-- Unknown commands, and all the commands having the key\n\t-- as first argument are handled here:\n\t-- set, get, ...\n\treturn key\nend\n\n-- If the current number of connections is already the maximum number\n-- allowed, close a random connection. This should be called every time\n-- we cache a new connection in the @connections hash.\nfunction rediscluster:close_existing_connection()\n\tlocal length = 0\n\tfor name,conn in pairs(self.connections) do\n\t\tlength = length + 1\n\tend\n\tif length >= self.max_connections then\n\t\tpcall(function ()\n\t\t\tlocal name,conn = next(self.connections)\n\t\t\tself.connections[name] = nil\n\t\t\tconn:disconnect()\n\t\tend)\n\tend\nend\n\nfunction rediscluster:close_all_connection()\n\tlocal connections = self.connections\n\tself.connections = {}\n\tfor name,conn in pairs(connections) do\n\t\tpcall(conn.disconnect,conn)\n\tend\nend\n\nfunction rediscluster:get_connection(node)\n\tif not node.name then\n\t\tnode.name = nodename(node)\n\tend\n\tlocal name = node.name\n\tlocal ok,conn = sync.once.Do(name,function ()\n\t\tlocal conn = self.connections[name]\n\t\tif not conn then\n\t\t\tself:close_existing_connection()\n\t\t\tconn = self:get_redis_link(node)\n\t\t\tself.connections[name] = conn\n\t\tend\n\t\treturn conn\n\tend)\n\tassert(ok,conn)\n\treturn conn\nend\n\n-- Return a link to a random node, or raise an error if no node can be\n-- contacted. This function is only called when we can't reach the node\n-- associated with a given hash slot, or when we don't know the right\n-- mapping.\n-- The function will try to get a successful reply to the PING command,\n-- otherwise the next node is tried.\nfunction rediscluster:get_random_connection()\n\t-- shuffle\n\tlocal shuffle_idx = {}\n\tlocal startpos = 1\n\tlocal endpos = #self.nodes\n\tfor i=startpos,endpos do\n\t\tshuffle_idx[i] = i\n\tend\n\tfor i=startpos,endpos do\n\t\tlocal idx = math.random(i,endpos)\n\t\tlocal tmp = shuffle_idx[i]\n\t\tshuffle_idx[i] = shuffle_idx[idx]\n\t\tshuffle_idx[idx] = tmp\n\tend\n\tfor i,idx in ipairs(shuffle_idx) do\n\t\tlocal ok,conn = pcall(function ()\n\t\t\tlocal node = self.nodes[idx]\n\t\t\tlocal conn = self:get_connection(node)\n\t\t\tif conn:ping() == \"PONG\" then\n\t\t\t\treturn conn\n\t\t\telse\n\t\t\t\t-- If the connection is not good close it ASAP in order\n\t\t\t\t-- to avoid waiting for the GC finalizer. File\n\t\t\t\t-- descriptors are a rare resource.\n\t\t\t\tself.connections[node.name] = nil\n\t\t\t\tconn:disconnect()\n\t\t\tend\n\t\tend)\n\t\tif ok and conn then\n\t\t\treturn conn\n\t\tend\n\tend\n\terror(\"Can't reach a single startup node.\")\nend\n\n-- Given a slot return the link (Redis instance) to the mapped node.\n-- Make sure to create a connection with the node if we don't have\n-- one.\nfunction rediscluster:get_connection_by_slot(slot)\n\tlocal node = self.slots[slot]\n\t-- If we don't know what the mapping is, return a random node.\n\tif not node then\n\t\treturn self:get_random_connection()\n\tend\n\tlocal ok,conn = pcall(self.get_connection,self,node)\n\tif not ok then\n\t\tif self.opt.read_slave and node.slaves and #node.slaves > 0 then\n\t\t\tlocal slave_node = node.slaves[math.random(1,#node.slaves)]\n\t\t\tlocal ok2,conn = pcall(self.get_connection,self,slave_node)\n\t\t\tif ok2 then\n\t\t\t\tconn:readonly()\t\t-- allow this connection read-slave\n\t\t\t\treturn conn\n\t\t\tend\n\t\tend\n\t\t-- This will probably never happen with recent redis-rb\n\t\t-- versions because the connection is enstablished in a lazy\n\t\t-- way only when a command is called. However it is wise to\n\t\t-- handle an instance creation error of some kind.\n\t\treturn self:get_random_connection()\n\tend\n\treturn conn\nend\n\n-- Dispatch commands.\nfunction rediscluster:call(...)\n\tlocal argv = table.pack(...)\n\tlocal cmd = string.lower(argv[1])\n\tlocal key = self:get_key_from_command(cmd, argv)\n\tif not key then\n\t\terror(\"No way to dispatch this command to Redis Cluster: \" .. tostring(argv[1]))\n\tend\n\tif cmd == \"subscribe\" or cmd == \"unsubscribe\" or cmd == \"psubscribe\" or cmd == \"punsubscribe\" then\n\t\tlocal slot = self:keyslot(key)\n\t\tlocal conn = self:get_watch_connection_by_slot(slot)\n\t\tlocal func = conn[cmd]\n\t\treturn func(conn,table.unpack(argv,2))\n\tend\n\n\tif self.refresh_table_asap then\n\t\tself:initialize_slots_cache()\n\tend\n\tlocal ttl = RedisClusterRequestTTL\t-- Max number of redirections\n\tlocal err\n\tlocal asking = false\n\tlocal try_random_node = false\n\twhile ttl > 0 do\n\t\tttl = ttl - 1\n\t\tlocal conn\n\t\tlocal slot = self:keyslot(key)\n\t\tif asking then\n\t\t\tconn = self:get_connection(asking)\n\t\telseif try_random_node then\n\t\t\tconn = self:get_random_connection()\n\t\t\ttry_random_node = false\n\t\telse\n\t\t\tconn = self:get_connection_by_slot(slot)\n\t\tend\n\n\t\tlocal result\n\t\tif asking then\n\t\t\t-- use pipeline\n\t\t\t-- ensure ASKING and command execute sequentially and consecutively\n\t\t\t-- save one RTT\n\t\t\tlocal cmd_list = {\n\t\t\t\t{ \"asking\" },\n\t\t\t\t{ ... },\n\t\t\t}\n\t\t\tasking = false\n\t\t\tlocal func = conn[\"pipeline\"]\n\t\t\tresult = { pcall(func, conn, cmd_list) }\n\t\telse\n\t\t\tlocal func = conn[cmd]\n\t\t\tresult = { pcall(func, conn, table.unpack(argv, 2)) }\n\t\tend\n\n\t\tlocal ok = result[1]\n\t\tif not ok then\n\t\t\terr = table.unpack(result,2)\n\t\t\terr = tostring(err)\n\t\t\tif err == \"[Error: socket]\" then\n\t\t\t\t-- may be never come here?\n\t\t\t\ttry_random_node = true\n\t\t\t\tif ttl < RedisClusterRequestTTL/2 then\n\t\t\t\t\tskynet.sleep(10)\n\t\t\t\tend\n\t\t\telse\n\t\t\t\t-- err: ./lualib/skynet/socketchannel.lua:371: xxx\n\t\t\t\terr = string.match(err,\".+:%d+:%s(.*)$\") or err\n\t\t\t\tlocal errlist = {}\n\t\t\t\tfor e in string.gmatch(err,\"([^%s]+)%s?\") do\n\t\t\t\t\ttable.insert(errlist,e)\n\t\t\t\tend\n\t\t\t\tif (errlist[1] ~= \"MOVED\" and errlist[1] ~= \"ASK\") then\n\t\t\t\t\terror(err)\n\t\t\t\telse\n\t\t\t\t\tif errlist[1] == \"ASK\" then\n\t\t\t\t\t\tasking = true\n\t\t\t\t\telse\n\t\t\t\t\t\t-- Serve replied with MOVED. It's better for us to\n\t\t\t\t\t\t-- ask for CLUSTER SLOTS the next time.\n\t\t\t\t\t\tself.refresh_table_asap = true\n\t\t\t\t\tend\n\t\t\t\t\tlocal newslot = tonumber(errlist[2])\n\t\t\t\t\tlocal node_ip,node_port = string.match(errlist[3],\"^([^:]+):([^:]+)$\")\n\t\t\t\t\tnode_port = assert(tonumber(node_port))\n\t\t\t\t\tlocal node = {\n\t\t\t\t\t\thost = node_ip,\n\t\t\t\t\t\tport = node_port,\n\t\t\t\t\t}\n\t\t\t\t\tif not asking then\n\t\t\t\t\t\tlocal oldnode = self.slots[newslot]\n\t\t\t\t\t\tif oldnode then\n\t\t\t\t\t\t\tnode.slaves = oldnode.slaves\n\t\t\t\t\t\tend\n\t\t\t\t\t\tself:set_node_name(node)\n\t\t\t\t\t\tself.slots[newslot] = node\n\t\t\t\t\telse\n\t\t\t\t\t\tasking = node\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\treturn table.unpack(result,2)\n\t\tend\n\tend\n\terror(string.format(\"Too many Cluster redirections?,maybe node is disconnected (last error: %q)\",err))\nend\n\nfunction rediscluster:get_watch_connection_by_slot(slot)\n\tif not self.slots[slot] then\n\t\tself:initialize_slots_cache()\n\tend\n\tlocal node = assert(self.slots[slot])\n\treturn self:get_watch_connection(node)\nend\n\nfunction rediscluster:get_watch_connection(node)\n\tlocal name = node.name\n\tlocal ok,conn = sync.once.Do(name,function ()\n\t\tif not self.__watching[name] then\n\t\t\tlocal conf = {\n\t\t\t\thost = node.host,\n\t\t\t\tport = node.port,\n\t\t\t\tauth = self.opt.auth,\n\t\t\t\tdb = self.opt.db or 0,\n\t\t\t}\n\t\t\tlocal db = redis.watch(conf)\n\t\t\tself.__watching[name] = db\n\t\t\tlocal onmessage = rawget(self,\"__onmessage\")\n\t\t\tskynet.fork(function ()\n\t\t\t\twhile true do\n\t\t\t\t\tlocal ok,data,channel,pchannel = pcall(db.message,db)\n\t\t\t\t\tif ok then\n\t\t\t\t\t\tif data and onmessage then\n\t\t\t\t\t\t\tpcall(onmessage,data,channel,pchannel)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend)\n\t\tend\n\t\treturn self.__watching[name]\n\tend)\n\tassert(ok,conn)\n\treturn conn\nend\n\n-- Currently we handle all the commands using method_missing for\n-- simplicity. For a Cluster client actually it will be better to have\n-- every single command as a method with the right arity and possibly\n-- additional checks (example: RPOPLPUSH with same src/dst key, SORT\n-- without GET or BY, and so forth).\nsetmetatable(rediscluster,{\n\t__index = function (t,cmd)\n\t\tt[cmd] = function (self,...)\n\t\t\treturn self:call(cmd,...)\n\t\tend\n\t\treturn t[cmd]\n\tend,\n})\n\nreturn _M\n"
  },
  {
    "path": "lualib/skynet/db/redis/crc16.lua",
    "content": "--/*\n-- This is the CRC16 algorithm used by Redis Cluster to hash keys.\n-- Implementation according to CCITT standards.\n--\n-- This is actually the XMODEM CRC 16 algorithm, using the\n-- following parameters:\n--\n-- Name                       : \"XMODEM\", also known as \"ZMODEM\", \"CRC-16/ACORN\"\n-- Width                      : 16 bit\n-- Poly                       : 1021 (That is actually x^16 + x^12 + x^5 + 1)\n-- Initialization             : 0000\n-- Reflect Input byte         : False\n-- Reflect Output CRC         : False\n-- Xor constant to output CRC : 0000\n-- Output for \"123456789\"     : 31C3\n--*/\n\n\n\nlocal XMODEMCRC16Lookup = {\n\t0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,\n\t0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,\n\t0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,\n\t0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,\n\t0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,\n\t0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,\n\t0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,\n\t0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,\n\t0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,\n\t0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,\n\t0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,\n\t0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,\n\t0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,\n\t0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,\n\t0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,\n\t0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,\n\t0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,\n\t0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,\n\t0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,\n\t0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,\n\t0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,\n\t0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,\n\t0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,\n\t0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,\n\t0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,\n\t0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,\n\t0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,\n\t0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,\n\t0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,\n\t0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,\n\t0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,\n\t0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0\n}\n\nreturn function(bytes)\n\tlocal crc = 0\n\tfor i=1,#bytes do\n\t\tlocal b = string.byte(bytes,i,i)\n\t\tcrc = ((crc<<8) & 0xffff) ~ XMODEMCRC16Lookup[(((crc>>8)~b) & 0xff) + 1]\n\tend\n\treturn tonumber(crc)\nend\n"
  },
  {
    "path": "lualib/skynet/db/redis.lua",
    "content": "local socketchannel = require \"skynet.socketchannel\"\n\nlocal tostring = tostring\nlocal tonumber = tonumber\nlocal table = table\nlocal string = string\nlocal assert = assert\nlocal setmetatable = setmetatable\nlocal ipairs = ipairs\nlocal type = type\nlocal select = select\nlocal pairs = pairs\n\n\nlocal redis = {}\nlocal command = {}\nlocal meta = {\n\t__index = command,\n\t-- DO NOT close channel in __gc\n}\n\n---------- redis response\nlocal redcmd = {}\n\nredcmd[36] = function(fd, data) -- '$'\n\tlocal bytes = tonumber(data)\n\tif bytes < 0 then\n\t\treturn true,nil\n\tend\n\tlocal firstline = fd:read(bytes+2)\n\treturn true,string.sub(firstline,1,-3)\nend\n\nredcmd[43] = function(fd, data) -- '+'\n\treturn true,data\nend\n\nredcmd[45] = function(fd, data) -- '-'\n\treturn false,data\nend\n\nredcmd[58] = function(fd, data) -- ':'\n\t-- todo: return string later\n\treturn true, tonumber(data)\nend\n\nlocal function read_response(fd)\n\tlocal result = fd:readline \"\\r\\n\"\n\tlocal firstchar = string.byte(result)\n\tlocal data = string.sub(result,2)\n\treturn redcmd[firstchar](fd,data)\nend\n\nredcmd[42] = function(fd, data)\t-- '*'\n\tlocal n = tonumber(data)\n\tif n < 0 then\n\t\treturn true, nil\n\tend\n\tlocal bulk = {}\n\tlocal noerr = true\n\tfor i = 1,n do\n\t\tlocal ok, v = read_response(fd)\n\t\tif not ok then\n\t\t\tnoerr = false\n\t\tend\n\t\tbulk[i] = v\n\tend\n\treturn noerr, bulk\nend\n\n-------------------\n\nfunction command:disconnect()\n\tself[1]:close()\n\tsetmetatable(self, nil)\nend\n\n-- msg could be any type of value\n\nlocal function make_cache(f)\n\treturn setmetatable({}, {\n\t\t__mode = \"kv\",\n\t\t__index = f,\n\t})\nend\n\nlocal header_cache = make_cache(function(t,k)\n\t\tlocal s = \"\\r\\n$\" .. k .. \"\\r\\n\"\n\t\tt[k] = s\n\t\treturn s\n\tend)\n\nlocal command_cache = make_cache(function(t,cmd)\n\t\tlocal s = \"\\r\\n$\"..#cmd..\"\\r\\n\"..cmd:upper()\n\t\tt[cmd] = s\n\t\treturn s\n\tend)\n\nlocal count_cache = make_cache(function(t,k)\n\t\tlocal s = \"*\" .. k\n\t\tt[k] = s\n\t\treturn s\n\tend)\n\nlocal command_np_cache = make_cache(function(t, cmd)\n\t\tlocal s = \"*1\" .. command_cache[cmd] .. \"\\r\\n\"\n\t\tt[cmd] = s\n\t\treturn s\n\tend)\n\nlocal function compose_message(cmd, msg)\n\tif msg == nil then\n\t\treturn command_np_cache[cmd]\n\tend\n\n\tlocal t = type(msg)\n\tlocal lines = {}\n\n\tif t == \"table\" then\n\t\tlocal n = msg.n or #msg\n\t\tlines[1] = count_cache[n+1]\n\t\tlines[2] = command_cache[cmd]\n\t\tlocal idx = 3\n\t\tfor i = 1, n do\n\t\t\tlocal v = msg[i]\n\t\t\tif v == nil then\n\t\t\t\tlines[idx] = \"\\r\\n$-1\"\n\t\t\t\tidx = idx + 1\n\t\t\telse\n\t\t\t\tv= tostring(v)\n\t\t\t\tlines[idx] = header_cache[#v]\n\t\t\t\tlines[idx+1] = v\n\t\t\t\tidx = idx + 2\n\t\t\tend\n\t\tend\n\t\tlines[idx] = \"\\r\\n\"\n\telse\n\t\tmsg = tostring(msg)\n\t\tlines[1] = \"*2\"\n\t\tlines[2] = command_cache[cmd]\n\t\tlines[3] = header_cache[#msg]\n\t\tlines[4] = msg\n\t\tlines[5] = \"\\r\\n\"\n\tend\n\n\treturn lines\nend\n\nlocal function redis_login(conf)\n\tlocal auth = conf.auth\n\tlocal db = conf.db\n\tif auth == nil and db == nil then\n\t\treturn\n\tend\n\tif auth then\n\t\tif conf.username then\n\t\t\tauth = { conf.username, auth }\n\t\tend\n\tend\n\treturn function(so)\n\t\tif auth then\n\t\t\tso:request(compose_message(\"AUTH\", auth), read_response)\n\t\tend\n\t\tif db then\n\t\t\tso:request(compose_message(\"SELECT\", db), read_response)\n\t\tend\n\tend\nend\n\nfunction redis.connect(db_conf)\n\tlocal channel = socketchannel.channel {\n\t\thost = db_conf.host,\n\t\tport = db_conf.port or 6379,\n\t\tauth = redis_login(db_conf),\n\t\tnodelay = true,\n\t\toverload = db_conf.overload,\n\t}\n\t-- try connect first only once\n\tchannel:connect(true)\n\treturn setmetatable( { channel }, meta )\nend\n\nsetmetatable(command, { __index = function(t,k)\n\tlocal cmd = string.upper(k)\n\tlocal f = function (self, v, ...)\n\t\tif v == nil then\n\t\t\treturn self[1]:request(compose_message(cmd), read_response)\n\t\telseif type(v) == \"table\" then\n\t\t\treturn self[1]:request(compose_message(cmd, v), read_response)\n\t\telse\n\t\t\treturn self[1]:request(compose_message(cmd, table.pack(v, ...)), read_response)\n\t\tend\n\tend\n\tt[k] = f\n\treturn f\nend})\n\nlocal function read_boolean(so)\n\tlocal ok, result = read_response(so)\n\treturn ok, result ~= 0\nend\n\nfunction command:exists(key)\n\tlocal fd = self[1]\n\treturn fd:request(compose_message (\"EXISTS\", key), read_boolean)\nend\n\nfunction command:sismember(key, value)\n\tlocal fd = self[1]\n\treturn fd:request(compose_message (\"SISMEMBER\", table.pack(key, value)), read_boolean)\nend\n\nlocal function compose_table(lines, msg)\n\tlocal tinsert = table.insert\n\ttinsert(lines, count_cache[#msg])\n\tlocal val\n\tfor _,v in ipairs(msg) do\n\t\tval = tostring(v)\n\t\ttinsert(lines,header_cache[#val])\n\t\ttinsert(lines,val)\n\tend\n\ttinsert(lines, \"\\r\\n\")\n\treturn lines\nend\n\nfunction command:pipeline(ops,resp)\n\tassert(ops and #ops > 0, \"pipeline is null\")\n\n\tlocal fd = self[1]\n\n\tlocal cmds = {}\n\tfor _, cmd in ipairs(ops) do\n\t\tcompose_table(cmds, cmd)\n\tend\n\n\tif resp then\n\t\treturn fd:request(cmds, function (fd)\n\t\t\tfor _=1, #ops do\n\t\t\t\tlocal ok, out = read_response(fd)\n\t\t\t\ttable.insert(resp, {ok = ok, out = out})\n\t\t\tend\n\t\t\treturn true, resp\n\t\tend)\n\telse\n\t\treturn fd:request(cmds, function (fd)\n\t\t\tlocal ok, out\n\t\t\tfor _=1, #ops do\n\t\t\t\tok, out = read_response(fd)\n\t\t\tend\n\t\t\t-- return last response\n\t\t\treturn ok,out\n\t\tend)\n\tend\nend\n\n--- watch mode\n\nlocal watch = {}\n\nlocal watchmeta = {\n\t__index = watch,\n\t__gc = function(self)\n\t\tself.__sock:close()\n\tend,\n}\n\nlocal function watch_login(conf, obj)\n\tlocal login_auth = redis_login(conf)\n\treturn function(so)\n\t\tif login_auth then\n\t\t\tlogin_auth(so)\n\t\tend\n\t\tfor k in pairs(obj.__psubscribe) do\n\t\t\tso:request(compose_message (\"PSUBSCRIBE\", k))\n\t\tend\n\t\tfor k in pairs(obj.__subscribe) do\n\t\t\tso:request(compose_message(\"SUBSCRIBE\", k))\n\t\tend\n\tend\nend\n\nfunction redis.watch(db_conf)\n\tlocal obj = {\n\t\t__subscribe = {},\n\t\t__psubscribe = {},\n\t}\n\tlocal channel = socketchannel.channel {\n\t\thost = db_conf.host,\n\t\tport = db_conf.port or 6379,\n\t\tauth = watch_login(db_conf, obj),\n\t\tnodelay = true,\n\t}\n\tobj.__sock = channel\n\n\t-- try connect first only once\n\tchannel:connect(true)\n\treturn setmetatable( obj, watchmeta )\nend\n\nfunction watch:disconnect()\n\tself.__sock:close()\n\tsetmetatable(self, nil)\nend\n\nlocal function watch_func( name )\n\tlocal NAME = string.upper(name)\n\twatch[name] = function(self, ...)\n\t\tlocal so = self.__sock\n\t\tfor i = 1, select(\"#\", ...) do\n\t\t\tlocal v = select(i, ...)\n\t\t\tso:request(compose_message(NAME, v))\n\t\tend\n\tend\nend\n\nwatch_func \"subscribe\"\nwatch_func \"psubscribe\"\nwatch_func \"unsubscribe\"\nwatch_func \"punsubscribe\"\n\nfunction watch:message()\n\tlocal so = self.__sock\n\twhile true do\n\t\tlocal ret = so:response(read_response)\n\t\tlocal ttype , channel, data , data2 = ret[1], ret[2], ret[3], ret[4]\n\t\tif ttype == \"message\" then\n\t\t\treturn data, channel\n\t\telseif ttype == \"pmessage\" then\n\t\t\treturn data2, data, channel\n\t\telseif ttype == \"subscribe\" then\n\t\t\tself.__subscribe[channel] = true\n\t\telseif ttype == \"psubscribe\" then\n\t\t\tself.__psubscribe[channel] = true\n\t\telseif ttype == \"unsubscribe\" then\n\t\t\tself.__subscribe[channel] = nil\n\t\telseif ttype == \"punsubscribe\" then\n\t\t\tself.__psubscribe[channel] = nil\n\t\tend\n\tend\nend\n\nreturn redis\n"
  },
  {
    "path": "lualib/skynet/debug.lua",
    "content": "local table = table\nlocal extern_dbgcmd = {}\n\nlocal function init(skynet, export)\n\tlocal internal_info_func\n\n\tfunction skynet.info_func(func)\n\t\tinternal_info_func = func\n\tend\n\n\tlocal dbgcmd\n\n\tlocal function init_dbgcmd()\n\t\tdbgcmd = {}\n\n\t\tfunction dbgcmd.MEM()\n\t\t\tlocal kb = collectgarbage \"count\"\n\t\t\tskynet.ret(skynet.pack(kb))\n\t\tend\n\n\t\tlocal gcing = false\n\t\tfunction dbgcmd.GC()\n\t\t\tif gcing then\n\t\t\t\treturn\n\t\t\tend\n\t\t\tgcing = true\n\t\t\tlocal before = collectgarbage \"count\"\n\t\t\tlocal before_time = skynet.now()\n\t\t\tcollectgarbage \"collect\"\n\t\t\t-- skip subsequent GC message\n\t\t\tskynet.yield()\n\t\t\tlocal after = collectgarbage \"count\"\n\t\t\tlocal after_time = skynet.now()\n\t\t\tskynet.error(string.format(\"GC %.2f Kb -> %.2f Kb, cost %.2f sec\", before, after, (after_time - before_time) / 100))\n\t\t\tgcing = false\n\t\tend\n\n\t\tfunction dbgcmd.STAT()\n\t\t\tlocal stat = {}\n\t\t\tstat.task = skynet.task()\n\t\t\tstat.mqlen = skynet.stat \"mqlen\"\n\t\t\tstat.cpu = skynet.stat \"cpu\"\n\t\t\tstat.message = skynet.stat \"message\"\n\t\t\tskynet.ret(skynet.pack(stat))\n\t\tend\n\n\t\tfunction dbgcmd.KILLTASK(threadname)\n\t\t\tlocal co = skynet.killthread(threadname)\n\t\t\tif co then\n\t\t\t\tskynet.error(string.format(\"Kill %s\", co))\n\t\t\t\tskynet.ret()\n\t\t\telse\n\t\t\t\tskynet.error(string.format(\"Kill %s : Not found\", threadname))\n\t\t\t\tskynet.ret(skynet.pack \"Not found\")\n\t\t\tend\n\t\tend\n\n\t\tfunction dbgcmd.TASK(session)\n\t\t\tif session then\n\t\t\t\tskynet.ret(skynet.pack(skynet.task(session)))\n\t\t\telse\n\t\t\t\tlocal task = {}\n\t\t\t\tskynet.task(task)\n\t\t\t\tskynet.ret(skynet.pack(task))\n\t\t\tend\n\t\tend\n\n\t\tfunction dbgcmd.UNIQTASK()\n\t\t\tskynet.ret(skynet.pack(skynet.uniqtask()))\n\t\tend\n\n\t\tfunction dbgcmd.INFO(...)\n\t\t\tif internal_info_func then\n\t\t\t\tskynet.ret(skynet.pack(internal_info_func(...)))\n\t\t\telse\n\t\t\t\tskynet.ret(skynet.pack(nil))\n\t\t\tend\n\t\tend\n\n\t\tfunction dbgcmd.EXIT()\n\t\t\tskynet.exit()\n\t\tend\n\n\t\tfunction dbgcmd.RUN(source, filename, ...)\n\t\t\tlocal inject = require \"skynet.inject\"\n\t\t\tlocal args = table.pack(...)\n\t\t\tlocal ok, output = inject(skynet, source, filename, args, export.dispatch, skynet.register_protocol)\n\t\t\tcollectgarbage \"collect\"\n\t\t\tskynet.ret(skynet.pack(ok, table.concat(output, \"\\n\")))\n\t\tend\n\n\t\tfunction dbgcmd.TERM(service)\n\t\t\tskynet.term(service)\n\t\tend\n\n\t\tfunction dbgcmd.REMOTEDEBUG(...)\n\t\t\tlocal remotedebug = require \"skynet.remotedebug\"\n\t\t\tremotedebug.start(export, ...)\n\t\tend\n\n\t\tfunction dbgcmd.SUPPORT(pname)\n\t\t\treturn skynet.ret(skynet.pack(skynet.dispatch(pname) ~= nil))\n\t\tend\n\n\t\tfunction dbgcmd.PING()\n\t\t\treturn skynet.ret()\n\t\tend\n\n\t\tfunction dbgcmd.LINK()\n\t\t\tskynet.response()\t-- get response , but not return. raise error when exit\n\t\tend\n\n\t\tfunction dbgcmd.TRACELOG(proto, flag)\n\t\t\tif type(proto) ~= \"string\" then\n\t\t\t\tflag = proto\n\t\t\t\tproto = \"lua\"\n\t\t\tend\n\t\t\tskynet.error(string.format(\"Turn trace log %s for %s\", flag, proto))\n\t\t\tskynet.traceproto(proto, flag)\n\t\t\tskynet.ret()\n\t\tend\n\n\t\treturn dbgcmd\n\tend -- function init_dbgcmd\n\n\tlocal function _debug_dispatch(session, address, cmd, ...)\n\t\tdbgcmd = dbgcmd or init_dbgcmd() -- lazy init dbgcmd\n\t\tlocal f = dbgcmd[cmd] or extern_dbgcmd[cmd]\n\t\tassert(f, cmd)\n\t\tf(...)\n\tend\n\n\tskynet.register_protocol {\n\t\tname = \"debug\",\n\t\tid = assert(skynet.PTYPE_DEBUG),\n\t\tpack = assert(skynet.pack),\n\t\tunpack = assert(skynet.unpack),\n\t\tdispatch = _debug_dispatch,\n\t}\nend\n\nlocal function reg_debugcmd(name, fn)\n\textern_dbgcmd[name] = fn\nend\n\nreturn {\n\tinit = init,\n\treg_debugcmd = reg_debugcmd,\n}\n"
  },
  {
    "path": "lualib/skynet/dns.lua",
    "content": "--[[\n\tlua dns resolver library\n\tSee  https://github.com/xjdrew/levent/blob/master/levent/dns.lua for more detail\n\n-- resource record type:\n-- TYPE            value and meaning\n-- A               1 a host address\n-- NS              2 an authoritative name server\n-- MD              3 a mail destination (Obsolete - use MX)\n-- MF              4 a mail forwarder (Obsolete - use MX)\n-- CNAME           5 the canonical name for an alias\n-- SOA             6 marks the start of a zone of authority\n-- MB              7 a mailbox domain name (EXPERIMENTAL)\n-- MG              8 a mail group member (EXPERIMENTAL)\n-- MR              9 a mail rename domain name (EXPERIMENTAL)\n-- NULL            10 a null RR (EXPERIMENTAL)\n-- WKS             11 a well known service description\n-- PTR             12 a domain name pointer\n-- HINFO           13 host information\n-- MINFO           14 mailbox or mail list information\n-- MX              15 mail exchange\n-- TXT             16 text strings\n-- AAAA            28 a ipv6 host address\n-- only appear in the question section:\n-- AXFR            252 A request for a transfer of an entire zone\n-- MAILB           253 A request for mailbox-related records (MB, MG or MR)\n-- MAILA           254 A request for mail agent RRs (Obsolete - see MX)\n-- *               255 A request for all records\n--\n-- resource recode class:\n-- IN              1 the Internet\n-- CS              2 the CSNET class (Obsolete - used only for examples in some obsolete RFCs)\n-- CH              3 the CHAOS class\n-- HS              4 Hesiod [Dyer 87]\n-- only appear in the question section:\n-- *               255 any class\n-- ]]\n\n--[[\n-- struct header {\n--  uint16_t tid     # identifier assigned by the program that generates any kind of query.\n--  uint16_t flags   # flags\n--  uint16_t qdcount # the number of entries in the question section.\n--  uint16_t ancount # the number of resource records in the answer section.\n--  uint16_t nscount # the number of name server resource records in the authority records section.\n--  uint16_t arcount # the number of resource records in the additional records section.\n-- }\n--\n-- request body:\n-- struct request {\n--  string name\n--  uint16_t atype\n--  uint16_t class\n-- }\n--\n-- response body:\n-- struct response {\n--  string name\n--  uint16_t atype\n--  uint16_t class\n--  uint16_t ttl\n--  uint16_t rdlength\n--  string rdata\n-- }\n--]]\n\nlocal skynet = require \"skynet\"\nlocal socket = require \"skynet.socket\"\n\nlocal MAX_DOMAIN_LEN = 1024\nlocal MAX_LABEL_LEN = 63\nlocal MAX_PACKET_LEN = 2048\nlocal DNS_HEADER_LEN = 12\nlocal TIMEOUT = 30 * 100\t-- 30 seconds\n\nlocal QTYPE = {\n\tA = 1,\n\tCNAME = 5,\n\tAAAA = 28,\n}\n\nlocal QCLASS = {\n\tIN = 1,\n}\n\nlocal weak = {__mode = \"kv\"}\nlocal CACHE = {}\n\nlocal dns = {}\nlocal request_pool = {}\nlocal local_hosts -- local static table lookup for hostnames\n\ndns.DEFAULT_HOSTS = \"/etc/hosts\"\ndns.DEFAULT_RESOLV_CONF = \"/etc/resolv.conf\"\n\n-- return name type: 'ipv4', 'ipv6', or 'hostname'\nlocal function guess_name_type(name)\n\tif name:match(\"^[%d%.]+$\") then\n\t\treturn \"ipv4\"\n\tend\n\n\tif name:find(\":\") then\n\t\treturn \"ipv6\"\n\tend\n\n\treturn \"hostname\"\nend\n\n-- http://man7.org/linux/man-pages/man5/hosts.5.html\nlocal function parse_hosts()\n\tif not dns.DEFAULT_HOSTS then\n\t\treturn\n\tend\n\n\tlocal f = io.open(dns.DEFAULT_HOSTS)\n\tif not f then\n\t\treturn\n\tend\n\n\tlocal rts = {}\n\tfor line in f:lines() do\n\t\tlocal ip, hosts = string.match(line, \"^%s*([%[%]%x%.%:]+)%s+([^#;]+)\")\n\t\tif not ip or not hosts then\n\t\t\tgoto continue\n\t\tend\n\n\t\tlocal family = guess_name_type(ip)\n\t\tif family == \"hostname\" then\n\t\t\tgoto continue\n\t\tend\n\n\t\tfor host in hosts:gmatch(\"%S+\") do\n\t\t\tlocal h = host:lower()\n\t\t\tlocal rt = rts[h]\n\t\t\tif not rt then\n\t\t\t\trt = {}\n\t\t\t\trts[h] = rt\n\t\t\tend\n\n\t\t\tif not rt[family] then\n\t\t\t\trt[family] = {}\n\t\t\tend\n\t\t\ttable.insert(rt[family], ip)\n\t\tend\n\t\t\n\t\t::continue::\n\tend\n\treturn rts\nend\n\n-- http://man7.org/linux/man-pages/man5/resolv.conf.5.html\nlocal function parse_resolv_conf()\n\tif not dns.DEFAULT_RESOLV_CONF then\n\t\treturn\n\tend\n\n\tlocal f = io.open(dns.DEFAULT_RESOLV_CONF)\n\tif not f then\n\t\treturn\n\tend\n\n\tlocal server\n\tfor line in f:lines() do\n\t\tserver = line:match(\"^%s*nameserver%s+([^#;%s]+)\")\n\t\tif server then\n\t\t\tbreak\n\t\tend\n\tend\n\tf:close()\n\treturn server\nend\n\nfunction dns.flush()\n\tCACHE[QTYPE.A] = setmetatable({},weak)\n\tCACHE[QTYPE.AAAA] = setmetatable({},weak)\nend\n\ndns.flush()\n\nlocal function verify_domain_name(name)\n\tif #name > MAX_DOMAIN_LEN then\n\t\treturn false\n\tend\n\tif not name:match(\"^[_%l%d%-%.]+$\") then\n\t\treturn false\n\tend\n\tfor w in name:gmatch(\"([_%w%-]+)%.?\") do\n\t\tif #w > MAX_LABEL_LEN then\n\t\t\treturn false\n\t\tend\n\tend\n\treturn true\nend\n\nlocal next_tid = 1\nlocal function gen_tid()\n\tlocal tid = next_tid\n\tif request_pool[tid] then\n\t\ttid = nil\n\t\tfor i = 1, 65535 do\n\t\t\t-- find available tid\n\t\t\tif not request_pool[i] then\n\t\t\t\ttid = i\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\t\tassert(tid)\n\tend\n\tnext_tid = tid + 1\n\tif next_tid > 65535 then\n\t\tnext_tid = 1\n\tend\n\treturn tid\nend\n\nlocal function pack_header(t)\n\treturn string.pack(\">HHHHHH\",\n\t\tt.tid, t.flags, t.qdcount, t.ancount or 0, t.nscount or 0, t.arcount or 0)\nend\n\nlocal function pack_question(name, qtype, qclass)\n\tlocal labels = {}\n\tfor w in name:gmatch(\"([_%w%-]+)%.?\") do\n\t\ttable.insert(labels, string.pack(\"s1\",w))\n\tend\n\ttable.insert(labels, '\\0')\n\ttable.insert(labels, string.pack(\">HH\", qtype, qclass))\n\treturn table.concat(labels)\nend\n\nlocal function unpack_header(chunk)\n\tlocal tid, flags, qdcount, ancount, nscount, arcount, left = string.unpack(\">HHHHHH\", chunk)\n\treturn {\n\t\ttid = tid,\n\t\tflags = flags,\n\t\tqdcount = qdcount,\n\t\tancount = ancount,\n\t\tnscount = nscount,\n\t\tarcount = arcount\n\t}, left\nend\n\n-- unpack a resource name\nlocal function unpack_name(chunk, left)\n\tlocal t = {}\n\tlocal jump_pointer\n\tlocal tag, offset, label\n\twhile true do\n\t\ttag, left = string.unpack(\"B\", chunk, left)\n\t\tif tag & 0xc0 == 0xc0 then\n\t\t\t-- pointer\n\t\t\toffset,left = string.unpack(\">H\", chunk, left - 1)\n\t\t\toffset = offset & 0x3fff\n\t\t\tif not jump_pointer then\n\t\t\t\tjump_pointer = left\n\t\t\tend\n\t\t\t-- offset is base 0, need to plus 1\n\t\t\tleft = offset + 1\n\t\telseif tag == 0 then\n\t\t\tbreak\n\t\telse\n\t\t\tlabel, left = string.unpack(\"s1\", chunk, left - 1)\n\t\t\tt[#t+1] = label\n\t\tend\n\tend\n\treturn table.concat(t, \".\"), jump_pointer or left\nend\n\nlocal function unpack_question(chunk, left)\n\tlocal name, left = unpack_name(chunk, left)\n\tlocal atype, class, left = string.unpack(\">HH\", chunk, left)\n\treturn {\n\t\tname = name,\n\t\tatype = atype,\n\t\tclass = class\n\t}, left\nend\n\nlocal function unpack_answer(chunk, left)\n\tlocal name, left = unpack_name(chunk, left)\n\tlocal atype, class, ttl, rdata, left = string.unpack(\">HHI4s2\", chunk, left)\n\treturn {\n\t\tname = name,\n\t\tatype = atype,\n\t\tclass = class,\n\t\tttl = ttl,\n\t\trdata = rdata\n\t},left\nend\n\nlocal function unpack_rdata(qtype, chunk)\n\tif qtype == QTYPE.A then\n\t\tlocal a,b,c,d = string.unpack(\"BBBB\", chunk)\n\t\treturn string.format(\"%d.%d.%d.%d\", a,b,c,d)\n\telseif qtype == QTYPE.AAAA then\n\t\tlocal a,b,c,d,e,f,g,h = string.unpack(\">HHHHHHHH\", chunk)\n\t\treturn string.format(\"%x:%x:%x:%x:%x:%x:%x:%x\", a, b, c, d, e, f, g, h)\n\telse\n\t\terror(\"Error qtype \" .. qtype)\n\tend\nend\n\nlocal dns_server = {\n\tfd = nil,\n\taddress = nil,\n\tport = nil,\n\tretire = nil,\n}\n\nlocal function resolve(content)\n\tif #content < DNS_HEADER_LEN then\n\t\t-- drop\n\t\tskynet.error(\"Recv an invalid package when dns query\")\n\t\treturn\n\tend\n\tlocal answer_header,left = unpack_header(content)\n\t-- verify answer\n\tassert(answer_header.qdcount == 1, \"malformed packet\")\n\n\tlocal question,left = unpack_question(content, left)\n\n\tlocal ttl\n\tlocal answer\n\tlocal answers_ipv4\n\tlocal answers_ipv6\n\n\tfor i=1, answer_header.ancount do\n\t\tanswer, left = unpack_answer(content, left)\n\t\tlocal answers\n\t\tif answer.atype == QTYPE.A then\n\t\t\tanswers_ipv4 = answers_ipv4 or {}\n\t\t\tanswers = answers_ipv4\n\t\telseif answer.atype == QTYPE.AAAA then\n\t\t\tanswers_ipv6 = answers_ipv6 or {}\n\t\t\tanswers = answers_ipv6\n\t\tend\n\t\tif answers then\n\t\t\tlocal ip = unpack_rdata(answer.atype, answer.rdata)\n\t\t\tttl = ttl and math.min(ttl, answer.ttl) or answer.ttl\n\t\t\tanswers[#answers+1] = ip\n\t\tend\n\tend\n\n\tif answers_ipv4 then\n\t\tCACHE[QTYPE.A][question.name] = { answers = answers_ipv4, ttl = skynet.now() + ttl * 100 }\n\tend\n\n\tif answers_ipv6 then\n\t\tCACHE[QTYPE.AAAA][question.name] = { answers = answers_ipv6, ttl = skynet.now() + ttl * 100 }\n\tend\n\n\tlocal resp = request_pool[answer_header.tid]\n\tif not resp then\n\t\t-- the resp may be timeout\n\t\treturn\n\tend\n\n\tif question.name ~= resp.name then\n\t\tskynet.error(\"Recv an invalid name when dns query\")\n\tend\n\n\tlocal r = CACHE[resp.qtype][resp.name]\n\tif r then\n\t\tresp.answers = r.answers\n\tend\n\n\tskynet.wakeup(resp.co)\nend\n\nlocal function connect_server()\n\tlocal fd = socket.udp(function(str, from)\n\t\tresolve(str)\n\tend)\n\n\tif not dns_server.address then\n\t\tdns_server.address = parse_resolv_conf()\n\t\tdns_server.port = 53\n\tend\n\n\tassert(dns_server.address, \"Call dns.server first\")\n\n\tlocal ok, err = pcall(socket.udp_connect,fd, dns_server.address, dns_server.port)\n\tif not ok then\n\t\tsocket.close(fd)\n\t\terror(err)\n\tend\n\n\tdns_server.fd = fd\n\tskynet.error(string.format(\"Udp server open %s:%s (%d)\", dns_server.address, dns_server.port, fd))\nend\n\nlocal DNS_SERVER_RETIRE = 60 * 100\nlocal function touch_server()\n\tdns_server.retire = skynet.now()\n\tif dns_server.fd then\n\t\treturn\n\tend\n\n\tconnect_server()\n\n\tlocal function check_alive()\n\t\tif skynet.now() > dns_server.retire + DNS_SERVER_RETIRE then\n\t\t\tlocal fd = dns_server.fd\n\t\t\tif fd then\n\t\t\t\tdns_server.fd = nil\n\t\t\t\tsocket.close(fd)\n\t\t\t\tskynet.error(string.format(\"Udp server close %s:%s (%d)\", dns_server.address, dns_server.port, fd))\n\t\t\tend\n\t\telse\n\t\t\tskynet.timeout( 2 * DNS_SERVER_RETIRE, check_alive)\n\t\tend\n\tend\n\n\tskynet.timeout( 2 * DNS_SERVER_RETIRE, check_alive)\nend\n\nfunction dns.server(server, port)\n\tdns_server.address = server\n\tdns_server.port = port or 53\nend\n\nlocal function lookup_cache(name, qtype, ignorettl)\n\tlocal result = CACHE[qtype][name]\n\tif result then\n\t\tif ignorettl or (result.ttl > skynet.now()) then\n\t\t\treturn result.answers\n\t\tend\n\tend\nend\n\nlocal function suspend(tid, name, qtype)\n\tlocal req = {\n\t\tname = name,\n\t\ttid = tid,\n\t\tqtype = qtype,\n\t\tco = coroutine.running(),\n\t}\n\trequest_pool[tid] = req\n\tskynet.fork(function()\n\t\tskynet.sleep(TIMEOUT)\n\t\tlocal req = request_pool[tid]\n\t\tif req then\n\t\t\t-- cancel tid\n\t\t\tskynet.error(string.format(\"DNS query %s timeout\", name))\n\t\t\trequest_pool[tid] = nil\n\t\t\tskynet.wakeup(req.co)\n\t\tend\n\tend)\n\tskynet.wait(req.co)\n\trequest_pool[tid] = nil\n\tif not req.answers then\n\t\tlocal answers = lookup_cache(name, qtype, true)\n\t\tif answers then\n\t\t\treturn answers[1], answers\n\t\tend\n\t\terror \"timeout or no answer\"\n\tend\n\treturn req.answers[1], req.answers\nend\n\n-- lookup local static table\nlocal function local_resolve(name, ipv6)\n\tif not local_hosts then\n\t\tlocal_hosts = parse_hosts()\n\tend\n\n\tif not local_hosts then\n\t\treturn\n\tend\n\n\tlocal family = ipv6 and \"ipv6\" or \"ipv4\"\n\tlocal t = local_hosts[name]\n\tif t then\n\t\tlocal answers = t[family]\n\t\tif answers then\n\t\t\treturn answers[1], answers\n\t\tend\n\tend\n\treturn nil\nend\n\n-- lookup dns server\nlocal function remote_resolve(name, ipv6)\n\tlocal qtype = ipv6 and QTYPE.AAAA or QTYPE.A\n\tlocal answers = lookup_cache(name, qtype)\n\tif answers then\n\t\treturn answers[1], answers\n\tend\n\tlocal question_header = {\n\t\ttid = gen_tid(),\n\t\tflags = 0x100, -- flags: 00000001 00000000, set RD\n\t\tqdcount = 1,\n\t}\n\tlocal req = pack_header(question_header) .. pack_question(name, qtype, QCLASS.IN)\n\ttouch_server()\n\tsocket.write(dns_server.fd, req)\n\treturn suspend(question_header.tid, name, qtype)\nend\n\nfunction dns.resolve(name, ipv6)\n\tlocal name = name:lower()\n\tlocal ntype = guess_name_type(name)\n\tif ntype ~= \"hostname\" then\n\t\tif (ipv6 and name == \"ipv4\") or (not ipv6 and name == \"ipv6\") then\n\t\t\treturn nil, \"illegal ip address\"\n\t\tend\n\t\treturn name\n\tend\n\n\tif not verify_domain_name(name) then\n\t\treturn nil, \"illegal name\"\n\tend\n\n\tlocal answer, answers = local_resolve(name, ipv6)\n\tif answer then\n\t\treturn answer, answers\n\tend\n\n\treturn remote_resolve(name, ipv6)\nend\n\nreturn dns\n"
  },
  {
    "path": "lualib/skynet/harbor.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal harbor = {}\n\nfunction harbor.globalname(name, handle)\n\thandle = handle or skynet.self()\n\tskynet.send(\".cslave\", \"lua\", \"REGISTER\", name, handle)\nend\n\nfunction harbor.queryname(name)\n\treturn skynet.call(\".cslave\", \"lua\", \"QUERYNAME\", name)\nend\n\nfunction harbor.link(id)\n\tskynet.call(\".cslave\", \"lua\", \"LINK\", id)\nend\n\nfunction harbor.connect(id)\n\tskynet.call(\".cslave\", \"lua\", \"CONNECT\", id)\nend\n\nfunction harbor.linkmaster()\n\tskynet.call(\".cslave\", \"lua\", \"LINKMASTER\")\nend\n\nreturn harbor\n"
  },
  {
    "path": "lualib/skynet/inject.lua",
    "content": "local function getupvaluetable(u, func, unique)\n\tlocal i = 1\n\twhile true do\n\t\tlocal name, value = debug.getupvalue(func, i)\n\t\tif name == nil then\n\t\t\treturn\n\t\tend\n\t\tlocal t = type(value)\n\t\tif t == \"table\" then\n\t\t\tu[name] = value\n\t\telseif t == \"function\" then\n\t\t\tif not unique[value] then\n\t\t\t\tunique[value] = true\n\t\t\t\tgetupvaluetable(u, value, unique)\n\t\t\tend\n\t\tend\n\t\ti=i+1\n\tend\nend\n\nreturn function(skynet, source, filename, args, ...)\n\tif filename then\n\t\tfilename = \"@\" .. filename\n\telse\n\t\tfilename = \"=(load)\"\n\tend\n\tlocal output = {}\n\n\tlocal function print(...)\n\t\tlocal value = { ... }\n\t\tfor k,v in ipairs(value) do\n\t\t\tvalue[k] = tostring(v)\n\t\tend\n\t\ttable.insert(output, table.concat(value, \"\\t\"))\n\tend\n\tlocal u = {}\n\tlocal unique = {}\n\tlocal funcs = { ... }\n\tfor k, func in ipairs(funcs) do\n\t\tgetupvaluetable(u, func, unique)\n\tend\n\tlocal p = {}\n\tlocal proto = u.proto\n\tif proto then\n\t\tfor k,v in pairs(proto) do\n\t\t\tlocal name, dispatch = v.name, v.dispatch\n\t\t\tif name and dispatch and not p[name] then\n\t\t\t\tlocal pp = {}\n\t\t\t\tp[name] = pp\n\t\t\t\tgetupvaluetable(pp, dispatch, unique)\n\t\t\tend\n\t\tend\n\tend\n\tlocal env = setmetatable( { print = print , _U = u, _P = p}, { __index = _ENV })\n\tlocal func, err = load(source, filename, \"bt\", env)\n\tif not func then\n\t\treturn false, { err }\n\tend\n\tlocal ok, err = skynet.pcall(func, table.unpack(args, 1, args.n))\n\tif not ok then\n\t\ttable.insert(output, err)\n\t\treturn false, output\n\tend\n\n\treturn true, output\nend\n"
  },
  {
    "path": "lualib/skynet/injectcode.lua",
    "content": "local debug = debug\nlocal table = table\n\nlocal FUNC_TEMP=[[\nlocal $ARGS\nreturn function(...)\n$SOURCE\nend,\nfunction()\nreturn {$LOCALS}\nend\n]]\n\nlocal temp = {}\nlocal function wrap_locals(co, source, level, ext_funcs)\n\tif co == coroutine.running() then\n\t\tlevel = level + 3\n\tend\n\tlocal f = debug.getinfo(co, level,\"f\").func\n\tif f == nil then\n\t\treturn false, \"Invalid level\"\n\tend\n\n\tlocal uv = {}\n\tlocal locals = {}\n\tlocal uv_id = {}\n\tlocal local_id = {}\n\n\tif ext_funcs then\n\t\tfor k,v in pairs(ext_funcs) do\n\t\t\ttable.insert(uv, k)\n\t\tend\n\tend\n\tlocal i = 1\n\twhile true do\n\t\tlocal name, value = debug.getlocal(co, level, i)\n\t\tif name == nil then\n\t\t\tbreak\n\t\tend\n\t\tif name:byte() ~= 40 then\t-- '('\n\t\t\ttable.insert(uv, name)\n\t\t\ttable.insert(locals, (\"[%d]=%s,\"):format(i,name))\n\t\t\tlocal_id[name] = value\n\t\tend\n\t\ti = i + 1\n\tend\n\tlocal i = 1\n\twhile true do\n\t\tlocal name = debug.getupvalue(f, i)\n\t\tif name == nil then\n\t\t\tbreak\n\t\tend\n\t\tuv_id[name] = i\n\t\ttable.insert(uv, name)\n\t\ti = i + 1\n\tend\n\ttemp.ARGS = table.concat(uv, \",\")\n\ttemp.SOURCE = source\n\ttemp.LOCALS = table.concat(locals)\n\tlocal full_source = FUNC_TEMP:gsub(\"%$(%w+)\",temp)\n\tlocal loader, err = load(full_source, \"=(debug)\")\n\tif loader == nil then\n\t\treturn false, err\n\tend\n\tlocal func, update = loader()\n\t-- join func's upvalues\n\tlocal i = 1\n\twhile true do\n\t\tlocal name = debug.getupvalue(func, i)\n\t\tif name == nil then\n\t\t\tbreak\n\t\tend\n\t\tif ext_funcs then\n\t\t\tlocal v = ext_funcs[name]\n\t\t\tif v then\n\t\t\t\tdebug.setupvalue(func, i, v)\n\t\t\tend\n\t\tend\n\n\t\tlocal local_value = local_id[name]\n\t\tif local_value then\n\t\t\tdebug.setupvalue(func, i, local_value)\n\t\tend\n\t\tlocal upvalue_id = uv_id[name]\n\t\tif upvalue_id then\n\t\t\tdebug.upvaluejoin(func, i, f, upvalue_id)\n\t\tend\n\t\ti=i+1\n\tend\n\tlocal vararg, v = debug.getlocal(co, level, -1)\n\tif vararg then\n\t\tlocal vargs = { v }\n\t\tlocal i = 2\n\t\twhile true do\n\t\t\tlocal vararg,v = debug.getlocal(co, level, -i)\n\t\t\tif vararg then\n\t\t\t\tvargs[i] = v\n\t\t\telse\n\t\t\t\tbreak\n\t\t\tend\n\t\t\ti=i+1\n\t\tend\n\t\treturn func, update, table.unpack(vargs)\n\telse\n\t\treturn func, update\n\tend\nend\n\nlocal function exec(co, level, func, update, ...)\n\tif not func then\n\t\treturn false, update\n\tend\n\tif co == coroutine.running() then\n\t\tlevel = level + 2\n\tend\n\tlocal rets = table.pack(pcall(func, ...))\n\tif rets[1] then\n\t\tlocal needupdate = update()\n\t\tfor k,v in pairs(needupdate) do\n\t\t\tdebug.setlocal(co, level,k,v)\n\t\tend\n\t\treturn table.unpack(rets, 1, rets.n)\n\telse\n\t\treturn false, rets[2]\n\tend\nend\n\nreturn function (source, co, level, ext_funcs)\n\tco = co or coroutine.running()\n\tlevel = level or 0\n\treturn exec(co, level, wrap_locals(co, source, level, ext_funcs))\nend\n\n"
  },
  {
    "path": "lualib/skynet/manager.lua",
    "content": "local skynet = require \"skynet\"\nlocal c = require \"skynet.core\"\n\nlocal function number_address(name)\n\tlocal t = type(name)\n\tif t == \"number\" then\n\t\treturn name\n\telseif t == \"string\" then\n\t\tlocal hex = name:match \"^:(%x+)\"\n\t\tif hex then\n\t\t\treturn tonumber(hex, 16)\n\t\tend\n\tend\nend\n\nfunction skynet.launch(...)\n\tlocal addr = c.command(\"LAUNCH\", table.concat({...},\" \"))\n\tif addr then\n\t\treturn tonumber(string.sub(addr , 2), 16)\n\tend\nend\n\nfunction skynet.kill(name)\n\tlocal addr = number_address(name)\n\tif addr then\n\t\tskynet.send(\".launcher\",\"lua\",\"REMOVE\", addr, true)\n\t\tname = skynet.address(addr)\n\tend\n\tc.command(\"KILL\",name)\nend\n\nfunction skynet.abort()\n\tc.command(\"ABORT\")\nend\n\nlocal function globalname(name, handle)\n\tlocal c = string.sub(name,1,1)\n\tassert(c ~= ':')\n\tif c == '.' then\n\t\treturn false\n\tend\n\n\tassert(#name < 16)\t-- GLOBALNAME_LENGTH is 16, defined in skynet_harbor.h\n\tassert(tonumber(name) == nil)\t-- global name can't be number\n\n\tlocal harbor = require \"skynet.harbor\"\n\n\tharbor.globalname(name, handle)\n\n\treturn true\nend\n\nfunction skynet.register(name)\n\tif not globalname(name) then\n\t\tc.command(\"REG\", name)\n\tend\nend\n\nfunction skynet.name(name, handle)\n\tif not globalname(name, handle) then\n\t\tc.command(\"NAME\", name .. \" \" .. skynet.address(handle))\n\tend\nend\n\nlocal dispatch_message = skynet.dispatch_message\n\nfunction skynet.forward_type(map, start_func)\n\tc.callback(function(ptype, msg, sz, ...)\n\t\tlocal prototype = map[ptype]\n\t\tif prototype then\n\t\t\tdispatch_message(prototype, msg, sz, ...)\n\t\telse\n\t\t\tlocal ok, err = pcall(dispatch_message, ptype, msg, sz, ...)\n\t\t\tc.trash(msg, sz)\n\t\t\tif not ok then\n\t\t\t\terror(err)\n\t\t\tend\n\t\tend\n\tend, true)\n\tskynet.timeout(0, function()\n\t\tskynet.init_service(start_func)\n\tend)\nend\n\nfunction skynet.filter(f ,start_func)\n\tc.callback(function(...)\n\t\tdispatch_message(f(...))\n\tend)\n\tskynet.timeout(0, function()\n\t\tskynet.init_service(start_func)\n\tend)\nend\n\nfunction skynet.monitor(service, query)\n\tlocal monitor\n\tif query then\n\t\tmonitor = skynet.queryservice(true, service)\n\telse\n\t\tmonitor = skynet.uniqueservice(true, service)\n\tend\n\tassert(monitor, \"Monitor launch failed\")\n\tc.command(\"MONITOR\", string.format(\":%08x\", monitor))\n\treturn monitor\nend\n\nreturn skynet\n"
  },
  {
    "path": "lualib/skynet/mqueue.lua",
    "content": "-- This is a deprecated module, use skynet.queue instead.\n\nlocal skynet = require \"skynet\"\nlocal c = require \"skynet.core\"\n\nlocal mqueue = {}\nlocal init_once\nlocal thread_id\nlocal message_queue = {}\n\nskynet.register_protocol {\n\tname = \"queue\",\n\t-- please read skynet.h for magic number 8\n\tid = 8,\n\tpack = skynet.pack,\n\tunpack = skynet.unpack,\n\tdispatch = function(session, from, ...)\n\t\ttable.insert(message_queue, {session = session, addr = from, ... })\n\t\tif thread_id then\n\t\t\tskynet.wakeup(thread_id)\n\t\t\tthread_id = nil\n\t\tend\n\tend\n}\n\nlocal function do_func(f, msg)\n\treturn pcall(f, table.unpack(msg))\nend\n\nlocal function message_dispatch(f)\n\twhile true do\n\t\tif #message_queue==0 then\n\t\t\tthread_id = coroutine.running()\n\t\t\tskynet.wait()\n\t\telse\n\t\t\tlocal msg = table.remove(message_queue,1)\n\t\t\tlocal session = msg.session\n\t\t\tif session == 0 then\n\t\t\t\tlocal ok, msg = do_func(f, msg)\n\t\t\t\tif ok then\n\t\t\t\t\tif msg then\n\t\t\t\t\t\tskynet.fork(message_dispatch,f)\n\t\t\t\t\t\terror(string.format(\"[:%x] send a message to [:%x] return something\", msg.addr, skynet.self()))\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\tskynet.fork(message_dispatch,f)\n\t\t\t\t\terror(string.format(\"[:%x] send a message to [:%x] throw an error : %s\", msg.addr, skynet.self(),msg))\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tlocal data, size = skynet.pack(do_func(f,msg))\n\t\t\t\t-- 1 means response\n\t\t\t\tc.send(msg.addr, 1, session, data, size)\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction mqueue.register(f)\n\tassert(init_once == nil)\n\tinit_once = true\n\tskynet.fork(message_dispatch,f)\nend\n\nlocal function catch(succ, ...)\n\tif succ then\n\t\treturn ...\n\telse\n\t\terror(...)\n\tend\nend\n\nfunction mqueue.call(addr, ...)\n\treturn catch(skynet.call(addr, \"queue\", ...))\nend\n\nfunction mqueue.send(addr, ...)\n\treturn skynet.send(addr, \"queue\", ...)\nend\n\nfunction mqueue.size()\n\treturn #message_queue\nend\n\nreturn mqueue\n"
  },
  {
    "path": "lualib/skynet/multicast.lua",
    "content": "local skynet = require \"skynet\"\nlocal mc = require \"skynet.multicast.core\"\n\nlocal multicastd\nlocal multicast = {}\nlocal dispatch = {}\n\nlocal chan = {}\nlocal chan_meta = {\n\t__index = chan,\n\t__gc = function(self)\n\t\tself:unsubscribe()\n\tend,\n\t__tostring = function (self)\n\t\treturn string.format(\"[Multicast:%x]\",self.channel)\n\tend,\n}\n\nfunction multicast.new(conf)\n\tassert(multicastd, \"Init first\")\n\tlocal self = {}\n\tconf = conf or self\n\tself.channel = conf.channel\n\tif self.channel == nil then\n\t\tself.channel = skynet.call(multicastd, \"lua\", \"NEW\")\n\tend\n\tself.__pack = conf.pack or skynet.pack\n\tself.__unpack = conf.unpack or skynet.unpack\n\tself.__dispatch = conf.dispatch\n\n\treturn setmetatable(self, chan_meta)\nend\n\nfunction chan:delete()\n\tlocal c = assert(self.channel)\n\tskynet.send(multicastd, \"lua\", \"DEL\", c)\n\tself.channel = nil\n\tself.__subscribe = nil\nend\n\nfunction chan:publish(...)\n\tlocal c = assert(self.channel)\n\tskynet.call(multicastd, \"lua\", \"PUB\", c, mc.pack(self.__pack(...)))\nend\n\nfunction chan:subscribe()\n\tlocal c = assert(self.channel)\n\tif self.__subscribe then\n\t\t-- already subscribe\n\t\treturn\n\tend\n\tskynet.call(multicastd, \"lua\", \"SUB\", c)\n\tself.__subscribe = true\n\tdispatch[c] = self\nend\n\nfunction chan:unsubscribe()\n\tif not self.__subscribe then\n\t\t-- already unsubscribe\n\t\treturn\n\tend\n\tlocal c = assert(self.channel)\n\tskynet.send(multicastd, \"lua\", \"USUB\", c)\n\tself.__subscribe = nil\n\tdispatch[c] = nil\nend\n\nlocal function dispatch_subscribe(channel, source, pack, msg, sz)\n\t-- channel as session, do need response\n\tskynet.ignoreret()\n\tlocal self = dispatch[channel]\n\tif not self then\n\t\tmc.close(pack)\n\t\t-- This channel may unsubscribe first, see #1141\n\t\treturn\n\tend\n\n\tif self.__subscribe then\n\t\tlocal ok, err = pcall(self.__dispatch, self, source, self.__unpack(msg, sz))\n\t\tmc.close(pack)\n\t\tassert(ok, err)\n\telse\n\t\t-- maybe unsubscribe first, but the message is send out. drop the message unneed\n\t\tmc.close(pack)\n\tend\nend\n\nlocal function init()\n\tmulticastd = skynet.uniqueservice \"multicastd\"\n\tskynet.register_protocol {\n\t\tname = \"multicast\",\n\t\tid = skynet.PTYPE_MULTICAST,\n\t\tunpack = mc.unpack,\n\t\tdispatch = dispatch_subscribe,\n\t}\nend\n\nskynet.init(init)\n\nreturn multicast"
  },
  {
    "path": "lualib/skynet/queue.lua",
    "content": "local skynet = require \"skynet\"\nlocal coroutine = coroutine\nlocal xpcall = xpcall\nlocal traceback = debug.traceback\nlocal table = table\n\nfunction skynet.queue()\n\tlocal current_thread\n\tlocal ref = 0\n\tlocal thread_queue = {}\n\n\tlocal function xpcall_ret(ok, ...)\n\t\tref = ref - 1\n\t\tif ref == 0 then\n\t\t\tcurrent_thread = table.remove(thread_queue,1)\n\t\t\tif current_thread then\n\t\t\t\tskynet.wakeup(current_thread)\n\t\t\tend\n\t\tend\n\t\tassert(ok, (...))\n\t\treturn ...\n\tend\n\n\treturn function(f, ...)\n\t\tlocal thread = coroutine.running()\n\t\tif current_thread and current_thread ~= thread then\n\t\t\ttable.insert(thread_queue, thread)\n\t\t\tskynet.wait()\n\t\t\tassert(ref == 0)\t-- current_thread == thread\n\t\tend\n\t\tcurrent_thread = thread\n\n\t\tref = ref + 1\n\t\treturn xpcall_ret(xpcall(f, traceback, ...))\n\tend\nend\n\nreturn skynet.queue\n"
  },
  {
    "path": "lualib/skynet/remotedebug.lua",
    "content": "local skynet = require \"skynet\"\nlocal debugchannel = require \"skynet.debugchannel\"\nlocal socketdriver = require \"skynet.socketdriver\"\nlocal injectrun = require \"skynet.injectcode\"\nlocal table = table\nlocal debug = debug\nlocal coroutine = coroutine\nlocal sethook = debugchannel.sethook\n\n\nlocal M = {}\n\nlocal HOOK_FUNC = \"raw_dispatch_message\"\nlocal raw_dispatcher\nlocal print = _G.print\nlocal skynet_suspend\nlocal skynet_resume\nlocal prompt\nlocal newline\n\nlocal function change_prompt(s)\n\tnewline = true\n\tprompt = s\nend\n\nlocal function replace_upvalue(func, uvname, value)\n\tlocal i = 1\n\twhile true do\n\t\tlocal name, uv = debug.getupvalue(func, i)\n\t\tif name == nil then\n\t\t\tbreak\n\t\tend\n\t\tif name == uvname then\n\t\t\tif value then\n\t\t\t\tdebug.setupvalue(func, i, value)\n\t\t\tend\n\t\t\treturn uv\n\t\tend\n\t\ti = i + 1\n\tend\nend\n\nlocal function remove_hook(dispatcher)\n\tassert(raw_dispatcher, \"Not in debug mode\")\n\treplace_upvalue(dispatcher, HOOK_FUNC, raw_dispatcher)\n\traw_dispatcher = nil\n\tprint = _G.print\n\n\tskynet.error \"Leave debug mode\"\nend\n\nlocal function gen_print(fd)\n\t-- redirect print to socket fd\n\treturn function(...)\n\t\tlocal tmp = table.pack(...)\n\t\tfor i=1,tmp.n do\n\t\t\ttmp[i] = tostring(tmp[i])\n\t\tend\n\t\ttable.insert(tmp, \"\\n\")\n\t\tsocketdriver.send(fd, table.concat(tmp, \"\\t\"))\n\tend\nend\n\nlocal function run_exp(ok, ...)\n\tif ok then\n\t\tprint(...)\n\tend\n\treturn ok\nend\n\nlocal function run_cmd(cmd, env, co, level)\n\tif not run_exp(injectrun(\"return \"..cmd, co, level, env)) then\n\t\tprint(select(2, injectrun(cmd,co, level,env)))\n\tend\nend\n\nlocal ctx_skynet = debug.getinfo(skynet.start,\"S\").short_src\t-- skip when enter this source file\nlocal ctx_term = debug.getinfo(run_cmd, \"S\").short_src\t-- term when get here\nlocal ctx_active = {}\n\nlocal linehook\nlocal function skip_hook(mode)\n\tlocal co = coroutine.running()\n\tlocal ctx = ctx_active[co]\n\tif mode == \"return\" then\n\t\tctx.level = ctx.level - 1\n\t\tif ctx.level == 0 then\n\t\t\tctx.needupdate = true\n\t\t\tsethook(linehook, \"crl\")\n\t\tend\n\telse\n\t\tctx.level = ctx.level + 1\n\tend\nend\n\nfunction linehook(mode, line)\n\tlocal co = coroutine.running()\n\tlocal ctx = ctx_active[co]\n\tif mode ~= \"line\" then\n\t\tctx.needupdate = true\n\t\tif mode ~= \"return\" then\n\t\t\tif ctx.next_mode or debug.getinfo(2,\"S\").short_src == ctx_skynet then\n\t\t\t\tctx.level = 1\n\t\t\t\tsethook(skip_hook, \"cr\")\n\t\t\tend\n\t\tend\n\telse\n\t\tif ctx.needupdate then\n\t\t\tctx.needupdate = false\n\t\t\tctx.filename = debug.getinfo(2, \"S\").short_src\n\t\t\tif ctx.filename == ctx_term then\n\t\t\t\tctx_active[co] = nil\n\t\t\t\tsethook()\n\t\t\t\tchange_prompt(string.format(\":%08x>\", skynet.self()))\n\t\t\t\treturn\n\t\t\tend\n\t\tend\n\t\tchange_prompt(string.format(\"%s(%d)>\",ctx.filename, line))\n\t\treturn true\t-- yield\n\tend\nend\n\nlocal function add_watch_hook()\n\tlocal co = coroutine.running()\n\tlocal ctx = {}\n\tctx_active[co] = ctx\n\tlocal level = 1\n\tsethook(function(mode)\n\t\tif mode == \"return\" then\n\t\t\tlevel = level - 1\n\t\telse\n\t\t\tlevel = level + 1\n\t\t\tif level == 0 then\n\t\t\t\tctx.needupdate = true\n\t\t\t\tsethook(linehook, \"crl\")\n\t\t\tend\n\t\tend\n\tend, \"cr\")\nend\n\nlocal function watch_proto(protoname, cond)\n\tlocal proto = assert(replace_upvalue(skynet.register_protocol, \"proto\"), \"Can't find proto table\")\n\tlocal p = proto[protoname]\n\tif p == nil then\n\t\treturn \"No \" .. protoname\n\tend\n\tlocal dispatch = p.dispatch_origin or p.dispatch\n\tif dispatch == nil then\n\t\treturn \"No dispatch\"\n\tend\n\tp.dispatch_origin = dispatch\n\tp.dispatch = function(...)\n\t\tif not cond or cond(...) then\n\t\t\tp.dispatch = dispatch\t-- restore origin dispatch function\n\t\t\tadd_watch_hook()\n\t\tend\n\t\tdispatch(...)\n\tend\nend\n\nlocal function remove_watch()\n\tfor co in pairs(ctx_active) do\n\t\tsethook(co)\n\tend\n\tctx_active = {}\nend\n\nlocal dbgcmd = {}\n\nfunction dbgcmd.s(co)\n\tlocal ctx = ctx_active[co]\n\tctx.next_mode = false\n\tskynet_suspend(co, skynet_resume(co))\nend\n\nfunction dbgcmd.n(co)\n\tlocal ctx = ctx_active[co]\n\tctx.next_mode = true\n\tskynet_suspend(co, skynet_resume(co))\nend\n\nfunction dbgcmd.c(co)\n\tsethook(co)\n\tctx_active[co] = nil\n\tchange_prompt(string.format(\":%08x>\", skynet.self()))\n\tskynet_suspend(co, skynet_resume(co))\nend\n\nlocal function hook_dispatch(dispatcher, resp, fd, channel)\n\tchange_prompt(string.format(\":%08x>\", skynet.self()))\n\n\tprint = gen_print(fd)\n\tlocal env = {\n\t\tprint = print,\n\t\twatch = watch_proto\n\t}\n\n\tlocal watch_env = {\n\t\tprint = print\n\t}\n\n\tlocal function watch_cmd(cmd)\n\t\tlocal co = next(ctx_active)\n\t\twatch_env._CO = co\n\t\tif dbgcmd[cmd] then\n\t\t\tdbgcmd[cmd](co)\n\t\telse\n\t\t\trun_cmd(cmd, watch_env, co, 0)\n\t\tend\n\tend\n\n\tlocal function debug_hook()\n\t\twhile true do\n\t\t\tif newline then\n\t\t\t\tsocketdriver.send(fd, prompt)\n\t\t\t\tnewline = false\n\t\t\tend\n\t\t\tlocal cmd = channel:read()\n\t\t\tif cmd then\n\t\t\t\tif cmd == \"cont\" then\n\t\t\t\t\t-- leave debug mode\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\t\tif cmd ~= \"\" then\n\t\t\t\t\tif next(ctx_active) then\n\t\t\t\t\t\twatch_cmd(cmd)\n\t\t\t\t\telse\n\t\t\t\t\t\trun_cmd(cmd, env, coroutine.running(),2)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tnewline = true\n\t\t\telse\n\t\t\t\t-- no input\n\t\t\t\treturn\n\t\t\tend\n\t\tend\n\t\t-- exit debug mode\n\t\tremove_watch()\n\t\tremove_hook(dispatcher)\n\t\tresp(true)\n\tend\n\n\tlocal func\n\tlocal function hook(...)\n\t\tdebug_hook()\n\t\treturn func(...)\n\tend\n\tfunc = replace_upvalue(dispatcher, HOOK_FUNC, hook)\n\tif func then\n\t\tlocal function idle()\n\t\t\tif raw_dispatcher then\n\t\t\t    skynet.timeout(10,idle)\t-- idle every 0.1s\n\t\t\tend\n\t\tend\n\t\tskynet.timeout(0, idle)\n\tend\n\treturn func\nend\n\nfunction M.start(import, fd, handle)\n\tlocal dispatcher = import.dispatch\n\tskynet_suspend = import.suspend\n\tskynet_resume = import.resume\n\tassert(raw_dispatcher == nil, \"Already in debug mode\")\n\tskynet.error \"Enter debug mode\"\n\tlocal channel = debugchannel.connect(handle)\n\traw_dispatcher = hook_dispatch(dispatcher, skynet.response(), fd, channel)\nend\n\nreturn M\n"
  },
  {
    "path": "lualib/skynet/require.lua",
    "content": "-- skynet module two-step initialize . When you require a skynet module :\n-- 1. Run module main function as official lua module behavior.\n-- 2. Run the functions register by skynet.init() during the step 1,\n--      unless calling `require` in main thread .\n-- If you call `require` in main thread ( service main function ), the functions\n-- registered by skynet.init() do not execute immediately, they will be executed\n-- by skynet.start() before start function.\n\nlocal M = {}\n\nlocal mainthread, ismain = coroutine.running()\nassert(ismain, \"skynet.require must initialize in main thread\")\n\nlocal context = {\n\t[mainthread] = {},\n}\n\ndo\n\tlocal require = _G.require\n\tlocal loaded = package.loaded\n\tlocal loading = {}\n\n\tfunction M.require(name)\n\t\tlocal m = loaded[name]\n\t\tif m ~= nil then\n\t\t\treturn m\n\t\tend\n\n\t\tlocal co, main = coroutine.running()\n\t\tif main then\n\t\t\treturn require(name)\n\t\tend\n\n\t\tlocal filename = package.searchpath(name, package.path)\n\t\tif not filename then\n\t\t\treturn require(name)\n\t\tend\n\n\t\tlocal modfunc = loadfile(filename)\n\t\tif not modfunc then\n\t\t\treturn require(name)\n\t\tend\n\n\t\tlocal loading_queue = loading[name]\n\t\tif loading_queue then\n\t\t\tassert(loading_queue.co ~= co, \"circular dependency\")\n\t\t\t-- Module is in the init process (require the same mod at the same time in different coroutines) , waiting.\n\t\t\tlocal skynet = require \"skynet\"\n\t\t\tloading_queue[#loading_queue+1] = co\n\t\t\tskynet.wait(co)\n\t\t\tlocal m = loaded[name]\n\t\t\tif m == nil then\n\t\t\t\terror(string.format(\"require %s failed\", name))\n\t\t\tend\n\t\t\treturn m\n\t\tend\n\n\t\tloading_queue = {co = co}\n\t\tloading[name] = loading_queue\n\n\t\tlocal old_init_list = context[co]\n\t\tlocal init_list = {}\n\t\tcontext[co] = init_list\n\n\t\t-- We should call modfunc in lua, because modfunc may yield by calling M.require recursive.\n\t\tlocal function execute_module()\n\t\t\tlocal m = modfunc(name, filename)\n\n\t\t\tfor _, f in ipairs(init_list) do\n\t\t\t\tf()\n\t\t\tend\n\n\t\t\tif m == nil then\n\t\t\t\tm = true\n\t\t\tend\n\n\t\t\tloaded[name] = m\n\t\tend\n\n\t\tlocal ok, err = xpcall(execute_module, debug.traceback)\n\n\t\tcontext[co] = old_init_list\n\n\t\tlocal waiting = #loading_queue\n\t\tif waiting > 0 then\n\t\t\tlocal skynet = require \"skynet\"\n\t\t\tfor i = 1, waiting do\n\t\t\t\tskynet.wakeup(loading_queue[i])\n\t\t\tend\n\t\tend\n\t\tloading[name] = nil\n\n\t\tif ok then\n\t\t\treturn loaded[name]\n\t\telse\n\t\t\terror(err)\n\t\tend\n\tend\nend\n\nfunction M.init_all()\n\tfor _, f in ipairs(context[mainthread]) do\n\t\tf()\n\tend\n\tcontext[mainthread] = nil\nend\n\nfunction M.init(f)\n\tassert(type(f) == \"function\")\n\tlocal co = coroutine.running()\n\ttable.insert(context[co], f)\nend\n\nreturn M"
  },
  {
    "path": "lualib/skynet/service.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal service = {}\nlocal cache = {}\nlocal provider\n\nlocal function get_provider()\n\tprovider = provider or skynet.uniqueservice \"service_provider\"\n\treturn provider\nend\n\nlocal function check(func)\n\tlocal info = debug.getinfo(func, \"u\")\n\tassert(info.nups == 1)\n\tassert(debug.getupvalue(func,1) == \"_ENV\")\nend\n\nfunction service.new(name, mainfunc, ...)\n\tlocal p = get_provider()\n\tlocal addr, booting = skynet.call(p, \"lua\", \"test\", name)\n\tlocal address\n\tif addr then\n\t\taddress = addr\n\telse\n\t\tif booting then\n\t\t\taddress = skynet.call(p, \"lua\", \"query\", name)\n\t\telse\n\t\t\tcheck(mainfunc)\n\t\t\tlocal code = string.dump(mainfunc)\n\t\t\taddress = skynet.call(p, \"lua\", \"launch\", name, code, ...)\n\t\tend\n\tend\n\tcache[name] = address\n\treturn address\nend\n\nfunction service.close(name)\n\tlocal addr = skynet.call(get_provider(), \"lua\", \"close\", name)\n\tif addr then\n        cache[name] = nil\n\t\tskynet.kill(addr)\n\t\treturn true\n\tend\n\treturn false\nend\n\nfunction service.query(name)\n\tif not cache[name] then\n\t\tcache[name] = skynet.call(get_provider(), \"lua\", \"query\", name)\n\tend\n\treturn cache[name]\nend\n\nreturn service\n"
  },
  {
    "path": "lualib/skynet/sharedata/corelib.lua",
    "content": "local core = require \"skynet.sharedata.core\"\nlocal type = type\nlocal rawset = rawset\n\nlocal conf = {}\n\nconf.host = {\n\tnew = core.new,\n\tdelete = core.delete,\n\tgetref = core.getref,\n\tmarkdirty = core.markdirty,\n\tincref = core.incref,\n\tdecref = core.decref,\n}\n\nlocal meta = {}\n\nlocal isdirty = core.isdirty\nlocal index = core.index\nlocal needupdate = core.needupdate\nlocal len = core.len\nlocal core_nextkey = core.nextkey\n\nlocal function findroot(self)\n\twhile self.__parent do\n\t\tself = self.__parent\n\tend\n\treturn self\nend\n\nlocal function update(root, cobj, gcobj)\n\troot.__obj = cobj\n\troot.__gcobj = gcobj\n\tlocal children = root.__cache\n\tif children then\n\t\tfor k,v in pairs(children) do\n\t\t\tlocal pointer = index(cobj, k)\n\t\t\tif type(pointer) == \"userdata\" then\n\t\t\t\tupdate(v, pointer, gcobj)\n\t\t\telse\n\t\t\t\tchildren[k] = nil\n\t\t\tend\n\t\tend\n\tend\nend\n\nlocal function genkey(self)\n\tlocal key = tostring(self.__key)\n\twhile self.__parent do\n\t\tself = self.__parent\n\t\tkey = self.__key .. \".\" .. key\n\tend\n\treturn key\nend\n\nlocal function getcobj(self)\n\tlocal obj = self.__obj\n\tif isdirty(obj) then\n\t\tlocal newobj, newtbl = needupdate(self.__gcobj)\n\t\tif newobj then\n\t\t\tlocal newgcobj = newtbl.__gcobj\n\t\t\tlocal root = findroot(self)\n\t\t\tupdate(root, newobj, newgcobj)\n\t\t\tif obj == self.__obj then\n\t\t\t\terror (\"The key [\" .. genkey(self) .. \"] doesn't exist after update\")\n\t\t\tend\n\t\t\tobj = self.__obj\n\t\tend\n\tend\n\treturn obj\nend\n\nfunction meta:__newindex(key, value)\n\terror (\"Error newindex, the key [\" .. genkey(self) .. \"]\")\nend\n\nfunction meta:__index(key)\n\tlocal obj = getcobj(self)\n\tlocal v = index(obj, key)\n\tif type(v) == \"userdata\" then\n\t\tlocal children = self.__cache\n\t\tif children == nil then\n\t\t\tchildren = {}\n\t\t\trawset(self, \"__cache\", children)\n\t\tend\n\t\tlocal r = children[key]\n\t\tif r then\n\t\t\treturn r\n\t\tend\n\t\tr = setmetatable({\n\t\t\t__obj = v,\n\t\t\t__gcobj = self.__gcobj,\n\t\t\t__parent = self,\n\t\t\t__key = key,\n\t\t}, meta)\n\t\tchildren[key] = r\n\t\treturn r\n\telse\n\t\treturn v\n\tend\nend\n\nfunction meta:__len()\n\treturn len(getcobj(self))\nend\n\nfunction meta:__pairs()\n\treturn conf.next, self, nil\nend\n\nfunction conf.next(obj, key)\n\tlocal cobj = getcobj(obj)\n\tlocal nextkey = core_nextkey(cobj, key)\n\tif nextkey then\n\t\treturn nextkey, obj[nextkey]\n\tend\nend\n\nfunction conf.box(obj)\n\tlocal gcobj = core.box(obj)\n\treturn setmetatable({\n\t\t__parent = false,\n\t\t__obj = obj,\n\t\t__gcobj = gcobj,\n\t\t__key = \"\",\n\t} , meta)\nend\n\nfunction conf.update(self, pointer)\n\tlocal cobj = self.__obj\n\tassert(isdirty(cobj), \"Only dirty object can be update\")\n\tcore.update(self.__gcobj, pointer, { __gcobj = core.box(pointer) })\nend\n\nfunction conf.flush(obj)\n\tgetcobj(obj)\nend\n\nlocal function clone_table(cobj)\n\tlocal obj = {}\n\tlocal key\n\twhile true do\n\t\tkey = core_nextkey(cobj, key)\n\t\tif key == nil then\n\t\t\tbreak\n\t\tend\n\t\tlocal v = index(cobj, key)\n\t\tif type(v) == \"userdata\" then\n\t\t\tv = clone_table(v)\n\t\tend\n\t\tobj[key] = v\n\tend\n\treturn obj\nend\n\nlocal function find_node(cobj, key, ...)\n\tif key == nil then\n\t\treturn cobj\n\tend\n\tlocal cobj = index(cobj, key)\n\tif cobj == nil then\n\t\treturn nil\n\tend\n\tif type(cobj) == \"userdata\" then\n\t\treturn find_node(cobj, ...)\n\tend\n\treturn cobj\nend\n\nfunction conf.copy(cobj, ...)\n\tcobj = find_node(cobj, ...)\n\tif cobj then\n\t\tif type(cobj) == \"userdata\" then\n\t\t\treturn clone_table(cobj)\n\t\telse\n\t\t\treturn cobj\n\t\tend\n\tend\nend\n\nreturn conf\n"
  },
  {
    "path": "lualib/skynet/sharedata.lua",
    "content": "local skynet = require \"skynet\"\nlocal sd = require \"skynet.sharedata.corelib\"\n\nlocal service\n\nskynet.init(function()\n\tservice = skynet.uniqueservice \"sharedatad\"\nend)\n\nlocal sharedata = {}\nlocal cache = setmetatable({}, { __mode = \"kv\" })\n\nlocal function monitor(name, obj, cobj)\n\tlocal newobj = cobj\n\twhile true do\n\t\tnewobj = skynet.call(service, \"lua\", \"monitor\", name, newobj)\n\t\tif newobj == nil then\n\t\t\tbreak\n\t\tend\n\t\tsd.update(obj, newobj)\n\t\tskynet.send(service, \"lua\", \"confirm\" , newobj)\n\tend\n\tif cache[name] == obj then\n\t\tcache[name] = nil\n\tend\nend\n\nfunction sharedata.query(name)\n\tif cache[name] then\n\t\treturn cache[name]\n\tend\n\tlocal obj = skynet.call(service, \"lua\", \"query\", name)\n\tif cache[name] and cache[name].__obj == obj then\n\t\tskynet.send(service, \"lua\", \"confirm\" , obj)\n\t\treturn cache[name]\n\tend\n\tlocal r = sd.box(obj)\n\tskynet.send(service, \"lua\", \"confirm\" , obj)\n\tskynet.fork(monitor,name, r, obj)\n\tcache[name] = r\n\treturn r\nend\n\nfunction sharedata.new(name, v, ...)\n\tskynet.call(service, \"lua\", \"new\", name, v, ...)\nend\n\nfunction sharedata.update(name, v, ...)\n\tskynet.call(service, \"lua\", \"update\", name, v, ...)\nend\n\nfunction sharedata.delete(name)\n\tskynet.call(service, \"lua\", \"delete\", name)\nend\n\nfunction sharedata.flush()\n\tfor name, obj in pairs(cache) do\n\t\tsd.flush(obj)\n\tend\n\tcollectgarbage()\nend\n\nfunction sharedata.deepcopy(name, ...)\n\tif cache[name] then\n\t\tlocal cobj = cache[name].__obj\n\t\treturn sd.copy(cobj, ...)\n\tend\n\n\tlocal cobj = skynet.call(service, \"lua\", \"query\", name)\n\tlocal ret = sd.copy(cobj, ...)\n\tskynet.send(service, \"lua\", \"confirm\" , cobj)\n\treturn ret\nend\n\nreturn sharedata\n"
  },
  {
    "path": "lualib/skynet/sharemap.lua",
    "content": "local stm = require \"skynet.stm\"\nlocal sprotoloader = require \"sprotoloader\"\nlocal sproto = require \"sproto\"\nlocal setmetatable = setmetatable\n\nlocal sharemap = {}\n\nfunction sharemap.register(protofile)\n\t-- use global slot 0 for type define\n\tsprotoloader.register(protofile, 0)\nend\n\nlocal sprotoobj\nlocal function loadsp()\n\tif sprotoobj == nil then\n\t\tsprotoobj = sprotoloader.load(0)\n\tend\n\treturn sprotoobj\nend\n\nfunction sharemap:commit()\n\tself.__obj(sprotoobj:encode(self.__typename, self.__data))\nend\n\nfunction sharemap:copy()\n\treturn stm.copy(self.__obj)\nend\n\nfunction sharemap.writer(typename, obj)\n\tlocal sp = loadsp()\n\tobj = obj or {}\n\tlocal stmobj = stm.new(sp:encode(typename,obj))\n\tlocal ret = {\n\t\t__typename = typename,\n\t\t__obj = stmobj,\n\t\t__data = obj,\n\t\tcommit = sharemap.commit,\n\t\tcopy = sharemap.copy,\n\t}\n\treturn setmetatable(ret, { __index = obj, __newindex = obj })\nend\n\nlocal function decode(msg, sz, self)\n\tlocal data = self.__data\n\tfor k in pairs(data) do\n\t\tdata[k] = nil\n\tend\n\treturn sprotoobj:decode(self.__typename, msg, sz, data)\nend\n\nfunction sharemap:update()\n\treturn self.__obj(decode, self)\nend\n\nfunction sharemap.reader(typename, stmcpy)\n\tlocal sp = loadsp()\n\tlocal stmobj = stm.newcopy(stmcpy)\n\tlocal _, data = stmobj(function(msg, sz)\n\t\treturn sp:decode(typename, msg, sz)\n\tend)\n\n\tlocal obj = {\n\t\t__typename = typename,\n\t\t__obj = stmobj,\n\t\t__data = data,\n\t\tupdate = sharemap.update,\n\t}\n\treturn setmetatable(obj, { __index = data, __newindex = error })\nend\n\nreturn sharemap\n"
  },
  {
    "path": "lualib/skynet/sharetable.lua",
    "content": "local skynet = require \"skynet\"\nlocal service = require \"skynet.service\"\nlocal core = require \"skynet.sharetable.core\"\nlocal is_sharedtable = core.is_sharedtable\nlocal stackvalues = core.stackvalues\n\nlocal function sharetable_service()\n\tlocal skynet = require \"skynet\"\n\tlocal core = require \"skynet.sharetable.core\"\n\n\tlocal matrix = {}\t-- all the matrix\n\tlocal files = {}\t-- filename : matrix\n\tlocal clients = {}\n\n\tlocal sharetable = {}\n\n\tlocal function close_matrix(m)\n\t\tif m == nil then\n\t\t\treturn\n\t\tend\n\t\tlocal ptr = m:getptr()\n\t\tlocal ref = matrix[ptr]\n\t\tif ref == nil or ref.count == 0 then\n\t\t\tmatrix[ptr] = nil\n\t\t\tm:close()\n\t\tend\n\tend\n\n\tfunction sharetable.loadfile(source, filename, ...)\n\t\tclose_matrix(files[filename])\n\t\tlocal m = core.matrix(\"@\" .. filename, ...)\n\t\tfiles[filename] = m\n\t\tskynet.ret()\n\tend\n\n\tfunction sharetable.loadstring(source, filename, datasource, ...)\n\t\tclose_matrix(files[filename])\n\t\tlocal m = core.matrix(datasource, ...)\n\t\tfiles[filename] = m\n\t\tskynet.ret()\n\tend\n\n\tlocal function loadtable(filename, ptr, len)\n\t\tclose_matrix(files[filename])\n\t\tlocal m = core.matrix([[\n\t\t\tlocal unpack, ptr, len = ...\n\t\t\treturn unpack(ptr, len)\n\t\t]], skynet.unpack, ptr, len)\n\t\tfiles[filename] = m\n\tend\n\n\tfunction sharetable.loadtable(source, filename, ptr, len)\n\t\tlocal ok, err = pcall(loadtable, filename, ptr, len)\n\t\tskynet.trash(ptr, len)\n\t\tassert(ok, err)\n\t\tskynet.ret()\n\tend\n\n\tlocal function query_file(source, filename)\n\t\tlocal m = files[filename]\n\t\tlocal ptr = m:getptr()\n\t\tlocal ref = matrix[ptr]\n\t\tif ref == nil then\n\t\t\tref = {\n\t\t\t\tfilename = filename,\n\t\t\t\tcount = 0,\n\t\t\t\tmatrix = m,\n\t\t\t\trefs = {},\n\t\t\t}\n\t\t\tmatrix[ptr] = ref\n\t\tend\n\t\tif ref.refs[source] == nil then\n\t\t\tref.refs[source] = true\n\t\t\tlocal list = clients[source]\n\t\t\tif not list then\n\t\t\t\tclients[source] = { ptr }\n\t\t\telse\n\t\t\t\ttable.insert(list, ptr)\n\t\t\tend\n\t\t\tref.count = ref.count + 1\n\t\tend\n\t\treturn ptr\n\tend\n\n\tfunction sharetable.query(source, filename)\n\t\tlocal m = files[filename]\n\t\tif m == nil then\n\t\t\tskynet.ret()\n\t\t\treturn\n\t\tend\n\t\tlocal ptr = query_file(source, filename)\n\t\tskynet.ret(skynet.pack(ptr))\n\tend\n\n\tlocal function querylist(source, filenamelist)\n\t\tlocal ptrList = {}\n        for _, filename in ipairs(filenamelist) do\n            if files[filename] then\n                ptrList[filename] = query_file(source, filename)\n            end\n        end\n\t\treturn ptrList\n\tend\n\n\tlocal function queryall(source)\n\t\tlocal ptrList = {}\n\t\tfor filename in pairs(files) do\n\t\t\tptrList[filename] = query_file(source, filename)\n\t\tend\n\t\treturn ptrList\n\tend\n\n    function sharetable.queryall(source, filenamelist)\n\t\tlocal queryFunc = filenamelist and querylist or queryall\n\t\tlocal ptrList = queryFunc(source, filenamelist)\n        skynet.ret(skynet.pack(ptrList))\n    end\n\n\tfunction sharetable.close(source)\n\t\tlocal list = clients[source]\n\t\tif list then\n\t\t\tfor _, ptr in ipairs(list) do\n\t\t\t\tlocal ref = matrix[ptr]\n\t\t\t\tif ref and ref.refs[source] then\n\t\t\t\t\tref.refs[source] = nil\n\t\t\t\t\tref.count = ref.count - 1\n\t\t\t\t\tif ref.count == 0 then\n\t\t\t\t\t\tif files[ref.filename] ~= ref.matrix then\n\t\t\t\t\t\t\t-- It's a history version\n\t\t\t\t\t\t\tskynet.error(string.format(\"Delete a version (%s) of %s\", ptr, ref.filename))\n\t\t\t\t\t\t\tref.matrix:close()\n\t\t\t\t\t\t\tmatrix[ptr] = nil\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tclients[source] = nil\n\t\tend\n\t\t-- no return\n\tend\n\n\tskynet.dispatch(\"lua\", function(_,source,cmd,...)\n\t\tsharetable[cmd](source,...)\n\tend)\n\n\tskynet.info_func(function()\n\t\tlocal info = {}\n\n\t\tfor filename, m in pairs(files) do\n\t\t\tinfo[filename] = {\n\t\t\t\tcurrent = m:getptr(),\n\t\t\t\tsize = m:size(),\n\t\t\t}\n\t\tend\n\n\t\tlocal function address(refs)\n\t\t\tlocal keys = {}\n\t\t\tfor addr in pairs(refs) do\n\t\t\t\ttable.insert(keys, skynet.address(addr))\n\t\t\tend\n\t\t\ttable.sort(keys)\n\t\t\treturn table.concat(keys, \",\")\n\t\tend\n\n\t\tfor ptr, copy in pairs(matrix) do\n\t\t\tlocal v = info[copy.filename]\n\t\t\tlocal h = v.history\n\t\t\tif h == nil then\n\t\t\t\th = {}\n\t\t\t\tv.history = h\n\t\t\tend\n\t\t\ttable.insert(h, string.format(\"%s [%d]: (%s)\", copy.matrix:getptr(), copy.matrix:size(), address(copy.refs)))\n\t\tend\n\t\tfor _, v in pairs(info) do\n\t\t\tif v.history then\n\t\t\t\tv.history = table.concat(v.history, \"\\n\\t\")\n\t\t\tend\n\t\tend\n\n\t\treturn info\n\tend)\n\nend\n\nlocal function load_service(t, key)\n\tif key == \"address\" then\n\t\tt.address = service.new(\"sharetable\", sharetable_service)\n\t\treturn t.address\n\telse\n\t\treturn nil\n\tend\nend\n\nlocal function report_close(t)\n\tlocal addr = rawget(t, \"address\")\n\tif addr then\n\t\tskynet.send(addr, \"lua\", \"close\")\n\tend\nend\n\nlocal sharetable = setmetatable ( {} , {\n\t__index = load_service,\n\t__gc = report_close,\n})\n\nfunction sharetable.loadfile(filename, ...)\n\tskynet.call(sharetable.address, \"lua\", \"loadfile\", filename, ...)\nend\n\nfunction sharetable.loadstring(filename, source, ...)\n\tskynet.call(sharetable.address, \"lua\", \"loadstring\", filename, source, ...)\nend\n\nfunction sharetable.loadtable(filename, tbl)\n\tassert(type(tbl) == \"table\")\n\tskynet.call(sharetable.address, \"lua\", \"loadtable\", filename, skynet.pack(tbl))\nend\n\n\nlocal RECORD = {}\nfunction sharetable.query(filename)\n\tlocal newptr = skynet.call(sharetable.address, \"lua\", \"query\", filename)\n\tif newptr then\n\t\tlocal t = core.clone(newptr)\n\t\tlocal map = RECORD[filename]\n\t\tif not map then\n\t\t\tmap = {}\n\t\t\tRECORD[filename] = map\n\t\tend\n\t\tmap[t] = true\n\t\treturn t\n\tend\nend\n\nfunction sharetable.queryall(filenamelist)\n    local list, t, map = {}\n    local ptrList = skynet.call(sharetable.address, \"lua\", \"queryall\", filenamelist)\n    for filename, ptr in pairs(ptrList) do\n        t = core.clone(ptr)\n        map = RECORD[filename]\n        if not map then\n            map = {}\n            RECORD[filename] = map\n        end\n        map[t] = true\n        list[filename] = t\n    end\n    return list\nend\n\nlocal pairs = pairs\nlocal type = type\nlocal assert = assert\nlocal next = next\nlocal rawset = rawset\nlocal getuservalue = debug.getuservalue\nlocal setuservalue = debug.setuservalue\nlocal getupvalue = debug.getupvalue\nlocal setupvalue = debug.setupvalue\nlocal getlocal = debug.getlocal\nlocal setlocal = debug.setlocal\nlocal getinfo = debug.getinfo\n\nlocal NILOBJ = {}\nlocal function insert_replace(old_t, new_t, replace_map)\n    for k, ov in pairs(old_t) do\n        if type(ov) == \"table\" then\n            local nv = new_t[k]\n            if nv == nil then\n                nv = NILOBJ\n            end\n            assert(replace_map[ov] == nil)\n            replace_map[ov] = nv\n            nv = type(nv) == \"table\" and nv or NILOBJ\n            insert_replace(ov, nv, replace_map)\n        end\n    end\n    replace_map[old_t] = new_t\n    return replace_map\nend\n\n\nlocal function resolve_replace(replace_map)\n    local match = {}\n    local record_map = {}\n\n    local function getnv(v)\n        local nv = replace_map[v]\n        if nv then\n            if nv == NILOBJ then\n                return nil\n            end\n            return nv\n        end\n        assert(false)\n    end\n\n    local function match_value(v)\n        if v == nil or record_map[v] or is_sharedtable(v) then\n            return\n        end\n\n        local tv = type(v)\n        local f = match[tv]\n        if f then\n            record_map[v] = true\n            return f(v)\n        end\n    end\n\n    local function match_mt(v)\n        local mt = debug.getmetatable(v)\n        if mt then\n            local nv = replace_map[mt]\n            if nv then\n                nv = getnv(mt)\n                debug.setmetatable(v, nv)\n            else\n                return match_value(mt)\n            end\n        end\n    end\n\n    local function match_internmt()\n        local internal_types = {\n            pointer = debug.upvalueid(getnv, 1),\n            boolean = false,\n            str = \"\",\n            number = 42,\n            thread = coroutine.running(),\n            func = getnv,\n        }\n        for _,v in pairs(internal_types) do\n            match_mt(v)\n        end\n        return match_mt(nil)\n    end\n\n\n    local function match_table(t)\n        local keys = false\n        for k,v in next, t do\n            local tk = type(k)\n            if match[tk] then\n                keys = keys or {}\n                keys[#keys+1] = k\n            end\n\n            local nv = replace_map[v]\n            if nv then\n                nv = getnv(v)\n                rawset(t, k, nv)\n            else\n                match_value(v)\n            end\n        end\n\n        if keys then\n            for _, old_k in ipairs(keys) do\n                local new_k = replace_map[old_k]\n                if new_k then\n                    local value = rawget(t, old_k)\n                    new_k = getnv(old_k)\n                    rawset(t, old_k, nil)\n                    if new_k then\n                        rawset(t, new_k, value)\n                    end\n                else\n                    match_value(old_k)\n                end\n            end\n        end\n        return match_mt(t)\n    end\n\n    local function match_userdata(u)\n        local uv = getuservalue(u)\n        local nv = replace_map[uv]\n        if nv then\n            nv = getnv(uv)\n            setuservalue(u, nv)\n        end\n        return match_mt(u)\n    end\n\n    local function match_funcinfo(info)\n        local func = info.func\n        local nups = info.nups\n        for i=1,nups do\n            local name, upv = getupvalue(func, i)\n            local nv = replace_map[upv]\n            if nv then\n                nv = getnv(upv)\n                setupvalue(func, i, nv)\n            elseif upv then\n                match_value(upv)\n            end\n        end\n\n        local level = info.level\n        local curco = info.curco\n        if not level then\n            return\n        end\n        local i = 1\n        while true do\n            local name, v = getlocal(curco, level, i)\n            if name == nil then\n                break\n            end\n            if replace_map[v] then\n                local nv = getnv(v)\n                setlocal(curco, level, i, nv)\n            elseif v then\n                match_value(v)\n            end\n            i = i + 1\n        end\n    end\n\n    local function match_function(f)\n        local info = getinfo(f, \"uf\")\n        return match_funcinfo(info)\n    end\n\n    local function match_thread(co, level)\n        -- match stackvalues\n        local values = {}\n        local n = stackvalues(co, values)\n        for i=1,n do\n            local v = values[i]\n            match_value(v)\n        end\n\n        local uplevel = co == coroutine.running() and 1 or 0\n        level = level or 1\n        while true do\n            local info = getinfo(co, level, \"uf\")\n            if not info then\n                break\n            end\n            info.level = level + uplevel\n            info.curco = co\n            match_funcinfo(info)\n            level = level + 1\n        end\n    end\n\n    local function prepare_match()\n        local co = coroutine.running()\n        record_map[co] = true\n        record_map[match] = true\n        record_map[RECORD] = true\n        record_map[record_map] = true\n        record_map[replace_map] = true\n        record_map[insert_replace] = true\n        record_map[resolve_replace] = true\n        assert(getinfo(co, 3, \"f\").func == sharetable.update)\n        match_thread(co, 5) -- ignore match_thread and match_funcinfo frame\n    end\n\n    match[\"table\"] = match_table\n    match[\"function\"] = match_function\n    match[\"userdata\"] = match_userdata\n    match[\"thread\"] = match_thread\n\n    prepare_match()\n    match_internmt()\n\n    local root = debug.getregistry()\n    assert(replace_map[root] == nil)\n    match_table(root)\nend\n\n\nfunction sharetable.update(...)\n\tlocal names = {...}\n\tlocal replace_map = {}\n\tfor _, name in ipairs(names) do\n\t\tlocal map = RECORD[name]\n\t\tif map then\n\t\t\tlocal new_t = sharetable.query(name)\n\t\t\tfor old_t,_ in pairs(map) do\n\t\t\t\tif old_t ~= new_t then\n\t\t\t\t\tinsert_replace(old_t, new_t, replace_map)\n                    map[old_t] = nil\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\n    if next(replace_map) then\n        resolve_replace(replace_map)\n    end\nend\n\nreturn sharetable\n\n"
  },
  {
    "path": "lualib/skynet/snax.lua",
    "content": "local skynet = require \"skynet\"\nlocal snax_interface = require \"snax.interface\"\n\nlocal snax = {}\nlocal typeclass = {}\n\nlocal interface_g = skynet.getenv(\"snax_interface_g\")\nlocal G = interface_g and require (interface_g) or { require = function() end }\ninterface_g = nil\n\nskynet.register_protocol {\n\tname = \"snax\",\n\tid = skynet.PTYPE_SNAX,\n\tpack = skynet.pack,\n\tunpack = skynet.unpack,\n}\n\n\nfunction snax.interface(name)\n\tif typeclass[name] then\n\t\treturn typeclass[name]\n\tend\n\n\tlocal si = snax_interface(name, G)\n\n\tlocal ret = {\n\t\tname = name,\n\t\taccept = {},\n\t\tresponse = {},\n\t\tsystem = {},\n\t}\n\n\tfor _,v in ipairs(si) do\n\t\tlocal id, group, name, f = table.unpack(v)\n\t\tret[group][name] = id\n\tend\n\n\ttypeclass[name] = ret\n\treturn ret\nend\n\nlocal meta = { __tostring = function(v) return string.format(\"[%s:%x]\", v.type, v.handle) end}\n\nlocal skynet_send = skynet.send\nlocal skynet_call = skynet.call\n\nlocal function gen_post(type, handle)\n\treturn setmetatable({} , {\n\t\t__index = function( t, k )\n\t\t\tlocal id = type.accept[k]\n\t\t\tif not id then\n\t\t\t\terror(string.format(\"post %s:%s no exist\", type.name, k))\n\t\t\tend\n\t\t\treturn function(...)\n\t\t\t\tskynet_send(handle, \"snax\", id, ...)\n\t\t\tend\n\t\tend })\nend\n\nlocal function gen_req(type, handle)\n\treturn setmetatable({} , {\n\t\t__index = function( t, k )\n\t\t\tlocal id = type.response[k]\n\t\t\tif not id then\n\t\t\t\terror(string.format(\"request %s:%s no exist\", type.name, k))\n\t\t\tend\n\t\t\treturn function(...)\n\t\t\t\treturn skynet_call(handle, \"snax\", id, ...)\n\t\t\tend\n\t\tend })\nend\n\nlocal function wrapper(handle, name, type)\n\treturn setmetatable ({\n\t\tpost = gen_post(type, handle),\n\t\treq = gen_req(type, handle),\n\t\ttype = name,\n\t\thandle = handle,\n\t\t}, meta)\nend\n\nlocal handle_cache = setmetatable( {} , { __mode = \"kv\" } )\n\nfunction snax.rawnewservice(name, ...)\n\tlocal t = snax.interface(name)\n\tlocal handle = skynet.newservice(\"snaxd\", name)\n\tassert(handle_cache[handle] == nil)\n\tif t.system.init then\n\t\tskynet.call(handle, \"snax\", t.system.init, ...)\n\tend\n\treturn handle\nend\n\nfunction snax.bind(handle, type)\n\tlocal ret = handle_cache[handle]\n\tif ret then\n\t\tassert(ret.type == type)\n\t\treturn ret\n\tend\n\tlocal t = snax.interface(type)\n\tret = wrapper(handle, type, t)\n\thandle_cache[handle] = ret\n\treturn ret\nend\n\nfunction snax.newservice(name, ...)\n\tlocal handle = snax.rawnewservice(name, ...)\n\treturn snax.bind(handle, name)\nend\n\nfunction snax.uniqueservice(name, ...)\n\tlocal handle = assert(skynet.call(\".service\", \"lua\", \"LAUNCH\", \"snaxd\", name, ...))\n\treturn snax.bind(handle, name)\nend\n\nfunction snax.globalservice(name, ...)\n\tlocal handle = assert(skynet.call(\".service\", \"lua\", \"GLAUNCH\", \"snaxd\", name, ...))\n\treturn snax.bind(handle, name)\nend\n\nfunction snax.queryservice(name)\n\tlocal handle = assert(skynet.call(\".service\", \"lua\", \"QUERY\", \"snaxd\", name))\n\treturn snax.bind(handle, name)\nend\n\nfunction snax.queryglobal(name)\n\tlocal handle = assert(skynet.call(\".service\", \"lua\", \"GQUERY\", \"snaxd\", name))\n\treturn snax.bind(handle, name)\nend\n\nfunction snax.kill(obj, ...)\n\tlocal t = snax.interface(obj.type)\n\tskynet_call(obj.handle, \"snax\", t.system.exit, ...)\nend\n\nfunction snax.self()\n\treturn snax.bind(skynet.self(), SERVICE_NAME)\nend\n\nfunction snax.exit(...)\n\tsnax.kill(snax.self(), ...)\nend\n\nlocal function test_result(ok, ...)\n\tif ok then\n\t\treturn ...\n\telse\n\t\terror(...)\n\tend\nend\n\nfunction snax.hotfix(obj, source, ...)\n\tlocal t = snax.interface(obj.type)\n\treturn test_result(skynet_call(obj.handle, \"snax\", t.system.hotfix, source, ...))\nend\n\nfunction snax.printf(fmt, ...)\n\tskynet.error(string.format(fmt, ...))\nend\n\nfunction snax.profile_info(obj)\n\tlocal t = snax.interface(obj.type)\n\treturn skynet_call(obj.handle, \"snax\", t.system.profile)\nend\n\nreturn snax\n"
  },
  {
    "path": "lualib/skynet/socket.lua",
    "content": "local driver = require \"skynet.socketdriver\"\nlocal skynet = require \"skynet\"\nlocal skynet_core = require \"skynet.core\"\nlocal assert = assert\n\nlocal BUFFER_LIMIT = 128 * 1024\nlocal socket = {}\t-- api\nlocal socket_pool = setmetatable( -- store all socket object\n\t{},\n\t{ __gc = function(p)\n\t\tfor id,v in pairs(p) do\n\t\t\tdriver.close(id)\n\t\t\tp[id] = nil\n\t\tend\n\tend\n\t}\n)\n\nlocal socket_onclose = {}\nlocal socket_message = {}\n\nlocal function wakeup(s)\n\tlocal co = s.co\n\tif co then\n\t\ts.co = nil\n\t\tskynet.wakeup(co)\n\tend\nend\n\nlocal function pause_socket(s, size)\n\tif s.pause ~= nil then\n\t\treturn\n\tend\n\tif size then\n\t\tskynet.error(string.format(\"Pause socket (%d) size : %d\" , s.id, size))\n\telse\n\t\tskynet.error(string.format(\"Pause socket (%d)\" , s.id))\n\tend\n\tdriver.pause(s.id)\n\ts.pause = true\n\tskynet.yield()\t-- there are subsequent socket messages in mqueue, maybe.\nend\n\nlocal function suspend(s)\n\tassert(not s.co)\n\ts.co = coroutine.running()\n\tif s.pause then\n\t\tskynet.error(string.format(\"Resume socket (%d)\", s.id))\n\t\tdriver.start(s.id)\n\t\tskynet.wait(s.co)\n\t\ts.pause = nil\n\telse\n\t\tskynet.wait(s.co)\n\tend\n\t-- wakeup closing corouting every time suspend,\n\t-- because socket.close() will wait last socket buffer operation before clear the buffer.\n\tif s.closing then\n\t\tskynet.wakeup(s.closing)\n\tend\nend\n\n-- read skynet_socket.h for these macro\n-- SKYNET_SOCKET_TYPE_DATA = 1\nsocket_message[1] = function(id, size, data)\n\tlocal s = socket_pool[id]\n\tif s == nil then\n\t\tskynet.error(\"socket: drop package from \" .. id)\n\t\tdriver.drop(data, size)\n\t\treturn\n\tend\n\n\tlocal sz = driver.push(s.buffer, s.pool, data, size)\n\tlocal rr = s.read_required\n\tlocal rrt = type(rr)\n\tif rrt == \"number\" then\n\t\t-- read size\n\t\tif sz >= rr then\n\t\t\ts.read_required = nil\n\t\t\tif sz > BUFFER_LIMIT then\n\t\t\t\tpause_socket(s, sz)\n\t\t\tend\n\t\t\twakeup(s)\n\t\tend\n\telse\n\t\tif s.buffer_limit and sz > s.buffer_limit then\n\t\t\tskynet.error(string.format(\"socket buffer overflow: fd=%d size=%d\", id , sz))\n\t\t\tdriver.close(id)\n\t\t\treturn\n\t\tend\n\t\tif rrt == \"string\" then\n\t\t\t-- read line\n\t\t\tif driver.readline(s.buffer,nil,rr) then\n\t\t\t\ts.read_required = nil\n\t\t\t\tif sz > BUFFER_LIMIT then\n\t\t\t\t\tpause_socket(s, sz)\n\t\t\t\tend\n\t\t\t\twakeup(s)\n\t\t\tend\n\t\telseif sz > BUFFER_LIMIT and not s.pause then\n\t\t\tpause_socket(s, sz)\n\t\tend\n\tend\nend\n\n-- SKYNET_SOCKET_TYPE_CONNECT = 2\nsocket_message[2] = function(id, ud , addr)\n\tlocal s = socket_pool[id]\n\tif s == nil then\n\t\treturn\n\tend\n\t-- log remote addr\n\tif not s.connected then\t-- resume may also post connect message\n\t\tif s.listen then\n\t\t\ts.addr = addr\n\t\t\ts.port = ud\n\t\tend\n\t\ts.connected = true\n\t\twakeup(s)\n\tend\nend\n\n-- SKYNET_SOCKET_TYPE_CLOSE = 3\nsocket_message[3] = function(id)\n\tlocal s = socket_pool[id]\n\tif s then\n\t\ts.connected = false\n\t\twakeup(s)\n\telse\n\t\tdriver.close(id)\n\tend\n\tlocal cb = socket_onclose[id]\n\tif cb then\n\t\tcb(id)\n\t\tsocket_onclose[id] = nil\n\tend\nend\n\n-- SKYNET_SOCKET_TYPE_ACCEPT = 4\nsocket_message[4] = function(id, newid, addr)\n\tlocal s = socket_pool[id]\n\tif s == nil then\n\t\tdriver.close(newid)\n\t\treturn\n\tend\n\ts.callback(newid, addr)\nend\n\n-- SKYNET_SOCKET_TYPE_ERROR = 5\nsocket_message[5] = function(id, _, err)\n\tlocal s = socket_pool[id]\n\tif s == nil then\n\t\tdriver.shutdown(id)\n\t\tskynet.error(\"socket: error on unknown\", id, err)\n\t\treturn\n\tend\n\tif s.callback then\n\t\tskynet.error(\"socket: accept error:\", err)\n\t\treturn\n\tend\n\tif s.connected then\n\t\tskynet.error(\"socket: error on\", id, err)\n\telseif s.connecting then\n\t\ts.connecting = err\n\tend\n\ts.connected = false\n\tdriver.shutdown(id)\n\n\twakeup(s)\nend\n\n-- SKYNET_SOCKET_TYPE_UDP = 6\nsocket_message[6] = function(id, size, data, address)\n\tlocal s = socket_pool[id]\n\tif s == nil or s.callback == nil then\n\t\tskynet.error(\"socket: drop udp package from \" .. id)\n\t\tdriver.drop(data, size)\n\t\treturn\n\tend\n\tlocal str = skynet.tostring(data, size)\n\tskynet_core.trash(data, size)\n\ts.callback(str, address)\nend\n\nlocal function default_warning(id, size)\n\tlocal s = socket_pool[id]\n\tif not s then\n\t\treturn\n\tend\n\tskynet.error(string.format(\"WARNING: %d K bytes need to send out (fd = %d)\", size, id))\nend\n\n-- SKYNET_SOCKET_TYPE_WARNING\nsocket_message[7] = function(id, size)\n\tlocal s = socket_pool[id]\n\tif s then\n\t\tlocal warning = s.on_warning or default_warning\n\t\twarning(id, size)\n\tend\nend\n\nskynet.register_protocol {\n\tname = \"socket\",\n\tid = skynet.PTYPE_SOCKET,\t-- PTYPE_SOCKET = 6\n\tunpack = driver.unpack,\n\tdispatch = function (_, _, t, ...)\n\t\tsocket_message[t](...)\n\tend\n}\n\nlocal function connect(id, func)\n\tlocal newbuffer\n\tif func == nil then\n\t\tnewbuffer = driver.buffer()\n\tend\n\tlocal s = {\n\t\tid = id,\n\t\tbuffer = newbuffer,\n\t\tpool = newbuffer and {},\n\t\tconnected = false,\n\t\tconnecting = true,\n\t\tread_required = false,\n\t\tco = false,\n\t\tcallback = func,\n\t\tprotocol = \"TCP\",\n\t}\n\tassert(not socket_onclose[id], \"socket has onclose callback\")\n\tlocal s2 = socket_pool[id]\n\tif s2 and not s2.listen then\n\t\terror(\"socket is not closed\")\n\tend\n\tsocket_pool[id] = s\n\tsuspend(s)\n\tlocal err = s.connecting\n\ts.connecting = nil\n\tif s.connected then\n\t\treturn id\n\telse\n\t\tsocket_pool[id] = nil\n\t\treturn nil, err\n\tend\nend\n\nfunction socket.open(addr, port)\n\tlocal id = driver.connect(addr,port)\n\treturn connect(id)\nend\n\nfunction socket.bind(os_fd)\n\tlocal id = driver.bind(os_fd)\n\treturn connect(id)\nend\n\nfunction socket.stdin()\n\treturn socket.bind(0)\nend\n\nfunction socket.start(id, func)\n\tdriver.start(id)\n\treturn connect(id, func)\nend\n\nfunction socket.pause(id)\n\tlocal s = socket_pool[id]\n\tif s == nil then\n\t\treturn\n\tend\n\tpause_socket(s)\nend\n\nfunction socket.shutdown(id)\n\tlocal s = socket_pool[id]\n\tif s then\n\t\t-- the framework would send SKYNET_SOCKET_TYPE_CLOSE , need close(id) later\n\t\tdriver.shutdown(id)\n\tend\nend\n\nfunction socket.close_fd(id)\n\tassert(socket_pool[id] == nil,\"Use socket.close instead\")\n\tdriver.close(id)\nend\n\nfunction socket.close(id)\n\tlocal s = socket_pool[id]\n\tif s == nil then\n\t\treturn\n\tend\n\tdriver.close(id)\n\tif s.connected then\n\t\ts.pause = false -- Do not resume this fd if it paused.\n\t\tif s.co then\n\t\t\t-- reading this socket on another coroutine, so don't shutdown (clear the buffer) immediately\n\t\t\t-- wait reading coroutine read the buffer.\n\t\t\tassert(not s.closing)\n\t\t\ts.closing = coroutine.running()\n\t\t\tskynet.wait(s.closing)\n\t\telse\n\t\t\tsuspend(s)\n\t\tend\n\t\ts.connected = false\n\tend\n\tsocket_pool[id] = nil\nend\n\nfunction socket.read(id, sz)\n\tlocal s = socket_pool[id]\n\tassert(s)\n\tif sz == nil then\n\t\t-- read some bytes\n\t\tlocal ret = driver.readall(s.buffer, s.pool)\n\t\tif ret ~= \"\" then\n\t\t\treturn ret\n\t\tend\n\n\t\tif not s.connected then\n\t\t\treturn false, ret\n\t\tend\n\t\tassert(not s.read_required)\n\t\ts.read_required = 0\n\t\tsuspend(s)\n\t\tret = driver.readall(s.buffer, s.pool)\n\t\tif ret ~= \"\" then\n\t\t\treturn ret\n\t\telse\n\t\t\treturn false, ret\n\t\tend\n\tend\n\n\tlocal ret = driver.pop(s.buffer, s.pool, sz)\n\tif ret then\n\t\treturn ret\n\tend\n\tif s.closing or not s.connected then\n\t\treturn false, driver.readall(s.buffer, s.pool)\n\tend\n\n\tassert(not s.read_required)\n\ts.read_required = sz\n\tsuspend(s)\n\tret = driver.pop(s.buffer, s.pool, sz)\n\tif ret then\n\t\treturn ret\n\telse\n\t\treturn false, driver.readall(s.buffer, s.pool)\n\tend\nend\n\nfunction socket.readall(id)\n\tlocal s = socket_pool[id]\n\tassert(s)\n\tif not s.connected then\n\t\tlocal r = driver.readall(s.buffer, s.pool)\n\t\treturn r ~= \"\" and r\n\tend\n\tassert(not s.read_required)\n\ts.read_required = true\n\tsuspend(s)\n\tassert(s.connected == false)\n\treturn driver.readall(s.buffer, s.pool)\nend\n\nfunction socket.readline(id, sep)\n\tsep = sep or \"\\n\"\n\tlocal s = socket_pool[id]\n\tassert(s)\n\tlocal ret = driver.readline(s.buffer, s.pool, sep)\n\tif ret then\n\t\treturn ret\n\tend\n\tif not s.connected then\n\t\treturn false, driver.readall(s.buffer, s.pool)\n\tend\n\tassert(not s.read_required)\n\ts.read_required = sep\n\tsuspend(s)\n\tif s.connected then\n\t\treturn driver.readline(s.buffer, s.pool, sep)\n\telse\n\t\treturn false, driver.readall(s.buffer, s.pool)\n\tend\nend\n\nfunction socket.block(id)\n\tlocal s = socket_pool[id]\n\tif not s or not s.connected then\n\t\treturn false\n\tend\n\tassert(not s.read_required)\n\ts.read_required = 0\n\tsuspend(s)\n\treturn s.connected\nend\n\nsocket.write = assert(driver.send)\nsocket.lwrite = assert(driver.lsend)\nsocket.header = assert(driver.header)\n\nfunction socket.invalid(id)\n\treturn socket_pool[id] == nil\nend\n\nfunction socket.disconnected(id)\n\tlocal s = socket_pool[id]\n\tif s then\n\t\treturn not(s.connected or s.connecting)\n\tend\nend\n\nfunction socket.listen(host, port, backlog)\n\tlocal id = driver.listen(host, port, backlog)\n\tlocal s = {\n\t\tid = id,\n\t\tconnected = false,\n\t\tlisten = true,\n\t}\n\tassert(socket_pool[id] == nil)\n\tsocket_pool[id] = s\n\tsuspend(s)\n\treturn id, s.addr, s.port\nend\n\n-- abandon use to forward socket id to other service\n-- you must call socket.start(id) later in other service\nfunction socket.abandon(id)\n\tlocal s = socket_pool[id]\n\tif s then\n\t\ts.connected = false\n\t\twakeup(s)\n\t\tsocket_onclose[id] = nil\n\t\tsocket_pool[id] = nil\n\tend\nend\n\nfunction socket.limit(id, limit)\n\tlocal s = assert(socket_pool[id])\n\ts.buffer_limit = limit\nend\n\n---------------------- UDP\n\nlocal function create_udp_object(id, cb)\n\tassert(not socket_pool[id], \"socket is not closed\")\n\tsocket_pool[id] = {\n\t\tid = id,\n\t\tconnected = true,\n\t\tprotocol = \"UDP\",\n\t\tcallback = cb,\n\t}\nend\n\nfunction socket.udp(callback, host, port)\n\tlocal id = driver.udp(host, port)\n\tcreate_udp_object(id, callback)\n\treturn id\nend\n\nfunction socket.udp_connect(id, addr, port, callback)\n\tlocal obj = socket_pool[id]\n\tif obj then\n\t\tassert(obj.protocol == \"UDP\")\n\t\tif callback then\n\t\t\tobj.callback = callback\n\t\tend\n\telse\n\t\tcreate_udp_object(id, callback)\n\tend\n\tdriver.udp_connect(id, addr, port)\nend\n\nfunction socket.udp_listen(addr, port, callback)\n\tlocal id = driver.udp_listen(addr, port)\n\tcreate_udp_object(id, callback)\n\treturn id\nend\n\nfunction socket.udp_dial(addr, port, callback)\n\tlocal id = driver.udp_dial(addr, port)\n\tcreate_udp_object(id, callback)\n\treturn id\nend\n\nsocket.sendto = assert(driver.udp_send)\nsocket.udp_address = assert(driver.udp_address)\nsocket.netstat = assert(driver.info)\nsocket.resolve = assert(driver.resolve)\n\nfunction socket.warning(id, callback)\n\tlocal obj = socket_pool[id]\n\tassert(obj)\n\tobj.on_warning = callback\nend\n\nfunction socket.onclose(id, callback)\n\tsocket_onclose[id] = callback\nend\n\nreturn socket\n"
  },
  {
    "path": "lualib/skynet/socketchannel.lua",
    "content": "local skynet = require \"skynet\"\nlocal socket = require \"skynet.socket\"\nlocal socketdriver = require \"skynet.socketdriver\"\n\n-- channel support auto reconnect , and capture socket error in request/response transaction\n-- { host = \"\", port = , auth = function(so) , response = function(so) session, data }\n\nlocal socket_channel = {}\nlocal channel = {}\nlocal channel_socket = {}\nlocal channel_meta = { __index = channel }\nlocal channel_socket_meta = {\n\t__index = channel_socket,\n\t__gc = function(cs)\n\t\tlocal fd = cs[1]\n\t\tcs[1] = false\n\t\tif fd then\n\t\t\tsocket.shutdown(fd)\n\t\tend\n\tend\n}\n\nlocal socket_error = setmetatable({}, {__tostring = function() return \"[Error: socket]\" end })\t-- alias for error object\nsocket_channel.error = socket_error\n\nfunction socket_channel.channel(desc)\n\tlocal c = {\n\t\t__host = assert(desc.host),\n\t\t__port = desc.port,\n\t\t__backup = desc.backup,\n\t\t__auth = desc.auth,\n\t\t__response = desc.response,\t-- It's for session mode\n\t\t__request = {},\t-- request seq { response func or session }\t-- It's for order mode\n\t\t__thread = {}, -- coroutine seq or session->coroutine map\n\t\t__result = {}, -- response result { coroutine -> result }\n\t\t__result_data = {},\n\t\t__connecting = {},\n\t\t__sock = false,\n\t\t__closed = false,\n\t\t__authcoroutine = false,\n\t\t__nodelay = desc.nodelay,\n\t\t__overload_notify = desc.overload,\n\t\t__overload = false,\n\t\t__socket_meta = channel_socket_meta,\n\t}\n\tif desc.socket_read or desc.socket_readline then\n\t\tc.__socket_meta = {\n\t\t\t__index = {\n\t\t\t\tread = desc.socket_read or channel_socket.read,\n\t\t\t\treadline = desc.socket_readline or channel_socket.readline,\n\t\t\t},\n\t\t\t__gc = channel_socket_meta.__gc\n\t\t}\n\tend\n\n\treturn setmetatable(c, channel_meta)\nend\n\nlocal function close_channel_socket(self)\n\tif self.__sock then\n\t\tlocal so = self.__sock\n\t\tself.__sock = false\n\t\tif self.__wait_response then\n\t\t\tskynet.wakeup(self.__wait_response)\n\t\t\tself.__wait_response = nil\n\t\tend\n\t\t-- never raise error\n\t\tpcall(socket.close,so[1])\n\tend\nend\n\nlocal function wakeup_all(self, errmsg)\n\tif self.__response then\n\t\tfor k,co in pairs(self.__thread) do\n\t\t\tself.__thread[k] = nil\n\t\t\tself.__result[co] = socket_error\n\t\t\tself.__result_data[co] = errmsg\n\t\t\tskynet.wakeup(co)\n\t\tend\n\telse\n\t\tfor i = 1, #self.__request do\n\t\t\tself.__request[i] = nil\n\t\tend\n\t\tfor i = 1, #self.__thread do\n\t\t\tlocal co = self.__thread[i]\n\t\t\tself.__thread[i] = nil\n\t\t\tif co then\t-- ignore the close signal\n\t\t\t\tself.__result[co] = socket_error\n\t\t\t\tself.__result_data[co] = errmsg\n\t\t\t\tskynet.wakeup(co)\n\t\t\tend\n\t\tend\n\tend\nend\n\nlocal function dispatch_by_session(self)\n\tlocal response = self.__response\n\t-- response() return session\n\twhile self.__sock do\n\t\tlocal ok , session, result_ok, result_data, padding = pcall(response, self.__sock)\n\t\tif ok and session then\n\t\t\tlocal co = self.__thread[session]\n\t\t\tif co then\n\t\t\t\tif padding and result_ok then\n\t\t\t\t\t-- If padding is true, append result_data to a table (self.__result_data[co])\n\t\t\t\t\tlocal result = self.__result_data[co] or {}\n\t\t\t\t\tself.__result_data[co] = result\n\t\t\t\t\ttable.insert(result, result_data)\n\t\t\t\telse\n\t\t\t\t\tself.__thread[session] = nil\n\t\t\t\t\tself.__result[co] = result_ok\n\t\t\t\t\tif result_ok and self.__result_data[co] then\n\t\t\t\t\t\ttable.insert(self.__result_data[co], result_data)\n\t\t\t\t\telse\n\t\t\t\t\t\tself.__result_data[co] = result_data\n\t\t\t\t\tend\n\t\t\t\t\tskynet.wakeup(co)\n\t\t\t\tend\n\t\t\t\tif not self.__sock then\n\t\t\t\t\t-- closed\n\t\t\t\t\twakeup_all(self, \"channel_closed\")\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tself.__thread[session] = nil\n\t\t\t\tskynet.error(\"socket: unknown session :\", session)\n\t\t\tend\n\t\telse\n\t\t\tclose_channel_socket(self)\n\t\t\tlocal errormsg\n\t\t\tif session ~= socket_error then\n\t\t\t\terrormsg = session\n\t\t\tend\n\t\t\twakeup_all(self, errormsg)\n\t\tend\n\tend\nend\n\nlocal function pop_response(self)\n\twhile self.__sock do\n\t\tlocal func,co = table.remove(self.__request, 1), table.remove(self.__thread, 1)\n\t\tif func then\n\t\t\treturn func, co\n\t\tend\n\t\tself.__wait_response = coroutine.running()\n\t\tskynet.wait(self.__wait_response)\n\tend\nend\n\n-- on close callback\nlocal function autoclose_cb(self, fd)\n\tlocal sock = self.__sock\n\tif self.__wait_response and sock and sock[1] == fd then\n\t\t-- closed by peer\n\t\tskynet.error(\"socket closed by peer : \", self.__host, self.__port)\n\t\tclose_channel_socket(self)\n\tend\nend\n\nlocal function push_response(self, response, co)\n\tif self.__response then\n\t\t-- response is session\n\t\tself.__thread[response] = co\n\telse\n\t\t-- response is a function, push it to __request\n\t\ttable.insert(self.__request, response)\n\t\ttable.insert(self.__thread, co)\n\t\tif self.__wait_response then\n\t\t\tskynet.wakeup(self.__wait_response)\n\t\t\tself.__wait_response = nil\n\t\tend\n\tend\nend\n\nlocal function get_response(func, sock)\n\tlocal result_ok, result_data, padding = func(sock)\n\tif result_ok and padding then\n\t\tlocal result = { result_data }\n\t\tlocal index = 2\n\t\trepeat\n\t\t\tresult_ok, result_data, padding = func(sock)\n\t\t\tif not result_ok then\n\t\t\t\treturn result_ok, result_data\n\t\t\tend\n\t\t\tresult[index] = result_data\n\t\t\tindex = index + 1\n\t\tuntil not padding\n\t\treturn true, result\n\telse\n\t\treturn result_ok, result_data\n\tend\nend\n\nlocal function dispatch_by_order(self)\n\twhile self.__sock do\n\t\tlocal func, co = pop_response(self)\n\t\tif not co then\n\t\t\t-- close signal\n\t\t\twakeup_all(self, \"channel_closed\")\n\t\t\tbreak\n\t\tend\n\t\tlocal sock = self.__sock\n\t\tif not sock then\n\t\t\t-- closed by peer\n\t\t\tself.__result[co] = socket_error\n\t\t\tskynet.wakeup(co)\n\t\t\twakeup_all(self)\n\t\t\tbreak\n\t\tend\n\t\tlocal ok, result_ok, result_data = pcall(get_response, func, sock)\n\t\tif ok then\n\t\t\tself.__result[co] = result_ok\n\t\t\tif result_ok and self.__result_data[co] then\n\t\t\t\ttable.insert(self.__result_data[co], result_data)\n\t\t\telse\n\t\t\t\tself.__result_data[co] = result_data\n\t\t\tend\n\t\t\tskynet.wakeup(co)\n\t\t\tif not self.__sock then\n\t\t\t\t-- closed\n\t\t\t\twakeup_all(self, \"channel_closed\")\n\t\t\t\tbreak\n\t\t\tend\n\t\telse\n\t\t\tclose_channel_socket(self)\n\t\t\tlocal errmsg\n\t\t\tif result_ok ~= socket_error then\n\t\t\t\terrmsg = result_ok\n\t\t\tend\n\t\t\tself.__result[co] = socket_error\n\t\t\tself.__result_data[co] = errmsg\n\t\t\tskynet.wakeup(co)\n\t\t\twakeup_all(self, errmsg)\n\t\tend\n\tend\nend\n\nlocal function dispatch_function(self)\n\tif self.__response then\n\t\treturn dispatch_by_session\n\telse\n\t\tsocket.onclose(self.__sock[1], function(fd)\n\t\t\tautoclose_cb(self, fd)\n\t\tend)\n\t\treturn dispatch_by_order\n\tend\nend\n\nlocal function term_dispatch_thread(self)\n\tif not self.__response and self.__dispatch_thread then\n\t\t-- dispatch by order, send close signal to dispatch thread\n\t\tpush_response(self, true, false)\t-- (true, false) is close signal\n\tend\nend\n\nlocal function connect_once(self)\n\tif self.__closed then\n\t\treturn false\n\tend\n\n\tlocal addr_list = {}\n\tlocal addr_set = {}\n\n\tlocal function _add_backup()\n\t\tif self.__backup then\n\t\t\tfor _, addr in ipairs(self.__backup) do\n\t\t\t\tlocal host, port\n\t\t\t\tif type(addr) == \"table\" then\n\t\t\t\t\thost,port = addr.host, addr.port\n\t\t\t\telse\n\t\t\t\t\thost = addr\n\t\t\t\t\tport = self.__port\n\t\t\t\tend\n\n\t\t\t\t-- don't add the same host\n\t\t\t\tlocal hostkey = host..\":\"..port\n\t\t\t\tif not addr_set[hostkey] then\n\t\t\t\t\taddr_set[hostkey] = true\n\t\t\t\t\ttable.insert(addr_list, { host = host, port = port })\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\n\tlocal function _next_addr()\n\t\tlocal addr =  table.remove(addr_list,1)\n\t\tif addr then\n\t\t\tskynet.error(\"socket: connect to backup host\", addr.host, addr.port)\n\t\tend\n\t\treturn addr\n\tend\n\n\tlocal function _connect_once(self, addr)\n\t\tlocal fd,err = socket.open(addr.host, addr.port)\n\t\tif not fd then\n\t\t\t-- try next one\n\t\t\taddr = _next_addr()\n\t\t\tif addr == nil then\n\t\t\t\treturn false, err\n\t\t\tend\n\t\t\treturn _connect_once(self, addr)\n\t\tend\n\n\t\tself.__host = addr.host\n\t\tself.__port = addr.port\n\n\t\tassert(not self.__sock and not self.__authcoroutine)\n\t\t-- term current dispatch thread (send a signal)\n\t\tterm_dispatch_thread(self)\n\n\t\tif self.__nodelay then\n\t\t\tsocketdriver.nodelay(fd)\n\t\tend\n\n\t\t-- register overload warning\n\n\t\tlocal overload = self.__overload_notify\n\t\tif overload then\n\t\t\tlocal function overload_trigger(id, size)\n\t\t\t\tif id == self.__sock[1] then\n\t\t\t\t\tif size == 0 then\n\t\t\t\t\t\tif self.__overload then\n\t\t\t\t\t\t\tself.__overload = false\n\t\t\t\t\t\t\toverload(false)\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\tif not self.__overload then\n\t\t\t\t\t\t\tself.__overload = true\n\t\t\t\t\t\t\toverload(true)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tskynet.error(string.format(\"WARNING: %d K bytes need to send out (fd = %d)\", size, id), self.__host, self.__port)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tskynet.fork(overload_trigger, fd, 0)\n\t\t\tsocket.warning(fd, overload_trigger)\n\t\tend\n\n\t\twhile self.__dispatch_thread do\n\t\t\t-- wait for dispatch thread exit\n\t\t\tskynet.yield()\n\t\tend\n\n\t\tself.__sock = setmetatable( {fd} , self.__socket_meta )\n\t\tself.__dispatch_thread = skynet.fork(function()\n\t\t\tif self.__sock then\n\t\t\t\t-- self.__sock can be false (socket closed) if error during connecting, See #1513\n\t\t\t\tpcall(dispatch_function(self), self)\n\t\t\tend\n\t\t\t-- clear dispatch_thread\n\t\t\tself.__dispatch_thread = nil\n\t\tend)\n\n\t\tif self.__auth then\n\t\t\tself.__authcoroutine = coroutine.running()\n\t\t\tlocal ok , message = pcall(self.__auth, self)\n\t\t\tif not ok then\n\t\t\t\tclose_channel_socket(self)\n\t\t\t\tif message ~= socket_error then\n\t\t\t\t\tself.__authcoroutine = false\n\t\t\t\t\tskynet.error(\"socket: auth failed\", message)\n\t\t\t\tend\n\t\t\tend\n\t\t\tself.__authcoroutine = false\n\t\t\tif ok then\n\t\t\t\tif not self.__sock then\n\t\t\t\t\t-- auth may change host, so connect again\n\t\t\t\t\treturn connect_once(self)\n\t\t\t\tend\n\t\t\t\t-- auth succ, go through\n\t\t\telse\n\t\t\t\t-- auth failed, try next addr\n\t\t\t\t_add_backup()\t-- auth may add new backup hosts\n\t\t\t\taddr = _next_addr()\n\t\t\t\tif addr == nil then\n\t\t\t\t\treturn false, \"no more backup host\"\n\t\t\t\tend\n\t\t\t\treturn _connect_once(self, addr)\n\t\t\tend\n\t\tend\n\n\t\treturn true\n\tend\n\n\t_add_backup()\n\treturn _connect_once(self, { host = self.__host, port = self.__port })\nend\n\nlocal function try_connect(self , once)\n\tlocal t = 0\n\twhile not self.__closed do\n\t\tlocal ok, err = connect_once(self)\n\t\tif ok then\n\t\t\tif not once then\n\t\t\t\tskynet.error(\"socket: connect to\", self.__host, self.__port)\n\t\t\tend\n\t\t\treturn\n\t\telseif once then\n\t\t\treturn err\n\t\telse\n\t\t\tskynet.error(\"socket: connect\", err)\n\t\tend\n\t\tif t > 1000 then\n\t\t\tskynet.error(\"socket: try to reconnect\", self.__host, self.__port)\n\t\t\tskynet.sleep(t)\n\t\t\tt = 0\n\t\telse\n\t\t\tskynet.sleep(t)\n\t\tend\n\t\tt = t + 100\n\tend\nend\n\nlocal function check_connection(self)\n\tif self.__sock then\n\t\tlocal authco = self.__authcoroutine\n\t\tif socket.disconnected(self.__sock[1]) then\n\t\t\t-- closed by peer\n\t\t\tskynet.error(\"socket: disconnect detected \", self.__host, self.__port)\n\t\t\tclose_channel_socket(self)\n\t\t\tif authco and authco == coroutine.running() then\n\t\t\t\t-- disconnected during auth, See #1513\n\t\t\t\treturn false\n\t\t\tend\n\t\t\treturn\n\t\tend\n\t\tif not authco then\n\t\t\treturn true\n\t\tend\n\t\tif authco == coroutine.running() then\n\t\t\t-- authing\n\t\t\treturn true\n\t\tend\n\tend\n\tif self.__closed then\n\t\treturn false\n\tend\nend\n\nlocal function block_connect(self, once)\n\tlocal r = check_connection(self)\n\tif r ~= nil then\n\t\treturn r\n\tend\n\tlocal err\n\n\tif #self.__connecting > 0 then\n\t\t-- connecting in other coroutine\n\t\tlocal co = coroutine.running()\n\t\ttable.insert(self.__connecting, co)\n\t\tskynet.wait(co)\n\telse\n\t\tself.__connecting[1] = true\n\t\terr = try_connect(self, once)\n\t\tfor i=2, #self.__connecting do\n\t\t\tlocal co = self.__connecting[i]\n\t\t\tself.__connecting[i] = nil\n\t\t\tskynet.wakeup(co)\n\t\tend\n\t\tself.__connecting[1] = nil\n\tend\n\n\tr = check_connection(self)\n\tif r == nil then\n\t\tskynet.error(\"Connect failed\", err, self.__host, self.__port)\n\t\terror(socket_error)\n\telse\n\t\treturn r\n\tend\nend\n\nfunction channel:connect(once)\n\tself.__closed = false\n\treturn block_connect(self, once)\nend\n\nlocal function wait_for_response(self, response)\n\tlocal co = coroutine.running()\n\tpush_response(self, response, co)\n\tskynet.wait(co)\n\n\tlocal result = self.__result[co]\n\tself.__result[co] = nil\n\tlocal result_data = self.__result_data[co]\n\tself.__result_data[co] = nil\n\n\tif result == socket_error then\n\t\tif result_data then\n\t\t\terror(result_data)\n\t\telse\n\t\t\terror(socket_error)\n\t\tend\n\telse\n\t\tassert(result, result_data)\n\t\treturn result_data\n\tend\nend\n\nlocal socket_write = socket.write\nlocal socket_lwrite = socket.lwrite\n\nlocal function sock_err(self)\n\tclose_channel_socket(self)\n\twakeup_all(self)\n\terror(socket_error)\nend\n\nfunction channel:request(request, response, padding)\n\tassert(block_connect(self, true))\t-- connect once\n\tlocal fd = self.__sock[1]\n\n\tif padding then\n\t\t-- padding may be a table, to support multi part request\n\t\t-- multi part request use low priority socket write\n\t\t-- now socket_lwrite returns as socket_write\n\t\tif not socket_lwrite(fd , request) then\n\t\t\tsock_err(self)\n\t\tend\n\t\tfor _,v in ipairs(padding) do\n\t\t\tif not socket_lwrite(fd, v) then\n\t\t\t\tsock_err(self)\n\t\t\tend\n\t\tend\n\telse\n\t\tif not socket_write(fd , request) then\n\t\t\tsock_err(self)\n\t\tend\n\tend\n\n\tif response == nil then\n\t\t-- no response\n\t\treturn\n\tend\n\n\treturn wait_for_response(self, response)\nend\n\nfunction channel:response(response)\n\tassert(block_connect(self))\n\n\treturn wait_for_response(self, response)\nend\n\nfunction channel:close()\n\tif not self.__closed then\n\t\tterm_dispatch_thread(self)\n\t\tself.__closed = true\n\t\tclose_channel_socket(self)\n\tend\nend\n\nfunction channel:changehost(host, port)\n\tself.__host = host\n    if port then\n\t\tself.__port = port\n    end\n\tif not self.__closed then\n\t\tclose_channel_socket(self)\n\tend\nend\n\nfunction channel:changebackup(backup)\n\tself.__backup = backup\nend\n\nchannel_meta.__gc = channel.close\n\nlocal function wrapper_socket_function(f)\n\treturn function(self, ...)\n\t\tlocal result = f(self[1], ...)\n\t\tif not result then\n\t\t\terror(socket_error)\n\t\telse\n\t\t\treturn result\n\t\tend\n\tend\nend\n\nchannel_socket.read = wrapper_socket_function(socket.read)\nchannel_socket.readline = wrapper_socket_function(socket.readline)\n\nreturn socket_channel\n"
  },
  {
    "path": "lualib/skynet.lua",
    "content": "-- read https://github.com/cloudwu/skynet/wiki/FAQ for the module \"skynet.core\"\nlocal c = require \"skynet.core\"\nlocal skynet_require = require \"skynet.require\"\nlocal tostring = tostring\nlocal coroutine = coroutine\nlocal assert = assert\nlocal error = error\nlocal pairs = pairs\nlocal pcall = pcall\nlocal table = table\nlocal next = next\nlocal tremove = table.remove\nlocal tinsert = table.insert\nlocal tpack = table.pack\nlocal tunpack = table.unpack\nlocal traceback = debug.traceback\n\nlocal cresume = coroutine.resume\nlocal running_thread = nil\nlocal init_thread = nil\n\nlocal function coroutine_resume(co, ...)\n\trunning_thread = co\n\treturn cresume(co, ...)\nend\nlocal coroutine_yield = coroutine.yield\nlocal coroutine_create = coroutine.create\n\nlocal proto = {}\nlocal skynet = {\n\t-- read skynet.h\n\tPTYPE_TEXT = 0,\n\tPTYPE_RESPONSE = 1,\n\tPTYPE_MULTICAST = 2,\n\tPTYPE_CLIENT = 3,\n\tPTYPE_SYSTEM = 4,\n\tPTYPE_HARBOR = 5,\n\tPTYPE_SOCKET = 6,\n\tPTYPE_ERROR = 7,\n\tPTYPE_QUEUE = 8,\t-- used in deprecated mqueue, use skynet.queue instead\n\tPTYPE_DEBUG = 9,\n\tPTYPE_LUA = 10,\n\tPTYPE_SNAX = 11,\n\tPTYPE_TRACE = 12,\t-- use for debug trace\n}\n\n-- code cache\nskynet.cache = require \"skynet.codecache\"\nskynet._proto = proto\n\nfunction skynet.register_protocol(class)\n\tlocal name = class.name\n\tlocal id = class.id\n\tassert(proto[name] == nil and proto[id] == nil)\n\tassert(type(name) == \"string\" and type(id) == \"number\" and id >=0 and id <=255)\n\tproto[name] = class\n\tproto[id] = class\nend\n\nlocal session_id_coroutine = {}\nlocal session_coroutine_id = {}\nlocal session_coroutine_address = {}\nlocal session_coroutine_tracetag = {}\nlocal unresponse = {}\n\nlocal wakeup_queue = {}\nlocal sleep_session = {}\n\nlocal watching_session = {}\nlocal error_queue = {}\nlocal fork_queue = { h = 1, t = 0 }\n\nlocal auxsend, auxtimeout, auxwait\ndo ---- avoid session rewind conflict\n\tlocal csend = c.send\n\tlocal cintcommand = c.intcommand\n\tlocal dangerzone\n\tlocal dangerzone_size = 0x1000\n\tlocal dangerzone_low = 0x70000000\n\tlocal dangerzone_up\t= dangerzone_low + dangerzone_size\n\n\tlocal set_checkrewind\t-- set auxsend and auxtimeout for safezone\n\tlocal set_checkconflict -- set auxsend and auxtimeout for dangerzone\n\n\tlocal function reset_dangerzone(session)\n\t\tdangerzone_up = session\n\t\tdangerzone_low = session\n\t\tdangerzone = { [session] = true }\n\t\tfor s in pairs(session_id_coroutine) do\n\t\t\tif s < dangerzone_low then\n\t\t\t\tdangerzone_low = s\n\t\t\telseif s > dangerzone_up then\n\t\t\t\tdangerzone_up = s\n\t\t\tend\n\t\t\tdangerzone[s] = true\n\t\tend\n\t\tdangerzone_low = dangerzone_low - dangerzone_size\n\tend\n\n\t-- in dangerzone, we should check if the next session already exist.\n\tlocal function checkconflict(session)\n\t\tif session == nil then\n\t\t\treturn\n\t\tend\n\t\tlocal next_session = session + 1\n\t\tif next_session > dangerzone_up then\n\t\t\t-- leave dangerzone\n\t\t\treset_dangerzone(session)\n\t\t\tassert(next_session > dangerzone_up)\n\t\t\tset_checkrewind()\n\t\telse\n\t\t\twhile true do\n\t\t\t\tif not dangerzone[next_session] then\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\t\tif not session_id_coroutine[next_session] then\n\t\t\t\t\treset_dangerzone(session)\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\t\t-- skip the session already exist.\n\t\t\t\tnext_session = c.genid() + 1\n\t\t\tend\n\t\tend\n\t\t-- session will rewind after 0x7fffffff\n\t\tif next_session == 0x80000000 and dangerzone[1] then\n\t\t\tassert(c.genid() == 1)\n\t\t\treturn checkconflict(1)\n\t\tend\n\tend\n\n\tlocal function auxsend_checkconflict(addr, proto, msg, sz)\n\t\tlocal session = csend(addr, proto, nil, msg, sz)\n\t\tcheckconflict(session)\n\t\treturn session\n\tend\n\n\tlocal function auxtimeout_checkconflict(timeout)\n\t\tlocal session = cintcommand(\"TIMEOUT\", timeout)\n\t\tcheckconflict(session)\n\t\treturn session\n\tend\n\n\tlocal function auxwait_checkconflict()\n\t\tlocal session = c.genid()\n\t\tcheckconflict(session)\n\t\treturn session\n\tend\n\n\tlocal function auxsend_checkrewind(addr, proto, msg, sz)\n\t\tlocal session = csend(addr, proto, nil, msg, sz)\n\t\tif session and session > dangerzone_low and session <= dangerzone_up then\n\t\t\t-- enter dangerzone\n\t\t\tset_checkconflict(session)\n\t\tend\n\t\treturn session\n\tend\n\n\tlocal function auxtimeout_checkrewind(timeout)\n\t\tlocal session = cintcommand(\"TIMEOUT\", timeout)\n\t\tif session and session > dangerzone_low and session <= dangerzone_up then\n\t\t\t-- enter dangerzone\n\t\t\tset_checkconflict(session)\n\t\tend\n\t\treturn session\n\tend\n\n\tlocal function auxwait_checkrewind()\n\t\tlocal session = c.genid()\n\t\tif session > dangerzone_low and session <= dangerzone_up then\n\t\t\t-- enter dangerzone\n\t\t\tset_checkconflict(session)\n\t\tend\n\t\treturn session\n\tend\n\n\tset_checkrewind = function()\n\t\tauxsend = auxsend_checkrewind\n\t\tauxtimeout = auxtimeout_checkrewind\n\t\tauxwait = auxwait_checkrewind\n\tend\n\n\tset_checkconflict = function(session)\n\t\treset_dangerzone(session)\n\t\tauxsend = auxsend_checkconflict\n\t\tauxtimeout = auxtimeout_checkconflict\n\t\tauxwait = auxwait_checkconflict\n\tend\n\n\t-- in safezone at the beginning\n\tset_checkrewind()\nend\n\ndo ---- request/select\n\tlocal function send_requests(self)\n\t\tlocal sessions = {}\n\t\tself._sessions = sessions\n\t\tlocal request_n = 0\n\t\tlocal err\n\t\tfor i = 1, #self do\n\t\t\tlocal req = self[i]\n\t\t\tlocal addr = req[1]\n\t\t\tlocal p = proto[req[2]]\n\t\t\tassert(p.unpack)\n\t\t\tlocal tag = session_coroutine_tracetag[running_thread]\n\t\t\tif tag then\n\t\t\t\tc.trace(tag, \"call\", 4)\n\t\t\t\tc.send(addr, skynet.PTYPE_TRACE, 0, tag)\n\t\t\tend\n\t\t\tlocal session = auxsend(addr, p.id , p.pack(tunpack(req, 3, req.n)))\n\t\t\tif session == nil then\n\t\t\t\terr = err or {}\n\t\t\t\terr[#err+1] = req\n\t\t\telse\n\t\t\t\tsessions[session] = req\n\t\t\t\twatching_session[session] = addr\n\t\t\t\tsession_id_coroutine[session] = self._thread\n\t\t\t\trequest_n = request_n + 1\n\t\t\tend\n\t\tend\n\t\tself._request = request_n\n\t\treturn err\n\tend\n\n\tlocal function request_thread(self)\n\t\twhile true do\n\t\t\tlocal succ, msg, sz, session = coroutine_yield \"SUSPEND\"\n\t\t\tif session == self._timeout then\n\t\t\t\tself._timeout = nil\n\t\t\t\tself.timeout = true\n\t\t\telse\n\t\t\t\twatching_session[session] = nil\n\t\t\t\tlocal req = self._sessions[session]\n\t\t\t\tlocal p = proto[req[2]]\n\t\t\t\tif succ then\n\t\t\t\t\tself._resp[session] = tpack( p.unpack(msg, sz) )\n\t\t\t\telse\n\t\t\t\t\tself._resp[session] = false\n\t\t\t\tend\n\t\t\tend\n\t\t\tskynet.wakeup(self)\n\t\tend\n\tend\n\n\tlocal function request_iter(self)\n\t\treturn function()\n\t\t\tif self._error then\n\t\t\t\t-- invalid address\n\t\t\t\tlocal e = tremove(self._error)\n\t\t\t\tif e then\n\t\t\t\t\treturn e\n\t\t\t\tend\n\t\t\t\tself._error = nil\n\t\t\tend\n\t\t\tlocal session, resp = next(self._resp)\n\t\t\tif session == nil then\n\t\t\t\tif self._request == 0 then\n\t\t\t\t\treturn\n\t\t\t\tend\n\t\t\t\tif self.timeout then\n\t\t\t\t\treturn\n\t\t\t\tend\n\t\t\t\tskynet.wait(self)\n\t\t\t\tif self.timeout then\n\t\t\t\t\treturn\n\t\t\t\tend\n\t\t\t\tsession, resp = next(self._resp)\n\t\t\tend\n\n\t\t\tself._request = self._request - 1\n\t\t\tlocal req = self._sessions[session]\n\t\t\tself._resp[session] = nil\n\t\t\tself._sessions[session] = nil\n\t\t\treturn req, resp\n\t\tend\n\tend\n\n\tlocal request_meta = {}\t; request_meta.__index = request_meta\n\n\tfunction request_meta:add(obj)\n\t\tassert(type(obj) == \"table\" and not self._thread)\n\t\tself[#self+1] = obj\n\t\treturn self\n\tend\n\n\trequest_meta.__call = request_meta.add\n\n\tfunction request_meta:close()\n\t\tif self._request > 0 then\n\t\t\tlocal resp = self._resp\n\t\t\tfor session, req in pairs(self._sessions) do\n\t\t\t\tif not resp[session] then\n\t\t\t\t\tsession_id_coroutine[session] = \"BREAK\"\n\t\t\t\t\twatching_session[session] = nil\n\t\t\t\tend\n\t\t\tend\n\t\t\tself._request = 0\n\t\tend\n\t\tif self._timeout then\n\t\t\tsession_id_coroutine[self._timeout] = \"BREAK\"\n\t\t\tself._timeout = nil\n\t\tend\n\tend\n\n\trequest_meta.__close = request_meta.close\n\n\tfunction request_meta:select(timeout)\n\t\tassert(self._thread == nil)\n\t\tself._thread = coroutine_create(request_thread)\n\t\tself._error = send_requests(self)\n\t\tself._resp = {}\n\t\tif timeout then\n\t\t\tself._timeout = auxtimeout(timeout)\n\t\t\tsession_id_coroutine[self._timeout] = self._thread\n\t\tend\n\n\t\tlocal running = running_thread\n\t\tcoroutine_resume(self._thread, self)\n\t\trunning_thread = running\n\t\treturn request_iter(self), nil, nil, self\n\tend\n\n\tfunction skynet.request(obj)\n\t\tlocal ret = setmetatable({}, request_meta)\n\t\tif obj then\n\t\t\treturn ret(obj)\n\t\tend\n\t\treturn ret\n\tend\nend\n\n-- suspend is function\nlocal suspend\n\n----- monitor exit\n\nlocal function dispatch_error_queue()\n\tlocal session = tremove(error_queue,1)\n\tif session then\n\t\tlocal co = session_id_coroutine[session]\n\t\tsession_id_coroutine[session] = nil\n\t\treturn suspend(co, coroutine_resume(co, false, nil, nil, session))\n\tend\nend\n\nlocal function _error_dispatch(error_session, error_source)\n\tskynet.ignoreret()\t-- don't return for error\n\tif error_session == 0 then\n\t\t-- error_source is down, clear unreponse set\n\t\tfor resp, address in pairs(unresponse) do\n\t\t\tif error_source == address then\n\t\t\t\tunresponse[resp] = nil\n\t\t\tend\n\t\tend\n\t\tfor session, srv in pairs(watching_session) do\n\t\t\tif srv == error_source then\n\t\t\t\ttinsert(error_queue, session)\n\t\t\tend\n\t\tend\n\telse\n\t\t-- capture an error for error_session\n\t\tif watching_session[error_session] then\n\t\t\ttinsert(error_queue, error_session)\n\t\tend\n\tend\nend\n\n-- coroutine reuse\n\nlocal coroutine_pool = setmetatable({}, { __mode = \"kv\" })\n\nlocal function co_create(f)\n\tlocal co = tremove(coroutine_pool)\n\tif co == nil then\n\t\tco = coroutine_create(function(...)\n\t\t\tf(...)\n\t\t\twhile true do\n\t\t\t\tlocal session = session_coroutine_id[co]\n\t\t\t\tif session and session ~= 0 then\n\t\t\t\t\tlocal source = debug.getinfo(f,\"S\")\n\t\t\t\t\tskynet.error(string.format(\"Maybe forgot response session %s from %s : %s:%d\",\n\t\t\t\t\t\tsession,\n\t\t\t\t\t\tskynet.address(session_coroutine_address[co]),\n\t\t\t\t\t\tsource.source, source.linedefined))\n\t\t\t\tend\n\t\t\t\t-- coroutine exit\n\t\t\t\tlocal tag = session_coroutine_tracetag[co]\n\t\t\t\tif tag ~= nil then\n\t\t\t\t\tif tag then c.trace(tag, \"end\")\tend\n\t\t\t\t\tsession_coroutine_tracetag[co] = nil\n\t\t\t\tend\n\t\t\t\tlocal address = session_coroutine_address[co]\n\t\t\t\tif address then\n\t\t\t\t\tsession_coroutine_id[co] = nil\n\t\t\t\t\tsession_coroutine_address[co] = nil\n\t\t\t\tend\n\n\t\t\t\t-- recycle co into pool\n\t\t\t\tf = nil\n\t\t\t\tcoroutine_pool[#coroutine_pool+1] = co\n\t\t\t\t-- recv new main function f\n\t\t\t\tf = coroutine_yield \"SUSPEND\"\n\t\t\t\tf(coroutine_yield())\n\t\t\tend\n\t\tend)\n\telse\n\t\t-- pass the main function f to coroutine, and restore running thread\n\t\tlocal running = running_thread\n\t\tcoroutine_resume(co, f)\n\t\trunning_thread = running\n\tend\n\treturn co\nend\n\nlocal function dispatch_wakeup()\n\twhile true do\n\t\tlocal token = tremove(wakeup_queue,1)\n\t\tif token then\n\t\t\tlocal session = sleep_session[token]\n\t\t\tif session then\n\t\t\t\tlocal co = session_id_coroutine[session]\n\t\t\t\tlocal tag = session_coroutine_tracetag[co]\n\t\t\t\tif tag then c.trace(tag, \"resume\") end\n\t\t\t\tsession_id_coroutine[session] = \"BREAK\"\n\t\t\t\treturn suspend(co, coroutine_resume(co, false, \"BREAK\", nil, session))\n\t\t\tend\n\t\telse\n\t\t\tbreak\n\t\tend\n\tend\n\treturn dispatch_error_queue()\nend\n\n-- suspend is local function\nfunction suspend(co, result, command)\n\tif not result then\n\t\tlocal session = session_coroutine_id[co]\n\t\tif session then -- coroutine may fork by others (session is nil)\n\t\t\tlocal addr = session_coroutine_address[co]\n\t\t\tif session ~= 0 then\n\t\t\t\t-- only call response error\n\t\t\t\tlocal tag = session_coroutine_tracetag[co]\n\t\t\t\tif tag then c.trace(tag, \"error\") end\n\t\t\t\tc.send(addr, skynet.PTYPE_ERROR, session, \"\")\n\t\t\tend\n\t\t\tsession_coroutine_id[co] = nil\n\t\tend\n\t\tsession_coroutine_address[co] = nil\n\t\tsession_coroutine_tracetag[co] = nil\n\t\tskynet.fork(function() end)\t-- trigger command \"SUSPEND\"\n\t\tlocal tb = traceback(co,tostring(command))\n\t\tcoroutine.close(co)\n\t\terror(tb)\n\tend\n\tif command == \"SUSPEND\" then\n\t\treturn dispatch_wakeup()\n\telseif command == \"QUIT\" then\n\t\tcoroutine.close(co)\n\t\t-- service exit\n\t\treturn\n\telseif command == \"USER\" then\n\t\t-- See skynet.coutine for detail\n\t\terror(\"Call skynet.coroutine.yield out of skynet.coroutine.resume\\n\" .. traceback(co))\n\telseif command == nil then\n\t\t-- debug trace\n\t\treturn\n\telse\n\t\terror(\"Unknown command : \" .. command .. \"\\n\" .. traceback(co))\n\tend\nend\n\nlocal co_create_for_timeout\nlocal timeout_traceback\n\nfunction skynet.trace_timeout(on)\n\tlocal function trace_coroutine(func, ti)\n\t\tlocal co\n\t\tco = co_create(function()\n\t\t\ttimeout_traceback[co] = nil\n\t\t\tfunc()\n\t\tend)\n\t\tlocal info = string.format(\"TIMER %d+%d : \", skynet.now(), ti)\n\t\ttimeout_traceback[co] = traceback(info, 3)\n\t\treturn co\n\tend\n\tif on then\n\t\ttimeout_traceback = timeout_traceback or {}\n\t\tco_create_for_timeout = trace_coroutine\n\telse\n\t\ttimeout_traceback = nil\n\t\tco_create_for_timeout = co_create\n\tend\nend\n\nskynet.trace_timeout(false)\t-- turn off by default\n\nfunction skynet.timeout(ti, func)\n\tlocal session = auxtimeout(ti)\n\tassert(session)\n\tlocal co = co_create_for_timeout(func, ti)\n\tassert(session_id_coroutine[session] == nil)\n\tsession_id_coroutine[session] = co\n\treturn co\t-- for debug\nend\n\nlocal function suspend_sleep(session, token)\n\tlocal tag = session_coroutine_tracetag[running_thread]\n\tif tag then c.trace(tag, \"sleep\", 2) end\n\tsession_id_coroutine[session] = running_thread\n\tassert(sleep_session[token] == nil, \"token duplicative\")\n\tsleep_session[token] = session\n\n\treturn coroutine_yield \"SUSPEND\"\nend\n\nfunction skynet.sleep(ti, token)\n\tlocal session = auxtimeout(ti)\n\tassert(session)\n\ttoken = token or coroutine.running()\n\tlocal succ, ret = suspend_sleep(session, token)\n\tsleep_session[token] = nil\n\tif succ then\n\t\treturn\n\tend\n\tif ret == \"BREAK\" then\n\t\treturn \"BREAK\"\n\telse\n\t\terror(ret)\n\tend\nend\n\nfunction skynet.yield()\n\treturn skynet.sleep(0)\nend\n\nfunction skynet.wait(token)\n\tlocal session = auxwait()\n\ttoken = token or coroutine.running()\n\tsuspend_sleep(session, token)\n\tsleep_session[token] = nil\n\tsession_id_coroutine[session] = nil\nend\n\nfunction skynet.killthread(thread)\n\tlocal session\n\t-- find session\n\tif type(thread) == \"string\" then\n\t\tfor k,v in pairs(session_id_coroutine) do\n\t\t\tlocal thread_string = tostring(v)\n\t\t\tif thread_string:find(thread) then\n\t\t\t\tsession = k\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\telse\n\t\tlocal t = fork_queue.t\n\t\tfor i = fork_queue.h, t do\n\t\t\tif fork_queue[i] == thread then\n\t\t\t\ttable.move(fork_queue, i+1, t, i)\n\t\t\t\tfork_queue[t] = nil\n\t\t\t\tfork_queue.t = t - 1\n\t\t\t\treturn thread\n\t\t\tend\n\t\tend\n\t\tfor k,v in pairs(session_id_coroutine) do\n\t\t\tif v == thread then\n\t\t\t\tsession = k\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\tend\n\tlocal co = session_id_coroutine[session]\n\tif co == nil then\n\t\treturn\n\tend\n\tlocal addr = session_coroutine_address[co]\n\tif addr then\n\t\tsession_coroutine_address[co] = nil\n\t\tsession_coroutine_tracetag[co] = nil\n\t\tlocal session = session_coroutine_id[co]\n\t\tif session > 0 then\n\t\t\tc.send(addr, skynet.PTYPE_ERROR, session, \"\")\n\t\tend\n\t\tsession_coroutine_id[co] = nil\n\tend\n\tif watching_session[session] then\n\t\tsession_id_coroutine[session] = \"BREAK\"\n\t\twatching_session[session] = nil\n\telse\n\t\tsession_id_coroutine[session] = nil\n\tend\n\tfor k,v in pairs(sleep_session) do\n\t\tif v == session then\n\t\t\tsleep_session[k] = nil\n\t\t\tbreak\n\t\tend\n\tend\n\tcoroutine.close(co)\n\treturn co\nend\n\nfunction skynet.self()\n\treturn c.addresscommand \"REG\"\nend\n\nfunction skynet.localname(name)\n\treturn c.addresscommand(\"QUERY\", name)\nend\n\nskynet.now = c.now\nskynet.hpc = c.hpc\t-- high performance counter\n\nlocal traceid = 0\nfunction skynet.trace(info)\n\tskynet.error(\"TRACE\", session_coroutine_tracetag[running_thread])\n\tif session_coroutine_tracetag[running_thread] == false then\n\t\t-- force off trace log\n\t\treturn\n\tend\n\ttraceid = traceid + 1\n\n\tlocal tag = string.format(\":%08x-%d\",skynet.self(), traceid)\n\tsession_coroutine_tracetag[running_thread] = tag\n\tif info then\n\t\tc.trace(tag, \"trace \" .. info)\n\telse\n\t\tc.trace(tag, \"trace\")\n\tend\nend\n\nfunction skynet.tracetag()\n\treturn session_coroutine_tracetag[running_thread]\nend\n\nlocal starttime\n\nfunction skynet.starttime()\n\tif not starttime then\n\t\tstarttime = c.intcommand(\"STARTTIME\")\n\tend\n\treturn starttime\nend\n\nfunction skynet.time()\n\treturn skynet.now()/100 + (starttime or skynet.starttime())\nend\n\nfunction skynet.exit()\n\tfork_queue = { h = 1, t = 0 }\t-- no fork coroutine can be execute after skynet.exit\n\tskynet.send(\".launcher\",\"lua\",\"REMOVE\",skynet.self(), false)\n\t-- report the sources that call me\n\tfor co, session in pairs(session_coroutine_id) do\n\t\tlocal address = session_coroutine_address[co]\n\t\tif session~=0 and address then\n\t\t\tc.send(address, skynet.PTYPE_ERROR, session, \"\")\n\t\tend\n\tend\n\tfor session, co in pairs(session_id_coroutine) do\n\t\tif type(co) == \"thread\" and co ~= running_thread then\n\t\t\tcoroutine.close(co)\n\t\tend\n\tend\n\tfor resp in pairs(unresponse) do\n\t\tresp(false)\n\tend\n\t-- report the sources I call but haven't return\n\tlocal tmp = {}\n\tfor session, address in pairs(watching_session) do\n\t\ttmp[address] = true\n\tend\n\tfor address in pairs(tmp) do\n\t\tc.send(address, skynet.PTYPE_ERROR, 0, \"\")\n\tend\n\tc.callback(function(prototype, msg, sz, session, source)\n\t\tif session ~= 0 and source ~= 0 then\n\t\t\tc.send(source, skynet.PTYPE_ERROR, session, \"\")\n\t\tend\n\tend)\n\tc.command(\"EXIT\")\n\t-- quit service\n\tcoroutine_yield \"QUIT\"\nend\n\nfunction skynet.getenv(key)\n\treturn (c.command(\"GETENV\",key))\nend\n\nfunction skynet.setenv(key, value)\n\tassert(c.command(\"GETENV\",key) == nil, \"Can't setenv exist key : \" .. key)\n\tc.command(\"SETENV\",key .. \" \" ..value)\nend\n\nfunction skynet.send(addr, typename, ...)\n\tlocal p = proto[typename]\n\treturn c.send(addr, p.id, 0 , p.pack(...))\nend\n\nfunction skynet.rawsend(addr, typename, msg, sz)\n\tlocal p = proto[typename]\n\treturn c.send(addr, p.id, 0 , msg, sz)\nend\n\nskynet.genid = assert(c.genid)\n\nskynet.redirect = function(dest,source,typename,...)\n\treturn c.redirect(dest, source, proto[typename].id, ...)\nend\n\nskynet.pack = assert(c.pack)\nskynet.packstring = assert(c.packstring)\nskynet.unpack = assert(c.unpack)\nskynet.tostring = assert(c.tostring)\nskynet.trash = assert(c.trash)\n\nlocal function yield_call(service, session)\n\twatching_session[session] = service\n\tsession_id_coroutine[session] = running_thread\n\tlocal succ, msg, sz = coroutine_yield \"SUSPEND\"\n\twatching_session[session] = nil\n\tif not succ then\n\t\terror \"call failed\"\n\tend\n\treturn msg,sz\nend\n\nfunction skynet.call(addr, typename, ...)\n\tlocal tag = session_coroutine_tracetag[running_thread]\n\tif tag then\n\t\tc.trace(tag, \"call\", 2)\n\t\tc.send(addr, skynet.PTYPE_TRACE, 0, tag)\n\tend\n\n\tlocal p = proto[typename]\n\tlocal session = auxsend(addr, p.id , p.pack(...))\n\tif session == nil then\n\t\terror(\"call to invalid address \" .. skynet.address(addr))\n\tend\n\treturn p.unpack(yield_call(addr, session))\nend\n\nfunction skynet.rawcall(addr, typename, msg, sz)\n\tlocal tag = session_coroutine_tracetag[running_thread]\n\tif tag then\n\t\tc.trace(tag, \"call\", 2)\n\t\tc.send(addr, skynet.PTYPE_TRACE, 0, tag)\n\tend\n\tlocal p = proto[typename]\n\tlocal session = assert(auxsend(addr, p.id , msg, sz), \"call to invalid address\")\n\treturn yield_call(addr, session)\nend\n\nfunction skynet.tracecall(tag, addr, typename, msg, sz)\n\tc.trace(tag, \"tracecall begin\")\n\tc.send(addr, skynet.PTYPE_TRACE, 0, tag)\n\tlocal p = proto[typename]\n\tlocal session = assert(auxsend(addr, p.id , msg, sz), \"call to invalid address\")\n\tlocal msg, sz = yield_call(addr, session)\n\tc.trace(tag, \"tracecall end\")\n\treturn msg, sz\nend\n\nfunction skynet.ret(msg, sz)\n\tmsg = msg or \"\"\n\tlocal tag = session_coroutine_tracetag[running_thread]\n\tif tag then c.trace(tag, \"response\") end\n\tlocal co_session = session_coroutine_id[running_thread]\n\tif co_session == nil then\n\t\terror \"No session\"\n\tend\n\tsession_coroutine_id[running_thread] = nil\n\tif co_session == 0 then\n\t\tif sz ~= nil then\n\t\t\tc.trash(msg, sz)\n\t\tend\n\t\treturn false\t-- send don't need ret\n\tend\n\tlocal co_address = session_coroutine_address[running_thread]\n\tlocal ret = c.send(co_address, skynet.PTYPE_RESPONSE, co_session, msg, sz)\n\tif ret then\n\t\treturn true\n\telseif ret == false then\n\t\t-- If the package is too large, returns false. so we should report error back\n\t\tc.send(co_address, skynet.PTYPE_ERROR, co_session, \"\")\n\tend\n\treturn false\nend\n\nfunction skynet.context()\n\tlocal co_session = session_coroutine_id[running_thread]\n\tlocal co_address = session_coroutine_address[running_thread]\n\treturn co_session, co_address\nend\n\nfunction skynet.ignoreret()\n\t-- We use session for other uses\n\tsession_coroutine_id[running_thread] = nil\nend\n\nfunction skynet.response(pack)\n\tpack = pack or skynet.pack\n\n\tlocal co_session = assert(session_coroutine_id[running_thread], \"no session\")\n\tsession_coroutine_id[running_thread] = nil\n\tlocal co_address = session_coroutine_address[running_thread]\n\tif co_session == 0 then\n\t\t--  do not response when session == 0 (send)\n\t\treturn function() end\n\tend\n\tlocal function response(ok, ...)\n\t\tif ok == \"TEST\" then\n\t\t\treturn unresponse[response] ~= nil\n\t\tend\n\t\tif not pack then\n\t\t\terror \"Can't response more than once\"\n\t\tend\n\n\t\tlocal ret\n\t\tif unresponse[response] then\n\t\t\tif ok then\n\t\t\t\tret = c.send(co_address, skynet.PTYPE_RESPONSE, co_session, pack(...))\n\t\t\t\tif ret == false then\n\t\t\t\t\t-- If the package is too large, returns false. so we should report error back\n\t\t\t\t\tc.send(co_address, skynet.PTYPE_ERROR, co_session, \"\")\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tret = c.send(co_address, skynet.PTYPE_ERROR, co_session, \"\")\n\t\t\tend\n\t\t\tunresponse[response] = nil\n\t\t\tret = ret ~= nil\n\t\telse\n\t\t\tret = false\n\t\tend\n\t\tpack = nil\n\t\treturn ret\n\tend\n\tunresponse[response] = co_address\n\n\treturn response\nend\n\nfunction skynet.retpack(...)\n\treturn skynet.ret(skynet.pack(...))\nend\n\nfunction skynet.wakeup(token)\n\tif sleep_session[token] then\n\t\ttinsert(wakeup_queue, token)\n\t\treturn true\n\tend\nend\n\nfunction skynet.dispatch(typename, func)\n\tlocal p = proto[typename]\n\tif func then\n\t\tlocal ret = p.dispatch\n\t\tp.dispatch = func\n\t\treturn ret\n\telse\n\t\treturn p and p.dispatch\n\tend\nend\n\nlocal function unknown_request(session, address, msg, sz, prototype)\n\tskynet.error(string.format(\"Unknown request (%s): %s\", prototype, c.tostring(msg,sz)))\n\terror(string.format(\"Unknown session : %d from %x\", session, address))\nend\n\nfunction skynet.dispatch_unknown_request(unknown)\n\tlocal prev = unknown_request\n\tunknown_request = unknown\n\treturn prev\nend\n\nlocal function unknown_response(session, address, msg, sz)\n\tskynet.error(string.format(\"Response message : %s\" , c.tostring(msg,sz)))\n\terror(string.format(\"Unknown session : %d from %x\", session, address))\nend\n\nfunction skynet.dispatch_unknown_response(unknown)\n\tlocal prev = unknown_response\n\tunknown_response = unknown\n\treturn prev\nend\n\nfunction skynet.fork(func,...)\n\tlocal n = select(\"#\", ...)\n\tlocal co\n\tif n == 0 then\n\t\tco = co_create(func)\n\telse\n\t\tlocal args = { ... }\n\t\tco = co_create(function() func(table.unpack(args,1,n)) end)\n\tend\n\tlocal t = fork_queue.t + 1\n\tfork_queue.t = t\n\tfork_queue[t] = co\n\treturn co\nend\n\nlocal trace_source = {}\n\nlocal function raw_dispatch_message(prototype, msg, sz, session, source)\n\t-- skynet.PTYPE_RESPONSE = 1, read skynet.h\n\tif prototype == 1 then\n\t\tlocal co = session_id_coroutine[session]\n\t\tif co == \"BREAK\" then\n\t\t\tsession_id_coroutine[session] = nil\n\t\telseif co == nil then\n\t\t\tunknown_response(session, source, msg, sz)\n\t\telse\n\t\t\tlocal tag = session_coroutine_tracetag[co]\n\t\t\tif tag then c.trace(tag, \"resume\") end\n\t\t\tsession_id_coroutine[session] = nil\n\t\t\tsuspend(co, coroutine_resume(co, true, msg, sz, session))\n\t\tend\n\telse\n\t\tlocal p = proto[prototype]\n\t\tif p == nil then\n\t\t\tif prototype == skynet.PTYPE_TRACE then\n\t\t\t\t-- trace next request\n\t\t\t\ttrace_source[source] = c.tostring(msg,sz)\n\t\t\telseif session ~= 0 then\n\t\t\t\tc.send(source, skynet.PTYPE_ERROR, session, \"\")\n\t\t\telse\n\t\t\t\tunknown_request(session, source, msg, sz, prototype)\n\t\t\tend\n\t\t\treturn\n\t\tend\n\n\t\tlocal f = p.dispatch\n\t\tif f then\n\t\t\tlocal co = co_create(f)\n\t\t\tsession_coroutine_id[co] = session\n\t\t\tsession_coroutine_address[co] = source\n\t\t\tlocal traceflag = p.trace\n\t\t\tif traceflag == false then\n\t\t\t\t-- force off\n\t\t\t\ttrace_source[source] = nil\n\t\t\t\tsession_coroutine_tracetag[co] = false\n\t\t\telse\n\t\t\t\tlocal tag = trace_source[source]\n\t\t\t\tif tag then\n\t\t\t\t\ttrace_source[source] = nil\n\t\t\t\t\tc.trace(tag, \"request\")\n\t\t\t\t\tsession_coroutine_tracetag[co] = tag\n\t\t\t\telseif traceflag then\n\t\t\t\t\t-- set running_thread for trace\n\t\t\t\t\trunning_thread = co\n\t\t\t\t\tskynet.trace()\n\t\t\t\tend\n\t\t\tend\n\t\t\tsuspend(co, coroutine_resume(co, session,source, p.unpack(msg,sz)))\n\t\telse\n\t\t\ttrace_source[source] = nil\n\t\t\tif session ~= 0 then\n\t\t\t\tc.send(source, skynet.PTYPE_ERROR, session, \"\")\n\t\t\telse\n\t\t\t\tunknown_request(session, source, msg, sz, proto[prototype].name)\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction skynet.dispatch_message(...)\n\tlocal succ, err = pcall(raw_dispatch_message,...)\n\twhile true do\n\t\tif fork_queue.h > fork_queue.t then\n\t\t\t-- queue is empty\n\t\t\tfork_queue.h = 1\n\t\t\tfork_queue.t = 0\n\t\t\tbreak\n\t\tend\n\t\t-- pop queue\n\t\tlocal h = fork_queue.h\n\t\tlocal co = fork_queue[h]\n\t\tfork_queue[h] = nil\n\t\tfork_queue.h = h + 1\n\n\t\tlocal fork_succ, fork_err = pcall(suspend,co,coroutine_resume(co))\n\t\tif not fork_succ then\n\t\t\tif succ then\n\t\t\t\tsucc = false\n\t\t\t\terr = tostring(fork_err)\n\t\t\telse\n\t\t\t\terr = tostring(err) .. \"\\n\" .. tostring(fork_err)\n\t\t\tend\n\t\tend\n\tend\n\tassert(succ, tostring(err))\nend\n\nfunction skynet.newservice(name, ...)\n\treturn skynet.call(\".launcher\", \"lua\" , \"LAUNCH\", \"snlua\", name, ...)\nend\n\nfunction skynet.uniqueservice(name, ...)\n\tif name == true then\n\t\treturn assert(skynet.call(\".service\", \"lua\", \"GLAUNCH\", ...))\n\telse\n\t\treturn assert(skynet.call(\".service\", \"lua\", \"LAUNCH\", name, ...))\n\tend\nend\n\nfunction skynet.queryservice(name, ...)\n\tif name == true then\n\t\treturn assert(skynet.call(\".service\", \"lua\", \"GQUERY\", ...))\n\telse\n\t\treturn assert(skynet.call(\".service\", \"lua\", \"QUERY\", name, ...))\n\tend\nend\n\nfunction skynet.address(addr)\n\tif type(addr) == \"number\" then\n\t\treturn string.format(\":%08x\",addr)\n\telse\n\t\treturn tostring(addr)\n\tend\nend\n\nfunction skynet.harbor(addr)\n\treturn c.harbor(addr)\nend\n\nskynet.error = c.error\nskynet.tracelog = c.trace\n\n-- true: force on\n-- false: force off\n-- nil: optional (use skynet.trace() to trace one message)\nfunction skynet.traceproto(prototype, flag)\n\tlocal p = assert(proto[prototype])\n\tp.trace = flag\nend\n\n----- register protocol\ndo\n\tlocal REG = skynet.register_protocol\n\n\tREG {\n\t\tname = \"lua\",\n\t\tid = skynet.PTYPE_LUA,\n\t\tpack = skynet.pack,\n\t\tunpack = skynet.unpack,\n\t}\n\n\tREG {\n\t\tname = \"response\",\n\t\tid = skynet.PTYPE_RESPONSE,\n\t}\n\n\tREG {\n\t\tname = \"error\",\n\t\tid = skynet.PTYPE_ERROR,\n\t\tunpack = function(...) return ... end,\n\t\tdispatch = _error_dispatch,\n\t}\nend\n\nskynet.init = skynet_require.init\n-- skynet.pcall is deprecated, use pcall directly\nskynet.pcall = pcall\n\nfunction skynet.init_service(start)\n\tlocal function main()\n\t\tskynet_require.init_all()\n\t\tstart()\n\tend\n\tlocal ok, err = xpcall(main, traceback)\n\tif not ok then\n\t\tskynet.error(\"init service failed: \" .. tostring(err))\n\t\tskynet.send(\".launcher\",\"lua\", \"ERROR\")\n\t\tskynet.exit()\n\telse\n\t\tskynet.send(\".launcher\",\"lua\", \"LAUNCHOK\")\n\tend\nend\n\nfunction skynet.start(start_func)\n\tc.callback(skynet.dispatch_message)\n\tinit_thread = skynet.timeout(0, function()\n\t\tskynet.init_service(start_func)\n\t\tinit_thread = nil\n\tend)\nend\n\nfunction skynet.endless()\n\treturn (c.intcommand(\"STAT\", \"endless\") == 1)\nend\n\nfunction skynet.mqlen()\n\treturn c.intcommand(\"STAT\", \"mqlen\")\nend\n\nfunction skynet.stat(what)\n\treturn c.intcommand(\"STAT\", what)\nend\n\nlocal function task_traceback(co)\n\tif co == \"BREAK\" then\n\t\treturn co\n\telseif timeout_traceback and timeout_traceback[co] then\n\t\treturn timeout_traceback[co]\n\telse\n\t\treturn traceback(co)\n\tend\nend\n\nfunction skynet.task(ret)\n\tif ret == nil then\n\t\tlocal t = 0\n\t\tfor _,co in pairs(session_id_coroutine) do\n\t\t\tif co ~= \"BREAK\" then\n\t\t\t\tt = t + 1\n\t\t\tend\n\t\tend\n\t\treturn t\n\tend\n\tif ret == \"init\" then\n\t\tif init_thread then\n\t\t\treturn traceback(init_thread)\n\t\telse\n\t\t\treturn\n\t\tend\n\tend\n\tlocal tt = type(ret)\n\tif tt == \"table\" then\n\t\tfor session,co in pairs(session_id_coroutine) do\n\t\t\tlocal key = string.format(\"%s session: %d\", tostring(co), session)\n\t\t\tret[key] = task_traceback(co)\n\t\tend\n\t\treturn\n\telseif tt == \"number\" then\n\t\tlocal co = session_id_coroutine[ret]\n\t\tif co then\n\t\t\treturn task_traceback(co)\n\t\telse\n\t\t\treturn \"No session\"\n\t\tend\n\telseif tt == \"thread\" then\n\t\tfor session, co in pairs(session_id_coroutine) do\n\t\t\tif co == ret then\n\t\t\t\treturn session\n\t\t\tend\n\t\tend\n\t\treturn\n\tend\nend\n\nfunction skynet.uniqtask()\n\tlocal stacks = {}\n\tfor session, co in pairs(session_id_coroutine) do\n\t\tlocal stack = task_traceback(co)\n\t\tlocal info = stacks[stack] or {count = 0, sessions = {}}\n\t\tinfo.count = info.count + 1\n\t\tif info.count < 10 then\n\t\t\tinfo.sessions[#info.sessions+1] = session\n\t\tend\n\t\tstacks[stack] = info\n\tend\n\tlocal ret = {}\n\tfor stack, info in pairs(stacks) do\n\t\tlocal count = info.count\n\t\tlocal sessions = table.concat(info.sessions, \",\")\n\t\tif count > 10 then\n\t\t\tsessions = sessions .. \"...\"\n\t\tend\n\t\tlocal head_line = string.format(\"%d\\tsessions:[%s]\\n\", count, sessions)\n\t\tret[head_line] = stack\n\tend\n\treturn ret\nend\n\nfunction skynet.term(service)\n\treturn _error_dispatch(0, service)\nend\n\nfunction skynet.memlimit(bytes)\n\tdebug.getregistry().memlimit = bytes\n\tskynet.memlimit = nil\t-- set only once\nend\n\n-- Inject internal debug framework\nlocal debug = require \"skynet.debug\"\ndebug.init(skynet, {\n\tdispatch = skynet.dispatch_message,\n\tsuspend = suspend,\n\tresume = coroutine_resume,\n})\n\nreturn skynet\n"
  },
  {
    "path": "lualib/snax/gateserver.lua",
    "content": "local skynet = require \"skynet\"\nlocal netpack = require \"skynet.netpack\"\nlocal socketdriver = require \"skynet.socketdriver\"\n\nlocal gateserver = {}\n\nlocal socket\t-- listen socket\nlocal queue\t\t-- message queue\nlocal maxclient\t-- max client\nlocal client_number = 0\nlocal CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end })\nlocal nodelay = false\n\nlocal connection = {}\n-- true : connected\n-- nil : closed\n-- false : close read\n\nfunction gateserver.openclient(fd)\n\tif connection[fd] then\n\t\tsocketdriver.start(fd)\n\tend\nend\n\nfunction gateserver.closeclient(fd)\n\tlocal c = connection[fd]\n\tif c ~= nil then\n\t\tconnection[fd] = nil\n\t\tsocketdriver.close(fd)\n\tend\nend\n\nfunction gateserver.start(handler)\n\tassert(handler.message)\n\tassert(handler.connect)\n\n\tlocal listen_context = {}\n\n\tfunction CMD.open( source, conf )\n\t\tassert(not socket)\n\t\tlocal address = conf.address or \"0.0.0.0\"\n\t\tlocal port = conf.port\n\t\tmaxclient = conf.maxclient or 1024\n\t\tnodelay = conf.nodelay\n\t\tskynet.error(\"Listen on\", address, port)\n\t\tsocket = socketdriver.listen(address, port, conf.backlog)\n\t\tlisten_context.co = coroutine.running()\n\t\tlisten_context.fd = socket\n\t\tskynet.wait(listen_context.co)\n\t\tconf.address = listen_context.addr\n\t\tconf.port = listen_context.port\n\t\tlisten_context = nil\n\t\tsocketdriver.start(socket)\n\t\tif handler.open then\n\t\t\treturn handler.open(source, conf)\n\t\tend\n\tend\n\n\tfunction CMD.close()\n\t\tassert(socket)\n\t\tsocketdriver.close(socket)\n\tend\n\n\tlocal MSG = {}\n\n\tlocal function dispatch_msg(fd, msg, sz)\n\t\tif connection[fd] then\n\t\t\thandler.message(fd, msg, sz)\n\t\telse\n\t\t\tskynet.error(string.format(\"Drop message from fd (%d) : %s\", fd, netpack.tostring(msg,sz)))\n\t\tend\n\tend\n\n\tMSG.data = dispatch_msg\n\n\tlocal function dispatch_queue()\n\t\tlocal fd, msg, sz = netpack.pop(queue)\n\t\tif fd then\n\t\t\t-- may dispatch even the handler.message blocked\n\t\t\t-- If the handler.message never block, the queue should be empty, so only fork once and then exit.\n\t\t\tskynet.fork(dispatch_queue)\n\t\t\tdispatch_msg(fd, msg, sz)\n\n\t\t\tfor fd, msg, sz in netpack.pop, queue do\n\t\t\t\tdispatch_msg(fd, msg, sz)\n\t\t\tend\n\t\tend\n\tend\n\n\tMSG.more = dispatch_queue\n\n\tfunction MSG.open(fd, msg)\n\t\tclient_number = client_number + 1\n\t\tif client_number >= maxclient then\n\t\t\tsocketdriver.shutdown(fd)\n\t\t\treturn\n\t\tend\n\t\tif nodelay then\n\t\t\tsocketdriver.nodelay(fd)\n\t\tend\n\t\tconnection[fd] = true\n\t\thandler.connect(fd, msg)\n\tend\n\n\tfunction MSG.close(fd)\n\t\tif fd ~= socket then\n\t\t\tclient_number = client_number - 1\n\t\t\tif connection[fd] then\n\t\t\t\tconnection[fd] = false\t-- close read\n\t\t\tend\n\t\t\tif handler.disconnect then\n\t\t\t\thandler.disconnect(fd)\n\t\t\tend\n\t\telse\n\t\t\tsocket = nil\n\t\tend\n\tend\n\n\tfunction MSG.error(fd, msg)\n\t\tif fd == socket then\n\t\t\tskynet.error(\"gateserver accept error:\",msg)\n\t\telse\n\t\t\tsocketdriver.shutdown(fd)\n\t\t\tif handler.error then\n\t\t\t\thandler.error(fd, msg)\n\t\t\tend\n\t\tend\n\tend\n\n\tfunction MSG.warning(fd, size)\n\t\tif handler.warning then\n\t\t\thandler.warning(fd, size)\n\t\tend\n\tend\n\n\tfunction MSG.init(id, addr, port)\n\t\tif listen_context then\n\t\t\tlocal co = listen_context.co\n\t\t\tif co then\n\t\t\t\tassert(id == listen_context.fd)\n\t\t\t\tlisten_context.addr = addr\n\t\t\t\tlisten_context.port = port\n\t\t\t\tskynet.wakeup(co)\n\t\t\t\tlisten_context.co = nil\n\t\t\tend\n\t\tend\n\tend\n\n\tskynet.register_protocol {\n\t\tname = \"socket\",\n\t\tid = skynet.PTYPE_SOCKET,\t-- PTYPE_SOCKET = 6\n\t\tunpack = function ( msg, sz )\n\t\t\treturn netpack.filter( queue, msg, sz)\n\t\tend,\n\t\tdispatch = function (_, _, q, type, ...)\n\t\t\tqueue = q\n\t\t\tif type then\n\t\t\t\tMSG[type](...)\n\t\t\tend\n\t\tend\n\t}\n\n\tlocal function init()\n\t\tskynet.dispatch(\"lua\", function (_, address, cmd, ...)\n\t\t\tlocal f = CMD[cmd]\n\t\t\tif f then\n\t\t\t\tskynet.ret(skynet.pack(f(address, ...)))\n\t\t\telse\n\t\t\t\tskynet.ret(skynet.pack(handler.command(cmd, address, ...)))\n\t\t\tend\n\t\tend)\n\tend\n\n\tif handler.embed then\n\t\tinit()\n\telse\n\t\tskynet.start(init)\n\tend\nend\n\nreturn gateserver\n"
  },
  {
    "path": "lualib/snax/hotfix.lua",
    "content": "local si = require \"snax.interface\"\n\nlocal function envid(f)\n\tlocal i = 1\n\twhile true do\n\t\tlocal name, value = debug.getupvalue(f, i)\n\t\tif name == nil then\n\t\t\treturn\n\t\tend\n\t\tif name == \"_ENV\" then\n\t\t\treturn debug.upvalueid(f, i)\n\t\tend\n\t\ti = i + 1\n\tend\nend\n\nlocal function collect_uv(f , uv, env)\n\tlocal i = 1\n\twhile true do\n\t\tlocal name, value = debug.getupvalue(f, i)\n\t\tif name == nil then\n\t\t\tbreak\n\t\tend\n\t\tlocal id = debug.upvalueid(f, i)\n\n\t\tif uv[name] then\n\t\t\tassert(uv[name].id == id, string.format(\"ambiguity local value %s\", name))\n\t\telse\n\t\t\tuv[name] = { func = f, index = i, id = id }\n\n\t\t\tif type(value) == \"function\" then\n\t\t\t\tif envid(value) == env then\n\t\t\t\t\tcollect_uv(value, uv, env)\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\t\ti = i + 1\n\tend\nend\n\nlocal function collect_all_uv(funcs)\n\tlocal globals = {}\n\tfor _, v in pairs(funcs) do\n\t\tif v[4] then\n\t\t\tcollect_uv(v[4], globals, envid(v[4]))\n\t\tend\n\tend\n\tif not globals[\"_ENV\"] then\n\t\tglobals[\"_ENV\"] = {func = collect_uv, index = 1}\n\tend\n\treturn globals\nend\n\nlocal function loader(source)\n\treturn function (path, name, G)\n\t\treturn load(source, \"=patch\", \"bt\", G)\n\tend\nend\n\nlocal function find_func(funcs, group , name)\n\tfor _, desc in pairs(funcs) do\n\t\tlocal _, g, n = table.unpack(desc)\n\t\tif group == g and name == n then\n\t\t\treturn desc\n\t\tend\n\tend\nend\n\nlocal dummy_env = {}\nfor k,v in pairs(_ENV) do dummy_env[k] = v end\n\nlocal function _patch(globals, f)\n\tlocal i = 1\n\twhile true do\n\t\tlocal name, value = debug.getupvalue(f, i)\n\t\tif name == nil then\n\t\t\tbreak\n\t\telseif value == nil or value == dummy_env then\n\t\t\tlocal old_uv = globals[name]\n\t\t\tif old_uv then\n\t\t\t\tdebug.upvaluejoin(f, i, old_uv.func, old_uv.index)\n\t\t\tend\n\t\telse\n\t\t\tif type(value) == \"function\" then\n\t\t\t\t_patch(globals, value)\n\t\t\tend\n\t\tend\n\t\ti = i + 1\n\tend\nend\n\nlocal function patch_func(funcs, globals, group, name, f)\n\tlocal desc = assert(find_func(funcs, group, name) , string.format(\"Patch mismatch %s.%s\", group, name))\n\t_patch(globals, f)\n\tdesc[4] = f\nend\n\nlocal function inject(funcs, source, ...)\n\tlocal patch = si(\"patch\", dummy_env, loader(source))\n\tlocal globals = collect_all_uv(funcs)\n\n\tfor _, v in pairs(patch) do\n\t\tlocal _, group, name, f = table.unpack(v)\n\t\tif f then\n\t\t\tpatch_func(funcs, globals, group, name, f)\n\t\tend\n\tend\n\n\tlocal hf = find_func(patch, \"system\", \"hotfix\")\n\tif hf and hf[4] then\n\t\treturn hf[4](...)\n\tend\nend\n\nreturn function (funcs, source, ...)\n\treturn pcall(inject, funcs, source, ...)\nend\n"
  },
  {
    "path": "lualib/snax/interface.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal function dft_loader(path, name, G)\n\tlocal errlist = {}\n\n\tfor pat in string.gmatch(path,\"[^;]+\") do\n\t\tlocal filename = string.gsub(pat, \"?\", name)\n\t\tlocal f , err = loadfile(filename, \"bt\", G)\n\t\tif f then\n\t\t\treturn f, pat\n\t\telse\n\t\t\ttable.insert(errlist, err)\n\t\tend\n\tend\n\n\terror(table.concat(errlist, \"\\n\"))\nend\n\nreturn function (name , G, loader)\n\tloader = loader or dft_loader\n\n\tlocal function func_id(id, group)\n\t\tlocal tmp = {}\n\t\tlocal function count( _, name, func)\n\t\t\tif type(name) ~= \"string\" then\n\t\t\t\terror (string.format(\"%s method only support string\", group))\n\t\t\tend\n\t\t\tif type(func) ~= \"function\" then\n\t\t\t\terror (string.format(\"%s.%s must be function\", group, name))\n\t\t\tend\n\t\t\tif tmp[name] then\n\t\t\t\terror (string.format(\"%s.%s duplicate definition\", group, name))\n\t\t\tend\n\t\t\ttmp[name] = true\n\t\t\ttable.insert(id, { #id + 1, group, name, func} )\n\t\tend\n\t\treturn setmetatable({}, { __newindex = count })\n\tend\n\n\tdo\n\t\tassert(getmetatable(G) == nil)\n\t\tassert(G.init == nil)\n\t\tassert(G.exit == nil)\n\t\tassert(G.accept == nil)\n\t\tassert(G.response == nil)\n\tend\n\n\tlocal temp_global = {}\n\tlocal env = setmetatable({} , { __index = temp_global })\n\tlocal func = {}\n\n\tlocal system = { \"init\", \"exit\", \"hotfix\", \"profile\"}\n\n\tdo\n\t\tfor k, v in ipairs(system) do\n\t\t\tsystem[v] = k\n\t\t\tfunc[k] = { k , \"system\", v }\n\t\tend\n\tend\n\n\tenv.accept = func_id(func, \"accept\")\n\tenv.response = func_id(func, \"response\")\n\n\tlocal function init_system(t, name, f)\n\t\tlocal index = system[name]\n\t\tif index then\n\t\t\tif type(f) ~= \"function\" then\n\t\t\t\terror (string.format(\"%s must be a function\", name))\n\t\t\tend\n\t\t\tfunc[index][4] = f\n\t\telse\n\t\t\ttemp_global[name] = f\n\t\tend\n\tend\n\n\tlocal path = assert(skynet.getenv \"snax\" , \"please set snax in config file\")\n\tlocal mainfunc, pattern = loader(path, name, G)\n\n\tsetmetatable(G,\t{ __index = env , __newindex = init_system })\n\tlocal ok, err = xpcall(mainfunc, debug.traceback)\n\tsetmetatable(G, nil)\n\tassert(ok,err)\n\n\tfor k,v in pairs(temp_global) do\n\t\tG[k] = v\n\tend\n\n\treturn func, pattern\nend\n"
  },
  {
    "path": "lualib/snax/loginserver.lua",
    "content": "local skynet = require \"skynet\"\nrequire \"skynet.manager\"\nlocal socket = require \"skynet.socket\"\nlocal crypt = require \"skynet.crypt\"\nlocal table = table\nlocal string = string\nlocal assert = assert\n\n--[[\n\nProtocol:\n\n\tline (\\n) based text protocol\n\n\t1. Server->Client : base64(8bytes random challenge)\n\t2. Client->Server : base64(8bytes handshake client key)\n\t3. Server: Gen a 8bytes handshake server key\n\t4. Server->Client : base64(DH-Exchange(server key))\n\t5. Server/Client secret := DH-Secret(client key/server key)\n\t6. Client->Server : base64(HMAC(challenge, secret))\n\t7. Client->Server : DES(secret, base64(token))\n\t8. Server : call auth_handler(token) -> server, uid (A user defined method)\n\t9. Server : call login_handler(server, uid, secret) ->subid (A user defined method)\n\t10. Server->Client : 200 base64(subid)\n\nError Code:\n\t401 Unauthorized . unauthorized by auth_handler\n\t403 Forbidden . login_handler failed\n\t406 Not Acceptable . already in login (disallow multi login)\n\nSuccess:\n\t200 base64(subid)\n]]\n\nlocal socket_error = {}\nlocal function assert_socket(service, v, fd)\n\tif v then\n\t\treturn v\n\telse\n\t\tskynet.error(string.format(\"%s failed: socket (fd = %d) closed\", service, fd))\n\t\terror(socket_error)\n\tend\nend\n\nlocal function write(service, fd, text)\n\tassert_socket(service, socket.write(fd, text), fd)\nend\n\nlocal function launch_slave(auth_handler)\n\tlocal function auth(fd, addr)\n\t\t-- set socket buffer limit (8K)\n\t\t-- If the attacker send large package, close the socket\n\t\tsocket.limit(fd, 8192)\n\n\t\tlocal challenge = crypt.randomkey()\n\t\twrite(\"auth\", fd, crypt.base64encode(challenge)..\"\\n\")\n\n\t\tlocal handshake = assert_socket(\"auth\", socket.readline(fd), fd)\n\t\tlocal clientkey = crypt.base64decode(handshake)\n\t\tif #clientkey ~= 8 then\n\t\t\terror \"Invalid client key\"\n\t\tend\n\t\tlocal serverkey = crypt.randomkey()\n\t\twrite(\"auth\", fd, crypt.base64encode(crypt.dhexchange(serverkey))..\"\\n\")\n\n\t\tlocal secret = crypt.dhsecret(clientkey, serverkey)\n\n\t\tlocal response = assert_socket(\"auth\", socket.readline(fd), fd)\n\t\tlocal hmac = crypt.hmac64(challenge, secret)\n\n\t\tif hmac ~= crypt.base64decode(response) then\n\t\t\terror \"challenge failed\"\n\t\tend\n\n\t\tlocal etoken = assert_socket(\"auth\", socket.readline(fd),fd)\n\n\t\tlocal token = crypt.desdecode(secret, crypt.base64decode(etoken))\n\n\t\tlocal ok, server, uid =  pcall(auth_handler,token)\n\n\t\treturn ok, server, uid, secret\n\tend\n\n\tlocal function ret_pack(ok, err, ...)\n\t\tif ok then\n\t\t\treturn skynet.pack(err, ...)\n\t\telse\n\t\t\tif err == socket_error then\n\t\t\t\treturn skynet.pack(nil, \"socket error\")\n\t\t\telse\n\t\t\t\treturn skynet.pack(false, err)\n\t\t\tend\n\t\tend\n\tend\n\n\tlocal function auth_fd(fd, addr)\n\t\tskynet.error(string.format(\"connect from %s (fd = %d)\", addr, fd))\n\t\tsocket.start(fd)\t-- may raise error here\n\t\tlocal msg, len = ret_pack(pcall(auth, fd, addr))\n\t\tsocket.abandon(fd)\t-- never raise error here\n\t\treturn msg, len\n\tend\n\n\tskynet.dispatch(\"lua\", function(_,_,...)\n\t\tlocal ok, msg, len = pcall(auth_fd, ...)\n\t\tif ok then\n\t\t\tskynet.ret(msg,len)\n\t\telse\n\t\t\tskynet.ret(skynet.pack(false, msg))\n\t\tend\n\tend)\nend\n\nlocal user_login = {}\n\nlocal function accept(conf, s, fd, addr)\n\t-- call slave auth\n\tlocal ok, server, uid, secret = skynet.call(s, \"lua\",  fd, addr)\n\t-- slave will accept(start) fd, so we can write to fd later\n\n\tif not ok then\n\t\tif ok ~= nil then\n\t\t\twrite(\"response 401\", fd, \"401 Unauthorized\\n\")\n\t\tend\n\t\terror(server)\n\tend\n\n\tif not conf.multilogin then\n\t\tif user_login[uid] then\n\t\t\twrite(\"response 406\", fd, \"406 Not Acceptable\\n\")\n\t\t\terror(string.format(\"User %s is already login\", uid))\n\t\tend\n\n\t\tuser_login[uid] = true\n\tend\n\n\tlocal ok, err = pcall(conf.login_handler, server, uid, secret)\n\t-- unlock login\n\tuser_login[uid] = nil\n\n\tif ok then\n\t\terr = err or \"\"\n\t\twrite(\"response 200\",fd,  \"200 \"..crypt.base64encode(err)..\"\\n\")\n\telse\n\t\twrite(\"response 403\",fd,  \"403 Forbidden\\n\")\n\t\terror(err)\n\tend\nend\n\nlocal function launch_master(conf)\n\tlocal instance = conf.instance or 8\n\tassert(instance > 0)\n\tlocal host = conf.host or \"0.0.0.0\"\n\tlocal port = assert(tonumber(conf.port))\n\tlocal slave = {}\n\tlocal balance = 1\n\n\tskynet.dispatch(\"lua\", function(_,source,command, ...)\n\t\tskynet.ret(skynet.pack(conf.command_handler(command, ...)))\n\tend)\n\n\tfor i=1,instance do\n\t\ttable.insert(slave, skynet.newservice(SERVICE_NAME))\n\tend\n\n\tskynet.error(string.format(\"login server listen at : %s %d\", host, port))\n\tlocal id = socket.listen(host, port)\n\tsocket.start(id , function(fd, addr)\n\t\tlocal s = slave[balance]\n\t\tbalance = balance + 1\n\t\tif balance > #slave then\n\t\t\tbalance = 1\n\t\tend\n\t\tlocal ok, err = pcall(accept, conf, s, fd, addr)\n\t\tif not ok then\n\t\t\tif err ~= socket_error then\n\t\t\t\tskynet.error(string.format(\"invalid client (fd = %d) error = %s\", fd, err))\n\t\t\tend\n\t\tend\n\t\tsocket.close(fd)\n\tend)\nend\n\nlocal function login(conf)\n\tlocal name = \".\" .. (conf.name or \"login\")\n\tskynet.start(function()\n\t\tlocal loginmaster = skynet.localname(name)\n\t\tif loginmaster then\n\t\t\tlocal auth_handler = assert(conf.auth_handler)\n\t\t\tlaunch_master = nil\n\t\t\tconf = nil\n\t\t\tlaunch_slave(auth_handler)\n\t\telse\n\t\t\tlaunch_slave = nil\n\t\t\tconf.auth_handler = nil\n\t\t\tassert(conf.login_handler)\n\t\t\tassert(conf.command_handler)\n\t\t\tskynet.register(name)\n\t\t\tlaunch_master(conf)\n\t\tend\n\tend)\nend\n\nreturn login\n"
  },
  {
    "path": "lualib/snax/msgserver.lua",
    "content": "local skynet = require \"skynet\"\nlocal gateserver = require \"snax.gateserver\"\nlocal netpack = require \"skynet.netpack\"\nlocal crypt = require \"skynet.crypt\"\nlocal socketdriver = require \"skynet.socketdriver\"\nlocal assert = assert\nlocal b64encode = crypt.base64encode\nlocal b64decode = crypt.base64decode\n\n--[[\n\nProtocol:\n\n\tAll the number type is big-endian\n\n\tShakehands (The first package)\n\n\tClient -> Server :\n\n\tbase64(uid)@base64(server)#base64(subid):index:base64(hmac)\n\n\tServer -> Client\n\n\tXXX ErrorCode\n\t\t404 User Not Found\n\t\t403 Index Expired\n\t\t401 Unauthorized\n\t\t400 Bad Request\n\t\t200 OK\n\n\tReq-Resp\n\n\tClient -> Server : Request\n\t\tword size (Not include self)\n\t\tstring content (size-4)\n\t\tdword session\n\n\tServer -> Client : Response\n\t\tword size (Not include self)\n\t\tstring content (size-5)\n\t\tbyte ok (1 is ok, 0 is error)\n\t\tdword session\n\nAPI:\n\tserver.userid(username)\n\t\treturn uid, subid, server\n\n\tserver.username(uid, subid, server)\n\t\treturn username\n\n\tserver.login(username, secret)\n\t\tupdate user secret\n\n\tserver.logout(username)\n\t\tuser logout\n\n\tserver.ip(username)\n\t\treturn ip when connection establish, or nil\n\n\tserver.start(conf)\n\t\tstart server\n\nSupported skynet command:\n\tkick username (may used by loginserver)\n\tlogin username secret  (used by loginserver)\n\tlogout username (used by agent)\n\nConfig for server.start:\n\tconf.expired_number : the number of the response message cached after sending out (default is 128)\n\tconf.login_handler(uid, secret) -> subid : the function when a new user login, alloc a subid for it. (may call by login server)\n\tconf.logout_handler(uid, subid) : the functon when a user logout. (may call by agent)\n\tconf.kick_handler(uid, subid) : the functon when a user logout. (may call by login server)\n\tconf.request_handler(username, session, msg) : the function when recv a new request.\n\tconf.register_handler(servername) : call when gate open\n\tconf.disconnect_handler(username) : call when a connection disconnect (afk)\n]]\n\nlocal server = {}\n\nskynet.register_protocol {\n\tname = \"client\",\n\tid = skynet.PTYPE_CLIENT,\n}\n\nlocal user_online = {}\nlocal handshake = {}\nlocal connection = {}\n\nfunction server.userid(username)\n\t-- base64(uid)@base64(server)#base64(subid)\n\tlocal uid, servername, subid = username:match \"([^@]*)@([^#]*)#(.*)\"\n\treturn b64decode(uid), b64decode(subid), b64decode(servername)\nend\n\nfunction server.username(uid, subid, servername)\n\treturn string.format(\"%s@%s#%s\", b64encode(uid), b64encode(servername), b64encode(tostring(subid)))\nend\n\nfunction server.logout(username)\n\tlocal u = user_online[username]\n\tuser_online[username] = nil\n\tif u.fd then\n\t\tif connection[u.fd] then\n\t\t\tgateserver.closeclient(u.fd)\n\t\t\tconnection[u.fd] = nil\n\t\tend\n\tend\nend\n\nfunction server.login(username, secret)\n\tassert(user_online[username] == nil)\n\tuser_online[username] = {\n\t\tsecret = secret,\n\t\tversion = 0,\n\t\tindex = 0,\n\t\tusername = username,\n\t\tresponse = {},\t-- response cache\n\t}\nend\n\nfunction server.ip(username)\n\tlocal u = user_online[username]\n\tif u and u.fd then\n\t\treturn u.ip\n\tend\nend\n\nfunction server.start(conf)\n\tlocal expired_number = conf.expired_number or 128\n\n\tlocal handler = {}\n\n\tlocal CMD = {\n\t\tlogin = assert(conf.login_handler),\n\t\tlogout = assert(conf.logout_handler),\n\t\tkick = assert(conf.kick_handler),\n\t}\n\n\tfunction handler.command(cmd, source, ...)\n\t\tlocal f = assert(CMD[cmd])\n\t\treturn f(...)\n\tend\n\n\tfunction handler.open(source, gateconf)\n\t\tlocal servername = assert(gateconf.servername)\n\t\treturn conf.register_handler(servername)\n\tend\n\n\tfunction handler.connect(fd, addr)\n\t\thandshake[fd] = addr\n\t\tgateserver.openclient(fd)\n\tend\n\n\tfunction handler.disconnect(fd)\n\t\thandshake[fd] = nil\n\t\tlocal c = connection[fd]\n\t\tif c then\n\t\t\tif conf.disconnect_handler then\n\t\t\t\tconf.disconnect_handler(c.username)\n\t\t\tend\n\t\t\t-- double check, conf.disconnect_handler may close fd\n\t\t\tif connection[fd] then\n\t\t\t\tc.fd = nil\n\t\t\t\tconnection[fd] = nil\n\t\t\t\tgateserver.closeclient(fd)\n\t\t\tend\n\t\tend\n\tend\n\n\thandler.error = handler.disconnect\n\n\t-- atomic , no yield\n\tlocal function do_auth(fd, message, addr)\n\t\tlocal username, index, hmac = string.match(message, \"([^:]*):([^:]*):([^:]*)\")\n\t\tlocal u = user_online[username]\n\t\tif u == nil then\n\t\t\treturn \"404 User Not Found\"\n\t\tend\n\t\tlocal idx = assert(tonumber(index))\n\t\thmac = b64decode(hmac)\n\n\t\tif idx <= u.version then\n\t\t\treturn \"403 Index Expired\"\n\t\tend\n\n\t\tlocal text = string.format(\"%s:%s\", username, index)\n\t\tlocal v = crypt.hmac_hash(u.secret, text)\t-- equivalent to crypt.hmac64(crypt.hashkey(text), u.secret)\n\t\tif v ~= hmac then\n\t\t\treturn \"401 Unauthorized\"\n\t\tend\n\n\t\tu.version = idx\n\t\tu.fd = fd\n\t\tu.ip = addr\n\t\tconnection[fd] = u\n\tend\n\n\tlocal function auth(fd, addr, msg, sz)\n\t\tlocal message = netpack.tostring(msg, sz)\n\t\tlocal ok, result = pcall(do_auth, fd, message, addr)\n\t\tif not ok then\n\t\t\tskynet.error(result)\n\t\t\tresult = \"400 Bad Request\"\n\t\tend\n\n\t\tlocal close = result ~= nil\n\n\t\tif result == nil then\n\t\t\tresult = \"200 OK\"\n\t\tend\n\n\t\tsocketdriver.send(fd, netpack.pack(result))\n\n\t\tif close then\n\t\t\tgateserver.closeclient(fd)\n\t\tend\n\tend\n\n\tlocal request_handler = assert(conf.request_handler)\n\n\t-- u.response is a struct { return_fd , response, version, index }\n\tlocal function retire_response(u)\n\t\tif u.index >= expired_number * 2 then\n\t\t\tlocal max = 0\n\t\t\tlocal response = u.response\n\t\t\tfor k,p in pairs(response) do\n\t\t\t\tif p[1] == nil then\n\t\t\t\t\t-- request complete, check expired\n\t\t\t\t\tif p[4] < expired_number then\n\t\t\t\t\t\tresponse[k] = nil\n\t\t\t\t\telse\n\t\t\t\t\t\tp[4] = p[4] - expired_number\n\t\t\t\t\t\tif p[4] > max then\n\t\t\t\t\t\t\tmax = p[4]\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tu.index = max + 1\n\t\tend\n\tend\n\n\tlocal function do_request(fd, message)\n\t\tlocal u = assert(connection[fd], \"invalid fd\")\n\t\tlocal session = string.unpack(\">I4\", message, -4)\n\t\tmessage = message:sub(1,-5)\n\t\tlocal p = u.response[session]\n\t\tif p then\n\t\t\t-- session can be reuse in the same connection\n\t\t\tif p[3] == u.version then\n\t\t\t\tlocal last = u.response[session]\n\t\t\t\tu.response[session] = nil\n\t\t\t\tp = nil\n\t\t\t\tif last[2] == nil then\n\t\t\t\t\tlocal error_msg = string.format(\"Conflict session %s\", crypt.hexencode(session))\n\t\t\t\t\tskynet.error(error_msg)\n\t\t\t\t\terror(error_msg)\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\t\tif p == nil then\n\t\t\tp = { fd }\n\t\t\tu.response[session] = p\n\t\t\tlocal ok, result = pcall(request_handler, u.username, message)\n\t\t\t-- NOTICE: YIELD here, socket may close.\n\t\t\tresult = result or \"\"\n\t\t\tif not ok then\n\t\t\t\tskynet.error(result)\n\t\t\t\tresult = string.pack(\">BI4\", 0, session)\n\t\t\telse\n\t\t\t\tresult = result .. string.pack(\">BI4\", 1, session)\n\t\t\tend\n\n\t\t\tp[2] = string.pack(\">s2\",result)\n\t\t\tp[3] = u.version\n\t\t\tp[4] = u.index\n\t\telse\n\t\t\t-- update version/index, change return fd.\n\t\t\t-- resend response.\n\t\t\tp[1] = fd\n\t\t\tp[3] = u.version\n\t\t\tp[4] = u.index\n\t\t\tif p[2] == nil then\n\t\t\t\t-- already request, but response is not ready\n\t\t\t\treturn\n\t\t\tend\n\t\tend\n\t\tu.index = u.index + 1\n\t\t-- the return fd is p[1] (fd may change by multi request) check connect\n\t\tfd = p[1]\n\t\tif connection[fd] then\n\t\t\tsocketdriver.send(fd, p[2])\n\t\tend\n\t\tp[1] = nil\n\t\tretire_response(u)\n\tend\n\n\tlocal function request(fd, msg, sz)\n\t\tlocal message = netpack.tostring(msg, sz)\n\t\tlocal ok, err = pcall(do_request, fd, message)\n\t\t-- not atomic, may yield\n\t\tif not ok then\n\t\t\tskynet.error(string.format(\"Invalid package %s : %s\", err, message))\n\t\t\tif connection[fd] then\n\t\t\t\tgateserver.closeclient(fd)\n\t\t\tend\n\t\tend\n\tend\n\n\tfunction handler.message(fd, msg, sz)\n\t\tlocal addr = handshake[fd]\n\t\tif addr then\n\t\t\tauth(fd,addr,msg,sz)\n\t\t\thandshake[fd] = nil\n\t\telse\n\t\t\trequest(fd, msg, sz)\n\t\tend\n\tend\n\n\treturn gateserver.start(handler)\nend\n\nreturn server\n"
  },
  {
    "path": "lualib/sproto.lua",
    "content": "local core = require \"sproto.core\"\nlocal assert = assert\n\nlocal sproto = {}\nlocal host = {}\n\nlocal weak_mt = { __mode = \"kv\" }\nlocal sproto_mt = { __index = sproto }\nlocal sproto_nogc = { __index = sproto }\nlocal host_mt = { __index = host }\n\nfunction sproto_mt:__gc()\n\tcore.deleteproto(self.__cobj)\nend\n\nfunction sproto.new(bin)\n\tlocal cobj = assert(core.newproto(bin))\n\tlocal self = {\n\t\t__cobj = cobj,\n\t\t__tcache = setmetatable( {} , weak_mt ),\n\t\t__pcache = setmetatable( {} , weak_mt ),\n\t}\n\treturn setmetatable(self, sproto_mt)\nend\n\nfunction sproto.sharenew(cobj)\n\tlocal self = {\n\t\t__cobj = cobj,\n\t\t__tcache = setmetatable( {} , weak_mt ),\n\t\t__pcache = setmetatable( {} , weak_mt ),\n\t}\n\treturn setmetatable(self, sproto_nogc)\nend\n\nfunction sproto.parse(ptext)\n\tlocal parser = require \"sprotoparser\"\n\tlocal pbin = parser.parse(ptext)\n\treturn sproto.new(pbin)\nend\n\nfunction sproto:host( packagename )\n\tpackagename = packagename or  \"package\"\n\tlocal obj = {\n\t\t__proto = self,\n\t\t__package = assert(core.querytype(self.__cobj, packagename), \"type package not found\"),\n\t\t__session = {},\n\t}\n\treturn setmetatable(obj, host_mt)\nend\n\nlocal function querytype(self, typename)\n\tlocal v = self.__tcache[typename]\n\tif not v then\n\t\tv = assert(core.querytype(self.__cobj, typename), \"type not found\")\n\t\tself.__tcache[typename] = v\n\tend\n\n\treturn v\nend\n\nfunction sproto:exist_type(typename)\n\tlocal v = self.__tcache[typename]\n\tif not v then\n\t\treturn core.querytype(self.__cobj, typename) ~= nil\n\telse\n\t\treturn true\n\tend\nend\n\nfunction sproto:encode(typename, tbl)\n\tlocal st = querytype(self, typename)\n\treturn core.encode(st, tbl)\nend\n\nfunction sproto:decode(typename, ...)\n\tlocal st = querytype(self, typename)\n\treturn core.decode(st, ...)\nend\n\nfunction sproto:pencode(typename, tbl)\n\tlocal st = querytype(self, typename)\n\treturn core.pack(core.encode(st, tbl))\nend\n\nfunction sproto:pdecode(typename, ...)\n\tlocal st = querytype(self, typename)\n\treturn core.decode(st, core.unpack(...))\nend\n\nlocal function queryproto(self, pname)\n\tlocal v = self.__pcache[pname]\n\tif not v then\n\t\tlocal tag, req, resp = core.protocol(self.__cobj, pname)\n\t\tassert(tag, pname .. \" not found\")\n\t\tif tonumber(pname) then\n\t\t\tpname, tag = tag, pname\n\t\tend\n\t\tv = {\n\t\t\trequest = req,\n\t\t\tresponse =resp,\n\t\t\tname = pname,\n\t\t\ttag = tag,\n\t\t}\n\t\tself.__pcache[pname] = v\n\t\tself.__pcache[tag]  = v\n\tend\n\n\treturn v\nend\nsproto.queryproto = queryproto\n\nfunction sproto:exist_proto(pname)\n\tlocal v = self.__pcache[pname]\n\tif not v then\n\t\treturn core.protocol(self.__cobj, pname) ~= nil\n\telse\n\t\treturn true\n\tend\nend\n\nfunction sproto:request_encode(protoname, tbl)\n\tlocal p = queryproto(self, protoname)\n\tlocal request = p.request\n\tif request then\n\t\treturn core.encode(request,tbl) , p.tag\n\telse\n\t\treturn \"\" , p.tag\n\tend\nend\n\nfunction sproto:response_encode(protoname, tbl)\n\tlocal p = queryproto(self, protoname)\n\tlocal response = p.response\n\tif response then\n\t\treturn core.encode(response,tbl)\n\telse\n\t\treturn \"\"\n\tend\nend\n\nfunction sproto:request_decode(protoname, ...)\n\tlocal p = queryproto(self, protoname)\n\tlocal request = p.request\n\tif request then\n\t\treturn core.decode(request,...) , p.name\n\telse\n\t\treturn nil, p.name\n\tend\nend\n\nfunction sproto:response_decode(protoname, ...)\n\tlocal p = queryproto(self, protoname)\n\tlocal response = p.response\n\tif response then\n\t\treturn core.decode(response,...)\n\tend\nend\n\nsproto.pack = core.pack\nsproto.unpack = core.unpack\n\nfunction sproto:default(typename, type)\n\tif type == nil then\n\t\treturn core.default(querytype(self, typename))\n\telse\n\t\tlocal p = queryproto(self, typename)\n\t\tif type == \"REQUEST\" then\n\t\t\tif p.request then\n\t\t\t\treturn core.default(p.request)\n\t\t\tend\n\t\telseif type == \"RESPONSE\" then\n\t\t\tif p.response then\n\t\t\t\treturn core.default(p.response)\n\t\t\tend\n\t\telse\n\t\t\terror \"Invalid type\"\n\t\tend\n\tend\nend\n\nlocal header_tmp = {}\n\nlocal function gen_response(self, response, session)\n\treturn function(args, ud)\n\t\theader_tmp.type = nil\n\t\theader_tmp.session = session\n\t\theader_tmp.ud = ud\n\t\tlocal header = core.encode(self.__package, header_tmp)\n\t\tif response then\n\t\t\tlocal content = core.encode(response, args)\n\t\t\treturn core.pack(header .. content)\n\t\telse\n\t\t\treturn core.pack(header)\n\t\tend\n\tend\nend\n\nfunction host:dispatch(...)\n\tlocal bin = core.unpack(...)\n\theader_tmp.type = nil\n\theader_tmp.session = nil\n\theader_tmp.ud = nil\n\tlocal header, size = core.decode(self.__package, bin, header_tmp)\n\tlocal content = bin:sub(size + 1)\n\tif header.type then\n\t\t-- request\n\t\tlocal proto = queryproto(self.__proto, header.type)\n\t\tlocal result\n\t\tif proto.request then\n\t\t\tresult = core.decode(proto.request, content)\n\t\tend\n\t\tif header_tmp.session then\n\t\t\treturn \"REQUEST\", proto.name, result, gen_response(self, proto.response, header_tmp.session), header.ud\n\t\telse\n\t\t\treturn \"REQUEST\", proto.name, result, nil, header.ud\n\t\tend\n\telse\n\t\t-- response\n\t\tlocal session = assert(header_tmp.session, \"session not found\")\n\t\tlocal response = assert(self.__session[session], \"Unknown session\")\n\t\tself.__session[session] = nil\n\t\tif response == true then\n\t\t\treturn \"RESPONSE\", session, nil, header.ud\n\t\telse\n\t\t\tlocal result = core.decode(response, content)\n\t\t\treturn \"RESPONSE\", session, result, header.ud\n\t\tend\n\tend\nend\n\nfunction host:attach(sp)\n\treturn function(name, args, session, ud)\n\t\tlocal proto = queryproto(sp, name)\n\t\theader_tmp.type = proto.tag\n\t\theader_tmp.session = session\n\t\theader_tmp.ud = ud\n\t\tlocal header = core.encode(self.__package, header_tmp)\n\n\t\tif session then\n\t\t\tself.__session[session] = proto.response or true\n\t\tend\n\n\t\tif proto.request then\n\t\t\tlocal content = core.encode(proto.request, args)\n\t\t\treturn core.pack(header ..  content)\n\t\telse\n\t\t\treturn core.pack(header)\n\t\tend\n\tend\nend\n\nreturn sproto\n"
  },
  {
    "path": "lualib/sprotoloader.lua",
    "content": "local parser = require \"sprotoparser\"\nlocal core = require \"sproto.core\"\nlocal sproto = require \"sproto\"\n\nlocal loader = {}\n\nfunction loader.register(filename, index)\n\tlocal f = assert(io.open(filename), \"Can't open sproto file\")\n\tlocal data = f:read \"a\"\n\tf:close()\n\tlocal sp = core.newproto(parser.parse(data))\n\tcore.saveproto(sp, index)\nend\n\nfunction loader.save(bin, index)\n\tlocal sp = core.newproto(bin)\n\tcore.saveproto(sp, index)\nend\n\nfunction loader.load(index)\n\tlocal sp = core.loadproto(index)\n\t--  no __gc in metatable\n\treturn sproto.sharenew(sp)\nend\n\nreturn loader\n\n"
  },
  {
    "path": "lualib/sprotoparser.lua",
    "content": "local lpeg = require \"lpeg\"\nlocal table = require \"table\"\n\nlocal packbytes\nlocal packvalue\n\nlocal version = _VERSION:match \"5.*\"\n\nif version and tonumber(version) >= 5.3 then\n\tfunction packbytes(str)\n\t\treturn string.pack(\"<s4\",str)\n\tend\n\n\tfunction packvalue(id)\n\t\tid = (id + 1) * 2\n\t\treturn string.pack(\"<I2\",id)\n\tend\nelse\n\tfunction packbytes(str)\n\t\tlocal size = #str\n\t\tlocal a = size % 256\n\t\tsize = math.floor(size / 256)\n\t\tlocal b = size % 256\n\t\tsize = math.floor(size / 256)\n\t\tlocal c = size % 256\n\t\tsize = math.floor(size / 256)\n\t\tlocal d = size\n\t\treturn string.char(a)..string.char(b)..string.char(c)..string.char(d) .. str\n\tend\n\n\tfunction packvalue(id)\n\t\tid = (id + 1) * 2\n\t\tassert(id >=0 and id < 65536)\n\t\tlocal a = id % 256\n\t\tlocal b = math.floor(id / 256)\n\t\treturn string.char(a) .. string.char(b)\n\tend\nend\n\nlocal P = lpeg.P\nlocal S = lpeg.S\nlocal R = lpeg.R\nlocal C = lpeg.C\nlocal Ct = lpeg.Ct\nlocal Cg = lpeg.Cg\nlocal Cc = lpeg.Cc\nlocal V = lpeg.V\n\nlocal function count_lines(_,pos, parser_state)\n\tif parser_state.pos < pos then\n\t\tparser_state.line = parser_state.line + 1\n\t\tparser_state.pos = pos\n\tend\n\treturn pos\nend\n\nlocal exception = lpeg.Cmt( lpeg.Carg(1) , function ( _ , pos, parser_state)\n\terror(string.format(\"syntax error at [%s] line (%d)\", parser_state.file or \"\", parser_state.line))\n\treturn pos\nend)\n\nlocal eof = P(-1)\nlocal newline = lpeg.Cmt((P\"\\n\" + \"\\r\\n\") * lpeg.Carg(1) ,count_lines)\nlocal line_comment = \"#\" * (1 - newline) ^0 * (newline + eof)\nlocal blank = S\" \\t\" + newline + line_comment\nlocal blank0 = blank ^ 0\nlocal blanks = blank ^ 1\nlocal alpha = R\"az\" + R\"AZ\" + \"_\"\nlocal alnum = alpha + R\"09\"\nlocal word = alpha * alnum ^ 0\nlocal name = C(word)\nlocal typename = C(word * (\".\" * word) ^ 0)\nlocal tag = R\"09\" ^ 1 / tonumber\nlocal mainkey = \"(\" * blank0 * C((word ^ 0)) * blank0 * \")\"\nlocal decimal = \"(\" * blank0 * C(tag) * blank0 * \")\"\n\nlocal function multipat(pat)\n\treturn Ct(blank0 * (pat * blanks) ^ 0 * pat^0 * blank0)\nend\n\nlocal function namedpat(name, pat)\n\treturn Ct(Cg(Cc(name), \"type\") * Cg(pat))\nend\n\nlocal typedef = P {\n\t\"ALL\",\n\tFIELD = namedpat(\"field\", name * blanks * tag * blank0 * \":\" * blank0 * (C\"*\")^-1 * typename * (mainkey + decimal)^0),\n\tSTRUCT = P\"{\" * multipat(V\"FIELD\" + V\"TYPE\") * P\"}\",\n\tTYPE = namedpat(\"type\", P\".\" * name * blank0 * V\"STRUCT\" ),\n\tSUBPROTO = Ct((C\"request\" + C\"response\") * blanks * (typename + V\"STRUCT\")),\n\tPROTOCOL = namedpat(\"protocol\", name * blanks * tag * blank0 * P\"{\" * multipat(V\"SUBPROTO\") * P\"}\"),\n\tALL = multipat(V\"TYPE\" + V\"PROTOCOL\"),\n}\n\nlocal proto = blank0 * typedef * blank0\n\nlocal convert = {}\n\nfunction convert.protocol(all, obj)\n\tlocal result = { tag = obj[2] }\n\tfor _, p in ipairs(obj[3]) do\n\t\tlocal pt = p[1]\n\t\tif result[pt] ~= nil then\n\t\t\terror(string.format(\"redefine %s in protocol %s\", pt, obj[1]))\n\t\tend\n\t\tlocal typename = p[2]\n\t\tif type(typename) == \"table\" then\n\t\t\tlocal struct = typename\n\t\t\ttypename = obj[1] .. \".\" .. p[1]\n\t\t\tall.type[typename] = convert.type(all, { typename, struct })\n\t\tend\n\t\tif typename == \"nil\" then\n\t\t\tif p[1] == \"response\" then\n\t\t\t\tresult.confirm = true\n\t\t\tend\n\t\telse\n\t\t\tresult[p[1]] = typename\n\t\tend\n\tend\n\treturn result\nend\n\nlocal map_keytypes = {\n\tinteger = true,\n\tstring = true,\n}\n\nfunction convert.type(all, obj)\n\tlocal result = {}\n\tlocal typename = obj[1]\n\tlocal tags = {}\n\tlocal names = {}\n\tfor _, f in ipairs(obj[2]) do\n\t\tif f.type == \"field\" then\n\t\t\tlocal name = f[1]\n\t\t\tif names[name] then\n\t\t\t\terror(string.format(\"redefine %s in type %s\", name, typename))\n\t\t\tend\n\t\t\tnames[name] = true\n\t\t\tlocal tag = f[2]\n\t\t\tif tags[tag] then\n\t\t\t\terror(string.format(\"redefine tag %d in type %s\", tag, typename))\n\t\t\tend\n\t\t\ttags[tag] = true\n\t\t\tlocal field = { name = name, tag = tag }\n\t\t\ttable.insert(result, field)\n\t\t\tlocal fieldtype = f[3]\n\t\t\tif fieldtype == \"*\" then\n\t\t\t\tfield.array = true\n\t\t\t\tfieldtype = f[4]\n\t\t\tend\n\t\t\tlocal mainkey = f[5]\n\t\t\tif mainkey then\n\t\t\t\tif fieldtype == \"integer\" then\n\t\t\t\t\tfield.decimal = mainkey\n\t\t\t\telse\n\t\t\t\t\tassert(field.array)\n\t\t\t\t\tfield.key = mainkey\n\t\t\t\tend\n\t\t\tend\n\t\t\tfield.typename = fieldtype\n\t\telse\n\t\t\tassert(f.type == \"type\")\t-- nest type\n\t\t\tlocal nesttypename = typename .. \".\" .. f[1]\n\t\t\tf[1] = nesttypename\n\t\t\tassert(all.type[nesttypename] == nil, \"redefined \" .. nesttypename)\n\t\t\tall.type[nesttypename] = convert.type(all, f)\n\t\tend\n\tend\n\ttable.sort(result, function(a,b) return a.tag < b.tag end)\n\treturn result\nend\n\nlocal function adjust(r)\n\tlocal result = { type = {} , protocol = {} }\n\n\tfor _, obj in ipairs(r) do\n\t\tlocal set = result[obj.type]\n\t\tlocal name = obj[1]\n\t\tassert(set[name] == nil , \"redefined \" .. name)\n\t\tset[name] = convert[obj.type](result,obj)\n\tend\n\n\treturn result\nend\n\nlocal buildin_types = {\n\tinteger = 0,\n\tboolean = 1,\n\tstring = 2,\n\tbinary = 2,\t-- binary is a sub type of string\n\tdouble = 3,\n}\n\nlocal function checktype(types, ptype, t)\n\tif buildin_types[t] then\n\t\treturn t\n\tend\n\tlocal fullname = ptype .. \".\" .. t\n\tif types[fullname] then\n\t\treturn fullname\n\telse\n\t\tptype = ptype:match \"(.+)%..+$\"\n\t\tif ptype then\n\t\t\treturn checktype(types, ptype, t)\n\t\telseif types[t] then\n\t\t\treturn t\n\t\tend\n\tend\nend\n\nlocal function check_protocol(r)\n\tlocal map = {}\n\tlocal type = r.type\n\tfor name, v in pairs(r.protocol) do\n\t\tlocal tag = v.tag\n\t\tlocal request = v.request\n\t\tlocal response = v.response\n\t\tlocal p = map[tag]\n\n\t\tif p then\n\t\t\terror(string.format(\"redefined protocol tag %d at %s\", tag, name))\n\t\tend\n\n\t\tif request and not type[request] then\n\t\t\terror(string.format(\"Undefined request type %s in protocol %s\", request, name))\n\t\tend\n\n\t\tif response and not type[response] then\n\t\t\terror(string.format(\"Undefined response type %s in protocol %s\", response, name))\n\t\tend\n\n\t\tmap[tag] = v\n\tend\n\treturn r\nend\n\nlocal function flattypename(r)\n\tfor typename, t in pairs(r.type) do\n\t\tfor _, f in pairs(t) do\n\t\t\tlocal ftype = f.typename\n\t\t\tlocal fullname = checktype(r.type, typename, ftype)\n\t\t\tif fullname == nil then\n\t\t\t\terror(string.format(\"Undefined type %s in type %s\", ftype, typename))\n\t\t\tend\n\t\t\tf.typename = fullname\n\t\tend\n\tend\n\n\treturn r\nend\n\nlocal function parser(text,filename)\n\tlocal state = { file = filename, pos = 0, line = 1 }\n\tlocal r = lpeg.match(proto * -1 + exception , text , 1, state )\n\treturn flattypename(check_protocol(adjust(r)))\nend\n\n--[[\n-- The protocol of sproto\n.type {\n\t.field {\n\t\tname 0 : string\n\t\tbuildin\t1 :\tinteger\n\t\ttype 2 : integer\n\t\ttag\t3 :\tinteger\n\t\tarray 4\t: boolean\n\t\tkey 5 : integer # If key exists, array must be true\n\t\tmap 6 : boolean # Interpret two fields struct as map when decoding\n\t}\n\tname 0 : string\n\tfields 1 : *field\n}\n\n.protocol {\n\tname 0 : string\n\ttag\t1 :\tinteger\n\trequest\t2 :\tinteger\t# index\n\tresponse 3 : integer # index\n\tconfirm 4 : boolean # true means response nil\n}\n\n.group {\n\ttype 0 : *type\n\tprotocol 1 : *protocol\n}\n]]\n\nlocal function packfield(f)\n\tlocal strtbl = {}\n\tif f.array then\n\t\tif f.key then\n\t\t\tif f.map then\n\t\t\t\ttable.insert(strtbl, \"\\7\\0\")  -- 7 fields\n\t\t\telse\n\t\t\t\ttable.insert(strtbl, \"\\6\\0\")  -- 6 fields\n\t\t\tend\n\t\telse\n\t\t\ttable.insert(strtbl, \"\\5\\0\")  -- 5 fields\n\t\tend\n\telse\n\t\ttable.insert(strtbl, \"\\4\\0\")\t-- 4 fields\n\tend\n\ttable.insert(strtbl, \"\\0\\0\")\t-- name\t(tag = 0, ref an object)\n\tif f.buildin then\n\t\ttable.insert(strtbl, packvalue(f.buildin))\t-- buildin (tag = 1)\n\t\tif f.extra then\n\t\t\ttable.insert(strtbl, packvalue(f.extra))\t-- f.buildin can be integer or string\n\t\telse\n\t\t\ttable.insert(strtbl, \"\\1\\0\")\t-- skip (tag = 2)\n\t\tend\n\t\ttable.insert(strtbl, packvalue(f.tag))\t\t-- tag (tag = 3)\n\telse\n\t\ttable.insert(strtbl, \"\\1\\0\")\t-- skip (tag = 1)\n\t\ttable.insert(strtbl, packvalue(f.type))\t\t-- type (tag = 2)\n\t\ttable.insert(strtbl, packvalue(f.tag))\t\t-- tag (tag = 3)\n\tend\n\tif f.array then\n\t\ttable.insert(strtbl, packvalue(1))\t-- array = true (tag = 4)\n\t\tif f.key then\n\t\t\ttable.insert(strtbl, packvalue(f.key)) -- key tag (tag = 5)\n\t\t\tif f.map then\n\t\t\t\ttable.insert(strtbl, packvalue(f.map)) -- map tag (tag = 6)\n\t\t\tend\n\t\tend\n\tend\n\ttable.insert(strtbl, packbytes(f.name)) -- external object (name)\n\treturn packbytes(table.concat(strtbl))\nend\n\nlocal function packtype(name, t, alltypes)\n\tlocal fields = {}\n\tlocal tmp = {}\n\tfor _, f in ipairs(t) do\n\t\ttmp.array = f.array\n\t\ttmp.name = f.name\n\t\ttmp.tag = f.tag\n\t\ttmp.extra = f.decimal\n\n\t\ttmp.buildin = buildin_types[f.typename]\n\t\tif f.typename == \"binary\" then\n\t\t\ttmp.extra = 1\t-- binary is sub type of string\n\t\tend\n\t\tlocal subtype\n\t\tif not tmp.buildin then\n\t\t\tsubtype = assert(alltypes[f.typename])\n\t\t\ttmp.type = subtype.id\n\t\telse\n\t\t\ttmp.type = nil\n\t\tend\n\t\ttmp.map = nil\n\t\tif f.key then\n\t\t\tassert(f.array)\n\t\t\tif f.key == \"\" then\n\t\t\t\ttmp.map = 1\n\t\t\t\tlocal c = 0\n\t\t\t\tlocal min_t = math.maxinteger\n\t\t\t\tfor n, t in pairs(subtype.fields) do\n\t\t\t\t\tc = c + 1\n\t\t\t\t\tif t.tag < min_t then\n\t\t\t\t\t\tmin_t = t.tag\n\t\t\t\t\t\tf.key = n\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tif c ~= 2 then\n\t\t\t\t\terror(string.format(\"Invalid map definition: %s, must only have two fields\", tmp.name))\n\t\t\t\tend\n\t\t\tend\n\t\t\tlocal stfield = subtype.fields[f.key]\n\t\t\tif not stfield or not stfield.buildin then\n\t\t\t\terror(\"Invalid map index :\" .. f.key)\n\t\t\tend\n\t\t\ttmp.key = stfield.tag\n\t\telse\n\t\t\ttmp.key = nil\n\t\tend\n\n\t\ttable.insert(fields, packfield(tmp))\n\tend\n\tlocal data\n\tif #fields == 0 then\n\t\tdata = {\n\t\t\t\"\\1\\0\",\t-- 1 fields\n\t\t\t\"\\0\\0\",\t-- name\t(id = 0, ref = 0)\n\t\t\tpackbytes(name),\n\t\t}\n\telse\n\t\tdata = {\n\t\t\t\"\\2\\0\",\t-- 2 fields\n\t\t\t\"\\0\\0\",\t-- name\t(tag = 0, ref = 0)\n\t\t\t\"\\0\\0\", -- field[]\t(tag = 1, ref = 1)\n\t\t\tpackbytes(name),\n\t\t\tpackbytes(table.concat(fields)),\n\t\t}\n\tend\n\n\treturn packbytes(table.concat(data))\nend\n\nlocal function packproto(name, p, alltypes)\n\tif p.request then\n\t\tlocal request = alltypes[p.request]\n\t\tif request == nil then\n\t\t\terror(string.format(\"Protocol %s request type %s not found\", name, p.request))\n\t\tend\n\t\trequest = request.id\n\tend\n\tlocal tmp = {\n\t\t\"\\4\\0\",\t-- 4 fields\n\t\t\"\\0\\0\",\t-- name (id=0, ref=0)\n\t\tpackvalue(p.tag),\t-- tag (tag=1)\n\t}\n\tif p.request == nil and p.response == nil and p.confirm == nil then\n\t\ttmp[1] = \"\\2\\0\"\t-- only two fields\n\telse\n\t\tif p.request then\n\t\t\ttable.insert(tmp, packvalue(alltypes[p.request].id)) -- request typename (tag=2)\n\t\telse\n\t\t\ttable.insert(tmp, \"\\1\\0\")\t-- skip this field (request)\n\t\tend\n\t\tif p.response then\n\t\t\ttable.insert(tmp, packvalue(alltypes[p.response].id)) -- request typename (tag=3)\n\t\telseif p.confirm then\n\t\t\ttmp[1] = \"\\5\\0\"\t-- add confirm field\n\t\t\ttable.insert(tmp, \"\\1\\0\")\t-- skip this field (response)\n\t\t\ttable.insert(tmp, packvalue(1))\t-- confirm = true\n\t\telse\n\t\t\ttmp[1] = \"\\3\\0\"\t-- only three fields\n\t\tend\n\tend\n\n\ttable.insert(tmp, packbytes(name))\n\n\treturn packbytes(table.concat(tmp))\nend\n\nlocal function packgroup(t,p)\n\tif next(t) == nil then\n\t\tassert(next(p) == nil)\n\t\treturn \"\\0\\0\"\n\tend\n\tlocal tt, tp\n\tlocal alltypes = {}\n\tfor name in pairs(t) do\n\t\ttable.insert(alltypes, name)\n\tend\n\ttable.sort(alltypes)\t-- make result stable\n\tfor idx, name in ipairs(alltypes) do\n\t\tlocal fields = {}\n\t\tfor _, type_fields in ipairs(t[name]) do\n\t\t\tfields[type_fields.name] = {\n\t\t\t\ttag = type_fields.tag,\n\t\t\t\tbuildin = buildin_types[type_fields.typename]\n\t\t\t}\n\t\tend\n\t\talltypes[name] = { id = idx - 1, fields = fields }\n\tend\n\ttt = {}\n\tfor _,name in ipairs(alltypes) do\n\t\ttable.insert(tt, packtype(name, t[name], alltypes))\n\tend\n\ttt = packbytes(table.concat(tt))\n\tif next(p) then\n\t\tlocal tmp = {}\n\t\tfor name, tbl in pairs(p) do\n\t\t\ttable.insert(tmp, tbl)\n\t\t\ttbl.name = name\n\t\tend\n\t\ttable.sort(tmp, function(a,b) return a.tag < b.tag end)\n\n\t\ttp = {}\n\t\tfor _, tbl in ipairs(tmp) do\n\t\t\ttable.insert(tp, packproto(tbl.name, tbl, alltypes))\n\t\tend\n\t\ttp = packbytes(table.concat(tp))\n\tend\n\tlocal result\n\tif tp == nil then\n\t\tresult = {\n\t\t\t\"\\1\\0\",\t-- 1 field\n\t\t\t\"\\0\\0\",\t-- type[] (id = 0, ref = 0)\n\t\t\ttt,\n\t\t}\n\telse\n\t\tresult = {\n\t\t\t\"\\2\\0\",\t-- 2fields\n\t\t\t\"\\0\\0\",\t-- type array\t(id = 0, ref = 0)\n\t\t\t\"\\0\\0\",\t-- protocol array\t(id = 1, ref =1)\n\n\t\t\ttt,\n\t\t\ttp,\n\t\t}\n\tend\n\n\treturn table.concat(result)\nend\n\nlocal function encodeall(r)\n\treturn packgroup(r.type, r.protocol)\nend\n\nlocal sparser = {}\n\nfunction sparser.dump(str)\n\tlocal tmp = \"\"\n\tfor i=1,#str do\n\t\ttmp = tmp .. string.format(\"%02X \", string.byte(str,i))\n\t\tif i % 8 == 0 then\n\t\t\tif i % 16 == 0 then\n\t\t\t\tprint(tmp)\n\t\t\t\ttmp = \"\"\n\t\t\telse\n\t\t\t\ttmp = tmp .. \"- \"\n\t\t\tend\n\t\tend\n\tend\n\tprint(tmp)\nend\n\nfunction sparser.parse(text, name)\n\tlocal r = parser(text, name or \"=text\")\n\tlocal data = encodeall(r)\n\treturn data\nend\n\nreturn sparser\n"
  },
  {
    "path": "lualib-src/lsha1.c",
    "content": "/*\nSHA-1 in C\nBy Steve Reid <sreid@sea-to-sky.net>\n100% Public\tDomain\n\n-----------------\nModified 7/98\nBy James H.\tBrown <jbrown@burgoyne.com>\nStill 100% Public Domain\n\nCorrected a\tproblem\twhich generated\timproper hash values on\t16 bit machines\nRoutine\tSHA1Update changed from\n\tvoid SHA1Update(SHA1_CTX* context, unsigned\tchar* data,\tunsigned int\nlen)\nto\n\tvoid SHA1Update(SHA1_CTX* context, unsigned\tchar* data,\tunsigned\nlong len)\n\nThe\t'len' parameter\twas\tdeclared an\tint\twhich works\tfine on\t32 bit machines.\nHowever, on\t16 bit machines\tan int is too small\tfor\tthe\tshifts being done\nagainst\nit.\t This caused the hash function to generate incorrect values\tif len was\ngreater\tthan 8191 (8K -\t1) due to the 'len << 3' on\tline 3 of SHA1Update().\n\nSince the file IO in main()\treads 16K at a time, any file 8K or\tlarger would\nbe guaranteed to generate the wrong\thash (e.g. Test\tVector #3, a million\n\"a\"s).\n\nI also changed the declaration of variables\ti &\tj in SHA1Update\tto\nunsigned long from unsigned\tint\tfor\tthe\tsame reason.\n\nThese changes should make no difference\tto any 32 bit implementations since\nan\nint\tand\ta long are the same\tsize in\tthose environments.\n\n--\nI also corrected a few compiler\twarnings generated by Borland C.\n1. Added #include <process.h> for exit() prototype\n2. Removed unused variable 'j' in SHA1Final\n3. Changed exit(0) to return(0)\tat end of main.\n\nALL\tchanges\tI made can be located by searching for comments\tcontaining 'JHB'\n-----------------\nModified 8/98\nBy Steve Reid <sreid@sea-to-sky.net>\nStill 100% public domain\n\n1- Removed #include\t<process.h>\tand\tused return() instead of exit()\n2- Fixed overwriting of\tfinalcount in SHA1Final() (discovered by Chris Hall)\n3- Changed email address from steve@edmweb.com to sreid@sea-to-sky.net\n\n-----------------\nModified 4/01\nBy Saul\tKravitz\t<Saul.Kravitz@celera.com>\nStill 100% PD\nModified to\trun\ton Compaq Alpha\thardware.\n\n-----------------\nModified 07/2002\nBy Ralph Giles <giles@ghostscript.com>\nStill 100% public domain\nmodified for use with stdint types,\tautoconf\ncode cleanup, removed attribution comments\nswitched SHA1Final() argument order\tfor\tconsistency\nuse\tSHA1_ prefix for public\tapi\nmove public\tapi\tto sha1.h\n\n-----------------\nModufiled 08/2014\nBy Cloud Wu <cloudwu@gmail.com>\nStill 100% PD\nLua binding\n*/\n\n/*\nTest Vectors (from FIPS\tPUB\t180-1)\n\"abc\"\n  A9993E36 4706816A\tBA3E2571 7850C26C 9CD0D89D\n\"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\"\n  84983E44 1C3BD26E\tBAAE4AA1 F95129E5 E54670F1\nA million repetitions of \"a\"\n  34AA973C D4C4DAA4\tF61EEB2B DBAD2731 6534016F\n*/\n\n#define LUA_LIB\n\n#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n \ntypedef struct {\n\tuint32_t state[5];\n\tuint32_t count[2];\n\tuint8_t  buffer[64];\n} SHA1_CTX;\n \n#define SHA1_DIGEST_SIZE 20\n\nstatic void\tSHA1_Transform(uint32_t\tstate[5], const\tuint8_t\tbuffer[64]);\n\n#define\trol(value, bits) (((value) << (bits)) |\t((value) >>\t(32\t- (bits))))\n\n/* blk0() and blk()\tperform\tthe\tinitial\texpand.\t*/\n/* I got the idea of expanding during the round\tfunction from SSLeay */\n/* FIXME: can we do\tthis in\tan endian-proof\tway? */\n#ifdef WORDS_BIGENDIAN\n#define\tblk0(i)\tblock.l[i]\n#else\n#define\tblk0(i)\t(block.l[i]\t= (rol(block.l[i],24)&0xFF00FF00) \\\n\t|(rol(block.l[i],8)&0x00FF00FF))\n#endif\n#define\tblk(i) (block.l[i&15] =\trol(block.l[(i+13)&15]^block.l[(i+8)&15] \\\n\t^block.l[(i+2)&15]^block.l[i&15],1))\n\n/* (R0+R1),\tR2,\tR3,\tR4 are the different operations\tused in\tSHA1 */\n#define\tR0(v,w,x,y,z,i)\tz+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);\n#define\tR1(v,w,x,y,z,i)\tz+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);\n#define\tR2(v,w,x,y,z,i)\tz+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);\n#define\tR3(v,w,x,y,z,i)\tz+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);\n#define\tR4(v,w,x,y,z,i)\tz+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);\n\n\n/* Hash\ta single 512-bit block.\tThis is\tthe\tcore of\tthe\talgorithm. */\nstatic void\tSHA1_Transform(uint32_t\tstate[5], const\tuint8_t\tbuffer[64])\n{\n\tuint32_t a,\tb, c, d, e;\n\ttypedef\tunion {\n\t\tuint8_t\tc[64];\n\t\tuint32_t l[16];\n\t} CHAR64LONG16;\n\tCHAR64LONG16 block;\n\n\tmemcpy(&block, buffer, 64);\n\n\t/* Copy\tcontext->state[] to\tworking\tvars */\n\ta =\tstate[0];\n\tb =\tstate[1];\n\tc =\tstate[2];\n\td =\tstate[3];\n\te =\tstate[4];\n\n\t/* 4 rounds\tof 20 operations each. Loop\tunrolled. */\n\tR0(a,b,c,d,e, 0); R0(e,a,b,c,d,\t1);\tR0(d,e,a,b,c, 2); R0(c,d,e,a,b,\t3);\n\tR0(b,c,d,e,a, 4); R0(a,b,c,d,e,\t5);\tR0(e,a,b,c,d, 6); R0(d,e,a,b,c,\t7);\n\tR0(c,d,e,a,b, 8); R0(b,c,d,e,a,\t9);\tR0(a,b,c,d,e,10); R0(e,a,b,c,d,11);\n\tR0(d,e,a,b,c,12); R0(c,d,e,a,b,13);\tR0(b,c,d,e,a,14); R0(a,b,c,d,e,15);\n\tR1(e,a,b,c,d,16); R1(d,e,a,b,c,17);\tR1(c,d,e,a,b,18); R1(b,c,d,e,a,19);\n\tR2(a,b,c,d,e,20); R2(e,a,b,c,d,21);\tR2(d,e,a,b,c,22); R2(c,d,e,a,b,23);\n\tR2(b,c,d,e,a,24); R2(a,b,c,d,e,25);\tR2(e,a,b,c,d,26); R2(d,e,a,b,c,27);\n\tR2(c,d,e,a,b,28); R2(b,c,d,e,a,29);\tR2(a,b,c,d,e,30); R2(e,a,b,c,d,31);\n\tR2(d,e,a,b,c,32); R2(c,d,e,a,b,33);\tR2(b,c,d,e,a,34); R2(a,b,c,d,e,35);\n\tR2(e,a,b,c,d,36); R2(d,e,a,b,c,37);\tR2(c,d,e,a,b,38); R2(b,c,d,e,a,39);\n\tR3(a,b,c,d,e,40); R3(e,a,b,c,d,41);\tR3(d,e,a,b,c,42); R3(c,d,e,a,b,43);\n\tR3(b,c,d,e,a,44); R3(a,b,c,d,e,45);\tR3(e,a,b,c,d,46); R3(d,e,a,b,c,47);\n\tR3(c,d,e,a,b,48); R3(b,c,d,e,a,49);\tR3(a,b,c,d,e,50); R3(e,a,b,c,d,51);\n\tR3(d,e,a,b,c,52); R3(c,d,e,a,b,53);\tR3(b,c,d,e,a,54); R3(a,b,c,d,e,55);\n\tR3(e,a,b,c,d,56); R3(d,e,a,b,c,57);\tR3(c,d,e,a,b,58); R3(b,c,d,e,a,59);\n\tR4(a,b,c,d,e,60); R4(e,a,b,c,d,61);\tR4(d,e,a,b,c,62); R4(c,d,e,a,b,63);\n\tR4(b,c,d,e,a,64); R4(a,b,c,d,e,65);\tR4(e,a,b,c,d,66); R4(d,e,a,b,c,67);\n\tR4(c,d,e,a,b,68); R4(b,c,d,e,a,69);\tR4(a,b,c,d,e,70); R4(e,a,b,c,d,71);\n\tR4(d,e,a,b,c,72); R4(c,d,e,a,b,73);\tR4(b,c,d,e,a,74); R4(a,b,c,d,e,75);\n\tR4(e,a,b,c,d,76); R4(d,e,a,b,c,77);\tR4(c,d,e,a,b,78); R4(b,c,d,e,a,79);\n\n\t/* Add the working vars\tback into context.state[] */\n\tstate[0] +=\ta;\n\tstate[1] +=\tb;\n\tstate[2] +=\tc;\n\tstate[3] +=\td;\n\tstate[4] +=\te;\n\n\t/* Wipe\tvariables */\n\ta =\tb =\tc =\td =\te =\t0;\n}\n\n\n/* SHA1Init\t- Initialize new context */\nstatic void sat_SHA1_Init(SHA1_CTX* context)\n{\n\t/* SHA1\tinitialization constants */\n\tcontext->state[0] =\t0x67452301;\n\tcontext->state[1] =\t0xEFCDAB89;\n\tcontext->state[2] =\t0x98BADCFE;\n\tcontext->state[3] =\t0x10325476;\n\tcontext->state[4] =\t0xC3D2E1F0;\n\tcontext->count[0] =\tcontext->count[1] =\t0;\n}\n\n\n/* Run your\tdata through this. */\nstatic void sat_SHA1_Update(SHA1_CTX* context,\tconst uint8_t* data, const size_t len)\n{\n\tsize_t i, j;\n\n#ifdef VERBOSE\n\tSHAPrintContext(context, \"before\");\n#endif\n\n\tj =\t(context->count[0] >> 3) & 63;\n\tif ((context->count[0] += len << 3)\t< (len << 3)) context->count[1]++;\n\tcontext->count[1] += (len >> 29);\n\tif ((j + len) >\t63)\t{\n\t\tmemcpy(&context->buffer[j],\tdata, (i = 64-j));\n\t\tSHA1_Transform(context->state, context->buffer);\n\t\tfor\t( ;\ti +\t63 < len; i\t+= 64) {\n\t\t\tSHA1_Transform(context->state, data\t+ i);\n\t\t}\n\t\tj =\t0;\n\t}\n\telse i = 0;\n\tmemcpy(&context->buffer[j],\t&data[i], len -\ti);\n\n#ifdef VERBOSE\n\tSHAPrintContext(context, \"after\t\");\n#endif\n}\n\n\n/* Add padding and return the message digest. */\nstatic void sat_SHA1_Final(SHA1_CTX* context, uint8_t digest[SHA1_DIGEST_SIZE])\n{\n\tuint32_t i;\n\tuint8_t\t finalcount[8];\n\n\tfor\t(i = 0;\ti <\t8; i++)\t{\n\t\tfinalcount[i] =\t(unsigned char)((context->count[(i >= 4\t? 0\t: 1)]\n\t\t >>\t((3-(i & 3)) * 8) )\t& 255);\t /*\tEndian independent */\n\t}\n\tsat_SHA1_Update(context, (uint8_t *)\"\\200\",\t1);\n\twhile ((context->count[0] &\t504) !=\t448) {\n\t\tsat_SHA1_Update(context, (uint8_t *)\"\\0\", 1);\n\t}\n\tsat_SHA1_Update(context, finalcount, 8);  /* Should\tcause a\tSHA1_Transform() */\n\tfor\t(i = 0;\ti <\tSHA1_DIGEST_SIZE; i++) {\n\t\tdigest[i] =\t(uint8_t)\n\t\t ((context->state[i>>2]\t>> ((3-(i &\t3))\t* 8) ) & 255);\n\t}\n\n\t/* Wipe\tvariables */\n\ti =\t0;\n\tmemset(context->buffer,\t0, 64);\n\tmemset(context->state, 0, 20);\n\tmemset(context->count, 0, 8);\n\tmemset(finalcount, 0, 8);\t/* SWR */\n}\n\n#include <lua.h>\n#include <lauxlib.h>\n\nint\nlsha1(lua_State *L) {\n\tsize_t sz = 0;\n\tconst uint8_t * buffer = (const uint8_t *)luaL_checklstring(L, 1, &sz);\n\tuint8_t digest[SHA1_DIGEST_SIZE];\n\tSHA1_CTX ctx;\n\tsat_SHA1_Init(&ctx);\n\tsat_SHA1_Update(&ctx, buffer, sz);\n\tsat_SHA1_Final(&ctx, digest);\n\tlua_pushlstring(L, (const char *)digest, SHA1_DIGEST_SIZE);\n\n\treturn 1;\n}\n\n#define BLOCKSIZE 64\n\nstatic inline void\nxor_key(uint8_t key[BLOCKSIZE], uint32_t xor_) {\n\tint i;\n\tfor (i=0;i<BLOCKSIZE;i+=sizeof(uint32_t)) {\n\t\tuint32_t * k = (uint32_t *)&key[i];\n\t\t*k ^= xor_;\n\t}\n}\n\nLUAMOD_API int\nlhmac_sha1(lua_State *L) {\n\tsize_t key_sz = 0;\n\tconst uint8_t * key = (const uint8_t *)luaL_checklstring(L, 1, &key_sz);\n\tsize_t text_sz = 0;\n\tconst uint8_t * text = (const uint8_t *)luaL_checklstring(L, 2, &text_sz);\n\tSHA1_CTX ctx1, ctx2;\n\tuint8_t digest1[SHA1_DIGEST_SIZE];\n\tuint8_t digest2[SHA1_DIGEST_SIZE];\n\tuint8_t rkey[BLOCKSIZE];\n\tmemset(rkey, 0, BLOCKSIZE);\n\n\tif (key_sz > BLOCKSIZE) {\n\t\tSHA1_CTX ctx;\n\t\tsat_SHA1_Init(&ctx);\n\t\tsat_SHA1_Update(&ctx, key, key_sz);\n\t\tsat_SHA1_Final(&ctx, rkey);\n\t\tkey_sz = SHA1_DIGEST_SIZE;\n\t} else {\n\t\tmemcpy(rkey, key, key_sz);\n\t}\n\n\txor_key(rkey, 0x5c5c5c5c);\n\tsat_SHA1_Init(&ctx1);\n\tsat_SHA1_Update(&ctx1, rkey, BLOCKSIZE);\n\n\txor_key(rkey, 0x5c5c5c5c ^ 0x36363636);\n\tsat_SHA1_Init(&ctx2);\n\tsat_SHA1_Update(&ctx2, rkey, BLOCKSIZE);\n\tsat_SHA1_Update(&ctx2, text, text_sz);\n\tsat_SHA1_Final(&ctx2, digest2);\n\n\tsat_SHA1_Update(&ctx1, digest2, SHA1_DIGEST_SIZE);\n\tsat_SHA1_Final(&ctx1, digest1);\n\n\tlua_pushlstring(L, (const char *)digest1, SHA1_DIGEST_SIZE);\n\n\treturn 1;\n}\n\n"
  },
  {
    "path": "lualib-src/ltls.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h> \n#include <openssl/err.h>\n#include <openssl/dh.h>\n#include <openssl/ssl.h>\n#include <openssl/conf.h>\n#include <openssl/engine.h>\n#include <lua.h>\n#include <lauxlib.h>\n\n\nstatic bool TLS_IS_INIT = false;\n\nstruct tls_context {\n    SSL* ssl;\n    BIO* in_bio;\n    BIO* out_bio;\n    bool is_server;\n    bool is_close;\n};\n\nstruct ssl_ctx {\n    SSL_CTX* ctx;\n};\n\n// static int\n// _ssl_verify_peer(int ok, X509_STORE_CTX* ctx) {\n//     return 1;\n// }\n\n\nstatic void\n_init_bio(lua_State* L, struct tls_context* tls_p, struct ssl_ctx* ctx_p) {\n    tls_p->ssl = SSL_new(ctx_p->ctx);\n    if(!tls_p->ssl) {\n        luaL_error(L, \"SSL_new failed\");\n    }\n\n    tls_p->in_bio = BIO_new(BIO_s_mem());\n    if(!tls_p->in_bio) {\n        luaL_error(L, \"new in bio failed\");\n    }\n    BIO_set_mem_eof_return(tls_p->in_bio, -1); /* see: https://www.openssl.org/docs/crypto/BIO_s_mem.html */\n\n    tls_p->out_bio = BIO_new(BIO_s_mem());\n    if(!tls_p->out_bio) {\n        luaL_error(L, \"new out bio failed\");\n    }\n    BIO_set_mem_eof_return(tls_p->out_bio, -1); /* see: https://www.openssl.org/docs/crypto/BIO_s_mem.html */\n\n    SSL_set_bio(tls_p->ssl, tls_p->in_bio, tls_p->out_bio);\n}\n\n\nstatic void\n_init_client_context(lua_State* L, struct tls_context* tls_p, struct ssl_ctx* ctx_p) {\n    tls_p->is_server = false;\n    _init_bio(L, tls_p, ctx_p);\n    SSL_set_connect_state(tls_p->ssl);\n}\n\nstatic void\n_init_server_context(lua_State* L, struct tls_context* tls_p, struct ssl_ctx* ctx_p) {\n    tls_p->is_server = true;\n    _init_bio(L, tls_p, ctx_p);\n    SSL_set_accept_state(tls_p->ssl);\n}\n\nstatic struct tls_context *\n_check_context(lua_State* L, int idx) {\n    struct tls_context* tls_p = (struct tls_context*)lua_touserdata(L, idx);\n    if(!tls_p) {\n        luaL_error(L, \"need tls context\");\n    }\n    if(tls_p->is_close) {\n        luaL_error(L, \"context is closed\");\n    }\n    return tls_p;\n}\n\nstatic struct ssl_ctx *\n_check_sslctx(lua_State* L, int idx) {\n    struct ssl_ctx* ctx_p = (struct ssl_ctx*)lua_touserdata(L, idx);\n    if(!ctx_p) {\n        luaL_error(L, \"need sslctx\");\n    }\n    return ctx_p;\n}\n\nstatic int\n_ltls_context_finished(lua_State* L) {\n    struct tls_context* tls_p = _check_context(L, 1);\n    int b = SSL_is_init_finished(tls_p->ssl);\n    lua_pushboolean(L, b);\n    return 1;\n}\n\nstatic int\n_ltls_context_close(lua_State* L) {\n    struct tls_context* tls_p = lua_touserdata(L, 1);\n    if(!tls_p->is_close) {\n        SSL_free(tls_p->ssl);\n        tls_p->ssl = NULL;\n        tls_p->in_bio = NULL; //in_bio and out_bio will be free when SSL_free is called\n        tls_p->out_bio = NULL;\n        tls_p->is_close = true;\n    }\n    return 0;\n}\n\nstatic int\n_bio_read(lua_State* L, struct tls_context* tls_p) {\n    char outbuff[4096];\n    int all_read = 0;\n    int read = 0;\n    int pending = BIO_ctrl_pending(tls_p->out_bio);\n    if(pending >0) {\n        luaL_Buffer b;\n        luaL_buffinit(L, &b);\n        while(pending > 0) {\n            read = BIO_read(tls_p->out_bio, outbuff, sizeof(outbuff));\n            // printf(\"BIO_read read:%d pending:%d\\n\", read, pending);\n            if(read <= 0) {\n                luaL_error(L, \"BIO_read error:%d\", read);\n            }else if(read <= sizeof(outbuff)) {\n                all_read += read;\n                luaL_addlstring(&b, (const char*)outbuff, read);\n            }else {\n                luaL_error(L, \"invalid BIO_read:%d\", read);\n            }\n            pending = BIO_ctrl_pending(tls_p->out_bio);\n        }\n        if(all_read>0) {\n            luaL_pushresult(&b);\n        }\n    }\n    return all_read;\n}\n\n\nstatic void\n_bio_write(lua_State* L, struct tls_context* tls_p, const char* s, size_t len) {\n    char* p = (char*)s;\n    size_t sz = len;\n    while(sz > 0) {\n        int written = BIO_write(tls_p->in_bio, p, sz);\n        // printf(\"BIO_write written:%d sz:%zu\\n\", written, sz);\n        if(written <= 0) {\n            luaL_error(L, \"BIO_write error:%d\", written);\n        }else if (written <= sz) {\n            p += written;\n            sz -= written;\n        }else {\n            luaL_error(L, \"invalid BIO_write:%d\", written);\n        }\n    }\n}\n\n\nstatic int\n_ltls_context_handshake(lua_State* L) {\n    struct tls_context* tls_p = _check_context(L, 1);\n    size_t slen = 0;\n    const char* exchange = lua_tolstring(L, 2, &slen);\n\n    // check handshake is finished\n    if(SSL_is_init_finished(tls_p->ssl)) {\n        luaL_error(L, \"handshake is finished\");\n    }\n\n    // handshake exchange\n    if(slen > 0 && exchange != NULL) {\n        _bio_write(L, tls_p, exchange, slen);\n    }\n\n    // first handshake; initiated by client\n    if(!SSL_is_init_finished(tls_p->ssl)) {\n        int ret = SSL_do_handshake(tls_p->ssl);\n        if(ret == 1) {\n            return 0;\n        } else if (ret < 0) {\n            int err = SSL_get_error(tls_p->ssl, ret);\n            ERR_clear_error();\n            if(err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {\n                int all_read = _bio_read(L, tls_p);\n                if(all_read>0) {\n                    return 1;\n                }\n            } else {\n                luaL_error(L, \"SSL_do_handshake error:%d ret:%d\", err, ret);\n            }\n        } else {\n            int err = SSL_get_error(tls_p->ssl, ret);\n            ERR_clear_error();\n            luaL_error(L, \"SSL_do_handshake error:%d ret:%d\", err, ret);\n        }\n    }\n    return 0;\n}\n\n\nstatic int\n_ltls_context_read(lua_State* L) {\n    struct tls_context* tls_p = _check_context(L, 1);\n    size_t slen = 0;\n    const char* encrypted_data = lua_tolstring(L, 2, &slen);\n\n    // write encrypted data\n    if(slen>0 && encrypted_data) {\n        _bio_write(L, tls_p, encrypted_data, slen);\n    }\n\n    char outbuff[4096];\n    int read = 0;\n    luaL_Buffer b;\n    luaL_buffinit(L, &b);\n\n    do {\n        read = SSL_read(tls_p->ssl, outbuff, sizeof(outbuff));\n        if(read < 0) {\n            int err = SSL_get_error(tls_p->ssl, read);\n            ERR_clear_error();\n            if(err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {\n                break;\n            }\n            luaL_error(L, \"SSL_read error:%d\", err);\n        }else if(read == 0){\n            break;\n        }\n        else if(read <= sizeof(outbuff)) {\n            luaL_addlstring(&b, outbuff, read);\n        }else {\n            luaL_error(L, \"invalid SSL_read:%d\", read);\n        }\n    }while(true);\n    luaL_pushresult(&b);\n    return 1;\n}\n\n\nstatic int\n_ltls_context_write(lua_State* L) {\n    struct tls_context* tls_p = _check_context(L, 1);\n    size_t slen = 0;\n    char* unencrypted_data = (char*)lua_tolstring(L, 2, &slen);\n\n    while(slen > 0) {\n        int written = SSL_write(tls_p->ssl, unencrypted_data,  slen);\n        if(written <= 0) {\n            int err = SSL_get_error(tls_p->ssl, written);\n            ERR_clear_error();\n            luaL_error(L, \"SSL_write error:%d\", err);\n        }else if(written <= slen) {\n            unencrypted_data += written;\n            slen -= written;\n        }else {\n            luaL_error(L, \"invalid SSL_write:%d\", written);\n        }\n    }\n\n    int all_read = _bio_read(L, tls_p);\n    if(all_read <= 0) {\n        lua_pushstring(L, \"\");\n    }\n    return 1;\n}\n\nstatic int\n_lset_ext_host_name(lua_State* L) {\n    struct tls_context* tls_p = _check_context(L, 1);\n    size_t slen = 0;\n    char* host = (char*)lua_tolstring(L, 2, &slen);\n    int ret = SSL_set_tlsext_host_name(tls_p->ssl, host);\n    lua_pushinteger(L, ret);\n    return 1;\n}\n\nstatic int\n_lctx_gc(lua_State* L) {\n    struct ssl_ctx* ctx_p = _check_sslctx(L, 1);\n    if(ctx_p->ctx) {\n        SSL_CTX_free(ctx_p->ctx);\n        ctx_p->ctx = NULL;\n    }\n    return 0;\n}\n\nstatic int\n_lctx_cert(lua_State* L) {\n    struct ssl_ctx* ctx_p = _check_sslctx(L, 1);\n    const char* certfile = lua_tostring(L, 2);\n    const char* key = lua_tostring(L, 3);\n    if(!certfile) {\n        luaL_error(L, \"need certfile\");\n    }\n\n    if(!key) {\n        luaL_error(L, \"need private key\");\n    }\n\n    int ret = SSL_CTX_use_certificate_chain_file(ctx_p->ctx, certfile);\n    if(ret != 1) {\n        luaL_error(L, \"SSL_CTX_use_certificate_chain_file error:%d\", ret);\n    }\n\n    ret = SSL_CTX_use_PrivateKey_file(ctx_p->ctx, key, SSL_FILETYPE_PEM);\n    if(ret != 1) {\n        luaL_error(L, \"SSL_CTX_use_PrivateKey_file error:%d\", ret);\n    }\n    ret = SSL_CTX_check_private_key(ctx_p->ctx);\n    if(ret != 1) {\n        luaL_error(L, \"SSL_CTX_check_private_key error:%d\", ret);\n    }\n    return 0;\n}\n\nstatic int\n_lctx_ciphers(lua_State* L) {\n    struct ssl_ctx* ctx_p = _check_sslctx(L, 1);\n    const char* s = lua_tostring(L, 2);\n    if(!s) {\n        luaL_error(L, \"need cipher list\");\n    }\n    int ret = SSL_CTX_set_tlsext_use_srtp(ctx_p->ctx, s);\n    if(ret != 0) {\n        luaL_error(L, \"SSL_CTX_set_tlsext_use_srtp error:%d\", ret);\n    }\n    return 0;\n}\n\n\nstatic int\nlnew_ctx(lua_State* L) {\n    struct ssl_ctx* ctx_p = (struct ssl_ctx*)lua_newuserdatauv(L, sizeof(*ctx_p), 0);\n    ctx_p->ctx = SSL_CTX_new(SSLv23_method());\n    if(!ctx_p->ctx) {\n        unsigned int err = ERR_get_error();\n        char buf[256];\n        ERR_error_string_n(err, buf, sizeof(buf));\n        luaL_error(L, \"SSL_CTX_new client failed. %s\\n\", buf);\n    }\n\n    if(luaL_newmetatable(L, \"_TLS_SSLCTX_METATABLE_\")) {\n        luaL_Reg l[] = {\n            {\"set_ciphers\", _lctx_ciphers},\n            {\"set_cert\", _lctx_cert},\n            {NULL, NULL},\n        };\n\n        luaL_newlib(L, l);\n        lua_setfield(L, -2, \"__index\");\n        lua_pushcfunction(L, _lctx_gc);\n        lua_setfield(L, -2, \"__gc\");\n    }\n    lua_setmetatable(L, -2);\n    return 1;\n}\n\n\nstatic int\nlnew_tls(lua_State* L) {\n    struct tls_context* tls_p = (struct tls_context*)lua_newuserdatauv(L, sizeof(*tls_p), 1);\n    tls_p->is_close = false;\n    const char* method = luaL_optstring(L, 1, \"nil\");\n    struct ssl_ctx* ctx_p = _check_sslctx(L, 2);\n    lua_pushvalue(L, 2);\n    lua_setiuservalue(L, -2, 1); // set ssl_ctx associated to tls_context\n\n    if(strcmp(method, \"client\") == 0) {\n        _init_client_context(L, tls_p, ctx_p);\n        if (!lua_isnoneornil(L, 3)) {\n            const char* hostname = luaL_checkstring(L, 3);\n            SSL_set_tlsext_host_name(tls_p->ssl, hostname);\n        }\n    }else if(strcmp(method, \"server\") == 0) {\n        _init_server_context(L, tls_p, ctx_p);\n    } else {\n        luaL_error(L, \"invalid method:%s e.g[server, client]\", method);\n    }\n\n    if(luaL_newmetatable(L, \"_TLS_CONTEXT_METATABLE_\")) {\n        luaL_Reg l[] = {\n            {\"close\", _ltls_context_close},\n            {\"finished\", _ltls_context_finished},\n            {\"handshake\", _ltls_context_handshake},\n            {\"read\", _ltls_context_read},\n            {\"write\", _ltls_context_write},\n            {\"set_ext_host_name\", _lset_ext_host_name},\n            {NULL, NULL},\n        };\n        luaL_newlib(L, l);\n        lua_setfield(L, -2, \"__index\");\n        lua_pushcfunction(L, _ltls_context_close);\n        lua_setfield(L, -2, \"__gc\");\n    }\n    lua_setmetatable(L, -2);\n    return 1;\n}\n\nint\nluaopen_ltls_c(lua_State* L) {\n    if(!TLS_IS_INIT) {\n        luaL_error(L, \"ltls need init, Put enablessl = true in you config file.\");\n    }\n    luaL_Reg l[] = {\n        {\"newctx\", lnew_ctx},\n        {\"newtls\", lnew_tls},\n        {NULL, NULL},\n    };\n    luaL_checkversion(L);\n    luaL_newlib(L, l);\n    return 1;\n}\n\n// for ltls init\nstatic int\nltls_init_constructor(lua_State* L) {\n#ifndef OPENSSL_EXTERNAL_INITIALIZATION\n    if(!TLS_IS_INIT) {\n        SSL_library_init();\n        SSL_load_error_strings();\n#if OPENSSL_VERSION_NUMBER < 0x30000000L\n        ERR_load_BIO_strings();\n#endif\n        OpenSSL_add_all_algorithms();\n    }\n#endif\n    TLS_IS_INIT = true;\n    return 0;\n}\n\nstatic int\nltls_init_destructor(lua_State* L) {\n#ifndef OPENSSL_EXTERNAL_INITIALIZATION\n    if(TLS_IS_INIT) {\n        ENGINE_cleanup();\n        CONF_modules_unload(1);\n        ERR_free_strings();\n        EVP_cleanup();\n        sk_SSL_COMP_free(SSL_COMP_get_compression_methods());\n        CRYPTO_cleanup_all_ex_data();\n    }\n#endif\n    TLS_IS_INIT = false;\n    return 0;\n}\n\nint\nluaopen_ltls_init_c(lua_State* L) {\n    luaL_Reg l[] = {\n        {\"constructor\", ltls_init_constructor},\n        {\"destructor\", ltls_init_destructor},\n        {NULL, NULL},\n    };\n    luaL_checkversion(L);\n    luaL_newlib(L, l);\n    return 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-bson.c",
    "content": "#define LUA_LIB\n\n#include <lua.h>\n#include <lauxlib.h>\n\n#include <time.h>\n#include <unistd.h>\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n#include \"atomic.h\"\n\n#define DEFAULT_CAP 64\n#define MAX_NUMBER 1024\n// avoid circular reference while encodeing\n#define MAX_DEPTH 128\n\n#define BSON_REAL 1\n#define BSON_STRING 2\n#define BSON_DOCUMENT 3\n#define BSON_ARRAY 4\n#define BSON_BINARY 5\n#define BSON_UNDEFINED 6\n#define BSON_OBJECTID 7\n#define BSON_BOOLEAN 8\n#define BSON_DATE 9\n#define BSON_NULL 10\n#define BSON_REGEX 11\n#define BSON_DBPOINTER 12\n#define BSON_JSCODE 13\n#define BSON_SYMBOL 14\n#define BSON_CODEWS 15\n#define BSON_INT32 16\n#define BSON_TIMESTAMP 17\n#define BSON_INT64 18\n#define BSON_MINKEY 255\n#define BSON_MAXKEY 127\n\n#define BSON_TYPE_SHIFT 5\n\nstatic char bson_numstrs[MAX_NUMBER][4];\nstatic int bson_numstr_len[MAX_NUMBER];\n\nstruct bson {\n\tint size;\n\tint cap;\n\tuint8_t *ptr;\n\tuint8_t buffer[DEFAULT_CAP];\n};\n\nstruct bson_reader {\n\tconst uint8_t * ptr;\n\tint size;\n};\n\nstatic inline int32_t\nget_length(const uint8_t * data) {\n\tconst uint8_t * b = (const uint8_t *)data;\n\tint32_t len = b[0] | b[1]<<8 | b[2]<<16 | b[3]<<24;\n\treturn len;\n}\n\nstatic inline void\nbson_destroy(struct bson *b) {\n\tif (b->ptr != b->buffer) {\n\t\tfree(b->ptr);\n\t}\n}\n\nstatic inline void\nbson_create(struct bson *b) {\n\tb->size = 0;\n\tb->cap = DEFAULT_CAP;\n\tb->ptr = b->buffer;\n}\n\nstatic inline void\nbson_reserve(struct bson *b, int sz) {\n\tif (b->size + sz <= b->cap)\n\t\treturn;\n\tdo {\n\t\tb->cap *= 2;\n\t} while (b->cap <= b->size + sz);\n\n\tif (b->ptr == b->buffer) {\n\t\tb->ptr = (uint8_t*)malloc(b->cap);\n\t\tmemcpy(b->ptr, b->buffer, b->size);\n\t} else {\n\t\tb->ptr = (uint8_t*)realloc(b->ptr, b->cap);\n\t}\n}\n\nstatic inline void\ncheck_reader(lua_State *L, struct bson_reader *br, int sz) {\n\tif (br->size < sz) {\n\t\tluaL_error(L, \"Invalid bson block (%d:%d)\", br->size, sz);\n\t}\n}\n\nstatic inline int\nread_byte(lua_State *L, struct bson_reader *br) {\n\tcheck_reader(L, br, 1);\n\tconst uint8_t * b = br->ptr;\n\tint r =  b[0];\n\t++br->ptr;\n\t--br->size;\n\n\treturn r;\n}\n\nstatic inline int32_t\nread_int32(lua_State *L, struct bson_reader *br) {\n\tcheck_reader(L, br, 4);\n\tconst uint8_t * b = br->ptr;\n\tuint32_t v = b[0] | b[1]<<8 | b[2]<<16 | b[3]<<24;\n\tbr->ptr+=4;\n\tbr->size-=4;\n\treturn (int32_t)v;\n}\n\nstatic inline int64_t\nread_int64(lua_State *L, struct bson_reader *br) {\n\tcheck_reader(L, br, 8);\n\tconst uint8_t * b = br->ptr;\n\tuint32_t lo = b[0] | b[1]<<8 | b[2]<<16 | b[3]<<24;\n\tuint32_t hi = b[4] | b[5]<<8 | b[6]<<16 | b[7]<<24;\n\tuint64_t v = (uint64_t)lo | (uint64_t)hi<<32;\n\tbr->ptr+=8;\n\tbr->size-=8;\n\treturn (int64_t)v;\n}\n\nstatic inline lua_Number\nread_double(lua_State *L, struct bson_reader *br) {\n\tcheck_reader(L, br, 8);\n\tunion {\n\t\tuint64_t i;\n\t\tdouble d;\n\t} v;\n\tconst uint8_t * b = br->ptr;\n\tuint32_t lo = b[0] | b[1]<<8 | b[2]<<16 | b[3]<<24;\n\tuint32_t hi = b[4] | b[5]<<8 | b[6]<<16 | b[7]<<24;\n\tv.i = (uint64_t)lo | (uint64_t)hi<<32;\n\tbr->ptr+=8;\n\tbr->size-=8;\n\treturn v.d;\n}\n\nstatic inline const void *\nread_bytes(lua_State *L, struct bson_reader *br, int sz) {\n\tconst void * r = br->ptr;\n\tcheck_reader(L, br, sz);\n\tbr->ptr+=sz;\n\tbr->size-=sz;\n\treturn r;\n}\n\nstatic inline const char *\nread_cstring(lua_State *L, struct bson_reader *br, size_t *sz) {\n\tint i;\n\tfor (i=0;;i++) {\n\t\tif (i==br->size) {\n\t\t\tluaL_error(L, \"Invalid bson block : cstring\");\n\t\t}\n\t\tif (br->ptr[i] == '\\0') {\n\t\t\tbreak;\n\t\t}\n\t}\n\t*sz = i;\n\tconst char * r = (const char *)br->ptr;\n\tbr->ptr += i+1;\n\tbr->size -= i+1;\n\treturn r;\n}\n\nstatic inline void\nwrite_byte(struct bson *b, uint8_t v) {\n\tbson_reserve(b,1);\n\tb->ptr[b->size++] = v;\n}\n\nstatic inline void\nwrite_int32(struct bson *b, int32_t v) {\n\tuint32_t uv = (uint32_t)v;\n\tbson_reserve(b,4);\n\tb->ptr[b->size++] = uv & 0xff;\n\tb->ptr[b->size++] = (uv >> 8)&0xff;\n\tb->ptr[b->size++] = (uv >> 16)&0xff;\n\tb->ptr[b->size++] = (uv >> 24)&0xff;\n}\n\nstatic inline void\nwrite_length(struct bson *b, int32_t v, int off) {\n\tuint32_t uv = (uint32_t)v;\n\tb->ptr[off++] = uv & 0xff;\n\tb->ptr[off++] = (uv >> 8)&0xff;\n\tb->ptr[off++] = (uv >> 16)&0xff;\n\tb->ptr[off++] = (uv >> 24)&0xff;\n}\n\n#define MAXUNICODE\t0x10FFFF\n\nstatic int\nutf8_copy(const char *s, char *d, size_t limit) {\n\tstatic const unsigned int limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFF};\n\tunsigned int c = s[0];\n\tunsigned int res = 0;\n\tif (limit < 1)\n\t\treturn 0;\n\td[0] = s[0];\n\tif (c < 0x80) {\n\t\treturn 1;\n\t} else {\n\t\tint count = 0;\n\t\twhile (c & 0x40) {\n\t\t\tint cc = s[++count];\n\t\t\tif (limit <= count || (cc & 0xC0) != 0x80)\n\t\t\t\treturn 0;\n\t\t\td[count] = s[count];\n\t\t\tres = (res << 6) | (cc & 0x3F);\n\t\t\tc <<= 1;\n\t\t}\n\t\tres |= ((c & 0x7F) << (count * 5));\n\t\tif (count > 3 || res > MAXUNICODE || res <= limits[count])\n\t\t\treturn 0;\n\t\treturn count+1;\n\t}\n}\n\nstatic void\nwrite_string(struct bson *b, lua_State *L, const char *key, size_t sz) {\n\tbson_reserve(b,sz+1);\n\tchar *dst = (char *)(b->ptr + b->size);\n\tconst char *src = key;\n\tsize_t n = sz;\n\twhile(n > 0) {\n\t\tint c = utf8_copy(src, dst, n);\n\t\tif (c == 0) {\n\t\t\tluaL_error(L, \"Invalid utf8 string\");\n\t\t}\n\t\tsrc += c;\n\t\tdst += c;\n\t\tn -= c;\n\t}\n\tb->ptr[b->size+sz] = '\\0';\n\tb->size+=sz+1;\n}\n\nstatic inline int\nreserve_length(struct bson *b) {\n\tint sz = b->size;\n\tbson_reserve(b,4);\n\tb->size +=4;\n\treturn sz;\n}\n\nstatic inline void\nwrite_int64(struct bson *b, int64_t v) {\n\tuint64_t uv = (uint64_t)v;\n\tint i;\n\tbson_reserve(b,8);\n\tfor (i=0;i<64;i+=8) {\n\t\tb->ptr[b->size++] = (uv>>i) & 0xff;\n\t}\n}\n\nstatic inline void\nwrite_double(struct bson *b, lua_Number d) {\n\tunion {\n\t\tdouble d;\n\t\tuint64_t i;\n\t} v;\n\tv.d = d;\n\tint i;\n\tbson_reserve(b,8);\n\tfor (i=0;i<64;i+=8) {\n\t\tb->ptr[b->size++] = (v.i>>i) & 0xff;\n\t}\n}\n\nstatic inline void\nappend_key(struct bson *bs, lua_State *L, int type, const char *key, size_t sz) {\n\twrite_byte(bs, type);\n\twrite_string(bs, L, key, sz);\n}\n\nstatic inline int\nis_32bit(int64_t v) {\n\treturn v >= INT32_MIN && v <= INT32_MAX;\n}\n\nstatic void\nappend_number(struct bson *bs, lua_State *L, const char *key, size_t sz) {\n\tif (lua_isinteger(L, -1)) {\n\t\tint64_t i = lua_tointeger(L, -1);\n\t\tif (is_32bit(i)) {\n\t\t\tappend_key(bs, L, BSON_INT32, key, sz);\n\t\t\twrite_int32(bs, i);\n\t\t} else {\n\t\t\tappend_key(bs, L, BSON_INT64, key, sz);\n\t\t\twrite_int64(bs, i);\n\t\t}\n\t} else {\n\t\tlua_Number d = lua_tonumber(L,-1);\n\t\tappend_key(bs, L, BSON_REAL, key, sz);\n\t\twrite_double(bs, d);\n\t}\n}\n\nstatic void append_table(struct bson *bs, lua_State *L, const char *key, size_t sz, int depth);\n\nstatic void\nwrite_binary(struct bson *b, const void * buffer, size_t sz) {\n\tint length = reserve_length(b);\n\tbson_reserve(b,sz);\n\tmemcpy(b->ptr + b->size, buffer, sz);\t// include sub type\n\tb->size+=sz;\n\twrite_length(b, sz-1, length);\t// not include sub type\n}\n\nstatic void\nappend_one(struct bson *bs, lua_State *L, const char *key, size_t sz, int depth) {\n\tint vt = lua_type(L,-1);\n\tswitch(vt) {\n\tcase LUA_TNUMBER:\n\t\tappend_number(bs, L, key, sz);\n\t\tbreak;\n\tcase LUA_TLIGHTUSERDATA:\n\tcase LUA_TUSERDATA: {\n\t\tappend_key(bs, L, BSON_DOCUMENT, key, sz);\n\t\tint32_t * doc = (int32_t*)lua_touserdata(L,-1);\n\t\tint32_t sz = *doc;\n\t\tbson_reserve(bs,sz);\n\t\tmemcpy(bs->ptr + bs->size, doc, sz);\n\t\tbs->size += sz;\n\t\tbreak;\n\t}\n\tcase LUA_TSTRING: {\n\t\tsize_t len;\n\t\tconst char * str = lua_tolstring(L,-1,&len);\n\t\tif (len > 1 && str[0]==0) {\n\t\t\tint subt = (uint8_t)str[1];\n\t\t\tappend_key(bs, L, subt, key, sz);\n\t\t\tswitch(subt) {\n\t\t\tcase BSON_BINARY:\n\t\t\t\twrite_binary(bs, str+2, len-2);\n\t\t\t\tbreak;\n\t\t\tcase BSON_OBJECTID:\n\t\t\t\tif (len != 2+12) {\n\t\t\t\t\tluaL_error(L, \"Invalid object id %s\", str+2);\n\t\t\t\t}\n\t\t\t\t// go though\n\t\t\tcase BSON_JSCODE:\n\t\t\tcase BSON_DBPOINTER:\n\t\t\tcase BSON_SYMBOL:\n\t\t\tcase BSON_CODEWS:\n\t\t\t\tbson_reserve(bs,len-2);\n\t\t\t\tmemcpy(bs->ptr + bs->size, str+2, len-2);\n\t\t\t\tbs->size += len-2;\n\t\t\t\tbreak;\n\t\t\tcase BSON_DATE: {\n\t\t\t\tif (len != 2+4) {\n\t\t\t\t\tluaL_error(L, \"Invalid date\");\n\t\t\t\t}\n\t\t\t\tconst uint32_t * ts = (const uint32_t *)(str + 2);\n\t\t\t\tint64_t v = (int64_t)*ts * 1000;\n\t\t\t\twrite_int64(bs, v);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase BSON_TIMESTAMP: {\n\t\t\t\tif (len != 2+8) {\n\t\t\t\t\tluaL_error(L, \"Invalid timestamp\");\n\t\t\t\t}\n\t\t\t\tconst uint32_t * inc = (const uint32_t *)(str + 2);\n\t\t\t\tconst uint32_t * ts = (const uint32_t *)(str + 6);\n\t\t\t\twrite_int32(bs, *inc);\n\t\t\t\twrite_int32(bs, *ts);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase BSON_REGEX: {\n\t\t\t\tstr+=2;\n\t\t\t\tlen-=3;\n\t\t\t\tsize_t i;\n\t\t\t\tfor (i=0;i<len;i++) {\n\t\t\t\t\tif (str[len-i-1]==0) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\twrite_string(bs, L, str, len-i-1);\n\t\t\t\twrite_string(bs, L, str + len-i, i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase BSON_MINKEY:\n\t\t\tcase BSON_MAXKEY:\n\t\t\tcase BSON_NULL:\n\t\t\t\tbreak;\n\t\t\tcase BSON_INT64: {\n\t\t\t\tif (len != 2 + 8) {\n\t\t\t\t\tluaL_error(L, \"Invalid int64\");\n\t\t\t\t}\n\t\t\t\tconst int64_t * v = (const int64_t *)(str + 2);\n\t\t\t\twrite_int64(bs, *v);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tluaL_error(L,\"Invalid subtype %d\", subt);\n\t\t\t}\n\t\t} else {\n\t\t\tsize_t len;\n\t\t\tconst char * str = lua_tolstring(L,-1,&len);\n\t\t\tappend_key(bs, L, BSON_STRING, key, sz);\n\t\t\tint off = reserve_length(bs);\n\t\t\twrite_string(bs, L, str, len);\n\t\t\twrite_length(bs, len+1, off);\t\t\n\t\t}\n\t\tbreak;\n\t}\n\tcase LUA_TTABLE:\n\t\tappend_table(bs, L, key, sz, depth+1);\n\t\tbreak;\n\tcase LUA_TBOOLEAN:\n\t\tappend_key(bs, L, BSON_BOOLEAN, key, sz);\n\t\twrite_byte(bs, lua_toboolean(L,-1));\n\t\tbreak;\n\tcase LUA_TNIL:\n\t\tluaL_error(L, \"Bson array has a hole (nil), Use bson.null instead\");\n\tdefault:\n\t\tluaL_error(L, \"Invalid value type : %s\", lua_typename(L,vt));\n\t}\n}\n\nstatic inline int \nbson_numstr( char *str, unsigned int i ) {\n\tif ( i < MAX_NUMBER) {\n\t\tmemcpy( str, bson_numstrs[i], 4 );\n\t\treturn bson_numstr_len[i];\n\t} else {\n\t\treturn sprintf( str,\"%u\", i );\n\t}\n}\n\nstatic void\npack_array(lua_State *L, struct bson *b, int depth, size_t len) {\n\tint length = reserve_length(b);\n\tsize_t i;\n\tfor (i=1;i<=len;i++) {\n\t\tchar numberkey[32];\n\t\tsize_t sz = bson_numstr(numberkey, i - 1);\n\t\tconst char * key = numberkey;\n\t\tlua_geti(L, -1, i);\n\t\tappend_one(b, L, key, sz, depth);\n\t\tlua_pop(L, 1);\n\t}\n\twrite_byte(b,0);\n\twrite_length(b, b->size - length, length);\n}\n\nstatic void\npack_dict_data(lua_State *L, struct bson *b, int depth, int kt) {\n\tconst char * key = NULL;\n\tsize_t sz;\n\tswitch(kt) {\n\tcase LUA_TNUMBER:\n\t\tluaL_error(L, \"Bson dictionary's key can't be number\");\n\t\tbreak;\n\tcase LUA_TSTRING:\n\t\tkey = lua_tolstring(L,-2,&sz);\n\t\tappend_one(b, L, key, sz, depth);\n\t\tlua_pop(L,1);\n\t\tbreak;\n\tdefault:\n\t\tluaL_error(L, \"Invalid key type : %s\", lua_typename(L, kt));\n\t\treturn;\n\t}\n}\n\nstatic void\npack_simple_dict(lua_State *L, struct bson *b, int depth) {\n\tint length = reserve_length(b);\n\tlua_pushnil(L);\n\twhile(lua_next(L,-2) != 0) {\n\t\tint kt = lua_type(L, -2);\n\t\tpack_dict_data(L, b, depth, kt);\n\t}\n\twrite_byte(b,0);\n\twrite_length(b, b->size - length, length);\n}\n\nstatic void\npack_meta_dict(lua_State *L, struct bson *b, int depth) {\n\tint length = reserve_length(b);\n\n\tlua_pushvalue(L, -2); // push meta_obj\n\tlua_call(L, 1, 3); // call __pairs_func => next_func, t_data, first_k\n\tfor(;;) {\n\t\tlua_pushvalue(L, -2); // copy data\n\t\tlua_pushvalue(L, -2); // copy k\n\t\tlua_copy(L, -5, -3); // copy next_func replace old_k\n\t\tlua_call(L, 2, 2); // call next_func\n\n\t\tint kt = lua_type(L, -2);\n\t\tif (kt == LUA_TNIL) {\n\t\t\tlua_pop(L, 4); // pop all k, v, next_func, obj\n\t\t\tbreak;\n\t\t}\n\t\tpack_dict_data(L, b, depth, kt);\n\t}\n\twrite_byte(b,0);\n\twrite_length(b, b->size - length, length);\n}\n\nstatic bool\nis_rawarray(lua_State *L) {\n\tlua_pushnil(L);\n\tif (lua_next(L, -2) == 0) {\n\t\t// empty table\n\t\treturn false;\n\t}\n\tlua_Integer firstkey = lua_isinteger(L, -2) ? lua_tointeger(L, -2) : 0;\n\tlua_pop(L, 2);\n\tif (firstkey <= 1) {\n\t\treturn firstkey > 0;\n\t}\n\treturn firstkey <= lua_rawlen(L, -1);\n}\n\nstatic void\nappend_table(struct bson *bs, lua_State *L, const char *key, size_t sz, int depth) {\n\tif (depth > MAX_DEPTH) {\n\t\tluaL_error(L, \"Too depth while encoding bson\");\n\t}\n\tluaL_checkstack(L, 16, NULL);\t// reserve enough stack space to pack table\n\tif (luaL_getmetafield(L, -1, \"__len\") != LUA_TNIL) {\n\t\tlua_pushvalue(L, -2);\n\t\tlua_call(L, 1, 1);\n\t\tif (!lua_isinteger(L, -1)) {\n\t\t\tluaL_error(L, \"__len should return integer\");\n\t\t}\n\t\tsize_t len = lua_tointeger(L, -1);\n\t\tlua_pop(L, 1);\n\t\tappend_key(bs, L, BSON_ARRAY, key, sz);\n\t\tpack_array(L, bs, depth, len);\n\t} else if (luaL_getmetafield(L, -1, \"__pairs\") != LUA_TNIL) {\n\t\tappend_key(bs, L, BSON_DOCUMENT, key, sz);\n\t\tpack_meta_dict(L, bs, depth);\n\t} else if (is_rawarray(L)) {\n\t\tappend_key(bs, L, BSON_ARRAY, key, sz);\n\t\tpack_array(L, bs, depth, lua_rawlen(L, -1));\n\t} else {\n\t\tappend_key(bs, L, BSON_DOCUMENT, key, sz);\n\t\tpack_simple_dict(L, bs, depth);\n\t}\n}\n\nstatic void\npack_ordered_dict(lua_State *L, struct bson *b, int n, int depth) {\n\tint length = reserve_length(b);\n\tint i;\n\tsize_t sz;\n\t// the first key is at index n\n\tconst char * key = lua_tolstring(L, n, &sz);\n\tfor (i=0;i<n;i+=2) {\n\t\tif (key == NULL) {\n\t\t\tluaL_error(L, \"Argument %d need a string\", i+1);\n\t\t}\n\t\tlua_pushvalue(L, i+1);\n\t\tappend_one(b, L, key, sz, depth);\n\t\tlua_pop(L,1);\n\t\tkey = lua_tolstring(L, i+2, &sz);\t// next key\n\t}\n\twrite_byte(b,0);\n\twrite_length(b, b->size - length, length);\n}\n \nstatic int\nltostring(lua_State *L) {\n\tsize_t sz = lua_rawlen(L, 1);\n\tvoid * ud = lua_touserdata(L,1);\n\tlua_pushlstring(L, (const char*)ud, sz);\n\treturn 1;\n}\n\nstatic int\nllen(lua_State *L) {\n\tsize_t sz = lua_rawlen(L, 1);\n\tlua_pushinteger(L, sz);\n\treturn 1;\n}\n\nstatic void\nmake_object(lua_State *L, int type, const void * ptr, size_t len) {\n\tluaL_Buffer b;\n\tluaL_buffinit(L, &b);\n\tluaL_addchar(&b, 0);\n\tluaL_addchar(&b, type);\n\tluaL_addlstring(&b, (const char*)ptr, len);\n\tluaL_pushresult(&b);\n}\n\nstatic void\nunpack_dict(lua_State *L, struct bson_reader *br, bool array) {\n\tluaL_checkstack(L, 16, NULL);\t// reserve enough stack space to unpack table\n\tint sz = read_int32(L, br);\n\tconst void * bytes = read_bytes(L, br, sz-5);\n\tstruct bson_reader t = { (const uint8_t*)bytes, sz-5 };\n\tint end = read_byte(L, br);\n\tif (end != '\\0') {\n\t\tluaL_error(L, \"Invalid document end\");\n\t}\n\n\tlua_newtable(L);\n\n\tfor (;;) {\n\t\tif (t.size == 0)\n\t\t\tbreak;\n\t\tint bt = read_byte(L, &t);\n\t\tsize_t klen = 0;\n\t\tconst char * key = read_cstring(L, &t, &klen);\n\t\tif (array) {\n\t\t\tint id = strtol(key, NULL, 10) + 1;\n\t\t\tlua_pushinteger(L,id);\n\t\t} else {\n\t\t\tlua_pushlstring(L, key, klen);\n\t\t}\n\t\tswitch (bt) {\n\t\tcase BSON_REAL:\n\t\t\tlua_pushnumber(L, read_double(L, &t));\n\t\t\tbreak;\n\t\tcase BSON_BOOLEAN:\n\t\t\tlua_pushboolean(L, read_byte(L, &t));\n\t\t\tbreak;\n\t\tcase BSON_STRING: {\n\t\t\tint sz = read_int32(L, &t);\n\t\t\tif (sz <= 0) {\n\t\t\t\tluaL_error(L, \"Invalid bson string , length = %d\", sz);\n\t\t\t}\n\t\t\tlua_pushlstring(L, (const char*)read_bytes(L, &t, sz), sz-1);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_DOCUMENT:\n\t\t\tunpack_dict(L, &t, false);\n\t\t\tbreak;\n\t\tcase BSON_ARRAY:\n\t\t\tunpack_dict(L, &t, true);\n\t\t\tbreak;\n\t\tcase BSON_BINARY: {\n\t\t\tint sz = read_int32(L, &t);\n\t\t\tint subtype = read_byte(L, &t);\n\n\t\t\tluaL_Buffer b;\n\t\t\tluaL_buffinit(L, &b);\n\t\t\tluaL_addchar(&b, 0);\n\t\t\tluaL_addchar(&b, BSON_BINARY);\n\t\t\tluaL_addchar(&b, subtype);\n\t\t\tluaL_addlstring(&b, (const char*)read_bytes(L, &t, sz), sz);\n\t\t\tluaL_pushresult(&b);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_OBJECTID:\n\t\t\tmake_object(L, BSON_OBJECTID, read_bytes(L, &t, 12), 12);\n\t\t\tbreak;\n\t\tcase BSON_DATE: {\n\t\t\tint64_t date = read_int64(L, &t);\n\t\t\tuint32_t v = date / 1000;\n\t\t\tmake_object(L, BSON_DATE, &v, 4);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_MINKEY:\n\t\tcase BSON_MAXKEY:\n\t\tcase BSON_NULL: {\n\t\t\tchar key[] = { 0, (char)bt };\n\t\t\tlua_pushlstring(L, key, sizeof(key));\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_REGEX: {\n\t\t\tsize_t rlen1=0;\n\t\t\tsize_t rlen2=0;\n\t\t\tconst char * r1 = read_cstring(L, &t, &rlen1);\n\t\t\tconst char * r2 = read_cstring(L, &t, &rlen2);\n\t\t\tluaL_Buffer b;\n\t\t\tluaL_buffinit(L, &b);\n\t\t\tluaL_addchar(&b, 0);\n\t\t\tluaL_addchar(&b, BSON_REGEX);\n\t\t\tluaL_addlstring(&b, r1, rlen1);\n\t\t\tluaL_addchar(&b,0);\n\t\t\tluaL_addlstring(&b, r2, rlen2);\n\t\t\tluaL_addchar(&b,0);\n\t\t\tluaL_pushresult(&b);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_INT32:\n\t\t\tlua_pushinteger(L, read_int32(L, &t));\n\t\t\tbreak;\n\t\tcase BSON_TIMESTAMP: {\n\t\t\tint32_t inc = read_int32(L, &t);\n\t\t\tint32_t ts = read_int32(L, &t);\n\n\t\t\tluaL_Buffer b;\n\t\t\tluaL_buffinit(L, &b);\n\t\t\tluaL_addchar(&b, 0);\n\t\t\tluaL_addchar(&b, BSON_TIMESTAMP);\n\t\t\tluaL_addlstring(&b, (const char *)&inc, 4);\n\t\t\tluaL_addlstring(&b, (const char *)&ts, 4);\n\t\t\tluaL_pushresult(&b);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_INT64:\n\t\t\tlua_pushinteger(L, read_int64(L, &t));\n\t\t\tbreak;\n\t\tcase BSON_DBPOINTER: {\n\t\t\tconst void * ptr = t.ptr;\n\t\t\tint sz = read_int32(L, &t);\n\t\t\tread_bytes(L, &t, sz+12);\n\t\t\tmake_object(L, BSON_DBPOINTER, ptr, sz + 16);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_JSCODE:\n\t\tcase BSON_SYMBOL: {\n\t\t\tconst void * ptr = t.ptr;\n\t\t\tint sz = read_int32(L, &t);\n\t\t\tread_bytes(L, &t, sz);\n\t\t\tmake_object(L, bt, ptr, sz + 4);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_CODEWS: {\n\t\t\tconst void * ptr = t.ptr;\n\t\t\tint sz = read_int32(L, &t);\n\t\t\tread_bytes(L, &t, sz-4);\n\t\t\tmake_object(L, bt, ptr, sz);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\t// unsupported\n\t\t\tluaL_error(L, \"Invalid bson type : %d\", bt);\n\t\t\tlua_pop(L,1);\n\t\t\tcontinue;\n\t\t}\n\t\tlua_rawset(L,-3);\n\t}\n}\n\nstatic int\nlmakeindex(lua_State *L) {\n\tint32_t *bson = (int32_t*)luaL_checkudata(L,1,\"bson\");\n\tconst uint8_t * start = (const uint8_t *)bson;\n\tstruct bson_reader br = { start+4, get_length(start) - 5 };\n\tlua_newtable(L);\n\n\tfor (;;) {\n\t\tif (br.size == 0)\n\t\t\tbreak;\n\t\tint bt = read_byte(L, &br);\n\t\tsize_t klen = 0;\n\t\tconst char * key = read_cstring(L, &br, &klen);\n\t\tint field_size = 0;\n\t\tswitch (bt) {\n\t\tcase BSON_INT64:\n\t\tcase BSON_TIMESTAMP: \n\t\tcase BSON_DATE:\n\t\tcase BSON_REAL:\n\t\t\tfield_size = 8;\n\t\t\tbreak;\n\t\tcase BSON_BOOLEAN:\n\t\t\tfield_size = 1;\n\t\t\tbreak;\n\t\tcase BSON_JSCODE:\n\t\tcase BSON_SYMBOL: \n\t\tcase BSON_STRING: {\n\t\t\tint sz = read_int32(L, &br);\n\t\t\tread_bytes(L, &br, sz);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_CODEWS:\n\t\tcase BSON_ARRAY:\n\t\tcase BSON_DOCUMENT: {\n\t\t\tint sz = read_int32(L, &br);\n\t\t\tread_bytes(L, &br, sz-4);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_BINARY: {\n\t\t\tint sz = read_int32(L, &br);\n\t\t\tread_bytes(L, &br, sz+1);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_OBJECTID:\n\t\t\tfield_size = 12;\n\t\t\tbreak;\n\t\tcase BSON_MINKEY:\n\t\tcase BSON_MAXKEY:\n\t\tcase BSON_NULL:\n\t\t\tbreak;\n\t\tcase BSON_REGEX: {\n\t\t\tsize_t rlen1=0;\n\t\t\tsize_t rlen2=0;\n\t\t\tread_cstring(L, &br, &rlen1);\n\t\t\tread_cstring(L, &br, &rlen2);\n\t\t\tbreak;\n\t\t}\n\t\tcase BSON_INT32:\n\t\t\tfield_size = 4;\n\t\t\tbreak;\n\t\tcase BSON_DBPOINTER: {\n\t\t\tint sz = read_int32(L, &br);\n\t\t\tread_bytes(L, &br, sz+12);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\t// unsupported\n\t\t\tluaL_error(L, \"Invalid bson type : %d\", bt);\n\t\t\tlua_pop(L,1);\n\t\t\tcontinue;\n\t\t}\n\t\tif (field_size > 0) {\n\t\t\tint id = bt | (int)(br.ptr - start) << BSON_TYPE_SHIFT;\n\t\t\tread_bytes(L, &br, field_size);\n\t\t\tlua_pushlstring(L, key, klen);\n\t\t\tlua_pushinteger(L,id);\n\t\t\tlua_rawset(L,-3);\n\t\t}\n\t}\n\tlua_setiuservalue(L,1,1);\n\tlua_settop(L,1);\n\n\treturn 1;\n}\n\nstatic void\nreplace_object(lua_State *L, int type, struct bson * bs) {\n\tsize_t len = 0;\n\tconst char * data = luaL_checklstring(L,3, &len);\n\tif (len < 6 || data[0] != 0 || data[1] != type) {\n\t\tluaL_error(L, \"Type mismatch, need bson type %d\", type);\n\t}\n\tswitch (type) {\n\tcase BSON_OBJECTID:\n\t\tif (len != 2+12) {\n\t\t\tluaL_error(L, \"Invalid object id\");\n\t\t}\n\t\tmemcpy(bs->ptr, data+2, 12);\n\t\tbreak;\n\tcase BSON_DATE: {\n\t\tif (len != 2+4) {\n\t\t\tluaL_error(L, \"Invalid date\");\n\t\t}\n\t\tconst uint32_t * ts = (const uint32_t *)(data + 2);\n\t\tint64_t v = (int64_t)*ts * 1000;\n\t\twrite_int64(bs, v);\n\t\tbreak;\n\t}\n\tcase BSON_TIMESTAMP: {\n\t\tif (len != 2+8) {\n\t\t\tluaL_error(L, \"Invalid timestamp\");\n\t\t}\n\t\tconst uint32_t * inc = (const uint32_t *)(data + 2);\n\t\tconst uint32_t * ts = (const uint32_t *)(data + 6);\n\t\twrite_int32(bs, *inc);\n\t\twrite_int32(bs, *ts);\n\t\tbreak;\n\t}\n\t}\n}\n\nstatic int\nlreplace(lua_State *L) {\n\tlua_getiuservalue(L,1,1);\n\tif (!lua_istable(L,-1)) {\n\t\treturn luaL_error(L, \"call makeindex first\");\n\t}\n\tlua_pushvalue(L,2);\n\tif (lua_rawget(L, -2) != LUA_TNUMBER) {\n\t\treturn luaL_error(L, \"Can't replace key : %s\", lua_tostring(L,2));\n\t}\n\tint id = lua_tointeger(L, -1);\n\tint type = id & ((1<<(BSON_TYPE_SHIFT)) - 1);\n\tint offset = id >> BSON_TYPE_SHIFT;\n\tuint8_t * start = (uint8_t*)lua_touserdata(L,1);\n\tstruct bson b = { 0,16, start + offset };\n\tswitch (type) {\n\tcase BSON_REAL:\n\t\twrite_double(&b, luaL_checknumber(L, 3));\n\t\tbreak;\n\tcase BSON_BOOLEAN:\n\t\twrite_byte(&b, lua_toboolean(L,3));\n\t\tbreak;\n\tcase BSON_OBJECTID:\n\tcase BSON_DATE:\n\tcase BSON_TIMESTAMP:\n\t\treplace_object(L, type, &b);\n\t\tbreak;\n\tcase BSON_INT32: {\n\t\tif (!lua_isinteger(L, 3)) {\n\t\t\tluaL_error(L, \"%f must be a 32bit integer \", lua_tonumber(L, 3));\n\t\t}\n\t\tint32_t i = lua_tointeger(L,3);\n\t\twrite_int32(&b, i);\n\t\tbreak;\n\t}\n\tcase BSON_INT64: {\n\t\tif (!lua_isinteger(L, 3)) {\n\t\t\tluaL_error(L, \"%f must be a 64bit integer \", lua_tonumber(L, 3));\n\t\t}\n\t\tint64_t i = lua_tointeger(L,3);\n\t\twrite_int64(&b, i);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tluaL_error(L, \"Can't replace type %d\", type);\n\t\tbreak;\n\t}\n\treturn 0;\n}\n\nstatic int\nldecode(lua_State *L) {\n\tconst int32_t * data = (const int32_t*)lua_touserdata(L,1);\n\tif (data == NULL) {\n\t\treturn 0;\n\t}\n\tconst uint8_t * b = (const uint8_t *)data;\n\tint32_t len = get_length(b);\n\tstruct bson_reader br = { b , len };\n\n\tunpack_dict(L, &br, false);\n\n\treturn 1;\n}\n\nstatic void\nbson_meta(lua_State *L) {\n\tif (luaL_newmetatable(L, \"bson\")) {\n\t\tluaL_Reg l[] = {\n\t\t\t{ \"decode\", ldecode },\n\t\t\t{ \"makeindex\", lmakeindex },\n\t\t\t{ NULL, NULL },\n\t\t};\n\t\tluaL_newlib(L,l);\n\t\tlua_setfield(L, -2, \"__index\");\n\t\tlua_pushcfunction(L, ltostring);\n\t\tlua_setfield(L, -2, \"__tostring\");\n\t\tlua_pushcfunction(L, llen);\n\t\tlua_setfield(L, -2, \"__len\");\n\t\tlua_pushcfunction(L, lreplace);\n\t\tlua_setfield(L, -2, \"__newindex\");\n\t}\n\tlua_setmetatable(L, -2);\n}\n\nstatic int\nencode_bson(lua_State *L) {\n\tstruct bson *b = (struct bson*)lua_touserdata(L, 2);\n\tlua_settop(L, 1);\n\tif (luaL_getmetafield(L, -1, \"__pairs\") != LUA_TNIL) {\n\t\tpack_meta_dict(L, b, 0);\n\t} else {\n\t\tpack_simple_dict(L, b, 0);\n\t}\n\tvoid * ud = lua_newuserdatauv(L, b->size, 1);\n\tmemcpy(ud, b->ptr, b->size);\n\treturn 1;\n}\n\nstatic int\nlencode(lua_State *L) {\n\tstruct bson b;\n\tlua_settop(L,1);\n\tluaL_checktype(L, 1, LUA_TTABLE);\n\tbson_create(&b);\n\tlua_pushcfunction(L, encode_bson);\n\tlua_pushvalue(L, 1);\n\tlua_pushlightuserdata(L, &b);\n\tif (lua_pcall(L, 2, 1, 0) != LUA_OK) {\n\t\tbson_destroy(&b);\n\t\treturn lua_error(L);\n\t}\n\tbson_destroy(&b);\n\tbson_meta(L);\n\treturn 1;\n}\n\nstatic int\nlto_lightuserdata(lua_State *L) {\n\tvoid *p = lua_touserdata(L, 1);\n\tlua_pushlightuserdata(L, p);\n\treturn 1;\n}\n\nstatic int\nencode_bson_byorder(lua_State *L) {\n\tint n = lua_gettop(L);\n\tstruct bson *b = (struct bson*)lua_touserdata(L, n);\n\tlua_settop(L, --n);\n\tpack_ordered_dict(L, b, n, 0);\n\tlua_settop(L,0);\n\tvoid * ud = lua_newuserdatauv(L, b->size, 1);\n\tmemcpy(ud, b->ptr, b->size);\n\treturn 1;\n}\n\nstatic int\nlencode_order(lua_State *L) {\n\tstruct bson b;\n\tint n = lua_gettop(L);\n\tif (n%2 != 0) {\n\t\treturn luaL_error(L, \"Invalid ordered dict\");\n\t}\n\tbson_create(&b);\n\tlua_pushvalue(L, 1);\t// copy the first arg to n\n\tlua_pushcfunction(L, encode_bson_byorder);\n\tlua_replace(L, 1);\n\tlua_pushlightuserdata(L, &b);\n\tif (lua_pcall(L, n+1, 1, 0) != LUA_OK) {\n\t\tbson_destroy(&b);\n\t\treturn lua_error(L);\n\t}\n\tbson_destroy(&b);\n\tbson_meta(L);\n\treturn 1;\n}\n\nstatic int\nldate(lua_State *L) {\n\tint d = luaL_checkinteger(L,1);\n\tluaL_Buffer b;\n\tluaL_buffinit(L, &b);\n\tluaL_addchar(&b, 0);\n\tluaL_addchar(&b, BSON_DATE);\n\tluaL_addlstring(&b, (const char *)&d, sizeof(d));\n\tluaL_pushresult(&b);\n\n\treturn 1;\n}\n\nstatic int\nlint64(lua_State *L) {\n\tint64_t d = luaL_checkinteger(L, 1);\n\tluaL_Buffer b;\n\tluaL_buffinit(L, &b);\n\tluaL_addchar(&b, 0);\n\tluaL_addchar(&b, BSON_INT64);\n\tluaL_addlstring(&b, (const char *)&d, sizeof(d));\n\tluaL_pushresult(&b);\n\n\treturn 1;\n}\n\nstatic int\nltimestamp(lua_State *L) {\n\tint d = luaL_checkinteger(L,1);\n\tluaL_Buffer b;\n\tluaL_buffinit(L, &b);\n\tluaL_addchar(&b, 0);\n\tluaL_addchar(&b, BSON_TIMESTAMP);\n\tif (lua_isnoneornil(L,2)) {\n\t\tstatic uint32_t inc = 0;\n\t\tluaL_addlstring(&b, (const char *)&inc, sizeof(inc));\n\t\t++inc;\n\t} else {\n\t\tuint32_t i = (uint32_t)lua_tointeger(L,2);\n\t\tluaL_addlstring(&b, (const char *)&i, sizeof(i));\n\t}\n\tluaL_addlstring(&b, (const char *)&d, sizeof(d));\n\tluaL_pushresult(&b);\n\n\treturn 1;\n}\n\nstatic int\nlregex(lua_State *L) {\n\tluaL_checkstring(L,1);\n\tif (lua_gettop(L) < 2) {\n\t\tlua_pushliteral(L,\"\");\n\t}\n\tluaL_Buffer b;\n\tluaL_buffinit(L, &b);\n\tluaL_addchar(&b, 0);\n\tluaL_addchar(&b, BSON_REGEX);\n\tlua_pushvalue(L,1);\n\tluaL_addvalue(&b);\n\tluaL_addchar(&b,0);\n\tlua_pushvalue(L,2);\n\tluaL_addvalue(&b);\n\tluaL_addchar(&b,0);\n\tluaL_pushresult(&b);\n\n\treturn 1;\n}\n\nstatic int\nlbinary(lua_State *L) {\n\tlua_settop(L,1);\n\tluaL_Buffer b;\n\tluaL_buffinit(L, &b);\n\tluaL_addchar(&b, 0);\n\tluaL_addchar(&b, BSON_BINARY);\n\tluaL_addchar(&b, 0);\t// sub type\n\tlua_pushvalue(L,1);\n\tluaL_addvalue(&b);\n\tluaL_pushresult(&b);\n\n\treturn 1;\n}\n\nstatic int\nlsubtype(lua_State *L, int subtype, const uint8_t * buf, size_t sz) {\n\tswitch(subtype) {\n\tcase BSON_BINARY:\n\t\tlua_pushvalue(L, lua_upvalueindex(6));\n\t\tlua_pushlstring(L, (const char *)buf+1, sz-1);\n\t\tlua_pushinteger(L, buf[0]);\n\t\treturn 3;\n\tcase BSON_OBJECTID: {\n\t\tif (sz != 12) {\n\t\t\treturn luaL_error(L, \"Invalid object id\");\n\t\t}\n\t\tchar oid[24];\n\t\tint i;\n\t\tconst uint8_t * id = buf;\n\t\tstatic const char *hex = \"0123456789abcdef\";\n\t\tfor (i=0;i<12;i++) {\n\t\t\toid[i*2] = hex[id[i] >> 4];\n\t\t\toid[i*2+1] = hex[id[i] & 0xf];\n\t\t}\n\t\tlua_pushvalue(L, lua_upvalueindex(7));\n\t\tlua_pushlstring(L, oid, 24);\n\n\t\treturn 2;\n\t}\n\tcase BSON_DATE: {\n\t\tif (sz != 4) {\n\t\t\treturn luaL_error(L, \"Invalid date\");\n\t\t}\n\t\tint d = *(const int *)buf;\n\t\tlua_pushvalue(L, lua_upvalueindex(9));\n\t\tlua_pushinteger(L, d);\n\t\treturn 2;\n\t}\n\tcase BSON_TIMESTAMP: {\n\t\tif (sz != 8) {\n\t\t\treturn luaL_error(L, \"Invalid timestamp\");\n\t\t}\n\t\tconst uint32_t * ts = (const uint32_t *)buf;\n\t\tlua_pushvalue(L, lua_upvalueindex(8));\n\t\tlua_pushinteger(L, (lua_Integer)ts[1]);\n\t\tlua_pushinteger(L, (lua_Integer)ts[0]);\n\t\treturn 3;\n\t}\n\tcase BSON_REGEX: {\n\t\t--sz;\n\t\tsize_t i;\n\t\tconst uint8_t *str = buf;\n\t\tfor (i=0;i<sz;i++) {\n\t\t\tif (str[sz-i-1]==0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tlua_pushvalue(L, lua_upvalueindex(10));\n\t\tif (i==sz) {\n\t\t\treturn luaL_error(L, \"Invalid regex\");\n\t\t}\n\t\tlua_pushlstring(L, (const char *)str, sz - i - 1);\n\t\tlua_pushlstring(L, (const char *)str+sz-i, i);\n\t\treturn 3;\n\t}\n\tcase BSON_MINKEY:\n\t\tlua_pushvalue(L, lua_upvalueindex(11));\n\t\treturn 1;\n\tcase BSON_MAXKEY:\n\t\tlua_pushvalue(L, lua_upvalueindex(12));\n\t\treturn 1;\n\tcase BSON_NULL:\n\t\tlua_pushvalue(L, lua_upvalueindex(4));\n\t\treturn 1;\n\tcase BSON_JSCODE:\n\tcase BSON_DBPOINTER:\n\tcase BSON_SYMBOL:\n\tcase BSON_CODEWS:\n\t\tlua_pushvalue(L, lua_upvalueindex(14));\n\t\tlua_pushlstring(L, (const char *)buf, sz);\n\t\treturn 2;\n\tcase BSON_INT64: {\n\t\tif (sz != 8) {\n\t\t\treturn luaL_error(L, \"Invalid int64\");\n\t\t}\n\t\tint64_t d = *(const int64_t *)buf;\n\t\tlua_pushvalue(L, lua_upvalueindex(13));\n\t\tlua_pushinteger(L, d);\n\t\treturn 2;\n\t}\n\tdefault:\n\t\treturn luaL_error(L, \"Invalid subtype %d\", subtype);\n\t}\n}\n\nstatic int\nltype(lua_State *L) {\n\tint t = lua_type(L,1);\n\tint type = 0;\n\tswitch (t) {\n\tcase LUA_TNUMBER:\n\t\ttype = 1;\n\t\tbreak;\n\tcase LUA_TBOOLEAN:\n\t\ttype = 2;\n\t\tbreak;\n\tcase LUA_TTABLE:\n\t\ttype = 3;\n\t\tbreak;\n\tcase LUA_TNIL:\n\t\tlua_pushvalue(L, lua_upvalueindex(4));\n\t\treturn 1;\n\tcase LUA_TSTRING: {\n\t\tsize_t len = 0;\n\t\tconst char * str = lua_tolstring(L,1,&len);\n\t\tif (str[0] == 0 && len >= 2) {\n\t\t\treturn lsubtype(L, (uint8_t)str[1], (const uint8_t *)str+2, len-2);\n\t\t} else {\n\t\t\ttype = 5;\n\t\t\tbreak;\n\t\t}\n\t}\n\tdefault:\n\t\treturn luaL_error(L, \"Invalid type %s\",lua_typename(L,t));\n\t}\n\tlua_pushvalue(L, lua_upvalueindex(type));\n\tlua_pushvalue(L,1);\n\treturn 2;\n}\n\nstatic void\ntypeclosure(lua_State *L) {\n\tstatic const char * typename_[] = {\n\t\t\"number\",\t// 1\n\t\t\"boolean\",\t// 2\n\t\t\"table\",\t// 3\n\t\t\"nil\",\t\t// 4\n\t\t\"string\",\t// 5\n\t\t\"binary\",\t// 6\n\t\t\"objectid\",\t// 7\n\t\t\"timestamp\",    // 8\n\t\t\"date\",\t\t// 9\n\t\t\"regex\",\t// 10\n\t\t\"minkey\",\t// 11\n\t\t\"maxkey\",\t// 12\n\t\t\"int64\",\t// 13\n\t\t\"unsupported\", // 14\n\t};\n\tint i;\n\tint n = sizeof(typename_)/sizeof(typename_[0]);\n\tfor (i=0;i<n;i++) {\n\t\tlua_pushstring(L, typename_[i]);\n\t}\n\tlua_pushcclosure(L, ltype, n);\n}\n\nstatic uint8_t oid_header[5];\nstatic ATOM_ULONG oid_counter;\n\nstatic void\ninit_oid_header() {\n\tif (ATOM_LOAD(&oid_counter)) {\n\t\t// already init\n\t\treturn;\n\t}\n\tpid_t pid = getpid();\n\tuint32_t h = 0;\n\tchar hostname[256];\n\tif (gethostname(hostname, sizeof(hostname))==0) {\n\t\tint i;\n\t\tfor (i=0;i<sizeof(hostname) && hostname[i];i++) {\n\t\t\th = h ^ ((h<<5)+(h>>2)+hostname[i]);\n \t\t}\n\t\th ^= i;\n\t}\n\toid_header[0] = h & 0xff;\n\toid_header[1] = (h>>8) & 0xff;\n\toid_header[2] = (h>>16) & 0xff;\n\toid_header[3] = pid & 0xff;\n\toid_header[4] = (pid >> 8) & 0xff;\n\t\n\tunsigned long c = h ^ time(NULL) ^ (uintptr_t)&h;\n\tif (c == 0) {\n\t\tc = 1;\n\t}\n\tATOM_STORE(&oid_counter, c);\n}\n\nstatic inline int\nhextoint(char c) {\n\tif (c>='0' && c<='9')\n\t\treturn c-'0';\n\tif (c>='a' && c<='z')\n\t\treturn c-'a'+10;\n\tif (c>='A' && c<='Z')\n\t\treturn c-'A'+10;\n\treturn 0;\n}\n\nstatic int\nlobjectid(lua_State *L) {\n\tuint8_t oid[14] = { 0, BSON_OBJECTID };\n\tif (lua_isstring(L,1)) {\n\t\tsize_t len;\n\t\tconst char * str = lua_tolstring(L,1,&len);\n\t\tif (len != 24) {\n\t\t\treturn luaL_error(L, \"Invalid objectid %s\", str);\n\t\t}\n\t\tint i;\n\t\tfor (i=0;i<12;i++) {\n\t\t\toid[i+2] = hextoint(str[i*2]) << 4 | hextoint(str[i*2+1]);\n\t\t}\n\t} else {\n\t\ttime_t ti = time(NULL);\n\t\t// old_counter is a static var, use atom inc.\n\t\tuint32_t id = ATOM_FINC(&oid_counter);\n\n\t\toid[2] = (ti>>24) & 0xff;\n\t\toid[3] = (ti>>16) & 0xff;\n\t\toid[4] = (ti>>8) & 0xff;\n\t\toid[5] = ti & 0xff;\n\t\tmemcpy(oid+6 , oid_header, 5);\n\t\toid[11] = (id>>16) & 0xff; \n\t\toid[12] = (id>>8) & 0xff; \n\t\toid[13] = id & 0xff;\n\t}\n\tlua_pushlstring( L, (const char *)oid, 14);\n\n\treturn 1;\n}\n\nLUAMOD_API int\nluaopen_bson(lua_State *L) {\n\tluaL_checkversion(L);\n\tint i;\n\tfor (i=0;i<MAX_NUMBER;i++) {\n\t\tchar tmp[8];\n\t\tbson_numstr_len[i] = sprintf(tmp,\"%d\",i);\n\t\tmemcpy(bson_numstrs[i], tmp, bson_numstr_len[i]);\n\t}\n\tluaL_Reg l[] = {\n\t\t{ \"encode\", lencode },\n\t\t{ \"encode_order\", lencode_order },\n\t\t{ \"date\", ldate },\n\t\t{ \"timestamp\", ltimestamp  },\n\t\t{ \"regex\", lregex },\n\t\t{ \"binary\", lbinary },\n\t\t{ \"objectid\", lobjectid },\n\t\t{ \"int64\", lint64 },\n\t\t{ \"decode\", ldecode },\n\t\t{ \"to_lightuserdata\", lto_lightuserdata },\n\t\t{ NULL,  NULL },\n\t};\n\n\tluaL_newlib(L,l);\n\n\ttypeclosure(L);\n\tlua_setfield(L,-2,\"type\");\n\tchar null[] = { 0, BSON_NULL };\n\tlua_pushlstring(L, null, sizeof(null));\n\tlua_setfield(L,-2,\"null\");\n\tchar minkey[] = { 0, (char)BSON_MINKEY };\n\tlua_pushlstring(L, minkey, sizeof(minkey));\n\tlua_setfield(L,-2,\"minkey\");\n\tchar maxkey[] = { 0, BSON_MAXKEY };\n\tlua_pushlstring(L, maxkey, sizeof(maxkey));\n\tlua_setfield(L,-2,\"maxkey\");\n\tinit_oid_header();\n\n\treturn 1;\n}\n\n"
  },
  {
    "path": "lualib-src/lua-clientsocket.c",
    "content": "// simple lua socket library for client\n// It's only for demo, limited feature. Don't use it in your project.\n// Rewrite socket library by yourself .\n\n#define LUA_LIB\n\n#include <lua.h>\n#include <lauxlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <pthread.h>\n#include <stdlib.h>\n\n#include <netinet/in.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <unistd.h>\n#include <errno.h>\n#include <fcntl.h>\n\n#define CACHE_SIZE 0x1000\t\n\nstatic int\nlconnect(lua_State *L) {\n\tconst char * addr = luaL_checkstring(L, 1);\n\tint port = luaL_checkinteger(L, 2);\n\tint fd = socket(AF_INET,SOCK_STREAM,0);\n\tstruct sockaddr_in my_addr;\n\n\tmy_addr.sin_addr.s_addr=inet_addr(addr);\n\tmy_addr.sin_family=AF_INET;\n\tmy_addr.sin_port=htons(port);\n\n\tint r = connect(fd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr_in));\n\n\tif (r == -1) {\n\t\treturn luaL_error(L, \"Connect %s %d failed\", addr, port);\n\t}\n\n\tint flag = fcntl(fd, F_GETFL, 0);\n\tfcntl(fd, F_SETFL, flag | O_NONBLOCK);\n\n\tlua_pushinteger(L, fd);\n\n\treturn 1;\n}\n\nstatic int\nlclose(lua_State *L) {\n\tint fd = luaL_checkinteger(L, 1);\n\tclose(fd);\n\n\treturn 0;\n}\n\nstatic void\nblock_send(lua_State *L, int fd, const char * buffer, int sz) {\n\twhile(sz > 0) {\n\t\tint r = send(fd, buffer, sz, 0);\n\t\tif (r < 0) {\n\t\t\tif (errno == EAGAIN || errno == EINTR)\n\t\t\t\tcontinue;\n\t\t\tluaL_error(L, \"socket error: %s\", strerror(errno));\n\t\t}\n\t\tbuffer += r;\n\t\tsz -= r;\n\t}\n}\n\n/*\n\tinteger fd\n\tstring message\n */\nstatic int\nlsend(lua_State *L) {\n\tsize_t sz = 0;\n\tint fd = luaL_checkinteger(L,1);\n\tconst char * msg = luaL_checklstring(L, 2, &sz);\n\n\tblock_send(L, fd, msg, (int)sz);\n\n\treturn 0;\n}\n\n/*\n\tintger fd\n\tstring last\n\ttable result\n\n\treturn \n\t\tboolean (true: data, false: block, nil: close)\n\t\tstring last\n */\n\nstruct socket_buffer {\n\tvoid * buffer;\n\tint sz;\n};\n\nstatic int\nlrecv(lua_State *L) {\n\tint fd = luaL_checkinteger(L,1);\n\n\tchar buffer[CACHE_SIZE];\n\tint r = recv(fd, buffer, CACHE_SIZE, 0);\n\tif (r == 0) {\n\t\tlua_pushliteral(L, \"\");\n\t\t// close\n\t\treturn 1;\n\t}\n\tif (r < 0) {\n\t\tif (errno == EAGAIN || errno == EINTR) {\n\t\t\treturn 0;\n\t\t}\n\t\tluaL_error(L, \"socket error: %s\", strerror(errno));\n\t}\n\tlua_pushlstring(L, buffer, r);\n\treturn 1;\n}\n\nstatic int\nlusleep(lua_State *L) {\n\tint n = luaL_checknumber(L, 1);\n\tusleep(n);\n\treturn 0;\n}\n\n// quick and dirty none block stdin readline\n\n#define QUEUE_SIZE 1024\n\nstruct queue {\n\tpthread_mutex_t lock;\n\tint head;\n\tint tail;\n\tchar * queue[QUEUE_SIZE];\n};\n\nstatic void *\nreadline_stdin(void * arg) {\n\tstruct queue * q = arg;\n\tchar tmp[1024];\n\twhile (!feof(stdin)) {\n\t\tif (fgets(tmp,sizeof(tmp),stdin) == NULL) {\n\t\t\t// read stdin failed\n\t\t\texit(1);\n\t\t}\n\t\tint n = strlen(tmp) -1;\n\n\t\tchar * str = malloc(n+1);\n\t\tmemcpy(str, tmp, n);\n\t\tstr[n] = 0;\n\n\t\tpthread_mutex_lock(&q->lock);\n\t\tq->queue[q->tail] = str;\n\n\t\tif (++q->tail >= QUEUE_SIZE) {\n\t\t\tq->tail = 0;\n\t\t}\n\t\tif (q->head == q->tail) {\n\t\t\t// queue overflow\n\t\t\texit(1);\n\t\t}\n\t\tpthread_mutex_unlock(&q->lock);\n\t}\n\treturn NULL;\n}\n\nstatic int\nlreadstdin(lua_State *L) {\n\tstruct queue *q = lua_touserdata(L, lua_upvalueindex(1));\n\tpthread_mutex_lock(&q->lock);\n\tif (q->head == q->tail) {\n\t\tpthread_mutex_unlock(&q->lock);\n\t\treturn 0;\n\t}\n\tchar * str = q->queue[q->head];\n\tif (++q->head >= QUEUE_SIZE) {\n\t\tq->head = 0;\n\t}\n\tpthread_mutex_unlock(&q->lock);\n\tlua_pushstring(L, str);\n\tfree(str);\n\treturn 1;\n}\n\nstatic int\nlshutdown(lua_State *L) {\n\tint fd = luaL_checkinteger(L,1);\n\tconst char *mode = luaL_checkstring(L,2);\n\tint v = 0;\n\tint i;\n\tint read = 1;\n\tint write = 2;\n\tfor (i=0;mode[i];i++) {\n\t\tswitch(mode[i]) {\n\t\tcase 'r':\n\t\t\tv |= read;\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\tv |= write;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn luaL_error(L, \"Invalid mode %c\", mode[i]);\n\t\t}\n\t}\n\tif (v == 0) {\n\t\treturn luaL_error(L, \"mode should be r or/and w\");\n\t}\n\tif (v == read)\n\t\tv = SHUT_RD;\n\telse if (v == write)\n\t\tv = SHUT_WR;\n\telse\n\t\tv = SHUT_RDWR;\n\tprintf(\"SHUTDOWN %d %d\\n\", fd, v);\n\tshutdown(fd, v);\n\treturn 0;\n}\n\nLUAMOD_API int\nluaopen_client_socket(lua_State *L) {\n\tluaL_checkversion(L);\n\tluaL_Reg l[] = {\n\t\t{ \"connect\", lconnect },\n\t\t{ \"recv\", lrecv },\n\t\t{ \"send\", lsend },\n\t\t{ \"shutdown\", lshutdown },\n\t\t{ \"close\", lclose },\n\t\t{ \"usleep\", lusleep },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_newlib(L, l);\n\n\tstruct queue * q = lua_newuserdata(L, sizeof(*q));\n\tmemset(q, 0, sizeof(*q));\n\tpthread_mutex_init(&q->lock, NULL);\n\tlua_pushcclosure(L, lreadstdin, 1);\n\tlua_setfield(L, -2, \"readstdin\");\n\n\tpthread_t pid ;\n\tpthread_create(&pid, NULL, readline_stdin, q);\n\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-cluster.c",
    "content": "#define LUA_LIB\n\n#include <lua.h>\n#include <lauxlib.h>\n#include <string.h>\n#include <assert.h>\n#include <unistd.h>\n\n#include \"skynet.h\"\n\n/*\n\tuint32_t/string addr \n\tuint32_t/session session\n\tlightuserdata msg\n\tuint32_t sz\n\n\treturn \n\t\tstring request\n\t\tuint32_t next_session\n */\n\n#define TEMP_LENGTH 0x8200\n#define MULTI_PART 0x8000\n\nstatic void\nfill_uint32(uint8_t * buf, uint32_t n) {\n\tbuf[0] = n & 0xff;\n\tbuf[1] = (n >> 8) & 0xff;\n\tbuf[2] = (n >> 16) & 0xff;\n\tbuf[3] = (n >> 24) & 0xff;\n}\n\nstatic void\nfill_header(lua_State *L, uint8_t *buf, int sz) {\n\tassert(sz < 0x10000);\n\tbuf[0] = (sz >> 8) & 0xff;\n\tbuf[1] = sz & 0xff;\n}\n\n/*\n\tThe request package : \n\t\tfirst WORD is size of the package with big-endian\n\t\tDWORD in content is small-endian\n\tsize <= 0x8000 (32K) and address is id\n\t\tWORD sz+9\n\t\tBYTE 0\n\t\tDWORD addr\n\t\tDWORD session\n\t\tPADDING msg(sz)\n\tsize > 0x8000 and address is id\n\t\tWORD 13\n\t\tBYTE 1\t; multireq\t, 0x41: multi push\n\t\tDWORD addr\n\t\tDWORD session\n\t\tDWORD sz\n\n\tsize <= 0x8000 (32K) and address is string\n\t\tWORD sz+6+namelen\n\t\tBYTE 0x80\n\t\tBYTE namelen\n\t\tSTRING name\n\t\tDWORD session\n\t\tPADDING msg(sz)\n\tsize > 0x8000 and address is string\n\t\tWORD 10 + namelen\n\t\tBYTE 0x81\t; 0xc1 : multi push\n\t\tBYTE namelen\n\t\tSTRING name\n\t\tDWORD session\n\t\tDWORD sz\n\n\tmulti req\n\t\tWORD sz + 5\n\t\tBYTE 2/3 ; 2:multipart, 3:multipart end\n\t\tDWORD SESSION\n\t\tPADDING msgpart(sz)\n\n\ttrace\n\t\tWORD stringsz + 1\n\t\tBYTE 4\n\t\tSTRING tag\n */\nstatic int\npackreq_number(lua_State *L, int session, void * msg, uint32_t sz, int is_push) {\n\tuint32_t addr = (uint32_t)lua_tointeger(L,1);\n\tuint8_t buf[TEMP_LENGTH];\n\tif (sz < MULTI_PART) {\n\t\tfill_header(L, buf, sz+9);\n\t\tbuf[2] = 0;\n\t\tfill_uint32(buf+3, addr);\n\t\tfill_uint32(buf+7, is_push ? 0 : (uint32_t)session);\n\t\tmemcpy(buf+11,msg,sz);\n\n\t\tlua_pushlstring(L, (const char *)buf, sz+11);\n\t\treturn 0;\n\t} else {\n\t\tint part = (sz - 1) / MULTI_PART + 1;\n\t\tfill_header(L, buf, 13);\n\t\tbuf[2] = is_push ? 0x41 : 1;\t// multi push or request\n\t\tfill_uint32(buf+3, addr);\n\t\tfill_uint32(buf+7, (uint32_t)session);\n\t\tfill_uint32(buf+11, sz);\n\t\tlua_pushlstring(L, (const char *)buf, 15);\n\t\treturn part;\n\t}\n}\n\nstatic int\npackreq_string(lua_State *L, int session, void * msg, uint32_t sz, int is_push) {\n\tsize_t namelen = 0;\n\tconst char *name = lua_tolstring(L, 1, &namelen);\n\tif (name == NULL || namelen < 1 || namelen > 255) {\n\t\tskynet_free(msg);\n\t\tif (name == NULL) {\n\t\t\tluaL_error(L, \"name is not a string, it's a %s\", lua_typename(L, lua_type(L, 1)));\n\t\t} else {\n\t\t\tluaL_error(L, \"name length is invalid, must be between 1 and 255 characters: %s\", name);\n\t\t}\n\t}\n\n\tuint8_t buf[TEMP_LENGTH];\n\tif (sz < MULTI_PART) {\n\t\tfill_header(L, buf, sz+6+namelen);\n\t\tbuf[2] = 0x80;\n\t\tbuf[3] = (uint8_t)namelen;\n\t\tmemcpy(buf+4, name, namelen);\n\t\tfill_uint32(buf+4+namelen, is_push ? 0 : (uint32_t)session);\n\t\tmemcpy(buf+8+namelen,msg,sz);\n\n\t\tlua_pushlstring(L, (const char *)buf, sz+8+namelen);\n\t\treturn 0;\n\t} else {\n\t\tint part = (sz - 1) / MULTI_PART + 1;\n\t\tfill_header(L, buf, 10+namelen);\n\t\tbuf[2] = is_push ? 0xc1 : 0x81;\t// multi push or request\n\t\tbuf[3] = (uint8_t)namelen;\n\t\tmemcpy(buf+4, name, namelen);\n\t\tfill_uint32(buf+4+namelen, (uint32_t)session);\n\t\tfill_uint32(buf+8+namelen, sz);\n\n\t\tlua_pushlstring(L, (const char *)buf, 12+namelen);\n\t\treturn part;\n\t}\n}\n\nstatic void\npackreq_multi(lua_State *L, int session, void * msg, uint32_t sz) {\n\tuint8_t buf[TEMP_LENGTH];\n\tint part = (sz - 1) / MULTI_PART + 1;\n\tint i;\n\tchar *ptr = msg;\n\tfor (i=0;i<part;i++) {\n\t\tuint32_t s;\n\t\tif (sz > MULTI_PART) {\n\t\t\ts = MULTI_PART;\n\t\t\tbuf[2] = 2;\n\t\t} else {\n\t\t\ts = sz;\n\t\t\tbuf[2] = 3;\t// the last multi part\n\t\t}\n\t\tfill_header(L, buf, s+5);\n\t\tfill_uint32(buf+3, (uint32_t)session);\n\t\tmemcpy(buf+7, ptr, s);\n\t\tlua_pushlstring(L, (const char *)buf, s+7);\n\t\tlua_rawseti(L, -2, i+1);\n\t\tsz -= s;\n\t\tptr += s;\n\t}\n}\n\nstatic int\npackrequest(lua_State *L, int is_push) {\n\tvoid *msg = lua_touserdata(L,3);\n\tif (msg == NULL) {\n\t\treturn luaL_error(L, \"Invalid request message\");\n\t}\n\tuint32_t sz = (uint32_t)luaL_checkinteger(L,4);\n\tint session = luaL_checkinteger(L,2);\n\tif (session <= 0) {\n\t\tskynet_free(msg);\n\t\treturn luaL_error(L, \"Invalid request session %d\", session);\n\t}\n\tint addr_type = lua_type(L,1);\n\tint multipak;\n\tif (addr_type == LUA_TNUMBER) {\n\t\tmultipak = packreq_number(L, session, msg, sz, is_push);\n\t} else {\n\t\tmultipak = packreq_string(L, session, msg, sz, is_push);\n\t}\n\tuint32_t new_session = (uint32_t)session + 1;\n\tif (new_session > INT32_MAX) {\n\t\tnew_session = 1;\n\t}\n\tlua_pushinteger(L, new_session);\n\tif (multipak) {\n\t\tlua_createtable(L, multipak, 0);\n\t\tpackreq_multi(L, session, msg, sz);\n\t\tskynet_free(msg);\n\t\treturn 3;\n\t} else {\n\t\tskynet_free(msg);\n\t\treturn 2;\n\t}\n}\n\nstatic int\nlpackrequest(lua_State *L) {\n\treturn packrequest(L, 0);\n}\n\nstatic int\nlpackpush(lua_State *L) {\n\treturn packrequest(L, 1);\n}\n\nstatic int\nlpacktrace(lua_State *L) {\n\tsize_t sz;\n\tconst char * tag = luaL_checklstring(L, 1, &sz);\n\tif (sz > 0x8000) {\n\t\treturn luaL_error(L, \"trace tag is too long : %d\", (int) sz);\n\t}\n\tuint8_t buf[TEMP_LENGTH];\n\tbuf[2] = 4;\n\tfill_header(L, buf, sz+1);\n\tmemcpy(buf+3, tag, sz);\n\tlua_pushlstring(L, (const char *)buf, sz+3);\n\treturn 1;\n}\n\n/*\n\tstring packed message\n\treturn \t\n\t\tuint32_t or string addr\n\t\tint session\n\t\tlightuserdata msg\n\t\tint sz\n\t\tboolean padding\n\t\tboolean is_push\n */\n\nstatic inline uint32_t\nunpack_uint32(const uint8_t * buf) {\n\treturn buf[0] | buf[1]<<8 | buf[2]<<16 | buf[3]<<24;\n}\n\nstatic void\nreturn_buffer(lua_State *L, const char * buffer, int sz) {\n\tvoid * ptr = skynet_malloc(sz);\n\tmemcpy(ptr, buffer, sz);\n\tlua_pushlightuserdata(L, ptr);\n\tlua_pushinteger(L, sz);\n}\n\nstatic int\nunpackreq_number(lua_State *L, const uint8_t * buf, int sz) {\n\tif (sz < 9) {\n\t\treturn luaL_error(L, \"Invalid cluster message (size=%d)\", sz);\n\t}\n\tuint32_t address = unpack_uint32(buf+1);\n\tuint32_t session = unpack_uint32(buf+5);\n\tlua_pushinteger(L, address);\n\tlua_pushinteger(L, session);\n\n\treturn_buffer(L, (const char *)buf+9, sz-9);\n\tif (session == 0) {\n\t\tlua_pushnil(L);\n\t\tlua_pushboolean(L,1);\t// is_push, no response\n\t\treturn 6;\n\t}\n\n\treturn 4;\n}\n\nstatic int\nunpackmreq_number(lua_State *L, const uint8_t * buf, int sz, int is_push) {\n\tif (sz != 13) {\n\t\treturn luaL_error(L, \"Invalid cluster message size %d (multi req must be 13)\", sz);\n\t}\n\tuint32_t address = unpack_uint32(buf+1);\n\tuint32_t session = unpack_uint32(buf+5);\n\tuint32_t size = unpack_uint32(buf+9);\n\tlua_pushinteger(L, address);\n\tlua_pushinteger(L, session);\n\tlua_pushnil(L);\n\tlua_pushinteger(L, size);\n\tlua_pushboolean(L, 1);\t// padding multi part\n\tlua_pushboolean(L, is_push);\n\n\treturn 6;\n}\n\nstatic int\nunpackmreq_part(lua_State *L, const uint8_t * buf, int sz) {\n\tif (sz < 5) {\n\t\treturn luaL_error(L, \"Invalid cluster multi part message\");\n\t}\n\tint padding = (buf[0] == 2);\n\tuint32_t session = unpack_uint32(buf+1);\n\tlua_pushboolean(L, 0);\t// no address\n\tlua_pushinteger(L, session);\n\treturn_buffer(L, (const char *)buf+5, sz-5);\n\tlua_pushboolean(L, padding);\n\n\treturn 5;\n}\n\nstatic int\nunpacktrace(lua_State *L, const char * buf, int sz) {\n\tlua_pushlstring(L, buf + 1, sz - 1);\n\treturn 1;\n}\n\nstatic int\nunpackreq_string(lua_State *L, const uint8_t * buf, int sz) {\n\tif (sz < 2) {\n\t\treturn luaL_error(L, \"Invalid cluster message (size=%d)\", sz);\n\t}\n\tsize_t namesz = buf[1];\n\tif (sz < namesz + 6) {\n\t\treturn luaL_error(L, \"Invalid cluster message (size=%d)\", sz);\n\t}\n\tlua_pushlstring(L, (const char *)buf+2, namesz);\n\tuint32_t session = unpack_uint32(buf + namesz + 2);\n\tlua_pushinteger(L, (uint32_t)session);\n\treturn_buffer(L, (const char *)buf+2+namesz+4, sz - namesz - 6);\n\tif (session == 0) {\n\t\tlua_pushnil(L);\n\t\tlua_pushboolean(L,1);\t// is_push, no response\n\t\treturn 6;\n\t}\n\n\treturn 4;\n}\n\nstatic int\nunpackmreq_string(lua_State *L, const uint8_t * buf, int sz, int is_push) {\n\tif (sz < 2) {\n\t\treturn luaL_error(L, \"Invalid cluster message (size=%d)\", sz);\n\t}\n\tsize_t namesz = buf[1];\n\tif (sz < namesz + 10) {\n\t\treturn luaL_error(L, \"Invalid cluster message (size=%d)\", sz);\n\t}\n\tlua_pushlstring(L, (const char *)buf+2, namesz);\n\tuint32_t session = unpack_uint32(buf + namesz + 2);\n\tuint32_t size = unpack_uint32(buf + namesz + 6);\n\tlua_pushinteger(L, session);\n\tlua_pushnil(L);\n\tlua_pushinteger(L, size);\n\tlua_pushboolean(L, 1);\t// padding multipart\n\tlua_pushboolean(L, is_push);\n\n\treturn 6;\n}\n\nstatic int\nlunpackrequest(lua_State *L) {\n\tint sz;\n\tconst char *msg;\n\tif (lua_type(L, 1) == LUA_TLIGHTUSERDATA) {\n\t\tmsg = (const char *)lua_touserdata(L, 1);\n\t\tsz = luaL_checkinteger(L, 2);\n\t} else {\n\t\tsize_t ssz;\n\t\tmsg = luaL_checklstring(L,1,&ssz);\n\t\tsz = (int)ssz;\n\t}\n\tif (sz == 0)\n\t\treturn luaL_error(L, \"Invalid req package. size == 0\");\n\tswitch (msg[0]) {\n\tcase 0:\n\t\treturn unpackreq_number(L, (const uint8_t *)msg, sz);\n\tcase 1:\n\t\treturn unpackmreq_number(L, (const uint8_t *)msg, sz, 0);\t// request\n\tcase '\\x41':\n\t\treturn unpackmreq_number(L, (const uint8_t *)msg, sz, 1);\t// push\n\tcase 2:\n\tcase 3:\n\t\treturn unpackmreq_part(L, (const uint8_t *)msg, sz);\n\tcase 4:\n\t\treturn unpacktrace(L, msg, sz);\n\tcase '\\x80':\n\t\treturn unpackreq_string(L, (const uint8_t *)msg, sz);\n\tcase '\\x81':\n\t\treturn unpackmreq_string(L, (const uint8_t *)msg, sz, 0 );\t// request\n\tcase '\\xc1':\n\t\treturn unpackmreq_string(L, (const uint8_t *)msg, sz, 1 );\t// push\n\tdefault:\n\t\treturn luaL_error(L, \"Invalid req package type %d\", msg[0]);\n\t}\n}\n\n/*\n\tThe response package :\n\tWORD size (big endian)\n\tDWORD session\n\tBYTE type\n\t\t0: error\n\t\t1: ok\n\t\t2: multi begin\n\t\t3: multi part\n\t\t4: multi end\n\tPADDING msg\n\t\ttype = 0, error msg\n\t\ttype = 1, msg\n\t\ttype = 2, DWORD size\n\t\ttype = 3/4, msg\n */\n/*\n\tint session\n\tboolean ok\n\tlightuserdata msg\n\tint sz\n\treturn string response\n */\nstatic int\nlpackresponse(lua_State *L) {\n\tuint32_t session = (uint32_t)luaL_checkinteger(L,1);\n\t// clusterd.lua:command.socket call lpackresponse,\n\t// and the msg/sz is return by skynet.rawcall , so don't free(msg)\n\tint ok = lua_toboolean(L,2);\n\tvoid * msg;\n\tsize_t sz;\n\t\n\tif (lua_type(L,3) == LUA_TSTRING) {\n\t\tmsg = (void *)lua_tolstring(L, 3, &sz);\n\t} else {\n\t\tmsg = lua_touserdata(L,3);\n\t\tsz = (size_t)luaL_checkinteger(L, 4);\n\t}\n\n\tif (!ok) {\n\t\tif (sz > MULTI_PART) {\n\t\t\t// truncate the error msg if too long\n\t\t\tsz = MULTI_PART;\n\t\t}\n\t} else {\n\t\tif (sz > MULTI_PART) {\n\t\t\t// return \n\t\t\tint part = (sz - 1) / MULTI_PART + 1;\n\t\t\tlua_createtable(L, part+1, 0);\n\t\t\tuint8_t buf[TEMP_LENGTH];\n\n\t\t\t// multi part begin\n\t\t\tfill_header(L, buf, 9);\n\t\t\tfill_uint32(buf+2, session);\n\t\t\tbuf[6] = 2;\n\t\t\tfill_uint32(buf+7, (uint32_t)sz);\n\t\t\tlua_pushlstring(L, (const char *)buf, 11);\n\t\t\tlua_rawseti(L, -2, 1);\n\n\t\t\tchar * ptr = msg;\n\t\t\tint i;\n\t\t\tfor (i=0;i<part;i++) {\n\t\t\t\tint s;\n\t\t\t\tif (sz > MULTI_PART) {\n\t\t\t\t\ts = MULTI_PART;\n\t\t\t\t\tbuf[6] = 3;\n\t\t\t\t} else {\n\t\t\t\t\ts = sz;\n\t\t\t\t\tbuf[6] = 4;\n\t\t\t\t}\n\t\t\t\tfill_header(L, buf, s+5);\n\t\t\t\tfill_uint32(buf+2, session);\n\t\t\t\tmemcpy(buf+7,ptr,s);\n\t\t\t\tlua_pushlstring(L, (const char *)buf, s+7);\n\t\t\t\tlua_rawseti(L, -2, i+2);\n\t\t\t\tsz -= s;\n\t\t\t\tptr += s;\n\t\t\t}\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tuint8_t buf[TEMP_LENGTH];\n\tfill_header(L, buf, sz+5);\n\tfill_uint32(buf+2, session);\n\tbuf[6] = ok;\n\tmemcpy(buf+7,msg,sz);\n\n\tlua_pushlstring(L, (const char *)buf, sz+7);\n\n\treturn 1;\n}\n\n/*\n\tstring packed response\n\treturn integer session\n\t\tboolean ok\n\t\tstring msg\n\t\tboolean padding\n */\nstatic int\nlunpackresponse(lua_State *L) {\n\tsize_t sz;\n\tconst char * buf = luaL_checklstring(L, 1, &sz);\n\tif (sz < 5) {\n\t\treturn 0;\n\t}\n\tuint32_t session = unpack_uint32((const uint8_t *)buf);\n\tlua_pushinteger(L, (lua_Integer)session);\n\tswitch(buf[4]) {\n\tcase 0:\t// error\n\t\tlua_pushboolean(L, 0);\n\t\tlua_pushlstring(L, buf+5, sz-5);\n\t\treturn 3;\n\tcase 1:\t// ok\n\tcase 4:\t// multi end\n\t\tlua_pushboolean(L, 1);\n\t\tlua_pushlstring(L, buf+5, sz-5);\n\t\treturn 3;\n\tcase 2:\t// multi begin\n\t\tif (sz != 9) {\n\t\t\treturn 0;\n\t\t}\n\t\tsz = unpack_uint32((const uint8_t *)buf+5);\n\t\tlua_pushboolean(L, 1);\n\t\tlua_pushinteger(L, sz);\n\t\tlua_pushboolean(L, 1);\n\t\treturn 4;\n\tcase 3:\t// multi part\n\t\tlua_pushboolean(L, 1);\n\t\tlua_pushlstring(L, buf+5, sz-5);\n\t\tlua_pushboolean(L, 1);\n\t\treturn 4;\n\tdefault:\n\t\treturn 0;\n\t}\n}\n\n/*\n\ttable\n\tpointer\n\tsz\n\n\tpush (pointer/sz) as string into table, and free pointer\n */\nstatic int\nlappend(lua_State *L) {\n\tluaL_checktype(L, 1, LUA_TTABLE);\n\tint n = lua_rawlen(L, 1);\n\tif (lua_isnil(L, 2)) {\n\t\tlua_settop(L, 3);\n\t\tlua_seti(L, 1, n + 1);\n\t\treturn 0;\n\t}\n\tvoid * buffer = lua_touserdata(L, 2);\n\tif (buffer == NULL)\n\t\treturn luaL_error(L, \"Need lightuserdata\");\n\tint sz = luaL_checkinteger(L, 3);\n\tlua_pushlstring(L, (const char *)buffer, sz);\n\tskynet_free((void *)buffer);\n\tlua_seti(L, 1, n+1);\n\treturn 0;\n}\n\nstatic int\nlconcat(lua_State *L) {\n\tif (!lua_istable(L,1))\n\t\treturn 0;\n\tif (lua_geti(L,1,1) != LUA_TNUMBER)\n\t\treturn 0;\n\tint sz = lua_tointeger(L,-1);\n\tlua_pop(L,1);\n\tchar * buff = skynet_malloc(sz);\n\tint idx = 2;\n\tint offset = 0;\n\twhile(lua_geti(L,1,idx) == LUA_TSTRING) {\n\t\tsize_t s;\n\t\tconst char * str = lua_tolstring(L, -1, &s);\n\t\tif (s+offset > sz) {\n\t\t\tskynet_free(buff);\n\t\t\treturn 0;\n\t\t}\n\t\tmemcpy(buff+offset, str, s);\n\t\tlua_pop(L,1);\n\t\toffset += s;\n\t\t++idx;\n\t}\n\tif (offset != sz) {\n\t\tskynet_free(buff);\n\t\treturn 0;\n\t}\n\t// buff/sz will send to other service, See clusterd.lua\n\tlua_pushlightuserdata(L, buff);\n\tlua_pushinteger(L, sz);\n\treturn 2;\n}\n\nstatic int\nlisname(lua_State *L) {\n\tconst char * name = lua_tostring(L, 1);\n\tif (name && name[0] == '@') {\n\t\tlua_pushboolean(L, 1);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic int\nlnodename(lua_State *L) {\n\tpid_t pid = getpid();\n\tchar hostname[256];\n\tif (gethostname(hostname, sizeof(hostname))==0) {\n\t\tint i;\n\t\tfor (i=0; hostname[i]; i++) {\n\t\t\tif (hostname[i] <= ' ')\n\t\t\t\thostname[i] = '_';\n\t\t}\n\t\tlua_pushfstring(L, \"%s%d\", hostname, (int)pid);\n\t} else {\n\t\tlua_pushfstring(L, \"noname%d\", (int)pid);\n\t}\n\treturn 1;\n}\n\nLUAMOD_API int\nluaopen_skynet_cluster_core(lua_State *L) {\n\tluaL_Reg l[] = {\n\t\t{ \"packrequest\", lpackrequest },\n\t\t{ \"packpush\", lpackpush },\n\t\t{ \"packtrace\", lpacktrace },\n\t\t{ \"unpackrequest\", lunpackrequest },\n\t\t{ \"packresponse\", lpackresponse },\n\t\t{ \"unpackresponse\", lunpackresponse },\n\t\t{ \"append\", lappend },\n\t\t{ \"concat\", lconcat },\n\t\t{ \"isname\", lisname },\n\t\t{ \"nodename\", lnodename },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_checkversion(L);\n\tluaL_newlib(L,l);\n\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-crypt.c",
    "content": "#define LUA_LIB\n\n#include <lua.h>\n#include <lauxlib.h>\n\n#include <time.h>\n#include <stdint.h>\n#include <string.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#define PADDING_MODE_ISO7816_4 0\n#define PADDING_MODE_PKCS7 1\n#define PADDING_MODE_COUNT 2\n\n#define SMALL_CHUNK 256\n\n/* the eight DES S-boxes */\n\nstatic uint32_t SB1[64] = {\n\t0x01010400, 0x00000000, 0x00010000, 0x01010404,\n\t0x01010004, 0x00010404, 0x00000004, 0x00010000,\n\t0x00000400, 0x01010400, 0x01010404, 0x00000400,\n\t0x01000404, 0x01010004, 0x01000000, 0x00000004,\n\t0x00000404, 0x01000400, 0x01000400, 0x00010400,\n\t0x00010400, 0x01010000, 0x01010000, 0x01000404,\n\t0x00010004, 0x01000004, 0x01000004, 0x00010004,\n\t0x00000000, 0x00000404, 0x00010404, 0x01000000,\n\t0x00010000, 0x01010404, 0x00000004, 0x01010000,\n\t0x01010400, 0x01000000, 0x01000000, 0x00000400,\n\t0x01010004, 0x00010000, 0x00010400, 0x01000004,\n\t0x00000400, 0x00000004, 0x01000404, 0x00010404,\n\t0x01010404, 0x00010004, 0x01010000, 0x01000404,\n\t0x01000004, 0x00000404, 0x00010404, 0x01010400,\n\t0x00000404, 0x01000400, 0x01000400, 0x00000000,\n\t0x00010004, 0x00010400, 0x00000000, 0x01010004\n};\n\nstatic uint32_t SB2[64] = {\n\t0x80108020, 0x80008000, 0x00008000, 0x00108020,\n\t0x00100000, 0x00000020, 0x80100020, 0x80008020,\n\t0x80000020, 0x80108020, 0x80108000, 0x80000000,\n\t0x80008000, 0x00100000, 0x00000020, 0x80100020,\n\t0x00108000, 0x00100020, 0x80008020, 0x00000000,\n\t0x80000000, 0x00008000, 0x00108020, 0x80100000,\n\t0x00100020, 0x80000020, 0x00000000, 0x00108000,\n\t0x00008020, 0x80108000, 0x80100000, 0x00008020,\n\t0x00000000, 0x00108020, 0x80100020, 0x00100000,\n\t0x80008020, 0x80100000, 0x80108000, 0x00008000,\n\t0x80100000, 0x80008000, 0x00000020, 0x80108020,\n\t0x00108020, 0x00000020, 0x00008000, 0x80000000,\n\t0x00008020, 0x80108000, 0x00100000, 0x80000020,\n\t0x00100020, 0x80008020, 0x80000020, 0x00100020,\n\t0x00108000, 0x00000000, 0x80008000, 0x00008020,\n\t0x80000000, 0x80100020, 0x80108020, 0x00108000\n};\n\nstatic uint32_t SB3[64] = {\n\t0x00000208, 0x08020200, 0x00000000, 0x08020008,\n\t0x08000200, 0x00000000, 0x00020208, 0x08000200,\n\t0x00020008, 0x08000008, 0x08000008, 0x00020000,\n\t0x08020208, 0x00020008, 0x08020000, 0x00000208,\n\t0x08000000, 0x00000008, 0x08020200, 0x00000200,\n\t0x00020200, 0x08020000, 0x08020008, 0x00020208,\n\t0x08000208, 0x00020200, 0x00020000, 0x08000208,\n\t0x00000008, 0x08020208, 0x00000200, 0x08000000,\n\t0x08020200, 0x08000000, 0x00020008, 0x00000208,\n\t0x00020000, 0x08020200, 0x08000200, 0x00000000,\n\t0x00000200, 0x00020008, 0x08020208, 0x08000200,\n\t0x08000008, 0x00000200, 0x00000000, 0x08020008,\n\t0x08000208, 0x00020000, 0x08000000, 0x08020208,\n\t0x00000008, 0x00020208, 0x00020200, 0x08000008,\n\t0x08020000, 0x08000208, 0x00000208, 0x08020000,\n\t0x00020208, 0x00000008, 0x08020008, 0x00020200\n};\n\nstatic uint32_t SB4[64] = {\n\t0x00802001, 0x00002081, 0x00002081, 0x00000080,\n\t0x00802080, 0x00800081, 0x00800001, 0x00002001,\n\t0x00000000, 0x00802000, 0x00802000, 0x00802081,\n\t0x00000081, 0x00000000, 0x00800080, 0x00800001,\n\t0x00000001, 0x00002000, 0x00800000, 0x00802001,\n\t0x00000080, 0x00800000, 0x00002001, 0x00002080,\n\t0x00800081, 0x00000001, 0x00002080, 0x00800080,\n\t0x00002000, 0x00802080, 0x00802081, 0x00000081,\n\t0x00800080, 0x00800001, 0x00802000, 0x00802081,\n\t0x00000081, 0x00000000, 0x00000000, 0x00802000,\n\t0x00002080, 0x00800080, 0x00800081, 0x00000001,\n\t0x00802001, 0x00002081, 0x00002081, 0x00000080,\n\t0x00802081, 0x00000081, 0x00000001, 0x00002000,\n\t0x00800001, 0x00002001, 0x00802080, 0x00800081,\n\t0x00002001, 0x00002080, 0x00800000, 0x00802001,\n\t0x00000080, 0x00800000, 0x00002000, 0x00802080\n};\n\nstatic uint32_t SB5[64] = {\n\t0x00000100, 0x02080100, 0x02080000, 0x42000100,\n\t0x00080000, 0x00000100, 0x40000000, 0x02080000,\n\t0x40080100, 0x00080000, 0x02000100, 0x40080100,\n\t0x42000100, 0x42080000, 0x00080100, 0x40000000,\n\t0x02000000, 0x40080000, 0x40080000, 0x00000000,\n\t0x40000100, 0x42080100, 0x42080100, 0x02000100,\n\t0x42080000, 0x40000100, 0x00000000, 0x42000000,\n\t0x02080100, 0x02000000, 0x42000000, 0x00080100,\n\t0x00080000, 0x42000100, 0x00000100, 0x02000000,\n\t0x40000000, 0x02080000, 0x42000100, 0x40080100,\n\t0x02000100, 0x40000000, 0x42080000, 0x02080100,\n\t0x40080100, 0x00000100, 0x02000000, 0x42080000,\n\t0x42080100, 0x00080100, 0x42000000, 0x42080100,\n\t0x02080000, 0x00000000, 0x40080000, 0x42000000,\n\t0x00080100, 0x02000100, 0x40000100, 0x00080000,\n\t0x00000000, 0x40080000, 0x02080100, 0x40000100\n};\n\nstatic uint32_t SB6[64] = {\n\t0x20000010, 0x20400000, 0x00004000, 0x20404010,\n\t0x20400000, 0x00000010, 0x20404010, 0x00400000,\n\t0x20004000, 0x00404010, 0x00400000, 0x20000010,\n\t0x00400010, 0x20004000, 0x20000000, 0x00004010,\n\t0x00000000, 0x00400010, 0x20004010, 0x00004000,\n\t0x00404000, 0x20004010, 0x00000010, 0x20400010,\n\t0x20400010, 0x00000000, 0x00404010, 0x20404000,\n\t0x00004010, 0x00404000, 0x20404000, 0x20000000,\n\t0x20004000, 0x00000010, 0x20400010, 0x00404000,\n\t0x20404010, 0x00400000, 0x00004010, 0x20000010,\n\t0x00400000, 0x20004000, 0x20000000, 0x00004010,\n\t0x20000010, 0x20404010, 0x00404000, 0x20400000,\n\t0x00404010, 0x20404000, 0x00000000, 0x20400010,\n\t0x00000010, 0x00004000, 0x20400000, 0x00404010,\n\t0x00004000, 0x00400010, 0x20004010, 0x00000000,\n\t0x20404000, 0x20000000, 0x00400010, 0x20004010\n};\n\nstatic uint32_t SB7[64] = {\n\t0x00200000, 0x04200002, 0x04000802, 0x00000000,\n\t0x00000800, 0x04000802, 0x00200802, 0x04200800,\n\t0x04200802, 0x00200000, 0x00000000, 0x04000002,\n\t0x00000002, 0x04000000, 0x04200002, 0x00000802,\n\t0x04000800, 0x00200802, 0x00200002, 0x04000800,\n\t0x04000002, 0x04200000, 0x04200800, 0x00200002,\n\t0x04200000, 0x00000800, 0x00000802, 0x04200802,\n\t0x00200800, 0x00000002, 0x04000000, 0x00200800,\n\t0x04000000, 0x00200800, 0x00200000, 0x04000802,\n\t0x04000802, 0x04200002, 0x04200002, 0x00000002,\n\t0x00200002, 0x04000000, 0x04000800, 0x00200000,\n\t0x04200800, 0x00000802, 0x00200802, 0x04200800,\n\t0x00000802, 0x04000002, 0x04200802, 0x04200000,\n\t0x00200800, 0x00000000, 0x00000002, 0x04200802,\n\t0x00000000, 0x00200802, 0x04200000, 0x00000800,\n\t0x04000002, 0x04000800, 0x00000800, 0x00200002\n};\n\nstatic uint32_t SB8[64] = {\n\t0x10001040, 0x00001000, 0x00040000, 0x10041040,\n\t0x10000000, 0x10001040, 0x00000040, 0x10000000,\n\t0x00040040, 0x10040000, 0x10041040, 0x00041000,\n\t0x10041000, 0x00041040, 0x00001000, 0x00000040,\n\t0x10040000, 0x10000040, 0x10001000, 0x00001040,\n\t0x00041000, 0x00040040, 0x10040040, 0x10041000,\n\t0x00001040, 0x00000000, 0x00000000, 0x10040040,\n\t0x10000040, 0x10001000, 0x00041040, 0x00040000,\n\t0x00041040, 0x00040000, 0x10041000, 0x00001000,\n\t0x00000040, 0x10040040, 0x00001000, 0x00041040,\n\t0x10001000, 0x00000040, 0x10000040, 0x10040000,\n\t0x10040040, 0x10000000, 0x00040000, 0x10001040,\n\t0x00000000, 0x10041040, 0x00040040, 0x10000040,\n\t0x10040000, 0x10001000, 0x10001040, 0x00000000,\n\t0x10041040, 0x00041000, 0x00041000, 0x00001040,\n\t0x00001040, 0x00040040, 0x10000000, 0x10041000\n};\n\n/* PC1: left and right halves bit-swap */\n\nstatic uint32_t LHs[16] = {\n\t0x00000000, 0x00000001, 0x00000100, 0x00000101,\n\t0x00010000, 0x00010001, 0x00010100, 0x00010101,\n\t0x01000000, 0x01000001, 0x01000100, 0x01000101,\n\t0x01010000, 0x01010001, 0x01010100, 0x01010101\n};\n\nstatic uint32_t RHs[16] = {\n\t0x00000000, 0x01000000, 0x00010000, 0x01010000,\n\t0x00000100, 0x01000100, 0x00010100, 0x01010100,\n\t0x00000001, 0x01000001, 0x00010001, 0x01010001,\n\t0x00000101, 0x01000101, 0x00010101, 0x01010101,\n};\n\n/* platform-independant 32-bit integer manipulation macros */\n\n#define GET_UINT32(n,b,i)\t\t\t\t\t   \\\n{\t\t\t\t\t\t\t\t\t\t\t   \\\n\t(n) = ( (uint32_t) (b)[(i)\t] << 24 )\t   \\\n\t\t| ( (uint32_t) (b)[(i) + 1] << 16 )\t   \\\n\t\t| ( (uint32_t) (b)[(i) + 2] <<  8 )\t   \\\n\t\t| ( (uint32_t) (b)[(i) + 3]\t   );\t  \\\n}\n\n#define PUT_UINT32(n,b,i)\t\t\t\t\t   \\\n{\t\t\t\t\t\t\t\t\t\t\t   \\\n\t(b)[(i)\t] = (uint8_t) ( (n) >> 24 );\t   \\\n\t(b)[(i) + 1] = (uint8_t) ( (n) >> 16 );\t   \\\n\t(b)[(i) + 2] = (uint8_t) ( (n) >>  8 );\t   \\\n\t(b)[(i) + 3] = (uint8_t) ( (n)\t   );\t   \\\n}\n\n/* Initial Permutation macro */\n\n#define DES_IP(X,Y)\t\t\t\t\t\t\t\t\t\t\t \\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   \\\n\tT = ((X >>  4) ^ Y) & 0x0F0F0F0F; Y ^= T; X ^= (T <<  4);   \\\n\tT = ((X >> 16) ^ Y) & 0x0000FFFF; Y ^= T; X ^= (T << 16);   \\\n\tT = ((Y >>  2) ^ X) & 0x33333333; X ^= T; Y ^= (T <<  2);   \\\n\tT = ((Y >>  8) ^ X) & 0x00FF00FF; X ^= T; Y ^= (T <<  8);   \\\n\tY = ((Y << 1) | (Y >> 31)) & 0xFFFFFFFF;\t\t\t\t\t\\\n\tT = (X ^ Y) & 0xAAAAAAAA; Y ^= T; X ^= T;\t\t\t\t   \\\n\tX = ((X << 1) | (X >> 31)) & 0xFFFFFFFF;\t\t\t\t\t\\\n}\n\n/* Final Permutation macro */\n\n#define DES_FP(X,Y)\t\t\t\t\t\t\t\t\t\t\t \\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   \\\n\tX = ((X << 31) | (X >> 1)) & 0xFFFFFFFF;\t\t\t\t\t\\\n\tT = (X ^ Y) & 0xAAAAAAAA; X ^= T; Y ^= T;\t\t\t\t   \\\n\tY = ((Y << 31) | (Y >> 1)) & 0xFFFFFFFF;\t\t\t\t\t\\\n\tT = ((Y >>  8) ^ X) & 0x00FF00FF; X ^= T; Y ^= (T <<  8);   \\\n\tT = ((Y >>  2) ^ X) & 0x33333333; X ^= T; Y ^= (T <<  2);   \\\n\tT = ((X >> 16) ^ Y) & 0x0000FFFF; Y ^= T; X ^= (T << 16);   \\\n\tT = ((X >>  4) ^ Y) & 0x0F0F0F0F; Y ^= T; X ^= (T <<  4);   \\\n}\n\n/* DES round macro */\n\n#define DES_ROUND(X,Y)\t\t\t\t\t\t  \\\n{\t\t\t\t\t\t\t\t\t\t\t   \\\n\tT = *SK++ ^ X;\t\t\t\t\t\t\t  \\\n\tY ^= SB8[ (T\t  ) & 0x3F ] ^\t\t\t  \\\n\t\t SB6[ (T >>  8) & 0x3F ] ^\t\t\t  \\\n\t\t SB4[ (T >> 16) & 0x3F ] ^\t\t\t  \\\n\t\t SB2[ (T >> 24) & 0x3F ];\t\t\t   \\\n\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tT = *SK++ ^ ((X << 28) | (X >> 4));\t\t \\\n\tY ^= SB7[ (T\t  ) & 0x3F ] ^\t\t\t  \\\n\t\t SB5[ (T >>  8) & 0x3F ] ^\t\t\t  \\\n\t\t SB3[ (T >> 16) & 0x3F ] ^\t\t\t  \\\n\t\t SB1[ (T >> 24) & 0x3F ];\t\t\t   \\\n}\n\n/* DES key schedule */\n\nstatic void \ndes_main_ks( uint32_t SK[32], const uint8_t key[8] ) {\n\tint i;\n\tuint32_t X, Y, T;\n\n\tGET_UINT32( X, key, 0 );\n\tGET_UINT32( Y, key, 4 );\n\n\t/* Permuted Choice 1 */\n\n\tT =  ((Y >>  4) ^ X) & 0x0F0F0F0F;  X ^= T; Y ^= (T <<  4);\n\tT =  ((Y\t  ) ^ X) & 0x10101010;  X ^= T; Y ^= (T\t  );\n\n\tX =   (LHs[ (X\t  ) & 0xF] << 3) | (LHs[ (X >>  8) & 0xF ] << 2)\n\t\t| (LHs[ (X >> 16) & 0xF] << 1) | (LHs[ (X >> 24) & 0xF ]\t )\n\t\t| (LHs[ (X >>  5) & 0xF] << 7) | (LHs[ (X >> 13) & 0xF ] << 6)\n\t\t| (LHs[ (X >> 21) & 0xF] << 5) | (LHs[ (X >> 29) & 0xF ] << 4);\n\n\tY =   (RHs[ (Y >>  1) & 0xF] << 3) | (RHs[ (Y >>  9) & 0xF ] << 2)\n\t\t| (RHs[ (Y >> 17) & 0xF] << 1) | (RHs[ (Y >> 25) & 0xF ]\t )\n\t\t| (RHs[ (Y >>  4) & 0xF] << 7) | (RHs[ (Y >> 12) & 0xF ] << 6)\n\t\t| (RHs[ (Y >> 20) & 0xF] << 5) | (RHs[ (Y >> 28) & 0xF ] << 4);\n\n\tX &= 0x0FFFFFFF;\n\tY &= 0x0FFFFFFF;\n\n\t/* calculate subkeys */\n\n\tfor( i = 0; i < 16; i++ )\n\t{\n\t\tif( i < 2 || i == 8 || i == 15 )\n\t\t{\n\t\t\tX = ((X <<  1) | (X >> 27)) & 0x0FFFFFFF;\n\t\t\tY = ((Y <<  1) | (Y >> 27)) & 0x0FFFFFFF;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tX = ((X <<  2) | (X >> 26)) & 0x0FFFFFFF;\n\t\t\tY = ((Y <<  2) | (Y >> 26)) & 0x0FFFFFFF;\n\t\t}\n\n\t\t*SK++ =   ((X <<  4) & 0x24000000) | ((X << 28) & 0x10000000)\n\t\t\t\t| ((X << 14) & 0x08000000) | ((X << 18) & 0x02080000)\n\t\t\t\t| ((X <<  6) & 0x01000000) | ((X <<  9) & 0x00200000)\n\t\t\t\t| ((X >>  1) & 0x00100000) | ((X << 10) & 0x00040000)\n\t\t\t\t| ((X <<  2) & 0x00020000) | ((X >> 10) & 0x00010000)\n\t\t\t\t| ((Y >> 13) & 0x00002000) | ((Y >>  4) & 0x00001000)\n\t\t\t\t| ((Y <<  6) & 0x00000800) | ((Y >>  1) & 0x00000400)\n\t\t\t\t| ((Y >> 14) & 0x00000200) | ((Y\t  ) & 0x00000100)\n\t\t\t\t| ((Y >>  5) & 0x00000020) | ((Y >> 10) & 0x00000010)\n\t\t\t\t| ((Y >>  3) & 0x00000008) | ((Y >> 18) & 0x00000004)\n\t\t\t\t| ((Y >> 26) & 0x00000002) | ((Y >> 24) & 0x00000001);\n\n\t\t*SK++ =   ((X << 15) & 0x20000000) | ((X << 17) & 0x10000000)\n\t\t\t\t| ((X << 10) & 0x08000000) | ((X << 22) & 0x04000000)\n\t\t\t\t| ((X >>  2) & 0x02000000) | ((X <<  1) & 0x01000000)\n\t\t\t\t| ((X << 16) & 0x00200000) | ((X << 11) & 0x00100000)\n\t\t\t\t| ((X <<  3) & 0x00080000) | ((X >>  6) & 0x00040000)\n\t\t\t\t| ((X << 15) & 0x00020000) | ((X >>  4) & 0x00010000)\n\t\t\t\t| ((Y >>  2) & 0x00002000) | ((Y <<  8) & 0x00001000)\n\t\t\t\t| ((Y >> 14) & 0x00000808) | ((Y >>  9) & 0x00000400)\n\t\t\t\t| ((Y\t  ) & 0x00000200) | ((Y <<  7) & 0x00000100)\n\t\t\t\t| ((Y >>  7) & 0x00000020) | ((Y >>  3) & 0x00000011)\n\t\t\t\t| ((Y <<  2) & 0x00000004) | ((Y >> 21) & 0x00000002);\n\t}\n}\n\n/* DES 64-bit block encryption/decryption */\n\nstatic void \ndes_crypt( const uint32_t SK[32], const uint8_t input[8], uint8_t output[8] ) {\n\tuint32_t X, Y, T;\n\n\tGET_UINT32( X, input, 0 );\n\tGET_UINT32( Y, input, 4 );\n\n\tDES_IP( X, Y );\n\n\tDES_ROUND( Y, X );  DES_ROUND( X, Y );\n\tDES_ROUND( Y, X );  DES_ROUND( X, Y );\n\tDES_ROUND( Y, X );  DES_ROUND( X, Y );\n\tDES_ROUND( Y, X );  DES_ROUND( X, Y );\n\tDES_ROUND( Y, X );  DES_ROUND( X, Y );\n\tDES_ROUND( Y, X );  DES_ROUND( X, Y );\n\tDES_ROUND( Y, X );  DES_ROUND( X, Y );\n\tDES_ROUND( Y, X );  DES_ROUND( X, Y );\n\n\tDES_FP( Y, X );\n\n\tPUT_UINT32( Y, output, 0 );\n\tPUT_UINT32( X, output, 4 );\n}\n\nstatic int\nlrandomkey(lua_State *L) {\n\tchar tmp[8];\n\tint i;\n\tchar x = 0;\n\tfor (i=0;i<8;i++) {\n\t\ttmp[i] = random() & 0xff;\n\t\tx ^= tmp[i];\n\t}\n\tif (x==0) {\n\t\ttmp[0] |= 1;\t// avoid 0\n\t}\n\tlua_pushlstring(L, tmp, 8);\n\treturn 1;\n}\n\nstatic void\npadding_mode_table(lua_State *L) {\n\t// see macros PADDING_MODE_ISO7816_4, etc.\n\tconst char * mode[] = {\n\t\t\"iso7816_4\",\n\t\t\"pkcs7\",\n\t};\n\tint n = sizeof(mode) / sizeof(mode[0]);\n\tint i;\n\tlua_createtable(L,0,n);\n\tfor (i=0;i<n;i++) {\n\t\tlua_pushinteger(L, i);\n\t\tlua_setfield(L, -2, mode[i]);\n\t}\n}\n\ntypedef void (*padding_add)(uint8_t buf[8], int offset);\ntypedef int (*padding_remove)(const uint8_t *last);\n\nstatic void\npadding_add_iso7816_4(uint8_t buf[8], int offset) {\n\tbuf[offset] = 0x80;\n\tmemset(buf+offset+1, 0, 7-offset);\n}\n\nstatic int\npadding_remove_iso7816_4(const uint8_t *last) {\n\tint padding = 1;\n\tint i;\n\tfor (i=0;i<8;i++,last--) {\n\t\tif (*last == 0) {\n\t\t\tpadding++;\n\t\t} else if (*last == 0x80) {\n\t\t\treturn padding;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\t// invalid\n\treturn 0;\n}\n\nstatic void\npadding_add_pkcs7(uint8_t buf[8], int offset) {\n\tuint8_t x = 8-offset;\n\tmemset(buf+offset, x, 8-offset);\n}\n\nstatic int\npadding_remove_pkcs7(const uint8_t *last) {\n\tint padding = *last;\n\tint i;\n\tfor (i=1;i<padding;i++) {\n\t\t--last;\n\t\tif (*last != padding)\n\t\t\treturn 0;\t// invalid\n\t}\n\treturn padding;\n}\n\nstatic padding_add padding_add_func[] = {\n\tpadding_add_iso7816_4,\n\tpadding_add_pkcs7,\n};\n\nstatic padding_remove padding_remove_func[] = {\n\tpadding_remove_iso7816_4,\n\tpadding_remove_pkcs7,\n};\n\nstatic inline void\ncheck_padding_mode(lua_State *L, int mode) {\n\tif (mode < 0 || mode >= PADDING_MODE_COUNT)\n\t\tluaL_error(L, \"Invalid padding mode %d\", mode);\n}\n\nstatic void\nadd_padding(lua_State *L, uint8_t buf[8], const uint8_t *src, int offset, int mode) {\n\tcheck_padding_mode(L, mode);\n\tif (offset >= 8)\n\t\tluaL_error(L, \"Invalid padding\");\n\tmemcpy(buf, src, offset);\n\tpadding_add_func[mode](buf, offset);\n}\n\nstatic int\nremove_padding(lua_State *L, const uint8_t *last, int mode) {\n\tcheck_padding_mode(L, mode);\n\treturn padding_remove_func[mode](last);\n}\n\nstatic void\ndes_key(lua_State *L, uint32_t SK[32]) {\n\tsize_t keysz = 0;\n\tconst void * key = luaL_checklstring(L, 1, &keysz);\n\tif (keysz != 8) {\n\t\tluaL_error(L, \"Invalid key size %d, need 8 bytes\", (int)keysz);\n\t}\n\tdes_main_ks(SK, (const uint8_t*)key);\n}\n\nstatic int\nldesencode(lua_State *L) {\n\tuint32_t SK[32];\n\tdes_key(L, SK);\n\n\tsize_t textsz = 0;\n\tconst uint8_t * text = (const uint8_t *)luaL_checklstring(L, 2, &textsz);\n\tsize_t chunksz = (textsz + 8) & ~7;\n\tint padding_mode = luaL_optinteger(L, 3, PADDING_MODE_ISO7816_4);\n\tuint8_t tmp[SMALL_CHUNK];\n\tuint8_t *buffer = tmp;\n\tif (chunksz > SMALL_CHUNK) {\n\t\tbuffer = (uint8_t*)lua_newuserdatauv(L, chunksz, 0);\n\t}\n\tint i;\n\tfor (i=0;i<(int)textsz-7;i+=8) {\n\t\tdes_crypt(SK, text+i, buffer+i);\n\t}\n\tuint8_t tail[8];\n\tadd_padding(L, tail, text+i, textsz - i, padding_mode);\n\tdes_crypt(SK, tail, buffer+i);\n\tlua_pushlstring(L, (const char *)buffer, chunksz);\n\n\treturn 1;\n}\n\nstatic int\nldesdecode(lua_State *L) {\n\tuint32_t ESK[32];\n\tdes_key(L, ESK);\n\tuint32_t SK[32];\n\tint i;\n\tfor( i = 0; i < 32; i += 2 ) {\n\t\tSK[i] = ESK[30 - i];\n\t\tSK[i + 1] = ESK[31 - i];\n\t}\n\tsize_t textsz = 0;\n\tconst uint8_t *text = (const uint8_t *)luaL_checklstring(L, 2, &textsz);\n\tif ((textsz & 7) || textsz == 0) {\n\t\treturn luaL_error(L, \"Invalid des crypt text length %d\", (int)textsz);\n\t}\n\tint padding_mode = luaL_optinteger(L, 3, PADDING_MODE_ISO7816_4);\n\tuint8_t tmp[SMALL_CHUNK];\n\tuint8_t *buffer = tmp;\n\tif (textsz > SMALL_CHUNK) {\n\t\tbuffer = (uint8_t*)lua_newuserdatauv(L, textsz, 0);\n\t}\n\tfor (i=0;i<textsz;i+=8) {\n\t\tdes_crypt(SK, text+i, buffer+i);\n\t}\n\tint padding = remove_padding(L, buffer + textsz - 1, padding_mode);\n\tif (padding <= 0 || padding > 8) {\n\t\treturn luaL_error(L, \"Invalid des crypt text\");\n\t}\n\tlua_pushlstring(L, (const char *)buffer, textsz - padding);\n\treturn 1;\n}\n\n\nstatic void\nHash(const char * str, int sz, uint8_t key[8]) {\n\tuint32_t djb_hash = 5381L;\n\tuint32_t js_hash = 1315423911L;\n\n\tint i;\n\tfor (i=0;i<sz;i++) {\n\t\tuint8_t c = (uint8_t)str[i];\n\t\tdjb_hash += (djb_hash << 5) + c;\n\t\tjs_hash ^= ((js_hash << 5) + c + (js_hash >> 2));\n\t}\n\n\tkey[0] = djb_hash & 0xff;\n\tkey[1] = (djb_hash >> 8) & 0xff;\n\tkey[2] = (djb_hash >> 16) & 0xff;\n\tkey[3] = (djb_hash >> 24) & 0xff;\n\n\tkey[4] = js_hash & 0xff;\n\tkey[5] = (js_hash >> 8) & 0xff;\n\tkey[6] = (js_hash >> 16) & 0xff;\n\tkey[7] = (js_hash >> 24) & 0xff;\n}\n\nstatic int\nlhashkey(lua_State *L) {\n\tsize_t sz = 0;\n\tconst char * key = luaL_checklstring(L, 1, &sz);\n\tuint8_t realkey[8];\n\tHash(key,(int)sz,realkey);\n\tlua_pushlstring(L, (const char *)realkey, 8);\n\treturn 1;\n}\n\nstatic int\nltohex(lua_State *L) {\n\tstatic char hex[] = \"0123456789abcdef\";\n\tsize_t sz = 0;\n\tconst uint8_t * text = (const uint8_t *)luaL_checklstring(L, 1, &sz);\n\tchar tmp[SMALL_CHUNK];\n\tchar *buffer = tmp;\n\tif (sz > SMALL_CHUNK/2) {\n\t\tbuffer = (char*)lua_newuserdatauv(L, sz * 2, 0);\n\t}\n\tint i;\n\tfor (i=0;i<sz;i++) {\n\t\tbuffer[i*2] = hex[text[i] >> 4];\n\t\tbuffer[i*2+1] = hex[text[i] & 0xf];\n\t}\n\tlua_pushlstring(L, buffer, sz * 2);\n\treturn 1;\n}\n\n#define HEX(v,c) { char tmp = (char) c; if (tmp >= '0' && tmp <= '9') { v = tmp-'0'; } else { v = tmp - 'a' + 10; } }\n\nstatic int\nlfromhex(lua_State *L) {\n\tsize_t sz = 0;\n\tconst char * text = luaL_checklstring(L, 1, &sz);\n\tif (sz & 1) {\n\t\treturn luaL_error(L, \"Invalid hex text size %d\", (int)sz);\n\t}\n\tchar tmp[SMALL_CHUNK];\n\tchar *buffer = tmp;\n\tif (sz > SMALL_CHUNK*2) {\n\t\tbuffer = (char*)lua_newuserdatauv(L, sz / 2, 0);\n\t}\n\tint i;\n\tfor (i=0;i<sz;i+=2) {\n\t\tuint8_t hi,low;\n\t\tHEX(hi, text[i]);\n\t\tHEX(low, text[i+1]);\n\t\tif (hi > 16 || low > 16) {\n\t\t\treturn luaL_error(L, \"Invalid hex text\", text);\n\t\t}\n\t\tbuffer[i/2] = hi<<4 | low;\n\t}\n\tlua_pushlstring(L, buffer, i/2);\n\treturn 1;\n}\n\n// Constants are the integer part of the sines of integers (in radians) * 2^32.\nstatic const uint32_t k[64] = {\n0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee ,\n0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501 ,\n0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be ,\n0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 ,\n0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa ,\n0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8 ,\n0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed ,\n0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a ,\n0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c ,\n0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70 ,\n0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05 ,\n0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 ,\n0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039 ,\n0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1 ,\n0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1 ,\n0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 };\n \n// r specifies the per-round shift amounts\nstatic const uint32_t r[] = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n\t\t\t\t\t  5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20,\n\t\t\t\t\t  4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n\t\t\t\t\t  6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21};\n \n// leftrotate function definition\n#define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c))))\n\nstatic void\ndigest_md5(uint32_t w[16], uint32_t result[4]) {\n\tuint32_t a, b, c, d, f, g, temp;\n\tint i;\n \n\ta = 0x67452301u;\n\tb = 0xefcdab89u;\n\tc = 0x98badcfeu;\n\td = 0x10325476u;\n\n\tfor(i = 0; i<64; i++) {\n\t\tif (i < 16) {\n\t\t\tf = (b & c) | ((~b) & d);\n\t\t\tg = i;\n\t\t} else if (i < 32) {\n\t\t\tf = (d & b) | ((~d) & c);\n\t\t\tg = (5*i + 1) % 16;\n\t\t} else if (i < 48) {\n\t\t\tf = b ^ c ^ d;\n\t\t\tg = (3*i + 5) % 16; \n\t\t} else {\n\t\t\tf = c ^ (b | (~d));\n\t\t\tg = (7*i) % 16;\n\t\t}\n\n\t\ttemp = d;\n\t\td = c;\n\t\tc = b;\n\t\tb = b + LEFTROTATE((a + f + k[i] + w[g]), r[i]);\n\t\ta = temp;\n\t}\n\n\tresult[0] = a;\n\tresult[1] = b;\n\tresult[2] = c;\n\tresult[3] = d;\n}\n\n// hmac64 use md5 algorithm without padding, and the result is (c^d .. a^b)\nstatic void\nhmac(uint32_t x[2], uint32_t y[2], uint32_t result[2]) {\n\tuint32_t w[16];\n\tuint32_t r[4];\n\tint i;\n\tfor (i=0;i<16;i+=4) {\n\t\tw[i] = x[1];\n\t\tw[i+1] = x[0];\n\t\tw[i+2] = y[1];\n\t\tw[i+3] = y[0];\n\t}\n\n\tdigest_md5(w,r);\n\n\tresult[0] = r[2]^r[3];\n\tresult[1] = r[0]^r[1];\n}\n\nstatic void\nhmac_md5(uint32_t x[2], uint32_t y[2], uint32_t result[2]) {\n\tuint32_t w[16];\n\tuint32_t r[4];\n\tint i;\n\tfor (i=0;i<12;i+=4) {\n\t\tw[i] = x[0];\n\t\tw[i+1] = x[1];\n\t\tw[i+2] = y[0];\n\t\tw[i+3] = y[1];\n\t}\n\n\tw[12] = 0x80;\n\tw[13] = 0;\n\tw[14] = 384;\n\tw[15] = 0;\n\n\tdigest_md5(w,r);\n\n\tresult[0] = (r[0] + 0x67452301u) ^ (r[2] + 0x98badcfeu);\n\tresult[1] = (r[1] + 0xefcdab89u) ^ (r[3] + 0x10325476u);\n}\n\nstatic void\nread64(lua_State *L, uint32_t xx[2], uint32_t yy[2]) {\n\tsize_t sz = 0;\n\tconst uint8_t *x = (const uint8_t *)luaL_checklstring(L, 1, &sz);\n\tif (sz != 8) {\n\t\tluaL_error(L, \"Invalid uint64 x\");\n\t}\n\tconst uint8_t *y = (const uint8_t *)luaL_checklstring(L, 2, &sz);\n\tif (sz != 8) {\n\t\tluaL_error(L, \"Invalid uint64 y\");\n\t}\n\txx[0] = x[0] | x[1]<<8 | x[2]<<16 | x[3]<<24;\n\txx[1] = x[4] | x[5]<<8 | x[6]<<16 | x[7]<<24;\n\tyy[0] = y[0] | y[1]<<8 | y[2]<<16 | y[3]<<24;\n\tyy[1] = y[4] | y[5]<<8 | y[6]<<16 | y[7]<<24;\n}\n\nstatic int\npushqword(lua_State *L, uint32_t result[2]) {\n\tuint8_t tmp[8];\n\ttmp[0] = result[0] & 0xff;\n\ttmp[1] = (result[0] >> 8 )& 0xff;\n\ttmp[2] = (result[0] >> 16 )& 0xff;\n\ttmp[3] = (result[0] >> 24 )& 0xff;\n\ttmp[4] = result[1] & 0xff;\n\ttmp[5] = (result[1] >> 8 )& 0xff;\n\ttmp[6] = (result[1] >> 16 )& 0xff;\n\ttmp[7] = (result[1] >> 24 )& 0xff;\n\n\tlua_pushlstring(L, (const char *)tmp, 8);\n\treturn 1;\n}\n\nstatic int\nlhmac64(lua_State *L) {\n\tuint32_t x[2], y[2];\n\tread64(L, x, y);\n\tuint32_t result[2];\n\thmac(x,y,result);\n\treturn pushqword(L, result);\n}\n\n/*\n  h1 = crypt.hmac64_md5(a,b)\n  m = md5.sum((a..b):rep(3))\n  h2 = crypt.xor_str(m:sub(1,8), m:sub(9,16))\n  assert(h1 == h2)\n */\nstatic int\nlhmac64_md5(lua_State *L) {\n\tuint32_t x[2], y[2];\n\tread64(L, x, y);\n\tuint32_t result[2];\n\thmac_md5(x,y,result);\n\treturn pushqword(L, result);\n}\n\n/*\n\t8bytes key\n\tstring text\n */\nstatic int\nlhmac_hash(lua_State *L) {\n\tuint32_t key[2];\n\tsize_t sz = 0;\n\tconst uint8_t *x = (const uint8_t *)luaL_checklstring(L, 1, &sz);\n\tif (sz != 8) {\n\t\tluaL_error(L, \"Invalid uint64 key\");\n\t}\n\tkey[0] = x[0] | x[1]<<8 | x[2]<<16 | x[3]<<24;\n\tkey[1] = x[4] | x[5]<<8 | x[6]<<16 | x[7]<<24;\n\tconst char * text = luaL_checklstring(L, 2, &sz);\n\tuint8_t h[8];\n\tHash(text,(int)sz,h);\n\tuint32_t htext[2];\n\thtext[0] = h[0] | h[1]<<8 | h[2]<<16 | h[3]<<24;\n\thtext[1] = h[4] | h[5]<<8 | h[6]<<16 | h[7]<<24;\n\tuint32_t result[2];\n\thmac(htext,key,result);\n\treturn pushqword(L, result);\n}\n\n// powmodp64 for DH-key exchange\n\n// The biggest 64bit prime\n#define P 0xffffffffffffffc5ull\n\nstatic inline uint64_t\nmul_mod_p(uint64_t a, uint64_t b) {\n\tuint64_t m = 0;\n\twhile(b) {\n\t\tif(b&1) {\n\t\t\tuint64_t t = P-a;\n\t\t\tif ( m >= t) {\n\t\t\t\tm -= t;\n\t\t\t} else {\n\t\t\t\tm += a;\n\t\t\t}\n\t\t}\n\t\tif (a >= P - a) {\n\t\t\ta = a * 2 - P;\n\t\t} else {\n\t\t\ta = a * 2;\n\t\t}\n\t\tb>>=1;\n\t}\n\treturn m;\n}\n\nstatic inline uint64_t\npow_mod_p(uint64_t a, uint64_t b) {\n\tif (b==1) {\n\t\treturn a;\n\t}\n\tuint64_t t = pow_mod_p(a, b>>1);\n\tt = mul_mod_p(t,t);\n\tif (b % 2) {\n\t\tt = mul_mod_p(t, a);\n\t}\n\treturn t;\n}\n\n// calc a^b % p\nstatic uint64_t\npowmodp(uint64_t a, uint64_t b) {\n\tif (a > P)\n\t\ta%=P;\n\treturn pow_mod_p(a,b);\n}\n\nstatic void\npush64(lua_State *L, uint64_t r) {\n\tuint8_t tmp[8];\n\ttmp[0] = r & 0xff;\n\ttmp[1] = (r >> 8 )& 0xff;\n\ttmp[2] = (r >> 16 )& 0xff;\n\ttmp[3] = (r >> 24 )& 0xff;\n\ttmp[4] = (r >> 32 )& 0xff;\n\ttmp[5] = (r >> 40 )& 0xff;\n\ttmp[6] = (r >> 48 )& 0xff;\n\ttmp[7] = (r >> 56 )& 0xff;\n\n\tlua_pushlstring(L, (const char *)tmp, 8);\n}\n\nstatic int\nldhsecret(lua_State *L) {\n\tuint32_t x[2], y[2];\n\tread64(L, x, y);\n\tuint64_t xx = (uint64_t)x[0] | (uint64_t)x[1]<<32;\n\tuint64_t yy = (uint64_t)y[0] | (uint64_t)y[1]<<32;\n\tif (xx == 0 || yy == 0)\n\t\treturn luaL_error(L, \"Can't be 0\");\n\tuint64_t r = powmodp(xx, yy);\n\n\tpush64(L, r);\n\n\treturn 1;\n}\n\n#define G 5\n\nstatic int\nldhexchange(lua_State *L) {\n\tsize_t sz = 0;\n\tconst uint8_t *x = (const uint8_t *)luaL_checklstring(L, 1, &sz);\n\tif (sz != 8) {\n\t\tluaL_error(L, \"Invalid dh uint64 key\");\n\t}\n\tuint32_t xx[2];\n\txx[0] = x[0] | x[1]<<8 | x[2]<<16 | x[3]<<24;\n\txx[1] = x[4] | x[5]<<8 | x[6]<<16 | x[7]<<24;\n\n\tuint64_t x64 = (uint64_t)xx[0] | (uint64_t)xx[1]<<32;\n\tif (x64 == 0)\n\t\treturn luaL_error(L, \"Can't be 0\");\n\n\tuint64_t r = powmodp(G,\tx64);\n\tpush64(L, r);\n\treturn 1;\n}\n\n// base64\n\nstatic int\nlb64encode(lua_State *L) {\n\tstatic const char* encoding = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\tsize_t sz = 0;\n\tconst uint8_t * text = (const uint8_t *)luaL_checklstring(L, 1, &sz);\n\tint encode_sz = (sz + 2)/3*4;\n\tchar tmp[SMALL_CHUNK];\n\tchar *buffer = tmp;\n\tif (encode_sz > SMALL_CHUNK) {\n\t\tbuffer = (char*)lua_newuserdatauv(L, encode_sz, 0);\n\t}\n\tint i,j;\n\tj=0;\n\tfor (i=0;i<(int)sz-2;i+=3) {\n\t\tuint32_t v = text[i] << 16 | text[i+1] << 8 | text[i+2];\n\t\tbuffer[j] = encoding[v >> 18];\n\t\tbuffer[j+1] = encoding[(v >> 12) & 0x3f];\n\t\tbuffer[j+2] = encoding[(v >> 6) & 0x3f];\n\t\tbuffer[j+3] = encoding[(v) & 0x3f];\n\t\tj+=4;\n\t}\n\tint padding = sz-i;\n\tuint32_t v;\n\tswitch(padding) {\n\tcase 1 :\n\t\tv = text[i];\n\t\tbuffer[j] = encoding[v >> 2];\n\t\tbuffer[j+1] = encoding[(v & 3) << 4];\n\t\tbuffer[j+2] = '=';\n\t\tbuffer[j+3] = '=';\n\t\tbreak;\n\tcase 2 :\n\t\tv = text[i] << 8 | text[i+1];\n\t\tbuffer[j] = encoding[v >> 10];\n\t\tbuffer[j+1] = encoding[(v >> 4) & 0x3f];\n\t\tbuffer[j+2] = encoding[(v & 0xf) << 2];\n\t\tbuffer[j+3] = '=';\n\t\tbreak;\n\t}\n\tlua_pushlstring(L, buffer, encode_sz);\n\treturn 1;\n}\n\nstatic inline int\nb64index(uint8_t c) {\n\tstatic const int decoding[] = {62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-2,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51};\n\tint decoding_size = sizeof(decoding)/sizeof(decoding[0]);\n\tif (c<43) {\n\t\treturn -1;\n\t}\n\tc -= 43;\n\tif (c>=decoding_size)\n\t\treturn -1;\n\treturn decoding[c];\n}\n\nstatic int\nlb64decode(lua_State *L) {\n\tsize_t sz = 0;\n\tconst uint8_t * text = (const uint8_t *)luaL_checklstring(L, 1, &sz);\n\tint decode_sz = (sz+3)/4*3;\n\tchar tmp[SMALL_CHUNK];\n\tchar *buffer = tmp;\n\tif (decode_sz > SMALL_CHUNK) {\n\t\tbuffer = (char*)lua_newuserdatauv(L, decode_sz, 0);\n\t}\n\tint i,j;\n\tint output = 0;\n\tfor (i=0;i<sz;) {\n\t\tint padding = 0;\n\t\tint c[4];\n\t\tfor (j=0;j<4;) {\n\t\t\tif (i>=sz && 4>j){\n\t\t\t\t/*To improve compatibility, there may not be enough equal signs */ \n\t\t\t\tc[j] = -2;   \n\t\t\t}else{\n\t\t\t\tc[j] = b64index(text[i]);\n\t\t\t}\n\t\t\tif (c[j] == -1) {\n\t\t\t\t++i;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (c[j] == -2) {\n\t\t\t\t++padding;\n\t\t\t}\n\t\t\t++i;\n\t\t\t++j;\n\t\t}\n\t\tuint32_t v;\n\t\tswitch (padding) {\n\t\tcase 0:\n\t\t\tv = (unsigned)c[0] << 18 | c[1] << 12 | c[2] << 6 | c[3];\n\t\t\tbuffer[output] = v >> 16;\n\t\t\tbuffer[output+1] = (v >> 8) & 0xff;\n\t\t\tbuffer[output+2] = v & 0xff;\n\t\t\toutput += 3;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tif (c[3] != -2 || (c[2] & 3)!=0) {\n\t\t\t\treturn luaL_error(L, \"Invalid base64 text\");\n\t\t\t}\n\t\t\tv = (unsigned)c[0] << 10 | c[1] << 4 | c[2] >> 2 ;\n\t\t\tbuffer[output] = v >> 8;\n\t\t\tbuffer[output+1] = v & 0xff;\n\t\t\toutput += 2;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tif (c[3] != -2 || c[2] != -2 || (c[1] & 0xf) !=0)  {\n\t\t\t\treturn luaL_error(L, \"Invalid base64 text\");\n\t\t\t}\n\t\t\tv = (unsigned)c[0] << 2 | c[1] >> 4;\n\t\t\tbuffer[output] = v;\n\t\t\t++ output;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn luaL_error(L, \"Invalid base64 text\");\n\t\t}\n\t}\n\tlua_pushlstring(L, buffer, output);\n\treturn 1;\n}\n\nstatic int\nlxor_str(lua_State *L) {\n\tsize_t len1,len2;\n\tconst char *s1 = luaL_checklstring(L,1,&len1);\n\tconst char *s2 = luaL_checklstring(L,2,&len2);\n\tif (len2 == 0) {\n\t\treturn luaL_error(L, \"Can't xor empty string\");\n\t}\n\tluaL_Buffer b;\n\tchar * buffer = luaL_buffinitsize(L, &b, len1);\n\tint i;\n\tfor (i=0;i<len1;i++) {\n\t\tbuffer[i] = s1[i] ^ s2[i % len2];\n\t}\n\tluaL_addsize(&b, len1);\n\tluaL_pushresult(&b);\n\treturn 1;\n}\n\n// defined in lsha1.c\nint lsha1(lua_State *L);\nint lhmac_sha1(lua_State *L);\n\n\nLUAMOD_API int\nluaopen_skynet_crypt(lua_State *L) {\n\tluaL_checkversion(L);\n\tstatic int init = 0;\n\tif (!init) {\n\t\t// Don't need call srandom more than once.\n\t\tinit = 1 ;\n\t\tsrandom((random() << 8) ^ (time(NULL) << 16) ^ getpid());\n\t}\n\tluaL_Reg l[] = {\n\t\t{ \"hashkey\", lhashkey },\n\t\t{ \"randomkey\", lrandomkey },\n\t\t{ \"desencode\", ldesencode },\n\t\t{ \"desdecode\", ldesdecode },\n\t\t{ \"hexencode\", ltohex },\n\t\t{ \"hexdecode\", lfromhex },\n\t\t{ \"hmac64\", lhmac64 },\n\t\t{ \"hmac64_md5\", lhmac64_md5 },\n\t\t{ \"dhexchange\", ldhexchange },\n\t\t{ \"dhsecret\", ldhsecret },\n\t\t{ \"base64encode\", lb64encode },\n\t\t{ \"base64decode\", lb64decode },\n\t\t{ \"sha1\", lsha1 },\n\t\t{ \"hmac_sha1\", lhmac_sha1 },\n\t\t{ \"hmac_hash\", lhmac_hash },\n\t\t{ \"xor_str\", lxor_str },\n\t\t{ \"padding\", NULL },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_newlib(L,l);\n\n\tpadding_mode_table(L);\n\tlua_setfield(L, -2, \"padding\");\n\n\treturn 1;\n}\n\nLUAMOD_API int\nluaopen_client_crypt(lua_State *L) {\n\treturn luaopen_skynet_crypt(L);\n}\n"
  },
  {
    "path": "lualib-src/lua-datasheet.c",
    "content": "#include <lua.h>\n#include <lauxlib.h>\n#include <stdint.h>\n\n#define NODECACHE \"_ctable\"\n#define PROXYCACHE \"_proxy\"\n#define TABLES \"_ctables\"\n\n#define VALUE_NIL 0\n#define VALUE_INTEGER 1\n#define VALUE_REAL 2\n#define VALUE_BOOLEAN 3\n#define VALUE_TABLE 4\n#define VALUE_STRING 5\n#define VALUE_INVALID 6\n\n#define INVALID_OFFSET 0xffffffff\n\nstruct proxy {\n\tconst char * data;\n\tint index;\n};\n\nstruct document {\n\tuint32_t strtbl;\n\tuint32_t n;\n\tuint32_t index[1];\n\t// table[n]\n\t// strings\n};\n\nstruct table {\n\tuint32_t array;\n\tuint32_t dict;\n\tuint8_t type[1];\n\t// value[array]\n\t// kvpair[dict]\n};\n\nstatic inline const struct table *\ngettable(const struct document *doc, int index) {\n\tif (doc->index[index] == INVALID_OFFSET) {\n\t\treturn NULL;\n\t}\n\treturn (const struct table *)((const char *)doc + sizeof(uint32_t) + sizeof(uint32_t) + doc->n * sizeof(uint32_t) + doc->index[index]);\n}\n\nstatic void\ncreate_proxy(lua_State *L, const void *data, int index) {\n\tconst struct table * t = gettable(data, index);\n\tif (t == NULL) {\n\t\tluaL_error(L, \"Invalid index %d\", index);\n\t}\n\tlua_getfield(L, LUA_REGISTRYINDEX, NODECACHE);\n\tif (lua_rawgetp(L, -1, t) == LUA_TTABLE) {\n\t\tlua_replace(L, -2);\n\t\treturn;\n\t}\n\tlua_pop(L, 1);\n\tlua_newtable(L);\n\tlua_pushvalue(L, lua_upvalueindex(1));\n\tlua_setmetatable(L, -2);\n\tlua_pushvalue(L, -1);\n\t// NODECACHE, table, table\n\tlua_rawsetp(L, -3, t);\n\t// NODECACHE, table\n\tlua_getfield(L, LUA_REGISTRYINDEX, PROXYCACHE);\n\t// NODECACHE, table, PROXYCACHE\n\tlua_pushvalue(L, -2);\n\t// NODECACHE, table, PROXYCACHE, table\n\tstruct proxy * p = lua_newuserdatauv(L, sizeof(struct proxy), 0);\n\t// NODECACHE, table, PROXYCACHE, table, proxy\n\tp->data = data;\n\tp->index = index;\n\tlua_rawset(L, -3);\n\t// NODECACHE, table, PROXYCACHE\n\tlua_pop(L, 1);\n\t// NODECACHE, table\n\tlua_replace(L, -2);\n\t// table\n}\n\nstatic void\nclear_table(lua_State *L) {\n\tint t = lua_gettop(L);\t// clear top table\n\tif (lua_type(L, t) != LUA_TTABLE) {\n\t\tluaL_error(L, \"Invalid cache\");\n\t}\n\tlua_pushnil(L);\n\twhile (lua_next(L, t) != 0) {\n\t\t// key value\n\t\tlua_pop(L, 1);\n\t\tlua_pushvalue(L, -1);\n\t\tlua_pushnil(L);\n\t\t// key key nil\n\t\tlua_rawset(L, t);\n\t\t// key\n\t}\n}\n\nstatic void\nupdate_cache(lua_State *L, const void *data, const void * newdata) {\n\tlua_getfield(L, LUA_REGISTRYINDEX, NODECACHE);\n\tint t = lua_gettop(L);\n\tlua_getfield(L, LUA_REGISTRYINDEX, PROXYCACHE);\n\tint pt = t + 1;\n\tlua_newtable(L);\t// temp table\n\tint nt = pt + 1;\n\tlua_pushnil(L);\n\twhile (lua_next(L, t) != 0) {\n\t\t// pointer (-2) -> table (-1)\n\t\tlua_pushvalue(L, -1);\n\t\tif (lua_rawget(L, pt) == LUA_TUSERDATA) {\n\t\t\t// pointer, table, proxy\n\t\t\tstruct proxy * p = lua_touserdata(L, -1);\n\t\t\tif (p->data == data) {\n\t\t\t\t// update to newdata\n\t\t\t\tp->data = newdata;\n\t\t\t\tconst struct table * newt = gettable(newdata, p->index);\n\t\t\t\tlua_pop(L, 1);\n\t\t\t\t// pointer, table\n\t\t\t\tclear_table(L);\n\t\t\t\tlua_pushvalue(L, lua_upvalueindex(1));\n\t\t\t\t// pointer, table, meta\n\t\t\t\tlua_setmetatable(L, -2);\n\t\t\t\t// pointer, table\n\t\t\t\tif (newt) {\n\t\t\t\t\tlua_rawsetp(L, nt, newt);\n\t\t\t\t} else {\n\t\t\t\t\tlua_pop(L, 1);\n\t\t\t\t}\n\t\t\t\t// pointer\n\t\t\t\tlua_pushvalue(L, -1);\n\t\t\t\tlua_pushnil(L);\n\t\t\t\tlua_rawset(L, t);\n\t\t\t} else {\n\t\t\t\tlua_pop(L, 2);\n\t\t\t}\n\t\t} else {\n\t\t\tlua_pop(L, 2);\n\t\t\t// pointer\n\t\t}\n\t}\n\t// copy nt to t\n\tlua_pushnil(L);\n\twhile (lua_next(L, nt) != 0) {\n\t\tlua_pushvalue(L, -2);\n\t\tlua_insert(L, -2);\n\t\t// key key value\n\t\tlua_rawset(L, t);\n\t}\n\t// NODECACHE PROXYCACHE TEMP\n\tlua_pop(L, 3);\n}\n\nstatic int\nlupdate(lua_State *L) {\n\tlua_getfield(L, LUA_REGISTRYINDEX, PROXYCACHE);\n\tlua_pushvalue(L, 1);\n\t// PROXYCACHE, table\n\tif (lua_rawget(L, -2) != LUA_TUSERDATA) {\n\t\tluaL_error(L, \"Invalid proxy table %p\", lua_topointer(L, 1));\n\t}\n\tstruct proxy * p = lua_touserdata(L, -1);\n\tluaL_checktype(L, 2, LUA_TLIGHTUSERDATA);\n\tconst char * newdata = lua_touserdata(L, 2);\n\tupdate_cache(L, p->data, newdata);\n\treturn 1;\n}\n\nstatic inline uint32_t\ngetuint32(const void *v) {\n\tunion {\n\t\tuint32_t d;\n\t\tuint8_t t[4];\n\t} test = { 1 };\n\tif (test.t[0] == 0) {\n\t\t// big endian\n\t\ttest.d = *(const uint32_t *)v;\n\t\treturn test.t[0] | test.t[1] << 4 | test.t[2] << 8 | test.t[3] << 12;\n\t} else {\n\t\treturn *(const uint32_t *)v;\n\t}\n}\n\nstatic inline float\ngetfloat(const void *v) {\n\tunion {\n\t\tuint32_t d;\n\t\tfloat f;\n\t\tuint8_t t[4];\n\t} test = { 1 };\n\tif (test.t[0] == 0) {\n\t\t// big endian\n\t\ttest.d = *(const uint32_t *)v;\n\t\ttest.d = test.t[0] | test.t[1] << 4 | test.t[2] << 8 | test.t[3] << 12;\n\t\treturn test.f;\n\t} else {\n\t\treturn *(const float *)v;\n\t}\n}\n\nstatic void\npushvalue(lua_State *L, const void *v, int type, const struct document * doc) {\n\tswitch (type) {\n\tcase VALUE_NIL:\n\t\tlua_pushnil(L);\n\t\tbreak;\n\tcase VALUE_INTEGER:\n\t\tlua_pushinteger(L, (int32_t)getuint32(v));\n\t\tbreak;\n\tcase VALUE_REAL:\n\t\tlua_pushnumber(L, getfloat(v));\n\t\tbreak;\n\tcase VALUE_BOOLEAN:\n\t\tlua_pushboolean(L, getuint32(v));\n\t\tbreak;\n\tcase VALUE_TABLE:\n\t\tcreate_proxy(L, doc, getuint32(v));\n\t\tbreak;\n\tcase VALUE_STRING:\n\t\tlua_pushstring(L,  (const char *)doc + doc->strtbl + getuint32(v));\n\t\tbreak;\n\tdefault:\n\t\tluaL_error(L, \"Invalid type %d at %p\", type, v);\n\t}\n}\n\nstatic void\ncopytable(lua_State *L, int tbl, struct proxy *p) {\n\tconst struct document * doc = (const struct document *)p->data; \n\tif (p->index < 0 || p->index >= doc->n) {\n\t\tluaL_error(L, \"Invalid proxy (index = %d, total = %d)\", p->index, (int)doc->n);\n\t}\n\tconst struct table * t = gettable(doc, p->index);\n\tif (t == NULL) {\n\t\tluaL_error(L, \"Invalid proxy (index = %d)\", p->index);\n\t}\n\tconst uint32_t * v = (const uint32_t *)((const char *)t + sizeof(uint32_t) + sizeof(uint32_t) + ((t->array + t->dict + 3) & ~3));\n\tint i;\n\tfor (i=0;i<t->array;i++) {\n\t\tpushvalue(L, v++, t->type[i], doc);\n\t\tlua_rawseti(L, tbl, i+1);\n\t}\n\tfor (i=0;i<t->dict;i++) {\n\t\tpushvalue(L, v++, VALUE_STRING, doc);\n\t\tpushvalue(L, v++, t->type[t->array+i], doc);\n\t\tlua_rawset(L, tbl);\n\t}\n}\n\nstatic int\nlnew(lua_State *L) {\n\tluaL_checktype(L, 1, LUA_TLIGHTUSERDATA);\n\tconst char * data = lua_touserdata(L, 1);\n\t// hold ref to data\n\tlua_getfield(L, LUA_REGISTRYINDEX, TABLES);\n\tlua_pushvalue(L, 1);\n\tlua_rawsetp(L, -2, data);\n\n\tcreate_proxy(L, data, 0);\n\treturn 1;\n}\n\nstatic void\ncopyfromdata(lua_State *L) {\n\tlua_getfield(L, LUA_REGISTRYINDEX, PROXYCACHE);\n\tlua_pushvalue(L, 1);\n\t// PROXYCACHE, table\n\tif (lua_rawget(L, -2) != LUA_TUSERDATA) {\n\t\tluaL_error(L, \"Invalid proxy table %p\", lua_topointer(L, 1));\n\t}\n\tstruct proxy * p = lua_touserdata(L, -1);\n\tlua_pop(L, 2);\n\tcopytable(L, 1, p);\n\tlua_pushnil(L);\n\tlua_setmetatable(L, 1);\t// remove metatable\n}\n\nstatic int\nlindex(lua_State *L) {\n\tcopyfromdata(L);\n\tlua_rawget(L, 1);\n\treturn 1;\n}\n\nstatic int\nlnext(lua_State *L) {\n\tluaL_checktype(L, 1, LUA_TTABLE);\n\tlua_settop(L, 2);  /* create a 2nd argument if there isn't one */\n\tif (lua_next(L, 1))\n\t\treturn 2;\n\telse {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n}\n\nstatic int\nlpairs(lua_State *L) {\n\tcopyfromdata(L);\n\tlua_pushcfunction(L, lnext);\n\tlua_pushvalue(L, 1);\n\tlua_pushnil(L);\n\treturn 3;\n}\n\nstatic int\nllen(lua_State *L) {\n\tcopyfromdata(L);\n\tlua_pushinteger(L, lua_rawlen(L, 1));\n\treturn 1;\n}\n\nstatic void\nnew_weak_table(lua_State *L, const char *mode) {\n\tlua_newtable(L);\t// NODECACHE { pointer:table }\n\n\tlua_createtable(L, 0, 1);\t// weak meta table\n\tlua_pushstring(L, mode);\n\tlua_setfield(L, -2, \"__mode\");\n\n\tlua_setmetatable(L, -2);\t// make NODECACHE weak\n}\n\nstatic void\ngen_metatable(lua_State *L) {\n\tnew_weak_table(L, \"kv\");\t// NODECACHE { pointer:table }\n\tlua_setfield(L, LUA_REGISTRYINDEX, NODECACHE);\n\n\tnew_weak_table(L, \"k\");\t// PROXYCACHE { table:userdata }\n\tlua_setfield(L, LUA_REGISTRYINDEX, PROXYCACHE);\n\n\tlua_newtable(L);\n\tlua_setfield(L, LUA_REGISTRYINDEX, TABLES);\n\n\tlua_createtable(L, 0, 1);\t// mod table\n\n\tlua_createtable(L, 0, 2);\t// metatable\n\tluaL_Reg l[] = {\n\t\t{ \"__index\", lindex },\n\t\t{ \"__pairs\", lpairs },\n\t\t{ \"__len\", llen },\n\t\t{ NULL, NULL },\n\t};\n\tlua_pushvalue(L, -1);\n\tluaL_setfuncs(L, l, 1);\n}\n\nstatic int\nlstringpointer(lua_State *L) {\n\tconst char * str = luaL_checkstring(L, 1);\n\tlua_pushlightuserdata(L, (void *)str);\n\treturn 1;\n}\n\nLUAMOD_API int\nluaopen_skynet_datasheet_core(lua_State *L) {\n\tluaL_checkversion(L);\n\tluaL_Reg l[] = {\n\t\t{ \"new\", lnew },\n\t\t{ \"update\", lupdate },\n\t\t{ NULL, NULL },\n\t};\n\n\tluaL_newlibtable(L,l);\n\tgen_metatable(L);\n\tluaL_setfuncs(L, l, 1);\n\tlua_pushcfunction(L, lstringpointer);\n\tlua_setfield(L, -2, \"stringpointer\");\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-debugchannel.c",
    "content": "#define LUA_LIB\n\n// only for debug use\n#include <lua.h>\n#include <lauxlib.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"spinlock.h\"\n\n#define METANAME \"debugchannel\"\n\nstruct command {\n\tstruct command * next;\n\tsize_t sz;\n};\n\nstruct channel {\n\tstruct spinlock lock;\n\tint ref;\n\tstruct command * head;\n\tstruct command * tail;\n};\n\nstatic struct channel *\nchannel_new() {\n\tstruct channel * c = malloc(sizeof(*c));\n\tmemset(c, 0 , sizeof(*c));\n\tc->ref = 1;\n\tSPIN_INIT(c)\n\n\treturn c;\n}\n\nstatic struct channel *\nchannel_connect(struct channel *c) {\n\tstruct channel * ret = NULL;\n\tSPIN_LOCK(c)\n\tif (c->ref == 1) {\n\t\t++c->ref;\n\t\tret = c;\n\t}\n\tSPIN_UNLOCK(c)\n\treturn ret;\n}\n\nstatic struct channel *\nchannel_release(struct channel *c) {\n\tSPIN_LOCK(c)\n\t--c->ref;\n\tif (c->ref > 0) {\n\t\tSPIN_UNLOCK(c)\n\t\treturn c;\n\t}\n\t// never unlock while reference is 0\n\tstruct command * p = c->head;\n\tc->head = NULL;\n\tc->tail = NULL;\n\twhile(p) {\n\t\tstruct command *next = p->next;\n\t\tfree(p);\n\t\tp = next;\n\t}\n\tSPIN_UNLOCK(c)\n\tSPIN_DESTROY(c)\n\tfree(c);\n\treturn NULL;\n}\n\n// call free after channel_read\nstatic struct command *\nchannel_read(struct channel *c, double timeout) {\n\tstruct command * ret = NULL;\n\tSPIN_LOCK(c)\n\tif (c->head == NULL) {\n\t\tSPIN_UNLOCK(c)\n\t\tint ti = (int)(timeout * 100000);\n\t\tusleep(ti);\n\t\treturn NULL;\n\t}\n\tret = c->head;\n\tc->head = ret->next;\n\tif (c->head == NULL) {\n\t\tc->tail = NULL;\n\t}\n\tSPIN_UNLOCK(c)\n\t\n\treturn ret;\n}\n\nstatic void\nchannel_write(struct channel *c, const char * s, size_t sz) {\n\tstruct command * cmd = malloc(sizeof(*cmd)+ sz);\n\tcmd->sz = sz;\n\tcmd->next = NULL;\n\tmemcpy(cmd+1, s, sz);\n\tSPIN_LOCK(c)\n\tif (c->tail == NULL) {\n\t\tc->head = c->tail = cmd;\n\t} else {\n\t\tc->tail->next = cmd;\n\t\tc->tail = cmd;\n\t}\n\tSPIN_UNLOCK(c)\n}\n\nstruct channel_box {\n\tstruct channel *c;\n};\n\nstatic int\nlread(lua_State *L) {\n\tstruct channel_box *cb = luaL_checkudata(L,1, METANAME);\n\tdouble ti = luaL_optnumber(L, 2, 0);\n\tstruct command * c = channel_read(cb->c, ti);\n\tif (c == NULL)\n\t\treturn 0;\n\tlua_pushlstring(L, (const char *)(c+1), c->sz);\n\tfree(c);\n\treturn 1;\n}\n\nstatic int\nlwrite(lua_State *L) {\n\tstruct channel_box *cb = luaL_checkudata(L,1, METANAME);\n\tsize_t sz;\n\tconst char * str = luaL_checklstring(L, 2, &sz);\n\tchannel_write(cb->c, str, sz);\n\treturn 0;\n}\n\nstatic int\nlrelease(lua_State *L) {\n\tstruct channel_box *cb = lua_touserdata(L, 1);\n\tif (cb) {\n\t\tif (channel_release(cb->c) == NULL) {\n\t\t\tcb->c = NULL;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nstatic struct channel *\nnew_channel(lua_State *L, struct channel *c) {\n\tif (c == NULL) {\n\t\tc = channel_new();\n\t} else {\n\t\tc = channel_connect(c);\n\t}\n\tif (c == NULL) {\n\t\tluaL_error(L, \"new channel failed\");\n\t\t// never go here\n\t}\n\tstruct channel_box * cb = lua_newuserdatauv(L, sizeof(*cb), 0);\n\tcb->c = c;\n\tif (luaL_newmetatable(L, METANAME)) {\n\t\tluaL_Reg l[]={\n\t\t\t{ \"read\", lread },\n\t\t\t{ \"write\", lwrite },\n\t\t\t{ NULL, NULL },\n\t\t};\n\t\tluaL_newlib(L,l);\n\t\tlua_setfield(L, -2, \"__index\");\n\t\tlua_pushcfunction(L, lrelease);\n\t\tlua_setfield(L, -2, \"__gc\");\n\t}\n\tlua_setmetatable(L, -2);\n\treturn c;\n}\n\nstatic int\nlcreate(lua_State *L) {\n\tstruct channel *c = new_channel(L, NULL);\n\tlua_pushlightuserdata(L, c);\n\treturn 2;\n}\n\nstatic int\nlconnect(lua_State *L) {\n\tstruct channel *c = lua_touserdata(L, 1);\n\tif (c == NULL)\n\t\treturn luaL_error(L, \"Invalid channel pointer\");\n\tnew_channel(L, c);\n\n\treturn 1;\n}\n\nstatic const int HOOKKEY = 0;\n\n/*\n** Auxiliary function used by several library functions: check for\n** an optional thread as function's first argument and set 'arg' with\n** 1 if this argument is present (so that functions can skip it to\n** access their other arguments)\n*/\nstatic lua_State *getthread (lua_State *L, int *arg) {\n  if (lua_isthread(L, 1)) {\n    *arg = 1;\n    return lua_tothread(L, 1);\n  }\n  else {\n    *arg = 0;\n    return L;  /* function will operate over current thread */\n  }\n}\n\n/*\n** Call hook function registered at hook table for the current\n** thread (if there is one)\n*/\nstatic void hookf (lua_State *L, lua_Debug *ar) {\n  static const char *const hooknames[] =\n    {\"call\", \"return\", \"line\", \"count\", \"tail call\"};\n  lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);\n  lua_pushthread(L);\n  if (lua_rawget(L, -2) == LUA_TFUNCTION) {  /* is there a hook function? */\n    lua_pushstring(L, hooknames[(int)ar->event]);  /* push event name */\n    if (ar->currentline >= 0)\n      lua_pushinteger(L, ar->currentline);  /* push current line */\n    else lua_pushnil(L);\n    lua_call(L, 2, 1);  /* call hook function */\n\tint yield = lua_toboolean(L, -1);\n\tlua_pop(L,1);\n\tif (yield) {\n\t\tlua_yield(L, 0);\n\t}\n  }\n}\n\n/*\n** Convert a string mask (for 'sethook') into a bit mask\n*/\nstatic int makemask (const char *smask, int count) {\n  int mask = 0;\n  if (strchr(smask, 'c')) mask |= LUA_MASKCALL;\n  if (strchr(smask, 'r')) mask |= LUA_MASKRET;\n  if (strchr(smask, 'l')) mask |= LUA_MASKLINE;\n  if (count > 0) mask |= LUA_MASKCOUNT;\n  return mask;\n}\n\nstatic int db_sethook (lua_State *L) {\n  int arg, mask, count;\n  lua_Hook func;\n  lua_State *L1 = getthread(L, &arg);\n  if (lua_isnoneornil(L, arg+1)) {  /* no hook? */\n    lua_settop(L, arg+1);\n    func = NULL; mask = 0; count = 0;  /* turn off hooks */\n  }\n  else {\n    const char *smask = luaL_checkstring(L, arg+2);\n    luaL_checktype(L, arg+1, LUA_TFUNCTION);\n    count = (int)luaL_optinteger(L, arg + 3, 0);\n    func = hookf; mask = makemask(smask, count);\n  }\n  if (lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY) == LUA_TNIL) {\n    lua_createtable(L, 0, 2);  /* create a hook table */\n    lua_pushvalue(L, -1);\n    lua_rawsetp(L, LUA_REGISTRYINDEX, &HOOKKEY);  /* set it in position */\n    lua_pushstring(L, \"k\");\n    lua_setfield(L, -2, \"__mode\");  /** hooktable.__mode = \"k\" */\n    lua_pushvalue(L, -1);\n    lua_setmetatable(L, -2);  /* setmetatable(hooktable) = hooktable */\n  }\n  lua_pushthread(L1); lua_xmove(L1, L, 1);  /* key (thread) */\n  lua_pushvalue(L, arg + 1);  /* value (hook function) */\n  lua_rawset(L, -3);  /* hooktable[L1] = new Lua hook */\n  lua_sethook(L1, func, mask, count);\n  return 0;\n}\n\nLUAMOD_API int\nluaopen_skynet_debugchannel(lua_State *L) {\n\tluaL_Reg l[] = {\n\t\t{ \"create\", lcreate },\t// for write\n\t\t{ \"connect\", lconnect },\t// for read\n\t\t{ \"release\", lrelease },\n\t\t{ \"sethook\", db_sethook },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_checkversion(L);\n\tluaL_newlib(L,l);\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-memory.c",
    "content": "#define LUA_LIB\n\n#include <lua.h>\n#include <lauxlib.h>\n\n#include \"malloc_hook.h\"\n\nstatic int\nltotal(lua_State *L) {\n\tsize_t t = malloc_used_memory();\n\tlua_pushinteger(L, (lua_Integer)t);\n\n\treturn 1;\n}\n\nstatic int\nlblock(lua_State *L) {\n\tsize_t t = malloc_memory_block();\n\tlua_pushinteger(L, (lua_Integer)t);\n\n\treturn 1;\n}\n\nstatic int\nldumpinfo(lua_State *L) {\n\tconst char *opts = NULL;\n\tif (lua_isstring(L, 1)) {\n\t\topts = luaL_checkstring(L,1);\n\t}\n\tmemory_info_dump(opts);\n\n\treturn 0;\n}\n\nstatic int\nljestat(lua_State *L) {\n\tstatic const char* names[] = {\n\t\t\"stats.allocated\",\n\t\t\"stats.resident\",\n\t\t\"stats.retained\",\n\t\t\"stats.mapped\",\n\t\t\"stats.active\" };\n\tstatic size_t flush = 1;\n\tmallctl_int64(\"epoch\", &flush); // refresh je.stats.cache\n\tlua_newtable(L);\n\tint i;\n\tfor (i = 0; i < (sizeof(names)/sizeof(names[0])); i++) {\n\t\tlua_pushstring(L, names[i]);\n\t\tlua_pushinteger(L,  (lua_Integer) mallctl_int64(names[i], NULL));\n\t\tlua_settable(L, -3);\n\t}\n\treturn 1;\n}\n\nstatic int\nlmallctl(lua_State *L) {\n\tconst char *name = luaL_checkstring(L,1);\n\tlua_pushinteger(L, (lua_Integer) mallctl_int64(name, NULL));\n\treturn 1;\n}\n\nstatic int\nldump(lua_State *L) {\n\tdump_c_mem();\n\n\treturn 0;\n}\n\nstatic int\nlcurrent(lua_State *L) {\n\tlua_pushinteger(L, malloc_current_memory());\n\treturn 1;\n}\n\nstatic int\nldumpheap(lua_State *L) {\n\tmallctl_cmd(\"prof.dump\");\n\treturn 0;\n}\n\nstatic int\nlprofactive(lua_State *L) {\n\tbool *pval, active;\n\tif (lua_isnone(L, 1)) {\n\t\tpval = NULL;\n\t} else {\n\t\tactive = lua_toboolean(L, 1) ? true : false;\n\t\tpval = &active;\n\t}\n\tbool ret = mallctl_bool(\"prof.active\", pval);\n\tlua_pushboolean(L, ret);\n\treturn 1;\n}\n\nLUAMOD_API int\nluaopen_skynet_memory(lua_State *L) {\n\tluaL_checkversion(L);\n\n\tluaL_Reg l[] = {\n\t\t{ \"total\", ltotal },\n\t\t{ \"block\", lblock },\n\t\t{ \"dumpinfo\", ldumpinfo },\n\t\t{ \"jestat\", ljestat },\n\t\t{ \"mallctl\", lmallctl },\n\t\t{ \"dump\", ldump },\n\t\t{ \"info\", dump_mem_lua },\n\t\t{ \"current\", lcurrent },\n\t\t{ \"dumpheap\", ldumpheap },\n\t\t{ \"profactive\", lprofactive },\n\t\t{ NULL, NULL },\n\t};\n\n\tluaL_newlib(L,l);\n\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-mongo.c",
    "content": "#define LUA_LIB\n\n#include \"skynet_malloc.h\"\n\n#include <lua.h>\n#include <lauxlib.h>\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define OP_COMPRESSED 2012\n#define OP_MSG 2013\n\ntypedef enum {\n\tMSG_CHECKSUM_PRESENT = 1 << 0,\n\tMSG_MORE_TO_COME = 1 << 1,\n\tMSG_EXHAUST_ALLOWED = 1 << 16,\n} msg_flags_t;\n\n\n#define DEFAULT_CAP 128\nstruct connection {\n\tint sock;\n\tint id;\n};\n\nstruct response {\n\tint flags;\n\tint32_t cursor_id[2];\n\tint starting_from;\n\tint number;\n};\n\nstruct buffer {\n\tint size;\n\tint cap;\n\tuint8_t * ptr;\n\tuint8_t buffer[DEFAULT_CAP];\n};\n\nstatic inline uint32_t\nlittle_endian(uint32_t v) {\n\tunion {\n\t\tuint32_t v;\n\t\tuint8_t b[4];\n\t} u;\n\tu.v = v;\n\treturn u.b[0] | u.b[1] << 8 | u.b[2] << 16 | u.b[3] << 24;\n}\n\ntypedef void * document;\n\nstatic inline uint32_t\nget_length(document buffer) {\n\tunion {\n\t\tuint32_t v;\n\t\tuint8_t b[4];\n\t} u;\n\tmemcpy(&u.v, buffer, 4);\n\treturn u.b[0] | u.b[1] << 8 | u.b[2] << 16 | u.b[3] << 24;\n}\n\nstatic inline void\nbuffer_destroy(struct buffer *b) {\n\tif (b->ptr != b->buffer) {\n\t\tskynet_free(b->ptr);\n\t}\n}\n\nstatic inline void\nbuffer_create(struct buffer *b) {\n\tb->size = 0;\n\tb->cap = DEFAULT_CAP;\n\tb->ptr = b->buffer;\n}\n\nstatic inline void\nbuffer_reserve(struct buffer *b, int sz) {\n\tif (b->size + sz <= b->cap)\n\t\treturn;\n\tdo {\n\t\tb->cap *= 2;\n\t} while (b->cap <= b->size + sz);\n\n\tif (b->ptr == b->buffer) {\n\t\tb->ptr = (uint8_t*)malloc(b->cap);\n\t\tmemcpy(b->ptr, b->buffer, b->size);\n\t} else {\n\t\tb->ptr = (uint8_t*)realloc(b->ptr, b->cap);\n\t}\n}\n\nstatic inline void\nwrite_int32(struct buffer *b, int32_t v) {\n\tuint32_t uv = (uint32_t)v;\n\tbuffer_reserve(b,4);\n\tb->ptr[b->size++] = uv & 0xff;\n\tb->ptr[b->size++] = (uv >> 8)&0xff;\n\tb->ptr[b->size++] = (uv >> 16)&0xff;\n\tb->ptr[b->size++] = (uv >> 24)&0xff;\n}\n\nstatic inline void\nwrite_int8(struct buffer *b, int8_t v) {\n\tuint8_t uv = (uint8_t)v;\n\tbuffer_reserve(b, 1);\n\tb->ptr[b->size++] = uv;\n}\n\n/*\nstatic inline void\nwrite_bytes(struct buffer *b, const void * buf, int sz) {\n\tbuffer_reserve(b,sz);\n\tmemcpy(b->ptr + b->size, buf, sz);\n\tb->size += sz;\n}\n\nstatic void\nwrite_string(struct buffer *b, const char *key, size_t sz) {\n\tbuffer_reserve(b,sz+1);\n\tmemcpy(b->ptr + b->size, key, sz);\n\tb->ptr[b->size+sz] = '\\0';\n\tb->size+=sz+1;\n}\n*/\n\nstatic inline int\nreserve_length(struct buffer *b) {\n\tint sz = b->size;\n\tbuffer_reserve(b,4);\n\tb->size +=4;\n\treturn sz;\n}\n\nstatic inline void\nwrite_length(struct buffer *b, int32_t v, int off) {\n\tuint32_t uv = (uint32_t)v;\n\tb->ptr[off++] = uv & 0xff;\n\tb->ptr[off++] = (uv >> 8)&0xff;\n\tb->ptr[off++] = (uv >> 16)&0xff;\n\tb->ptr[off++] = (uv >> 24)&0xff;\n}\n\nstruct header_t {\n\t//int32_t message_length; \t// total message size, include this\n\tint32_t request_id;\t\t\t// identifier for this message\n\tint32_t response_to;\t\t// requestID from the original request(used in responses from the database)\n\tint32_t opcode;\t\t\t// message type\n\n\tint32_t flags;\n};\n\n// 1 string data\n// 2 result document table\n// return boolean succ (false -> request id, error document)\n//\tnumber request_id\n//  document first\nstatic int\nunpack_reply(lua_State *L) {\n\tsize_t data_len = 0;\n\tconst char * data = luaL_checklstring(L,1,&data_len);\n\tconst struct header_t* h = (const struct header_t*)data;\n\n\tif (data_len < sizeof(*h)) {\n\t\tlua_pushboolean(L, 0);\n\t\treturn 1;\n\t}\n\n\tint opcode = little_endian(h->opcode);\n\tif (opcode != OP_MSG) {\n\t\treturn luaL_error(L, \"Unsupported opcode:%d\", opcode);\n\t}\n\n\tint id = little_endian(h->response_to);\n\tint flags = little_endian(h->flags);\n\n\tif (flags != 0) {\n\t\tif ((flags & MSG_CHECKSUM_PRESENT) != 0)  {\n\t\t\treturn luaL_error(L, \"Unsupported OP_MSG flag checksumPresent\");\n\t\t}\n\n\t\tif ((flags ^ MSG_MORE_TO_COME) != 0) {\n\t\t\treturn luaL_error(L, \"Unsupported OP_MSG flag:%d\", flags);\n\t\t}\n\t}\n\n\tint sz = (int)data_len - sizeof(*h);\n\n\tconst uint8_t * section = (const uint8_t *)(h+1);\n\n\tuint8_t payload_type = *section;\n\tconst uint8_t * doc = section+1;\n\n\tif (payload_type != 0) {\n\t\treturn luaL_error(L, \"Unsupported OP_MSG payload type: %d\", payload_type);\n\t}\n\n\tint32_t doc_sz = get_length((document)(doc));\n\tif ((sz - 1) != doc_sz) {\n\t\treturn luaL_error(L, \"Unsupported OP_MSG reply: >1 section\");\n\t}\n\n\tlua_pushboolean(L, 1);\n\tlua_pushinteger(L, id);\n\tlua_pushlightuserdata(L, (void *)(doc));\n\treturn 3;\n}\n\n// string 4 bytes length\n// return integer\nstatic int\nreply_length(lua_State *L) {\n\tconst char * rawlen_str = luaL_checkstring(L, 1);\n\tint rawlen = 0;\n\tmemcpy(&rawlen, rawlen_str, sizeof(int));\n\tint length = little_endian(rawlen);\n\tlua_pushinteger(L, length - 4);\n\treturn 1;\n}\n\n// @param 1 request_id int\n// @param 2 flags int\n// @param 3 command bson document\n// @return\nstatic int\nop_msg(lua_State *L) {\n\tint id = luaL_checkinteger(L, 1);\n\tint flags = luaL_checkinteger(L, 2);\n\tdocument cmd = lua_touserdata(L, 3);\n\n\tif (cmd == NULL) {\n\t\treturn luaL_error(L, \"opmsg require cmd document\");\n\t}\n\n\tluaL_Buffer b;\n\tluaL_buffinit(L, &b);\n\n\tstruct buffer buf;\n\tbuffer_create(&buf);\n\t\tint len = reserve_length(&buf);\n\t\twrite_int32(&buf, id);\n\t\twrite_int32(&buf, 0);\n\t\twrite_int32(&buf, OP_MSG);\n\t\twrite_int32(&buf, flags);\n\t\twrite_int8(&buf, 0);\n\n\t\tint32_t cmd_len = get_length(cmd);\n\t\tint total = buf.size + cmd_len;\n\n\t\twrite_length(&buf, total, len);\n\t\tluaL_addlstring(&b, (const char *)buf.ptr, buf.size);\n\tbuffer_destroy(&buf);\n\n\tluaL_addlstring(&b, (const char *)cmd, cmd_len);\n\tluaL_pushresult(&b);\n\treturn 1;\n}\n\n\nLUAMOD_API int\nluaopen_skynet_mongo_driver(lua_State *L) {\n\tluaL_checkversion(L);\n\tluaL_Reg l[] ={\n\t\t{ \"reply\", unpack_reply }, // 接收响应\n\t\t{ \"length\", reply_length },\n\t\t{ \"op_msg\", op_msg},\n\t\t{ NULL, NULL },\n\t};\n\n\tluaL_newlib(L,l);\n\treturn 1;\n}"
  },
  {
    "path": "lualib-src/lua-multicast.c",
    "content": "#define LUA_LIB\n\n#include \"skynet.h\"\n\n#include <lua.h>\n#include <lauxlib.h>\n#include <stdint.h>\n#include <string.h>\n\n#include \"atomic.h\"\n\nstruct mc_package {\n\tATOM_INT reference;\n\tuint32_t size;\n\tvoid *data;\n};\n\nstatic int\npack(lua_State *L, void *data, size_t size) {\n\tstruct mc_package * pack = skynet_malloc(sizeof(struct mc_package));\n\tATOM_INIT(&pack->reference, 0);\n\tpack->size = (uint32_t)size;\n\tpack->data = data;\n\tstruct mc_package ** ret = skynet_malloc(sizeof(*ret));\n\t*ret = pack;\n\tlua_pushlightuserdata(L, ret);\n\tlua_pushinteger(L, sizeof(ret));\n\treturn 2;\n}\n\n/*\n\tlightuserdata\n\tinteger size\n\n\treturn lightuserdata, sizeof(struct mc_package *)\n */\nstatic int\nmc_packlocal(lua_State *L) {\n\tvoid * data = lua_touserdata(L, 1);\n\tsize_t size = (size_t)luaL_checkinteger(L, 2);\n\tif (size != (uint32_t)size) {\n\t\treturn luaL_error(L, \"Size should be 32bit integer\");\n\t}\n\treturn pack(L, data, size);\n}\n\n/*\n\tlightuserdata\n\tinteger size\n\n\treturn lightuserdata, sizeof(struct mc_package *)\n */\nstatic int\nmc_packremote(lua_State *L) {\n\tvoid * data = lua_touserdata(L, 1);\n\tsize_t size = (size_t)luaL_checkinteger(L, 2);\n\tif (size != (uint32_t)size) {\n\t\treturn luaL_error(L, \"Size should be 32bit integer\");\n\t}\n\tvoid * msg = skynet_malloc(size);\n\tmemcpy(msg, data, size);\n\treturn pack(L, msg, size);\n}\n\n/*\n\tlightuserdata struct mc_package **\n\tinteger size (must be sizeof(struct mc_package *)\n\n\treturn package, lightuserdata, size\n */\nstatic int\nmc_unpacklocal(lua_State *L) {\n\tstruct mc_package ** pack = lua_touserdata(L,1);\n\tint sz = luaL_checkinteger(L,2);\n\tif (sz != sizeof(pack)) {\n\t\treturn luaL_error(L, \"Invalid multicast package size %d\", sz);\n\t}\n\tlua_pushlightuserdata(L, *pack);\n\tlua_pushlightuserdata(L, (*pack)->data);\n\tlua_pushinteger(L, (lua_Integer)((*pack)->size));\n\treturn 3;\n}\n\n/*\n\tlightuserdata struct mc_package **\n\tinteger reference\n\n\treturn mc_package *\n */\nstatic int\nmc_bindrefer(lua_State *L) {\n\tstruct mc_package ** pack = lua_touserdata(L,1);\n\tint ref = luaL_checkinteger(L,2);\n\tif (ATOM_LOAD(&(*pack)->reference) != 0) {\n\t\treturn luaL_error(L, \"Can't bind a multicast package more than once\");\n\t}\n\tATOM_STORE(&(*pack)->reference , ref);\n\n\tlua_pushlightuserdata(L, *pack);\n\n\tskynet_free(pack);\n\n\treturn 1;\n}\n\n/*\n\tlightuserdata struct mc_package *\n */\nstatic int\nmc_closelocal(lua_State *L) {\n\tstruct mc_package *pack = lua_touserdata(L,1);\n\n\tint ref = ATOM_FDEC(&pack->reference)-1;\n\tif (ref <= 0) {\n\t\tskynet_free(pack->data);\n\t\tskynet_free(pack);\n\t\tif (ref < 0) {\n\t\t\treturn luaL_error(L, \"Invalid multicast package reference %d\", ref);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/*\n\tlightuserdata struct mc_package **\n\treturn lightuserdata/size\n */\nstatic int\nmc_remote(lua_State *L) {\n\tstruct mc_package **ptr = lua_touserdata(L,1);\n\tstruct mc_package *pack = *ptr;\n\tlua_pushlightuserdata(L, pack->data);\n\tlua_pushinteger(L, (lua_Integer)(pack->size));\n\tskynet_free(pack);\n\tskynet_free(ptr);\n\treturn 2;\n}\n\nstatic int\nmc_nextid(lua_State *L) {\n\tuint32_t id = (uint32_t)luaL_checkinteger(L, 1);\n\tid += 256;\n\t// remove the highest bit, see #1139\n\tlua_pushinteger(L, id & 0x7fffffffu);\n\n\treturn 1;\n}\n\nLUAMOD_API int\nluaopen_skynet_multicast_core(lua_State *L) {\n\tluaL_Reg l[] = {\n\t\t{ \"pack\", mc_packlocal },\n\t\t{ \"unpack\", mc_unpacklocal },\n\t\t{ \"bind\", mc_bindrefer },\n\t\t{ \"close\", mc_closelocal },\n\t\t{ \"remote\", mc_remote },\n\t\t{ \"packremote\", mc_packremote },\n\t\t{ \"nextid\", mc_nextid },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_checkversion(L);\n\tluaL_newlib(L,l);\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-netpack.c",
    "content": "#define LUA_LIB\n\n#include \"skynet_malloc.h\"\n\n#include \"skynet_socket.h\"\n\n#include <lua.h>\n#include <lauxlib.h>\n\n#include <assert.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define QUEUESIZE 1024\n#define HASHSIZE 4096\n#define SMALLSTRING 2048\n\n#define TYPE_DATA 1\n#define TYPE_MORE 2\n#define TYPE_ERROR 3\n#define TYPE_OPEN 4\n#define TYPE_CLOSE 5\n#define TYPE_WARNING 6\n#define TYPE_INIT 7\n\n/*\n\tEach package is uint16 + data , uint16 (serialized in big-endian) is the number of bytes comprising the data .\n */\n\nstruct netpack {\n\tint id;\n\tint size;\n\tvoid * buffer;\n};\n\nstruct uncomplete {\n\tstruct netpack pack;\n\tstruct uncomplete * next;\n\tint read;\n\tint header;\n};\n\nstruct queue {\n\tint cap;\n\tint head;\n\tint tail;\n\tstruct uncomplete * hash[HASHSIZE];\n\tstruct netpack queue[QUEUESIZE];\n};\n\nstatic void\nclear_list(struct uncomplete * uc) {\n\twhile (uc) {\n\t\tskynet_free(uc->pack.buffer);\n\t\tvoid * tmp = uc;\n\t\tuc = uc->next;\n\t\tskynet_free(tmp);\n\t}\n}\n\nstatic int\nlclear(lua_State *L) {\n\tstruct queue * q = lua_touserdata(L, 1);\n\tif (q == NULL) {\n\t\treturn 0;\n\t}\n\tint i;\n\tfor (i=0;i<HASHSIZE;i++) {\n\t\tclear_list(q->hash[i]);\n\t\tq->hash[i] = NULL;\n\t}\n\tif (q->head > q->tail) {\n\t\tq->tail += q->cap;\n\t}\n\tfor (i=q->head;i<q->tail;i++) {\n\t\tstruct netpack *np = &q->queue[i % q->cap];\n\t\tskynet_free(np->buffer);\n\t}\n\tq->head = q->tail = 0;\n\n\treturn 0;\n}\n\nstatic inline int\nhash_fd(int fd) {\n\tint a = fd >> 24;\n\tint b = fd >> 12;\n\tint c = fd;\n\treturn (int)(((uint32_t)(a + b + c)) % HASHSIZE);\n}\n\nstatic struct uncomplete *\nfind_uncomplete(struct queue *q, int fd) {\n\tif (q == NULL)\n\t\treturn NULL;\n\tint h = hash_fd(fd);\n\tstruct uncomplete * uc = q->hash[h];\n\tif (uc == NULL)\n\t\treturn NULL;\n\tif (uc->pack.id == fd) {\n\t\tq->hash[h] = uc->next;\n\t\treturn uc;\n\t}\n\tstruct uncomplete * last = uc;\n\twhile (last->next) {\n\t\tuc = last->next;\n\t\tif (uc->pack.id == fd) {\n\t\t\tlast->next = uc->next;\n\t\t\treturn uc;\n\t\t}\n\t\tlast = uc;\n\t}\n\treturn NULL;\n}\n\nstatic struct queue *\nget_queue(lua_State *L) {\n\tstruct queue *q = lua_touserdata(L,1);\n\tif (q == NULL) {\n\t\tq = lua_newuserdatauv(L, sizeof(struct queue), 0);\n\t\tq->cap = QUEUESIZE;\n\t\tq->head = 0;\n\t\tq->tail = 0;\n\t\tint i;\n\t\tfor (i=0;i<HASHSIZE;i++) {\n\t\t\tq->hash[i] = NULL;\n\t\t}\n\t\tlua_replace(L, 1);\n\t}\n\treturn q;\n}\n\nstatic void\nexpand_queue(lua_State *L, struct queue *q) {\n\tstruct queue *nq = lua_newuserdatauv(L, sizeof(struct queue) + q->cap * sizeof(struct netpack), 0);\n\tnq->cap = q->cap + QUEUESIZE;\n\tnq->head = 0;\n\tnq->tail = q->cap;\n\tmemcpy(nq->hash, q->hash, sizeof(nq->hash));\n\tmemset(q->hash, 0, sizeof(q->hash));\n\tint i;\n\tfor (i=0;i<q->cap;i++) {\n\t\tint idx = (q->head + i) % q->cap;\n\t\tnq->queue[i] = q->queue[idx];\n\t}\n\tq->head = q->tail = 0;\n\tlua_replace(L,1);\n}\n\nstatic void\npush_data(lua_State *L, int fd, void *buffer, int size, int clone) {\n\tif (clone) {\n\t\tvoid * tmp = skynet_malloc(size);\n\t\tmemcpy(tmp, buffer, size);\n\t\tbuffer = tmp;\n\t}\n\tstruct queue *q = get_queue(L);\n\tstruct netpack *np = &q->queue[q->tail];\n\tif (++q->tail >= q->cap)\n\t\tq->tail -= q->cap;\n\tnp->id = fd;\n\tnp->buffer = buffer;\n\tnp->size = size;\n\tif (q->head == q->tail) {\n\t\texpand_queue(L, q);\n\t}\n}\n\nstatic struct uncomplete *\nsave_uncomplete(lua_State *L, int fd) {\n\tstruct queue *q = get_queue(L);\n\tint h = hash_fd(fd);\n\tstruct uncomplete * uc = skynet_malloc(sizeof(struct uncomplete));\n\tmemset(uc, 0, sizeof(*uc));\n\tuc->next = q->hash[h];\n\tuc->pack.id = fd;\n\tq->hash[h] = uc;\n\n\treturn uc;\n}\n\nstatic inline int\nread_size(uint8_t * buffer) {\n\tint r = (int)buffer[0] << 8 | (int)buffer[1];\n\treturn r;\n}\n\nstatic void\npush_more(lua_State *L, int fd, uint8_t *buffer, int size) {\n\tif (size == 1) {\n\t\tstruct uncomplete * uc = save_uncomplete(L, fd);\n\t\tuc->read = -1;\n\t\tuc->header = *buffer;\n\t\treturn;\n\t}\n\tint pack_size = read_size(buffer);\n\tbuffer += 2;\n\tsize -= 2;\n\n\tif (size < pack_size) {\n\t\tstruct uncomplete * uc = save_uncomplete(L, fd);\n\t\tuc->read = size;\n\t\tuc->pack.size = pack_size;\n\t\tuc->pack.buffer = skynet_malloc(pack_size);\n\t\tmemcpy(uc->pack.buffer, buffer, size);\n\t\treturn;\n\t}\n\tpush_data(L, fd, buffer, pack_size, 1);\n\n\tbuffer += pack_size;\n\tsize -= pack_size;\n\tif (size > 0) {\n\t\tpush_more(L, fd, buffer, size);\n\t}\n}\n\nstatic void\nclose_uncomplete(lua_State *L, int fd) {\n\tstruct queue *q = lua_touserdata(L,1);\n\tstruct uncomplete * uc = find_uncomplete(q, fd);\n\tif (uc) {\n\t\tskynet_free(uc->pack.buffer);\n\t\tskynet_free(uc);\n\t}\n}\n\nstatic int\nfilter_data_(lua_State *L, int fd, uint8_t * buffer, int size) {\n\tstruct queue *q = lua_touserdata(L,1);\n\tstruct uncomplete * uc = find_uncomplete(q, fd);\n\tif (uc) {\n\t\t// fill uncomplete\n\t\tif (uc->read < 0) {\n\t\t\t// read size\n\t\t\tassert(uc->read == -1);\n\t\t\tint pack_size = *buffer;\n\t\t\tpack_size |= uc->header << 8 ;\n\t\t\t++buffer;\n\t\t\t--size;\n\t\t\tuc->pack.size = pack_size;\n\t\t\tuc->pack.buffer = skynet_malloc(pack_size);\n\t\t\tuc->read = 0;\n\t\t}\n\t\tint need = uc->pack.size - uc->read;\n\t\tif (size < need) {\n\t\t\tmemcpy(uc->pack.buffer + uc->read, buffer, size);\n\t\t\tuc->read += size;\n\t\t\tint h = hash_fd(fd);\n\t\t\tuc->next = q->hash[h];\n\t\t\tq->hash[h] = uc;\n\t\t\treturn 1;\n\t\t}\n\t\tmemcpy(uc->pack.buffer + uc->read, buffer, need);\n\t\tbuffer += need;\n\t\tsize -= need;\n\t\tif (size == 0) {\n\t\t\tlua_pushvalue(L, lua_upvalueindex(TYPE_DATA));\n\t\t\tlua_pushinteger(L, fd);\n\t\t\tlua_pushlightuserdata(L, uc->pack.buffer);\n\t\t\tlua_pushinteger(L, uc->pack.size);\n\t\t\tskynet_free(uc);\n\t\t\treturn 5;\n\t\t}\n\t\t// more data\n\t\tpush_data(L, fd, uc->pack.buffer, uc->pack.size, 0);\n\t\tskynet_free(uc);\n\t\tpush_more(L, fd, buffer, size);\n\t\tlua_pushvalue(L, lua_upvalueindex(TYPE_MORE));\n\t\treturn 2;\n\t} else {\n\t\tif (size == 1) {\n\t\t\tstruct uncomplete * uc = save_uncomplete(L, fd);\n\t\t\tuc->read = -1;\n\t\t\tuc->header = *buffer;\n\t\t\treturn 1;\n\t\t}\n\t\tint pack_size = read_size(buffer);\n\t\tbuffer+=2;\n\t\tsize-=2;\n\n\t\tif (size < pack_size) {\n\t\t\tstruct uncomplete * uc = save_uncomplete(L, fd);\n\t\t\tuc->read = size;\n\t\t\tuc->pack.size = pack_size;\n\t\t\tuc->pack.buffer = skynet_malloc(pack_size);\n\t\t\tmemcpy(uc->pack.buffer, buffer, size);\n\t\t\treturn 1;\n\t\t}\n\t\tif (size == pack_size) {\n\t\t\t// just one package\n\t\t\tlua_pushvalue(L, lua_upvalueindex(TYPE_DATA));\n\t\t\tlua_pushinteger(L, fd);\n\t\t\tvoid * result = skynet_malloc(pack_size);\n\t\t\tmemcpy(result, buffer, size);\n\t\t\tlua_pushlightuserdata(L, result);\n\t\t\tlua_pushinteger(L, size);\n\t\t\treturn 5;\n\t\t}\n\t\t// more data\n\t\tpush_data(L, fd, buffer, pack_size, 1);\n\t\tbuffer += pack_size;\n\t\tsize -= pack_size;\n\t\tpush_more(L, fd, buffer, size);\n\t\tlua_pushvalue(L, lua_upvalueindex(TYPE_MORE));\n\t\treturn 2;\n\t}\n}\n\nstatic inline int\nfilter_data(lua_State *L, int fd, uint8_t * buffer, int size) {\n\tint ret = filter_data_(L, fd, buffer, size);\n\t// buffer is the data of socket message, it malloc at socket_server.c : function forward_message .\n\t// it should be free before return,\n\tskynet_free(buffer);\n\treturn ret;\n}\n\nstatic void\npushstring(lua_State *L, const char * msg, int size) {\n\tif (msg) {\n\t\tlua_pushlstring(L, msg, size);\n\t} else {\n\t\tlua_pushliteral(L, \"\");\n\t}\n}\n\n/*\n\tuserdata queue\n\tlightuserdata msg\n\tinteger size\n\treturn\n\t\tuserdata queue\n\t\tinteger type\n\t\tinteger fd\n\t\tstring msg | lightuserdata/integer\n */\nstatic int\nlfilter(lua_State *L) {\n\tstruct skynet_socket_message *message = lua_touserdata(L,2);\n\tint size = luaL_checkinteger(L,3);\n\tchar * buffer = message->buffer;\n\tif (buffer == NULL) {\n\t\tbuffer = (char *)(message+1);\n\t\tsize -= sizeof(*message);\n\t} else {\n\t\tsize = -1;\n\t}\n\n\tlua_settop(L, 1);\n\n\tswitch(message->type) {\n\tcase SKYNET_SOCKET_TYPE_DATA:\n\t\t// ignore listen id (message->id)\n\t\tassert(size == -1);\t// never padding string\n\t\treturn filter_data(L, message->id, (uint8_t *)buffer, message->ud);\n\tcase SKYNET_SOCKET_TYPE_CONNECT:\n\t\tlua_pushvalue(L, lua_upvalueindex(TYPE_INIT));\n\t\tlua_pushinteger(L, message->id);\n\t\tlua_pushlstring(L, buffer, size);\n\t\tlua_pushinteger(L, message->ud);\n\t\treturn 5;\n\tcase SKYNET_SOCKET_TYPE_CLOSE:\n\t\t// no more data in fd (message->id)\n\t\tclose_uncomplete(L, message->id);\n\t\tlua_pushvalue(L, lua_upvalueindex(TYPE_CLOSE));\n\t\tlua_pushinteger(L, message->id);\n\t\treturn 3;\n\tcase SKYNET_SOCKET_TYPE_ACCEPT:\n\t\tlua_pushvalue(L, lua_upvalueindex(TYPE_OPEN));\n\t\t// ignore listen id (message->id);\n\t\tlua_pushinteger(L, message->ud);\n\t\tpushstring(L, buffer, size);\n\t\treturn 4;\n\tcase SKYNET_SOCKET_TYPE_ERROR:\n\t\t// no more data in fd (message->id)\n\t\tclose_uncomplete(L, message->id);\n\t\tlua_pushvalue(L, lua_upvalueindex(TYPE_ERROR));\n\t\tlua_pushinteger(L, message->id);\n\t\tpushstring(L, buffer, size);\n\t\treturn 4;\n\tcase SKYNET_SOCKET_TYPE_WARNING:\n\t\tlua_pushvalue(L, lua_upvalueindex(TYPE_WARNING));\n\t\tlua_pushinteger(L, message->id);\n\t\tlua_pushinteger(L, message->ud);\n\t\treturn 4;\n\tdefault:\n\t\t// never get here\n\t\treturn 1;\n\t}\n}\n\n/*\n\tuserdata queue\n\treturn\n\t\tinteger fd\n\t\tlightuserdata msg\n\t\tinteger size\n */\nstatic int\nlpop(lua_State *L) {\n\tstruct queue * q = lua_touserdata(L, 1);\n\tif (q == NULL || q->head == q->tail)\n\t\treturn 0;\n\tstruct netpack *np = &q->queue[q->head];\n\tif (++q->head >= q->cap) {\n\t\tq->head = 0;\n\t}\n\tlua_pushinteger(L, np->id);\n\tlua_pushlightuserdata(L, np->buffer);\n\tlua_pushinteger(L, np->size);\n\n\treturn 3;\n}\n\n/*\n\tstring msg | lightuserdata/integer\n\n\tlightuserdata/integer\n */\n\nstatic const char *\ntolstring(lua_State *L, size_t *sz, int index) {\n\tconst char * ptr;\n\tif (lua_isuserdata(L,index)) {\n\t\tptr = (const char *)lua_touserdata(L,index);\n\t\t*sz = (size_t)luaL_checkinteger(L, index+1);\n\t} else {\n\t\tptr = luaL_checklstring(L, index, sz);\n\t}\n\treturn ptr;\n}\n\nstatic inline void\nwrite_size(uint8_t * buffer, int len) {\n\tbuffer[0] = (len >> 8) & 0xff;\n\tbuffer[1] = len & 0xff;\n}\n\nstatic int\nlpack(lua_State *L) {\n\tsize_t len;\n\tconst char * ptr = tolstring(L, &len, 1);\n\tif (len >= 0x10000) {\n\t\treturn luaL_error(L, \"Invalid size (too long) of data : %d\", (int)len);\n\t}\n\n\tuint8_t * buffer = skynet_malloc(len + 2);\n\twrite_size(buffer, len);\n\tmemcpy(buffer+2, ptr, len);\n\n\tlua_pushlightuserdata(L, buffer);\n\tlua_pushinteger(L, len + 2);\n\n\treturn 2;\n}\n\nstatic int\nltostring(lua_State *L) {\n\tvoid * ptr = lua_touserdata(L, 1);\n\tint size = luaL_checkinteger(L, 2);\n\tif (ptr == NULL) {\n\t\tlua_pushliteral(L, \"\");\n\t} else {\n\t\tlua_pushlstring(L, (const char *)ptr, size);\n\t\tskynet_free(ptr);\n\t}\n\treturn 1;\n}\n\nLUAMOD_API int\nluaopen_skynet_netpack(lua_State *L) {\n\tluaL_checkversion(L);\n\tluaL_Reg l[] = {\n\t\t{ \"pop\", lpop },\n\t\t{ \"pack\", lpack },\n\t\t{ \"clear\", lclear },\n\t\t{ \"tostring\", ltostring },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_newlib(L,l);\n\n\t// the order is same with macros : TYPE_* (defined top)\n\tlua_pushliteral(L, \"data\");\n\tlua_pushliteral(L, \"more\");\n\tlua_pushliteral(L, \"error\");\n\tlua_pushliteral(L, \"open\");\n\tlua_pushliteral(L, \"close\");\n\tlua_pushliteral(L, \"warning\");\n\tlua_pushliteral(L, \"init\");\n\n\tlua_pushcclosure(L, lfilter, 7);\n\tlua_setfield(L, -2, \"filter\");\n\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-seri.c",
    "content": "/*\n\tmodify from https://github.com/cloudwu/lua-serialize\n */\n\n#define LUA_LIB\n\n#include \"skynet_malloc.h\"\n\n#include <lua.h>\n#include <lauxlib.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <assert.h>\n#include <string.h>\n\n#define TYPE_NIL 0\n#define TYPE_BOOLEAN 1\n// hibits 0 false 1 true\n#define TYPE_NUMBER 2\n// hibits 0 : 0 , 1: byte, 2:word, 4: dword, 6: qword, 8 : double\n#define TYPE_NUMBER_ZERO 0\n#define TYPE_NUMBER_BYTE 1\n#define TYPE_NUMBER_WORD 2\n#define TYPE_NUMBER_DWORD 4\n#define TYPE_NUMBER_QWORD 6\n#define TYPE_NUMBER_REAL 8\n\n#define TYPE_USERDATA 3\n#define TYPE_SHORT_STRING 4\n// hibits 0~31 : len\n#define TYPE_LONG_STRING 5\n#define TYPE_TABLE 6\n\n#define MAX_COOKIE 32\n#define COMBINE_TYPE(t,v) ((t) | (v) << 3)\n\n#define BLOCK_SIZE 128\n#define MAX_DEPTH 32\n\nstruct block {\n\tstruct block * next;\n\tchar buffer[BLOCK_SIZE];\n};\n\nstruct write_block {\n\tstruct block * head;\n\tstruct block * current;\n\tint len;\n\tint ptr;\n};\n\nstruct read_block {\n\tchar * buffer;\n\tint len;\n\tint ptr;\n};\n\ninline static struct block *\nblk_alloc(void) {\n\tstruct block *b = skynet_malloc(sizeof(struct block));\n\tb->next = NULL;\n\treturn b;\n}\n\ninline static void\nwb_push(struct write_block *b, const void *buf, int sz) {\n\tconst char * buffer = buf;\n\tif (b->ptr == BLOCK_SIZE) {\n_again:\n\t\tb->current = b->current->next = blk_alloc();\n\t\tb->ptr = 0;\n\t}\n\tif (b->ptr <= BLOCK_SIZE - sz) {\n\t\tmemcpy(b->current->buffer + b->ptr, buffer, sz);\n\t\tb->ptr+=sz;\n\t\tb->len+=sz;\n\t} else {\n\t\tint copy = BLOCK_SIZE - b->ptr;\n\t\tmemcpy(b->current->buffer + b->ptr, buffer, copy);\n\t\tbuffer += copy;\n\t\tb->len += copy;\n\t\tsz -= copy;\n\t\tgoto _again;\n\t}\n}\n\nstatic void\nwb_init(struct write_block *wb , struct block *b) {\n\twb->head = b;\n\tassert(b->next == NULL);\n\twb->len = 0;\n\twb->current = wb->head;\n\twb->ptr = 0;\n}\n\nstatic void\nwb_free(struct write_block *wb) {\n\tstruct block *blk = wb->head;\n\tblk = blk->next;\t// the first block is on stack\n\twhile (blk) {\n\t\tstruct block * next = blk->next;\n\t\tskynet_free(blk);\n\t\tblk = next;\n\t}\n\twb->head = NULL;\n\twb->current = NULL;\n\twb->ptr = 0;\n\twb->len = 0;\n}\n\nstatic void\nrball_init(struct read_block * rb, char * buffer, int size) {\n\trb->buffer = buffer;\n\trb->len = size;\n\trb->ptr = 0;\n}\n\nstatic const void *\nrb_read(struct read_block *rb, int sz) {\n\tif (rb->len < sz) {\n\t\treturn NULL;\n\t}\n\n\tint ptr = rb->ptr;\n\trb->ptr += sz;\n\trb->len -= sz;\n\treturn rb->buffer + ptr;\n}\n\nstatic inline void\nwb_nil(struct write_block *wb) {\n\tuint8_t n = TYPE_NIL;\n\twb_push(wb, &n, 1);\n}\n\nstatic inline void\nwb_boolean(struct write_block *wb, int boolean) {\n\tuint8_t n = COMBINE_TYPE(TYPE_BOOLEAN , boolean ? 1 : 0);\n\twb_push(wb, &n, 1);\n}\n\nstatic inline void\nwb_integer(struct write_block *wb, lua_Integer v) {\n\tint type = TYPE_NUMBER;\n\tif (v == 0) {\n\t\tuint8_t n = COMBINE_TYPE(type , TYPE_NUMBER_ZERO);\n\t\twb_push(wb, &n, 1);\n\t} else if (v != (int32_t)v) {\n\t\tuint8_t n = COMBINE_TYPE(type , TYPE_NUMBER_QWORD);\n\t\tint64_t v64 = v;\n\t\twb_push(wb, &n, 1);\n\t\twb_push(wb, &v64, sizeof(v64));\n\t} else if (v < 0) {\n\t\tint32_t v32 = (int32_t)v;\n\t\tuint8_t n = COMBINE_TYPE(type , TYPE_NUMBER_DWORD);\n\t\twb_push(wb, &n, 1);\n\t\twb_push(wb, &v32, sizeof(v32));\n\t} else if (v<0x100) {\n\t\tuint8_t n = COMBINE_TYPE(type , TYPE_NUMBER_BYTE);\n\t\twb_push(wb, &n, 1);\n\t\tuint8_t byte = (uint8_t)v;\n\t\twb_push(wb, &byte, sizeof(byte));\n\t} else if (v<0x10000) {\n\t\tuint8_t n = COMBINE_TYPE(type , TYPE_NUMBER_WORD);\n\t\twb_push(wb, &n, 1);\n\t\tuint16_t word = (uint16_t)v;\n\t\twb_push(wb, &word, sizeof(word));\n\t} else {\n\t\tuint8_t n = COMBINE_TYPE(type , TYPE_NUMBER_DWORD);\n\t\twb_push(wb, &n, 1);\n\t\tuint32_t v32 = (uint32_t)v;\n\t\twb_push(wb, &v32, sizeof(v32));\n\t}\n}\n\nstatic inline void\nwb_real(struct write_block *wb, double v) {\n\tuint8_t n = COMBINE_TYPE(TYPE_NUMBER , TYPE_NUMBER_REAL);\n\twb_push(wb, &n, 1);\n\twb_push(wb, &v, sizeof(v));\n}\n\nstatic inline void\nwb_pointer(struct write_block *wb, void *v) {\n\tuint8_t n = TYPE_USERDATA;\n\twb_push(wb, &n, 1);\n\twb_push(wb, &v, sizeof(v));\n}\n\nstatic inline void\nwb_string(struct write_block *wb, const char *str, int len) {\n\tif (len < MAX_COOKIE) {\n\t\tuint8_t n = COMBINE_TYPE(TYPE_SHORT_STRING, len);\n\t\twb_push(wb, &n, 1);\n\t\tif (len > 0) {\n\t\t\twb_push(wb, str, len);\n\t\t}\n\t} else {\n\t\tuint8_t n;\n\t\tif (len < 0x10000) {\n\t\t\tn = COMBINE_TYPE(TYPE_LONG_STRING, 2);\n\t\t\twb_push(wb, &n, 1);\n\t\t\tuint16_t x = (uint16_t) len;\n\t\t\twb_push(wb, &x, 2);\n\t\t} else {\n\t\t\tn = COMBINE_TYPE(TYPE_LONG_STRING, 4);\n\t\t\twb_push(wb, &n, 1);\n\t\t\tuint32_t x = (uint32_t) len;\n\t\t\twb_push(wb, &x, 4);\n\t\t}\n\t\twb_push(wb, str, len);\n\t}\n}\n\nstatic void pack_one(lua_State *L, struct write_block *b, int index, int depth);\n\nstatic int\nwb_table_array(lua_State *L, struct write_block * wb, int index, int depth) {\n\tint array_size = lua_rawlen(L,index);\n\tif (array_size >= MAX_COOKIE-1) {\n\t\tuint8_t n = COMBINE_TYPE(TYPE_TABLE, MAX_COOKIE-1);\n\t\twb_push(wb, &n, 1);\n\t\twb_integer(wb, array_size);\n\t} else {\n\t\tuint8_t n = COMBINE_TYPE(TYPE_TABLE, array_size);\n\t\twb_push(wb, &n, 1);\n\t}\n\n\tint i;\n\tfor (i=1;i<=array_size;i++) {\n\t\tlua_rawgeti(L,index,i);\n\t\tpack_one(L, wb, -1, depth);\n\t\tlua_pop(L,1);\n\t}\n\n\treturn array_size;\n}\n\nstatic void\nwb_table_hash(lua_State *L, struct write_block * wb, int index, int depth, int array_size) {\n\tlua_pushnil(L);\n\twhile (lua_next(L, index) != 0) {\n\t\tif (lua_type(L,-2) == LUA_TNUMBER) {\n\t\t\tif (lua_isinteger(L, -2)) {\n\t\t\t\tlua_Integer x = lua_tointeger(L,-2);\n\t\t\t\tif (x>0 && x<=array_size) {\n\t\t\t\t\tlua_pop(L,1);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpack_one(L,wb,-2,depth);\n\t\tpack_one(L,wb,-1,depth);\n\t\tlua_pop(L, 1);\n\t}\n\twb_nil(wb);\n}\n\nstatic int\nwb_table_metapairs(lua_State *L, struct write_block *wb, int index, int depth) {\n\tuint8_t n = COMBINE_TYPE(TYPE_TABLE, 0);\n\twb_push(wb, &n, 1);\n\tlua_pushvalue(L, index);\n\tif (lua_pcall(L, 1, 3,0) != LUA_OK)\n\t\treturn 1;\n\tfor(;;) {\n\t\tlua_pushvalue(L, -2);\n\t\tlua_pushvalue(L, -2);\n\t\tlua_copy(L, -5, -3);\n\t\tif (lua_pcall(L, 2, 2, 0) != LUA_OK)\n\t\t\treturn 1;\n\t\tint type = lua_type(L, -2);\n\t\tif (type == LUA_TNIL) {\n\t\t\tlua_pop(L, 4);\n\t\t\tbreak;\n\t\t}\n\t\tpack_one(L, wb, -2, depth);\n\t\tpack_one(L, wb, -1, depth);\n\t\tlua_pop(L, 1);\n\t}\n\twb_nil(wb);\n\treturn 0;\n}\n\nstatic int\nwb_table(lua_State *L, struct write_block *wb, int index, int depth) {\n\tif (!lua_checkstack(L, LUA_MINSTACK)) {\n\t\tlua_pushstring(L, \"out of memory\");\n\t\treturn 1;\n\t}\n\tif (index < 0) {\n\t\tindex = lua_gettop(L) + index + 1;\n\t}\n\tif (luaL_getmetafield(L, index, \"__pairs\") != LUA_TNIL) {\n\t\treturn wb_table_metapairs(L, wb, index, depth);\n\t} else {\n\t\tint array_size = wb_table_array(L, wb, index, depth);\n\t\twb_table_hash(L, wb, index, depth, array_size);\n\t\treturn 0;\n\t}\n}\n\nstatic void\npack_one(lua_State *L, struct write_block *b, int index, int depth) {\n\tif (depth > MAX_DEPTH) {\n\t\twb_free(b);\n\t\tluaL_error(L, \"serialize can't pack too depth table\");\n\t}\n\tint type = lua_type(L,index);\n\tswitch(type) {\n\tcase LUA_TNIL:\n\t\twb_nil(b);\n\t\tbreak;\n\tcase LUA_TNUMBER: {\n\t\tif (lua_isinteger(L, index)) {\n\t\t\tlua_Integer x = lua_tointeger(L,index);\n\t\t\twb_integer(b, x);\n\t\t} else {\n\t\t\tlua_Number n = lua_tonumber(L,index);\n\t\t\twb_real(b,n);\n\t\t}\n\t\tbreak;\n\t}\n\tcase LUA_TBOOLEAN: \n\t\twb_boolean(b, lua_toboolean(L,index));\n\t\tbreak;\n\tcase LUA_TSTRING: {\n\t\tsize_t sz = 0;\n\t\tconst char *str = lua_tolstring(L,index,&sz);\n\t\twb_string(b, str, (int)sz);\n\t\tbreak;\n\t}\n\tcase LUA_TLIGHTUSERDATA:\n\t\twb_pointer(b, lua_touserdata(L,index));\n\t\tbreak;\n\tcase LUA_TTABLE: {\n\t\tif (index < 0) {\n\t\t\tindex = lua_gettop(L) + index + 1;\n\t\t}\n\t\tif (wb_table(L, b, index, depth+1)) {\n\t\t\twb_free(b);\n\t\t\tlua_error(L);\n\t\t}\n\t\tbreak;\n\t}\n\tdefault:\n\t\twb_free(b);\n\t\tluaL_error(L, \"Unsupport type %s to serialize\", lua_typename(L, type));\n\t}\n}\n\nstatic void\npack_from(lua_State *L, struct write_block *b, int from) {\n\tint n = lua_gettop(L) - from;\n\tint i;\n\tfor (i=1;i<=n;i++) {\n\t\tpack_one(L, b , from + i, 0);\n\t}\n}\n\nstatic inline void\ninvalid_stream_line(lua_State *L, struct read_block *rb, int line) {\n\tint len = rb->len;\n\tluaL_error(L, \"Invalid serialize stream %d (line:%d)\", len, line);\n}\n\n#define invalid_stream(L,rb) invalid_stream_line(L,rb,__LINE__)\n\nstatic lua_Integer\nget_integer(lua_State *L, struct read_block *rb, int cookie) {\n\tswitch (cookie) {\n\tcase TYPE_NUMBER_ZERO:\n\t\treturn 0;\n\tcase TYPE_NUMBER_BYTE: {\n\t\tuint8_t n;\n\t\tconst uint8_t * pn = (const uint8_t *)rb_read(rb,sizeof(n));\n\t\tif (pn == NULL)\n\t\t\tinvalid_stream(L,rb);\n\t\tn = *pn;\n\t\treturn n;\n\t}\n\tcase TYPE_NUMBER_WORD: {\n\t\tuint16_t n;\n\t\tconst void * pn = rb_read(rb,sizeof(n));\n\t\tif (pn == NULL)\n\t\t\tinvalid_stream(L,rb);\n\t\tmemcpy(&n, pn, sizeof(n));\n\t\treturn n;\n\t}\n\tcase TYPE_NUMBER_DWORD: {\n\t\tint32_t n;\n\t\tconst void * pn = rb_read(rb,sizeof(n));\n\t\tif (pn == NULL)\n\t\t\tinvalid_stream(L,rb);\n\t\tmemcpy(&n, pn, sizeof(n));\n\t\treturn n;\n\t}\n\tcase TYPE_NUMBER_QWORD: {\n\t\tint64_t n;\n\t\tconst void * pn = rb_read(rb,sizeof(n));\n\t\tif (pn == NULL)\n\t\t\tinvalid_stream(L,rb);\n\t\tmemcpy(&n, pn, sizeof(n));\n\t\treturn n;\n\t}\n\tdefault:\n\t\tinvalid_stream(L,rb);\n\t\treturn 0;\n\t}\n}\n\nstatic double\nget_real(lua_State *L, struct read_block *rb) {\n\tdouble n;\n\tconst void * pn = rb_read(rb,sizeof(n));\n\tif (pn == NULL)\n\t\tinvalid_stream(L,rb);\n\tmemcpy(&n, pn, sizeof(n));\n\treturn n;\n}\n\nstatic void *\nget_pointer(lua_State *L, struct read_block *rb) {\n\tvoid * userdata = 0;\n\tconst void * v = rb_read(rb,sizeof(userdata));\n\tif (v == NULL) {\n\t\tinvalid_stream(L,rb);\n\t}\n\tmemcpy(&userdata, v, sizeof(userdata));\n\treturn userdata;\n}\n\nstatic void\nget_buffer(lua_State *L, struct read_block *rb, int len) {\n\tconst char * p = (const char *)rb_read(rb,len);\n\tif (p == NULL) {\n\t\tinvalid_stream(L,rb);\n\t}\n\tlua_pushlstring(L,p,len);\n}\n\nstatic void unpack_one(lua_State *L, struct read_block *rb);\n\nstatic void\nunpack_table(lua_State *L, struct read_block *rb, int array_size) {\n\tif (array_size == MAX_COOKIE-1) {\n\t\tuint8_t type;\n\t\tconst uint8_t * t = (const uint8_t *)rb_read(rb, sizeof(type));\n\t\tif (t==NULL) {\n\t\t\tinvalid_stream(L,rb);\n\t\t}\n\t\ttype = *t;\n\t\tint cookie = type >> 3;\n\t\tif ((type & 7) != TYPE_NUMBER || cookie == TYPE_NUMBER_REAL) {\n\t\t\tinvalid_stream(L,rb);\n\t\t}\n\t\tarray_size = get_integer(L,rb,cookie);\n\t}\n\tluaL_checkstack(L,LUA_MINSTACK,NULL);\n\tlua_createtable(L,array_size,0);\n\tint i;\n\tfor (i=1;i<=array_size;i++) {\n\t\tunpack_one(L,rb);\n\t\tlua_rawseti(L,-2,i);\n\t}\n\tfor (;;) {\n\t\tunpack_one(L,rb);\n\t\tif (lua_isnil(L,-1)) {\n\t\t\tlua_pop(L,1);\n\t\t\treturn;\n\t\t}\n\t\tunpack_one(L,rb);\n\t\tlua_rawset(L,-3);\n\t}\n}\n\nstatic void\npush_value(lua_State *L, struct read_block *rb, int type, int cookie) {\n\tswitch(type) {\n\tcase TYPE_NIL:\n\t\tlua_pushnil(L);\n\t\tbreak;\n\tcase TYPE_BOOLEAN:\n\t\tlua_pushboolean(L,cookie);\n\t\tbreak;\n\tcase TYPE_NUMBER:\n\t\tif (cookie == TYPE_NUMBER_REAL) {\n\t\t\tlua_pushnumber(L,get_real(L,rb));\n\t\t} else {\n\t\t\tlua_pushinteger(L, get_integer(L, rb, cookie));\n\t\t}\n\t\tbreak;\n\tcase TYPE_USERDATA:\n\t\tlua_pushlightuserdata(L,get_pointer(L,rb));\n\t\tbreak;\n\tcase TYPE_SHORT_STRING:\n\t\tget_buffer(L,rb,cookie);\n\t\tbreak;\n\tcase TYPE_LONG_STRING: {\n\t\tif (cookie == 2) {\n\t\t\tconst void * plen = rb_read(rb, 2);\n\t\t\tif (plen == NULL) {\n\t\t\t\tinvalid_stream(L,rb);\n\t\t\t}\n\t\t\tuint16_t n;\n\t\t\tmemcpy(&n, plen, sizeof(n));\n\t\t\tget_buffer(L,rb,n);\n\t\t} else {\n\t\t\tif (cookie != 4) {\n\t\t\t\tinvalid_stream(L,rb);\n\t\t\t}\n\t\t\tconst void * plen = rb_read(rb, 4);\n\t\t\tif (plen == NULL) {\n\t\t\t\tinvalid_stream(L,rb);\n\t\t\t}\n\t\t\tuint32_t n;\n\t\t\tmemcpy(&n, plen, sizeof(n));\n\t\t\tget_buffer(L,rb,n);\n\t\t}\n\t\tbreak;\n\t}\n\tcase TYPE_TABLE: {\n\t\tunpack_table(L,rb,cookie);\n\t\tbreak;\n\t}\n\tdefault: {\n\t\tinvalid_stream(L,rb);\n\t\tbreak;\n\t}\n\t}\n}\n\nstatic void\nunpack_one(lua_State *L, struct read_block *rb) {\n\tuint8_t type;\n\tconst uint8_t * t = (const uint8_t *)rb_read(rb, sizeof(type));\n\tif (t==NULL) {\n\t\tinvalid_stream(L, rb);\n\t}\n\ttype = *t;\n\tpush_value(L, rb, type & 0x7, type>>3);\n}\n\nstatic void\nseri(lua_State *L, struct block *b, int len) {\n\tuint8_t * buffer = skynet_malloc(len);\n\tuint8_t * ptr = buffer;\n\tint sz = len;\n\twhile(len>0) {\n\t\tif (len >= BLOCK_SIZE) {\n\t\t\tmemcpy(ptr, b->buffer, BLOCK_SIZE);\n\t\t\tptr += BLOCK_SIZE;\n\t\t\tlen -= BLOCK_SIZE;\n\t\t\tb = b->next;\n\t\t} else {\n\t\t\tmemcpy(ptr, b->buffer, len);\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tlua_pushlightuserdata(L, buffer);\n\tlua_pushinteger(L, sz);\n}\n\nint\nluaseri_unpack(lua_State *L) {\n\tif (lua_isnoneornil(L,1)) {\n\t\treturn 0;\n\t}\n\tvoid * buffer;\n\tint len;\n\tif (lua_type(L,1) == LUA_TSTRING) {\n\t\tsize_t sz;\n\t\t buffer = (void *)lua_tolstring(L,1,&sz);\n\t\tlen = (int)sz;\n\t} else {\n\t\tbuffer = lua_touserdata(L,1);\n\t\tlen = luaL_checkinteger(L,2);\n\t}\n\tif (len == 0) {\n\t\treturn 0;\n\t}\n\tif (buffer == NULL) {\n\t\treturn luaL_error(L, \"deserialize null pointer\");\n\t}\n\n\tlua_settop(L,1);\n\tstruct read_block rb;\n\trball_init(&rb, buffer, len);\n\n\tint i;\n\tfor (i=0;;i++) {\n\t\tif (i%8==7) {\n\t\t\tluaL_checkstack(L,LUA_MINSTACK,NULL);\n\t\t}\n\t\tuint8_t type = 0;\n\t\tconst uint8_t * t = (const uint8_t *)rb_read(&rb, sizeof(type));\n\t\tif (t==NULL)\n\t\t\tbreak;\n\t\ttype = *t;\n\t\tpush_value(L, &rb, type & 0x7, type>>3);\n\t}\n\n\t// Need not free buffer\n\n\treturn lua_gettop(L) - 1;\n}\n\nLUAMOD_API int\nluaseri_pack(lua_State *L) {\n\tstruct block temp;\n\ttemp.next = NULL;\n\tstruct write_block wb;\n\twb_init(&wb, &temp);\n\tpack_from(L,&wb,0);\n\tassert(wb.head == &temp);\n\tseri(L, &temp, wb.len);\n\n\twb_free(&wb);\n\n\treturn 2;\n}\n"
  },
  {
    "path": "lualib-src/lua-seri.h",
    "content": "#ifndef LUA_SERIALIZE_H\n#define LUA_SERIALIZE_H\n\n#include <lua.h>\n\nint luaseri_pack(lua_State *L);\nint luaseri_unpack(lua_State *L);\n\n#endif\n"
  },
  {
    "path": "lualib-src/lua-sharedata.c",
    "content": "#define LUA_LIB\n\n#include <lua.h>\n#include <lauxlib.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include \"atomic.h\"\n\n#define KEYTYPE_INTEGER 0\n#define KEYTYPE_STRING 1\n\n#define VALUETYPE_NIL 0\n#define VALUETYPE_REAL 1\n#define VALUETYPE_STRING 2\n#define VALUETYPE_BOOLEAN 3\n#define VALUETYPE_TABLE 4\n#define VALUETYPE_INTEGER 5\n\nstruct table;\n\nunion value {\n\tlua_Number n;\n\tlua_Integer d;\n\tstruct table * tbl;\n\tint string;\n\tint boolean;\n};\n\nstruct node {\n\tunion value v;\n\tint key;\t// integer key or index of string table\n\tint next;\t// next slot index\n\tuint32_t keyhash;\n\tuint8_t keytype;\t// key type must be integer or string\n\tuint8_t valuetype;\t// value type can be number/string/boolean/table\n\tuint8_t nocolliding;\t// 0 means colliding slot\n};\n\nstruct state {\n\tint dirty;\n\tATOM_INT ref;\n\tstruct table * root;\n};\n\nstruct table {\n\tint sizearray;\n\tint sizehash;\n\tuint8_t *arraytype;\n\tunion value * array;\n\tstruct node * hash;\n\tlua_State * L;\n};\n\nstruct context {\n\tlua_State * L;\n\tstruct table * tbl;\n\tint string_index;\n};\n\nstruct ctrl {\n\tstruct table * root;\n\tstruct table * update;\n};\n\nstatic int\ncountsize(lua_State *L, int sizearray) {\n\tint n = 0;\n\tlua_pushnil(L);\n\twhile (lua_next(L, 1) != 0) {\n\t\tint type = lua_type(L, -2);\n\t\t++n;\n\t\tif (type == LUA_TNUMBER) {\n\t\t\tif (!lua_isinteger(L, -2)) {\n\t\t\t\tluaL_error(L, \"Invalid key %f\", lua_tonumber(L, -2));\n\t\t\t}\n\t\t\tlua_Integer nkey = lua_tointeger(L, -2);\n\t\t\tif (nkey > 0 && nkey <= sizearray) {\n\t\t\t\t--n;\n\t\t\t}\n\t\t} else if (type != LUA_TSTRING && type != LUA_TTABLE) {\n\t\t\tluaL_error(L, \"Invalid key type %s\", lua_typename(L, type));\n\t\t}\n\t\tlua_pop(L, 1);\n\t}\n\n\treturn n;\n}\n\nstatic uint32_t\ncalchash(const char * str, size_t l) {\n\tuint32_t h = (uint32_t)l;\n\tsize_t l1;\n\tsize_t step = (l >> 5) + 1;\n\tfor (l1 = l; l1 >= step; l1 -= step) {\n\t\th = h ^ ((h<<5) + (h>>2) + (uint8_t)(str[l1 - 1]));\n\t}\n\treturn h;\n}\n\nstatic int\nstringindex(struct context *ctx, const char * str, size_t sz) {\n\tlua_State *L = ctx->L;\n\tlua_pushlstring(L, str, sz);\n\tlua_pushvalue(L, -1);\n\tlua_rawget(L, 1);\n\tint index;\n\t// stringmap(1) str index\n\tif (lua_isnil(L, -1)) {\n\t\tindex = ++ctx->string_index;\n\t\tlua_pop(L, 1);\n\t\tlua_pushinteger(L, index);\n\t\tlua_rawset(L, 1);\n\t} else {\n\t\tindex = lua_tointeger(L, -1);\n\t\tlua_pop(L, 2);\n\t}\n\treturn index;\n}\n\nstatic int convtable(lua_State *L);\n\nstatic void\nsetvalue(struct context * ctx, lua_State *L, int index, struct node *n) {\n\tint vt = lua_type(L, index);\n\tswitch(vt) {\n\tcase LUA_TNIL:\n\t\tn->valuetype = VALUETYPE_NIL;\n\t\tbreak;\n\tcase LUA_TNUMBER:\n\t\tif (lua_isinteger(L, index)) {\n\t\t\tn->v.d = lua_tointeger(L, index);\n\t\t\tn->valuetype = VALUETYPE_INTEGER;\n\t\t} else {\n\t\t\tn->v.n = lua_tonumber(L, index);\n\t\t\tn->valuetype = VALUETYPE_REAL;\n\t\t}\n\t\tbreak;\n\tcase LUA_TSTRING: {\n\t\tsize_t sz = 0;\n\t\tconst char * str = lua_tolstring(L, index, &sz);\n\t\tn->v.string = stringindex(ctx, str, sz);\n\t\tn->valuetype = VALUETYPE_STRING;\n\t\tbreak;\n\t}\n\tcase LUA_TBOOLEAN:\n\t\tn->v.boolean = lua_toboolean(L, index);\n\t\tn->valuetype = VALUETYPE_BOOLEAN;\n\t\tbreak;\n\tcase LUA_TTABLE: {\n\t\tstruct table *tbl = ctx->tbl;\n\t\tctx->tbl = (struct table *)malloc(sizeof(struct table));\n\t\tif (ctx->tbl == NULL) {\n\t\t\tctx->tbl = tbl;\n\t\t\tluaL_error(L, \"memory error\");\n\t\t\t// never get here\n\t\t}\n\t\tmemset(ctx->tbl, 0, sizeof(struct table));\n\t\tint absidx = lua_absindex(L, index);\n\n\t\tlua_pushcfunction(L, convtable);\n\t\tlua_pushvalue(L, absidx);\n\t\tlua_pushlightuserdata(L, ctx);\n\n\t\tlua_call(L, 2, 0);\n\n\t\tn->v.tbl = ctx->tbl;\n\t\tn->valuetype = VALUETYPE_TABLE;\n\n\t\tctx->tbl = tbl;\n\n\t\tbreak;\n\t}\n\tdefault:\n\t\tluaL_error(L, \"Unsupport value type %s\", lua_typename(L, vt));\n\t\tbreak;\n\t}\n}\n\nstatic void\nsetarray(struct context *ctx, lua_State *L, int index, int key) {\n\tstruct node n;\n\tsetvalue(ctx, L, index, &n);\n\tstruct table *tbl = ctx->tbl;\n\t--key;\t// base 0\n\ttbl->arraytype[key] = n.valuetype;\n\ttbl->array[key] = n.v;\n}\n\nstatic int\nishashkey(struct context * ctx, lua_State *L, int index, int *key, uint32_t *keyhash, int *keytype) {\n\tint sizearray = ctx->tbl->sizearray;\n\tint kt = lua_type(L, index);\n\tif (kt == LUA_TNUMBER) {\n\t\t*key = lua_tointeger(L, index);\n\t\tif (*key > 0 && *key <= sizearray) {\n\t\t\treturn 0;\n\t\t}\n\t\t*keyhash = (uint32_t)*key;\n\t\t*keytype = KEYTYPE_INTEGER;\n\t} else {\n\t\tsize_t sz = 0;\n\t\tconst char * s = lua_tolstring(L, index, &sz);\n\t\t*keyhash = calchash(s, sz);\n\t\t*key = stringindex(ctx, s, sz);\n\t\t*keytype = KEYTYPE_STRING;\n\t}\n\treturn 1;\n}\n\nstatic void\nfillnocolliding(lua_State *L, struct context *ctx) {\n\tstruct table * tbl = ctx->tbl;\n\tlua_pushnil(L);\n\twhile (lua_next(L, 1) != 0) {\n\t\tint key;\n\t\tint keytype;\n\t\tuint32_t keyhash;\n\t\tif (!ishashkey(ctx, L, -2, &key, &keyhash, &keytype)) {\n\t\t\tsetarray(ctx, L, -1, key);\n\t\t} else {\n\t\t\tstruct node * n = &tbl->hash[keyhash % tbl->sizehash];\n\t\t\tif (n->valuetype == VALUETYPE_NIL) {\n\t\t\t\tn->key = key;\n\t\t\t\tn->keytype = keytype;\n\t\t\t\tn->keyhash = keyhash;\n\t\t\t\tn->next = -1;\n\t\t\t\tn->nocolliding = 1;\n\t\t\t\tsetvalue(ctx, L, -1, n);\t// set n->v , n->valuetype\n\t\t\t}\n\t\t}\n\t\tlua_pop(L,1);\n\t}\n}\n\nstatic void\nfillcolliding(lua_State *L, struct context *ctx) {\n\tstruct table * tbl = ctx->tbl;\n\tint sizehash = tbl->sizehash;\n\tint emptyslot = 0;\n\tint i;\n\tlua_pushnil(L);\n\twhile (lua_next(L, 1) != 0) {\n\t\tint key;\n\t\tint keytype;\n\t\tuint32_t keyhash;\n\t\tif (ishashkey(ctx, L, -2, &key, &keyhash, &keytype)) {\n\t\t\tstruct node * mainpos = &tbl->hash[keyhash % tbl->sizehash];\n\t\t\tif (!(mainpos->keytype == keytype && mainpos->key == key)) {\n\t\t\t\t// the key has not insert\n\t\t\t\tstruct node * n = NULL;\n\t\t\t\tfor (i=emptyslot;i<sizehash;i++) {\n\t\t\t\t\tif (tbl->hash[i].valuetype == VALUETYPE_NIL) {\n\t\t\t\t\t\tn = &tbl->hash[i];\n\t\t\t\t\t\temptyslot = i + 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tassert(n);\n\t\t\t\tn->next = mainpos->next;\n\t\t\t\tmainpos->next = n - tbl->hash;\n\t\t\t\tmainpos->nocolliding = 0;\n\t\t\t\tn->key = key;\n\t\t\t\tn->keytype = keytype;\n\t\t\t\tn->keyhash = keyhash;\n\t\t\t\tn->nocolliding = 0;\n\t\t\t\tsetvalue(ctx, L, -1, n);\t// set n->v , n->valuetype\n\t\t\t}\n\t\t}\n\t\tlua_pop(L,1);\n\t}\n}\n\n// table need convert\n// struct context * ctx\nstatic int\nconvtable(lua_State *L) {\n\tint i;\n\tstruct context *ctx = lua_touserdata(L,2);\n\tstruct table *tbl = ctx->tbl;\n\n\ttbl->L = ctx->L;\n\n\tint sizearray = lua_rawlen(L, 1);\n\tif (sizearray) {\n\t\ttbl->arraytype = (uint8_t *)malloc(sizearray * sizeof(uint8_t));\n\t\tif (tbl->arraytype == NULL) {\n\t\t\tgoto memerror;\n\t\t}\n\t\tfor (i=0;i<sizearray;i++) {\n\t\t\ttbl->arraytype[i] = VALUETYPE_NIL;\n\t\t}\n\t\ttbl->array = (union value *)malloc(sizearray * sizeof(union value));\n\t\tif (tbl->array == NULL) {\n\t\t\tgoto memerror;\n\t\t}\n\t\ttbl->sizearray = sizearray;\n\t}\n\tint sizehash = countsize(L, sizearray);\n\tif (sizehash) {\n\t\ttbl->hash = (struct node *)malloc(sizehash * sizeof(struct node));\n\t\tif (tbl->hash == NULL) {\n\t\t\tgoto memerror;\n\t\t}\n\t\tfor (i=0;i<sizehash;i++) {\n\t\t\ttbl->hash[i].valuetype = VALUETYPE_NIL;\n\t\t\ttbl->hash[i].nocolliding = 0;\n\t\t\ttbl->hash[i].next = -1;\n\t\t}\n\t\ttbl->sizehash = sizehash;\n\n\t\tfillnocolliding(L, ctx);\n\t\tfillcolliding(L, ctx);\n\t} else {\n\t\tint i;\n\t\tfor (i=1;i<=sizearray;i++) {\n\t\t\tlua_rawgeti(L, 1, i);\n\t\t\tsetarray(ctx, L, -1, i);\n\t\t\tlua_pop(L,1);\n\t\t}\n\t}\n\n\treturn 0;\nmemerror:\n\treturn luaL_error(L, \"memory error\");\n}\n\nstatic void\ndelete_tbl(struct table *tbl) {\n\tint i;\n\tfor (i=0;i<tbl->sizearray;i++) {\n\t\tif (tbl->arraytype[i] == VALUETYPE_TABLE) {\n\t\t\tdelete_tbl(tbl->array[i].tbl);\n\t\t}\n\t}\n\tfor (i=0;i<tbl->sizehash;i++) {\n\t\tif (tbl->hash[i].valuetype == VALUETYPE_TABLE) {\n\t\t\tdelete_tbl(tbl->hash[i].v.tbl);\n\t\t}\n\t}\n\tfree(tbl->arraytype);\n\tfree(tbl->array);\n\tfree(tbl->hash);\n\tfree(tbl);\n}\n\nstatic int\npconv(lua_State *L) {\n\tstruct context *ctx = lua_touserdata(L,1);\n\tlua_State * pL = lua_touserdata(L, 2);\n\tint ret;\n\n\tlua_settop(L, 0);\n\n\t// init L (may throw memory error)\n\t// create a table for string map\n\tlua_newtable(L);\n\n\tlua_pushcfunction(pL, convtable);\n\tlua_pushvalue(pL,1);\n\tlua_pushlightuserdata(pL, ctx);\n\n\tret = lua_pcall(pL, 2, 0, 0);\n\tif (ret != LUA_OK) {\n\t\tsize_t sz = 0;\n\t\tconst char * error = lua_tolstring(pL, -1, &sz);\n\t\tlua_pushlstring(L, error, sz);\n\t\tlua_error(L);\n\t\t// never get here\n\t}\n\n\tluaL_checkstack(L, ctx->string_index + 3, NULL);\n\tlua_settop(L,1);\n\n\treturn 1;\n}\n\nstatic void\nconvert_stringmap(struct context *ctx, struct table *tbl) {\n\tlua_State *L = ctx->L;\n\tlua_checkstack(L, ctx->string_index + LUA_MINSTACK);\n\tlua_settop(L, ctx->string_index + 1);\n\tlua_pushvalue(L, 1);\n\tstruct state * s = lua_newuserdatauv(L, sizeof(*s), 1);\n\ts->dirty = 0;\n\tATOM_INIT(&s->ref , 0);\n\ts->root = tbl;\n\tlua_replace(L, 1);\n\tlua_replace(L, -2);\n\n\tlua_pushnil(L);\n\t// ... stringmap nil\n\twhile (lua_next(L, -2) != 0) {\n\t\tint idx = lua_tointeger(L, -1);\n\t\tlua_pop(L, 1);\n\t\tlua_pushvalue(L, -1);\n\t\tlua_replace(L, idx);\n\t}\n\n\tlua_pop(L, 1);\n\n\tlua_gc(L, LUA_GCCOLLECT, 0);\n}\n\nstatic int\nlnewconf(lua_State *L) {\n\tint ret;\n\tstruct context ctx;\n\tstruct table * tbl = NULL;\n\tluaL_checktype(L,1,LUA_TTABLE);\n\tctx.L = luaL_newstate();\n\tctx.tbl = NULL;\n\tctx.string_index = 1;\t// 1 reserved for dirty flag\n\tif (ctx.L == NULL) {\n\t\tlua_pushliteral(L, \"memory error\");\n\t\tgoto error;\n\t}\n\ttbl = (struct table *)malloc(sizeof(struct table));\n\tif (tbl == NULL) {\n\t\t// lua_pushliteral may fail because of memory error, close first.\n\t\tlua_close(ctx.L);\n\t\tctx.L = NULL;\n\t\tlua_pushliteral(L, \"memory error\");\n\t\tgoto error;\n\t}\n\tmemset(tbl, 0, sizeof(struct table));\n\tctx.tbl = tbl;\n\n\tlua_pushcfunction(ctx.L, pconv);\n\tlua_pushlightuserdata(ctx.L , &ctx);\n\tlua_pushlightuserdata(ctx.L , L);\n\n\tret = lua_pcall(ctx.L, 2, 1, 0);\n\n\tif (ret != LUA_OK) {\n\t\tsize_t sz = 0;\n\t\tconst char * error = lua_tolstring(ctx.L, -1, &sz);\n\t\tlua_pushlstring(L, error, sz);\n\t\tgoto error;\n\t}\n\n\tconvert_stringmap(&ctx, tbl);\n\n\tlua_pushlightuserdata(L, tbl);\t\n\n\treturn 1;\nerror:\n\tif (ctx.L) {\n\t\tlua_close(ctx.L);\n\t}\n\tif (tbl) {\n\t\tdelete_tbl(tbl);\n\t}\n\tlua_error(L);\n\treturn -1;\n}\n\nstatic struct table *\nget_table(lua_State *L, int index) {\n\tstruct table *tbl = lua_touserdata(L,index);\n\tif (tbl == NULL) {\n\t\tluaL_error(L, \"Need a conf object\");\n\t}\n\treturn tbl;\n}\n\nstatic int\nldeleteconf(lua_State *L) {\n\tstruct table *tbl = get_table(L,1);\n\tlua_close(tbl->L);\n\tdelete_tbl(tbl);\n\treturn 0;\n}\n\nstatic void\npushvalue(lua_State *L, lua_State *sL, uint8_t vt, union value *v) {\n\tswitch(vt) {\n\tcase VALUETYPE_REAL:\n\t\tlua_pushnumber(L, v->n);\n\t\tbreak;\n\tcase VALUETYPE_INTEGER:\n\t\tlua_pushinteger(L, v->d);\n\t\tbreak;\n\tcase VALUETYPE_STRING: {\n\t\tsize_t sz = 0;\n\t\tconst char *str = lua_tolstring(sL, v->string, &sz);\n\t\tlua_pushlstring(L, str, sz);\n\t\tbreak;\n\t}\n\tcase VALUETYPE_BOOLEAN:\n\t\tlua_pushboolean(L, v->boolean);\n\t\tbreak;\n\tcase VALUETYPE_TABLE:\n\t\tlua_pushlightuserdata(L, v->tbl);\n\t\tbreak;\n\tdefault:\n\t\tlua_pushnil(L);\n\t\tbreak;\n\t}\n}\n\nstatic struct node *\nlookup_key(struct table *tbl, uint32_t keyhash, int key, int keytype, const char *str, size_t sz) {\n\tif (tbl->sizehash == 0)\n\t\treturn NULL;\n\tstruct node *n = &tbl->hash[keyhash % tbl->sizehash];\n\tif (keyhash != n->keyhash && n->nocolliding)\n\t\treturn NULL;\n\tfor (;;) {\n\t\tif (keyhash == n->keyhash) {\n\t\t\tif (n->keytype == KEYTYPE_INTEGER) {\n\t\t\t\tif (keytype == KEYTYPE_INTEGER && n->key == key) {\n\t\t\t\t\treturn n;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// n->keytype == KEYTYPE_STRING\n\t\t\t\tif (keytype == KEYTYPE_STRING) {\n\t\t\t\t\tsize_t sz2 = 0;\n\t\t\t\t\tconst char * str2 = lua_tolstring(tbl->L, n->key, &sz2);\n\t\t\t\t\tif (sz == sz2 && memcmp(str,str2,sz) == 0) {\n\t\t\t\t\t\treturn n;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (n->next < 0) {\n\t\t\treturn NULL;\n\t\t}\n\t\tn = &tbl->hash[n->next];\t\t\n\t}\n}\n\nstatic int\nlindexconf(lua_State *L) {\n\tstruct table *tbl = get_table(L,1);\n\tint kt = lua_type(L,2);\n\tuint32_t keyhash;\n\tint key = 0;\n\tint keytype;\n\tsize_t sz = 0;\n\tconst char * str = NULL;\n\tif (kt == LUA_TNIL) {\n\t\treturn 0;\n\t} else if (kt == LUA_TNUMBER) {\n\t\tif (!lua_isinteger(L, 2)) {\n\t\t\treturn luaL_error(L, \"Invalid key %f\", lua_tonumber(L, 2));\n\t\t}\n\t\tkey = (int)lua_tointeger(L, 2);\n\t\tif (key > 0 && key <= tbl->sizearray) {\n\t\t\t--key;\n\t\t\tpushvalue(L, tbl->L, tbl->arraytype[key], &tbl->array[key]);\n\t\t\treturn 1;\n\t\t}\n\t\tkeytype = KEYTYPE_INTEGER;\n\t\tkeyhash = (uint32_t)key;\n\t} else {\n\t\tstr = luaL_checklstring(L, 2, &sz);\n\t\tkeyhash = calchash(str, sz);\n\t\tkeytype = KEYTYPE_STRING;\n\t}\n\n\tstruct node *n = lookup_key(tbl, keyhash, key, keytype, str, sz);\n\tif (n) {\n\t\tpushvalue(L, tbl->L, n->valuetype, &n->v);\n\t\treturn 1;\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nstatic void\npushkey(lua_State *L, lua_State *sL, struct node *n) {\n\tif (n->keytype == KEYTYPE_INTEGER) {\n\t\tlua_pushinteger(L, n->key);\n\t} else {\n\t\tsize_t sz = 0;\n\t\tconst char * str = lua_tolstring(sL, n->key, &sz);\n\t\tlua_pushlstring(L, str, sz);\n\t}\n}\n\nstatic int\npushfirsthash(lua_State *L, struct table * tbl) {\n\tif (tbl->sizehash) {\n\t\tpushkey(L, tbl->L, &tbl->hash[0]);\n\t\treturn 1;\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nstatic int\nlnextkey(lua_State *L) {\n\tstruct table *tbl = get_table(L,1);\n\tif (lua_isnoneornil(L,2)) {\n\t\tif (tbl->sizearray > 0) {\n\t\t\tint i;\n\t\t\tfor (i=0;i<tbl->sizearray;i++) {\n\t\t\t\tif (tbl->arraytype[i] != VALUETYPE_NIL) {\n\t\t\t\t\tlua_pushinteger(L, i+1);\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn pushfirsthash(L, tbl);\n\t}\n\tint kt = lua_type(L,2);\n\tuint32_t keyhash;\n\tint key = 0;\n\tint keytype;\n\tsize_t sz=0;\n\tconst char *str = NULL;\n\tint sizearray = tbl->sizearray;\n\tif (kt == LUA_TNUMBER) {\n\t\tif (!lua_isinteger(L, 2)) {\n\t\t\treturn 0;\n\t\t}\n\t\tkey = (int)lua_tointeger(L, 2);\n\t\tif (key > 0 && key <= sizearray) {\n\t\t\tlua_Integer i;\n\t\t\tfor (i=key;i<sizearray;i++) {\n\t\t\t\tif (tbl->arraytype[i] != VALUETYPE_NIL) {\n\t\t\t\t\tlua_pushinteger(L, i+1);\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn pushfirsthash(L, tbl);\n\t\t}\n\t\tkeyhash = (uint32_t)key;\n\t\tkeytype = KEYTYPE_INTEGER;\n\t} else {\n\t\tstr = luaL_checklstring(L, 2, &sz);\n\t\tkeyhash = calchash(str, sz);\n\t\tkeytype = KEYTYPE_STRING;\n\t}\n\n\tstruct node *n = lookup_key(tbl, keyhash, key, keytype, str, sz);\n\tif (n) {\n\t\t++n;\n\t\tint index = n-tbl->hash;\n\t\tif (index == tbl->sizehash) {\n\t\t\treturn 0;\n\t\t}\n\t\tpushkey(L, tbl->L, n);\n\t\treturn 1;\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nstatic int\nllen(lua_State *L) {\n\tstruct table *tbl = get_table(L,1);\n\tlua_pushinteger(L, tbl->sizearray);\n\treturn 1;\n}\n\nstatic int\nlhashlen(lua_State *L) {\n\tstruct table *tbl = get_table(L,1);\n\tlua_pushinteger(L, tbl->sizehash);\n\treturn 1;\n}\n\nstatic int\nreleaseobj(lua_State *L) {\n\tstruct ctrl *c = lua_touserdata(L, 1);\n\tstruct table *tbl = c->root;\n\tstruct state *s = lua_touserdata(tbl->L, 1);\n\tATOM_FDEC(&s->ref);\n\tc->root = NULL;\n\tc->update = NULL;\n\n\treturn 0;\n}\n\nstatic int\nlboxconf(lua_State *L) {\n\tstruct table * tbl = get_table(L,1);\t\n\tstruct state * s = lua_touserdata(tbl->L, 1);\n\tATOM_FINC(&s->ref);\n\n\tstruct ctrl * c = lua_newuserdatauv(L, sizeof(*c), 1);\n\tc->root = tbl;\n\tc->update = NULL;\n\tif (luaL_newmetatable(L, \"confctrl\")) {\n\t\tlua_pushcfunction(L, releaseobj);\n\t\tlua_setfield(L, -2, \"__gc\");\n\t}\n\tlua_setmetatable(L, -2);\n\n\treturn 1;\n}\n\nstatic int\nlmarkdirty(lua_State *L) {\n\tstruct table *tbl = get_table(L,1);\n\tstruct state * s = lua_touserdata(tbl->L, 1);\n\ts->dirty = 1;\n\treturn 0;\n}\n\nstatic int\nlisdirty(lua_State *L) {\n\tstruct table *tbl = get_table(L,1);\n\tstruct state * s = lua_touserdata(tbl->L, 1);\n\tint d = s->dirty;\n\tlua_pushboolean(L, d);\n\t\n\treturn 1;\n}\n\nstatic int\nlgetref(lua_State *L) {\n\tstruct table *tbl = get_table(L,1);\n\tstruct state * s = lua_touserdata(tbl->L, 1);\n\tlua_pushinteger(L , ATOM_LOAD(&s->ref));\n\n\treturn 1;\n}\n\nstatic int\nlincref(lua_State *L) {\n\tstruct table *tbl = get_table(L,1);\n\tstruct state * s = lua_touserdata(tbl->L, 1);\n\tint ref = ATOM_FINC(&s->ref)+1;\n\tlua_pushinteger(L , ref);\n\n\treturn 1;\n}\n\nstatic int\nldecref(lua_State *L) {\n\tstruct table *tbl = get_table(L,1);\n\tstruct state * s = lua_touserdata(tbl->L, 1);\n\tint ref = ATOM_FDEC(&s->ref)-1;\n\tlua_pushinteger(L , ref);\n\n\treturn 1;\n}\n\nstatic int\nlneedupdate(lua_State *L) {\n\tstruct ctrl * c = lua_touserdata(L, 1);\n\tif (c->update) {\n\t\tlua_pushlightuserdata(L, c->update);\n\t\tlua_getiuservalue(L, 1, 1);\n\t\treturn 2;\n\t}\n\treturn 0;\n}\n\nstatic int\nlupdate(lua_State *L) {\n\tluaL_checktype(L, 1, LUA_TUSERDATA);\n\tluaL_checktype(L, 2, LUA_TLIGHTUSERDATA);\n\tluaL_checktype(L, 3, LUA_TTABLE);\n\tstruct ctrl * c= lua_touserdata(L, 1);\n\tstruct table *n = lua_touserdata(L, 2);\n\tif (c->root == n) {\n\t\treturn luaL_error(L, \"You should update a new object\");\n\t}\n\tlua_settop(L, 3);\n\tlua_setiuservalue(L, 1, 1);\n\tc->update = n;\n\n\treturn 0;\n}\n\nLUAMOD_API int\nluaopen_skynet_sharedata_core(lua_State *L) {\n\tluaL_Reg l[] = {\n\t\t// used by host\n\t\t{ \"new\", lnewconf },\n\t\t{ \"delete\", ldeleteconf },\n\t\t{ \"markdirty\", lmarkdirty },\n\t\t{ \"getref\", lgetref },\n\t\t{ \"incref\", lincref },\n\t\t{ \"decref\", ldecref },\n\n\t\t// used by client\n\t\t{ \"box\", lboxconf },\n\t\t{ \"index\", lindexconf },\n\t\t{ \"nextkey\", lnextkey },\n\t\t{ \"len\", llen },\n\t\t{ \"hashlen\", lhashlen },\n\t\t{ \"isdirty\", lisdirty },\n\t\t{ \"needupdate\", lneedupdate },\n\t\t{ \"update\", lupdate },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_checkversion(L);\n\tluaL_newlib(L, l);\n\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-sharetable.c",
    "content": "#define LUA_LIB\n\n#include <lua.h>\n#include <lauxlib.h>\n#include <lualib.h>\n\n#include \"lgc.h\"\n\n#ifdef makeshared\n\nstatic void\nmark_shared(lua_State *L) {\n\tif (lua_type(L, -1) != LUA_TTABLE) {\n\t\tluaL_error(L, \"Not a table, it's a %s.\", lua_typename(L, lua_type(L, -1)));\n\t}\n\tTable * t = (Table *)lua_topointer(L, -1);\n\tif (isshared(t))\n\t\treturn;\n\tmakeshared(t);\n\tluaL_checkstack(L, 4, NULL);\n\tif (lua_getmetatable(L, -1)) {\n\t\tluaL_error(L, \"Can't share metatable\");\n\t}\n\tlua_pushnil(L);\n\twhile (lua_next(L, -2) != 0) {\n\t\tint i;\n\t\tfor (i=0;i<2;i++) {\n\t\t\tint idx = -i-1;\n\t\t\tint t = lua_type(L, idx);\n\t\t\tswitch (t) {\n\t\t\tcase LUA_TTABLE:\n\t\t\t\tmark_shared(L);\n\t\t\t\tbreak;\n\t\t\tcase LUA_TNUMBER:\n\t\t\tcase LUA_TBOOLEAN:\n\t\t\tcase LUA_TLIGHTUSERDATA:\n\t\t\t\tbreak;\n\t\t\tcase LUA_TFUNCTION:\n\t\t\t\tif (lua_getupvalue(L, idx, 1) != NULL) {\n\t\t\t\t\tluaL_error(L, \"Invalid function with upvalue\");\n\t\t\t\t} else if (!lua_iscfunction(L, idx)) {\n\t\t\t\t\tLClosure *f = (LClosure *)lua_topointer(L, idx);\n\t\t\t\t\tmakeshared(f);\n\t\t\t\t\tlua_sharefunction(L, idx);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LUA_TSTRING:\n\t\t\t\tlua_sharestring(L, idx);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tluaL_error(L, \"Invalid type [%s]\", lua_typename(L, t));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tlua_pop(L, 1);\n\t}\n}\n\nstatic int\nlis_sharedtable(lua_State* L) {\n\tint b = 0;\n\tif(lua_type(L, 1) == LUA_TTABLE) {\n\t\tTable * t = (Table *)lua_topointer(L, 1);\n\t\tb = isshared(t);\n\t}\n\tlua_pushboolean(L, b);\n\treturn 1;\n}\n\nstatic int\nmake_matrix(lua_State *L) {\n\t// turn off gc , because marking shared will prevent gc mark.\n\tlua_gc(L, LUA_GCSTOP, 0);\n\tmark_shared(L);\n\tTable * t = (Table *)lua_topointer(L, -1);\n\tlua_pushlightuserdata(L, t);\n\treturn 1;\n}\n\nstatic int\nclone_table(lua_State *L) {\n\tlua_clonetable(L, lua_touserdata(L, 1));\n\n\treturn 1;\n}\n\nstatic int\nlco_stackvalues(lua_State* L) {\n    lua_State *cL = lua_tothread(L, 1);\n    luaL_argcheck(L, cL, 1, \"thread expected\");\n    int n = 0;\n    if(cL != L) {\n        luaL_checktype(L, 2, LUA_TTABLE);\n        n = lua_gettop(cL);\n        if(n > 0) {\n            luaL_checkstack(L, n+1, NULL);\n            int top = lua_gettop(L);\n            lua_xmove(cL, L, n);\n            int i=0;\n            for(i=1; i<=n; i++) {\n                lua_pushvalue(L, top+i);\n                lua_seti(L, 2, i);\n            }\n            lua_xmove(L, cL, n);\n        }\n    }\n\n    lua_pushinteger(L, n);\n    return 1;\n}\n\n\nstruct state_ud {\n\tlua_State *L;\n};\n\nstatic int\nclose_state(lua_State *L) {\n\tstruct state_ud *ud = (struct state_ud *)luaL_checkudata(L, 1, \"BOXMATRIXSTATE\");\n\tif (ud->L) {\n\t\tlua_close(ud->L);\n\t\tud->L = NULL;\n\t}\n\treturn 0;\n}\n\nstatic int\nget_matrix(lua_State *L) {\n\tstruct state_ud *ud = (struct state_ud *)luaL_checkudata(L, 1, \"BOXMATRIXSTATE\");\n\tif (ud->L) {\n\t\tconst void * v = lua_topointer(ud->L, 1);\n\t\tlua_pushlightuserdata(L, (void *)v);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic int\nget_size(lua_State *L) {\n\tstruct state_ud *ud = (struct state_ud *)luaL_checkudata(L, 1, \"BOXMATRIXSTATE\");\n\tif (ud->L) {\n\t\tlua_Integer sz = lua_gc(ud->L, LUA_GCCOUNT, 0);\n\t\tsz *= 1024;\n\t\tsz += lua_gc(ud->L, LUA_GCCOUNTB, 0);\n\t\tlua_pushinteger(L, sz);\n\t} else {\n\t\tlua_pushinteger(L, 0);\n\t}\n\treturn 1;\n}\n\n\nstatic int\nbox_state(lua_State *L, lua_State *mL) {\n\tstruct state_ud *ud = (struct state_ud *)lua_newuserdatauv(L, sizeof(*ud), 0);\n\tud->L = mL;\n\tif (luaL_newmetatable(L, \"BOXMATRIXSTATE\")) {\n\t\tlua_pushvalue(L, -1);\n\t\tlua_setfield(L, -2, \"__index\");\n\t\tlua_pushcfunction(L, close_state);\n\t\tlua_setfield(L, -2, \"close\");\n\t\tlua_pushcfunction(L, get_matrix);\n\t\tlua_setfield(L, -2, \"getptr\");\n\t\tlua_pushcfunction(L, get_size);\n\t\tlua_setfield(L, -2, \"size\");\n\t}\n\tlua_setmetatable(L, -2);\n\n\treturn 1;\n}\n\nstatic int\nload_matrixfile(lua_State *L) {\n\tluaL_openlibs(L);\n\tconst char * source = (const char *)lua_touserdata(L, 1);\n\tif (source[0] == '@') {\n\t\tif (luaL_loadfilex_(L, source+1, NULL) != LUA_OK)\n\t\t\tlua_error(L);\n\t} else {\n\t\tif (luaL_loadstring(L, source) != LUA_OK)\n\t\t\tlua_error(L);\n\t}\n\tlua_replace(L, 1);\n\tif (lua_pcall(L, lua_gettop(L) - 1, 1, 0) != LUA_OK)\n\t\tlua_error(L);\n\tlua_gc(L, LUA_GCCOLLECT, 0);\n\tlua_pushcfunction(L, make_matrix);\n\tlua_insert(L, -2);\n\tlua_call(L, 1, 1);\n\treturn 1;\n}\n\nstatic int\nmatrix_from_file(lua_State *L) {\n\tlua_State *mL = lua_newstate(luaL_alloc, NULL, G(L)->seed);\n\tif (mL == NULL) {\n\t\treturn luaL_error(L, \"luaL_newstate failed\");\n\t}\n\tconst char * source = luaL_checkstring(L, 1);\n\tint top = lua_gettop(L);\n\tlua_pushcfunction(mL, load_matrixfile);\n\tlua_pushlightuserdata(mL, (void *)source);\n\tif (top > 1) {\n\t\tif (!lua_checkstack(mL, top + 1)) {\n\t\t\treturn luaL_error(L, \"Too many argument %d\", top);\n\t\t}\n\t\tint i;\n\t\tfor (i=2;i<=top;i++) {\n\t\t\tswitch(lua_type(L, i)) {\n\t\t\tcase LUA_TBOOLEAN:\n\t\t\t\tlua_pushboolean(mL, lua_toboolean(L, i));\n\t\t\t\tbreak;\n\t\t\tcase LUA_TNUMBER:\n\t\t\t\tif (lua_isinteger(L, i)) {\n\t\t\t\t\tlua_pushinteger(mL, lua_tointeger(L, i));\n\t\t\t\t} else {\n\t\t\t\t\tlua_pushnumber(mL, lua_tonumber(L, i));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LUA_TLIGHTUSERDATA:\n\t\t\t\tlua_pushlightuserdata(mL, lua_touserdata(L, i));\n\t\t\t\tbreak;\n\t\t\tcase LUA_TFUNCTION:\n\t\t\t\tif (lua_iscfunction(L, i) && lua_getupvalue(L, i, 1) == NULL) {\n\t\t\t\t\tlua_pushcfunction(mL, lua_tocfunction(L, i));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\treturn luaL_argerror(L, i, \"Only support light C function\");\n\t\t\tdefault:\n\t\t\t\treturn luaL_argerror(L, i, \"Type invalid\");\n\t\t\t}\n\t\t}\n\t}\n\tint ok = lua_pcall(mL, top, 1, 0);\n\tif (ok != LUA_OK) {\n\t\tlua_pushstring(L, lua_tostring(mL, -1));\n\t\tlua_close(mL);\n\t\tlua_error(L);\n\t}\n\treturn box_state(L, mL);\n}\n\nLUAMOD_API int\nluaopen_skynet_sharetable_core(lua_State *L) {\n\tluaL_checkversion(L);\n\tluaL_Reg l[] = {\n\t\t{ \"clone\", clone_table },\n\t\t{ \"stackvalues\", lco_stackvalues }, \n\t\t{ \"matrix\", matrix_from_file },\n\t\t{ \"is_sharedtable\", lis_sharedtable },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_newlib(L, l);\n\treturn 1;\n}\n\n#else\n\nLUAMOD_API int\nluaopen_skynet_sharetable_core(lua_State *L) {\n\treturn luaL_error(L, \"No share string table support\");\n}\n\n#endif"
  },
  {
    "path": "lualib-src/lua-skynet.c",
    "content": "#define LUA_LIB\n\n#include \"skynet.h\"\n#include \"lua-seri.h\"\n\n#define KNRM  \"\\x1B[0m\"\n#define KRED  \"\\x1B[31m\"\n\n#include <lua.h>\n#include <lauxlib.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <inttypes.h>\n\n#include <time.h>\n\n#if defined(__APPLE__)\n#include <sys/time.h>\n#endif\n\n#include \"skynet.h\"\n\n// return nsec\nstatic int64_t\nget_time() {\n#if !defined(__APPLE__) || defined(AVAILABLE_MAC_OS_X_VERSION_10_12_AND_LATER)\n\tstruct timespec ti;\n\tclock_gettime(CLOCK_MONOTONIC, &ti);\n\treturn (int64_t)1000000000 * ti.tv_sec + ti.tv_nsec;\n#else\n\tstruct timeval tv;\n\tgettimeofday(&tv, NULL);\n\treturn (int64_t)1000000000 * tv.tv_sec + tv.tv_usec * 1000;\n#endif\n}\n\nstatic int\ntraceback (lua_State *L) {\n\tconst char *msg = lua_tostring(L, 1);\n\tif (msg)\n\t\tluaL_traceback(L, L, msg, 1);\n\telse {\n\t\tlua_pushliteral(L, \"(no error message)\");\n\t}\n\treturn 1;\n}\n\nstruct callback_context {\n\tlua_State *L;\n};\n\nstatic int\n_cb(struct skynet_context * context, void * ud, int type, int session, uint32_t source, const void * msg, size_t sz) {\n\tstruct callback_context *cb_ctx = (struct callback_context *)ud;\n\tlua_State *L = cb_ctx->L;\n\tint trace = 1;\n\tint r;\n\tlua_pushvalue(L,2);\n\n\tlua_pushinteger(L, type);\n\tlua_pushlightuserdata(L, (void *)msg);\n\tlua_pushinteger(L,sz);\n\tlua_pushinteger(L, session);\n\tlua_pushinteger(L, source);\n\n\tr = lua_pcall(L, 5, 0 , trace);\n\n\tif (r == LUA_OK) {\n\t\treturn 0;\n\t}\n\tconst char * self = skynet_command(context, \"REG\", NULL);\n\tswitch (r) {\n\tcase LUA_ERRRUN:\n\t\tskynet_error(context, \"lua call [%x to %s : %d msgsz = %d] error : \" KRED \"%s\" KNRM, source , self, session, sz, lua_tostring(L,-1));\n\t\tbreak;\n\tcase LUA_ERRMEM:\n\t\tskynet_error(context, \"lua memory error : [%x to %s : %d]\", source , self, session);\n\t\tbreak;\n\tcase LUA_ERRERR:\n\t\tskynet_error(context, \"lua error in error : [%x to %s : %d]\", source , self, session);\n\t\tbreak;\n\t};\n\n\tlua_pop(L,1);\n\n\treturn 0;\n}\n\nstatic int\nforward_cb(struct skynet_context * context, void * ud, int type, int session, uint32_t source, const void * msg, size_t sz) {\n\t_cb(context, ud, type, session, source, msg, sz);\n\t// don't delete msg in forward mode.\n\treturn 1;\n}\n\nstatic void\nclear_last_context(lua_State *L) {\n\tif (lua_getfield(L, LUA_REGISTRYINDEX, \"callback_context\") == LUA_TUSERDATA) {\n\t\tlua_pushnil(L);\n\t\tlua_setiuservalue(L, -2, 2);\n\t}\n\tlua_pop(L, 1);\n}\n\nstatic int\n_cb_pre(struct skynet_context * context, void * ud, int type, int session, uint32_t source, const void * msg, size_t sz) {\n\tstruct callback_context *cb_ctx = (struct callback_context *)ud;\n\tclear_last_context(cb_ctx->L);\n\tskynet_callback(context, ud, _cb);\n\treturn _cb(context, cb_ctx, type, session, source, msg, sz);\n}\n\nstatic int\n_forward_pre(struct skynet_context *context, void *ud, int type, int session, uint32_t source, const void *msg, size_t sz) {\n\tstruct callback_context *cb_ctx = (struct callback_context *)ud;\n\tclear_last_context(cb_ctx->L);\n\tskynet_callback(context, ud, forward_cb);\n\treturn forward_cb(context, cb_ctx, type, session, source, msg, sz);\n}\n\nstatic int\nlcallback(lua_State *L) {\n\tstruct skynet_context * context = lua_touserdata(L, lua_upvalueindex(1));\n\tint forward = lua_toboolean(L, 2);\n\tluaL_checktype(L,1,LUA_TFUNCTION);\n\tlua_settop(L,1);\n\tstruct callback_context * cb_ctx = (struct callback_context *)lua_newuserdatauv(L, sizeof(*cb_ctx), 2);\n\tcb_ctx->L = lua_newthread(L);\n\tlua_pushcfunction(cb_ctx->L, traceback);\n\tlua_setiuservalue(L, -2, 1);\n\tlua_getfield(L, LUA_REGISTRYINDEX, \"callback_context\");\n\tlua_setiuservalue(L, -2, 2);\n\tlua_setfield(L, LUA_REGISTRYINDEX, \"callback_context\");\n\tlua_xmove(L, cb_ctx->L, 1);\n\n\tskynet_callback(context, cb_ctx, (forward)?(_forward_pre):(_cb_pre));\n\treturn 0;\n}\n\nstatic int\nlcommand(lua_State *L) {\n\tstruct skynet_context * context = lua_touserdata(L, lua_upvalueindex(1));\n\tconst char * cmd = luaL_checkstring(L,1);\n\tconst char * result;\n\tconst char * parm = NULL;\n\tif (lua_gettop(L) == 2) {\n\t\tparm = luaL_checkstring(L,2);\n\t}\n\n\tresult = skynet_command(context, cmd, parm);\n\tif (result) {\n\t\tlua_pushstring(L, result);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic int\nladdresscommand(lua_State *L) {\n\tstruct skynet_context * context = lua_touserdata(L, lua_upvalueindex(1));\n\tconst char * cmd = luaL_checkstring(L,1);\n\tconst char * result;\n\tconst char * parm = NULL;\n\tif (lua_gettop(L) == 2) {\n\t\tparm = luaL_checkstring(L,2);\n\t}\n\tresult = skynet_command(context, cmd, parm);\n\tif (result && result[0] == ':') {\n\t\tint i;\n\t\tuint32_t addr = 0;\n\t\tfor (i=1;result[i];i++) {\n\t\t\tint c = result[i];\n\t\t\tif (c>='0' && c<='9') {\n\t\t\t\tc = c - '0';\n\t\t\t} else if (c>='a' && c<='f') {\n\t\t\t\tc = c - 'a' + 10;\n\t\t\t} else if (c>='A' && c<='F') {\n\t\t\t\tc = c - 'A' + 10;\n\t\t\t} else {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\taddr = addr * 16 + c;\n\t\t}\n\t\tlua_pushinteger(L, addr);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic int\nlintcommand(lua_State *L) {\n\tstruct skynet_context * context = lua_touserdata(L, lua_upvalueindex(1));\n\tconst char * cmd = luaL_checkstring(L,1);\n\tconst char * result;\n\tconst char * parm = NULL;\n\tchar tmp[64];\t// for integer parm\n\tif (lua_gettop(L) == 2) {\n\t\tif (lua_isnumber(L, 2)) {\n\t\t\tint32_t n = (int32_t)luaL_checkinteger(L,2);\n\t\t\tsprintf(tmp, \"%d\", n);\n\t\t\tparm = tmp;\n\t\t} else {\n\t\t\tparm = luaL_checkstring(L,2);\n\t\t}\n\t}\n\n\tresult = skynet_command(context, cmd, parm);\n\tif (result) {\n\t\tchar *endptr = NULL;\n\t\tlua_Integer r = strtoll(result, &endptr, 0);\n\t\tif (endptr == NULL || *endptr != '\\0') {\n\t\t\t// may be real number\n\t\t\tdouble n = strtod(result, &endptr);\n\t\t\tif (endptr == NULL || *endptr != '\\0') {\n\t\t\t\treturn luaL_error(L, \"Invalid result %s\", result);\n\t\t\t} else {\n\t\t\t\tlua_pushnumber(L, n);\n\t\t\t}\n\t\t} else {\n\t\t\tlua_pushinteger(L, r);\n\t\t}\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic int\nlgenid(lua_State *L) {\n\tstruct skynet_context * context = lua_touserdata(L, lua_upvalueindex(1));\n\tint session = skynet_send(context, 0, 0, PTYPE_TAG_ALLOCSESSION , 0 , NULL, 0);\n\tlua_pushinteger(L, session);\n\treturn 1;\n}\n\nstatic const char *\nget_dest_string(lua_State *L, int index) {\n\tconst char * dest_string = lua_tostring(L, index);\n\tif (dest_string == NULL) {\n\t\tluaL_error(L, \"dest address type (%s) must be a string or number.\", lua_typename(L, lua_type(L,index)));\n\t}\n\treturn dest_string;\n}\n\nstatic int\nsend_message(lua_State *L, int source, int idx_type) {\n\tstruct skynet_context * context = lua_touserdata(L, lua_upvalueindex(1));\n\tuint32_t dest = (uint32_t)lua_tointeger(L, 1);\n\tconst char * dest_string = NULL;\n\tif (dest == 0) {\n\t\tif (lua_type(L,1) == LUA_TNUMBER) {\n\t\t\treturn luaL_error(L, \"Invalid service address 0\");\n\t\t}\n\t\tdest_string = get_dest_string(L, 1);\n\t}\n\n\tint type = luaL_checkinteger(L, idx_type+0);\n\tint session = 0;\n\tif (lua_isnil(L,idx_type+1)) {\n\t\ttype |= PTYPE_TAG_ALLOCSESSION;\n\t} else {\n\t\tsession = luaL_checkinteger(L,idx_type+1);\n\t}\n\n\tint mtype = lua_type(L,idx_type+2);\n\tswitch (mtype) {\n\tcase LUA_TSTRING: {\n\t\tsize_t len = 0;\n\t\tvoid * msg = (void *)lua_tolstring(L,idx_type+2,&len);\n\t\tif (len == 0) {\n\t\t\tmsg = NULL;\n\t\t}\n\t\tif (dest_string) {\n\t\t\tsession = skynet_sendname(context, source, dest_string, type, session , msg, len);\n\t\t} else {\n\t\t\tsession = skynet_send(context, source, dest, type, session , msg, len);\n\t\t}\n\t\tbreak;\n\t}\n\tcase LUA_TLIGHTUSERDATA: {\n\t\tvoid * msg = lua_touserdata(L,idx_type+2);\n\t\tint size = luaL_checkinteger(L,idx_type+3);\n\t\tif (dest_string) {\n\t\t\tsession = skynet_sendname(context, source, dest_string, type | PTYPE_TAG_DONTCOPY, session, msg, size);\n\t\t} else {\n\t\t\tsession = skynet_send(context, source, dest, type | PTYPE_TAG_DONTCOPY, session, msg, size);\n\t\t}\n\t\tbreak;\n\t}\n\tdefault:\n\t\tluaL_error(L, \"invalid param %s\", lua_typename(L, lua_type(L,idx_type+2)));\n\t}\n\tif (session < 0) {\n\t\tif (session == -2) {\n\t\t\t// package is too large\n\t\t\tlua_pushboolean(L, 0);\n\t\t\treturn 1;\n\t\t}\n\t\t// send to invalid address\n\t\t// todo: maybe throw an error would be better\n\t\treturn 0;\n\t}\n\tlua_pushinteger(L,session);\n\treturn 1;\n}\n\n/*\n\tuint32 address\n\t string address\n\tinteger type\n\tinteger session\n\tstring message\n\t lightuserdata message_ptr\n\t integer len\n */\nstatic int\nlsend(lua_State *L) {\n\treturn send_message(L, 0, 2);\n}\n\n/*\n\tuint32 address\n\t string address\n\tinteger source_address\n\tinteger type\n\tinteger session\n\tstring message\n\t lightuserdata message_ptr\n\t integer len\n */\nstatic int\nlredirect(lua_State *L) {\n\tuint32_t source = (uint32_t)luaL_checkinteger(L,2);\n\treturn send_message(L, source, 3);\n}\n\nstatic int\nlerror(lua_State *L) {\n\tstruct skynet_context * context = lua_touserdata(L, lua_upvalueindex(1));\n\tint n = lua_gettop(L);\n\tif (n <= 1) {\n\t\tlua_settop(L, 1);\n\t\tsize_t len;\n\t\tconst char *s = luaL_tolstring(L, 1, &len);\n\t\tskynet_error(context, \"%*s\", (int)len, s);\n\t\treturn 0;\n\t}\n\tluaL_Buffer b;\n\tluaL_buffinit(L, &b);\n\tint i;\n\tfor (i=1; i<=n; i++) {\n\t\tluaL_tolstring(L, i, NULL);\n\t\tluaL_addvalue(&b);\n\t\tif (i<n) {\n\t\t\tluaL_addchar(&b, ' ');\n\t\t}\n\t}\n\tluaL_pushresult(&b);\n\tsize_t len;\n\tconst char *s = luaL_tolstring(L, -1, &len);\n\tskynet_error(context, \"%*s\", (int)len, s);\n\treturn 0;\n}\n\nstatic int\nltostring(lua_State *L) {\n\tif (lua_isnoneornil(L,1)) {\n\t\treturn 0;\n\t}\n\tchar * msg = lua_touserdata(L,1);\n\tint sz = luaL_checkinteger(L,2);\n\tlua_pushlstring(L,msg,sz);\n\treturn 1;\n}\n\nstatic int\nlharbor(lua_State *L) {\n\tstruct skynet_context * context = lua_touserdata(L, lua_upvalueindex(1));\n\tuint32_t handle = (uint32_t)luaL_checkinteger(L,1);\n\tint harbor = 0;\n\tint remote = skynet_isremote(context, handle, &harbor);\n\tlua_pushinteger(L,harbor);\n\tlua_pushboolean(L, remote);\n\n\treturn 2;\n}\n\nstatic int\nlpackstring(lua_State *L) {\n\tluaseri_pack(L);\n\tchar * str = (char *)lua_touserdata(L, -2);\n\tint sz = lua_tointeger(L, -1);\n\tlua_pushlstring(L, str, sz);\n\tskynet_free(str);\n\treturn 1;\n}\n\nstatic int\nltrash(lua_State *L) {\n\tint t = lua_type(L,1);\n\tswitch (t) {\n\tcase LUA_TSTRING: {\n\t\tbreak;\n\t}\n\tcase LUA_TLIGHTUSERDATA: {\n\t\tvoid * msg = lua_touserdata(L,1);\n\t\tluaL_checkinteger(L,2);\n\t\tskynet_free(msg);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tluaL_error(L, \"skynet.trash invalid param %s\", lua_typename(L,t));\n\t}\n\n\treturn 0;\n}\n\nstatic int\nlnow(lua_State *L) {\n\tuint64_t ti = skynet_now();\n\tlua_pushinteger(L, ti);\n\treturn 1;\n}\n\nstatic int\nlhpc(lua_State *L) {\n\tlua_pushinteger(L, get_time());\n\treturn 1;\n}\n\n#define MAX_LEVEL 3\n\nstruct source_info {\n\tconst char * source;\n\tint line;\n};\n\n/*\n\tstring tag\n\tstring userstring\n\tthread co (default nil/current L)\n\tinteger level (default nil)\n */\nstatic int\nltrace(lua_State *L) {\n\tstruct skynet_context * context = lua_touserdata(L, lua_upvalueindex(1));\n\tconst char * tag = luaL_checkstring(L, 1);\n\tconst char * user = luaL_checkstring(L, 2);\n\tif (!lua_isnoneornil(L, 3)) {\n\t\tlua_State * co = L;\n\t\tint level;\n\t\tif (lua_isthread(L, 3)) {\n\t\t\tco = lua_tothread (L, 3);\n\t\t\tlevel = luaL_optinteger(L, 4, 1);\n\t\t} else {\n\t\t\tlevel = luaL_optinteger(L, 3, 1);\n\t\t}\n\t\tstruct source_info si[MAX_LEVEL];\n\t\tlua_Debug d;\n\t\tint index = 0;\n\t\tdo {\n\t\t\tif (!lua_getstack(co, level, &d))\n\t\t\t\tbreak;\n\t\t\tlua_getinfo(co, \"Sl\", &d);\n\t\t\tlevel++;\n\t\t\tsi[index].source = d.source;\n\t\t\tsi[index].line = d.currentline;\n\t\t\tif (d.currentline >= 0)\n\t\t\t\t++index;\n\t\t} while (index < MAX_LEVEL);\n\t\tswitch (index) {\n\t\tcase 1:\n\t\t\tskynet_error(context, \"<TRACE %s> %\" PRId64 \" %s : %s:%d\", tag, get_time(), user, si[0].source, si[0].line);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tskynet_error(context, \"<TRACE %s> %\" PRId64 \" %s : %s:%d %s:%d\", tag, get_time(), user,\n\t\t\t\tsi[0].source, si[0].line,\n\t\t\t\tsi[1].source, si[1].line\n\t\t\t\t);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tskynet_error(context, \"<TRACE %s> %\" PRId64 \" %s : %s:%d %s:%d %s:%d\", tag, get_time(), user,\n\t\t\t\tsi[0].source, si[0].line,\n\t\t\t\tsi[1].source, si[1].line,\n\t\t\t\tsi[2].source, si[2].line\n\t\t\t\t);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tskynet_error(context, \"<TRACE %s> %\" PRId64 \" %s\", tag, get_time(), user);\n\t\t\tbreak;\n\t\t}\n\t\treturn 0;\n\t}\n\tskynet_error(context, \"<TRACE %s> %\" PRId64 \" %s\", tag, get_time(), user);\n\treturn 0;\n}\n\nLUAMOD_API int\nluaopen_skynet_core(lua_State *L) {\n\tluaL_checkversion(L);\n\n\tluaL_Reg l[] = {\n\t\t{ \"send\" , lsend },\n\t\t{ \"genid\", lgenid },\n\t\t{ \"redirect\", lredirect },\n\t\t{ \"command\" , lcommand },\n\t\t{ \"intcommand\", lintcommand },\n\t\t{ \"addresscommand\", laddresscommand },\n\t\t{ \"error\", lerror },\n\t\t{ \"harbor\", lharbor },\n\t\t{ \"callback\", lcallback },\n\t\t{ \"trace\", ltrace },\n\t\t{ NULL, NULL },\n\t};\n\n\t// functions without skynet_context\n\tluaL_Reg l2[] = {\n\t\t{ \"tostring\", ltostring },\n\t\t{ \"pack\", luaseri_pack },\n\t\t{ \"unpack\", luaseri_unpack },\n\t\t{ \"packstring\", lpackstring },\n\t\t{ \"trash\" , ltrash },\n\t\t{ \"now\", lnow },\n\t\t{ \"hpc\", lhpc },\t// getHPCounter\n\t\t{ NULL, NULL },\n\t};\n\n\tlua_createtable(L, 0, sizeof(l)/sizeof(l[0]) + sizeof(l2)/sizeof(l2[0]) -2);\n\n\tlua_getfield(L, LUA_REGISTRYINDEX, \"skynet_context\");\n\tstruct skynet_context *ctx = lua_touserdata(L,-1);\n\tif (ctx == NULL) {\n\t\treturn luaL_error(L, \"Init skynet context first\");\n\t}\n\n\n\tluaL_setfuncs(L,l,1);\n\n\tluaL_setfuncs(L,l2,0);\n\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-socket.c",
    "content": "#define LUA_LIB\n\n#include \"skynet_malloc.h\"\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <assert.h>\n\n#include <lua.h>\n#include <lauxlib.h>\n\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <netdb.h>\n#include <netinet/in.h>\n\n#include \"skynet.h\"\n#include \"skynet_socket.h\"\n\n#define BACKLOG 32\n// 2 ** 12 == 4096\n#define LARGE_PAGE_NODE 12\n#define POOL_SIZE_WARNING 32\n#define BUFFER_LIMIT (256 * 1024)\n\nstruct buffer_node {\n\tchar * msg;\n\tint sz;\n\tstruct buffer_node *next;\n};\n\nstruct socket_buffer {\n\tint size;\n\tint offset;\n\tstruct buffer_node *head;\n\tstruct buffer_node *tail;\n};\n\nstatic int\nlfreepool(lua_State *L) {\n\tstruct buffer_node * pool = lua_touserdata(L, 1);\n\tint sz = lua_rawlen(L,1) / sizeof(*pool);\n\tint i;\n\tfor (i=0;i<sz;i++) {\n\t\tstruct buffer_node *node = &pool[i];\n\t\tif (node->msg) {\n\t\t\tskynet_free(node->msg);\n\t\t\tnode->msg = NULL;\n\t\t}\n\t}\n\treturn 0;\n}\n\nstatic int\nlnewpool(lua_State *L, int sz) {\n\tstruct buffer_node * pool = lua_newuserdatauv(L, sizeof(struct buffer_node) * sz, 0);\n\tint i;\n\tfor (i=0;i<sz;i++) {\n\t\tpool[i].msg = NULL;\n\t\tpool[i].sz = 0;\n\t\tpool[i].next = &pool[i+1];\n\t}\n\tpool[sz-1].next = NULL;\n\tif (luaL_newmetatable(L, \"buffer_pool\")) {\n\t\tlua_pushcfunction(L, lfreepool);\n\t\tlua_setfield(L, -2, \"__gc\");\n\t}\n\tlua_setmetatable(L, -2);\n\treturn 1;\n}\n\nstatic int\nlnewbuffer(lua_State *L) {\n\tstruct socket_buffer * sb = lua_newuserdatauv(L, sizeof(*sb), 0);\n\tsb->size = 0;\n\tsb->offset = 0;\n\tsb->head = NULL;\n\tsb->tail = NULL;\n\t\n\treturn 1;\n}\n\n/*\n\tuserdata send_buffer\n\ttable pool\n\tlightuserdata msg\n\tint size\n\n\treturn size\n\n\tComment: The table pool record all the buffers chunk, \n\tand the first index [1] is a lightuserdata : free_node. We can always use this pointer for struct buffer_node .\n\tThe following ([2] ...)  userdatas in table pool is the buffer chunk (for struct buffer_node), \n\twe never free them until the VM closed. The size of first chunk ([2]) is 16 struct buffer_node,\n\tand the second size is 32 ... The largest size of chunk is LARGE_PAGE_NODE (4096)\n\n\tlpushbbuffer will get a free struct buffer_node from table pool, and then put the msg/size in it.\n\tlpopbuffer return the struct buffer_node back to table pool (By calling return_free_node).\n */\nstatic int\nlpushbuffer(lua_State *L) {\n\tstruct socket_buffer *sb = lua_touserdata(L,1);\n\tif (sb == NULL) {\n\t\treturn luaL_error(L, \"need buffer object at param 1\");\n\t}\n\tchar * msg = lua_touserdata(L,3);\n\tif (msg == NULL) {\n\t\treturn luaL_error(L, \"need message block at param 3\");\n\t}\n\tint pool_index = 2;\n\tluaL_checktype(L,pool_index,LUA_TTABLE);\n\tint sz = luaL_checkinteger(L,4);\n\tlua_rawgeti(L,pool_index,1);\n\tstruct buffer_node * free_node = lua_touserdata(L,-1);\t// sb poolt msg size free_node\n\tlua_pop(L,1);\n\tif (free_node == NULL) {\n\t\tint tsz = lua_rawlen(L,pool_index);\n\t\tif (tsz == 0)\n\t\t\ttsz++;\n\t\tint size = 8;\n\t\tif (tsz <= LARGE_PAGE_NODE-3) {\n\t\t\tsize <<= tsz;\n\t\t} else {\n\t\t\tsize <<= LARGE_PAGE_NODE-3;\n\t\t}\n\t\tlnewpool(L, size);\t\n\t\tfree_node = lua_touserdata(L,-1);\n\t\tlua_rawseti(L, pool_index, tsz+1);\n\t\tif (tsz > POOL_SIZE_WARNING) {\n\t\t\tskynet_error(NULL, \"Too many socket pool (%d)\", tsz);\n\t\t}\n\t}\n\tlua_pushlightuserdata(L, free_node->next);\t\n\tlua_rawseti(L, pool_index, 1);\t// sb poolt msg size\n\tfree_node->msg = msg;\n\tfree_node->sz = sz;\n\tfree_node->next = NULL;\n\n\tif (sb->head == NULL) {\n\t\tassert(sb->tail == NULL);\n\t\tsb->head = sb->tail = free_node;\n\t} else {\n\t\tsb->tail->next = free_node;\n\t\tsb->tail = free_node;\n\t}\n\tsb->size += sz;\n\n\tlua_pushinteger(L, sb->size);\n\n\treturn 1;\n}\n\nstatic void\nreturn_free_node(lua_State *L, int pool, struct socket_buffer *sb) {\n\tstruct buffer_node *free_node = sb->head;\n\tsb->offset = 0;\n\tsb->head = free_node->next;\n\tif (sb->head == NULL) {\n\t\tsb->tail = NULL;\n\t}\n\tlua_rawgeti(L,pool,1);\n\tfree_node->next = lua_touserdata(L,-1);\n\tlua_pop(L,1);\n\tskynet_free(free_node->msg);\n\tfree_node->msg = NULL;\n\n\tfree_node->sz = 0;\n\tlua_pushlightuserdata(L, free_node);\n\tlua_rawseti(L, pool, 1);\n}\n\nstatic void\npop_lstring(lua_State *L, struct socket_buffer *sb, int sz, int skip) {\n\tstruct buffer_node * current = sb->head;\n\tif (sz < current->sz - sb->offset) {\n\t\tlua_pushlstring(L, current->msg + sb->offset, sz-skip);\n\t\tsb->offset+=sz;\n\t\treturn;\n\t}\n\tif (sz == current->sz - sb->offset) {\n\t\tlua_pushlstring(L, current->msg + sb->offset, sz-skip);\n\t\treturn_free_node(L,2,sb);\n\t\treturn;\n\t}\n\n\tluaL_Buffer b;\n\tluaL_buffinitsize(L, &b, sz);\n\tfor (;;) {\n\t\tint bytes = current->sz - sb->offset;\n\t\tif (bytes >= sz) {\n\t\t\tif (sz > skip) {\n\t\t\t\tluaL_addlstring(&b, current->msg + sb->offset, sz - skip);\n\t\t\t} \n\t\t\tsb->offset += sz;\n\t\t\tif (bytes == sz) {\n\t\t\t\treturn_free_node(L,2,sb);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tint real_sz = sz - skip;\n\t\tif (real_sz > 0) {\n\t\t\tluaL_addlstring(&b, current->msg + sb->offset, (real_sz < bytes) ? real_sz : bytes);\n\t\t}\n\t\treturn_free_node(L,2,sb);\n\t\tsz-=bytes;\n\t\tif (sz==0)\n\t\t\tbreak;\n\t\tcurrent = sb->head;\n\t\tassert(current);\n\t}\n\tluaL_pushresult(&b);\n}\n\nstatic int\nlheader(lua_State *L) {\n\tsize_t len;\n\tconst uint8_t * s = (const uint8_t *)luaL_checklstring(L, 1, &len);\n\tif (len > 4 || len < 1) {\n\t\treturn luaL_error(L, \"Invalid read %s\", s);\n\t}\n\tint i;\n\tsize_t sz = 0;\n\tfor (i=0;i<(int)len;i++) {\n\t\tsz <<= 8;\n\t\tsz |= s[i];\n\t}\n\n\tlua_pushinteger(L, (lua_Integer)sz);\n\n\treturn 1;\n}\n\n/*\n\tuserdata send_buffer\n\ttable pool\n\tinteger sz \n */\nstatic int\nlpopbuffer(lua_State *L) {\n\tstruct socket_buffer * sb = lua_touserdata(L, 1);\n\tif (sb == NULL) {\n\t\treturn luaL_error(L, \"Need buffer object at param 1\");\n\t}\n\tluaL_checktype(L,2,LUA_TTABLE);\n\tint sz = luaL_checkinteger(L,3);\n\tif (sb->size < sz || sz == 0) {\n\t\tlua_pushnil(L);\n\t} else {\n\t\tpop_lstring(L,sb,sz,0);\n\t\tsb->size -= sz;\n\t}\n\tlua_pushinteger(L, sb->size);\n\n\treturn 2;\n}\n\n/*\n\tuserdata send_buffer\n\ttable pool\n */\nstatic int\nlclearbuffer(lua_State *L) {\n\tstruct socket_buffer * sb = lua_touserdata(L, 1);\n\tif (sb == NULL) {\n\t\tif (lua_isnil(L, 1)) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn luaL_error(L, \"Need buffer object at param 1\");\n\t}\n\tluaL_checktype(L,2,LUA_TTABLE);\n\twhile(sb->head) {\n\t\treturn_free_node(L,2,sb);\n\t}\n\tsb->size = 0;\n\treturn 0;\n}\n\nstatic int\nlreadall(lua_State *L) {\n\tstruct socket_buffer * sb = lua_touserdata(L, 1);\n\tif (sb == NULL) {\n\t\treturn luaL_error(L, \"Need buffer object at param 1\");\n\t}\n\tluaL_checktype(L,2,LUA_TTABLE);\n\tluaL_Buffer b;\n\tluaL_buffinit(L, &b);\n\twhile(sb->head) {\n\t\tstruct buffer_node *current = sb->head;\n\t\tluaL_addlstring(&b, current->msg + sb->offset, current->sz - sb->offset);\n\t\treturn_free_node(L,2,sb);\n\t}\n\tluaL_pushresult(&b);\n\tsb->size = 0;\n\treturn 1;\n}\n\nstatic int\nldrop(lua_State *L) {\n\tvoid * msg = lua_touserdata(L,1);\n\tluaL_checkinteger(L,2);\n\tskynet_free(msg);\n\treturn 0;\n}\n\nstatic bool\ncheck_sep(struct buffer_node * node, int from, const char *sep, int seplen) {\n\tfor (;;) {\n\t\tint sz = node->sz - from;\n\t\tif (sz >= seplen) {\n\t\t\treturn memcmp(node->msg+from,sep,seplen) == 0;\n\t\t}\n\t\tif (sz > 0) {\n\t\t\tif (memcmp(node->msg + from, sep, sz)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tnode = node->next;\n\t\tsep += sz;\n\t\tseplen -= sz;\n\t\tfrom = 0;\n\t}\n}\n\n/*\n\tuserdata send_buffer\n\ttable pool , nil for check\n\tstring sep\n */\nstatic int\nlreadline(lua_State *L) {\n\tstruct socket_buffer * sb = lua_touserdata(L, 1);\n\tif (sb == NULL) {\n\t\treturn luaL_error(L, \"Need buffer object at param 1\");\n\t}\n\t// only check\n\tbool check = !lua_istable(L, 2);\n\tsize_t seplen = 0;\n\tconst char *sep = luaL_checklstring(L,3,&seplen);\n\tint i;\n\tstruct buffer_node *current = sb->head;\n\tif (current == NULL)\n\t\treturn 0;\n\tint from = sb->offset;\n\tint bytes = current->sz - from;\n\tfor (i=0;i<=sb->size - (int)seplen;i++) {\n\t\tif (check_sep(current, from, sep, seplen)) {\n\t\t\tif (check) {\n\t\t\t\tlua_pushboolean(L,true);\n\t\t\t} else {\n\t\t\t\tpop_lstring(L, sb, i+seplen, seplen);\n\t\t\t\tsb->size -= i+seplen;\n\t\t\t}\n\t\t\treturn 1;\n\t\t}\n\t\t++from;\n\t\t--bytes;\n\t\tif (bytes == 0) {\n\t\t\tcurrent = current->next;\n\t\t\tfrom = 0;\n\t\t\tif (current == NULL)\n\t\t\t\tbreak;\n\t\t\tbytes = current->sz;\n\t\t}\n\t}\n\treturn 0;\n}\n\nstatic int\nlstr2p(lua_State *L) {\n\tsize_t sz = 0;\n\tconst char * str = luaL_checklstring(L,1,&sz);\n\tvoid *ptr = skynet_malloc(sz);\n\tmemcpy(ptr, str, sz);\n\tlua_pushlightuserdata(L, ptr);\n\tlua_pushinteger(L, (int)sz);\n\treturn 2;\n}\n\n// for skynet socket\n\n/*\n\tlightuserdata msg\n\tinteger size\n\n\treturn type n1 n2 ptr_or_string\n*/\nstatic int\nlunpack(lua_State *L) {\n\tstruct skynet_socket_message *message = lua_touserdata(L,1);\n\tint size = luaL_checkinteger(L,2);\n\n\tlua_pushinteger(L, message->type);\n\tlua_pushinteger(L, message->id);\n\tlua_pushinteger(L, message->ud);\n\tif (message->buffer == NULL) {\n\t\tlua_pushlstring(L, (char *)(message+1),size - sizeof(*message));\n\t} else {\n\t\tlua_pushlightuserdata(L, message->buffer);\n\t}\n\tif (message->type == SKYNET_SOCKET_TYPE_UDP) {\n\t\tint addrsz = 0;\n\t\tconst char * addrstring = skynet_socket_udp_address(message, &addrsz);\n\t\tif (addrstring) {\n\t\t\tlua_pushlstring(L, addrstring, addrsz);\n\t\t\treturn 5;\n\t\t}\n\t}\n\treturn 4;\n}\n\nstatic const char *\naddress_port(lua_State *L, char *tmp, const char * addr, int port_index, int *port) {\n\tconst char * host;\n\tif (lua_isnoneornil(L,port_index)) {\n\t\thost = strchr(addr, '[');\n\t\tif (host) {\n\t\t\t// is ipv6\n\t\t\t++host;\n\t\t\tconst char * sep = strchr(addr,']');\n\t\t\tif (sep == NULL) {\n\t\t\t\tluaL_error(L, \"Invalid address %s.\",addr);\n\t\t\t}\n\t\t\tmemcpy(tmp, host, sep-host);\n\t\t\ttmp[sep-host] = '\\0';\n\t\t\thost = tmp;\n\t\t\tsep = strchr(sep + 1, ':');\n\t\t\tif (sep == NULL) {\n\t\t\t\tluaL_error(L, \"Invalid address %s.\",addr);\n\t\t\t}\n\t\t\t*port = strtoul(sep+1,NULL,10);\n\t\t} else {\n\t\t\t// is ipv4\n\t\t\tconst char * sep = strchr(addr,':');\n\t\t\tif (sep == NULL) {\n\t\t\t\tluaL_error(L, \"Invalid address %s.\",addr);\n\t\t\t}\n\t\t\tmemcpy(tmp, addr, sep-addr);\n\t\t\ttmp[sep-addr] = '\\0';\n\t\t\thost = tmp;\n\t\t\t*port = strtoul(sep+1,NULL,10);\n\t\t}\n\t} else {\n\t\thost = addr;\n\t\t*port = luaL_optinteger(L,port_index, 0);\n\t}\n\treturn host;\n}\n\nstatic int\nlconnect(lua_State *L) {\n\tsize_t sz = 0;\n\tconst char * addr = luaL_checklstring(L,1,&sz);\n\tchar tmp[sz];\n\tint port = 0;\n\tconst char * host = address_port(L, tmp, addr, 2, &port);\n\tif (port == 0) {\n\t\treturn luaL_error(L, \"Invalid port\");\n\t}\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tint id = skynet_socket_connect(ctx, host, port);\n\tlua_pushinteger(L, id);\n\n\treturn 1;\n}\n\nstatic int\nlclose(lua_State *L) {\n\tint id = luaL_checkinteger(L,1);\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tskynet_socket_close(ctx, id);\n\treturn 0;\n}\n\nstatic int\nlshutdown(lua_State *L) {\n\tint id = luaL_checkinteger(L,1);\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tskynet_socket_shutdown(ctx, id);\n\treturn 0;\n}\n\nstatic int\nllisten(lua_State *L) {\n\tsize_t sz = 0;\n\tconst char * addr = luaL_checklstring(L, 1, &sz);\n\tchar tmp[sz];\n\tint port = 0;\n\tconst char * host = address_port(L, tmp, addr, 2, &port);\n\tif (port == 0) {\n\t\treturn luaL_error(L, \"Invalid port\");\n\t}\n\tint backlog = luaL_optinteger(L,3,BACKLOG);\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tint id = skynet_socket_listen(ctx, host,port,backlog);\n\tif (id < 0) {\n\t\treturn luaL_error(L, \"Listen error\");\n\t}\n\n\tlua_pushinteger(L,id);\n\treturn 1;\n}\n\nstatic size_t\ncount_size(lua_State *L, int index) {\n\tsize_t tlen = 0;\n\tint i;\n\tfor (i=1;lua_geti(L, index, i) != LUA_TNIL; ++i) {\n\t\tsize_t len;\n\t\tluaL_checklstring(L, -1, &len);\n\t\ttlen += len;\n\t\tlua_pop(L,1);\n\t}\n\tlua_pop(L,1);\n\treturn tlen;\n}\n\nstatic void\nconcat_table(lua_State *L, int index, void *buffer, size_t tlen) {\n\tchar *ptr = buffer;\n\tint i;\n\tfor (i=1;lua_geti(L, index, i) != LUA_TNIL; ++i) {\n\t\tsize_t len;\n\t\tconst char * str = lua_tolstring(L, -1, &len);\n\t\tif (str == NULL || tlen < len) {\n\t\t\tbreak;\n\t\t}\n\t\tmemcpy(ptr, str, len);\n\t\tptr += len;\n\t\ttlen -= len;\n\t\tlua_pop(L,1);\n\t}\n\tif (tlen != 0) {\n\t\tskynet_free(buffer);\n\t\tluaL_error(L, \"Invalid strings table\");\n\t}\n\tlua_pop(L,1);\n}\n\nstatic void\nget_buffer(lua_State *L, int index, struct socket_sendbuffer *buf) {\n\tvoid *buffer;\n\tswitch(lua_type(L, index)) {\n\t\tsize_t len;\n\tcase LUA_TUSERDATA:\n\t\t// lua full useobject must be a raw pointer, it can't be a socket object or a memory object.\n\t\tbuf->type = SOCKET_BUFFER_RAWPOINTER;\n\t\tbuf->buffer = lua_touserdata(L, index);\n\t\tif (lua_isinteger(L, index+1)) {\n\t\t\tbuf->sz = lua_tointeger(L, index+1);\n\t\t} else {\n\t\t\tbuf->sz = lua_rawlen(L, index);\n\t\t}\n\t\tbreak;\n\tcase LUA_TLIGHTUSERDATA: {\n\t\tint sz = -1;\n\t\tif (lua_isinteger(L, index+1)) {\n\t\t\tsz = lua_tointeger(L,index+1);\n\t\t}\n\t\tif (sz < 0) {\n\t\t\tbuf->type = SOCKET_BUFFER_OBJECT;\n\t\t} else {\n\t\t\tbuf->type = SOCKET_BUFFER_MEMORY;\n\t\t}\n\t\tbuf->buffer = lua_touserdata(L,index);\n\t\tbuf->sz = (size_t)sz;\n\t\tbreak;\n\t\t}\n\tcase LUA_TTABLE:\n\t\t// concat the table as a string\n\t\tlen = count_size(L, index);\n\t\tbuffer = skynet_malloc(len);\n\t\tconcat_table(L, index, buffer, len);\n\t\tbuf->type = SOCKET_BUFFER_MEMORY;\n\t\tbuf->buffer = buffer;\n\t\tbuf->sz = len;\n\t\tbreak;\n\tdefault:\n\t\tbuf->type = SOCKET_BUFFER_RAWPOINTER;\n\t\tbuf->buffer = luaL_checklstring(L, index, &buf->sz);\n\t\tbreak;\n\t}\n}\n\nstatic int\nlsend(lua_State *L) {\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tint id = luaL_checkinteger(L, 1);\n\tstruct socket_sendbuffer buf;\n\tbuf.id = id;\n\tget_buffer(L, 2, &buf);\n\tint err = skynet_socket_sendbuffer(ctx, &buf);\n\tlua_pushboolean(L, !err);\n\treturn 1;\n}\n\nstatic int\nlsendlow(lua_State *L) {\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tint id = luaL_checkinteger(L, 1);\n\tstruct socket_sendbuffer buf;\n\tbuf.id = id;\n\tget_buffer(L, 2, &buf);\n\tint err = skynet_socket_sendbuffer_lowpriority(ctx, &buf);\n\tlua_pushboolean(L, !err);\n\treturn 1;\n}\n\nstatic int\nlbind(lua_State *L) {\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tint fd = luaL_checkinteger(L, 1);\n\tint id = skynet_socket_bind(ctx,fd);\n\tlua_pushinteger(L,id);\n\treturn 1;\n}\n\nstatic int\nlstart(lua_State *L) {\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tint id = luaL_checkinteger(L, 1);\n\tskynet_socket_start(ctx,id);\n\treturn 0;\n}\n\nstatic int\nlpause(lua_State *L) {\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tint id = luaL_checkinteger(L, 1);\n\tskynet_socket_pause(ctx,id);\n\treturn 0;\n}\n\nstatic int\nlnodelay(lua_State *L) {\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tint id = luaL_checkinteger(L, 1);\n\tskynet_socket_nodelay(ctx,id);\n\treturn 0;\n}\n\nstatic int\nludp(lua_State *L) {\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tsize_t sz = 0;\n\tconst char * addr = lua_tolstring(L,1,&sz);\n\tchar tmp[sz];\n\tint port = 0;\n\tconst char * host = NULL;\n\tif (addr) {\n\t\thost = address_port(L, tmp, addr, 2, &port);\n\t}\n\n\tint id = skynet_socket_udp(ctx, host, port);\n\tif (id < 0) {\n\t\treturn luaL_error(L, \"udp init failed\");\n\t}\n\tlua_pushinteger(L, id);\n\treturn 1;\n}\n\nstatic int\nludp_connect(lua_State *L) {\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tint id = luaL_checkinteger(L, 1);\n\tsize_t sz = 0;\n\tconst char * addr = luaL_checklstring(L,2,&sz);\n\tchar tmp[sz];\n\tint port = 0;\n\tconst char * host = NULL;\n\tif (addr) {\n\t\thost = address_port(L, tmp, addr, 3, &port);\n\t}\n\n\tif (skynet_socket_udp_connect(ctx, id, host, port)) {\n\t\treturn luaL_error(L, \"udp connect failed\");\n\t}\n\n\treturn 0;\n}\n\nstatic int\nludp_dial(lua_State *L){\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tsize_t sz = 0;\n\tconst char * addr = luaL_checklstring(L, 1, &sz);\n\tchar tmp[sz];\n\tint port = 0;\n\tconst char * host =  address_port(L, tmp, addr, 2, &port);\n\n\tint id = skynet_socket_udp_dial(ctx, host, port);\n\tif (id < 0){\n\t\treturn luaL_error(L, \"udp dial host failed\");\n\t}\n\n\tlua_pushinteger(L, id);\n\treturn 1;\n}\n\nstatic int\nludp_listen(lua_State *L){\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tsize_t sz = 0;\n\tconst char * addr = luaL_checklstring(L, 1, &sz);\n\tchar tmp[sz];\n\n\tint port = 0;\n\tconst char * host = address_port(L, tmp, addr, 2, &port);\n\n\tint id = skynet_socket_udp_listen(ctx, host, port);\n\tif (id < 0){\n\t\treturn luaL_error(L, \"udp listen host failed\");\n\t}\n\n\tlua_pushinteger(L, id);\n\treturn 1;\n}\n\n\nstatic int\nludp_send(lua_State *L) {\n\tstruct skynet_context * ctx = lua_touserdata(L, lua_upvalueindex(1));\n\tint id = luaL_checkinteger(L, 1);\n\tconst char * address = luaL_checkstring(L, 2);\n\tstruct socket_sendbuffer buf;\n\tbuf.id = id;\n\tget_buffer(L, 3, &buf);\n\tint err = skynet_socket_udp_sendbuffer(ctx, address, &buf);\n\n\tlua_pushboolean(L, !err);\n\n\treturn 1;\n}\n\nstatic int\nludp_address(lua_State *L) {\n\tsize_t sz = 0;\n\tconst uint8_t * addr = (const uint8_t *)luaL_checklstring(L, 1, &sz);\n\tuint16_t port = 0;\n\tmemcpy(&port, addr+1, sizeof(uint16_t));\n\tport = ntohs(port);\n\tconst void * src = addr+3;\n\tchar tmp[256];\n\tint family;\n\tif (sz == 1+2+4) {\n\t\tfamily = AF_INET;\n\t} else {\n\t\tif (sz != 1+2+16) {\n\t\t\treturn luaL_error(L, \"Invalid udp address\");\n\t\t}\n\t\tfamily = AF_INET6;\n\t}\n\tif (inet_ntop(family, src, tmp, sizeof(tmp)) == NULL) {\n\t\treturn luaL_error(L, \"Invalid udp address\");\n\t}\n\tlua_pushstring(L, tmp);\n\tlua_pushinteger(L, port);\n\treturn 2;\n}\n\nstatic void\ngetinfo(lua_State *L, struct socket_info *si) {\n\tlua_newtable(L);\n\tlua_pushinteger(L, si->id);\n\tlua_setfield(L, -2, \"id\");\n\tlua_pushinteger(L, si->opaque);\n\tlua_setfield(L, -2, \"address\");\n\tswitch(si->type) {\n\tcase SOCKET_INFO_LISTEN:\n\t\tlua_pushstring(L, \"LISTEN\");\n\t\tlua_setfield(L, -2, \"type\");\n\t\tlua_pushinteger(L, si->read);\n\t\tlua_setfield(L, -2, \"accept\");\n\t\tlua_pushinteger(L, si->rtime);\n\t\tlua_setfield(L, -2, \"rtime\");\n\t\tif (si->name[0]) {\n\t\t\tlua_pushstring(L, si->name);\n\t\t\tlua_setfield(L, -2, \"sock\");\n\t\t}\n\t\treturn;\n\tcase SOCKET_INFO_TCP:\n\t\tlua_pushstring(L, \"TCP\");\n\t\tbreak;\n\tcase SOCKET_INFO_UDP:\n\t\tlua_pushstring(L, \"UDP\");\n\t\tbreak;\n\tcase SOCKET_INFO_BIND:\n\t\tlua_pushstring(L, \"BIND\");\n\t\tbreak;\n\tcase SOCKET_INFO_CLOSING:\n\t\tlua_pushstring(L, \"CLOSING\");\n\t\tbreak;\n\tdefault:\n\t\tlua_pushstring(L, \"UNKNOWN\");\n\t\tlua_setfield(L, -2, \"type\");\n\t\treturn;\n\t}\n\tlua_setfield(L, -2, \"type\");\n\tlua_pushinteger(L, si->read);\n\tlua_setfield(L, -2, \"read\");\n\tlua_pushinteger(L, si->write);\n\tlua_setfield(L, -2, \"write\");\n\tlua_pushinteger(L, si->wbuffer);\n\tlua_setfield(L, -2, \"wbuffer\");\n\tlua_pushinteger(L, si->rtime);\n\tlua_setfield(L, -2, \"rtime\");\n\tlua_pushinteger(L, si->wtime);\n\tlua_setfield(L, -2, \"wtime\");\n\tlua_pushboolean(L, si->reading);\n\tlua_setfield(L, -2, \"reading\");\n\tlua_pushboolean(L, si->writing);\n\tlua_setfield(L, -2, \"writing\");\n\tif (si->name[0]) {\n\t\tlua_pushstring(L, si->name);\n\t\tlua_setfield(L, -2, \"peer\");\n\t}\n}\n\nstatic int\nlinfo(lua_State *L) {\n\tlua_newtable(L);\n\tstruct socket_info * si = skynet_socket_info();\n\tstruct socket_info * temp = si;\n\tint n = 0;\n\twhile (temp) {\n\t\tgetinfo(L, temp);\n\t\tlua_seti(L, -2, ++n);\n\t\ttemp = temp->next;\n\t}\n\tsocket_info_release(si);\n\treturn 1;\n}\n\nstatic int\nlresolve(lua_State *L) {\n\tconst char * host = luaL_checkstring(L, 1);\n\tint status;\n\tstruct addrinfo ai_hints;\n\tstruct addrinfo *ai_list = NULL;\n\tstruct addrinfo *ai_ptr = NULL;\n\tmemset( &ai_hints, 0, sizeof( ai_hints ) );\n\tstatus = getaddrinfo( host, NULL, &ai_hints, &ai_list);\n\tif ( status != 0 ) {\n\t\treturn luaL_error(L, gai_strerror(status));\n\t}\n\tlua_newtable(L);\n\tint idx = 1;\n\tchar tmp[128];\n\tfor (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next ) {\n\t\tstruct sockaddr * addr = ai_ptr->ai_addr;\n\t\tvoid * sin_addr = (ai_ptr->ai_family == AF_INET) ? (void*)&((struct sockaddr_in *)addr)->sin_addr : (void*)&((struct sockaddr_in6 *)addr)->sin6_addr;\n\t\tif (inet_ntop(ai_ptr->ai_family, sin_addr, tmp, sizeof(tmp))) {\n\t\t\tlua_pushstring(L, tmp);\n\t\t\tlua_rawseti(L, -2, idx++);\n\t\t}\n\t}\n\n\tfreeaddrinfo(ai_list);\n\treturn 1;\n}\n\nLUAMOD_API int\nluaopen_skynet_socketdriver(lua_State *L) {\n\tluaL_checkversion(L);\n\tluaL_Reg l[] = {\n\t\t{ \"buffer\", lnewbuffer },\n\t\t{ \"push\", lpushbuffer },\n\t\t{ \"pop\", lpopbuffer },\n\t\t{ \"drop\", ldrop },\n\t\t{ \"readall\", lreadall },\n\t\t{ \"clear\", lclearbuffer },\n\t\t{ \"readline\", lreadline },\n\t\t{ \"str2p\", lstr2p },\n\t\t{ \"header\", lheader },\n\t\t{ \"info\", linfo },\n\n\t\t{ \"unpack\", lunpack },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_newlib(L,l);\n\tluaL_Reg l2[] = {\n\t\t{ \"connect\", lconnect },\n\t\t{ \"close\", lclose },\n\t\t{ \"shutdown\", lshutdown },\n\t\t{ \"listen\", llisten },\n\t\t{ \"send\", lsend },\n\t\t{ \"lsend\", lsendlow },\n\t\t{ \"bind\", lbind },\n\t\t{ \"start\", lstart },\n\t\t{ \"pause\", lpause },\n\t\t{ \"nodelay\", lnodelay },\n\t\t{ \"udp\", ludp },\n\t\t{ \"udp_connect\", ludp_connect },\n\t\t{ \"udp_dial\", ludp_dial},\n\t\t{ \"udp_listen\", ludp_listen},\n\t\t{ \"udp_send\", ludp_send },\n\t\t{ \"udp_address\", ludp_address },\n\t\t{ \"resolve\", lresolve },\n\t\t{ NULL, NULL },\n\t};\n\tlua_getfield(L, LUA_REGISTRYINDEX, \"skynet_context\");\n\tstruct skynet_context *ctx = lua_touserdata(L,-1);\n\tif (ctx == NULL) {\n\t\treturn luaL_error(L, \"Init skynet context first\");\n\t}\n\n\tluaL_setfuncs(L,l2,1);\n\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/lua-stm.c",
    "content": "#define LUA_LIB\n\n#include <lua.h>\n#include <lauxlib.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <assert.h>\n#include <string.h>\n\n#include \"rwlock.h\"\n#include \"skynet_malloc.h\"\n#include \"atomic.h\"\n\nstruct stm_object {\n\tstruct rwlock lock;\n\tATOM_INT reference;\n\tstruct stm_copy * copy;\n};\n\nstruct stm_copy {\n\tATOM_INT reference;\n\tuint32_t sz;\n\tvoid * msg;\n};\n\n// msg should alloc by skynet_malloc \nstatic struct stm_copy *\nstm_newcopy(void * msg, int32_t sz) {\n\tstruct stm_copy * copy = skynet_malloc(sizeof(*copy));\n\tATOM_INIT(&copy->reference, 1);\n\tcopy->sz = sz;\n\tcopy->msg = msg;\n\n\treturn copy;\n}\n\nstatic struct stm_object *\nstm_new(void * msg, int32_t sz) {\n\tstruct stm_object * obj = skynet_malloc(sizeof(*obj));\n\trwlock_init(&obj->lock);\n\tATOM_INIT(&obj->reference , 1);\n\tobj->copy = stm_newcopy(msg, sz);\n\n\treturn obj;\n}\n\nstatic void\nstm_releasecopy(struct stm_copy *copy) {\n\tif (copy == NULL)\n\t\treturn;\n\tif (ATOM_FDEC(&copy->reference) <= 1) {\n\t\tskynet_free(copy->msg);\n\t\tskynet_free(copy);\n\t}\n}\n\nstatic void\nstm_release(struct stm_object *obj) {\n\tassert(obj->copy);\n\trwlock_wlock(&obj->lock);\n\t// writer release the stm object, so release the last copy .\n\tstm_releasecopy(obj->copy);\n\tobj->copy = NULL;\n\tif (ATOM_FDEC(&obj->reference) > 1) {\n\t\t// stm object grab by readers, reset the copy to NULL.\n\t\trwlock_wunlock(&obj->lock);\n\t\treturn;\n\t}\n\t// no one grab the stm object, no need to unlock wlock.\n\tskynet_free(obj);\n}\n\nstatic void\nstm_releasereader(struct stm_object *obj) {\n\trwlock_rlock(&obj->lock);\n\tif (ATOM_FDEC(&obj->reference) == 1) {\n\t\t// last reader, no writer. so no need to unlock\n\t\tassert(obj->copy == NULL);\n\t\tskynet_free(obj);\n\t\treturn;\n\t}\n\trwlock_runlock(&obj->lock);\n}\n\nstatic void\nstm_grab(struct stm_object *obj) {\n\trwlock_rlock(&obj->lock);\n\tint ref = ATOM_FINC(&obj->reference);\n\trwlock_runlock(&obj->lock);\n\tassert(ref > 0);\n}\n\nstatic struct stm_copy *\nstm_copy(struct stm_object *obj) {\n\trwlock_rlock(&obj->lock);\n\tstruct stm_copy * ret = obj->copy;\n\tif (ret) {\n\t\tint ref = ATOM_FINC(&ret->reference);\n\t\tassert(ref > 0);\n\t}\n\trwlock_runlock(&obj->lock);\n\t\n\treturn ret;\n}\n\nstatic void\nstm_update(struct stm_object *obj, void *msg, int32_t sz) {\n\tstruct stm_copy *copy = stm_newcopy(msg, sz);\n\trwlock_wlock(&obj->lock);\n\tstruct stm_copy *oldcopy = obj->copy;\n\tobj->copy = copy;\n\trwlock_wunlock(&obj->lock);\n\n\tstm_releasecopy(oldcopy);\n}\n\n// lua binding\n\nstruct boxstm {\n\tstruct stm_object * obj;\n};\n\nstatic int\nlcopy(lua_State *L) {\n\tstruct boxstm * box = lua_touserdata(L, 1);\n\tstm_grab(box->obj);\n\tlua_pushlightuserdata(L, box->obj);\n\treturn 1;\n}\n\nstatic int\nlnewwriter(lua_State *L) {\n\tvoid * msg;\n\tsize_t sz;\n\tif (lua_isuserdata(L,1)) {\n\t\tmsg = lua_touserdata(L, 1);\n\t\tsz = (size_t)luaL_checkinteger(L, 2);\n\t} else {\n\t\tconst char * tmp = luaL_checklstring(L,1,&sz);\n\t\tmsg = skynet_malloc(sz);\n\t\tmemcpy(msg, tmp, sz);\n\t}\n\tstruct boxstm * box = lua_newuserdatauv(L, sizeof(*box), 0);\n\tbox->obj = stm_new(msg,sz);\n\tlua_pushvalue(L, lua_upvalueindex(1));\n\tlua_setmetatable(L, -2);\n\n\treturn 1;\n}\n\nstatic int\nldeletewriter(lua_State *L) {\n\tstruct boxstm * box = lua_touserdata(L, 1);\n\tstm_release(box->obj);\n\tbox->obj = NULL;\n\n\treturn 0;\n}\n\nstatic int\nlupdate(lua_State *L) {\n\tstruct boxstm * box = lua_touserdata(L, 1);\n\tvoid * msg;\n\tsize_t sz;\n\tif (lua_isuserdata(L, 2)) {\n\t\tmsg = lua_touserdata(L, 2);\n\t\tsz = (size_t)luaL_checkinteger(L, 3);\n\t} else {\n\t\tconst char * tmp = luaL_checklstring(L,2,&sz);\n\t\tmsg = skynet_malloc(sz);\n\t\tmemcpy(msg, tmp, sz);\n\t}\n\tstm_update(box->obj, msg, sz);\n\n\treturn 0;\n}\n\nstruct boxreader {\n\tstruct stm_object *obj;\n\tstruct stm_copy *lastcopy;\n};\n\nstatic int\nlnewreader(lua_State *L) {\n\tstruct boxreader * box = lua_newuserdatauv(L, sizeof(*box), 0);\n\tbox->obj = lua_touserdata(L, 1);\n\tbox->lastcopy = NULL;\n\tlua_pushvalue(L, lua_upvalueindex(1));\n\tlua_setmetatable(L, -2);\n\n\treturn 1;\n}\n\nstatic int\nldeletereader(lua_State *L) {\n\tstruct boxreader * box = lua_touserdata(L, 1);\n\tstm_releasereader(box->obj);\n\tbox->obj = NULL;\n\tstm_releasecopy(box->lastcopy);\n\tbox->lastcopy = NULL;\n\n\treturn 0;\n}\n\nstatic int\nlread(lua_State *L) {\n\tstruct boxreader * box = lua_touserdata(L, 1);\n\tluaL_checktype(L, 2, LUA_TFUNCTION);\n\n\tstruct stm_copy * copy = stm_copy(box->obj);\n\tif (copy == box->lastcopy) {\n\t\t// not update\n\t\tstm_releasecopy(copy);\n\t\tlua_pushboolean(L, 0);\n\t\treturn 1;\n\t}\n\n\tstm_releasecopy(box->lastcopy);\n\tbox->lastcopy = copy;\n\tif (copy) {\n\t\tlua_settop(L, 3);\n\t\tlua_replace(L, 1);\n\t\tlua_settop(L, 2);\n\t\tlua_pushlightuserdata(L, copy->msg);\n\t\tlua_pushinteger(L, copy->sz);\n\t\tlua_pushvalue(L, 1);\n\t\tlua_call(L, 3, LUA_MULTRET);\n\t\tlua_pushboolean(L, 1);\n\t\tlua_replace(L, 1);\n\t\treturn lua_gettop(L);\n\t} else {\n\t\tlua_pushboolean(L, 0);\n\t\treturn 1;\n\t}\n}\n\nLUAMOD_API int\nluaopen_skynet_stm(lua_State *L) {\n\tluaL_checkversion(L);\n\tlua_createtable(L, 0, 3);\n\n\tlua_pushcfunction(L, lcopy);\n\tlua_setfield(L, -2, \"copy\");\n\n\tluaL_Reg writer[] = {\n\t\t{ \"new\", lnewwriter },\n\t\t{ NULL, NULL },\n\t};\n\tlua_createtable(L, 0, 2);\n\tlua_pushcfunction(L, ldeletewriter),\n\tlua_setfield(L, -2, \"__gc\");\n\tlua_pushcfunction(L, lupdate),\n\tlua_setfield(L, -2, \"__call\");\n\tluaL_setfuncs(L, writer, 1);\n\n\tluaL_Reg reader[] = {\n\t\t{ \"newcopy\", lnewreader },\n\t\t{ NULL, NULL },\n\t};\n\tlua_createtable(L, 0, 2);\n\tlua_pushcfunction(L, ldeletereader),\n\tlua_setfield(L, -2, \"__gc\");\n\tlua_pushcfunction(L, lread),\n\tlua_setfield(L, -2, \"__call\");\n\tluaL_setfuncs(L, reader, 1);\n\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/sproto/README",
    "content": "Check https://github.com/cloudwu/sproto for more\n"
  },
  {
    "path": "lualib-src/sproto/README.md",
    "content": "Introduction\n======\n\nSproto is an efficient serialization library for C, and focuses on lua binding. It's like Google protocol buffers, but much faster.\n\nThe design is simple. It only supports a few types that lua supports. It can be easily bound to other dynamic languages, or be used directly in C.\n\nIn my i5-2500 @3.3GHz CPU, the benchmark is below:\n\nThe schema in sproto:\n\n```\n.Person {\n    name 0 : string\n    id 1 : integer\n    email 2 : string\n\n    .PhoneNumber {\n        number 0 : string\n        type 1 : integer\n    }\n\n    phone 3 : *PhoneNumber\n}\n\n.AddressBook {\n    person 0 : *Person\n}\n```\n\nIt's equal to:\n\n```\nmessage Person {\n  required string name = 1;\n  required int32 id = 2;\n  optional string email = 3;\n\n  message PhoneNumber {\n    required string number = 1;\n    optional int32 type = 2 ;\n  }\n\n  repeated PhoneNumber phone = 4;\n}\n\nmessage AddressBook {\n  repeated Person person = 1;\n}\n```\n\nUse the data:\n```lua\nlocal ab = {\n    person = {\n        {\n            name = \"Alice\",\n            id = 10000,\n            phone = {\n                { number = \"123456789\" , type = 1 },\n                { number = \"87654321\" , type = 2 },\n            }\n        },\n        {\n            name = \"Bob\",\n            id = 20000,\n            phone = {\n                { number = \"01234567890\" , type = 3 },\n            }\n        }\n    }\n}\n```\n\nlibrary| encode 1M times | decode 1M times | size\n-------| --------------- | --------------- | ----\nsproto | 2.15s           | 7.84s           | 83 bytes\nsproto (nopack) |1.58s   | 6.93s           | 130 bytes\npbc-lua\t  | 6.94s        | 16.9s           | 69 bytes\nlua-cjson | 4.92s        | 8.30s           | 183 bytes\n\n* pbc-lua is a google protocol buffers library https://github.com/cloudwu/pbc\n* lua-cjson is a json library https://github.com/efelix/lua-cjson\n\nParser\n=======\n\n```lua\nlocal parser = require \"sprotoparser\"\n```\n\n* `parser.parse` parses a sproto schema to a binary string.\n\nThe parser is needed for parsing the sproto schema. You can use it to generate binary string offline. The schema text and the parser is not needed when your program is running.\n\nLua API\n=======\n\n```lua\nlocal sproto = require \"sproto\"\nlocal sprotocore = require \"sproto.core\" -- optional\n```\n\n* `sproto.new(spbin)` creates a sproto object by a schema binary string (generates by parser).\n* `sprotocore.newproto(spbin)` creates a sproto c object by a schema binary string (generates by parser).\n* `sproto.sharenew(spbin)` share a sproto object from a sproto c object (generates by sprotocore.newproto).\n* `sproto.parse(schema)` creates a sproto object by a schema text string (by calling parser.parse)\n* `sproto:exist_type(typename)` detect whether a type exist in sproto object.\n* `sproto:encode(typename, luatable)` encodes a lua table with typename into a binary string.\n* `sproto:decode(typename, blob [,sz])` decodes a binary string generated by sproto.encode with typename. If blob is a lightuserdata (C ptr), sz (integer) is needed.\n* `sproto:pencode(typename, luatable)` The same with sproto:encode, but pack (compress) the results.\n* `sproto:pdecode(typename, blob [,sz])` The same with sproto.decode, but unpack the blob (generated by sproto:pencode) first.\n* `sproto:default(typename, type)` Create a table with default values of typename. Type can be nil , \"REQUEST\", or \"RESPONSE\".\n\nRPC API\n=======\n\nThere is a lua wrapper for the core API for RPC .\n\n`sproto:host([packagename])` creates a host object to deliver the rpc message.\n\n`host:dispatch(blob [,sz])` unpack and decode (sproto:pdecode) the binary string with type the host created (packagename). \n\nIf .type is exist, it's a REQUEST message with .type , returns \"REQUEST\", protoname, message, responser, .ud. The responser is a function for encode the response message. The responser will be nil when .session is not exist.\n\nIf .type is not exist, it's a RESPONSE message for .session . Returns \"RESPONSE\", .session, message, .ud .\n\n`host:attach(sprotoobj)` creates a function(protoname, message, session, ud) to pack and encode request message with sprotoobj.\n\nIf you don't want to use host object, you can also use these following apis to encode and decode the rpc message:\n\n`sproto:request_encode(protoname, tbl)` encode a request message with protoname.\n\n`sproto:response_encode(protoname, tbl)` encode a response message with protoname.\n\n`sproto:request_decode(protoname, blob [,sz])` decode a request message with protoname.\n\n`sproto:response_decode(protoname, blob [,sz]` decode a response message with protoname.\n\nRead testrpc.lua for detail.\n\nSchema Language\n==========\n\nLike Protocol Buffers (but unlike json), sproto messages are strongly-typed and are not self-describing. You must define your message structure in a special language.\n\nYou can use sprotoparser library to parse the schema text to a binary string, so that the sproto library can use it. \nYou can parse them offline and save the string, or you can parse them during your program running.\n\nThe schema text is like this:\n\n```\n# This is a comment.\n\n.Person {\t# . means a user defined type \n    name 0 : string\t# string is a build-in type.\n    id 1 : integer\n    email 2 : string\n\n    .PhoneNumber {\t# user defined type can be nest.\n        number 0 : string\n        type 1 : integer\n    }\n\n    phone 3 : *PhoneNumber\t# *PhoneNumber means an array of PhoneNumber.\n    height 4 : integer(2)\t# (2) means a 1/100 fixed-point number.\n    data 5 : binary\t\t# Some binary data\n    weight 6 : double   # floating number\n}\n\n.AddressBook {\n    person 0 : *Person(id)\t# (id) is optional, means Person.id is main index.\n}\n\nfoobar 1 {\t# define a new protocol (for RPC used) with tag 1\n    request Person\t# Associate the type Person with foobar.request\n    response {\t# define the foobar.response type\n        ok 0 : boolean\n    }\n}\n\n```\n\nA schema text can be self-described by the sproto schema language.\n\n```\n.type {\n    .field {\n        name 0 : string\n        buildin\t1 : integer\n        type 2 : integer\t# type is fixed-point number precision when buildin is SPROTO_TINTEGER; When buildin is SPROTO_TSTRING, it means binary string when type is 1.\n        tag 3 : integer\n        array 4\t: boolean\n        key 5 : integer # If key exists, array must be true, and it's a map.\n    }\n    name 0 : string\n    fields 1 : *field\n}\n\n.protocol {\n    name 0 : string\n    tag 1 : integer\n    request 2 : integer # index\n    response 3 : integer # index\n    confirm 4 : boolean # response nil where confirm == true\n}\n\n.group {\n    type 0 : *type\n    protocol 1 : *protocol\n}\n```\n\nTypes\n=======\n\n* **string** : string\n* **binary** : binary string (it's a sub type of string)\n* **integer** : integer, the max length of an integer is signed 64bit. It can be a fixed-point number with specified precision.\n* **double** : double precision floating-point number, satisfy [the IEEE 754 standard](https://en.wikipedia.org/wiki/Double-precision_floating-point_format).\n* **boolean** : true or false\n\nYou can add * before the typename to declare an array.\n\nYou can also specify a main index with the syntax likes `*array(id)`, the array would be encode as an unordered map with the `id` field as key.\n\nFor empty main index likes `*array()`, the array would be encoded as an unordered map with the first field as key and the second field as value.\n\nUser defined type can be any name in alphanumeric characters except the build-in typenames, and nested types are supported.\n\n* Where are double or real types?\n\nI have been using Google protocol buffers for many years in many projects, and I found the real types were seldom used. If you really need it, you can use string to serialize the double numbers. When you need decimal, you can specify the fixed-point precision.\n\n**NOTE** : `double` is supported now.\n\n* Where is enum?\n\nIn lua, enum types are not very useful. You can use integer to define an enum table in lua.\n\nWire protocol\n========\n\nEach integer number must be serialized in little-endian format.\n\nThe sproto message must be a user defined type struct, and a struct is encoded in three parts. The header, the field part, and the data part. \nThe tag and small integer or boolean will be encoded in field part, and others are in data part.\n\nAll the fields must be encoded in ascending order (by tag, base 0). The tags of fields can be discontinuous, if a field is nil. (default value in lua), don't encode it in message.\n\nThe header is a 16bit integer. It is the number of fields.\n\nEach field in field part is a 16bit integer (n). If n is zero, that means the field data is encoded in data part ;\n\nIf n is even (and not zero), the value of this field is n/2-1 , and the tag increases 1;\n\nIf n is odd, that means the tags is not continuous, and we should add current tag by (n+1)/2 .\n\nArrays are always encode in data part, 4 bytes header for the size, and the following bytes is the contents. See the example 2 for the struct array; example 3/4 for the integer array ; example 5 for the boolean array.\n\nFor integer array, an additional byte (4 or 8) to indicate the value is 32bit or 64bit.\n\nRead the examples below to see more details.\n\nNotice: If the tag is not declared in schema, the decoder will simply ignore the field for protocol version compatibility.\nNotice more: all examples are tested in `test_wire_protocol.lua`, update `test_wire_protocol.lua` when update examples.\n\n```\n.Person {\n    name 0 : string\n    age 1 : integer\n    marital 2 : boolean\n    children 3 : *Person\n}\n\n.Data {\n\tnumbers 0 : *integer\n\tbools 1 : *boolean\n\tnumber 2 : integer\n\tbignumber 3 : integer\n \tdouble 4 : double\n \tdoubles 5 : *double\n \tfpn 6 : integer(2)\n}\n```\n\nExample 1:\n\n```\nperson { name = \"Alice\" ,  age = 13, marital = false } \n\n03 00 (fn = 3)\n00 00 (id = 0, value in data part)\n1C 00 (id = 1, value = 13)\n02 00 (id = 2, value = false)\n05 00 00 00 (sizeof \"Alice\")\n41 6C 69 63 65 (\"Alice\")\n```\n\nExample 2:\n\n```\nperson {\n    name = \"Bob\",\n    age = 40,\n    children = {\n        { name = \"Alice\" ,  age = 13 },\n        { name = \"Carol\" ,  age = 5 },\n    }\n}\n\n04 00 (fn = 4)\n00 00 (id = 0, value in data part)\n52 00 (id = 1, value = 40)\n01 00 (skip id = 2)\n00 00 (id = 3, value in data part)\n\n03 00 00 00 (sizeof \"Bob\")\n42 6F 62 (\"Bob\")\n\n26 00 00 00 (sizeof children)\n\n0F 00 00 00 (sizeof child 1)\n02 00 (fn = 2)\n00 00 (id = 0, value in data part)\n1C 00 (id = 1, value = 13)\n05 00 00 00 (sizeof \"Alice\")\n41 6C 69 63 65 (\"Alice\")\n\n0F 00 00 00 (sizeof child 2)\n02 00 (fn = 2)\n00 00 (id = 0, value in data part)\n0C 00 (id = 1, value = 5)\n05 00 00 00 (sizeof \"Carol\")\n43 61 72 6F 6C (\"Carol\")\n```\n\nExample 3:\n\n```\ndata {\n    numbers = { 1,2,3,4,5 }\n}\n\n01 00 (fn = 1)\n00 00 (id = 0, value in data part)\n\n15 00 00 00 (sizeof numbers)\n04 ( sizeof int32 )\n01 00 00 00 (1)\n02 00 00 00 (2)\n03 00 00 00 (3)\n04 00 00 00 (4)\n05 00 00 00 (5)\n```\n\nExample 4:\n```\ndata {\n    numbers = {\n        (1<<32)+1,\n        (1<<32)+2,\n        (1<<32)+3,\n    }\n}\n\n01 00 (fn = 1)\n00 00 (id = 0, value in data part)\n\n19 00 00 00 (sizeof numbers)\n08 ( sizeof int64 )\n01 00 00 00 01 00 00 00 ( (1<32) + 1)\n02 00 00 00 01 00 00 00 ( (1<32) + 2)\n03 00 00 00 01 00 00 00 ( (1<32) + 3)\n```\n\nExample 5:\n```\ndata {\n    bools = { false, true, false }\n}\n\n02 00 (fn = 2)\n01 00 (skip id = 0)\n00 00 (id = 1, value in data part)\n\n03 00 00 00 (sizeof bools)\n00 (false)\n01 (true)\n00 (false)\n```\n\nExample 6:\n```\ndata {\n    number = 100000,\n    bignumber = -10000000000,\n}\n\n03 00 (fn = 3)\n03 00 (skip id = 1)\n00 00 (id = 2, value in data part)\n00 00 (id = 3, value in data part)\n\n04 00 00 00 (sizeof number, data part)\nA0 86 01 00 (100000, 32bit integer)\n\n08 00 00 00 (sizeof bignumber, data part)\n00 1C F4 AB FD FF FF FF (-10000000000, 64bit integer)\n```\n\nExample 7:\n```\ndata {\n    double = 0.01171875,\n    doubles = {0.01171875, 23, 4}\n}\n\n03 00 (fn = 3)\n07 00 (skip id = 3)\n00 00 (id = 4, value in data part)\n00 00 (id = 5, value in data part)\n\n08 00 00 00 (sizeof number, data part)\n00 00 00 00 00 00 88 3f (0.01171875, 64bit double)\n\n19 00 00 00 (sizeof doubles)\n08 (sizeof double)\n00 00 00 00 00 00 88 3f (0.01171875, 64bit double)\n00 00 00 00 00 00 37 40 (23, 64bit double)\n00 00 00 00 00 00 10 40 (4, 64bit double)\n```\n\nExample 8:\n```\ndata {\n    fpn = 1.82,\n}\n\n02 00 (fn = 2)\n0b 00 (skip id = 5)\n6e 01 (id = 6, value = 0x16e/2 - 1 = 182)\n```\n\n0 Packing\n=======\n\nThe algorithm is very similar to [Cap'n proto](http://kentonv.github.io/capnproto/), but 0x00 is not treated specially. \n\nIn packed format, the message is padding to 8. Each 8 byte is reduced to a tag byte followed by zero to eight content bytes. \nThe bits of the tag byte correspond to the bytes of the unpacked word, with the least-significant bit corresponding to the first byte. \nEach zero bit indicates that the corresponding byte is zero. The non-zero bytes are packed following the tag.\n\nFor example:\n\n```\nunpacked (hex):  08 00 00 00 03 00 02 00   19 00 00 00 aa 01 00 00\npacked (hex):  51 08 03 02   31 19 aa 01\n```\n\nTag 0xff is treated specially. A number N is following the 0xff tag. N means (N+1)\\*8 bytes should be copied directly. \nThe bytes may or may not contain zeros. Because of this rule, the worst-case space overhead of packing is 2 bytes per 2 KiB of input.\n\nFor example:\n\n```\nunpacked (hex):  8a (x 30 bytes)\npacked (hex):  ff 03 8a (x 30 bytes) 00 00\n```\n\nC API\n=====\n\n```C\nstruct sproto * sproto_create(const void * proto, size_t sz);\n```\n\nCreate a sproto object with a schema string encoded by sprotoparser:\n\n```C\nvoid sproto_release(struct sproto *);\n```\n\nRelease the sproto object:\n\n```C\nint sproto_prototag(struct sproto *, const char * name);\nconst char * sproto_protoname(struct sproto *, int proto);\n// SPROTO_REQUEST(0) : request, SPROTO_RESPONSE(1): response\nstruct sproto_type * sproto_protoquery(struct sproto *, int proto, int what);\n```\n\nConvert between tag and name of a protocol, and query the type object of it:\n\n```C\nstruct sproto_type * sproto_type(struct sproto *, const char * typename);\n```\n\nQuery the type object from a sproto object:\n\n```C\nstruct sproto_arg {\n\tvoid *ud;\n\tconst char *tagname;\n\tint tagid;\n\tint type;\n\tstruct sproto_type *subtype;\n\tvoid *value;\n\tint length;\n\tint index;\t// array base 1\n\tint mainindex;\t// for map\n\tint extra; // SPROTO_TINTEGER: fixed-point presision ; SPROTO_TSTRING 0:utf8 string 1:binary\n};\n\ntypedef int (*sproto_callback)(const struct sproto_arg *args);\n\nint sproto_decode(struct sproto_type *, const void * data, int size, sproto_callback cb, void *ud);\nint sproto_encode(struct sproto_type *, void * buffer, int size, sproto_callback cb, void *ud);\n```\n\nencode and decode the sproto message with a user defined callback function. Read the implementation of lsproto.c for more details.\n\n```C\nint sproto_pack(const void * src, int srcsz, void * buffer, int bufsz);\nint sproto_unpack(const void * src, int srcsz, void * buffer, int bufsz);\n```\n\npack and unpack the message with the 0 packing algorithm.\n\nOther Implementions and bindings\n=====\nSee Wiki https://github.com/cloudwu/sproto/wiki\n\nQuestion?\n==========\n\n* Send me an email: http://www.codingnow.com/2000/gmail.gif\n* My Blog: http://blog.codingnow.com\n* Design: http://blog.codingnow.com/2014/07/ejoyproto.html (in Chinese)\n"
  },
  {
    "path": "lualib-src/sproto/lsproto.c",
    "content": "#define LUA_LIB\n\n#include <string.h>\n#include <stdlib.h>\n#include <math.h>\n#include \"msvcint.h\"\n\n#include \"lua.h\"\n#include \"lauxlib.h\"\n#include \"sproto.h\"\n\n#define MAX_GLOBALSPROTO 16\n#define ENCODE_BUFFERSIZE 2050\n\n#define ENCODE_MAXSIZE 0x1000000\n#define ENCODE_DEEPLEVEL 64\n\n#ifndef luaL_newlib /* using LuaJIT */\n/*\n** set functions from list 'l' into table at top - 'nup'; each\n** function gets the 'nup' elements at the top as upvalues.\n** Returns with only the table at the stack.\n*/\nLUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {\n#ifdef luaL_checkversion\n\tluaL_checkversion(L);\n#endif\n\tluaL_checkstack(L, nup, \"too many upvalues\");\n\tfor (; l->name != NULL; l++) {  /* fill the table with given functions */\n\t\tint i;\n\t\tfor (i = 0; i < nup; i++)  /* copy upvalues to the top */\n\t\t\tlua_pushvalue(L, -nup);\n\t\tlua_pushcclosure(L, l->func, nup);  /* closure with those upvalues */\n\t\tlua_setfield(L, -(nup + 2), l->name);\n\t}\n\tlua_pop(L, nup);  /* remove upvalues */\n}\n\n#define luaL_newlibtable(L,l) \\\n  lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)\n\n#define luaL_newlib(L,l)  (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))\n#endif\n\n#if LUA_VERSION_NUM < 503\n\n#if LUA_VERSION_NUM < 502\nstatic int64_t lua_tointegerx(lua_State *L, int idx, int *isnum) {\n\tif (lua_isnumber(L, idx)) {\n\t\tif (isnum) *isnum = 1;\n\t\treturn (int64_t)lua_tointeger(L, idx);\n\t}\n\telse {\n\t\tif (isnum) *isnum = 0;\n\t\treturn 0;\n\t}\n}\n\nstatic int lua_absindex (lua_State *L, int idx) {\n\tif (idx > 0 || idx <= LUA_REGISTRYINDEX)\n\t\treturn idx;\n\treturn lua_gettop(L) + idx + 1;\n}\n\n#endif\n\nstatic void\nlua_geti(lua_State *L, int index, lua_Integer i) {\n\tindex = lua_absindex(L, index);\n\tlua_pushinteger(L, i);\n\tlua_gettable(L, index);\n}\n\nstatic void\nlua_seti(lua_State *L, int index, lua_Integer n) {\n\tindex = lua_absindex(L, index);\n\tlua_pushinteger(L, n);\n\tlua_insert(L, -2);\n\tlua_settable(L, index);\n}\n\n#endif\n\n#if defined(SPROTO_WEAK_TYPE)\nstatic int64_t\ntointegerx (lua_State *L, int idx, int *isnum) {\n\tint _isnum = 0;\n\tint64_t v = lua_tointegerx(L, idx, &_isnum);\n\tif (!_isnum){\n\t\tdouble num = lua_tonumberx(L, idx, &_isnum);\n\t\tif(_isnum) {\n\t\t\tv = (int64_t)llround(num);\n\t\t}\n\t}\n\tif(isnum) *isnum = _isnum;\n\treturn v;\n}\n\nstatic int\ntobooleanx (lua_State *L, int idx, int *isbool) {\n\tif (isbool) *isbool = 1;\n\treturn lua_toboolean(L, idx);\n}\n\nstatic const char *\ntolstringx (lua_State *L, int idx, size_t *len, int *isstring) {\n\tconst char * str = luaL_tolstring(L, idx, len); // call metamethod, '__tostring' must return a string\n\tif (isstring) {\n\t\t*isstring = 1;\n\t}\n\tlua_pop(L, 1);\n\treturn str;\n}\n\n#else\n#define tointegerx(L, idx, isnum) lua_tointegerx((L), (idx), (isnum))\n\nstatic int\ntobooleanx (lua_State *L, int idx, int *isbool) {\n\tif (isbool) *isbool = lua_isboolean(L, idx);\n\treturn lua_toboolean(L, idx);\n}\n\nstatic const char *\ntolstringx (lua_State *L, int idx, size_t *len, int *isstring) {\n\tif (isstring) {\n\t\t*isstring = (lua_type(L, idx) == LUA_TSTRING);\n\t}\n\tconst char * str = lua_tolstring(L, idx, len);\n\treturn str;\n}\n\n#endif\n\nstatic int\nlnewproto(lua_State *L) {\n\tstruct sproto * sp;\n\tsize_t sz;\n\tvoid * buffer = (void *)luaL_checklstring(L,1,&sz);\n\tsp = sproto_create(buffer, sz);\n\tif (sp) {\n\t\tlua_pushlightuserdata(L, sp);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic int\nldeleteproto(lua_State *L) {\n\tstruct sproto * sp = lua_touserdata(L,1);\n\tif (sp == NULL) {\n\t\treturn luaL_argerror(L, 1, \"Need a sproto object\");\n\t}\n\tsproto_release(sp);\n\treturn 0;\n}\n\nstatic int\nlquerytype(lua_State *L) {\n\tconst char * type_name;\n\tstruct sproto *sp = lua_touserdata(L,1);\n\tstruct sproto_type *st;\n\tif (sp == NULL) {\n\t\treturn luaL_argerror(L, 1, \"Need a sproto object\");\n\t}\n\ttype_name = luaL_checkstring(L,2);\n\tst = sproto_type(sp, type_name);\n\tif (st) {\n\t\tlua_pushlightuserdata(L, st);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstruct encode_ud {\n\tlua_State *L;\n\tstruct sproto_type *st;\n\tint tbl_index;\n\tconst char * array_tag;\n\tint array_index;\n\tint deep;\n\tint map_entry;\n\tint iter_func;\n\tint iter_table;\n\tint iter_key;\n};\n\nstatic int\nnext_list(lua_State *L, struct encode_ud * self) {\n\t// todo: check the key is equal to mainindex value\n\tif (self->iter_func) {\n\t\tlua_pushvalue(L, self->iter_func);\n\t\tlua_pushvalue(L, self->iter_table);\n\t\tlua_pushvalue(L, self->iter_key);\n\t\tlua_call(L, 2, 2);\n\t\tif (lua_isnil(L, -2)) {\n\t\t\tlua_pop(L, 2);\n\t\t\treturn 0;\n\t\t}\n\t\treturn 1;\n\t} else {\n\t\tlua_pushvalue(L,self->iter_key);\n\t\treturn lua_next(L, self->array_index);\n\t}\n}\n\nstatic int\nget_encodefield(const struct sproto_arg *args) {\n\tstruct encode_ud *self = args->ud;\n\tlua_State *L = self->L;\n\tif (args->index > 0) {\n\t\tint map = args->ktagname != NULL;\n\t\tif (args->tagname != self->array_tag) {\n\t\t\t// a new array\n\t\t\tself->array_tag = args->tagname;\n\t\t\tlua_getfield(L, self->tbl_index, args->tagname);\n\t\t\tif (lua_isnil(L, -1)) {\n\t\t\t\tif (self->array_index) {\n\t\t\t\t\tlua_replace(L, self->array_index);\n\t\t\t\t}\n\t\t\t\tself->array_index = 0;\n\t\t\t\treturn SPROTO_CB_NOARRAY;\n\t\t\t}\n\t\t\tif (self->array_index) {\n\t\t\t\tlua_replace(L, self->array_index);\n\t\t\t} else {\n\t\t\t\tself->array_index = lua_gettop(L);\n\t\t\t}\n\n\t\t\tif (map) {\n\t\t\t\tif (!self->map_entry) {\n\t\t\t\t\tlua_createtable(L, 0, 2); // key/value entry\n\t\t\t\t\tself->map_entry = lua_gettop(L);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (luaL_getmetafield(L, self->array_index, \"__pairs\")) {\n\t\t\t\tlua_pushvalue(L, self->array_index);\n\t\t\t\tlua_call(L,\t1, 3);\n\t\t\t\tint top = lua_gettop(L);\n\t\t\t\tself->iter_func = top - 2;\n\t\t\t\tself->iter_table = top - 1;\n\t\t\t\tself->iter_key = top;\n\t\t\t} else if (!lua_istable(L,self->array_index)) {\n\t\t\t\treturn luaL_error(L, \"%s.%s(%d) should be a table or an userdata with metamethods (Is a %s)\",\n\t\t\t\t\tsproto_name(self->st), args->tagname, args->index, lua_typename(L, lua_type(L, -1)));\n\t\t\t} else {\n\t\t\t\tlua_pushnil(L);\n\t\t\t\tself->iter_func = 0;\n\t\t\t\tself->iter_table = 0;\n\t\t\t\tself->iter_key = lua_gettop(L);\n\t\t\t}\n\t\t}\n\t\tif (args->mainindex >= 0) { // *type(mainindex)\n\t\t\tif (!next_list(L, self)) {\n\t\t\t\t// iterate end\n\t\t\t\tlua_pushnil(L);\n\t\t\t\tlua_replace(L, self->iter_key);\n\t\t\t\treturn SPROTO_CB_NIL;\n\t\t\t}\n\t\t\tif (map) {\n\t\t\t\tlua_pushvalue(L, -2);\n\t\t\t\tlua_replace(L, self->iter_key);\n\t\t\t\tlua_setfield(L, self->map_entry, args->vtagname);\n\t\t\t\tlua_setfield(L, self->map_entry, args->ktagname);\n\t\t\t\tlua_pushvalue(L, self->map_entry);\n\t\t\t} else {\n\t\t\t\tlua_insert(L, -2);\n\t\t\t\tlua_replace(L, self->iter_key);\n\t\t\t}\n\t\t} else {\n\t\t\tlua_geti(L, self->array_index, args->index);\n\t\t}\n\t} else {\n\t\tlua_getfield(L, self->tbl_index, args->tagname);\n\t}\n\treturn 0;\n}\n\nstatic int encode(const struct sproto_arg *args);\n\nstatic int\nencode_one(const struct sproto_arg *args, struct encode_ud *self) {\n\tlua_State *L = self->L;\n\tint type = args->type;\n\tswitch (type) {\n\tcase SPROTO_TINTEGER: {\n\t\tint64_t v;\n\t\tlua_Integer vh;\n\t\tint isnum;\n\t\tif (args->extra) {\n\t\t\t// It's decimal.\n\t\t\tlua_Number vn = lua_tonumber(L, -1);\n\t\t\t// use 64bit integer for 32bit architecture.\n\t\t\tv = (int64_t)(round(vn * args->extra));\n\t\t} else {\n\t\t\tv = tointegerx(L, -1, &isnum);\n\t\t\tif(!isnum) {\n\t\t\t\treturn luaL_error(L, \"%s.%s[%d] is not an integer (Is a %s)\",\n\t\t\t\t\tsproto_name(self->st), args->tagname, args->index, lua_typename(L, lua_type(L, -1)));\n\t\t\t}\n\t\t}\n\t\tlua_pop(L,1);\n\t\t// notice: in lua 5.2, lua_Integer maybe 52bit\n\t\tvh = v >> 31;\n\t\tif (vh == 0 || vh == -1) {\n\t\t\t*(uint32_t *)args->value = (uint32_t)v;\n\t\t\treturn 4;\n\t\t}\n\t\telse {\n\t\t\t*(uint64_t *)args->value = (uint64_t)v;\n\t\t\treturn 8;\n\t\t}\n\t}\n\tcase SPROTO_TDOUBLE: {\n\t\tlua_Number v = lua_tonumber(L, -1);\n\t\t*(double*)args->value = (double)v;\n\t\tlua_pop(L,1);\n\t\treturn 8;\n\t}\n\tcase SPROTO_TBOOLEAN: {\n\t\tint isbool;\n\t\tint v = tobooleanx(L, -1, &isbool);\n\t\tif (!isbool) {\n\t\t\treturn luaL_error(L, \"%s.%s[%d] is not a boolean (Is a %s)\",\n\t\t\t\tsproto_name(self->st), args->tagname, args->index, lua_typename(L, lua_type(L, -1)));\n\t\t}\n\t\t*(int *)args->value = v;\n\t\tlua_pop(L,1);\n\t\treturn 4;\n\t}\n\tcase SPROTO_TSTRING: {\n\t\tsize_t sz = 0;\n\t\tint isstring;\n\t\tint type = lua_type(L, -1); // get the type firstly, lua_tolstring may convert value on stack to string\n\t\tconst char * str = tolstringx(L, -1, &sz, &isstring);\n\t\tif (!isstring) {\n\t\t\treturn luaL_error(L, \"%s.%s[%d] is not a string (Is a %s)\",\n\t\t\t\tsproto_name(self->st), args->tagname, args->index, lua_typename(L, type));\n\t\t}\n\t\tif (sz > args->length)\n\t\t\treturn SPROTO_CB_ERROR;\n\t\tmemcpy(args->value, str, sz);\n\t\tlua_pop(L,1);\n\t\treturn sz;\n\t}\n\tcase SPROTO_TSTRUCT: {\n\t\tstruct encode_ud sub;\n\t\tint r;\n\t\tint top = lua_gettop(L);\n\t\tsub.L = L;\n\t\tsub.st = args->subtype;\n\t\tsub.tbl_index = top;\n\t\tsub.array_tag = NULL;\n\t\tsub.array_index = 0;\n\t\tsub.deep = self->deep + 1;\n\t\tsub.map_entry = 0;\n\t\tsub.iter_func = 0;\n\t\tsub.iter_table = 0;\n\t\tsub.iter_key = 0;\n\t\tr = sproto_encode(args->subtype, args->value, args->length, encode, &sub);\n\t\tlua_settop(L, top-1);\t// pop the value\n\t\tif (r < 0)\n\t\t\treturn SPROTO_CB_ERROR;\n\t\treturn r;\n\t}\n\tdefault:\n\t\treturn luaL_error(L, \"Invalid field type %d\", args->type);\n\t}\n}\n\nstatic int\nencode(const struct sproto_arg *args) {\n\tstruct encode_ud *self = args->ud;\n\tlua_State *L = self->L;\n\tint code;\n\tluaL_checkstack(L, 12, NULL);\n\tif (self->deep >= ENCODE_DEEPLEVEL)\n\t\treturn luaL_error(L, \"The table is too deep\");\n\tcode = get_encodefield(args);\n\tif (code < 0) {\n\t\treturn code;\n\t}\n\tif (lua_isnil(L, -1)) {\n\t\tlua_pop(L,1);\n\t\treturn SPROTO_CB_NIL;\n\t}\n\treturn encode_one(args, self);\n}\n\nstatic void *\nexpand_buffer(lua_State *L, int osz, int nsz) {\n\t// assert(osz > 0 && osz < nsz)\n\tif (luai_unlikely(nsz > ENCODE_MAXSIZE)) {\n\t\tluaL_error(L, \"object is too large (>%d)\", ENCODE_MAXSIZE);\n\t\treturn NULL;\n\t}\n\n\t// osz = osz * 1.5\n\t// factor > 1.618... never reuse alloced space\n\t// factor = 1.3, reuse after 3 steps\n\t// factor = 1.4, reuse after 4 steps\n\t// factor = 1.5, reuse after 5 steps\n\t// factor = 1.6, reuse after 8 steps\n\tosz += osz >> 1;\n\tif (osz < nsz) {\n\t\tosz = nsz;\n\t} else if (osz > ENCODE_MAXSIZE) {\n\t\tosz = ENCODE_MAXSIZE;\n\t}\n\n\tvoid *output = lua_newuserdata(L, osz);\n\tlua_replace(L, lua_upvalueindex(1));\n\tlua_pushinteger(L, osz);\n\tlua_replace(L, lua_upvalueindex(2));\n\n\treturn output;\n}\n\n/*\n\tlightuserdata sproto_type\n\ttable source\n\n\treturn string\n */\nstatic int\nlencode(lua_State *L) {\n\tstruct encode_ud self;\n\tvoid * buffer = lua_touserdata(L, lua_upvalueindex(1));\n\tint sz = lua_tointeger(L, lua_upvalueindex(2));\n\tint tbl_index = 2;\n\tstruct sproto_type * st = lua_touserdata(L, 1);\n\tif (st == NULL) {\n\t\tluaL_checktype(L, tbl_index, LUA_TNIL);\n\t\tlua_pushstring(L, \"\");\n\t\treturn 1;\t// response nil\n\t}\n\tself.L = L;\n\tself.st = st;\n\tself.tbl_index = tbl_index;\n\tfor (;;) {\n\t\tint r;\n\t\tself.array_tag = NULL;\n\t\tself.array_index = 0;\n\t\tself.deep = 0;\n\n\t\tlua_settop(L, tbl_index);\n\t\tself.map_entry = 0;\n\t\tself.iter_func = 0;\n\t\tself.iter_table = 0;\n\t\tself.iter_key = 0;\n\n\t\tr = sproto_encode(st, buffer, sz, encode, &self);\n\t\tif (r<0) {\n\t\t\t// nsz > osz to double sz\n            buffer = expand_buffer(L, sz, sz + 1);\n\t\t\tsz = lua_tointeger(L, lua_upvalueindex(2));\n\t\t} else {\n\t\t\tlua_pushlstring(L, buffer, r);\n\t\t\treturn 1;\n\t\t}\n\t}\n}\n\nstruct decode_ud {\n\tlua_State *L;\n\tconst char * array_tag;\n\tint array_index;\n\tint result_index;\n\tint deep;\n\tint mainindex_tag;\n\tint key_index;\n\tint map_entry;\n};\n\nstatic int\ndecode(const struct sproto_arg *args) {\n\tstruct decode_ud * self = args->ud;\n\tlua_State *L = self->L;\n\tif (self->deep >= ENCODE_DEEPLEVEL)\n\t\treturn luaL_error(L, \"The table is too deep\");\n\tluaL_checkstack(L, 12, NULL);\n\tif (args->index != 0) {\n\t\t// It's array\n\t\tif (args->tagname != self->array_tag) {\n\t\t\tself->array_tag = args->tagname;\n\t\t\tlua_newtable(L);\n\t\t\tlua_pushvalue(L, -1);\n\t\t\tlua_setfield(L, self->result_index, args->tagname);\n\t\t\tif (self->array_index) {\n\t\t\t\tlua_replace(L, self->array_index);\n\t\t\t} else {\n\t\t\t\tself->array_index = lua_gettop(L);\n\t\t\t}\n\t\t\tif (args->index < 0) {\n\t\t\t\t// It's a empty array, return now.\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\tswitch (args->type) {\n\tcase SPROTO_TINTEGER: {\n\t\t// notice: in lua 5.2, 52bit integer support (not 64)\n\t\tif (args->extra) {\n\t\t\t// lua_Integer is 32bit in small lua.\n\t\t\tint64_t v = *(int64_t*)args->value;\n\t\t\tlua_Number vn = (lua_Number)v;\n\t\t\tvn /= args->extra;\n\t\t\tlua_pushnumber(L, vn);\n\t\t} else {\n\t\t\tint64_t v = *(int64_t*)args->value;\n\t\t\tlua_pushinteger(L, v);\n\t\t}\n\t\tbreak;\n\t}\n\tcase SPROTO_TDOUBLE: {\n\t\tdouble v = *(double*)args->value;\n\t\tlua_pushnumber(L, v);\n\t\tbreak;\n\t}\n\tcase SPROTO_TBOOLEAN: {\n\t\tint v = *(uint64_t*)args->value;\n\t\tlua_pushboolean(L,v);\n\t\tbreak;\n\t}\n\tcase SPROTO_TSTRING: {\n\t\tlua_pushlstring(L, args->value, args->length);\n\t\tbreak;\n\t}\n\tcase SPROTO_TSTRUCT: {\n\t\tint map = args->ktagname != NULL;\n\t\tstruct decode_ud sub;\n\t\tint r;\n\t\tsub.L = L;\n\t\tif (map) {\n\t\t\tif (!self->map_entry) {\n\t\t\t\tlua_newtable(L);\n\t\t\t\tself->map_entry = lua_gettop(L);\n\t\t\t}\n\t\t\tsub.result_index = self->map_entry;\n\t\t} else {\n\t\t\tlua_newtable(L);\n\t\t\tsub.result_index = lua_gettop(L);\n\t\t}\n\t\tsub.deep = self->deep + 1;\n\t\tsub.array_index = 0;\n\t\tsub.array_tag = NULL;\n\t\tsub.map_entry = 0;\n\t\tif (args->mainindex >= 0) {\n\t\t\t// This struct will set into a map, so mark the main index tag.\n\t\t\tsub.mainindex_tag = args->mainindex;\n\t\t\tlua_pushnil(L);\n\t\t\tsub.key_index = lua_gettop(L);\n\n\t\t\tr = sproto_decode(args->subtype, args->value, args->length, decode, &sub);\n\t\t\tif (r < 0)\n\t\t\t\treturn SPROTO_CB_ERROR;\n\t\t\tif (r != args->length)\n\t\t\t\treturn r;\n\t\t\tif (map) {\n\t\t\t\tlua_getfield(L, sub.result_index, args->ktagname);\n\t\t\t\tif (lua_isnil(L, -1)) {\n\t\t\t\t\tluaL_error(L, \"Can't find key field in [%s]\", args->tagname);\n\t\t\t\t}\n\t\t\t\tlua_getfield(L, sub.result_index, args->vtagname);\n\t\t\t\tif (lua_isnil(L, -1)) {\n\t\t\t\t\tluaL_error(L, \"Can't find value field in [%s]\", args->tagname);\n\t\t\t\t}\n\t\t\t\tlua_settable(L, self->array_index);\n\t\t\t\tlua_settop(L, sub.result_index);\n\t\t\t} else {\n\t\t\t\tlua_pushvalue(L, sub.key_index);\n\t\t\t\tif (lua_isnil(L, -1)) {\n\t\t\t\t\tluaL_error(L, \"Can't find main index (tag=%d) in [%s]\", args->mainindex, args->tagname);\n\t\t\t\t}\n\t\t\t\tlua_pushvalue(L, sub.result_index);\n\t\t\t\tlua_settable(L, self->array_index);\n\t\t\t\tlua_settop(L, sub.result_index-1);\n\t\t\t}\n\t\t\treturn 0;\n\t\t} else {\n\t\t\tsub.mainindex_tag = -1;\n\t\t\tsub.key_index = 0;\n\t\t\tr = sproto_decode(args->subtype, args->value, args->length, decode, &sub);\n\t\t\tif (r < 0)\n\t\t\t\treturn SPROTO_CB_ERROR;\n\t\t\tif (r != args->length)\n\t\t\t\treturn r;\n\t\t\tlua_settop(L, sub.result_index);\n\t\t\tbreak;\n\t\t}\n\t}\n\tdefault:\n\t\tluaL_error(L, \"Invalid type\");\n\t}\n\tif (args->index > 0) {\n\t\tlua_seti(L, self->array_index, args->index);\n\t} else {\n\t\tif (self->mainindex_tag == args->tagid) {\n\t\t\t// This tag is marked, save the value to key_index\n\t\t\t// assert(self->key_index > 0);\n\t\t\tlua_pushvalue(L,-1);\n\t\t\tlua_replace(L, self->key_index);\n\t\t}\n\t\tlua_setfield(L, self->result_index, args->tagname);\n\t}\n\n\treturn 0;\n}\n\nstatic const void *\ngetbuffer(lua_State *L, int index, size_t *sz) {\n\tconst void * buffer = NULL;\n\tint t = lua_type(L, index);\n\tif (t == LUA_TSTRING) {\n\t\tbuffer = lua_tolstring(L, index, sz);\n\t} else {\n\t\tif (t != LUA_TUSERDATA && t != LUA_TLIGHTUSERDATA) {\n\t\t\tluaL_argerror(L, index, \"Need a string or userdata\");\n\t\t\treturn NULL;\n\t\t}\n\t\tbuffer = lua_touserdata(L, index);\n\t\t*sz = luaL_checkinteger(L, index+1);\n\t}\n\treturn buffer;\n}\n\n/*\n\tlightuserdata sproto_type\n\tstring source\t/  (lightuserdata , integer)\n\treturn table, sz(decoded bytes)\n */\nstatic int\nldecode(lua_State *L) {\n\tstruct sproto_type * st = lua_touserdata(L, 1);\n\tconst void * buffer;\n\tstruct decode_ud self;\n\tsize_t sz;\n\tint r;\n\tif (st == NULL) {\n\t\t// return nil\n\t\treturn 0;\n\t}\n\tsz = 0;\n\tbuffer = getbuffer(L, 2, &sz);\n\tif (!lua_istable(L, -1)) {\n\t\tlua_newtable(L);\n\t}\n\tself.L = L;\n\tself.result_index = lua_gettop(L);\n\tself.array_index = 0;\n\tself.array_tag = NULL;\n\tself.deep = 0;\n\tself.mainindex_tag = -1;\n\tself.key_index = 0;\n\tself.map_entry = 0;\n\tr = sproto_decode(st, buffer, (int)sz, decode, &self);\n\tif (r < 0) {\n\t\treturn luaL_error(L, \"decode error\");\n\t}\n\tlua_settop(L, self.result_index);\n\tlua_pushinteger(L, r);\n\treturn 2;\n}\n\nstatic int\nldumpproto(lua_State *L) {\n\tstruct sproto * sp = lua_touserdata(L, 1);\n\tif (sp == NULL) {\n\t\treturn luaL_argerror(L, 1, \"Need a sproto_type object\");\n\t}\n\tsproto_dump(sp);\n\n\treturn 0;\n}\n\n\n/*\n\tstring source\t/  (lightuserdata , integer)\n\treturn string\n */\nstatic int\nlpack(lua_State *L) {\n\tsize_t sz=0;\n\tconst void * buffer = getbuffer(L, 1, &sz);\n\t// the worst-case space overhead of packing is 2 bytes per 2 KiB of input (256 words = 2KiB).\n\tsize_t maxsz = (sz + 2047) / 2048 * 2 + sz + 2;\n\tvoid * output = lua_touserdata(L, lua_upvalueindex(1));\n\tint bytes;\n\tint osz = lua_tointeger(L, lua_upvalueindex(2));\n\tif (osz < maxsz) {\n\t\toutput = expand_buffer(L, osz, maxsz);\n\t}\n\tbytes = sproto_pack(buffer, sz, output, maxsz);\n\tif (bytes > maxsz) {\n\t\treturn luaL_error(L, \"packing error, return size = %d\", bytes);\n\t}\n\tlua_pushlstring(L, output, bytes);\n\n\treturn 1;\n}\n\nstatic int\nlunpack(lua_State *L) {\n\tsize_t sz=0;\n\tconst void * buffer = getbuffer(L, 1, &sz);\n\tvoid * output = lua_touserdata(L, lua_upvalueindex(1));\n\tint osz = lua_tointeger(L, lua_upvalueindex(2));\n\tint r = sproto_unpack(buffer, sz, output, osz);\n\tif (r < 0)\n\t\treturn luaL_error(L, \"Invalid unpack stream\");\n\tif (r > osz) {\n\t\toutput = expand_buffer(L, osz, r);\n\t\tr = sproto_unpack(buffer, sz, output, r);\n\t\tif (r < 0)\n\t\t\treturn luaL_error(L, \"Invalid unpack stream\");\n\t}\n\tlua_pushlstring(L, output, r);\n\treturn 1;\n}\n\nstatic void\npushfunction_withbuffer(lua_State *L, const char * name, lua_CFunction func) {\n\tlua_newuserdata(L, ENCODE_BUFFERSIZE);\n\tlua_pushinteger(L, ENCODE_BUFFERSIZE);\n\tlua_pushcclosure(L, func, 2);\n\tlua_setfield(L, -2, name);\n}\n\nstatic int\nlprotocol(lua_State *L) {\n\tstruct sproto * sp = lua_touserdata(L, 1);\n\tstruct sproto_type * request;\n\tstruct sproto_type * response;\n\tint t;\n\tint tag;\n\tif (sp == NULL) {\n\t\treturn luaL_argerror(L, 1, \"Need a sproto_type object\");\n\t}\n\tt = lua_type(L,2);\n\tif (t == LUA_TNUMBER) {\n\t\tconst char * name;\n\t\ttag = lua_tointeger(L, 2);\n\t\tname = sproto_protoname(sp, tag);\n\t\tif (name == NULL)\n\t\t\treturn 0;\n\t\tlua_pushstring(L, name);\n\t} else {\n\t\tconst char * name = lua_tostring(L, 2);\n\t\tif (name == NULL) {\n\t\t\treturn luaL_argerror(L, 2, \"Should be number or string\");\n\t\t}\n\t\ttag = sproto_prototag(sp, name);\n\t\tif (tag < 0)\n\t\t\treturn 0;\n\t\tlua_pushinteger(L, tag);\n\t}\n\trequest = sproto_protoquery(sp, tag, SPROTO_REQUEST);\n\tif (request == NULL) {\n\t\tlua_pushnil(L);\n\t} else {\n\t\tlua_pushlightuserdata(L, request);\n\t}\n\tresponse = sproto_protoquery(sp, tag, SPROTO_RESPONSE);\n\tif (response == NULL) {\n\t\tif (sproto_protoresponse(sp, tag)) {\n\t\t\tlua_pushlightuserdata(L, NULL);\t// response nil\n\t\t} else {\n\t\t\tlua_pushnil(L);\n\t\t}\n\t} else {\n\t\tlua_pushlightuserdata(L, response);\n\t}\n\treturn 3;\n}\n\n/* global sproto pointer for multi states\n   NOTICE : It is not thread safe\n */\nstatic struct sproto * G_sproto[MAX_GLOBALSPROTO];\n\nstatic int\nlsaveproto(lua_State *L) {\n\tstruct sproto * sp = lua_touserdata(L, 1);\n\tint index = luaL_optinteger(L, 2, 0);\n\tif (index < 0 || index >= MAX_GLOBALSPROTO) {\n\t\treturn luaL_error(L, \"Invalid global slot index %d\", index);\n\t}\n\t/* TODO : release old object (memory leak now, but thread safe)*/\n\tG_sproto[index] = sp;\n\treturn 0;\n}\n\nstatic int\nlloadproto(lua_State *L) {\n\tint index = luaL_optinteger(L, 1, 0);\n\tstruct sproto * sp;\n\tif (index < 0 || index >= MAX_GLOBALSPROTO) {\n\t\treturn luaL_error(L, \"Invalid global slot index %d\", index);\n\t}\n\tsp = G_sproto[index];\n\tif (sp == NULL) {\n\t\treturn luaL_error(L, \"nil sproto at index %d\", index);\n\t}\n\n\tlua_pushlightuserdata(L, sp);\n\n\treturn 1;\n}\n\nstatic void\npush_default(const struct sproto_arg *args, int table) {\n\tlua_State *L = args->ud;\n\tswitch(args->type) {\n\tcase SPROTO_TINTEGER:\n\t\tif (args->extra)\n\t\t\tlua_pushnumber(L, 0.0);\n\t\telse\n\t\t\tlua_pushinteger(L, 0);\n\t\tbreak;\n\tcase SPROTO_TDOUBLE:\n\t\tlua_pushnumber(L, 0.0);\n\t\tbreak;\n\tcase SPROTO_TBOOLEAN:\n\t\tlua_pushboolean(L, 0);\n\t\tbreak;\n\tcase SPROTO_TSTRING:\n\t\tlua_pushliteral(L, \"\");\n\t\tbreak;\n\tcase SPROTO_TSTRUCT:\n\t\tif (table) {\n\t\t\tlua_pushstring(L, sproto_name(args->subtype));\n\t\t} else {\n\t\t\tlua_createtable(L, 0, 1);\n\t\t\tlua_pushstring(L, sproto_name(args->subtype));\n\t\t\tlua_setfield(L, -2, \"__type\");\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tluaL_error(L, \"Invalid type %d\", args->type);\n\t\tbreak;\n\t}\n}\n\nstatic int\nencode_default(const struct sproto_arg *args) {\n\tlua_State *L = args->ud;\n\tlua_pushstring(L, args->tagname);\n\tif (args->index > 0) {\n\t\tlua_newtable(L);\n\t\tpush_default(args, 1);\n\t\tlua_setfield(L, -2, \"__array\");\n\t\tlua_rawset(L, -3);\n\t\treturn SPROTO_CB_NOARRAY;\n\t} else {\n\t\tpush_default(args, 0);\n\t\tlua_rawset(L, -3);\n\t\treturn SPROTO_CB_NIL;\n\t}\n}\n\n/*\n\tlightuserdata sproto_type\n\treturn default table\n */\nstatic int\nldefault(lua_State *L) {\n\tint ret;\n\t// 64 is always enough for dummy buffer, except the type has many fields ( > 27).\n\tchar dummy[64];\n\tstruct sproto_type * st = lua_touserdata(L, 1);\n\tif (st == NULL) {\n\t\treturn luaL_argerror(L, 1, \"Need a sproto_type object\");\n\t}\n\tlua_newtable(L);\n\tret = sproto_encode(st, dummy, sizeof(dummy), encode_default, L);\n\tif (ret<0) {\n\t\t// try again\n\t\tint sz = sizeof(dummy) * 2;\n\t\tvoid * tmp = lua_newuserdata(L, sz);\n\t\tlua_insert(L, -2);\n\t\tfor (;;) {\n\t\t\tret = sproto_encode(st, tmp, sz, encode_default, L);\n\t\t\tif (ret >= 0)\n\t\t\t\tbreak;\n\t\t\tsz *= 2;\n\t\t\ttmp = lua_newuserdata(L, sz);\n\t\t\tlua_replace(L, -3);\n\t\t}\n\t}\n\treturn 1;\n}\n\nLUAMOD_API int\nluaopen_sproto_core(lua_State *L) {\n#ifdef luaL_checkversion\n\tluaL_checkversion(L);\n#endif\n\tluaL_Reg l[] = {\n\t\t{ \"newproto\", lnewproto },\n\t\t{ \"deleteproto\", ldeleteproto },\n\t\t{ \"dumpproto\", ldumpproto },\n\t\t{ \"querytype\", lquerytype },\n\t\t{ \"decode\", ldecode },\n\t\t{ \"protocol\", lprotocol },\n\t\t{ \"loadproto\", lloadproto },\n\t\t{ \"saveproto\", lsaveproto },\n\t\t{ \"default\", ldefault },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_newlib(L,l);\n\tpushfunction_withbuffer(L, \"encode\", lencode);\n\tpushfunction_withbuffer(L, \"pack\", lpack);\n\tpushfunction_withbuffer(L, \"unpack\", lunpack);\n\treturn 1;\n}\n"
  },
  {
    "path": "lualib-src/sproto/msvcint.h",
    "content": "#ifndef msvc_int_h\n#define msvc_int_h\n\n#ifdef _MSC_VER\n# define inline __inline\n# ifndef _MSC_STDINT_H_\n#  if (_MSC_VER < 1300)\ntypedef signed char       int8_t;\ntypedef signed short      int16_t;\ntypedef signed int        int32_t;\ntypedef unsigned char     uint8_t;\ntypedef unsigned short    uint16_t;\ntypedef unsigned int      uint32_t;\n#  else\ntypedef signed __int8     int8_t;\ntypedef signed __int16    int16_t;\ntypedef signed __int32    int32_t;\ntypedef unsigned __int8   uint8_t;\ntypedef unsigned __int16  uint16_t;\ntypedef unsigned __int32  uint32_t;\n#  endif\ntypedef signed __int64       int64_t;\ntypedef unsigned __int64     uint64_t;\n# endif\n\n#else\n\n#include <stdint.h>\n\n#endif\n\n#endif\n"
  },
  {
    "path": "lualib-src/sproto/sproto.c",
    "content": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <assert.h>\n#include \"msvcint.h\"\n\n#include \"sproto.h\"\n\n#define CHUNK_SIZE 1000\n#define SIZEOF_LENGTH 4\n#define SIZEOF_HEADER 2\n#define SIZEOF_FIELD 2\n#define SIZEOF_INT64 ((int)sizeof(uint64_t))\n#define SIZEOF_INT32 ((int)sizeof(uint32_t))\n\nstruct field {\n\tint tag;\n\tint type;\n\tconst char * name;\n\tstruct sproto_type * st;\n\tint key;\n\tint map; // interpreted two fields struct as map\n\tint extra;\n};\n\nstruct sproto_type {\n\tconst char * name;\n\tint n;\n\tint base;\n\tint maxn;\n\tstruct field *f;\n};\n\nstruct protocol {\n\tconst char *name;\n\tint tag;\n\tint confirm;\t// confirm == 1 where response nil\n\tstruct sproto_type * p[2];\n};\n\nstruct chunk {\n\tstruct chunk * next;\n};\n\nstruct pool {\n\tstruct chunk * header;\n\tstruct chunk * current;\n\tint current_used;\n};\n\nstruct sproto {\n\tstruct pool memory;\n\tint type_n;\n\tint protocol_n;\n\tstruct sproto_type * type;\n\tstruct protocol * proto;\n};\n\nstatic void\npool_init(struct pool *p) {\n\tp->header = NULL;\n\tp->current = NULL;\n\tp->current_used = 0;\n}\n\nstatic void\npool_release(struct pool *p) {\n\tstruct chunk * tmp = p->header;\n\twhile (tmp) {\n\t\tstruct chunk * n = tmp->next;\n\t\tfree(tmp);\n\t\ttmp = n;\n\t}\n}\n\nstatic void *\npool_newchunk(struct pool *p, size_t sz) {\n\tstruct chunk * t = malloc(sz + sizeof(struct chunk));\n\tif (t == NULL)\n\t\treturn NULL;\n\tt->next = p->header;\n\tp->header = t;\n\treturn t+1;\n}\n\nstatic void *\npool_alloc(struct pool *p, size_t sz) {\n\t// align by 8\n\tsz = (sz + 7) & ~7;\n\tif (sz >= CHUNK_SIZE) {\n\t\treturn pool_newchunk(p, sz);\n\t}\n\tif (p->current == NULL) {\n\t\tif (pool_newchunk(p, CHUNK_SIZE) == NULL)\n\t\t\treturn NULL;\n\t\tp->current = p->header;\n\t}\n\tif (sz + p->current_used <= CHUNK_SIZE) {\n\t\tvoid * ret = (char *)(p->current+1) + p->current_used;\n\t\tp->current_used += sz;\n\t\treturn ret;\n\t}\n\n\tif (sz >= p->current_used) {\n\t\treturn pool_newchunk(p, sz);\n\t} else {\n\t\tvoid * ret = pool_newchunk(p, CHUNK_SIZE);\n\t\tp->current = p->header;\n\t\tp->current_used = sz;\n\t\treturn ret;\n\t}\n}\n\nstatic inline int\ntoword(const uint8_t * p) {\n\treturn p[0] | p[1]<<8;\n}\n\nstatic inline uint32_t\ntodword(const uint8_t *p) {\n\treturn p[0] | p[1]<<8 | p[2]<<16 | p[3]<<24;\n}\n\nstatic int\ncount_array(const uint8_t * stream) {\n\tuint32_t length = todword(stream);\n\tint n = 0;\n\tstream += SIZEOF_LENGTH;\n\twhile (length > 0) {\n\t\tuint32_t nsz;\n\t\tif (length < SIZEOF_LENGTH)\n\t\t\treturn -1;\n\t\tnsz = todword(stream);\n\t\tnsz += SIZEOF_LENGTH;\n\t\tif (nsz > length)\n\t\t\treturn -1;\n\t\t++n;\n\t\tstream += nsz;\n\t\tlength -= nsz;\n\t}\n\n\treturn n;\n}\n\nstatic int\nstruct_field(const uint8_t * stream, size_t sz) {\n\tconst uint8_t * field;\n\tint fn, header, i;\n\tif (sz < SIZEOF_LENGTH)\n\t\treturn -1;\n\tfn = toword(stream);\n\theader = SIZEOF_HEADER + SIZEOF_FIELD * fn;\n\tif (sz < header)\n\t\treturn -1;\n\tfield = stream + SIZEOF_HEADER;\n\tsz -= header;\n\tstream += header;\n\tfor (i=0;i<fn;i++) {\n\t\tint value= toword(field + i * SIZEOF_FIELD);\n\t\tuint32_t dsz;\n\t\tif (value != 0)\n\t\t\tcontinue;\n\t\tif (sz < SIZEOF_LENGTH)\n\t\t\treturn -1;\n\t\tdsz = todword(stream);\n\t\tif (sz < SIZEOF_LENGTH + dsz)\n\t\t\treturn -1;\n\t\tstream += SIZEOF_LENGTH + dsz;\n\t\tsz -= SIZEOF_LENGTH + dsz;\n\t}\n\n\treturn fn;\n}\n\nstatic const char *\nimport_string(struct sproto *s, const uint8_t * stream) {\n\tuint32_t sz = todword(stream);\n\tchar * buffer = pool_alloc(&s->memory, sz+1);\n\tmemcpy(buffer, stream+SIZEOF_LENGTH, sz);\n\tbuffer[sz] = '\\0';\n\treturn buffer;\n}\n\nstatic int\ncalc_pow(int base, int n) {\n\tint r;\n\tif (n == 0)\n\t\treturn 1;\n\tr = calc_pow(base * base , n / 2);\n\tif (n&1) {\n\t\tr *= base;\n\t}\n\treturn r;\n}\n\nstatic const uint8_t *\nimport_field(struct sproto *s, struct field *f, const uint8_t * stream) {\n\tuint32_t sz;\n\tconst uint8_t * result;\n\tint fn;\n\tint i;\n\tint array = 0;\n\tint tag = -1;\n\tf->tag = -1;\n\tf->type = -1;\n\tf->name = NULL;\n\tf->st = NULL;\n\tf->key = -1;\n\tf->map = -1;\n\tf->extra = 0;\n\n\tsz = todword(stream);\n\tstream += SIZEOF_LENGTH;\n\tresult = stream + sz;\n\tfn = struct_field(stream, sz);\n\tif (fn < 0)\n\t\treturn NULL;\n\tstream += SIZEOF_HEADER;\n\tfor (i=0;i<fn;i++) {\n\t\tint value;\n\t\t++tag;\n\t\tvalue = toword(stream + SIZEOF_FIELD * i);\n\t\tif (value & 1) {\n\t\t\ttag+= value/2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (tag == 0) { // name\n\t\t\tif (value != 0)\n\t\t\t\treturn NULL;\n\t\t\tf->name = import_string(s, stream + fn * SIZEOF_FIELD);\n\t\t\tcontinue;\n\t\t}\n\t\tif (value == 0)\n\t\t\treturn NULL;\n\t\tvalue = value/2 - 1;\n\t\tswitch(tag) {\n\t\tcase 1: // buildin\n\t\t\tif (value >= SPROTO_TSTRUCT)\n\t\t\t\treturn NULL;\t// invalid buildin type\n\t\t\tf->type = value;\n\t\t\tbreak;\n\t\tcase 2: // type index\n\t\t\tif (f->type == SPROTO_TINTEGER) {\n\t\t\t\tf->extra = calc_pow(10, value);\n\t\t\t} else if (f->type == SPROTO_TSTRING) {\n\t\t\t\tf->extra = value;\t// string if 0 ; binary is 1\n\t\t\t} else {\n\t\t\t\tif (value >= s->type_n)\n\t\t\t\t\treturn NULL;\t// invalid type index\n\t\t\t\tif (f->type >= 0)\n\t\t\t\t\treturn NULL;\n\t\t\t\tf->type = SPROTO_TSTRUCT;\n\t\t\t\tf->st = &s->type[value];\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 3: // tag\n\t\t\tf->tag = value;\n\t\t\tbreak;\n\t\tcase 4: // array\n\t\t\tif (value)\n\t\t\t\tarray = SPROTO_TARRAY;\n\t\t\tbreak;\n\t\tcase 5:\t// key\n\t\t\tf->key = value;\n\t\t\tbreak;\n\t\tcase 6: // map\n\t\t\tif (value)\n\t\t\t\tf->map = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn NULL;\n\t\t}\n\t}\n\tif (f->tag < 0 || f->type < 0 || f->name == NULL)\n\t\treturn NULL;\n\tf->type |= array;\n\n\treturn result;\n}\n\n/*\n.type {\n\t.field {\n\t\tname 0 : string\n\t\tbuildin 1 : integer\n\t\ttype 2 : integer\n\t\ttag 3 : integer\n\t\tarray 4 : boolean\n\t\tkey 5 : integer\n\t\tmap 6 : boolean // Interpreted two fields struct as map when decoding\n\t}\n\tname 0 : string\n\tfields 1 : *field\n}\n*/\nstatic const uint8_t *\nimport_type(struct sproto *s, struct sproto_type *t, const uint8_t * stream) {\n\tconst uint8_t * result;\n\tuint32_t sz = todword(stream);\n\tint i;\n\tint fn;\n\tint n;\n\tint maxn;\n\tint last;\n\tstream += SIZEOF_LENGTH;\n\tresult = stream + sz;\n\tfn = struct_field(stream, sz);\n\tif (fn <= 0 || fn > 2)\n\t\treturn NULL;\n\tfor (i=0;i<fn*SIZEOF_FIELD;i+=SIZEOF_FIELD) {\n\t\t// name and fields must encode to 0\n\t\tint v = toword(stream + SIZEOF_HEADER + i);\n\t\tif (v != 0)\n\t\t\treturn NULL;\n\t}\n\tmemset(t, 0, sizeof(*t));\n\tstream += SIZEOF_HEADER + fn * SIZEOF_FIELD;\n\tt->name = import_string(s, stream);\n\tif (fn == 1) {\n\t\treturn result;\n\t}\n\tstream += todword(stream)+SIZEOF_LENGTH;\t// second data\n\tn = count_array(stream);\n\tif (n<0)\n\t\treturn NULL;\n\tstream += SIZEOF_LENGTH;\n\tmaxn = n;\n\tlast = -1;\n\tt->n = n;\n\tt->f = pool_alloc(&s->memory, sizeof(struct field) * n);\n\tfor (i=0;i<n;i++) {\n\t\tint tag;\n\t\tstruct field *f = &t->f[i];\n\t\tstream = import_field(s, f, stream);\n\t\tif (stream == NULL)\n\t\t\treturn NULL;\n\t\ttag = f->tag;\n\t\tif (tag <= last)\n\t\t\treturn NULL;\t// tag must in ascending order\n\t\tif (tag > last+1) {\n\t\t\t++maxn;\n\t\t}\n\t\tlast = tag;\n\t}\n\tt->maxn = maxn;\n\tt->base = t->f[0].tag;\n\tn = t->f[n-1].tag - t->base + 1;\n\tif (n != t->n) {\n\t\tt->base = -1;\n\t}\n\treturn result;\n}\n\n/*\n.protocol {\n\tname 0 : string\n\ttag 1 : integer\n\trequest 2 : integer\n\tresponse 3 : integer\n}\n*/\nstatic const uint8_t *\nimport_protocol(struct sproto *s, struct protocol *p, const uint8_t * stream) {\n\tconst uint8_t * result;\n\tuint32_t sz = todword(stream);\n\tint fn;\n\tint i;\n\tint tag;\n\tstream += SIZEOF_LENGTH;\n\tresult = stream + sz;\n\tfn = struct_field(stream, sz);\n\tstream += SIZEOF_HEADER;\n\tp->name = NULL;\n\tp->tag = -1;\n\tp->p[SPROTO_REQUEST] = NULL;\n\tp->p[SPROTO_RESPONSE] = NULL;\n\tp->confirm = 0;\n\ttag = 0;\n\tfor (i=0;i<fn;i++,tag++) {\n\t\tint value = toword(stream + SIZEOF_FIELD * i);\n\t\tif (value & 1) {\n\t\t\ttag += (value-1)/2;\n\t\t\tcontinue;\n\t\t}\n\t\tvalue = value/2 - 1;\n\t\tswitch (i) {\n\t\tcase 0: // name\n\t\t\tif (value != -1) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tp->name = import_string(s, stream + SIZEOF_FIELD *fn);\n\t\t\tbreak;\n\t\tcase 1: // tag\n\t\t\tif (value < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tp->tag = value;\n\t\t\tbreak;\n\t\tcase 2: // request\n\t\t\tif (value < 0 || value>=s->type_n)\n\t\t\t\treturn NULL;\n\t\t\tp->p[SPROTO_REQUEST] = &s->type[value];\n\t\t\tbreak;\n\t\tcase 3: // response\n\t\t\tif (value < 0 || value>=s->type_n)\n\t\t\t\treturn NULL;\n\t\t\tp->p[SPROTO_RESPONSE] = &s->type[value];\n\t\t\tbreak;\n\t\tcase 4:\t// confirm\n\t\t\tp->confirm = value;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\tif (p->name == NULL || p->tag<0) {\n\t\treturn NULL;\n\t}\n\n\treturn result;\n}\n\nstatic struct sproto *\ncreate_from_bundle(struct sproto *s, const uint8_t * stream, size_t sz) {\n\tconst uint8_t * content;\n\tconst uint8_t * typedata = NULL;\n\tconst uint8_t * protocoldata = NULL;\n\tint fn = struct_field(stream, sz);\n\tint i;\n\tif (fn < 0 || fn > 2)\n\t\treturn NULL;\n\n\tstream += SIZEOF_HEADER;\n\tcontent = stream + fn*SIZEOF_FIELD;\n\n\tfor (i=0;i<fn;i++) {\n\t\tint value = toword(stream + i*SIZEOF_FIELD);\n\t\tint n;\n\t\tif (value != 0)\n\t\t\treturn NULL;\n\t\tn = count_array(content);\n\t\tif (n<0)\n\t\t\treturn NULL;\n\t\tif (i == 0) {\n\t\t\ttypedata = content+SIZEOF_LENGTH;\n\t\t\ts->type_n = n;\n\t\t\ts->type = pool_alloc(&s->memory, n * sizeof(*s->type));\n\t\t} else {\n\t\t\tprotocoldata = content+SIZEOF_LENGTH;\n\t\t\ts->protocol_n = n;\n\t\t\ts->proto = pool_alloc(&s->memory, n * sizeof(*s->proto));\n\t\t}\n\t\tcontent += todword(content) + SIZEOF_LENGTH;\n\t}\n\n\tfor (i=0;i<s->type_n;i++) {\n\t\ttypedata = import_type(s, &s->type[i], typedata);\n\t\tif (typedata == NULL) {\n\t\t\treturn NULL;\n\t\t}\n\t}\n\tfor (i=0;i<s->protocol_n;i++) {\n\t\tprotocoldata = import_protocol(s, &s->proto[i], protocoldata);\n\t\tif (protocoldata == NULL) {\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\treturn s;\n}\n\nstruct sproto *\nsproto_create(const void * proto, size_t sz) {\n\tstruct pool mem;\n\tstruct sproto * s;\n\tpool_init(&mem);\n\ts = pool_alloc(&mem, sizeof(*s));\n\tif (s == NULL)\n\t\treturn NULL;\n\tmemset(s, 0, sizeof(*s));\n\ts->memory = mem;\n\tif (create_from_bundle(s, proto, sz) == NULL) {\n\t\tpool_release(&s->memory);\n\t\treturn NULL;\n\t}\n\treturn s;\n}\n\nvoid\nsproto_release(struct sproto * s) {\n\tif (s == NULL)\n\t\treturn;\n\tpool_release(&s->memory);\n}\n\nstatic const char *\nget_typename(int type, struct field *f) {\n\tif (type == SPROTO_TSTRUCT) {\n\t\treturn f->st->name;\n\t} else {\n\t\tswitch (type) {\n\t\tcase SPROTO_TINTEGER:\n\t\t\tif (f->extra)\n\t\t\t\treturn \"decimal\";\n\t\t\telse\n\t\t\t\treturn \"integer\";\n\t\tcase SPROTO_TBOOLEAN:\n\t\t\treturn \"boolean\";\n\t\tcase SPROTO_TSTRING:\n\t\t\tif (f->extra == SPROTO_TSTRING_BINARY)\n\t\t\t\treturn \"binary\";\n\t\t\telse\n\t\t\t\treturn \"string\";\n\t\tcase SPROTO_TDOUBLE:\n\t\t\treturn \"double\";\n\t\tdefault:\n\t\t\treturn \"invalid\";\n\t\t}\n\t}\n}\n\nvoid\nsproto_dump(struct sproto *s) {\n\tint i,j;\n\tprintf(\"=== %d types ===\\n\", s->type_n);\n\tfor (i=0;i<s->type_n;i++) {\n\t\tstruct sproto_type *t = &s->type[i];\n\t\tprintf(\"%s\\n\", t->name);\n\t\tfor (j=0;j<t->n;j++) {\n\t\t\tchar container[2] = { 0, 0 };\n\t\t\tconst char * typename = NULL;\n\t\t\tstruct field *f = &t->f[j];\n\t\t\tint type = f->type & ~SPROTO_TARRAY;\n\t\t\tif (f->type & SPROTO_TARRAY) {\n\t\t\t\tcontainer[0] = '*';\n\t\t\t} else {\n\t\t\t\tcontainer[0] = 0;\n\t\t\t}\n\t\t\ttypename = get_typename(type, f);\n\t\t\tprintf(\"\\t%s (%d) %s%s\", f->name, f->tag, container, typename);\n\t\t\tif (type == SPROTO_TINTEGER && f->extra > 0) {\n\t\t\t\tprintf(\"(%d)\", f->extra);\n\t\t\t}\n\t\t\tif (f->key >= 0) {\n\t\t\t\tprintf(\" key[%d]\", f->key);\n\t\t\t\tif (f->map >= 0) {\n\t\t\t\t\tprintf(\" value[%d]\", f->st->f[1].tag);\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\n\tprintf(\"=== %d protocol ===\\n\", s->protocol_n);\n\tfor (i=0;i<s->protocol_n;i++) {\n\t\tstruct protocol *p = &s->proto[i];\n\t\tif (p->p[SPROTO_REQUEST]) {\n\t\t\tprintf(\"\\t%s (%d) request:%s\", p->name, p->tag, p->p[SPROTO_REQUEST]->name);\n\t\t} else {\n\t\t\tprintf(\"\\t%s (%d) request:(null)\", p->name, p->tag);\n\t\t}\n\t\tif (p->p[SPROTO_RESPONSE]) {\n\t\t\tprintf(\" response:%s\", p->p[SPROTO_RESPONSE]->name);\n\t\t} else if (p->confirm) {\n\t\t\tprintf(\" response nil\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\n// query\nint\nsproto_prototag(const struct sproto *sp, const char * name) {\n\tint i;\n\tfor (i=0;i<sp->protocol_n;i++) {\n\t\tif (strcmp(name, sp->proto[i].name) == 0) {\n\t\t\treturn sp->proto[i].tag;\n\t\t}\n\t}\n\treturn -1;\n}\n\nstatic struct protocol *\nquery_proto(const struct sproto *sp, int tag) {\n\tint begin = 0, end = sp->protocol_n;\n\twhile(begin<end) {\n\t\tint mid = (begin+end)/2;\n\t\tint t = sp->proto[mid].tag;\n\t\tif (t==tag) {\n\t\t\treturn &sp->proto[mid];\n\t\t}\n\t\tif (tag > t) {\n\t\t\tbegin = mid+1;\n\t\t} else {\n\t\t\tend = mid;\n\t\t}\n\t}\n\treturn NULL;\n}\n\nstruct sproto_type *\nsproto_protoquery(const struct sproto *sp, int proto, int what) {\n\tstruct protocol * p;\n\tif (what <0 || what >1) {\n\t\treturn NULL;\n\t}\n\tp = query_proto(sp, proto);\n\tif (p) {\n\t\treturn p->p[what];\n\t}\n\treturn NULL;\n}\n\nint\nsproto_protoresponse(const struct sproto * sp, int proto) {\n\tstruct protocol * p = query_proto(sp, proto);\n\treturn (p!=NULL && (p->p[SPROTO_RESPONSE] || p->confirm));\n}\n\nconst char *\nsproto_protoname(const struct sproto *sp, int proto) {\n\tstruct protocol * p = query_proto(sp, proto);\n\tif (p) {\n\t\treturn p->name;\n\t}\n\treturn NULL;\n}\n\nstruct sproto_type *\nsproto_type(const struct sproto *sp, const char * type_name) {\n\tint i;\n\tfor (i=0;i<sp->type_n;i++) {\n\t\tif (strcmp(type_name, sp->type[i].name) == 0) {\n\t\t\treturn &sp->type[i];\n\t\t}\n\t}\n\treturn NULL;\n}\n\nconst char *\nsproto_name(struct sproto_type * st) {\n\treturn st->name;\n}\n\nstatic struct field *\nfindtag(const struct sproto_type *st, int tag) {\n\tint begin, end;\n\tif (st->base >=0 ) {\n\t\ttag -= st->base;\n\t\tif (tag < 0 || tag >= st->n)\n\t\t\treturn NULL;\n\t\treturn &st->f[tag];\n\t}\n\tbegin = 0;\n\tend = st->n;\n\twhile (begin < end) {\n\t\tint mid = (begin+end)/2;\n\t\tstruct field *f = &st->f[mid];\n\t\tint t = f->tag;\n\t\tif (t == tag) {\n\t\t\treturn f;\n\t\t}\n\t\tif (tag > t) {\n\t\t\tbegin = mid + 1;\n\t\t} else {\n\t\t\tend = mid;\n\t\t}\n\t}\n\treturn NULL;\n}\n\n// encode & decode\n// sproto_callback(void *ud, int tag, int type, struct sproto_type *, void *value, int length)\n//\t  return size, -1 means error\n\nstatic inline int\nfill_size(uint8_t * data, int sz) {\n\tdata[0] = sz & 0xff;\n\tdata[1] = (sz >> 8) & 0xff;\n\tdata[2] = (sz >> 16) & 0xff;\n\tdata[3] = (sz >> 24) & 0xff;\n\treturn sz + SIZEOF_LENGTH;\n}\n\nstatic int\nencode_integer(uint32_t v, uint8_t * data, int size) {\n\tif (size < SIZEOF_LENGTH + sizeof(v))\n\t\treturn -1;\n\tdata[4] = v & 0xff;\n\tdata[5] = (v >> 8) & 0xff;\n\tdata[6] = (v >> 16) & 0xff;\n\tdata[7] = (v >> 24) & 0xff;\n\treturn fill_size(data, sizeof(v));\n}\n\nstatic int\nencode_uint64(uint64_t v, uint8_t * data, int size) {\n\tif (size < SIZEOF_LENGTH + sizeof(v))\n\t\treturn -1;\n\tdata[4] = v & 0xff;\n\tdata[5] = (v >> 8) & 0xff;\n\tdata[6] = (v >> 16) & 0xff;\n\tdata[7] = (v >> 24) & 0xff;\n\tdata[8] = (v >> 32) & 0xff;\n\tdata[9] = (v >> 40) & 0xff;\n\tdata[10] = (v >> 48) & 0xff;\n\tdata[11] = (v >> 56) & 0xff;\n\treturn fill_size(data, sizeof(v));\n}\n\n/*\n//#define CB(tagname,type,index,subtype,value,length) cb(ud, tagname,type,index,subtype,value,length)\n\nstatic int\ndo_cb(sproto_callback cb, void *ud, const char *tagname, int type, int index, struct sproto_type *subtype, void *value, int length) {\n\tif (subtype) {\n\t\tif (type >= 0) {\n\t\t\tprintf(\"callback: tag=%s[%d], subtype[%s]:%d\\n\",tagname,index, subtype->name, type);\n\t\t} else {\n\t\t\tprintf(\"callback: tag=%s[%d], subtype[%s]\\n\",tagname,index, subtype->name);\n\t\t}\n\t} else if (index > 0) {\n\t\tprintf(\"callback: tag=%s[%d]\\n\",tagname,index);\n\t} else if (index == 0) {\n\t\tprintf(\"callback: tag=%s\\n\",tagname);\n\t} else {\n\t\tprintf(\"callback: tag=%s [mainkey]\\n\",tagname);\n\t}\n\treturn cb(ud, tagname,type,index,subtype,value,length);\n}\n#define CB(tagname,type,index,subtype,value,length) do_cb(cb,ud, tagname,type,index,subtype,value,length)\n*/\n\nstatic int\nencode_object(sproto_callback cb, struct sproto_arg *args, uint8_t *data, int size) {\n\tint sz;\n\tif (size < SIZEOF_LENGTH)\n\t\treturn -1;\n\targs->value = data+SIZEOF_LENGTH;\n\targs->length = size-SIZEOF_LENGTH;\n\tsz = cb(args);\n\tif (sz < 0) {\n\t\tif (sz == SPROTO_CB_NIL)\n\t\t\treturn 0;\n\t\treturn -1;\t// sz == SPROTO_CB_ERROR\n\t}\n\tassert(sz <= size-SIZEOF_LENGTH);\t// verify buffer overflow\n\treturn fill_size(data, sz);\n}\n\nstatic inline void\nuint32_to_uint64(int negative, uint8_t *buffer) {\n\tif (negative) {\n\t\tbuffer[4] = 0xff;\n\t\tbuffer[5] = 0xff;\n\t\tbuffer[6] = 0xff;\n\t\tbuffer[7] = 0xff;\n\t} else {\n\t\tbuffer[4] = 0;\n\t\tbuffer[5] = 0;\n\t\tbuffer[6] = 0;\n\t\tbuffer[7] = 0;\n\t}\n}\n\nstatic uint8_t *\nencode_integer_array(sproto_callback cb, struct sproto_arg *args, uint8_t *buffer, int size, int *noarray) {\n\tuint8_t * header = buffer;\n\tint intlen;\n\tint index;\n\tif (size < 1)\n\t\treturn NULL;\n\tbuffer++;\n\tsize--;\n\tintlen = SIZEOF_INT32;\n\tindex = 1;\n\t*noarray = 0;\n\n\tfor (;;) {\n\t\tint sz;\n\t\tunion {\n\t\t\tuint64_t u64;\n\t\t\tuint32_t u32;\n\t\t} u;\n\t\targs->value = &u;\n\t\targs->length = sizeof(u);\n\t\targs->index = index;\n\t\tsz = cb(args);\n\t\tif (sz <= 0) {\n\t\t\tif (sz == SPROTO_CB_NIL) // nil object, end of array\n\t\t\t\tbreak;\n\t\t\tif (sz == SPROTO_CB_NOARRAY) {\t// no array, don't encode it\n\t\t\t\t*noarray = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn NULL;\t// sz == SPROTO_CB_ERROR\n\t\t}\n\t\t// notice: sizeof(uint64_t) is size_t (unsigned) , size may be negative. See issue #75\n\t\t// so use MACRO SIZOF_INT64 instead\n\t\tif (size < SIZEOF_INT64)\n\t\t\treturn NULL;\n\t\tif (sz == SIZEOF_INT32) {\n\t\t\tuint32_t v = u.u32;\n\t\t\tbuffer[0] = v & 0xff;\n\t\t\tbuffer[1] = (v >> 8) & 0xff;\n\t\t\tbuffer[2] = (v >> 16) & 0xff;\n\t\t\tbuffer[3] = (v >> 24) & 0xff;\n\n\t\t\tif (intlen == SIZEOF_INT64) {\n\t\t\t\tuint32_to_uint64(v & 0x80000000, buffer);\n\t\t\t}\n\t\t} else {\n\t\t\tuint64_t v;\n\t\t\tif (sz != SIZEOF_INT64)\n\t\t\t\treturn NULL;\n\t\t\tif (intlen == SIZEOF_INT32) {\n\t\t\t\tint i;\n\t\t\t\t// rearrange\n\t\t\t\tsize -= (index-1) * SIZEOF_INT32;\n\t\t\t\tif (size < SIZEOF_INT64)\n\t\t\t\t\treturn NULL;\n\t\t\t\tbuffer += (index-1) * SIZEOF_INT32;\n\t\t\t\tfor (i=index-2;i>=0;i--) {\n\t\t\t\t\tint negative;\n\t\t\t\t\tmemcpy(header+1+i*SIZEOF_INT64, header+1+i*SIZEOF_INT32, SIZEOF_INT32);\n\t\t\t\t\tnegative = header[1+i*SIZEOF_INT64+3] & 0x80;\n\t\t\t\t\tuint32_to_uint64(negative, header+1+i*SIZEOF_INT64);\n\t\t\t\t}\n\t\t\t\tintlen = SIZEOF_INT64;\n\t\t\t}\n\n\t\t\tv = u.u64;\n\t\t\tbuffer[0] = v & 0xff;\n\t\t\tbuffer[1] = (v >> 8) & 0xff;\n\t\t\tbuffer[2] = (v >> 16) & 0xff;\n\t\t\tbuffer[3] = (v >> 24) & 0xff;\n\t\t\tbuffer[4] = (v >> 32) & 0xff;\n\t\t\tbuffer[5] = (v >> 40) & 0xff;\n\t\t\tbuffer[6] = (v >> 48) & 0xff;\n\t\t\tbuffer[7] = (v >> 56) & 0xff;\n\t\t}\n\n\t\tsize -= intlen;\n\t\tbuffer += intlen;\n\t\tindex++;\n\t}\n\n\tif (buffer == header + 1) {\n\t\treturn header;\n\t}\n\t*header = (uint8_t)intlen;\n\treturn buffer;\n}\n\nstatic uint8_t *\nencode_array_object(sproto_callback cb, struct sproto_arg *args, uint8_t *buffer, int size, int *noarray) {\n\tint sz;\n\t*noarray = 0;\n\targs->index = 1;\n\tfor (;;) {\n\t\tif (size < SIZEOF_LENGTH)\n\t\t\treturn NULL;\n\t\tsize -= SIZEOF_LENGTH;\n\t\targs->value = buffer + SIZEOF_LENGTH;\n\t\targs->length = size;\n\t\tsz = cb(args);\n\t\tif (sz < 0) {\n\t\t\tif (sz == SPROTO_CB_NIL) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (sz == SPROTO_CB_NOARRAY) {\t// no array, don't encode it\n\t\t\t\t*noarray = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn NULL;\t// sz == SPROTO_CB_ERROR\n\t\t}\n\t\tfill_size(buffer, sz);\n\t\tbuffer += SIZEOF_LENGTH+sz;\n\t\tsize -= sz;\n\t\t++args->index;\n\t}\n\treturn buffer;\n}\n\nstatic int\nencode_array(sproto_callback cb, struct sproto_arg *args, uint8_t *data, int size) {\n\tuint8_t * buffer;\n\tint sz;\n\tif (size < SIZEOF_LENGTH)\n\t\treturn -1;\n\tsize -= SIZEOF_LENGTH;\n\tbuffer = data + SIZEOF_LENGTH;\n\tswitch (args->type) {\n\tcase SPROTO_TDOUBLE:\n\tcase SPROTO_TINTEGER: {\n\t\tint noarray;\n\t\tbuffer = encode_integer_array(cb,args,buffer,size, &noarray);\n\t\tif (buffer == NULL)\n\t\t\treturn -1;\n\n\t\tif (noarray) {\n\t\t\treturn 0;\n\t\t}\n\t\tbreak;\n\t}\n\tcase SPROTO_TBOOLEAN:\n\t\targs->index = 1;\n\t\tfor (;;) {\n\t\t\tint v = 0;\n\t\t\targs->value = &v;\n\t\t\targs->length = sizeof(v);\n\t\t\tsz = cb(args);\n\t\t\tif (sz < 0) {\n\t\t\t\tif (sz == SPROTO_CB_NIL)\t\t// nil object , end of array\n\t\t\t\t\tbreak;\n\t\t\t\tif (sz == SPROTO_CB_NOARRAY)\t// no array, don't encode it\n\t\t\t\t\treturn 0;\n\t\t\t\treturn -1;\t// sz == SPROTO_CB_ERROR\n\t\t\t}\n\t\t\tif (size < 1)\n\t\t\t\treturn -1;\n\t\t\tbuffer[0] = v ? 1: 0;\n\t\t\tsize -= 1;\n\t\t\tbuffer += 1;\n\t\t\t++args->index;\n\t\t}\n\t\tbreak;\n\tdefault: {\n\t\tint noarray;\n\t\tbuffer = encode_array_object(cb, args, buffer, size, &noarray);\n\t\tif (buffer == NULL)\n\t\t\treturn -1;\n\t\tif (noarray)\n\t\t\treturn 0;\n\t\tbreak;\n\t}\n\t}\n\tsz = buffer - (data + SIZEOF_LENGTH);\n\treturn fill_size(data, sz);\n}\n\nint\nsproto_encode(const struct sproto_type *st, void * buffer, int size, sproto_callback cb, void *ud) {\n\tstruct sproto_arg args;\n\tuint8_t * header = buffer;\n\tuint8_t * data;\n\tint header_sz = SIZEOF_HEADER + st->maxn * SIZEOF_FIELD;\n\tint i;\n\tint index;\n\tint lasttag;\n\tint datasz;\n\tif (size < header_sz)\n\t\treturn -1;\n\targs.ud = ud;\n\tdata = header + header_sz;\n\tsize -= header_sz;\n\tindex = 0;\n\tlasttag = -1;\n\tfor (i=0;i<st->n;i++) {\n\t\tstruct field *f = &st->f[i];\n\t\tint type = f->type;\n\t\tint value = 0;\n\t\tint sz = -1;\n\t\targs.tagname = f->name;\n\t\targs.tagid = f->tag;\n\t\targs.subtype = f->st;\n\t\targs.mainindex = f->key;\n\t\targs.extra = f->extra;\n\t\targs.ktagname = NULL;\n\t\targs.vtagname = NULL;\n\t\tif (type & SPROTO_TARRAY) {\n\t\t\targs.type = type & (~SPROTO_TARRAY);\n\t\t\tif (f->map > 0) {\n\t\t\t\targs.ktagname = f->st->f[0].name;\n\t\t\t\targs.vtagname = f->st->f[1].name;\n\t\t\t}\n\t\t\tsz = encode_array(cb, &args, data, size);\n\t\t} else {\n\t\t\targs.type = type;\n\t\t\targs.index = 0;\n\t\t\tswitch(type) {\n\t\t\tcase SPROTO_TDOUBLE:\n\t\t\tcase SPROTO_TINTEGER:\n\t\t\tcase SPROTO_TBOOLEAN: {\n\t\t\t\tunion {\n\t\t\t\t\tuint64_t u64;\n\t\t\t\t\tuint32_t u32;\n\t\t\t\t} u;\n\t\t\t\targs.value = &u;\n\t\t\t\targs.length = sizeof(u);\n\t\t\t\tsz = cb(&args);\n\t\t\t\tif (sz < 0) {\n\t\t\t\t\tif (sz == SPROTO_CB_NIL)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (sz == SPROTO_CB_NOARRAY)\t// no array, don't encode it\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\treturn -1;\t// sz == SPROTO_CB_ERROR\n\t\t\t\t}\n\t\t\t\tif (sz == SIZEOF_INT32) {\n\t\t\t\t\tif (u.u32 < 0x7fff) {\n\t\t\t\t\t\tvalue = (u.u32+1) * 2;\n\t\t\t\t\t\tsz = 2; // sz can be any number > 0\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsz = encode_integer(u.u32, data, size);\n\t\t\t\t\t}\n\t\t\t\t} else if (sz == SIZEOF_INT64) {\n\t\t\t\t\tsz= encode_uint64(u.u64, data, size);\n\t\t\t\t} else {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase SPROTO_TSTRUCT:\n\t\t\tcase SPROTO_TSTRING:\n\t\t\t\tsz = encode_object(cb, &args, data, size);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (sz < 0)\n\t\t\treturn -1;\n\t\tif (sz > 0) {\n\t\t\tuint8_t * record;\n\t\t\tint tag;\n\t\t\tif (value == 0) {\n\t\t\t\tdata += sz;\n\t\t\t\tsize -= sz;\n\t\t\t}\n\t\t\trecord = header+SIZEOF_HEADER+SIZEOF_FIELD*index;\n\t\t\ttag = f->tag - lasttag - 1;\n\t\t\tif (tag > 0) {\n\t\t\t\t// skip tag\n\t\t\t\ttag = (tag - 1) * 2 + 1;\n\t\t\t\tif (tag > 0xffff)\n\t\t\t\t\treturn -1;\n\t\t\t\trecord[0] = tag & 0xff;\n\t\t\t\trecord[1] = (tag >> 8) & 0xff;\n\t\t\t\t++index;\n\t\t\t\trecord += SIZEOF_FIELD;\n\t\t\t}\n\t\t\t++index;\n\t\t\trecord[0] = value & 0xff;\n\t\t\trecord[1] = (value >> 8) & 0xff;\n\t\t\tlasttag = f->tag;\n\t\t}\n\t}\n\theader[0] = index & 0xff;\n\theader[1] = (index >> 8) & 0xff;\n\n\tdatasz = data - (header + header_sz);\n\tdata = header + header_sz;\n\tif (index != st->maxn) {\n\t\tmemmove(header + SIZEOF_HEADER + index * SIZEOF_FIELD, data, datasz);\n\t}\n\treturn SIZEOF_HEADER + index * SIZEOF_FIELD + datasz;\n}\n\nstatic int\ndecode_array_object(sproto_callback cb, struct sproto_arg *args, uint8_t * stream, int sz) {\n\tuint32_t hsz;\n\tint index = 1;\n\twhile (sz > 0) {\n\t\tif (sz < SIZEOF_LENGTH)\n\t\t\treturn -1;\n\t\thsz = todword(stream);\n\t\tstream += SIZEOF_LENGTH;\n\t\tsz -= SIZEOF_LENGTH;\n\t\tif (hsz > sz)\n\t\t\treturn -1;\n\t\targs->index = index;\n\t\targs->value = stream;\n\t\targs->length = hsz;\n\t\tif (cb(args))\n\t\t\treturn -1;\n\t\tsz -= hsz;\n\t\tstream += hsz;\n\t\t++index;\n\t}\n\treturn 0;\n}\n\nstatic inline uint64_t\nexpand64(uint32_t v) {\n\tuint64_t value = v;\n\tif (value & 0x80000000) {\n\t\tvalue |= (uint64_t)~0  << 32 ;\n\t}\n\treturn value;\n}\n\nstatic int\ndecode_empty_array(sproto_callback cb, struct sproto_arg *args) {\n\t// It's empty array, call cb with index == -1 to create the empty array.\n\targs->index = -1;\n\targs->value = NULL;\n\targs->length = 0;\n\treturn cb(args);\n}\n\nstatic int\ndecode_array(sproto_callback cb, struct sproto_arg *args, uint8_t * stream) {\n\tuint32_t sz = todword(stream);\n\tint type = args->type;\n\tint i;\n\tif (sz == 0) {\n\t\treturn decode_empty_array(cb, args);\n\t}\n\tstream += SIZEOF_LENGTH;\n\tswitch (type) {\n\tcase SPROTO_TDOUBLE:\n\tcase SPROTO_TINTEGER: {\n\t\tif (--sz == 0) {\n\t\t\t// An empty array but with a len prefix\n\t\t\treturn decode_empty_array(cb, args);\n\t\t}\n\t\tint len = *stream;\n\t\t++stream;\n\t\tif (len == SIZEOF_INT32) {\n\t\t\tif (sz % SIZEOF_INT32 != 0)\n\t\t\t\treturn -1;\n\t\t\tfor (i=0;i<sz/SIZEOF_INT32;i++) {\n\t\t\t\tuint64_t value = expand64(todword(stream + i*SIZEOF_INT32));\n\t\t\t\targs->index = i+1;\n\t\t\t\targs->value = &value;\n\t\t\t\targs->length = sizeof(value);\n\t\t\t\tcb(args);\n\t\t\t}\n\t\t} else if (len == SIZEOF_INT64) {\n\t\t\tif (sz % SIZEOF_INT64 != 0)\n\t\t\t\treturn -1;\n\t\t\tfor (i=0;i<sz/SIZEOF_INT64;i++) {\n\t\t\t\tuint64_t low = todword(stream + i*SIZEOF_INT64);\n\t\t\t\tuint64_t hi = todword(stream + i*SIZEOF_INT64 + SIZEOF_INT32);\n\t\t\t\tuint64_t value = low | hi << 32;\n\t\t\t\targs->index = i+1;\n\t\t\t\targs->value = &value;\n\t\t\t\targs->length = sizeof(value);\n\t\t\t\tcb(args);\n\t\t\t}\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t\tbreak;\n\t}\n\tcase SPROTO_TBOOLEAN:\n\t\tfor (i=0;i<sz;i++) {\n\t\t\tuint64_t value = stream[i];\n\t\t\targs->index = i+1;\n\t\t\targs->value = &value;\n\t\t\targs->length = sizeof(value);\n\t\t\tcb(args);\n\t\t}\n\t\tbreak;\n\tcase SPROTO_TSTRING:\n\tcase SPROTO_TSTRUCT:\n\t\treturn decode_array_object(cb, args, stream, sz);\n\tdefault:\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nint\nsproto_decode(const struct sproto_type *st, const void * data, int size, sproto_callback cb, void *ud) {\n\tstruct sproto_arg args;\n\tint total = size;\n\tuint8_t * stream;\n\tuint8_t * datastream;\n\tint fn;\n\tint i;\n\tint tag;\n\tif (size < SIZEOF_HEADER)\n\t\treturn -1;\n\t// debug print\n\t// printf(\"sproto_decode[%p] (%s)\\n\", ud, st->name);\n\tstream = (void *)data;\n\tfn = toword(stream);\n\tstream += SIZEOF_HEADER;\n\tsize -= SIZEOF_HEADER ;\n\tif (size < fn * SIZEOF_FIELD)\n\t\treturn -1;\n\tdatastream = stream + fn * SIZEOF_FIELD;\n\tsize -= fn * SIZEOF_FIELD;\n\targs.ud = ud;\n\n\ttag = -1;\n\tfor (i=0;i<fn;i++) {\n\t\tuint8_t * currentdata;\n\t\tstruct field * f;\n\t\tint value = toword(stream + i * SIZEOF_FIELD);\n\t\t++ tag;\n\t\tif (value & 1) {\n\t\t\ttag += value/2;\n\t\t\tcontinue;\n\t\t}\n\t\tvalue = value/2 - 1;\n\t\tcurrentdata = datastream;\n\t\tif (value < 0) {\n\t\t\tuint32_t sz;\n\t\t\tif (size < SIZEOF_LENGTH)\n\t\t\t\treturn -1;\n\t\t\tsz = todword(datastream);\n\t\t\tif (size < sz + SIZEOF_LENGTH)\n\t\t\t\treturn -1;\n\t\t\tdatastream += sz+SIZEOF_LENGTH;\n\t\t\tsize -= sz+SIZEOF_LENGTH;\n\t\t}\n\t\tf = findtag(st, tag);\n\t\tif (f == NULL)\n\t\t\tcontinue;\n\t\targs.tagname = f->name;\n\t\targs.tagid = f->tag;\n\t\targs.type = f->type;\n\t\targs.subtype = f->st;\n\t\targs.index = 0;\n\t\targs.mainindex = f->key;\n\t\targs.extra = f->extra;\n\t\targs.ktagname = NULL;\n\t\targs.vtagname = NULL;\n\t\tif (value < 0) {\n\t\t\tif (f->type & SPROTO_TARRAY) {\n\t\t\t\targs.type = f->type & (~SPROTO_TARRAY);\n\t\t\t\tif (f->map > 0) {\n\t\t\t\t\targs.ktagname = f->st->f[0].name;\n\t\t\t\t\targs.vtagname = f->st->f[1].name;\n\t\t\t\t}\n\t\t\t\tif (decode_array(cb, &args, currentdata)) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tswitch (f->type) {\n\t\t\t\tcase SPROTO_TDOUBLE:\n\t\t\t\tcase SPROTO_TINTEGER: {\n\t\t\t\t\tuint32_t sz = todword(currentdata);\n\t\t\t\t\tif (sz == SIZEOF_INT32) {\n\t\t\t\t\t\tuint64_t v = expand64(todword(currentdata + SIZEOF_LENGTH));\n\t\t\t\t\t\targs.value = &v;\n\t\t\t\t\t\targs.length = sizeof(v);\n\t\t\t\t\t\tcb(&args);\n\t\t\t\t\t} else if (sz != SIZEOF_INT64) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tuint32_t low = todword(currentdata + SIZEOF_LENGTH);\n\t\t\t\t\t\tuint32_t hi = todword(currentdata + SIZEOF_LENGTH + SIZEOF_INT32);\n\t\t\t\t\t\tuint64_t v = (uint64_t)low | (uint64_t) hi << 32;\n\t\t\t\t\t\targs.value = &v;\n\t\t\t\t\t\targs.length = sizeof(v);\n\t\t\t\t\t\tcb(&args);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase SPROTO_TSTRING:\n\t\t\t\tcase SPROTO_TSTRUCT: {\n\t\t\t\t\tuint32_t sz = todword(currentdata);\n\t\t\t\t\targs.value = currentdata+SIZEOF_LENGTH;\n\t\t\t\t\targs.length = sz;\n\t\t\t\t\tif (cb(&args))\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (f->type != SPROTO_TINTEGER && f->type != SPROTO_TBOOLEAN) {\n\t\t\treturn -1;\n\t\t} else {\n\t\t\tuint64_t v = value;\n\t\t\targs.value = &v;\n\t\t\targs.length = sizeof(v);\n\t\t\tcb(&args);\n\t\t}\n\t}\n\treturn total - size;\n}\n\n// 0 pack\n\nstatic int\npack_seg(const uint8_t *src, uint8_t * buffer, int sz, int n) {\n\tuint8_t header = 0;\n\tint notzero = 0;\n\tint i;\n\tuint8_t * obuffer = buffer;\n\t++buffer;\n\t--sz;\n\tif (sz < 0)\n\t\tobuffer = NULL;\n\n\tfor (i=0;i<8;i++) {\n\t\tif (src[i] != 0) {\n\t\t\tnotzero++;\n\t\t\theader |= 1<<i;\n\t\t\tif (sz > 0) {\n\t\t\t\t*buffer = src[i];\n\t\t\t\t++buffer;\n\t\t\t\t--sz;\n\t\t\t}\n\t\t}\n\t}\n\tif ((notzero == 7 || notzero == 6) && n > 0) {\n\t\tnotzero = 8;\n\t}\n\tif (notzero == 8) {\n\t\tif (n > 0) {\n\t\t\treturn 8;\n\t\t} else {\n\t\t\treturn 10;\n\t\t}\n\t}\n\tif (obuffer) {\n\t\t*obuffer = header;\n\t}\n\treturn notzero + 1;\n}\n\nstatic inline void\nwrite_ff(const uint8_t * src, const uint8_t * src_end, uint8_t * des, int n) {\n\tdes[0] = 0xff;\n\tdes[1] = n - 1;\n\tif (src + n * 8 <= src_end) {\n\t\tmemcpy(des+2, src, n*8);\n\t} else {\n\t\tint sz = (int)(src_end - src);\n\t\tmemcpy(des+2, src, sz);\n\t\tmemset(des+2+sz, 0, n*8-sz);\n\t}\n}\n\nint\nsproto_pack(const void * srcv, int srcsz, void * bufferv, int bufsz) {\n\tuint8_t tmp[8];\n\tint i;\n\tconst uint8_t * ff_srcstart = NULL;\n\tuint8_t * ff_desstart = NULL;\n\tint ff_n = 0;\n\tint size = 0;\n\tconst uint8_t * src = srcv;\n\tconst uint8_t * src_end = (uint8_t *)srcv + srcsz;\n\tuint8_t * buffer = bufferv;\n\tfor (i=0;i<srcsz;i+=8) {\n\t\tint n;\n\t\tint padding = i+8 - srcsz;\n\t\tif (padding > 0) {\n\t\t\tint j;\n\t\t\tmemcpy(tmp, src, 8-padding);\n\t\t\tfor (j=0;j<padding;j++) {\n\t\t\t\ttmp[7-j] = 0;\n\t\t\t}\n\t\t\tsrc = tmp;\n\t\t}\n\t\tn = pack_seg(src, buffer, bufsz, ff_n);\n\t\tbufsz -= n;\n\t\tif (n == 10) {\n\t\t\t// first FF\n\t\t\tff_srcstart = src;\n\t\t\tff_desstart = buffer;\n\t\t\tff_n = 1;\n\t\t} else if (n==8 && ff_n>0) {\n\t\t\t++ff_n;\n\t\t\tif (ff_n == 256) {\n\t\t\t\tif (bufsz >= 0) {\n\t\t\t\t\twrite_ff(ff_srcstart, src_end, ff_desstart, 256);\n\t\t\t\t}\n\t\t\t\tff_n = 0;\n\t\t\t}\n\t\t} else {\n\t\t\tif (ff_n > 0) {\n\t\t\t\tif (bufsz >= 0) {\n\t\t\t\t\twrite_ff(ff_srcstart, src_end, ff_desstart, ff_n);\n\t\t\t\t}\n\t\t\t\tff_n = 0;\n\t\t\t}\n\t\t}\n\t\tsrc += 8;\n\t\tbuffer += n;\n\t\tsize += n;\n\t}\n\tif(bufsz >= 0 && ff_n > 0) {\n\t\twrite_ff(ff_srcstart, src_end, ff_desstart, ff_n);\n\t}\n\treturn size;\n}\n\nint\nsproto_unpack(const void * srcv, int srcsz, void * bufferv, int bufsz) {\n\tconst uint8_t * src = srcv;\n\tuint8_t * buffer = bufferv;\n\tint size = 0;\n\twhile (srcsz > 0) {\n\t\tuint8_t header = src[0];\n\t\t--srcsz;\n\t\t++src;\n\t\tif (header == 0xff) {\n\t\t\tint n;\n\t\t\tif (srcsz <= 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tn = (src[0] + 1) * 8;\n\t\t\tif (srcsz < n + 1)\n\t\t\t\treturn -1;\n\t\t\tsrcsz -= n + 1;\n\t\t\t++src;\n\t\t\tif (bufsz >= n) {\n\t\t\t\tmemcpy(buffer, src, n);\n\t\t\t}\n\t\t\tbufsz -= n;\n\t\t\tbuffer += n;\n\t\t\tsrc += n;\n\t\t\tsize += n;\n\t\t} else {\n\t\t\tint i;\n\t\t\tfor (i=0;i<8;i++) {\n\t\t\t\tint nz = (header >> i) & 1;\n\t\t\t\tif (nz) {\n\t\t\t\t\tif (srcsz <= 0)\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\tif (bufsz > 0) {\n\t\t\t\t\t\t*buffer = *src;\n\t\t\t\t\t\t--bufsz;\n\t\t\t\t\t\t++buffer;\n\t\t\t\t\t}\n\t\t\t\t\t++src;\n\t\t\t\t\t--srcsz;\n\t\t\t\t} else {\n\t\t\t\t\tif (bufsz > 0) {\n\t\t\t\t\t\t*buffer = 0;\n\t\t\t\t\t\t--bufsz;\n\t\t\t\t\t\t++buffer;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t++size;\n\t\t\t}\n\t\t}\n\t}\n\treturn size;\n}\n"
  },
  {
    "path": "lualib-src/sproto/sproto.h",
    "content": "#ifndef sproto_h\n#define sproto_h\n\n#include <stddef.h>\n\nstruct sproto;\nstruct sproto_type;\n\n#define SPROTO_REQUEST 0\n#define SPROTO_RESPONSE 1\n\n// type (sproto_arg.type)\n#define SPROTO_TINTEGER 0\n#define SPROTO_TBOOLEAN 1\n#define SPROTO_TSTRING 2\n#define SPROTO_TDOUBLE 3\n#define SPROTO_TSTRUCT 4\n\n// container type\n#define SPROTO_TARRAY 0x80\n\n// sub type of string (sproto_arg.extra)\n#define SPROTO_TSTRING_STRING 0\n#define SPROTO_TSTRING_BINARY 1\n\n#define SPROTO_CB_ERROR -1\n#define SPROTO_CB_NIL -2\n#define SPROTO_CB_NOARRAY -3\n\nstruct sproto * sproto_create(const void * proto, size_t sz);\nvoid sproto_release(struct sproto *);\n\nint sproto_prototag(const struct sproto *, const char * name);\nconst char * sproto_protoname(const struct sproto *, int proto);\n// SPROTO_REQUEST(0) : request, SPROTO_RESPONSE(1): response\nstruct sproto_type * sproto_protoquery(const struct sproto *, int proto, int what);\nint sproto_protoresponse(const struct sproto *, int proto);\n\nstruct sproto_type * sproto_type(const struct sproto *, const char * type_name);\n\nint sproto_pack(const void * src, int srcsz, void * buffer, int bufsz);\nint sproto_unpack(const void * src, int srcsz, void * buffer, int bufsz);\n\nstruct sproto_arg {\n\tvoid *ud;\n\tconst char *tagname;\n\tint tagid;\n\tint type;\n\tstruct sproto_type *subtype;\n\tvoid *value;\n\tint length;\n\tint index;\t// array base 1, negative value indicates that it is a empty array\n\tint mainindex;\t// for map\n\tint extra; // SPROTO_TINTEGER: decimal ; SPROTO_TSTRING 0:utf8 string 1:binary\n\n\t// When interpretd two fields struct as map, the following fields must not be NULL.\n\tconst char *ktagname;\n\tconst char *vtagname;\n};\n\ntypedef int (*sproto_callback)(const struct sproto_arg *args);\n\nint sproto_decode(const struct sproto_type *, const void * data, int size, sproto_callback cb, void *ud);\nint sproto_encode(const struct sproto_type *, void * buffer, int size, sproto_callback cb, void *ud);\n\n// for debug use\nvoid sproto_dump(struct sproto *);\nconst char * sproto_name(struct sproto_type *);\n\n#endif\n"
  },
  {
    "path": "mingw.mk",
    "content": "# Cross-compilation toolchain\nCC = x86_64-w64-mingw32-gcc\nAR = x86_64-w64-mingw32-ar\nRANLIB = x86_64-w64-mingw32-ranlib\n\nLUA_CLIB_PATH ?= luaclib\nCSERVICE_PATH ?= cservice\nSKYNET_BUILD_PATH ?= .\nCOMPAT_MINGW_DIR = 3rd/compat-mingw\n\nLUA_DIR = 3rd/lua\nLUA_CFLAGS = -g -O2 -Wall -I. -std=gnu99 -I../../skynet-src\nLUA_STATICLIB := 3rd/lua/liblua.a\nLUA_DLL ?= 3rd/lua/lua54.dll\nSKYNET_DLL ?= $(SKYNET_BUILD_PATH)/skynet.dll\nLUA_INC ?= $(LUA_DIR)\n\n# Lua linking options\nLUA_LIBS = -L$(LUA_DIR) -llua54\nLUA_STATIC_LIBS = $(LUA_STATICLIB)\n\n# Skynet linking and include options\nSKYNET_LINK_LIBS = -L$(SKYNET_BUILD_PATH) -lskynet\nSKYNET_INCLUDES = -Iskynet-src -I$(COMPAT_MINGW_DIR) -I$(LUA_INC)\nSHARED_BUILD = $(CC) $(CFLAGS) $(SHARED)\n\n# Compiler flags\nCFLAGS = -g -O2 -Wall -std=gnu99 -I$(LUA_INC) $(MYCFLAGS)\nCFLAGS += -I3rd/lua -Iskynet-src -I$(COMPAT_MINGW_DIR)\nCFLAGS += -include $(COMPAT_MINGW_DIR)/compat.h\nCFLAGS += -Wno-int-conversion -Wno-incompatible-pointer-types -Wno-pointer-sign -Wno-unused-function\n\nLDFLAGS = -Wl,--export-all-symbols,--out-implib,libskynet.a\nSHARED = -fPIC --shared -Wl,--export-all-symbols,--enable-auto-import,--allow-shlib-undefined,--unresolved-symbols=ignore-all\n\nSKYNET_LIBS = -static-libgcc -Wl,-Bstatic -lpthread -Wl,-Bdynamic -lm -lws2_32 -lgdi32\n\nSKYNET_DEFINES = -DNOUSE_JEMALLOC\n\nCOMPAT_LIB = $(COMPAT_MINGW_DIR)/libcompat.a\n\nCSERVICE = snlua logger gate harbor\n\nLUA_CLIB = skynet client bson md5 sproto lpeg\n\nLUA_CLIB_SKYNET = \\\n  lua-skynet.c lua-seri.c \\\n  lua-socket.c \\\n  lua-mongo.c \\\n  lua-netpack.c \\\n  lua-memory.c \\\n  lua-multicast.c \\\n  lua-cluster.c \\\n  lua-crypt.c lsha1.c \\\n  lua-sharedata.c \\\n  lua-stm.c \\\n  lua-debugchannel.c \\\n  lua-datasheet.c \\\n  lua-sharetable.c \\\n  \\\n\nSKYNET_SRC = skynet_main.c skynet_handle.c skynet_module.c skynet_mq.c \\\n  skynet_server.c skynet_start.c skynet_timer.c skynet_error.c \\\n  skynet_harbor.c skynet_env.c skynet_monitor.c skynet_socket.c socket_server.c \\\n  mem_info.c malloc_hook.c skynet_daemon.c skynet_log.c\n\n$(LUA_STATICLIB): \n\t@echo \"Building Lua static library...\"\n\tcd $(LUA_DIR) && $(CC) $(LUA_CFLAGS) -DMAKE_LIB -c onelua.c -o onelua.o\n\tcd $(LUA_DIR) && $(AR) rcs liblua.a onelua.o\n\n$(LUA_DLL) : $(LUA_STATICLIB)\n\t@echo \"Building Lua DLL...\"\n\tcd $(LUA_DIR) && $(CC) -shared -o lua54.dll onelua.o -Wl,--export-all-symbols,--out-implib,liblua54.a $(SKYNET_LIBS)\n\t@echo \"Lua DLL and import library created successfully\"\n\n$(LUA_DIR)/lua.exe : $(LUA_DLL) $(LUA_STATICLIB)\n\t@echo \"Building Lua interpreter...\"\n\tcd $(LUA_DIR) && $(CC) $(LUA_CFLAGS) -c lua.c -o lua.o\n\tcd $(LUA_DIR) && $(CC) $(LUA_CFLAGS) -o lua.exe lua.o -L. -llua54 $(SKYNET_LIBS)\n\tcp $(LUA_DLL) $(SKYNET_BUILD_PATH)/\n\n$(LUA_DIR)/luac.exe : $(LUA_DLL) $(LUA_STATICLIB)\n\t@echo \"Building Lua compiler...\"\n\tcd $(LUA_DIR) && $(CC) $(LUA_CFLAGS) -DMAKE_LUAC -c onelua.c -o luac.o\n\tcd $(LUA_DIR) && $(CC) $(LUA_CFLAGS) -o luac.exe luac.o liblua.a $(SKYNET_LIBS)\n\n$(COMPAT_LIB): $(COMPAT_MINGW_DIR)/compat.c\n\t@echo \"Building compatibility library...\"\n\t$(CC) $(CFLAGS) -c $(COMPAT_MINGW_DIR)/compat.c -o $(COMPAT_MINGW_DIR)/compat.o\n\tcd $(COMPAT_MINGW_DIR) && $(AR) rcs libcompat.a compat.o\n\tcd $(COMPAT_MINGW_DIR) && $(RANLIB) libcompat.a\n\n# Build order: first build core libraries, then dependent modules\nall : core_libs modules tools\n\n.PHONY: core_libs modules tools\n\ncore_libs: $(LUA_STATICLIB) $(LUA_DLL) $(SKYNET_DLL)\n\nmodules: core_libs $(foreach v, $(CSERVICE), $(CSERVICE_PATH)/$(v).so) $(foreach v, $(LUA_CLIB), $(LUA_CLIB_PATH)/$(v).so)\n\ntools: core_libs $(LUA_DIR)/lua.exe $(LUA_DIR)/luac.exe $(SKYNET_BUILD_PATH)/skynet.exe\n\n\nSKYNET_LIB_SRC = $(filter-out skynet_main.c, $(SKYNET_SRC))\n\n\n$(SKYNET_DLL) : $(foreach v, $(SKYNET_LIB_SRC), skynet-src/$(v)) $(COMPAT_LIB) $(LUA_DLL)\n\t@echo \"Building skynet.dll...\"\n\t$(CC) $(CFLAGS) -shared -o $@ $(foreach v, $(SKYNET_LIB_SRC), skynet-src/$(v)) $(COMPAT_LIB) $(LUA_LIBS) $(SKYNET_INCLUDES) $(SKYNET_LIBS) $(SKYNET_DEFINES) $(LDFLAGS)\n\n\n$(SKYNET_BUILD_PATH)/skynet.exe : skynet-src/skynet_main.c $(SKYNET_DLL) $(COMPAT_LIB) $(LUA_DLL)\n\t@echo \"Building skynet.exe...\"\n\t$(CC) $(CFLAGS) -o $@ skynet-src/skynet_main.c $(COMPAT_LIB) $(SKYNET_LINK_LIBS) $(LUA_LIBS) $(SKYNET_INCLUDES) $(SKYNET_LIBS) $(SKYNET_DEFINES)\n\tcp $(LUA_DLL) $(SKYNET_BUILD_PATH)/\n\n$(LUA_CLIB_PATH) :\n\tmkdir $(LUA_CLIB_PATH)\n\n$(CSERVICE_PATH) :\n\tmkdir $(CSERVICE_PATH)\n\ndefine CSERVICE_TEMP\n  $$(CSERVICE_PATH)/$(1).so : service-src/service_$(1).c $$(LUA_DLL) $$(SKYNET_DLL) | $$(CSERVICE_PATH)\n\t$$(CC) $$(CFLAGS) $$(SHARED) $$< -o $$@ $$(SKYNET_INCLUDES) $$(LUA_LIBS) $$(SKYNET_LINK_LIBS)\nendef\n\n$(foreach v, $(CSERVICE), $(eval $(call CSERVICE_TEMP,$(v))))\n\n\n$(LUA_CLIB_PATH)/skynet.so : $(addprefix lualib-src/,$(LUA_CLIB_SKYNET)) $(SKYNET_DLL) $(LUA_DLL) | $(LUA_CLIB_PATH)\n\t$(SHARED_BUILD) $(addprefix lualib-src/,$(LUA_CLIB_SKYNET)) -o $@ $(SKYNET_INCLUDES) -Iservice-src -Ilualib-src $(SKYNET_LINK_LIBS) $(LUA_LIBS) $(SKYNET_LIBS)\n\n$(LUA_CLIB_PATH)/bson.so : lualib-src/lua-bson.c $(LUA_DLL) | $(LUA_CLIB_PATH)\n\t$(SHARED_BUILD) $^ -o $@ $(SKYNET_INCLUDES) $(LUA_LIBS) $(SKYNET_LIBS)\n\n$(LUA_CLIB_PATH)/md5.so : 3rd/lua-md5/md5.c 3rd/lua-md5/md5lib.c 3rd/lua-md5/compat-5.2.c $(LUA_DLL) | $(LUA_CLIB_PATH)\n\t$(SHARED_BUILD) -I3rd/lua-md5 -Wno-attributes $^ -o $@ $(LUA_LIBS) $(SKYNET_LIBS)\n\n$(LUA_CLIB_PATH)/client.so : lualib-src/lua-clientsocket.c lualib-src/lua-crypt.c lualib-src/lsha1.c $(COMPAT_LIB) $(LUA_DLL) | $(LUA_CLIB_PATH)\n\t$(SHARED_BUILD) $^ -o $@ $(LUA_LIBS) $(SKYNET_LIBS)\n\n$(LUA_CLIB_PATH)/sproto.so : lualib-src/sproto/sproto.c lualib-src/sproto/lsproto.c $(LUA_DLL) | $(LUA_CLIB_PATH)\n\t$(SHARED_BUILD) -Ilualib-src/sproto $^ -o $@ $(LUA_LIBS) $(SKYNET_LIBS)\n\n$(LUA_CLIB_PATH)/lpeg.so : 3rd/lpeg/lpcap.c 3rd/lpeg/lpcode.c 3rd/lpeg/lpprint.c 3rd/lpeg/lptree.c 3rd/lpeg/lpvm.c 3rd/lpeg/lpcset.c $(LUA_DLL) | $(LUA_CLIB_PATH)\n\t$(SHARED_BUILD) -I3rd/lpeg $^ -o $@ $(LUA_LIBS) $(SKYNET_LIBS)\n\n.PHONY: clean cleanall core_libs modules tools\n\nclean :\n\trm -f $(SKYNET_BUILD_PATH)/*.exe $(SKYNET_BUILD_PATH)/*.dll $(SKYNET_BUILD_PATH)/*.a\n\trm -f $(COMPAT_LIB) $(COMPAT_MINGW_DIR)/*.o\n\trm -f $(CSERVICE_PATH)/*.so $(LUA_CLIB_PATH)/*.so\n\trm -f $(LUA_DIR)/*.a\n\ncleanall: clean\n\trm -f $(LUA_STATICLIB)\n\trm -f $(LUA_DIR)/*.exe $(LUA_DIR)/*.dll $(LUA_DIR)/*.a $(LUA_DIR)/*.o\n"
  },
  {
    "path": "platform.mk",
    "content": "PLAT ?= none\nPLATS = linux freebsd macosx mingw\n\nCC ?= gcc\n\n.PHONY : none $(PLATS) clean all cleanall\n\n#ifneq ($(PLAT), none)\n\n.PHONY : default\n\ndefault :\n\t$(MAKE) $(PLAT)\n\n#endif\n\nnone :\n\t@echo \"Please do 'make PLATFORM' where PLATFORM is one of these:\"\n\t@echo \"   $(PLATS)\"\n\nSKYNET_LIBS := -lpthread -lm\nSHARED := -fPIC --shared\nEXPORT := -Wl,-E\n\nlinux : PLAT = linux\nmacosx : PLAT = macosx\nfreebsd : PLAT = freebsd\nmingw : PLAT = mingw\n\nmacosx : SHARED := -fPIC -dynamiclib -Wl,-undefined,dynamic_lookup\nmacosx : EXPORT :=\nmacosx linux : SKYNET_LIBS += -ldl\nlinux freebsd : SKYNET_LIBS += -lrt\n\n# Turn off jemalloc and malloc hook on macosx\n\nmacosx : MALLOC_STATICLIB :=\nmacosx : SKYNET_DEFINES :=-DNOUSE_JEMALLOC\n\nlinux macosx freebsd :\n\t$(MAKE) all PLAT=$@ SKYNET_LIBS=\"$(SKYNET_LIBS)\" SHARED=\"$(SHARED)\" EXPORT=\"$(EXPORT)\" MALLOC_STATICLIB=\"$(MALLOC_STATICLIB)\" SKYNET_DEFINES=\"$(SKYNET_DEFINES)\"\n\nmingw :\n\t$(MAKE) -f mingw.mk all PLAT=$@\n"
  },
  {
    "path": "service/bootstrap.lua",
    "content": "local service = require \"skynet.service\"\nlocal skynet = require \"skynet.manager\"\t-- import skynet.launch, ...\n\nskynet.start(function()\n\tlocal standalone = skynet.getenv \"standalone\"\n\n\tlocal launcher = assert(skynet.launch(\"snlua\",\"launcher\"))\n\tskynet.name(\".launcher\", launcher)\n\n\tlocal harbor_id = tonumber(skynet.getenv \"harbor\" or 0)\n\tif harbor_id == 0 then\n\t\tassert(standalone ==  nil)\n\t\tstandalone = true\n\t\tskynet.setenv(\"standalone\", \"true\")\n\n\t\tlocal ok, slave = pcall(skynet.newservice, \"cdummy\")\n\t\tif not ok then\n\t\t\tskynet.abort()\n\t\tend\n\t\tskynet.name(\".cslave\", slave)\n\n\telse\n\t\tif standalone then\n\t\t\tif not pcall(skynet.newservice,\"cmaster\") then\n\t\t\t\tskynet.abort()\n\t\t\tend\n\t\tend\n\n\t\tlocal ok, slave = pcall(skynet.newservice, \"cslave\")\n\t\tif not ok then\n\t\t\tskynet.abort()\n\t\tend\n\t\tskynet.name(\".cslave\", slave)\n\tend\n\n\tif standalone then\n\t\tlocal datacenter = skynet.newservice \"datacenterd\"\n\t\tskynet.name(\"DATACENTER\", datacenter)\n\tend\n\tskynet.newservice \"service_mgr\"\n\n\tlocal enablessl = skynet.getenv \"enablessl\"\n\tif enablessl == \"true\" then\n\t\tservice.new(\"ltls_holder\", function ()\n\t\t\tlocal c = require \"ltls.init.c\"\n\t\t\tc.constructor()\n\t\tend)\n\tend\n\n\tpcall(skynet.newservice,skynet.getenv \"start\" or \"main\")\n\tskynet.exit()\nend)\n"
  },
  {
    "path": "service/cdummy.lua",
    "content": "local skynet = require \"skynet\"\nrequire \"skynet.manager\"\t-- import skynet.launch, ...\n\nlocal globalname = {}\nlocal queryname = {}\nlocal harbor = {}\nlocal harbor_service\n\nskynet.register_protocol {\n\tname = \"harbor\",\n\tid = skynet.PTYPE_HARBOR,\n\tpack = function(...) return ... end,\n\tunpack = skynet.tostring,\n}\n\nskynet.register_protocol {\n\tname = \"text\",\n\tid = skynet.PTYPE_TEXT,\n\tpack = function(...) return ... end,\n\tunpack = skynet.tostring,\n}\n\nlocal function response_name(name)\n\tlocal address = globalname[name]\n\tif queryname[name] then\n\t\tlocal tmp = queryname[name]\n\t\tqueryname[name] = nil\n\t\tfor _,resp in ipairs(tmp) do\n\t\t\tresp(true, address)\n\t\tend\n\tend\nend\n\nfunction harbor.REGISTER(name, handle)\n\tassert(globalname[name] == nil)\n\tglobalname[name] = handle\n\tresponse_name(name)\n\tskynet.redirect(harbor_service, handle, \"harbor\", 0, \"N \" .. name)\nend\n\nfunction harbor.QUERYNAME(name)\n\tif name:byte() == 46 then\t-- \".\" , local name\n\t\tskynet.ret(skynet.pack(skynet.localname(name)))\n\t\treturn\n\tend\n\tlocal result = globalname[name]\n\tif result then\n\t\tskynet.ret(skynet.pack(result))\n\t\treturn\n\tend\n\tlocal queue = queryname[name]\n\tif queue == nil then\n\t\tqueue = { skynet.response() }\n\t\tqueryname[name] = queue\n\telse\n\t\ttable.insert(queue, skynet.response())\n\tend\nend\n\nfunction harbor.LINK(id)\n\tskynet.ret()\nend\n\nfunction harbor.CONNECT(id)\n\tskynet.error(\"Can't connect to other harbor in single node mode\")\nend\n\nskynet.start(function()\n\tlocal harbor_id = tonumber(skynet.getenv \"harbor\")\n\tassert(harbor_id == 0)\n\n\tskynet.dispatch(\"lua\", function (session,source,command,...)\n\t\tlocal f = assert(harbor[command])\n\t\tf(...)\n\tend)\n\tskynet.dispatch(\"text\", function(session,source,command)\n\t\t-- ignore all the command\n\tend)\n\n\tharbor_service = assert(skynet.launch(\"harbor\", harbor_id, skynet.self()))\nend)\n"
  },
  {
    "path": "service/clusteragent.lua",
    "content": "local skynet = require \"skynet\"\nlocal socket = require \"skynet.socket\"\nlocal cluster = require \"skynet.cluster.core\"\nlocal ignoreret = skynet.ignoreret\n\nlocal clusterd, gate, fd = ...\nclusterd = tonumber(clusterd)\ngate = tonumber(gate)\nfd = tonumber(fd)\n\nlocal large_request = {}\nlocal inquery_name = {}\nlocal register_name\n\nlocal register_name_mt = { __index =\n\tfunction(self, name)\n\t\tlocal waitco = inquery_name[name]\n\t\tif waitco then\n\t\t\tlocal co = coroutine.running()\n\t\t\ttable.insert(waitco, co)\n\t\t\tskynet.wait(co)\n\t\t\treturn rawget(register_name, name)\n\t\telse\n\t\t\twaitco = {}\n\t\t\tinquery_name[name] = waitco\n\n\t\t\tlocal addr = skynet.call(clusterd, \"lua\", \"queryname\", name:sub(2))\t-- name must be '@xxxx'\n\t\t\tif addr then\n\t\t\t\tregister_name[name] = addr\n\t\t\tend\n\t\t\tinquery_name[name] = nil\n\t\t\tfor _, co in ipairs(waitco) do\n\t\t\t\tskynet.wakeup(co)\n\t\t\tend\n\t\t\treturn addr\n\t\tend\n\tend\n}\n\nlocal function new_register_name()\n\tregister_name = setmetatable({}, register_name_mt)\nend\nnew_register_name()\n\nlocal tracetag\n\nlocal function dispatch_request(_,_,addr, session, msg, sz, padding, is_push)\n\tignoreret()\t-- session is fd, don't call skynet.ret\n\tif session == nil then\n\t\t-- trace\n\t\ttracetag = addr\n\t\treturn\n\tend\n\tif padding then\n\t\tlocal req = large_request[session] or { addr = addr , is_push = is_push, tracetag = tracetag }\n\t\ttracetag = nil\n\t\tlarge_request[session] = req\n\t\tcluster.append(req, msg, sz)\n\t\treturn\n\telse\n\t\tlocal req = large_request[session]\n\t\tif req then\n\t\t\ttracetag = req.tracetag\n\t\t\tlarge_request[session] = nil\n\t\t\tcluster.append(req, msg, sz)\n\t\t\tmsg,sz = cluster.concat(req)\n\t\t\taddr = req.addr\n\t\t\tis_push = req.is_push\n\t\tend\n\t\tif not msg then\n\t\t\ttracetag = nil\n\t\t\tlocal response = cluster.packresponse(session, false, \"Invalid large req\")\n\t\t\tsocket.write(fd, response)\n\t\t\treturn\n\t\tend\n\tend\n\tlocal ok, response\n\tif addr == 0 then\n\t\tlocal name = skynet.unpack(msg, sz)\n\t\tskynet.trash(msg, sz)\n\t\tlocal addr = register_name[\"@\" .. name]\n\t\tif addr then\n\t\t\tok = true\n\t\t\tmsg = skynet.packstring(addr)\n\t\telse\n\t\t\tok = false\n\t\t\tmsg = \"name not found\"\n\t\tend\n\t\tsz = nil\n\telse\n\t\tif cluster.isname(addr) then\n\t\t\taddr = register_name[addr]\n\t\tend\n\t\tif addr then\n\t\t\tif is_push then\n\t\t\t\tskynet.rawsend(addr, \"lua\", msg, sz)\n\t\t\t\treturn\t-- no response\n\t\t\telse\n\t\t\t\tif tracetag then\n\t\t\t\t\tok , msg, sz = pcall(skynet.tracecall, tracetag, addr, \"lua\", msg, sz)\n\t\t\t\t\ttracetag = nil\n\t\t\t\telse\n\t\t\t\t\tok , msg, sz = pcall(skynet.rawcall, addr, \"lua\", msg, sz)\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tok = false\n\t\t\tmsg = \"Invalid name\"\n\t\tend\n\tend\n\tif ok then\n\t\tresponse = cluster.packresponse(session, true, msg, sz)\n\t\tif type(response) == \"table\" then\n\t\t\tfor _, v in ipairs(response) do\n\t\t\t\tsocket.lwrite(fd, v)\n\t\t\tend\n\t\telse\n\t\t\tsocket.write(fd, response)\n\t\tend\n\telse\n\t\tresponse = cluster.packresponse(session, false, msg)\n\t\tsocket.write(fd, response)\n\tend\nend\n\nskynet.start(function()\n\tskynet.register_protocol {\n\t\tname = \"client\",\n\t\tid = skynet.PTYPE_CLIENT,\n\t\tunpack = cluster.unpackrequest,\n\t\tdispatch = dispatch_request,\n\t}\n\t-- fd can write, but don't read fd, the data package will forward from gate though client protocol.\n\t-- forward may fail, see https://github.com/cloudwu/skynet/issues/1958\n\tpcall(skynet.call,gate, \"lua\", \"forward\", fd)\n\n\tskynet.dispatch(\"lua\", function(_,source, cmd, ...)\n\t\tif cmd == \"exit\" then\n\t\t\tsocket.close_fd(fd)\n\t\t\tskynet.exit()\n\t\telseif cmd == \"namechange\" then\n\t\t\tnew_register_name()\n\t\telse\n\t\t\tskynet.error(string.format(\"Invalid command %s from %s\", cmd, skynet.address(source)))\n\t\tend\n\tend)\nend)\n"
  },
  {
    "path": "service/clusterd.lua",
    "content": "local skynet = require \"skynet\"\nrequire \"skynet.manager\"\nlocal cluster = require \"skynet.cluster.core\"\n\nlocal config_name = skynet.getenv \"cluster\"\nlocal node_address = {}\nlocal node_sender = {}\nlocal node_sender_closed = {}\nlocal command = {}\nlocal config = {}\nlocal nodename = cluster.nodename()\n\nlocal connecting = {}\n\nlocal function open_channel(t, key)\n\tlocal ct = connecting[key]\n\tif ct then\n\t\tlocal co = coroutine.running()\n\t\tlocal channel\n\t\twhile ct do\n\t\t\ttable.insert(ct, co)\n\t\t\tskynet.wait(co)\n\t\t\tchannel = ct.channel\n\t\t\tct = connecting[key]\n\t\t\t-- reload again if ct ~= nil\n\t\tend\n\t\treturn assert(node_address[key] and channel)\n\tend\n\tct = {}\n\tconnecting[key] = ct\n\tlocal address = node_address[key]\n\tif address == nil and not config.nowaiting then\n\t\tlocal co = coroutine.running()\n\t\tassert(ct.namequery == nil)\n\t\tct.namequery = co\n\t\tskynet.error(\"Waiting for cluster node [\".. key..\"]\")\n\t\tskynet.wait(co)\n\t\taddress = node_address[key]\n\tend\n\tlocal succ, err, c\n\tif address then\n\t\tc = node_sender[key]\n\t\tif c == nil then\n\t\t\tc = skynet.newservice(\"clustersender\", key, nodename, address)\n\t\t\tif node_sender[key] then\n\t\t\t\t-- double check\n\t\t\t\tskynet.kill(c)\n\t\t\t\tc = node_sender[key]\n\t\t\telse\n\t\t\t\tnode_sender[key] = c\n\t\t\tend\n\t\tend\n\n\t\tsucc = pcall(skynet.call, c, \"lua\", \"changenode\", address)\n\n\t\tif succ then\n\t\t\tt[key] = c\n\t\t\tct.channel = c\n                        node_sender_closed[key] = nil\n\t\telse\n\t\t\terr = string.format(\"changenode [%s] (%s) failed\", key, address)\n\t\tend\n\telseif address == false then\n\t\tc = node_sender[key]\n\t\tif c == nil or node_sender_closed[key] then\n\t\t\t-- no sender or closed, always succ\n\t\t\tsucc = true\n\t\telse\n\t\t\t-- turn off the sender\n\t\t\tsucc, err = pcall(skynet.call, c, \"lua\", \"changenode\", false)\n                        if succ then --turn off failed, wait next index todo turn off\n                                node_sender_closed[key] = true\n                        end\n\t\tend\n\telse\n\t\terr = string.format(\"cluster node [%s] is absent.\", key)\n\tend\n\tconnecting[key] = nil\n\tfor _, co in ipairs(ct) do\n\t\tskynet.wakeup(co)\n\tend\n\tif node_address[key] ~= address then\n\t\treturn open_channel(t,key)\n\tend\n\tassert(succ, err)\n\treturn c\nend\n\nlocal node_channel = setmetatable({}, { __index = open_channel })\n\nlocal function loadconfig(tmp)\n\tif tmp == nil then\n\t\ttmp = {}\n\t\tif config_name then\n\t\t\tlocal f = assert(io.open(config_name))\n\t\t\tlocal source = f:read \"*a\"\n\t\t\tf:close()\n\t\t\tassert(load(source, \"@\"..config_name, \"t\", tmp))()\n\t\tend\n\tend\n\tlocal reload = {}\n\tfor name,address in pairs(tmp) do\n\t\tif name:sub(1,2) == \"__\" then\n\t\t\tlocal opt = name:sub(3)\n\t\t\tconfig[opt] = address\n\t\t\tskynet.error(string.format(\"Config %s = %s\", opt, address))\n\t\telse\n\t\t\tassert(address == false or type(address) == \"string\")\n\t\t\tif node_address[name] ~= address then\n\t\t\t\t-- address changed\n\t\t\t\tif node_sender[name] then\n\t\t\t\t\t-- reset connection if node_sender[name] exist\n\t\t\t\t\tnode_channel[name] = nil\n\t\t\t\t\ttable.insert(reload, name)\n\t\t\t\tend\n\t\t\t\tnode_address[name] = address\n\t\t\tend\n\t\t\tlocal ct = connecting[name]\n\t\t\tif ct and ct.namequery and not config.nowaiting then\n\t\t\t\tskynet.error(string.format(\"Cluster node [%s] resolved : %s\", name, address))\n\t\t\t\tskynet.wakeup(ct.namequery)\n\t\t\tend\n\t\tend\n\tend\n\tif config.nowaiting then\n\t\t-- wakeup all connecting request\n\t\tfor name, ct in pairs(connecting) do\n\t\t\tif ct.namequery then\n\t\t\t\tskynet.wakeup(ct.namequery)\n\t\t\tend\n\t\tend\n\tend\n\tfor _, name in ipairs(reload) do\n\t\t-- open_channel would block\n\t\tskynet.fork(open_channel, node_channel, name)\n\tend\nend\n\nfunction command.reload(source, config)\n\tloadconfig(config)\n\tskynet.ret(skynet.pack(nil))\nend\n\nfunction command.listen(source, addr, port, maxclient)\n\tlocal gate = skynet.newservice(\"gate\")\n\tif port == nil then\n\t\tlocal address = assert(node_address[addr], addr .. \" is down\")\n\t\tskynet.call(gate, \"lua\", \"open\", { address = address, port = port, maxclient = maxclient })\n\t\tskynet.ret(skynet.pack(addr, port))\n\telse\n\t\tlocal realaddr, realport = skynet.call(gate, \"lua\", \"open\", { address = addr, port = port, maxclient = maxclient })\n\t\tskynet.ret(skynet.pack(realaddr, realport))\n\tend\nend\n\nfunction command.sender(source, node)\n\tskynet.ret(skynet.pack(node_channel[node]))\nend\n\nfunction command.senders(source)\n\tskynet.retpack(node_sender)\nend\n\nlocal proxy = {}\n\nfunction command.proxy(source, node, name)\n\tif name == nil then\n\t\tnode, name = node:match \"^([^@.]+)([@.].+)\"\n\t\tif name == nil then\n\t\t\terror (\"Invalid name \" .. tostring(node))\n\t\tend\n\tend\n\tlocal fullname = node .. \".\" .. name\n\tlocal p = proxy[fullname]\n\tif p == nil then\n\t\tp = skynet.newservice(\"clusterproxy\", node, name)\n\t\t-- double check\n\t\tif proxy[fullname] then\n\t\t\tskynet.kill(p)\n\t\t\tp = proxy[fullname]\n\t\telse\n\t\t\tproxy[fullname] = p\n\t\tend\n\tend\n\tskynet.ret(skynet.pack(p))\nend\n\nlocal cluster_agent = {}\t-- fd:service\nlocal register_name = {}\n\nlocal function clearnamecache()\n\tfor fd, service in pairs(cluster_agent) do\n\t\tif type(service) == \"number\" then\n\t\t\tskynet.send(service, \"lua\", \"namechange\")\n\t\tend\n\tend\nend\n\nfunction command.register(source, name, addr)\n\tassert(register_name[name] == nil)\n\taddr = addr or source\n\tlocal old_name = register_name[addr]\n\tif old_name then\n\t\tregister_name[old_name] = nil\n\t\tclearnamecache()\n\tend\n\tregister_name[addr] = name\n\tregister_name[name] = addr\n\tskynet.ret(nil)\n\tskynet.error(string.format(\"Register [%s] :%08x\", name, addr))\nend\n\nfunction command.unregister(_, name)\n\tif not register_name[name] then\n\t\treturn skynet.ret(nil)\n\tend\n\tlocal addr = register_name[name]\n\tregister_name[addr] = nil\n\tregister_name[name] = nil\n\tclearnamecache()\n\tskynet.ret(nil)\n\tskynet.error(string.format(\"Unregister [%s] :%08x\", name, addr))\nend\n\nfunction command.queryname(source, name)\n\tskynet.ret(skynet.pack(register_name[name]))\nend\n\nfunction command.socket(source, subcmd, fd, msg)\n\tif subcmd == \"open\" then\n\t\tskynet.error(string.format(\"socket accept from %s\", msg))\n\t\t-- new cluster agent\n\t\tcluster_agent[fd] = false\n\t\tlocal agent = skynet.newservice(\"clusteragent\", skynet.self(), source, fd)\n\t\tlocal closed = cluster_agent[fd]\n\t\tcluster_agent[fd] = agent\n\t\tif closed then\n\t\t\tskynet.send(agent, \"lua\", \"exit\")\n\t\t\tcluster_agent[fd] = nil\n\t\tend\n\telse\n\t\tif subcmd == \"close\" or subcmd == \"error\" then\n\t\t\t-- close cluster agent\n\t\t\tlocal agent = cluster_agent[fd]\n\t\t\tif type(agent) == \"boolean\" then\n\t\t\t\tcluster_agent[fd] = true\n\t\t\telseif agent then\n\t\t\t\tskynet.send(agent, \"lua\", \"exit\")\n\t\t\t\tcluster_agent[fd] = nil\n\t\t\tend\n\t\telse\n\t\t\tskynet.error(string.format(\"socket %s %d %s\", subcmd, fd, msg or \"\"))\n\t\tend\n\tend\nend\n\nskynet.start(function()\n\tloadconfig()\n\tskynet.dispatch(\"lua\", function(session , source, cmd, ...)\n\t\tlocal f = assert(command[cmd])\n\t\tf(source, ...)\n\tend)\nend)\n"
  },
  {
    "path": "service/clusterproxy.lua",
    "content": "local skynet = require \"skynet\"\nlocal cluster = require \"skynet.cluster\"\nrequire \"skynet.manager\"\t-- inject skynet.forward_type\n\nlocal node, address = ...\n\nskynet.register_protocol {\n\tname = \"system\",\n\tid = skynet.PTYPE_SYSTEM,\n\tunpack = function (...) return ... end,\n}\n\nlocal forward_map = {\n\t[skynet.PTYPE_SNAX] = skynet.PTYPE_SYSTEM,\n\t[skynet.PTYPE_LUA] = skynet.PTYPE_SYSTEM,\n\t[skynet.PTYPE_RESPONSE] = skynet.PTYPE_RESPONSE,\t-- don't free response message\n}\n\nskynet.forward_type( forward_map ,function()\n\tlocal clusterd = skynet.uniqueservice(\"clusterd\")\n\tlocal n = tonumber(address)\n\tif n then\n\t\taddress = n\n\tend\n\tlocal sender = skynet.call(clusterd, \"lua\", \"sender\", node)\n\tskynet.dispatch(\"system\", function (session, source, msg, sz)\n\t\tif session == 0 then\n\t\t\tskynet.send(sender, \"lua\", \"push\", address, msg, sz)\n\t\telse\n\t\t\tskynet.ret(skynet.rawcall(sender, \"lua\", skynet.pack(\"req\", address, msg, sz)))\n\t\tend\n\tend)\nend)\n"
  },
  {
    "path": "service/clustersender.lua",
    "content": "local skynet = require \"skynet\"\nlocal sc = require \"skynet.socketchannel\"\nlocal socket = require \"skynet.socket\"\nlocal cluster = require \"skynet.cluster.core\"\n\nlocal channel\nlocal session = 1\nlocal node, nodename, init_host, init_port = ...\n\nlocal command = {}\n\nlocal function send_request(addr, msg, sz)\n\t-- msg is a local pointer, cluster.packrequest will free it\n\tlocal current_session = session\n\tlocal request, new_session, padding = cluster.packrequest(addr, session, msg, sz)\n\tsession = new_session\n\n\tlocal tracetag = skynet.tracetag()\n\tif tracetag then\n\t\tif tracetag:sub(1,1) ~= \"(\" then\n\t\t\t-- add nodename\n\t\t\tlocal newtag = string.format(\"(%s-%s-%d)%s\", nodename, node, session, tracetag)\n\t\t\tskynet.tracelog(tracetag, string.format(\"session %s\", newtag))\n\t\t\ttracetag = newtag\n\t\tend\n\t\tskynet.tracelog(tracetag, string.format(\"cluster %s\", node))\n\t\tchannel:request(cluster.packtrace(tracetag))\n\tend\n\treturn channel:request(request, current_session, padding)\nend\n\nfunction command.req(...)\n\tlocal ok, msg = pcall(send_request, ...)\n\tif ok then\n\t\tif type(msg) == \"table\" then\n\t\t\tskynet.ret(cluster.concat(msg))\n\t\telse\n\t\t\tskynet.ret(msg)\n\t\tend\n\telse\n\t\tskynet.error(msg)\n\t\tskynet.response()(false)\n\tend\nend\n\nfunction command.push(addr, msg, sz)\n\tlocal request, new_session, padding = cluster.packpush(addr, session, msg, sz)\n\tif padding then\t-- is multi push\n\t\tsession = new_session\n\tend\n\n\tchannel:request(request, nil, padding)\nend\n\nlocal function read_response(sock)\n\tlocal sz = socket.header(sock:read(2))\n\tlocal msg = sock:read(sz)\n\treturn cluster.unpackresponse(msg)\t-- session, ok, data, padding\nend\n\nfunction command.changenode(host, port)\n\tif not host then\n\t\tskynet.error(\"Close cluster sender\", channel.__host, channel.__port)\n\t\tchannel:close()\n\telse\n\t\tchannel:changehost(host, port)\n\t\tchannel:connect(true)\n\tend\n\tskynet.ret(skynet.pack(nil))\nend\n\nskynet.start(function()\n\tchannel = sc.channel {\n\t\t\thost = init_host,\n\t\t\tport = tonumber(init_port),\n\t\t\tresponse = read_response,\n\t\t\tnodelay = true,\n\t\t}\n\tskynet.dispatch(\"lua\", function(session , source, cmd, ...)\n\t\tlocal f = assert(command[cmd])\n\t\tf(...)\n\tend)\nend)\n"
  },
  {
    "path": "service/cmaster.lua",
    "content": "local skynet = require \"skynet\"\nlocal socket = require \"skynet.socket\"\n\n--[[\n\tmaster manage data :\n\t\t1. all the slaves address : id -> ipaddr:port\n\t\t2. all the global names : name -> address\n\n\tmaster hold connections from slaves .\n\n\tprotocol slave->master :\n\t\tpackage size 1 byte\n\t\ttype 1 byte :\n\t\t\t'H' : HANDSHAKE, report slave id, and address.\n\t\t\t'R' : REGISTER name address\n\t\t\t'Q' : QUERY name\n\n\n\tprotocol master->slave:\n\t\tpackage size 1 byte\n\t\ttype 1 byte :\n\t\t\t'W' : WAIT n\n\t\t\t'C' : CONNECT slave_id slave_address\n\t\t\t'N' : NAME globalname address\n\t\t\t'D' : DISCONNECT slave_id\n]]\n\nlocal slave_node = {}\nlocal global_name = {}\n\nlocal function read_package(fd)\n\tlocal sz = socket.read(fd, 1)\n\tassert(sz, \"closed\")\n\tsz = string.byte(sz)\n\tlocal content = assert(socket.read(fd, sz), \"closed\")\n\treturn skynet.unpack(content)\nend\n\nlocal function pack_package(...)\n\tlocal message = skynet.packstring(...)\n\tlocal size = #message\n\tassert(size <= 255 , \"too long\")\n\treturn string.char(size) .. message\nend\n\nlocal function report_slave(fd, slave_id, slave_addr)\n\tlocal message = pack_package(\"C\", slave_id, slave_addr)\n\tlocal n = 0\n\tfor k,v in pairs(slave_node) do\n\t\tif v.fd ~= 0 then\n\t\t\tsocket.write(v.fd, message)\n\t\t\tn = n + 1\n\t\tend\n\tend\n\tsocket.write(fd, pack_package(\"W\", n))\nend\n\nlocal function handshake(fd)\n\tlocal t, slave_id, slave_addr = read_package(fd)\n\tassert(t=='H', \"Invalid handshake type \" .. t)\n\tassert(slave_id ~= 0 , \"Invalid slave id 0\")\n\tif slave_node[slave_id] then\n\t\terror(string.format(\"Slave %d already register on %s\", slave_id, slave_node[slave_id].addr))\n\tend\n\treport_slave(fd, slave_id, slave_addr)\n\tslave_node[slave_id] = {\n\t\tfd = fd,\n\t\tid = slave_id,\n\t\taddr = slave_addr,\n\t}\n\treturn slave_id , slave_addr\nend\n\nlocal function dispatch_slave(fd)\n\tlocal t, name, address = read_package(fd)\n\tif t == 'R' then\n\t\t-- register name\n\t\tassert(type(address)==\"number\", \"Invalid request\")\n\t\tif not global_name[name] then\n\t\t\tglobal_name[name] = address\n\t\tend\n\t\tlocal message = pack_package(\"N\", name, address)\n\t\tfor k,v in pairs(slave_node) do\n\t\t\tsocket.write(v.fd, message)\n\t\tend\n\telseif t == 'Q' then\n\t\t-- query name\n\t\tlocal address = global_name[name]\n\t\tif address then\n\t\t\tsocket.write(fd, pack_package(\"N\", name, address))\n\t\tend\n\telse\n\t\tskynet.error(\"Invalid slave message type \" .. t)\n\tend\nend\n\nlocal function monitor_slave(slave_id, slave_address)\n\tlocal fd = slave_node[slave_id].fd\n\tskynet.error(string.format(\"Harbor %d (fd=%d) report %s\", slave_id, fd, slave_address))\n\twhile pcall(dispatch_slave, fd) do end\n\tskynet.error(\"slave \" ..slave_id .. \" is down\")\n\tlocal message = pack_package(\"D\", slave_id)\n\tslave_node[slave_id].fd = 0\n\tfor k,v in pairs(slave_node) do\n\t\tsocket.write(v.fd, message)\n\tend\n\tsocket.close(fd)\nend\n\nskynet.start(function()\n\tlocal master_addr = skynet.getenv \"standalone\"\n\tskynet.error(\"master listen socket \" .. tostring(master_addr))\n\tlocal fd = socket.listen(master_addr)\n\tsocket.start(fd , function(id, addr)\n\t\tskynet.error(\"connect from \" .. addr .. \" \" .. id)\n\t\tsocket.start(id)\n\t\tlocal ok, slave, slave_addr = pcall(handshake, id)\n\t\tif ok then\n\t\t\tskynet.fork(monitor_slave, slave, slave_addr)\n\t\telse\n\t\t\tskynet.error(string.format(\"disconnect fd = %d, error = %s\", id, slave))\n\t\t\tsocket.close(id)\n\t\tend\n\tend)\nend)\n"
  },
  {
    "path": "service/cmemory.lua",
    "content": "local skynet = require \"skynet\"\nlocal memory = require \"skynet.memory\"\n\nmemory.dumpinfo()\n--memory.dump()\nlocal info = memory.info()\nfor k,v in pairs(info) do\n\tprint(string.format(\":%08x %gK\",k,v/1024))\nend\n\nprint(\"Total memory:\", memory.total())\nprint(\"Total block:\", memory.block())\n\nskynet.start(function() skynet.exit() end)\n"
  },
  {
    "path": "service/console.lua",
    "content": "local skynet = require \"skynet\"\nlocal snax   = require \"skynet.snax\"\nlocal socket = require \"skynet.socket\"\n\nlocal function split_cmdline(cmdline)\n\tlocal split = {}\n\tfor i in string.gmatch(cmdline, \"%S+\") do\n\t\ttable.insert(split,i)\n\tend\n\treturn split\nend\n\nlocal function console_main_loop()\n\tlocal stdin = socket.stdin()\n\twhile true do\n\t\tlocal cmdline = socket.readline(stdin, \"\\n\")\n\t\tlocal split = split_cmdline(cmdline)\n\t\tlocal command = split[1]\n\t\tif command == \"snax\" then\n\t\t\tpcall(snax.newservice, select(2, table.unpack(split)))\n\t\telseif cmdline ~= \"\" then\n\t\t\tpcall(skynet.newservice, cmdline)\n\t\tend\n\tend\nend\n\nskynet.start(function()\n\tskynet.fork(console_main_loop)\nend)\n"
  },
  {
    "path": "service/cslave.lua",
    "content": "local skynet = require \"skynet\"\nlocal socket = require \"skynet.socket\"\nlocal socketdriver = require \"skynet.socketdriver\"\nrequire \"skynet.manager\"\t-- import skynet.launch, ...\nlocal table = table\n\nlocal slaves = {}\nlocal connect_queue = {}\nlocal globalname = {}\nlocal queryname = {}\nlocal harbor = {}\nlocal harbor_service\nlocal monitor = {}\nlocal monitor_master_set = {}\n\nlocal function read_package(fd)\n\tlocal sz = socket.read(fd, 1)\n\tassert(sz, \"closed\")\n\tsz = string.byte(sz)\n\tlocal content = assert(socket.read(fd, sz), \"closed\")\n\treturn skynet.unpack(content)\nend\n\nlocal function pack_package(...)\n\tlocal message = skynet.packstring(...)\n\tlocal size = #message\n\tassert(size <= 255 , \"too long\")\n\treturn string.char(size) .. message\nend\n\nlocal function monitor_clear(id)\n\tlocal v = monitor[id]\n\tif v then\n\t\tmonitor[id] = nil\n\t\tfor _, v in ipairs(v) do\n\t\t\tv(true)\n\t\tend\n\tend\nend\n\nlocal function connect_slave(slave_id, address)\n\tlocal ok, err = pcall(function()\n\t\tif slaves[slave_id] == nil then\n\t\t\tlocal fd = assert(socket.open(address), \"Can't connect to \"..address)\n\t\t\tsocketdriver.nodelay(fd)\n\t\t\tskynet.error(string.format(\"Connect to harbor %d (fd=%d), %s\", slave_id, fd, address))\n\t\t\tslaves[slave_id] = fd\n\t\t\tmonitor_clear(slave_id)\n\t\t\tsocket.abandon(fd)\n\t\t\tskynet.send(harbor_service, \"harbor\", string.format(\"S %d %d\",fd,slave_id))\n\t\tend\n\tend)\n\tif not ok then\n\t\tskynet.error(err)\n\tend\nend\n\nlocal function ready()\n\tlocal queue = connect_queue\n\tconnect_queue = nil\n\tfor k,v in pairs(queue) do\n\t\tconnect_slave(k,v)\n\tend\n\tfor name,address in pairs(globalname) do\n\t\tskynet.redirect(harbor_service, address, \"harbor\", 0, \"N \" .. name)\n\tend\nend\n\nlocal function response_name(name)\n\tlocal address = globalname[name]\n\tif queryname[name] then\n\t\tlocal tmp = queryname[name]\n\t\tqueryname[name] = nil\n\t\tfor _,resp in ipairs(tmp) do\n\t\t\tresp(true, address)\n\t\tend\n\tend\nend\n\nlocal function monitor_master(master_fd)\n\twhile true do\n\t\tlocal ok, t, id_name, address = pcall(read_package,master_fd)\n\t\tif ok then\n\t\t\tif t == 'C' then\n\t\t\t\tif connect_queue then\n\t\t\t\t\tconnect_queue[id_name] = address\n\t\t\t\telse\n\t\t\t\t\tconnect_slave(id_name, address)\n\t\t\t\tend\n\t\t\telseif t == 'N' then\n\t\t\t\tglobalname[id_name] = address\n\t\t\t\tresponse_name(id_name)\n\t\t\t\tif connect_queue == nil then\n\t\t\t\t\tskynet.redirect(harbor_service, address, \"harbor\", 0, \"N \" .. id_name)\n\t\t\t\tend\n\t\t\telseif t == 'D' then\n\t\t\t\tlocal fd = slaves[id_name]\n\t\t\t\tslaves[id_name] = false\n\t\t\t\tif fd then\n\t\t\t\t\tmonitor_clear(id_name)\n\t\t\t\t\tsocket.close(fd)\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tskynet.error(\"Master disconnect\")\n\t\t\tfor _, v in ipairs(monitor_master_set) do\n\t\t\t\tv(true)\n\t\t\tend\n\t\t\tsocket.close(master_fd)\n\t\t\tbreak\n\t\tend\n\tend\nend\n\nlocal function accept_slave(fd)\n\tsocket.start(fd)\n\tlocal id = socket.read(fd, 1)\n\tif not id then\n\t\tskynet.error(string.format(\"Connection (fd =%d) closed\", fd))\n\t\tsocket.close(fd)\n\t\treturn\n\tend\n\tid = string.byte(id)\n\tif slaves[id] ~= nil then\n\t\tskynet.error(string.format(\"Slave %d exist (fd =%d)\", id, fd))\n\t\tsocket.close(fd)\n\t\treturn\n\tend\n\tslaves[id] = fd\n\tmonitor_clear(id)\n\tsocket.abandon(fd)\n\tskynet.error(string.format(\"Harbor %d connected (fd = %d)\", id, fd))\n\tskynet.send(harbor_service, \"harbor\", string.format(\"A %d %d\", fd, id))\nend\n\nskynet.register_protocol {\n\tname = \"harbor\",\n\tid = skynet.PTYPE_HARBOR,\n\tpack = function(...) return ... end,\n\tunpack = skynet.tostring,\n}\n\nskynet.register_protocol {\n\tname = \"text\",\n\tid = skynet.PTYPE_TEXT,\n\tpack = function(...) return ... end,\n\tunpack = skynet.tostring,\n}\n\nlocal function monitor_harbor(master_fd)\n\treturn function(session, source, command)\n\t\tlocal t = string.sub(command, 1, 1)\n\t\tlocal arg = string.sub(command, 3)\n\t\tif t == 'Q' then\n\t\t\t-- query name\n\t\t\tif globalname[arg] then\n\t\t\t\tskynet.redirect(harbor_service, globalname[arg], \"harbor\", 0, \"N \" .. arg)\n\t\t\telse\n\t\t\t\tsocket.write(master_fd, pack_package(\"Q\", arg))\n\t\t\tend\n\t\telseif t == 'D' then\n\t\t\t-- harbor down\n\t\t\tlocal id = tonumber(arg)\n\t\t\tif slaves[id] then\n\t\t\t\tmonitor_clear(id)\n\t\t\tend\n\t\t\tslaves[id] = false\n\t\telse\n\t\t\tskynet.error(\"Unknown command \", command)\n\t\tend\n\tend\nend\n\nfunction harbor.REGISTER(fd, name, handle)\n\tassert(globalname[name] == nil)\n\tglobalname[name] = handle\n\tresponse_name(name)\n\tsocket.write(fd, pack_package(\"R\", name, handle))\n\tskynet.redirect(harbor_service, handle, \"harbor\", 0, \"N \" .. name)\nend\n\nfunction harbor.LINK(fd, id)\n\tif slaves[id] then\n\t\tif monitor[id] == nil then\n\t\t\tmonitor[id] = {}\n\t\tend\n\t\ttable.insert(monitor[id], skynet.response())\n\telse\n\t\tskynet.ret()\n\tend\nend\n\nfunction harbor.LINKMASTER()\n\ttable.insert(monitor_master_set, skynet.response())\nend\n\nfunction harbor.CONNECT(fd, id)\n\tif not slaves[id] then\n\t\tif monitor[id] == nil then\n\t\t\tmonitor[id] = {}\n\t\tend\n\t\ttable.insert(monitor[id], skynet.response())\n\telse\n\t\tskynet.ret()\n\tend\nend\n\nfunction harbor.QUERYNAME(fd, name)\n\tif name:byte() == 46 then\t-- \".\" , local name\n\t\tskynet.ret(skynet.pack(skynet.localname(name)))\n\t\treturn\n\tend\n\tlocal result = globalname[name]\n\tif result then\n\t\tskynet.ret(skynet.pack(result))\n\t\treturn\n\tend\n\tlocal queue = queryname[name]\n\tif queue == nil then\n\t\tsocket.write(fd, pack_package(\"Q\", name))\n\t\tqueue = { skynet.response() }\n\t\tqueryname[name] = queue\n\telse\n\t\ttable.insert(queue, skynet.response())\n\tend\nend\n\nskynet.start(function()\n\tlocal master_addr = skynet.getenv \"master\"\n\tlocal harbor_id = tonumber(skynet.getenv \"harbor\")\n\tlocal slave_address = assert(skynet.getenv \"address\")\n\tlocal slave_fd = socket.listen(slave_address)\n\tskynet.error(\"slave connect to master \" .. tostring(master_addr))\n\tlocal master_fd = assert(socket.open(master_addr), \"Can't connect to master\")\n\n\tskynet.dispatch(\"lua\", function (_,_,command,...)\n\t\tlocal f = assert(harbor[command])\n\t\tf(master_fd, ...)\n\tend)\n\tskynet.dispatch(\"text\", monitor_harbor(master_fd))\n\n\tharbor_service = assert(skynet.launch(\"harbor\", harbor_id, skynet.self()))\n\n\tlocal hs_message = pack_package(\"H\", harbor_id, slave_address)\n\tsocket.write(master_fd, hs_message)\n\tlocal t, n = read_package(master_fd)\n\tassert(t == \"W\" and type(n) == \"number\", \"slave shakehand failed\")\n\tskynet.error(string.format(\"Waiting for %d harbors\", n))\n\tskynet.fork(monitor_master, master_fd)\n\tif n > 0 then\n\t\tlocal co = coroutine.running()\n\t\tsocket.start(slave_fd, function(fd, addr)\n\t\t\tskynet.error(string.format(\"New connection (fd = %d, %s)\",fd, addr))\n\t\t\tsocketdriver.nodelay(fd)\n\t\t\tif pcall(accept_slave,fd) then\n\t\t\t\tlocal s = 0\n\t\t\t\tfor k,v in pairs(slaves) do\n\t\t\t\t\ts = s + 1\n\t\t\t\tend\n\t\t\t\tif s >= n then\n\t\t\t\t\tskynet.wakeup(co)\n\t\t\t\tend\n\t\t\tend\n\t\tend)\n\t\tskynet.wait()\n\tend\n\tsocket.close(slave_fd)\n\tskynet.error(\"Shakehand ready\")\n\tskynet.fork(ready)\nend)\n"
  },
  {
    "path": "service/datacenterd.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal command = {}\nlocal database = {}\nlocal wait_queue = {}\nlocal mode = {}\n\nlocal function query(db, key, ...)\n\tif db == nil or key == nil then\n\t\treturn db\n\telse\n\t\treturn query(db[key], ...)\n\tend\nend\n\nfunction command.QUERY(key, ...)\n\tlocal d = database[key]\n\tif d ~= nil then\n\t\treturn query(d, ...)\n\tend\nend\n\nlocal function update(db, key, value, ...)\n\tif select(\"#\",...) == 0 then\n\t\tlocal ret = db[key]\n\t\tdb[key] = value\n\t\treturn ret, value\n\telse\n\t\tif db[key] == nil then\n\t\t\tdb[key] = {}\n\t\tend\n\t\treturn update(db[key], value, ...)\n\tend\nend\n\nlocal function wakeup(db, key1, ...)\n\tif key1 == nil then\n\t\treturn\n\tend\n\tlocal q = db[key1]\n\tif q == nil then\n\t\treturn\n\tend\n\tif q[mode] == \"queue\" then\n\t\tdb[key1] = nil\n\t\tif select(\"#\", ...) ~= 1 then\n\t\t\t-- throw error because can't wake up a branch\n\t\t\tfor _,response in ipairs(q) do\n\t\t\t\tresponse(false)\n\t\t\tend\n\t\telse\n\t\t\treturn q\n\t\tend\n\telse\n\t\t-- it's branch\n\t\treturn wakeup(q , ...)\n\tend\nend\n\nfunction command.UPDATE(...)\n\tlocal ret, value = update(database, ...)\n\tif ret ~= nil or value == nil then\n\t\treturn ret\n\tend\n\tlocal q = wakeup(wait_queue, ...)\n\tif q then\n\t\tfor _, response in ipairs(q) do\n\t\t\tresponse(true,value)\n\t\tend\n\tend\nend\n\nlocal function waitfor(db, key1, key2, ...)\n\tif key2 == nil then\n\t\t-- push queue\n\t\tlocal q = db[key1]\n\t\tif q == nil then\n\t\t\tq = { [mode] = \"queue\" }\n\t\t\tdb[key1] = q\n\t\telse\n\t\t\tassert(q[mode] == \"queue\")\n\t\tend\n\t\ttable.insert(q, skynet.response())\n\telse\n\t\tlocal q = db[key1]\n\t\tif q == nil then\n\t\t\tq = { [mode] = \"branch\" }\n\t\t\tdb[key1] = q\n\t\telse\n\t\t\tassert(q[mode] == \"branch\")\n\t\tend\n\t\treturn waitfor(q, key2, ...)\n\tend\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function (_, _, cmd, ...)\n\t\tif cmd == \"WAIT\" then\n\t\t\tlocal ret = command.QUERY(...)\n\t\t\tif ret ~= nil then\n\t\t\t\tskynet.ret(skynet.pack(ret))\n\t\t\telse\n\t\t\t\twaitfor(wait_queue, ...)\n\t\t\tend\n\t\telse\n\t\t\tlocal f = assert(command[cmd])\n\t\t\tskynet.ret(skynet.pack(f(...)))\n\t\tend\n\tend)\nend)\n"
  },
  {
    "path": "service/dbg.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal cmd = { ... }\n\nlocal function format_table(t)\n\tlocal index = {}\n\tfor k in pairs(t) do\n\t\ttable.insert(index, k)\n\tend\n\ttable.sort(index)\n\tlocal result = {}\n\tfor _,v in ipairs(index) do\n\t\ttable.insert(result, string.format(\"%s:%s\",v,tostring(t[v])))\n\tend\n\treturn table.concat(result,\"\\t\")\nend\n\nlocal function dump_line(key, value)\n\tif type(value) == \"table\" then\n\t\tprint(key, format_table(value))\n\telse\n\t\tprint(key,tostring(value))\n\tend\nend\n\nlocal function dump_list(list)\n\tlocal index = {}\n\tfor k in pairs(list) do\n\t\ttable.insert(index, k)\n\tend\n\ttable.sort(index)\n\tfor _,v in ipairs(index) do\n\t\tdump_line(v, list[v])\n\tend\nend\n\nskynet.start(function()\n\tlocal list = skynet.call(\".launcher\",\"lua\", table.unpack(cmd))\n\tif list then\n\t\tdump_list(list)\n\tend\n\tskynet.exit()\nend)"
  },
  {
    "path": "service/debug_agent.lua",
    "content": "local skynet = require \"skynet\"\nlocal debugchannel = require \"skynet.debugchannel\"\n\nlocal CMD = {}\n\nlocal channel\n\nfunction CMD.start(address, fd)\n\tassert(channel == nil, \"start more than once\")\n\tskynet.error(string.format(\"Attach to :%08x\", address))\n\tlocal handle\n\tchannel, handle = debugchannel.create()\n\tlocal ok, err = pcall(skynet.call, address, \"debug\", \"REMOTEDEBUG\", fd, handle)\n\tif not ok then\n\t\tskynet.ret(skynet.pack(false, \"Debugger attach failed\"))\n\telse\n\t\t-- todo hook\n\t\tskynet.ret(skynet.pack(true))\n\tend\n\tskynet.exit()\nend\n\nfunction CMD.cmd(cmdline)\n\tchannel:write(cmdline)\nend\n\nfunction CMD.ping()\n\tskynet.ret()\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(_,_,cmd,...)\n\t\tlocal f = CMD[cmd]\n\t\tf(...)\n\tend)\nend)\n"
  },
  {
    "path": "service/debug_console.lua",
    "content": "local skynet = require \"skynet\"\nlocal codecache = require \"skynet.codecache\"\nlocal core = require \"skynet.core\"\nlocal socket = require \"skynet.socket\"\nlocal snax = require \"skynet.snax\"\nlocal memory = require \"skynet.memory\"\nlocal httpd = require \"http.httpd\"\nlocal sockethelper = require \"http.sockethelper\"\n\nlocal arg = table.pack(...)\nassert(arg.n <= 2)\nlocal ip = (arg.n == 2 and arg[1] or \"127.0.0.1\")\nlocal port = tonumber(arg[arg.n])\nlocal TIMEOUT = 300 -- 3 sec\n\nlocal COMMAND = {}\nlocal COMMANDX = {}\n\nlocal function format_table(t)\n\tlocal index = {}\n\tfor k in pairs(t) do\n\t\ttable.insert(index, k)\n\tend\n\ttable.sort(index, function(a, b) return tostring(a) < tostring(b) end)\n\tlocal result = {}\n\tfor _,v in ipairs(index) do\n\t\ttable.insert(result, string.format(\"%s:%s\",v,tostring(t[v])))\n\tend\n\treturn table.concat(result,\"\\t\")\nend\n\nlocal function dump_line(print, key, value)\n\tif type(value) == \"table\" then\n\t\tprint(key, format_table(value))\n\telse\n\t\tprint(key,tostring(value))\n\tend\nend\n\nlocal function dump_list(print, list)\n\tlocal index = {}\n\tfor k in pairs(list) do\n\t\ttable.insert(index, k)\n\tend\n\ttable.sort(index, function(a, b) return tostring(a) < tostring(b) end)\n\tfor _,v in ipairs(index) do\n\t\tdump_line(print, v, list[v])\n\tend\nend\n\nlocal function split_cmdline(cmdline)\n\tlocal split = {}\n\tfor i in string.gmatch(cmdline, \"%S+\") do\n\t\ttable.insert(split,i)\n\tend\n\treturn split\nend\n\nlocal function docmd(cmdline, print, fd)\n\tlocal split = split_cmdline(cmdline)\n\tlocal command = split[1]\n\tlocal cmd = COMMAND[command]\n\tlocal ok, list\n\tif cmd then\n\t\tok, list = pcall(cmd, table.unpack(split,2))\n\telse\n\t\tcmd = COMMANDX[command]\n\t\tif cmd then\n\t\t\tsplit.fd = fd\n\t\t\tsplit[1] = cmdline\n\t\t\tok, list = pcall(cmd, split)\n\t\telse\n\t\t\tprint(\"Invalid command, type help for command list\")\n\t\tend\n\tend\n\n\tif ok then\n\t\tif list then\n\t\t\tif type(list) == \"string\" then\n\t\t\t\tprint(list)\n\t\t\telse\n\t\t\t\tdump_list(print, list)\n\t\t\tend\n\t\tend\n\t\tprint(\"<CMD OK>\")\n\telse\n\t\tprint(list)\n\t\tprint(\"<CMD Error>\")\n\tend\nend\n\nlocal function console_main_loop(stdin, print, addr)\n\tprint(\"Welcome to skynet console\")\n\tskynet.error(addr, \"connected\")\n\tlocal ok, err = pcall(function()\n\t\twhile true do\n\t\t\tlocal cmdline = socket.readline(stdin, \"\\n\")\n\t\t\tif not cmdline then\n\t\t\t\tbreak\n\t\t\tend\n\t\t\tif cmdline:sub(1,4) == \"GET \" then\n\t\t\t\t-- http\n\t\t\t\tlocal code, url = httpd.read_request(sockethelper.readfunc(stdin, cmdline.. \"\\n\"), 8192)\n\t\t\t\tlocal cmdline = url:sub(2):gsub(\"/\",\" \")\n\t\t\t\tdocmd(cmdline, print, stdin)\n\t\t\t\tbreak\n\t\t\telseif cmdline:sub(1,5) == \"POST \" then\n\t\t\t\t-- http post\n\t\t\t\tlocal code, url, method, header, body = httpd.read_request(sockethelper.readfunc(stdin, cmdline.. \"\\n\"), 8192)\n\t\t\t\tdocmd(body, print, stdin)\n\t\t\t\tbreak\n\t\t\tend\n\t\t\t\n\t\t\tif cmdline ~= \"\" then\n\t\t\t\tdocmd(cmdline, print, stdin)\n\t\t\tend\n\t\tend\n\tend)\n\tif not ok then\n\t\tskynet.error(stdin, err)\n\tend\n\tskynet.error(addr, \"disconnect\")\n\tsocket.close(stdin)\nend\n\nskynet.start(function()\n\tlocal listen_socket, ip, port = socket.listen (ip, port)\n\tskynet.error(\"Start debug console at \" .. ip .. \":\" .. port)\n\tsocket.start(listen_socket , function(id, addr)\n\t\tlocal function print(...)\n\t\t\tlocal t = { ... }\n\t\t\tfor k,v in ipairs(t) do\n\t\t\t\tt[k] = tostring(v)\n\t\t\tend\n\t\t\tsocket.write(id, table.concat(t,\"\\t\"))\n\t\t\tsocket.write(id, \"\\n\")\n\t\tend\n\t\tsocket.start(id)\n\t\tskynet.fork(console_main_loop, id , print, addr)\n\tend)\nend)\n\nfunction COMMAND.help()\n\treturn {\n\t\thelp = \"This help message\",\n\t\tlist = \"List all the service\",\n\t\tstat = \"Dump all stats\",\n\t\tinfo = \"info address : get service infomation\",\n\t\texit = \"exit address : kill a lua service\",\n\t\tkill = \"kill address : kill service\",\n\t\tmem = \"mem : show memory status\",\n\t\tgc = \"gc : force every lua service do garbage collect\",\n\t\tstart = \"lanuch a new lua service\",\n\t\tsnax = \"lanuch a new snax service\",\n\t\tclearcache = \"clear lua code cache\",\n\t\tservice = \"List unique service\",\n\t\ttask = \"task address : show service task detail\",\n\t\tuniqtask = \"task address : show service unique task detail\",\n\t\tinject = \"inject address luascript.lua\",\n\t\tlogon = \"logon address\",\n\t\tlogoff = \"logoff address\",\n\t\tlog = \"launch a new lua service with log\",\n\t\tdebug = \"debug address : debug a lua service\",\n\t\tsignal = \"signal address sig\",\n\t\tcmem = \"Show C memory info\",\n\t\tjmem = \"Show jemalloc mem stats\",\n\t\tping = \"ping address\",\n\t\tcall = \"call address ...\",\n\t\ttrace = \"trace address [proto] [on|off]\",\n\t\tnetstat = \"netstat : show netstat\",\n\t\tprofactive = \"profactive [on|off] : active/deactive jemalloc heap profilling\",\n\t\tdumpheap = \"dumpheap : dump heap profilling\",\n\t\tkilltask = \"killtask address threadname : threadname listed by task\",\n\t\tdbgcmd = \"run address debug command\",\n\t\tgetenv = \"getenv name : skynet.getenv(name)\",\n\t\tsetenv = \"setenv name value: skynet.setenv(name,value)\",\n\t}\nend\n\nfunction COMMAND.clearcache()\n\tcodecache.clear()\nend\n\nfunction COMMAND.start(...)\n\tlocal ok, addr = pcall(skynet.newservice, ...)\n\tif ok then\n\t\tif addr then\n\t\t\treturn { [skynet.address(addr)] = ... }\n\t\telse\n\t\t\treturn \"Exit\"\n\t\tend\n\telse\n\t\treturn \"Failed\"\n\tend\nend\n\nfunction COMMAND.log(...)\n\tlocal ok, addr = pcall(skynet.call, \".launcher\", \"lua\", \"LOGLAUNCH\", \"snlua\", ...)\n\tif ok then\n\t\tif addr then\n\t\t\treturn { [skynet.address(addr)] = ... }\n\t\telse\n\t\t\treturn \"Failed\"\n\t\tend\n\telse\n\t\treturn \"Failed\"\n\tend\nend\n\nfunction COMMAND.snax(...)\n\tlocal ok, s = pcall(snax.newservice, ...)\n\tif ok then\n\t\tlocal addr = s.handle\n\t\treturn { [skynet.address(addr)] = ... }\n\telse\n\t\treturn \"Failed\"\n\tend\nend\n\nfunction COMMAND.service()\n\treturn skynet.call(\"SERVICE\", \"lua\", \"LIST\")\nend\n\nlocal function adjust_address(address)\n\tlocal prefix = address:sub(1,1)\n\tif prefix == '.' then\n\t\treturn assert(skynet.localname(address), \"Not a valid name\")\n\telseif prefix ~= ':' then\n\t\taddress = assert(tonumber(\"0x\" .. address), \"Need an address\") | (skynet.harbor(skynet.self()) << 24)\n\tend\n\treturn address\nend\n\nfunction COMMAND.list()\n\treturn skynet.call(\".launcher\", \"lua\", \"LIST\")\nend\n\nlocal function timeout(ti)\n\tif ti then\n\t\tti = tonumber(ti)\n\t\tif ti <= 0 then\n\t\t\tti = nil\n\t\tend\n\telse\n\t\tti = TIMEOUT\n\tend\n\treturn ti\nend\n\nfunction COMMAND.stat(ti)\n\treturn skynet.call(\".launcher\", \"lua\", \"STAT\", timeout(ti))\nend\n\nfunction COMMAND.mem(ti)\n\treturn skynet.call(\".launcher\", \"lua\", \"MEM\", timeout(ti))\nend\n\nfunction COMMAND.kill(address)\n\treturn skynet.call(\".launcher\", \"lua\", \"KILL\", adjust_address(address))\nend\n\nfunction COMMAND.gc(ti)\n\treturn skynet.call(\".launcher\", \"lua\", \"GC\", timeout(ti))\nend\n\nfunction COMMAND.exit(address)\n\tskynet.send(adjust_address(address), \"debug\", \"EXIT\")\nend\n\nfunction COMMAND.inject(address, filename, ...)\n\taddress = adjust_address(address)\n\tlocal f = io.open(filename, \"rb\")\n\tif not f then\n\t\treturn \"Can't open \" .. filename\n\tend\n\tlocal source = f:read \"*a\"\n\tf:close()\n\tlocal ok, output = skynet.call(address, \"debug\", \"RUN\", source, filename, ...)\n\tif ok == false then\n\t\terror(output)\n\tend\n\treturn output\nend\n\nfunction COMMAND.dbgcmd(address, cmd, ...)\n\taddress = adjust_address(address)\n\treturn skynet.call(address, \"debug\", cmd, ...)\nend\n\nfunction COMMAND.task(address)\n\treturn COMMAND.dbgcmd(address, \"TASK\")\nend\n\nfunction COMMAND.killtask(address, threadname)\n\treturn COMMAND.dbgcmd(address, \"KILLTASK\", threadname)\nend\n\nfunction COMMAND.uniqtask(address)\n\treturn COMMAND.dbgcmd(address, \"UNIQTASK\")\nend\n\nfunction COMMAND.info(address, ...)\n\treturn COMMAND.dbgcmd(address, \"INFO\", ...)\nend\n\nfunction COMMANDX.debug(cmd)\n\tlocal address = adjust_address(cmd[2])\n\tlocal agent = skynet.newservice \"debug_agent\"\n\tlocal stop\n\tlocal term_co = coroutine.running()\n\tlocal function forward_cmd()\n\t\trepeat\n\t\t\t-- notice :  It's a bad practice to call socket.readline from two threads (this one and console_main_loop), be careful.\n\t\t\tskynet.call(agent, \"lua\", \"ping\")\t-- detect agent alive, if agent exit, raise error\n\t\t\tlocal cmdline = socket.readline(cmd.fd, \"\\n\")\n\t\t\tcmdline = cmdline and cmdline:gsub(\"(.*)\\r$\", \"%1\")\n\t\t\tif not cmdline then\n\t\t\t\tskynet.send(agent, \"lua\", \"cmd\", \"cont\")\n\t\t\t\tbreak\n\t\t\tend\n\t\t\tskynet.send(agent, \"lua\", \"cmd\", cmdline)\n\t\tuntil stop or cmdline == \"cont\"\n\tend\n\tskynet.fork(function()\n\t\tpcall(forward_cmd)\n\t\tif not stop then\t-- block at skynet.call \"start\"\n\t\t\tterm_co = nil\n\t\telse\n\t\t\tskynet.wakeup(term_co)\n\t\tend\n\tend)\n\tlocal ok, err = skynet.call(agent, \"lua\", \"start\", address, cmd.fd)\n\tstop = true\n\tif term_co then\n\t\t-- wait for fork coroutine exit.\n\t\tskynet.wait(term_co)\n\tend\n\n\tif not ok then\n\t\terror(err)\n\tend\nend\n\nfunction COMMAND.logon(address)\n\taddress = adjust_address(address)\n\tcore.command(\"LOGON\", skynet.address(address))\nend\n\nfunction COMMAND.logoff(address)\n\taddress = adjust_address(address)\n\tcore.command(\"LOGOFF\", skynet.address(address))\nend\n\nfunction COMMAND.signal(address, sig)\n\taddress = skynet.address(adjust_address(address))\n\tif sig then\n\t\tcore.command(\"SIGNAL\", string.format(\"%s %d\",address,sig))\n\telse\n\t\tcore.command(\"SIGNAL\", address)\n\tend\nend\n\nfunction COMMAND.cmem()\n\tlocal info = memory.info()\n\tlocal tmp = {}\n\tfor k,v in pairs(info) do\n\t\ttmp[skynet.address(k)] = v\n\tend\n\ttmp.total = memory.total()\n\ttmp.block = memory.block()\n\n\treturn tmp\nend\n\nfunction COMMAND.jmem()\n\tlocal info = memory.jestat()\n\tlocal tmp = {}\n\tfor k,v in pairs(info) do\n\t\ttmp[k] = string.format(\"%11d  %8.2f Mb\", v, v/1048576)\n\tend\n\treturn tmp\nend\n\nfunction COMMAND.ping(address)\n\taddress = adjust_address(address)\n\tlocal ti = skynet.now()\n\tskynet.call(address, \"debug\", \"PING\")\n\tti = skynet.now() - ti\n\treturn tostring(ti)\nend\n\nlocal function toboolean(x)\n\treturn x and (x == \"true\" or x == \"on\")\nend\n\nfunction COMMAND.trace(address, proto, flag)\n\taddress = adjust_address(address)\n\tif flag == nil then\n\t\tif proto == \"on\" or proto == \"off\" then\n\t\t\tproto = toboolean(proto)\n\t\tend\n\telse\n\t\tflag = toboolean(flag)\n\tend\n\tskynet.call(address, \"debug\", \"TRACELOG\", proto, flag)\nend\n\nfunction COMMANDX.call(cmd)\n\tlocal address = adjust_address(cmd[2])\n\tlocal cmdline = assert(cmd[1]:match(\"%S+%s+%S+%s(.+)\") , \"need arguments\")\n\tlocal args_func = assert(load(\"return \" .. cmdline, \"debug console\", \"t\", {}), \"Invalid arguments\")\n\tlocal args = table.pack(pcall(args_func))\n\tif not args[1] then\n\t\terror(args[2])\n\tend\n\tlocal rets = table.pack(skynet.call(address, \"lua\", table.unpack(args, 2, args.n)))\n\treturn rets\nend\n\nlocal function bytes(size)\n\tif size == nil or size == 0 then\n\t\treturn\n\tend\n\tif size < 1024 then\n\t\treturn size\n\tend\n\tif size < 1024 * 1024 then\n\t\treturn tostring(size/1024) .. \"K\"\n\tend\n\treturn tostring(size/(1024*1024)) .. \"M\"\nend\n\nlocal function convert_stat(info)\n\tlocal now = skynet.now()\n\tlocal function time(t)\n\t\tif t == nil then\n\t\t\treturn\n\t\tend\n\t\tt = now - t\n\t\tif t < 6000 then\n\t\t\treturn tostring(t/100) .. \"s\"\n\t\tend\n\t\tlocal hour = t // (100*60*60)\n\t\tt = t - hour * 100 * 60 * 60\n\t\tlocal min = t // (100*60)\n\t\tt = t - min * 100 * 60\n\t\tlocal sec = t / 100\n\t\treturn string.format(\"%s%d:%.2gs\",hour == 0 and \"\" or (hour .. \":\"),min,sec)\n\tend\n\n\tinfo.address = skynet.address(info.address)\n\tinfo.read = bytes(info.read)\n\tinfo.write = bytes(info.write)\n\tinfo.wbuffer = bytes(info.wbuffer)\n\tinfo.rtime = time(info.rtime)\n\tinfo.wtime = time(info.wtime)\nend\n\nfunction COMMAND.netstat()\n\tlocal stat = socket.netstat()\n\tfor _, info in ipairs(stat) do\n\t\tconvert_stat(info)\n\tend\n\treturn stat\nend\n\nfunction COMMAND.dumpheap()\n\tmemory.dumpheap()\nend\n\nfunction COMMAND.profactive(flag)\n\tif flag ~= nil then\n\t\tif flag == \"on\" or flag == \"off\" then\n\t\t\tflag = toboolean(flag)\n\t\tend\n\t\tmemory.profactive(flag)\n\tend\n\tlocal active = memory.profactive()\n\treturn \"heap profilling is \".. (active and \"active\" or \"deactive\")\nend\n\nfunction COMMAND.getenv(name)\n\tlocal value = skynet.getenv(name)\n\treturn {[name]=tostring(value)}\nend\n\nfunction COMMAND.setenv(name,value)\n\treturn skynet.setenv(name,value)\nend\n"
  },
  {
    "path": "service/gate.lua",
    "content": "local skynet = require \"skynet\"\nlocal gateserver = require \"snax.gateserver\"\n\nlocal watchdog\nlocal connection = {}\t-- fd -> connection : { fd , client, agent , ip, mode }\n\nskynet.register_protocol {\n\tname = \"client\",\n\tid = skynet.PTYPE_CLIENT,\n}\n\nlocal handler = {}\n\nfunction handler.open(source, conf)\n\twatchdog = conf.watchdog or source\n\treturn conf.address, conf.port\nend\n\nfunction handler.message(fd, msg, sz)\n\t-- recv a package, forward it\n\tlocal c = connection[fd]\n\tlocal agent = c.agent\n\tif agent then\n\t\t-- It's safe to redirect msg directly , gateserver framework will not free msg.\n\t\tskynet.redirect(agent, c.client, \"client\", fd, msg, sz)\n\telse\n\t\tskynet.send(watchdog, \"lua\", \"socket\", \"data\", fd, skynet.tostring(msg, sz))\n\t\t-- skynet.tostring will copy msg to a string, so we must free msg here.\n\t\tskynet.trash(msg,sz)\n\tend\nend\n\nfunction handler.connect(fd, addr)\n\tlocal c = {\n\t\tfd = fd,\n\t\tip = addr,\n\t}\n\tconnection[fd] = c\n\tskynet.send(watchdog, \"lua\", \"socket\", \"open\", fd, addr)\nend\n\nlocal function unforward(c)\n\tif c.agent then\n\t\tc.agent = nil\n\t\tc.client = nil\n\tend\nend\n\nlocal function close_fd(fd)\n\tlocal c = connection[fd]\n\tif c then\n\t\tunforward(c)\n\t\tconnection[fd] = nil\n\tend\nend\n\nfunction handler.disconnect(fd)\n\tclose_fd(fd)\n\tskynet.send(watchdog, \"lua\", \"socket\", \"close\", fd)\nend\n\nfunction handler.error(fd, msg)\n\tclose_fd(fd)\n\tskynet.send(watchdog, \"lua\", \"socket\", \"error\", fd, msg)\nend\n\nfunction handler.warning(fd, size)\n\tskynet.send(watchdog, \"lua\", \"socket\", \"warning\", fd, size)\nend\n\nlocal CMD = {}\n\nfunction CMD.forward(source, fd, client, address)\n\tlocal c = assert(connection[fd])\n\tunforward(c)\n\tc.client = client or 0\n\tc.agent = address or source\n\tgateserver.openclient(fd)\nend\n\nfunction CMD.accept(source, fd)\n\tlocal c = assert(connection[fd])\n\tunforward(c)\n\tgateserver.openclient(fd)\nend\n\nfunction CMD.kick(source, fd)\n\tgateserver.closeclient(fd)\nend\n\nfunction handler.command(cmd, source, ...)\n\tlocal f = assert(CMD[cmd])\n\treturn f(source, ...)\nend\n\ngateserver.start(handler)\n"
  },
  {
    "path": "service/launcher.lua",
    "content": "local skynet = require \"skynet\"\nlocal core = require \"skynet.core\"\nrequire \"skynet.manager\"\t-- import manager apis\nlocal string = string\n\nlocal services = {}\nlocal command = {}\nlocal instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK)\nlocal launch_session = {} -- for command.QUERY, service_address -> session\n\nlocal function handle_to_address(handle)\n\treturn tonumber(\"0x\" .. string.sub(handle , 2))\nend\n\nlocal NORET = {}\n\nfunction command.LIST()\n\tlocal list = {}\n\tfor k,v in pairs(services) do\n\t\tlist[skynet.address(k)] = v\n\tend\n\treturn list\nend\n\nlocal function list_srv(ti, fmt_func, ...)\n\tlocal list = {}\n\tlocal sessions = {}\n\tlocal req = skynet.request()\n\tfor addr in pairs(services) do\n\t\tlocal r = { addr, \"debug\", ... }\n\t\treq:add(r)\n\t\tsessions[r] = addr\n\tend\n\tfor req, resp in req:select(ti) do\n\t\tlocal addr = req[1]\n\t\tif resp then\n\t\t\tlocal stat = resp[1]\n\t\t\tlist[skynet.address(addr)] = fmt_func(stat, addr)\n\t\telse\n\t\t\tlist[skynet.address(addr)] = fmt_func(\"ERROR\", addr)\n\t\tend\n\t\tsessions[req] = nil\n\tend\n\tfor session, addr in pairs(sessions) do\n\t\tlist[skynet.address(addr)] = fmt_func(\"TIMEOUT\", addr)\n\tend\n\treturn list\nend\n\nfunction command.STAT(addr, ti)\n\treturn list_srv(ti, function(v) return v end, \"STAT\")\nend\n\nfunction command.KILL(_, handle)\n\tskynet.kill(handle)\n\tlocal ret = { [skynet.address(handle)] = tostring(services[handle]) }\n\tservices[handle] = nil\n\treturn ret\nend\n\nfunction command.MEM(addr, ti)\n\treturn list_srv(ti, function(kb, addr)\n\t\tlocal v = services[addr]\n\t\tif type(kb) == \"string\" then\n\t\t\treturn string.format(\"%s (%s)\", kb, v)\n\t\telse\n\t\t\treturn string.format(\"%.2f Kb (%s)\",kb,v)\n\t\tend\n\tend, \"MEM\")\nend\n\nfunction command.GC(addr, ti)\n\tfor k,v in pairs(services) do\n\t\tskynet.send(k,\"debug\",\"GC\")\n\tend\n\treturn command.MEM(addr, ti)\nend\n\nfunction command.REMOVE(_, handle, kill)\n\tservices[handle] = nil\n\tlocal response = instance[handle]\n\tif response then\n\t\t-- instance is dead\n\t\tresponse(not kill)\t-- return nil to caller of newservice, when kill == false\n\t\tinstance[handle] = nil\n\t\tlaunch_session[handle] = nil\n\tend\n\n\t-- don't return (skynet.ret) because the handle may exit\n\treturn NORET\nend\n\nlocal function launch_service(service, ...)\n\tlocal param = table.concat({...}, \" \")\n\tlocal inst = skynet.launch(service, param)\n\tlocal session = skynet.context()\n\tlocal response = skynet.response()\n\tif inst then\n\t\tservices[inst] = service .. \" \" .. param\n\t\tinstance[inst] = response\n\t\tlaunch_session[inst] = session\n\telse\n\t\tresponse(false)\n\t\treturn\n\tend\n\treturn inst\nend\n\nfunction command.LAUNCH(_, service, ...)\n\tlaunch_service(service, ...)\n\treturn NORET\nend\n\nfunction command.LOGLAUNCH(_, service, ...)\n\tlocal inst = launch_service(service, ...)\n\tif inst then\n\t\tcore.command(\"LOGON\", skynet.address(inst))\n\tend\n\treturn NORET\nend\n\nfunction command.ERROR(address)\n\t-- see serivce-src/service_lua.c\n\t-- init failed\n\tlocal response = instance[address]\n\tif response then\n\t\tresponse(false)\n\t\tlaunch_session[address] = nil\n\t\tinstance[address] = nil\n\tend\n\tservices[address] = nil\n\treturn NORET\nend\n\nfunction command.LAUNCHOK(address)\n\t-- init notice\n\tlocal response = instance[address]\n\tif response then\n\t\tresponse(true, address)\n\t\tinstance[address] = nil\n\t\tlaunch_session[address] = nil\n\tend\n\n\treturn NORET\nend\n\nfunction command.QUERY(_, request_session)\n\tfor address, session in pairs(launch_session) do\n\t\tif session == request_session then\n\t\t\treturn address\n\t\tend\n\tend\nend\n\n-- for historical reasons, launcher support text command (for C service)\n\nskynet.register_protocol {\n\tname = \"text\",\n\tid = skynet.PTYPE_TEXT,\n\tunpack = skynet.tostring,\n\tdispatch = function(session, address , cmd)\n\t\tif cmd == \"\" then\n\t\t\tcommand.LAUNCHOK(address)\n\t\telseif cmd == \"ERROR\" then\n\t\t\tcommand.ERROR(address)\n\t\telse\n\t\t\terror (\"Invalid text command \" .. cmd)\n\t\tend\n\tend,\n}\n\nskynet.dispatch(\"lua\", function(session, address, cmd , ...)\n\tcmd = string.upper(cmd)\n\tlocal f = command[cmd]\n\tif f then\n\t\tlocal ret = f(address, ...)\n\t\tif ret ~= NORET then\n\t\t\tskynet.ret(skynet.pack(ret))\n\t\tend\n\telse\n\t\tskynet.ret(skynet.pack {\"Unknown command\"} )\n\tend\nend)\n\nskynet.start(function() end)\n"
  },
  {
    "path": "service/multicastd.lua",
    "content": "local skynet = require \"skynet\"\nlocal mc = require \"skynet.multicast.core\"\nlocal datacenter = require \"skynet.datacenter\"\n\nlocal harbor_id = skynet.harbor(skynet.self())\n\nlocal command = {}\nlocal channel = {}\nlocal channel_n = {}\nlocal channel_remote = {}\nlocal channel_id = harbor_id\nlocal NORET = {}\n\nlocal function get_address(t, id)\n\tlocal v = assert(datacenter.get(\"multicast\", id))\n\tt[id] = v\n\treturn v\nend\n\nlocal node_address = setmetatable({}, { __index = get_address })\n\n-- new LOCAL channel , The low 8bit is the same with harbor_id\nfunction command.NEW()\n\twhile channel[channel_id] do\n\t\tchannel_id = mc.nextid(channel_id)\n\tend\n\tchannel[channel_id] = {}\n\tchannel_n[channel_id] = 0\n\tlocal ret = channel_id\n\tchannel_id = mc.nextid(channel_id)\n\treturn ret\nend\n\n-- MUST call by the owner node of channel, delete a remote channel\nfunction command.DELR(source, c)\n\tchannel[c] = nil\n\tchannel_n[c] = nil\n\treturn NORET\nend\n\n-- delete a channel, if the channel is remote, forward the command to the owner node\n-- otherwise, delete the channel, and call all the remote node, DELR\nfunction command.DEL(source, c)\n\tlocal node = c % 256\n\tif node ~= harbor_id then\n\t\tskynet.send(node_address[node], \"lua\", \"DEL\", c)\n\t\treturn NORET\n\tend\n\tlocal remote = channel_remote[c]\n\tchannel[c] = nil\n\tchannel_n[c] = nil\n\tchannel_remote[c] = nil\n\tif remote then\n\t\tfor node in pairs(remote) do\n\t\t\tskynet.send(node_address[node], \"lua\", \"DELR\", c)\n\t\tend\n\tend\n\treturn NORET\nend\n\n-- forward multicast message to a node (channel id use the session field)\nlocal function remote_publish(node, channel, source, ...)\n\tskynet.redirect(node_address[node], source, \"multicast\", channel, ...)\nend\n\n-- publish a message, for local node, use the message pointer (call mc.bind to add the reference)\n-- for remote node, call remote_publish. (call mc.unpack and skynet.tostring to convert message pointer to string)\nlocal function publish(c , source, pack, size)\n\tlocal remote = channel_remote[c]\n\tif remote then\n\t\t-- remote publish should unpack the pack, because we should not publish the pointer out.\n\t\tlocal _, msg, sz = mc.unpack(pack, size)\n\t\tlocal msg = skynet.tostring(msg,sz)\n\t\tfor node in pairs(remote) do\n\t\t\tremote_publish(node, c, source, msg)\n\t\tend\n\tend\n\n\tlocal group = channel[c]\n\tif group == nil or next(group) == nil then\n\t\t-- dead channel, delete the pack. mc.bind returns the pointer in pack and free the pack (struct mc_package **)\n\t\tlocal pack = mc.bind(pack, 1)\n\t\tmc.close(pack)\n\t\treturn\n\tend\n\tlocal msg = skynet.tostring(pack, size)\t-- copy (pack,size) to a string\n\tmc.bind(pack, channel_n[c])\t-- mc.bind will free the pack(struct mc_package **)\n\tfor k in pairs(group) do\n\t\t-- the msg is a pointer to the real message, publish pointer in local is ok.\n\t\tskynet.redirect(k, source, \"multicast\", c , msg)\n\tend\nend\n\nskynet.register_protocol {\n\tname = \"multicast\",\n\tid = skynet.PTYPE_MULTICAST,\n\tunpack = function(msg, sz)\n\t\treturn mc.packremote(msg, sz)\n\tend,\n\tdispatch = function (...)\n\t\tskynet.ignoreret()\n\t\tpublish(...)\n\tend,\n}\n\n-- publish a message, if the caller is remote, forward the message to the owner node (by remote_publish)\n-- If the caller is local, call publish\nfunction command.PUB(source, c, pack, size)\n\tassert(skynet.harbor(source) == harbor_id)\n\tlocal node = c % 256\n\tif node ~= harbor_id then\n\t\t-- remote publish\n\t\tremote_publish(node, c, source, mc.remote(pack))\n\telse\n\t\tpublish(c, source, pack,size)\n\tend\nend\n\n-- the node (source) subscribe a channel\n-- MUST call by channel owner node (assert source is not local and channel is create by self)\n-- If channel is not exist, return true\n-- Else set channel_remote[channel] true\nfunction command.SUBR(source, c)\n\tlocal node = skynet.harbor(source)\n\tif not channel[c] then\n\t\t-- channel none exist\n\t\treturn true\n\tend\n\tassert(node ~= harbor_id and c % 256 == harbor_id)\n\tlocal group = channel_remote[c]\n\tif group == nil then\n\t\tgroup = {}\n\t\tchannel_remote[c] = group\n\tend\n\tgroup[node] = true\nend\n\n-- the service (source) subscribe a channel\n-- If the channel is remote, node subscribe it by send a SUBR to the owner .\nfunction command.SUB(source, c)\n\tlocal node = c % 256\n\tif node ~= harbor_id then\n\t\t-- remote group\n\t\tif channel[c] == nil then\n\t\t\tif skynet.call(node_address[node], \"lua\", \"SUBR\", c) then\n\t\t\t\treturn\n\t\t\tend\n\t\t\tif channel[c] == nil then\n\t\t\t\t-- double check, because skynet.call whould yield, other SUB may occur.\n\t\t\t\tchannel[c] = {}\n\t\t\t\tchannel_n[c] = 0\n\t\t\tend\n\t\tend\n\tend\n\tlocal group = channel[c]\n\tif group and not group[source] then\n\t\tchannel_n[c] = channel_n[c] + 1\n\t\tgroup[source] = true\n\tend\nend\n\n-- MUST call by a node, unsubscribe a channel\nfunction command.USUBR(source, c)\n\tlocal node = skynet.harbor(source)\n\tassert(node ~= harbor_id)\n\tlocal group = assert(channel_remote[c])\n\tgroup[node] = nil\n\treturn NORET\nend\n\n-- Unsubscribe a channel, if the subscriber is empty and the channel is remote, send USUBR to the channel owner\nfunction command.USUB(source, c)\n\tlocal group = assert(channel[c])\n\tif group[source] then\n\t\tgroup[source] = nil\n\t\tchannel_n[c] = channel_n[c] - 1\n\t\tif channel_n[c] == 0 then\n\t\t\tlocal node = c % 256\n\t\t\tif node ~= harbor_id then\n\t\t\t\t-- remote group\n\t\t\t\tchannel[c] = nil\n\t\t\t\tchannel_n[c] = nil\n\t\t\t\tskynet.send(node_address[node], \"lua\", \"USUBR\", c)\n\t\t\tend\n\t\tend\n\tend\n\treturn NORET\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(_,source, cmd, ...)\n\t\tlocal f = assert(command[cmd])\n\t\tlocal result = f(source, ...)\n\t\tif result ~= NORET then\n\t\t\tskynet.ret(skynet.pack(result))\n\t\tend\n\tend)\n\tlocal self = skynet.self()\n\tlocal id = skynet.harbor(self)\n\tassert(datacenter.set(\"multicast\", id, self) == nil)\nend)\n\n"
  },
  {
    "path": "service/service_cell.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal service_name = (...)\nlocal init = {}\n\nfunction init.init(code, ...)\n\tlocal start_func\n\tskynet.start = function(f)\n\t\tstart_func = f\n\tend\n\tskynet.dispatch(\"lua\", function() error(\"No dispatch function\")\tend)\n\tlocal mainfunc = assert(load(code, service_name))\n\tassert(skynet.pcall(mainfunc,...))\n\tif start_func then\n\t\tstart_func()\n\tend\n\tskynet.ret()\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(_,_,cmd,...)\n\t\tinit[cmd](...)\n\tend)\nend)\n"
  },
  {
    "path": "service/service_mgr.lua",
    "content": "local skynet = require \"skynet\"\nrequire \"skynet.manager\"\t-- import skynet.register\nlocal snax = require \"skynet.snax\"\n\nlocal cmd = {}\nlocal service = {}\n\nlocal function request(name, func, ...)\n\tlocal ok, handle = pcall(func, ...)\n\tlocal s = service[name]\n\tassert(type(s) == \"table\")\n\tif ok then\n\t\tservice[name] = handle\n\telse\n\t\tservice[name] = tostring(handle)\n\tend\n\n\tfor _,v in ipairs(s) do\n\t\tskynet.wakeup(v.co)\n\tend\n\n\tif ok then\n\t\treturn handle\n\telse\n\t\terror(tostring(handle))\n\tend\nend\n\nlocal function waitfor(name , func, ...)\n\tlocal s = service[name]\n\tif type(s) == \"number\" then\n\t\treturn s\n\tend\n\tlocal co = coroutine.running()\n\n\tif s == nil then\n\t\ts = {}\n\t\tservice[name] = s\n\telseif type(s) == \"string\" then\n\t\terror(s)\n\tend\n\n\tassert(type(s) == \"table\")\n\n\tlocal session, source = skynet.context()\n\n\tif s.launch == nil and func then\n\t\ts.launch = {\n\t\t\tsession = session,\n\t\t\tsource = source,\n\t\t\tco = co,\n\t\t}\n\t\treturn request(name, func, ...)\n\tend\n\n\ttable.insert(s, {\n\t\tco = co,\n\t\tsession = session,\n\t\tsource = source,\n\t})\n\tskynet.wait()\n\ts = service[name]\n\tif type(s) == \"string\" then\n\t\terror(s)\n\tend\n\tassert(type(s) == \"number\")\n\treturn s\nend\n\nlocal function read_name(service_name)\n\tif string.byte(service_name) == 64 then -- '@'\n\t\treturn string.sub(service_name , 2)\n\telse\n\t\treturn service_name\n\tend\nend\n\nfunction cmd.LAUNCH(service_name, subname, ...)\n\tlocal realname = read_name(service_name)\n\n\tif realname == \"snaxd\" then\n\t\treturn waitfor(service_name..\".\"..subname, snax.rawnewservice, subname, ...)\n\telse\n\t\treturn waitfor(service_name, skynet.newservice, realname, subname, ...)\n\tend\nend\n\nfunction cmd.QUERY(service_name, subname)\n\tlocal realname = read_name(service_name)\n\n\tif realname == \"snaxd\" then\n\t\treturn waitfor(service_name..\".\"..subname)\n\telse\n\t\treturn waitfor(service_name)\n\tend\nend\n\nlocal function list_service()\n\tlocal val\n\tlocal result = {}\n\tfor k,v in pairs(service) do\n\t\tif type(v) == \"string\" then\n\t\t\tval = \"Error: \" .. v\n\t\telseif type(v) == \"table\" then\n\t\t\tlocal querying = {}\n\t\t\tif v.launch then\n\t\t\t\tlocal session = skynet.task(v.launch.co)\n\t\t\t\tlocal launching_address = skynet.call(\".launcher\", \"lua\", \"QUERY\", session)\n\t\t\t\tif launching_address then\n\t\t\t\t\ttable.insert(querying, \"Init as \" .. skynet.address(launching_address))\n\t\t\t\t\ttable.insert(querying,  skynet.call(launching_address, \"debug\", \"TASK\", \"init\"))\n\t\t\t\t\ttable.insert(querying, \"Launching from \" .. skynet.address(v.launch.source))\n\t\t\t\t\ttable.insert(querying, skynet.call(v.launch.source, \"debug\", \"TASK\", v.launch.session))\n\t\t\t\tend\n\t\t\tend\n\t\t\tif #v > 0 then\n\t\t\t\ttable.insert(querying , \"Querying:\" )\n\t\t\t\tfor _, detail in ipairs(v) do\n\t\t\t\t\ttable.insert(querying, skynet.address(detail.source) .. \" \" .. tostring(skynet.call(detail.source, \"debug\", \"TASK\", detail.session)))\n\t\t\t\tend\n\t\t\tend\n\t\t\tval = table.concat(querying, \"\\n\")\n\t\telse\n\t\t\tval = skynet.address(v)\n\t\tend\n\n\t\tresult[k] = val\n\tend\n\n\treturn result\nend\n\n\nlocal function register_global()\n\tfunction cmd.GLAUNCH(name, ...)\n\t\tlocal global_name = \"@\" .. name\n\t\treturn cmd.LAUNCH(global_name, ...)\n\tend\n\n\tfunction cmd.GQUERY(name, ...)\n\t\tlocal global_name = \"@\" .. name\n\t\treturn cmd.QUERY(global_name, ...)\n\tend\n\n\tlocal mgr = {}\n\n\tfunction cmd.REPORT(m)\n\t\tmgr[m] = true\n\tend\n\n\tlocal function add_list(all, m)\n\t\tlocal harbor = \"@\" .. skynet.harbor(m)\n\t\tlocal result = skynet.call(m, \"lua\", \"LIST\")\n\t\tfor k,v in pairs(result) do\n\t\t\tall[k .. harbor] = v\n\t\tend\n\tend\n\n\tfunction cmd.LIST()\n\t\tlocal result = {}\n\t\tfor k in pairs(mgr) do\n\t\t\tpcall(add_list, result, k)\n\t\tend\n\t\tlocal l = list_service()\n\t\tfor k, v in pairs(l) do\n\t\t\tresult[k] = v\n\t\tend\n\t\treturn result\n\tend\nend\n\nlocal function register_local()\n\tlocal function waitfor_remote(cmd, name, ...)\n\t\tlocal global_name = \"@\" .. name\n\t\tlocal local_name\n\t\tif name == \"snaxd\" then\n\t\t\tlocal_name = global_name .. \".\" .. (...)\n\t\telse\n\t\t\tlocal_name = global_name\n\t\tend\n\t\treturn waitfor(local_name, skynet.call, \"SERVICE\", \"lua\", cmd, global_name, ...)\n\tend\n\n\tfunction cmd.GLAUNCH(...)\n\t\treturn waitfor_remote(\"LAUNCH\", ...)\n\tend\n\n\tfunction cmd.GQUERY(...)\n\t\treturn waitfor_remote(\"QUERY\", ...)\n\tend\n\n\tfunction cmd.LIST()\n\t\treturn list_service()\n\tend\n\n\tskynet.call(\"SERVICE\", \"lua\", \"REPORT\", skynet.self())\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(session, address, command, ...)\n\t\tlocal f = cmd[command]\n\t\tif f == nil then\n\t\t\tskynet.ret(skynet.pack(nil, \"Invalid command \" .. command))\n\t\t\treturn\n\t\tend\n\n\t\tlocal ok, r = pcall(f, ...)\n\n\t\tif ok then\n\t\t\tskynet.ret(skynet.pack(r))\n\t\telse\n\t\t\tskynet.ret(skynet.pack(nil, r))\n\t\tend\n\tend)\n\tlocal handle = skynet.localname \".service\"\n\tif  handle then\n\t\tskynet.error(\".service is already register by \", skynet.address(handle))\n\t\tskynet.exit()\n\telse\n\t\tskynet.register(\".service\")\n\tend\n\tif skynet.getenv \"standalone\" then\n\t\tskynet.register(\"SERVICE\")\n\t\tregister_global()\n\telse\n\t\tregister_local()\n\tend\nend)\n"
  },
  {
    "path": "service/service_provider.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal provider = {}\n\nlocal function new_service(svr, name)\n\tlocal s = {}\n\tsvr[name] = s\n\ts.queue = {}\n\treturn s\nend\n\nlocal svr = setmetatable({}, { __index = new_service })\n\n\nfunction provider.query(name)\n\tlocal s = svr[name]\n\tif s.queue then\n\t\ttable.insert(s.queue, skynet.response())\n\telse\n\t\tif s.address then\n\t\t\treturn skynet.ret(skynet.pack(s.address))\n\t\telse\n\t\t\terror(s.error)\n\t\tend\n\tend\nend\n\nlocal function boot(addr, name, code, ...)\n\tlocal s = svr[name]\n\tskynet.call(addr, \"lua\", \"init\", code, ...)\n\tlocal tmp = table.pack( ... )\n\tfor i=1,tmp.n do\n\t\ttmp[i] = tostring(tmp[i])\n\tend\n\n\tif tmp.n > 0 then\n\t\ts.init = table.concat(tmp, \",\")\n\tend\n\ts.time = skynet.time()\nend\n\nfunction provider.launch(name, code, ...)\n\tlocal s = svr[name]\n\tif s.address then\n\t\treturn skynet.ret(skynet.pack(s.address))\n\tend\n\tif s.booting then\n\t\ttable.insert(s.queue, skynet.response())\n\telse\n\t\ts.booting = true\n\t\tlocal err\n\t\tlocal ok, addr = pcall(skynet.newservice,\"service_cell\", name)\n\t\tif ok then\n\t\t\tok, err = xpcall(boot, debug.traceback, addr, name, code, ...)\n\t\telse\n\t\t\terr = addr\n\t\t\taddr = nil\n\t\tend\n\t\ts.booting = nil\n\t\tif ok then\n\t\t\ts.address = addr\n\t\t\tfor _, resp in ipairs(s.queue) do\n\t\t\t\tresp(true, addr)\n\t\t\tend\n\t\t\ts.queue = nil\n\t\t\tskynet.ret(skynet.pack(addr))\n\t\telse\n\t\t\tif addr then\n\t\t\t\tskynet.send(addr, \"debug\", \"EXIT\")\n\t\t\tend\n\t\t\ts.error = err\n\t\t\tfor _, resp in ipairs(s.queue) do\n\t\t\t\tresp(false)\n\t\t\tend\n\t\t\ts.queue = nil\n\t\t\terror(err)\n\t\tend\n\tend\nend\n\nfunction provider.test(name)\n\tlocal s = svr[name]\n\tif s.booting then\n\t\tskynet.ret(skynet.pack(nil, true))\t-- booting\n\telseif s.address then\n\t\tskynet.ret(skynet.pack(s.address))\n\telseif s.error then\n\t\terror(s.error)\n\telse\n\t\tskynet.ret()\t-- nil\n\tend\nend\n\nfunction provider.close(name)\n\tlocal s = svr[name]\n\tif not s or s.booting then\n\t\treturn skynet.ret(skynet.pack(nil))\n\tend\n\n\tsvr[name] = nil\n\tskynet.ret(skynet.pack(s.address))\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(session, address, cmd, ...)\n\t\tprovider[cmd](...)\n\tend)\n\tskynet.info_func(function()\n\t\tlocal info = {}\n\t\tfor k,v in pairs(svr) do\n\t\t\tlocal status\n\t\t\tif v.booting then\n\t\t\t\tstatus = \"booting\"\n\t\t\telseif v.queue then\n\t\t\t\tstatus = \"waiting(\" .. #v.queue .. \")\"\n\t\t\tend\n\t\t\tinfo[skynet.address(v.address)] = {\n\t\t\t\tinit = v.init,\n\t\t\t\tname = k,\n\t\t\t\ttime = os.date(\"%Y %b %d %T %z\",math.floor(v.time)),\n\t\t\t\tstatus = status,\n\t\t\t}\n\t\tend\n\t\treturn info\n\tend)\nend)\n"
  },
  {
    "path": "service/sharedatad.lua",
    "content": "local skynet = require \"skynet\"\nlocal sharedata = require \"skynet.sharedata.corelib\"\nlocal table = table\nlocal cache = require \"skynet.codecache\"\ncache.mode \"OFF\"\t-- turn off codecache, because CMD.new may load data file\n\nlocal NORET = {}\nlocal pool = {}\nlocal pool_count = {}\nlocal objmap = {}\nlocal collect_tick = 10\n\nlocal function newobj(name, tbl)\n\tassert(pool[name] == nil)\n\tlocal cobj = sharedata.host.new(tbl)\n\tsharedata.host.incref(cobj)\n\tlocal v = {obj = cobj, watch = {} }\n\tobjmap[cobj] = v\n\tpool[name] = v\n\tpool_count[name] = { n = 0, threshold = 16 }\nend\n\nlocal function collect1min()\n\tif collect_tick > 1 then\n\t\tcollect_tick = 1\n\tend\nend\n\nlocal function collectobj()\n\twhile true do\n\t\tskynet.sleep(60*100)\t-- sleep 1min\n\t\tif collect_tick <= 0 then\n\t\t\tcollect_tick = 10\t-- reset tick count to 10 min\n\t\t\tcollectgarbage()\n\t\t\tfor obj, v in pairs(objmap) do\n\t\t\t\tif v == true then\n\t\t\t\t\tif sharedata.host.getref(obj) <= 0  then\n\t\t\t\t\t\tobjmap[obj] = nil\n\t\t\t\t\t\tsharedata.host.delete(obj)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tcollect_tick = collect_tick - 1\n\t\tend\n\tend\nend\n\nlocal CMD = {}\n\nlocal env_mt = { __index = _ENV }\n\nfunction CMD.new(name, t, ...)\n\tlocal dt = type(t)\n\tlocal value\n\tif dt == \"table\" then\n\t\tvalue = t\n\telseif dt == \"string\" then\n\t\tvalue = setmetatable({}, env_mt)\n\t\tlocal f\n\t\tif t:sub(1,1) == \"@\" then\n\t\t\tf = assert(loadfile(t:sub(2),\"bt\",value))\n\t\telse\n\t\t\tf = assert(load(t, \"=\" .. name, \"bt\", value))\n\t\tend\n\t\tlocal _, ret = assert(skynet.pcall(f, ...))\n\t\tsetmetatable(value, nil)\n\t\tif type(ret) == \"table\" then\n\t\t\tvalue = ret\n\t\tend\n\telseif dt == \"nil\" then\n\t\tvalue = {}\n\telse\n\t\terror (\"Unknown data type \" .. dt)\n\tend\n\tnewobj(name, value)\nend\n\nfunction CMD.delete(name)\n\tlocal v = assert(pool[name])\n\tpool[name] = nil\n\tpool_count[name] = nil\n\tassert(objmap[v.obj])\n\tobjmap[v.obj] = true\n\tsharedata.host.decref(v.obj)\n\tfor _,response in pairs(v.watch) do\n\t\tresponse(true)\n\tend\nend\n\nfunction CMD.query(name)\n\tlocal v = assert(pool[name], name)\n\tlocal obj = v.obj\n\tsharedata.host.incref(obj)\n\treturn v.obj\nend\n\nfunction CMD.confirm(cobj)\n\tif objmap[cobj] then\n\t\tsharedata.host.decref(cobj)\n\tend\n\treturn NORET\nend\n\nfunction CMD.update(name, t, ...)\n\tlocal v = pool[name]\n\tlocal watch, oldcobj\n\tif v then\n\t\twatch = v.watch\n\t\toldcobj = v.obj\n\t\tobjmap[oldcobj] = true\n\t\tsharedata.host.decref(oldcobj)\n\t\tpool[name] = nil\n\t\tpool_count[name] = nil\n\tend\n\tCMD.new(name, t, ...)\n\tlocal newobj = pool[name].obj\n\tif watch then\n\t\tsharedata.host.markdirty(oldcobj)\n\t\tfor _,response in pairs(watch) do\n\t\t\tsharedata.host.incref(newobj)\n\t\t\tresponse(true, newobj)\n\t\tend\n\tend\n\tcollect1min()\t-- collect in 1 min\nend\n\nlocal function check_watch(queue)\n\tlocal n = 0\n\tfor k,response in pairs(queue) do\n\t\tif not response \"TEST\" then\n\t\t\tqueue[k] = nil\n\t\t\tn = n + 1\n\t\tend\n\tend\n\treturn n\nend\n\nfunction CMD.monitor(name, obj)\n\tlocal v = assert(pool[name])\n\tif obj ~= v.obj then\n\t\tsharedata.host.incref(v.obj)\n\t\treturn v.obj\n\tend\n\n\tlocal n = pool_count[name].n + 1\n\tif n > pool_count[name].threshold then\n\t\tn = n - check_watch(v.watch)\n\t\tpool_count[name].threshold = n * 2\n\tend\n\tpool_count[name].n = n\n\n\ttable.insert(v.watch, skynet.response())\n\n\treturn NORET\nend\n\nskynet.start(function()\n\tskynet.fork(collectobj)\n\tskynet.dispatch(\"lua\", function (session, source ,cmd, ...)\n\t\tlocal f = assert(CMD[cmd])\n\t\tlocal r = f(...)\n\t\tif r ~= NORET then\n\t\t\tskynet.ret(skynet.pack(r))\n\t\tend\n\tend)\nend)\n\n"
  },
  {
    "path": "service/snaxd.lua",
    "content": "local skynet = require \"skynet\"\nlocal c = require \"skynet.core\"\nlocal snax_interface = require \"snax.interface\"\nlocal profile = require \"skynet.profile\"\nlocal snax = require \"skynet.snax\"\n\nlocal snax_name = tostring(...)\nlocal loaderpath = skynet.getenv\"snax_loader\"\nlocal loader = loaderpath and assert(dofile(loaderpath))\nlocal func, pattern = snax_interface(snax_name, _ENV, loader)\nlocal snax_path = pattern:sub(1,pattern:find(\"?\", 1, true)-1) .. snax_name ..  \"/\"\npackage.path = snax_path .. \"?.lua;\" .. package.path\n\nSERVICE_NAME = snax_name\nSERVICE_PATH = snax_path\n\nlocal profile_table = {}\n\nlocal function update_stat(name, ti)\n\tlocal t = profile_table[name]\n\tif t == nil then\n\t\tt = { count = 0,  time = 0 }\n\t\tprofile_table[name] = t\n\tend\n\tt.count = t.count + 1\n\tt.time = t.time + ti\nend\n\nlocal traceback = debug.traceback\n\nlocal function return_f(f, ...)\n\treturn skynet.ret(skynet.pack(f(...)))\nend\n\nlocal function timing( method, ... )\n\tlocal err, msg\n\tprofile.start()\n\tif method[2] == \"accept\" then\n\t\t-- no return\n\t\terr,msg = xpcall(method[4], traceback, ...)\n\telse\n\t\terr,msg = xpcall(return_f, traceback, method[4], ...)\n\tend\n\tlocal ti = profile.stop()\n\tupdate_stat(method[3], ti)\n\tassert(err,msg)\nend\n\nskynet.start(function()\n\tlocal init = false\n\tlocal function dispatcher( session , source , id, ...)\n\t\tlocal method = func[id]\n\n\t\tif method[2] == \"system\" then\n\t\t\tlocal command = method[3]\n\t\t\tif command == \"hotfix\" then\n\t\t\t\tlocal hotfix = require \"snax.hotfix\"\n\t\t\t\tskynet.ret(skynet.pack(hotfix(func, ...)))\n\t\t\telseif command == \"profile\" then\n\t\t\t\tskynet.ret(skynet.pack(profile_table))\n\t\t\telseif command == \"init\" then\n\t\t\t\tassert(not init, \"Already init\")\n\t\t\t\tlocal initfunc = method[4] or function() end\n\t\t\t\tinitfunc(...)\n\t\t\t\tskynet.ret()\n\t\t\t\tskynet.info_func(function()\n\t\t\t\t\treturn profile_table\n\t\t\t\tend)\n\t\t\t\tinit = true\n\t\t\telse\n\t\t\t\tassert(init, \"Never init\")\n\t\t\t\tassert(command == \"exit\")\n\t\t\t\tlocal exitfunc = method[4] or function() end\n\t\t\t\texitfunc(...)\n\t\t\t\tskynet.ret()\n\t\t\t\tinit = false\n\t\t\t\tskynet.exit()\n\t\t\tend\n\t\telse\n\t\t\tassert(init, \"Init first\")\n\t\t\ttiming(method, ...)\n\t\tend\n\tend\n\tskynet.dispatch(\"snax\", dispatcher)\n\n\t-- set lua dispatcher\n\tfunction snax.enablecluster()\n\t\tskynet.dispatch(\"lua\", dispatcher)\n\tend\nend)\n"
  },
  {
    "path": "service-src/databuffer.h",
    "content": "#ifndef skynet_databuffer_h\n#define skynet_databuffer_h\n\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n\n#define MESSAGEPOOL 1023\n\nstruct message {\n\tchar * buffer;\n\tint size;\n\tstruct message * next;\n};\n\nstruct databuffer {\n\tint header;\n\tint offset;\n\tint size;\n\tstruct message * head;\n\tstruct message * tail;\n};\n\nstruct messagepool_list {\n\tstruct messagepool_list *next;\n\tstruct message pool[MESSAGEPOOL];\n};\n\nstruct messagepool {\n\tstruct messagepool_list * pool;\n\tstruct message * freelist;\n};\n\n// use memset init struct \n\nstatic void \nmessagepool_free(struct messagepool *pool) {\n\tstruct messagepool_list *p = pool->pool;\n\twhile(p) {\n\t\tstruct messagepool_list *tmp = p;\n\t\tp=p->next;\n\t\tskynet_free(tmp);\n\t}\n\tpool->pool = NULL;\n\tpool->freelist = NULL;\n}\n\nstatic inline void\n_return_message(struct databuffer *db, struct messagepool *mp) {\n\tstruct message *m = db->head;\n\tif (m->next == NULL) {\n\t\tassert(db->tail == m);\n\t\tdb->head = db->tail = NULL;\n\t} else {\n\t\tdb->head = m->next;\n\t}\n\tskynet_free(m->buffer);\n\tm->buffer = NULL;\n\tm->size = 0;\n\tm->next = mp->freelist;\n\tmp->freelist = m;\n}\n\nstatic void\ndatabuffer_read(struct databuffer *db, struct messagepool *mp, char * buffer, int sz) {\n\tassert(db->size >= sz);\n\tdb->size -= sz;\n\tfor (;;) {\n\t\tstruct message *current = db->head;\n\t\tint bsz = current->size - db->offset;\n\t\tif (bsz > sz) {\n\t\t\tmemcpy(buffer, current->buffer + db->offset, sz);\n\t\t\tdb->offset += sz;\n\t\t\treturn;\n\t\t}\n\t\tif (bsz == sz) {\n\t\t\tmemcpy(buffer, current->buffer + db->offset, sz);\n\t\t\tdb->offset = 0;\n\t\t\t_return_message(db, mp);\n\t\t\treturn;\n\t\t} else {\n\t\t\tmemcpy(buffer, current->buffer + db->offset, bsz);\n\t\t\t_return_message(db, mp);\n\t\t\tdb->offset = 0;\n\t\t\tbuffer+=bsz;\n\t\t\tsz-=bsz;\n\t\t}\n\t}\n}\n\nstatic void\ndatabuffer_push(struct databuffer *db, struct messagepool *mp, void *data, int sz) {\n\tstruct message * m;\n\tif (mp->freelist) {\n\t\tm = mp->freelist;\n\t\tmp->freelist = m->next;\n\t} else {\n\t\tstruct messagepool_list * mpl = skynet_malloc(sizeof(*mpl));\n\t\tstruct message * temp = mpl->pool;\n\t\tint i;\n\t\tfor (i=1;i<MESSAGEPOOL;i++) {\n\t\t\ttemp[i].buffer = NULL;\n\t\t\ttemp[i].size = 0;\n\t\t\ttemp[i].next = &temp[i+1];\n\t\t}\n\t\ttemp[MESSAGEPOOL-1].next = NULL;\n\t\tmpl->next = mp->pool;\n\t\tmp->pool = mpl;\n\t\tm = &temp[0];\n\t\tmp->freelist = &temp[1];\n\t}\n\tm->buffer = data;\n\tm->size = sz;\n\tm->next = NULL;\n\tdb->size += sz;\n\tif (db->head == NULL) {\n\t\tassert(db->tail == NULL);\n\t\tdb->head = db->tail = m;\n\t} else {\n\t\tdb->tail->next = m;\n\t\tdb->tail = m;\n\t}\n}\n\nstatic int\ndatabuffer_readheader(struct databuffer *db, struct messagepool *mp, int header_size) {\n\tif (db->header == 0) {\n\t\t// parser header (2 or 4)\n\t\tif (db->size < header_size) {\n\t\t\treturn -1;\n\t\t}\n\t\tuint8_t plen[4];\n\t\tdatabuffer_read(db,mp,(char *)plen,header_size);\n\t\t// big-endian\n\t\tif (header_size == 2) {\n\t\t\tdb->header = plen[0] << 8 | plen[1];\n\t\t} else {\n\t\t\tdb->header = plen[0] << 24 | plen[1] << 16 | plen[2] << 8 | plen[3];\n\t\t}\n\t}\n\tif (db->size < db->header)\n\t\treturn -1;\n\treturn db->header;\n}\n\nstatic inline void\ndatabuffer_reset(struct databuffer *db) {\n\tdb->header = 0;\n}\n\nstatic void\ndatabuffer_clear(struct databuffer *db, struct messagepool *mp) {\n\twhile (db->head) {\n\t\t_return_message(db,mp);\n\t}\n\tmemset(db, 0, sizeof(*db));\n}\n\n#endif\n"
  },
  {
    "path": "service-src/hashid.h",
    "content": "#ifndef skynet_hashid_h\n#define skynet_hashid_h\n\n#include <assert.h>\n#include <stdlib.h>\n#include <string.h>\n\nstruct hashid_node {\n\tint id;\n\tstruct hashid_node *next;\n};\n\nstruct hashid {\n\tint hashmod;\n\tint cap;\n\tint count;\n\tstruct hashid_node *id;\n\tstruct hashid_node **hash;\n};\n\nstatic void\nhashid_init(struct hashid *hi, int max) {\n\tint i;\n\tint hashcap;\n\thashcap = 16;\n\twhile (hashcap < max) {\n\t\thashcap *= 2;\n\t}\n\thi->hashmod = hashcap - 1;\n\thi->cap = max;\n\thi->count = 0;\n\thi->id = skynet_malloc(max * sizeof(struct hashid_node));\n\tfor (i=0;i<max;i++) {\n\t\thi->id[i].id = -1;\n\t\thi->id[i].next = NULL;\n\t}\n\thi->hash = skynet_malloc(hashcap * sizeof(struct hashid_node *));\n\tmemset(hi->hash, 0, hashcap * sizeof(struct hashid_node *));\n}\n\nstatic void\nhashid_clear(struct hashid *hi) {\n\tskynet_free(hi->id);\n\tskynet_free(hi->hash);\n\thi->id = NULL;\n\thi->hash = NULL;\n\thi->hashmod = 1;\n\thi->cap = 0;\n\thi->count = 0;\n}\n\nstatic int\nhashid_lookup(struct hashid *hi, int id) {\n\tint h = id & hi->hashmod;\n\tstruct hashid_node * c = hi->hash[h];\n\twhile(c) {\n\t\tif (c->id == id)\n\t\t\treturn c - hi->id;\n\t\tc = c->next;\n\t}\n\treturn -1;\n}\n\nstatic int\nhashid_remove(struct hashid *hi, int id) {\n\tint h = id & hi->hashmod;\n\tstruct hashid_node * c = hi->hash[h];\n\tif (c == NULL)\n\t\treturn -1;\n\tif (c->id == id) {\n\t\thi->hash[h] = c->next;\n\t\tgoto _clear;\n\t}\n\twhile(c->next) {\n\t\tif (c->next->id == id) {\n\t\t\tstruct hashid_node * temp = c->next;\n\t\t\tc->next = temp->next;\n\t\t\tc = temp;\n\t\t\tgoto _clear;\n\t\t}\n\t\tc = c->next;\n\t}\n\treturn -1;\n_clear:\n\tc->id = -1;\n\tc->next = NULL;\n\t--hi->count;\n\treturn c - hi->id;\n}\n\nstatic int\nhashid_insert(struct hashid * hi, int id) {\n\tstruct hashid_node *c = NULL;\n\tint i;\n\tfor (i=0;i<hi->cap;i++) {\n\t\tint index = (i+id) % hi->cap;\n\t\tif (hi->id[index].id == -1) {\n\t\t\tc = &hi->id[index];\n\t\t\tbreak;\n\t\t}\n\t}\n\tassert(c);\n\t++hi->count;\n\tc->id = id;\n\tassert(c->next == NULL);\n\tint h = id & hi->hashmod;\n\tif (hi->hash[h]) {\n\t\tc->next = hi->hash[h];\n\t}\n\thi->hash[h] = c;\n\t\n\treturn c - hi->id;\n}\n\nstatic inline int\nhashid_full(struct hashid *hi) {\n\treturn hi->count == hi->cap;\n}\n\n#endif\n"
  },
  {
    "path": "service-src/service_gate.c",
    "content": "#include \"skynet.h\"\n#include \"skynet_socket.h\"\n#include \"databuffer.h\"\n#include \"hashid.h\"\n\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdarg.h>\n\n#define BACKLOG 128\n\nstruct connection {\n\tint id;\t// skynet_socket id\n\tuint32_t agent;\n\tuint32_t client;\n\tchar remote_name[32];\n\tstruct databuffer buffer;\n};\n\nstruct gate {\n\tstruct skynet_context *ctx;\n\tint listen_id;\n\tuint32_t watchdog;\n\tuint32_t broker;\n\tint client_tag;\n\tint header_size;\n\tint max_connection;\n\tstruct hashid hash;\n\tstruct connection *conn;\n\t// todo: save message pool ptr for release\n\tstruct messagepool mp;\n};\n\nstruct gate *\ngate_create(void) {\n\tstruct gate * g = skynet_malloc(sizeof(*g));\n\tmemset(g,0,sizeof(*g));\n\tg->listen_id = -1;\n\treturn g;\n}\n\nvoid\ngate_release(struct gate *g) {\n\tint i;\n\tstruct skynet_context *ctx = g->ctx;\n\tfor (i=0;i<g->max_connection;i++) {\n\t\tstruct connection *c = &g->conn[i];\n\t\tif (c->id >=0) {\n\t\t\tskynet_socket_close(ctx, c->id);\n\t\t}\n\t}\n\tif (g->listen_id >= 0) {\n\t\tskynet_socket_close(ctx, g->listen_id);\n\t}\n\tmessagepool_free(&g->mp);\n\thashid_clear(&g->hash);\n\tskynet_free(g->conn);\n\tskynet_free(g);\n}\n\nstatic void\n_parm(char *msg, int sz, int command_sz) {\n\twhile (command_sz < sz) {\n\t\tif (msg[command_sz] != ' ')\n\t\t\tbreak;\n\t\t++command_sz;\n\t}\n\tint i;\n\tfor (i=command_sz;i<sz;i++) {\n\t\tmsg[i-command_sz] = msg[i];\n\t}\n\tmsg[i-command_sz] = '\\0';\n}\n\nstatic void\n_forward_agent(struct gate * g, int fd, uint32_t agentaddr, uint32_t clientaddr) {\n\tint id = hashid_lookup(&g->hash, fd);\n\tif (id >=0) {\n\t\tstruct connection * agent = &g->conn[id];\n\t\tagent->agent = agentaddr;\n\t\tagent->client = clientaddr;\n\t}\n}\n\nstatic void\n_ctrl(struct gate * g, const void * msg, int sz) {\n\tstruct skynet_context * ctx = g->ctx;\n\tchar tmp[sz+1];\n\tmemcpy(tmp, msg, sz);\n\ttmp[sz] = '\\0';\n\tchar * command = tmp;\n\tint i;\n\tif (sz == 0)\n\t\treturn;\n\tfor (i=0;i<sz;i++) {\n\t\tif (command[i]==' ') {\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (memcmp(command,\"kick\",i)==0) {\n\t\t_parm(tmp, sz, i);\n\t\tint uid = strtol(command , NULL, 10);\n\t\tint id = hashid_lookup(&g->hash, uid);\n\t\tif (id>=0) {\n\t\t\tskynet_socket_close(ctx, uid);\n\t\t}\n\t\treturn;\n\t}\n\tif (memcmp(command,\"forward\",i)==0) {\n\t\t_parm(tmp, sz, i);\n\t\tchar * client = tmp;\n\t\tchar * idstr = strsep(&client, \" \");\n\t\tif (client == NULL) {\n\t\t\treturn;\n\t\t}\n\t\tint id = strtol(idstr , NULL, 10);\n\t\tchar * agent = strsep(&client, \" \");\n\t\tif (client == NULL) {\n\t\t\treturn;\n\t\t}\n\t\tuint32_t agent_handle = strtoul(agent+1, NULL, 16);\n\t\tuint32_t client_handle = strtoul(client+1, NULL, 16);\n\t\t_forward_agent(g, id, agent_handle, client_handle);\n\t\treturn;\n\t}\n\tif (memcmp(command,\"broker\",i)==0) {\n\t\t_parm(tmp, sz, i);\n\t\tg->broker = skynet_queryname(ctx, command);\n\t\treturn;\n\t}\n\tif (memcmp(command,\"start\",i) == 0) {\n\t\t_parm(tmp, sz, i);\n\t\tint uid = strtol(command , NULL, 10);\n\t\tint id = hashid_lookup(&g->hash, uid);\n\t\tif (id>=0) {\n\t\t\tskynet_socket_start(ctx, uid);\n\t\t}\n\t\treturn;\n\t}\n\tif (memcmp(command, \"close\", i) == 0) {\n\t\tif (g->listen_id >= 0) {\n\t\t\tskynet_socket_close(ctx, g->listen_id);\n\t\t\tg->listen_id = -1;\n\t\t}\n\t\treturn;\n\t}\n\tskynet_error(ctx, \"[gate] Unknown command : %s\", command);\n}\n\nstatic void\n_report(struct gate * g, const char * data, ...) {\n\tif (g->watchdog == 0) {\n\t\treturn;\n\t}\n\tstruct skynet_context * ctx = g->ctx;\n\tva_list ap;\n\tva_start(ap, data);\n\tchar tmp[1024];\n\tint n = vsnprintf(tmp, sizeof(tmp), data, ap);\n\tva_end(ap);\n\n\tskynet_send(ctx, 0, g->watchdog, PTYPE_TEXT,  0, tmp, n);\n}\n\nstatic void\n_forward(struct gate *g, struct connection * c, int size) {\n\tstruct skynet_context * ctx = g->ctx;\n\tint fd = c->id;\n\tif (fd <= 0) {\n\t\t// socket error\n\t\treturn;\n\t}\n\tif (g->broker) {\n\t\tvoid * temp = skynet_malloc(size);\n\t\tdatabuffer_read(&c->buffer,&g->mp,(char *)temp, size);\n\t\tskynet_send(ctx, 0, g->broker, g->client_tag | PTYPE_TAG_DONTCOPY, fd, temp, size);\n\t\treturn;\n\t}\n\tif (c->agent) {\n\t\tvoid * temp = skynet_malloc(size);\n\t\tdatabuffer_read(&c->buffer,&g->mp,(char *)temp, size);\n\t\tskynet_send(ctx, c->client, c->agent, g->client_tag | PTYPE_TAG_DONTCOPY, fd , temp, size);\n\t} else if (g->watchdog) {\n\t\tchar * tmp = skynet_malloc(size + 32);\n\t\tint n = snprintf(tmp,32,\"%d data \",c->id);\n\t\tdatabuffer_read(&c->buffer,&g->mp,tmp+n,size);\n\t\tskynet_send(ctx, 0, g->watchdog, PTYPE_TEXT | PTYPE_TAG_DONTCOPY, fd, tmp, size + n);\n\t}\n}\n\nstatic void\ndispatch_message(struct gate *g, struct connection *c, int id, void * data, int sz) {\n\tdatabuffer_push(&c->buffer,&g->mp, data, sz);\n\tfor (;;) {\n\t\tint size = databuffer_readheader(&c->buffer, &g->mp, g->header_size);\n\t\tif (size < 0) {\n\t\t\treturn;\n\t\t} else if (size > 0) {\n\t\t\tif (size >= 0x1000000) {\n\t\t\t\tstruct skynet_context * ctx = g->ctx;\n\t\t\t\tdatabuffer_clear(&c->buffer,&g->mp);\n\t\t\t\tskynet_socket_close(ctx, id);\n\t\t\t\tskynet_error(ctx, \"Recv socket message > 16M\");\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\t_forward(g, c, size);\n\t\t\t\tdatabuffer_reset(&c->buffer);\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic void\ndispatch_socket_message(struct gate *g, const struct skynet_socket_message * message, int sz) {\n\tstruct skynet_context * ctx = g->ctx;\n\tswitch(message->type) {\n\tcase SKYNET_SOCKET_TYPE_DATA: {\n\t\tint id = hashid_lookup(&g->hash, message->id);\n\t\tif (id>=0) {\n\t\t\tstruct connection *c = &g->conn[id];\n\t\t\tdispatch_message(g, c, message->id, message->buffer, message->ud);\n\t\t} else {\n\t\t\tskynet_error(ctx, \"Drop unknown connection %d message\", message->id);\n\t\t\tskynet_socket_close(ctx, message->id);\n\t\t\tskynet_free(message->buffer);\n\t\t}\n\t\tbreak;\n\t}\n\tcase SKYNET_SOCKET_TYPE_CONNECT: {\n\t\tif (message->id == g->listen_id) {\n\t\t\t// start listening\n\t\t\tbreak;\n\t\t}\n\t\tint id = hashid_lookup(&g->hash, message->id);\n\t\tif (id<0) {\n\t\t\tskynet_error(ctx, \"Close unknown connection %d\", message->id);\n\t\t\tskynet_socket_close(ctx, message->id);\n\t\t}\n\t\tbreak;\n\t}\n\tcase SKYNET_SOCKET_TYPE_CLOSE:\n\tcase SKYNET_SOCKET_TYPE_ERROR: {\n\t\tint id = hashid_remove(&g->hash, message->id);\n\t\tif (id>=0) {\n\t\t\tstruct connection *c = &g->conn[id];\n\t\t\tdatabuffer_clear(&c->buffer,&g->mp);\n\t\t\tmemset(c, 0, sizeof(*c));\n\t\t\tc->id = -1;\n\t\t\t_report(g, \"%d close\", message->id);\n\t\t\tskynet_socket_close(ctx, message->id);\n\t\t}\n\t\tbreak;\n\t}\n\tcase SKYNET_SOCKET_TYPE_ACCEPT:\n\t\t// report accept, then it will be get a SKYNET_SOCKET_TYPE_CONNECT message\n\t\tassert(g->listen_id == message->id);\n\t\tif (hashid_full(&g->hash)) {\n\t\t\tskynet_socket_close(ctx, message->ud);\n\t\t} else {\n\t\t\tstruct connection *c = &g->conn[hashid_insert(&g->hash, message->ud)];\n\t\t\tif (sz >= sizeof(c->remote_name)) {\n\t\t\t\tsz = sizeof(c->remote_name) - 1;\n\t\t\t}\n\t\t\tc->id = message->ud;\n\t\t\tmemcpy(c->remote_name, message+1, sz);\n\t\t\tc->remote_name[sz] = '\\0';\n\t\t\t_report(g, \"%d open %d %s:0\",c->id, c->id, c->remote_name);\n\t\t\tskynet_error(ctx, \"socket open: %x\", c->id);\n\t\t}\n\t\tbreak;\n\tcase SKYNET_SOCKET_TYPE_WARNING:\n\t\tskynet_error(ctx, \"fd (%d) send buffer (%d)K\", message->id, message->ud);\n\t\tbreak;\n\t}\n}\n\nstatic int\n_cb(struct skynet_context * ctx, void * ud, int type, int session, uint32_t source, const void * msg, size_t sz) {\n\tstruct gate *g = ud;\n\tswitch(type) {\n\tcase PTYPE_TEXT:\n\t\t_ctrl(g , msg , (int)sz);\n\t\tbreak;\n\tcase PTYPE_CLIENT: {\n\t\tif (sz <=4 ) {\n\t\t\tskynet_error(ctx, \"Invalid client message from %x\",source);\n\t\t\tbreak;\n\t\t}\n\t\t// The last 4 bytes in msg are the id of socket, write following bytes to it\n\t\tconst uint8_t * idbuf = msg + sz - 4;\n\t\tuint32_t uid = idbuf[0] | idbuf[1] << 8 | idbuf[2] << 16 | idbuf[3] << 24;\n\t\tint id = hashid_lookup(&g->hash, uid);\n\t\tif (id>=0) {\n\t\t\t// don't send id (last 4 bytes)\n\t\t\tskynet_socket_send(ctx, uid, (void*)msg, sz-4);\n\t\t\t// return 1 means don't free msg\n\t\t\treturn 1;\n\t\t} else {\n\t\t\tskynet_error(ctx, \"Invalid client id %d from %x\",(int)uid,source);\n\t\t\tbreak;\n\t\t}\n\t}\n\tcase PTYPE_SOCKET:\n\t\t// recv socket message from skynet_socket\n\t\tdispatch_socket_message(g, msg, (int)(sz-sizeof(struct skynet_socket_message)));\n\t\tbreak;\n\t}\n\treturn 0;\n}\n\nstatic int\nstart_listen(struct gate *g, char * listen_addr) {\n\tstruct skynet_context * ctx = g->ctx;\n\tchar * portstr = strrchr(listen_addr,':');\n\tconst char * host = \"\";\n\tint port;\n\tif (portstr == NULL) {\n\t\tport = strtol(listen_addr, NULL, 10);\n\t\tif (port <= 0) {\n\t\t\tskynet_error(ctx, \"Invalid gate address %s\",listen_addr);\n\t\t\treturn 1;\n\t\t}\n\t} else {\n\t\tport = strtol(portstr + 1, NULL, 10);\n\t\tif (port <= 0) {\n\t\t\tskynet_error(ctx, \"Invalid gate address %s\",listen_addr);\n\t\t\treturn 1;\n\t\t}\n\t\tportstr[0] = '\\0';\n\t\thost = listen_addr;\n\t}\n\tg->listen_id = skynet_socket_listen(ctx, host, port, BACKLOG);\n\tif (g->listen_id < 0) {\n\t\treturn 1;\n\t}\n\tskynet_socket_start(ctx, g->listen_id);\n\treturn 0;\n}\n\nint\ngate_init(struct gate *g , struct skynet_context * ctx, char * parm) {\n\tif (parm == NULL)\n\t\treturn 1;\n\tint max = 0;\n\tint sz = strlen(parm)+1;\n\tchar watchdog[sz];\n\tchar binding[sz];\n\tint client_tag = 0;\n\tchar header;\n\tint n = sscanf(parm, \"%c %s %s %d %d\", &header, watchdog, binding, &client_tag, &max);\n\tif (n<4) {\n\t\tskynet_error(ctx, \"Invalid gate parm %s\",parm);\n\t\treturn 1;\n\t}\n\tif (max <=0 ) {\n\t\tskynet_error(ctx, \"Need max connection\");\n\t\treturn 1;\n\t}\n\tif (header != 'S' && header !='L') {\n\t\tskynet_error(ctx, \"Invalid data header style\");\n\t\treturn 1;\n\t}\n\n\tif (client_tag == 0) {\n\t\tclient_tag = PTYPE_CLIENT;\n\t}\n\tif (watchdog[0] == '!') {\n\t\tg->watchdog = 0;\n\t} else {\n\t\tg->watchdog = skynet_queryname(ctx, watchdog);\n\t\tif (g->watchdog == 0) {\n\t\t\tskynet_error(ctx, \"Invalid watchdog %s\",watchdog);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tg->ctx = ctx;\n\n\thashid_init(&g->hash, max);\n\tg->conn = skynet_malloc(max * sizeof(struct connection));\n\tmemset(g->conn, 0, max *sizeof(struct connection));\n\tg->max_connection = max;\n\tint i;\n\tfor (i=0;i<max;i++) {\n\t\tg->conn[i].id = -1;\n\t}\n\t\n\tg->client_tag = client_tag;\n\tg->header_size = header=='S' ? 2 : 4;\n\n\tskynet_callback(ctx,g,_cb);\n\n\treturn start_listen(g,binding);\n}\n"
  },
  {
    "path": "service-src/service_harbor.c",
    "content": "#include \"skynet.h\"\n#include \"skynet_harbor.h\"\n#include \"skynet_socket.h\"\n#include \"skynet_handle.h\"\n\n/*\n\tharbor listen the PTYPE_HARBOR (in text)\n\tN name : update the global name\n\tS fd id: connect to new harbor , we should send self_id to fd first , and then recv a id (check it), and at last send queue.\n\tA fd id: accept new harbor , we should send self_id to fd , and then send queue.\n\n\tIf the fd is disconnected, send message to slave in PTYPE_TEXT.  D id\n\tIf we don't known a globalname, send message to slave in PTYPE_TEXT. Q name\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <assert.h>\n#include <stdint.h>\n#include <unistd.h>\n\n#define HASH_SIZE 4096\n#define DEFAULT_QUEUE_SIZE 1024\n\n// 12 is sizeof(struct remote_message_header)\n#define HEADER_COOKIE_LENGTH 12\n\n/*\n\tmessage type (8bits) is in destination high 8bits\n\tharbor id (8bits) is also in that place , but remote message doesn't need harbor id.\n */\nstruct remote_message_header {\n\tuint32_t source;\n\tuint32_t destination;\n\tuint32_t session;\n};\n\nstruct harbor_msg {\n\tstruct remote_message_header header;\n\tvoid * buffer;\n\tsize_t size;\n};\n\nstruct harbor_msg_queue {\n\tint size;\n\tint head;\n\tint tail;\n\tstruct harbor_msg * data;\n};\n\nstruct keyvalue {\n\tstruct keyvalue * next;\n\tchar key[GLOBALNAME_LENGTH];\n\tuint32_t hash;\n\tuint32_t value;\n\tstruct harbor_msg_queue * queue;\n};\n\nstruct hashmap {\n\tstruct keyvalue *node[HASH_SIZE];\n};\n\n#define STATUS_WAIT 0\n#define STATUS_HANDSHAKE 1\n#define STATUS_HEADER 2\n#define STATUS_CONTENT 3\n#define STATUS_DOWN 4\n\nstruct slave {\n\tint fd;\n\tstruct harbor_msg_queue *queue;\n\tint status;\n\tint length;\n\tint read;\n\tuint8_t size[4];\n\tchar * recv_buffer;\n};\n\nstruct harbor {\n\tstruct skynet_context *ctx;\n\tint id;\n\tuint32_t slave;\n\tstruct hashmap * map;\n\tstruct slave s[REMOTE_MAX];\n};\n\n// hash table\n\nstatic void\npush_queue_msg(struct harbor_msg_queue * queue, struct harbor_msg * m) {\n\t// If there is only 1 free slot which is reserved to distinguish full/empty\n\t// of circular buffer, expand it.\n\tif (((queue->tail + 1) % queue->size) == queue->head) {\n\t\tstruct harbor_msg * new_buffer = skynet_malloc(queue->size * 2 * sizeof(struct harbor_msg));\n\t\tint i;\n\t\tfor (i=0;i<queue->size-1;i++) {\n\t\t\tnew_buffer[i] = queue->data[(i+queue->head) % queue->size];\n\t\t}\n\t\tskynet_free(queue->data);\n\t\tqueue->data = new_buffer;\n\t\tqueue->head = 0;\n\t\tqueue->tail = queue->size - 1;\n\t\tqueue->size *= 2;\n\t}\n\tstruct harbor_msg * slot = &queue->data[queue->tail];\n\t*slot = *m;\n\tqueue->tail = (queue->tail + 1) % queue->size;\n}\n\nstatic void\npush_queue(struct harbor_msg_queue * queue, void * buffer, size_t sz, struct remote_message_header * header) {\n\tstruct harbor_msg m;\n\tm.header = *header;\n\tm.buffer = buffer;\n\tm.size = sz;\n\tpush_queue_msg(queue, &m);\n}\n\nstatic struct harbor_msg *\npop_queue(struct harbor_msg_queue * queue) {\n\tif (queue->head == queue->tail) {\n\t\treturn NULL;\n\t}\n\tstruct harbor_msg * slot = &queue->data[queue->head];\n\tqueue->head = (queue->head + 1) % queue->size;\n\treturn slot;\n}\n\nstatic struct harbor_msg_queue *\nnew_queue() {\n\tstruct harbor_msg_queue * queue = skynet_malloc(sizeof(*queue));\n\tqueue->size = DEFAULT_QUEUE_SIZE;\n\tqueue->head = 0;\n\tqueue->tail = 0;\n\tqueue->data = skynet_malloc(DEFAULT_QUEUE_SIZE * sizeof(struct harbor_msg));\n\n\treturn queue;\n}\n\nstatic void\nrelease_queue(struct harbor_msg_queue *queue) {\n\tif (queue == NULL)\n\t\treturn;\n\tstruct harbor_msg * m;\n\twhile ((m=pop_queue(queue)) != NULL) {\n\t\tskynet_free(m->buffer);\n\t}\n\tskynet_free(queue->data);\n\tskynet_free(queue);\n}\n\nstatic struct keyvalue *\nhash_search(struct hashmap * hash, const char name[GLOBALNAME_LENGTH]) {\n\tuint32_t *ptr = (uint32_t*) name;\n\tuint32_t h = ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3];\n\tstruct keyvalue * node = hash->node[h % HASH_SIZE];\n\twhile (node) {\n\t\tif (node->hash == h && strncmp(node->key, name, GLOBALNAME_LENGTH) == 0) {\n\t\t\treturn node;\n\t\t}\n\t\tnode = node->next;\n\t}\n\treturn NULL;\n}\n\n/*\n\n// Don't support erase name yet\n\nstatic struct void\nhash_erase(struct hashmap * hash, char name[GLOBALNAME_LENGTH) {\n\tuint32_t *ptr = name;\n\tuint32_t h = ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3];\n\tstruct keyvalue ** ptr = &hash->node[h % HASH_SIZE];\n\twhile (*ptr) {\n\t\tstruct keyvalue * node = *ptr;\n\t\tif (node->hash == h && strncmp(node->key, name, GLOBALNAME_LENGTH) == 0) {\n\t\t\t_release_queue(node->queue);\n\t\t\t*ptr->next = node->next;\n\t\t\tskynet_free(node);\n\t\t\treturn;\n\t\t}\n\t\t*ptr = &(node->next);\n\t}\n}\n*/\n\nstatic struct keyvalue *\nhash_insert(struct hashmap * hash, const char name[GLOBALNAME_LENGTH]) {\n\tuint32_t *ptr = (uint32_t *)name;\n\tuint32_t h = ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3];\n\tstruct keyvalue ** pkv = &hash->node[h % HASH_SIZE];\n\tstruct keyvalue * node = skynet_malloc(sizeof(*node));\n\tmemcpy(node->key, name, GLOBALNAME_LENGTH);\n\tnode->next = *pkv;\n\tnode->queue = NULL;\n\tnode->hash = h;\n\tnode->value = 0;\n\t*pkv = node;\n\n\treturn node;\n}\n\nstatic struct hashmap * \nhash_new() {\n\tstruct hashmap * h = skynet_malloc(sizeof(struct hashmap));\n\tmemset(h,0,sizeof(*h));\n\treturn h;\n}\n\nstatic void\nhash_delete(struct hashmap *hash) {\n\tint i;\n\tfor (i=0;i<HASH_SIZE;i++) {\n\t\tstruct keyvalue * node = hash->node[i];\n\t\twhile (node) {\n\t\t\tstruct keyvalue * next = node->next;\n\t\t\trelease_queue(node->queue);\n\t\t\tskynet_free(node);\n\t\t\tnode = next;\n\t\t}\n\t}\n\tskynet_free(hash);\n}\n\n///////////////\n\nstatic void\nclose_harbor(struct harbor *h, int id) {\n\tstruct slave *s = &h->s[id];\n\ts->status = STATUS_DOWN;\n\tif (s->fd) {\n\t\tskynet_socket_close(h->ctx, s->fd);\n\t\ts->fd = 0;\n\t}\n\tif (s->queue) {\n\t\trelease_queue(s->queue);\n\t\ts->queue = NULL;\n\t}\n}\n\nstatic void\nreport_harbor_down(struct harbor *h, int id) {\n\tchar down[64];\n\tint n = sprintf(down, \"D %d\",id);\n\n\tskynet_send(h->ctx, 0, h->slave, PTYPE_TEXT, 0, down, n);\n}\n\nstruct harbor *\nharbor_create(void) {\n\tstruct harbor * h = skynet_malloc(sizeof(*h));\n\tmemset(h,0,sizeof(*h));\n\th->map = hash_new();\n\treturn h;\n}\n\n\nstatic void\nclose_all_remotes(struct harbor *h) {\n\tint i;\n\tfor (i=1;i<REMOTE_MAX;i++) {\n\t\tclose_harbor(h,i);\n\t\t// don't call report_harbor_down.\n\t\t// never call skynet_send during module exit, because of dead lock\n\t}\n}\n\nvoid\nharbor_release(struct harbor *h) {\n\tclose_all_remotes(h);\n\thash_delete(h->map);\n\tskynet_free(h);\n}\n\nstatic inline void\nto_bigendian(uint8_t *buffer, uint32_t n) {\n\tbuffer[0] = (n >> 24) & 0xff;\n\tbuffer[1] = (n >> 16) & 0xff;\n\tbuffer[2] = (n >> 8) & 0xff;\n\tbuffer[3] = n & 0xff;\n}\n\nstatic inline void\nheader_to_message(const struct remote_message_header * header, uint8_t * message) {\n\tto_bigendian(message , header->source);\n\tto_bigendian(message+4 , header->destination);\n\tto_bigendian(message+8 , header->session);\n}\n\nstatic inline uint32_t\nfrom_bigendian(uint32_t n) {\n\tunion {\n\t\tuint32_t big;\n\t\tuint8_t bytes[4];\n\t} u;\n\tu.big = n;\n\treturn u.bytes[0] << 24 | u.bytes[1] << 16 | u.bytes[2] << 8 | u.bytes[3];\n}\n\nstatic inline void\nmessage_to_header(const uint32_t *message, struct remote_message_header *header) {\n\theader->source = from_bigendian(message[0]);\n\theader->destination = from_bigendian(message[1]);\n\theader->session = from_bigendian(message[2]);\n}\n\n// socket package\n\nstatic void\nforward_local_messsage(struct harbor *h, void *msg, int sz) {\n\tconst char * cookie = msg;\n\tcookie += sz - HEADER_COOKIE_LENGTH;\n\tstruct remote_message_header header;\n\tmessage_to_header((const uint32_t *)cookie, &header);\n\n\tuint32_t destination = header.destination;\n\tint type = destination >> HANDLE_REMOTE_SHIFT;\n\tdestination = (destination & HANDLE_MASK) | ((uint32_t)h->id << HANDLE_REMOTE_SHIFT);\n\n\tif (skynet_send(h->ctx, header.source, destination, type | PTYPE_TAG_DONTCOPY , (int)header.session, (void *)msg, sz-HEADER_COOKIE_LENGTH) < 0) {\n\t\tif (type != PTYPE_ERROR) {\n\t\t\t// don't need report error when type is error\n\t\t\tskynet_send(h->ctx, destination, header.source , PTYPE_ERROR, (int)header.session, NULL, 0);\n\t\t}\n\t\tskynet_error(h->ctx, \"Unknown destination :%x from :%x type(%d)\", destination, header.source, type);\n\t}\n}\n\nstatic void\nsend_remote(struct skynet_context * ctx, int fd, const char * buffer, size_t sz, struct remote_message_header * cookie) {\n\tsize_t sz_header = sz+sizeof(*cookie);\n\tif (sz_header > UINT32_MAX) {\n\t\tskynet_error(ctx, \"remote message from :%08x to :%08x is too large.\", cookie->source, cookie->destination);\n\t\treturn;\n\t}\n\tuint8_t sendbuf[sz_header+4];\n\tto_bigendian(sendbuf, (uint32_t)sz_header);\n\tmemcpy(sendbuf+4, buffer, sz);\n\theader_to_message(cookie, sendbuf+4+sz);\n\n\tstruct socket_sendbuffer tmp;\n\ttmp.id = fd;\n\ttmp.type = SOCKET_BUFFER_RAWPOINTER;\n\ttmp.buffer = sendbuf;\n\ttmp.sz = sz_header+4;\n\n\t// ignore send error, because if the connection is broken, the mainloop will recv a message.\n\tskynet_socket_sendbuffer(ctx, &tmp);\n}\n\nstatic void\ndispatch_name_queue(struct harbor *h, struct keyvalue * node) {\n\tstruct harbor_msg_queue * queue = node->queue;\n\tuint32_t handle = node->value;\n\tint harbor_id = handle >> HANDLE_REMOTE_SHIFT;\n\tstruct skynet_context * context = h->ctx;\n\tstruct slave *s = &h->s[harbor_id];\n\tint fd = s->fd;\n\tif (fd == 0) {\n\t\tif (s->status == STATUS_DOWN) {\n\t\t\tchar tmp [GLOBALNAME_LENGTH+1];\n\t\t\tmemcpy(tmp, node->key, GLOBALNAME_LENGTH);\n\t\t\ttmp[GLOBALNAME_LENGTH] = '\\0';\n\t\t\tskynet_error(context, \"Drop message to %s (in harbor %d)\",tmp,harbor_id);\n\t\t} else {\n\t\t\tif (s->queue == NULL) {\n\t\t\t\ts->queue = node->queue;\n\t\t\t\tnode->queue = NULL;\n\t\t\t} else {\n\t\t\t\tstruct harbor_msg * m;\n\t\t\t\twhile ((m = pop_queue(queue))!=NULL) {\n\t\t\t\t\tpush_queue_msg(s->queue, m);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (harbor_id == (h->slave >> HANDLE_REMOTE_SHIFT)) {\n\t\t\t\t// the harbor_id is local\n\t\t\t\tstruct harbor_msg * m;\n\t\t\t\twhile ((m = pop_queue(s->queue)) != NULL) {\n\t\t\t\t\tint type = m->header.destination >> HANDLE_REMOTE_SHIFT;\n\t\t\t\t\tskynet_send(context, m->header.source, handle , type | PTYPE_TAG_DONTCOPY, m->header.session, m->buffer, m->size);\n\t\t\t\t}\n\t\t\t\trelease_queue(s->queue);\n\t\t\t\ts->queue = NULL;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\tstruct harbor_msg * m;\n\twhile ((m = pop_queue(queue)) != NULL) {\n\t\tm->header.destination |= (handle & HANDLE_MASK);\n\t\tsend_remote(context, fd, m->buffer, m->size, &m->header);\n\t\tskynet_free(m->buffer);\n\t}\n}\n\nstatic void\ndispatch_queue(struct harbor *h, int id) {\n\tstruct slave *s = &h->s[id];\n\tint fd = s->fd;\n\tassert(fd != 0);\n\n\tstruct harbor_msg_queue *queue = s->queue;\n\tif (queue == NULL)\n\t\treturn;\n\n\tstruct harbor_msg * m;\n\twhile ((m = pop_queue(queue)) != NULL) {\n\t\tsend_remote(h->ctx, fd, m->buffer, m->size, &m->header);\n\t\tskynet_free(m->buffer);\n\t}\n\trelease_queue(queue);\n\ts->queue = NULL;\n}\n\nstatic void\npush_socket_data(struct harbor *h, const struct skynet_socket_message * message) {\n\tassert(message->type == SKYNET_SOCKET_TYPE_DATA);\n\tint fd = message->id;\n\tint i;\n\tint id = 0;\n\tstruct slave * s = NULL;\n\tfor (i=1;i<REMOTE_MAX;i++) {\n\t\tif (h->s[i].fd == fd) {\n\t\t\ts = &h->s[i];\n\t\t\tid = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (s == NULL) {\n\t\tskynet_error(h->ctx, \"Invalid socket fd (%d) data\", fd);\n\t\treturn;\n\t}\n\tuint8_t * buffer = (uint8_t *)message->buffer;\n\tint size = message->ud;\n\n\tfor (;;) {\n\t\tswitch(s->status) {\n\t\tcase STATUS_HANDSHAKE: {\n\t\t\t// check id\n\t\t\tuint8_t remote_id = buffer[0];\n\t\t\tif (remote_id != id) {\n\t\t\t\tskynet_error(h->ctx, \"Invalid shakehand id (%d) from fd = %d , harbor = %d\", id, fd, remote_id);\n\t\t\t\tclose_harbor(h,id);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t++buffer;\n\t\t\t--size;\n\t\t\ts->status = STATUS_HEADER;\n\n\t\t\tdispatch_queue(h, id);\n\n\t\t\tif (size == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// go though\n\t\t}\n\t\tcase STATUS_HEADER: {\n\t\t\t// big endian 4 bytes length, the first one must be 0.\n\t\t\tint need = 4 - s->read;\n\t\t\tif (size < need) {\n\t\t\t\tmemcpy(s->size + s->read, buffer, size);\n\t\t\t\ts->read += size;\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tmemcpy(s->size + s->read, buffer, need);\n\t\t\t\tbuffer += need;\n\t\t\t\tsize -= need;\n\n\t\t\t\tif (s->size[0] != 0) {\n\t\t\t\t\tskynet_error(h->ctx, \"Message is too long from harbor %d\", id);\n\t\t\t\t\tclose_harbor(h,id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ts->length = s->size[1] << 16 | s->size[2] << 8 | s->size[3];\n\t\t\t\ts->read = 0;\n\t\t\t\ts->recv_buffer = skynet_malloc(s->length);\n\t\t\t\ts->status = STATUS_CONTENT;\n\t\t\t\tif (size == 0) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// go though\n\t\tcase STATUS_CONTENT: {\n\t\t\tint need = s->length - s->read;\n\t\t\tif (size < need) {\n\t\t\t\tmemcpy(s->recv_buffer + s->read, buffer, size);\n\t\t\t\ts->read += size;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tmemcpy(s->recv_buffer + s->read, buffer, need);\n\t\t\tforward_local_messsage(h, s->recv_buffer, s->length);\n\t\t\ts->length = 0;\n\t\t\ts->read = 0;\n\t\t\ts->recv_buffer = NULL;\n\t\t\tsize -= need;\n\t\t\tbuffer += need;\n\t\t\ts->status = STATUS_HEADER;\n\t\t\tif (size == 0)\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nstatic void\nupdate_name(struct harbor *h, const char name[GLOBALNAME_LENGTH], uint32_t handle) {\n\tstruct keyvalue * node = hash_search(h->map, name);\n\tif (node == NULL) {\n\t\tnode = hash_insert(h->map, name);\n\t}\n\tnode->value = handle;\n\tif (node->queue) {\n\t\tdispatch_name_queue(h, node);\n\t\trelease_queue(node->queue);\n\t\tnode->queue = NULL;\n\t}\n}\n\nstatic int\nremote_send_handle(struct harbor *h, uint32_t source, uint32_t destination, int type, int session, const char * msg, size_t sz) {\n\tint harbor_id = destination >> HANDLE_REMOTE_SHIFT;\n\tstruct skynet_context * context = h->ctx;\n\tif (harbor_id == h->id) {\n\t\t// local message\n\t\tskynet_send(context, source, destination , type | PTYPE_TAG_DONTCOPY, session, (void *)msg, sz);\n\t\treturn 1;\n\t}\n\n\tstruct slave * s = &h->s[harbor_id];\n\tif (s->fd == 0 || s->status == STATUS_HANDSHAKE) {\n\t\tif (s->status == STATUS_DOWN) {\n\t\t\t// throw an error return to source\n\t\t\t// report the destination is dead\n\t\t\tskynet_send(context, destination, source, PTYPE_ERROR, session, NULL, 0);\n\t\t\tskynet_error(context, \"Drop message to harbor %d from %x to %x (session = %d, msgsz = %d)\",harbor_id, source, destination,session,(int)sz);\n\t\t} else {\n\t\t\tif (s->queue == NULL) {\n\t\t\t\ts->queue = new_queue();\n\t\t\t}\n\t\t\tstruct remote_message_header header;\n\t\t\theader.source = source;\n\t\t\theader.destination = (type << HANDLE_REMOTE_SHIFT) | (destination & HANDLE_MASK);\n\t\t\theader.session = (uint32_t)session;\n\t\t\tpush_queue(s->queue, (void *)msg, sz, &header);\n\t\t\treturn 1;\n\t\t}\n\t} else {\n\t\tstruct remote_message_header cookie;\n\t\tcookie.source = source;\n\t\tcookie.destination = (destination & HANDLE_MASK) | ((uint32_t)type << HANDLE_REMOTE_SHIFT);\n\t\tcookie.session = (uint32_t)session;\n\t\tsend_remote(context, s->fd, msg,sz,&cookie);\n\t}\n\n\treturn 0;\n}\n\nstatic int\nremote_send_name(struct harbor *h, uint32_t source, const char name[GLOBALNAME_LENGTH], int type, int session, const char * msg, size_t sz) {\n\tstruct keyvalue * node = hash_search(h->map, name);\n\tif (node == NULL) {\n\t\tnode = hash_insert(h->map, name);\n\t}\n\tif (node->value == 0) {\n\t\tif (node->queue == NULL) {\n\t\t\tnode->queue = new_queue();\n\t\t}\n\t\tstruct remote_message_header header;\n\t\theader.source = source;\n\t\theader.destination = type << HANDLE_REMOTE_SHIFT;\n\t\theader.session = (uint32_t)session;\n\t\tpush_queue(node->queue, (void *)msg, sz, &header);\n\t\tchar query[2+GLOBALNAME_LENGTH+1] = \"Q \";\n\t\tquery[2+GLOBALNAME_LENGTH] = 0;\n\t\tmemcpy(query+2, name, GLOBALNAME_LENGTH);\n\t\tskynet_send(h->ctx, 0, h->slave, PTYPE_TEXT, 0, query, strlen(query));\n\t\treturn 1;\n\t} else {\n\t\treturn remote_send_handle(h, source, node->value, type, session, msg, sz);\n\t}\n}\n\nstatic void\nhandshake(struct harbor *h, int id) {\n\tstruct slave *s = &h->s[id];\n\tuint8_t handshake[1] = { (uint8_t)h->id };\n\tstruct socket_sendbuffer tmp;\n\ttmp.id = s->fd;\n\ttmp.type = SOCKET_BUFFER_RAWPOINTER;\n\ttmp.buffer = handshake;\n\ttmp.sz = 1;\n\tskynet_socket_sendbuffer(h->ctx, &tmp);\n}\n\nstatic void\nharbor_command(struct harbor * h, const char * msg, size_t sz, int session, uint32_t source) {\n\tconst char * name = msg + 2;\n\tint s = (int)sz;\n\ts -= 2;\n\tswitch(msg[0]) {\n\tcase 'N' : {\n\t\tif (s <=0 || s>= GLOBALNAME_LENGTH) {\n\t\t\tskynet_error(h->ctx, \"Invalid global name %s\", name);\n\t\t\treturn;\n\t\t}\n\t\tstruct remote_name rn;\n\t\tmemset(&rn, 0, sizeof(rn));\n\t\tmemcpy(rn.name, name, s);\n\t\trn.handle = source;\n\t\tupdate_name(h, rn.name, rn.handle);\n\t\tbreak;\n\t}\n\tcase 'S' :\n\tcase 'A' : {\n\t\tchar buffer[s+1];\n\t\tmemcpy(buffer, name, s);\n\t\tbuffer[s] = 0;\n\t\tint fd=0, id=0;\n\t\tsscanf(buffer, \"%d %d\",&fd,&id);\n\t\tif (fd == 0 || id <= 0 || id>=REMOTE_MAX) {\n\t\t\tskynet_error(h->ctx, \"Invalid command %c %s\", msg[0], buffer);\n\t\t\treturn;\n\t\t}\n\t\tstruct slave * slave = &h->s[id];\n\t\tif (slave->fd != 0) {\n\t\t\tskynet_error(h->ctx, \"Harbor %d alreay exist\", id);\n\t\t\treturn;\n\t\t}\n\t\tslave->fd = fd;\n\n\t\tskynet_socket_start(h->ctx, fd);\n\t\thandshake(h, id);\n\t\tif (msg[0] == 'S') {\n\t\t\tslave->status = STATUS_HANDSHAKE;\n\t\t} else {\n\t\t\tslave->status = STATUS_HEADER;\n\t\t\tdispatch_queue(h,id);\n\t\t}\n\t\tbreak;\n\t}\n\tdefault:\n\t\tskynet_error(h->ctx, \"Unknown command %s\", msg);\n\t\treturn;\n\t}\n}\n\nstatic int\nharbor_id(struct harbor *h, int fd) {\n\tint i;\n\tfor (i=1;i<REMOTE_MAX;i++) {\n\t\tstruct slave *s = &h->s[i];\n\t\tif (s->fd == fd) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn 0;\n}\n\nstatic int\nmainloop(struct skynet_context * context, void * ud, int type, int session, uint32_t source, const void * msg, size_t sz) {\n\tstruct harbor * h = ud;\n\tswitch (type) {\n\tcase PTYPE_SOCKET: {\n\t\tconst struct skynet_socket_message * message = msg;\n\t\tswitch(message->type) {\n\t\tcase SKYNET_SOCKET_TYPE_DATA:\n\t\t\tpush_socket_data(h, message);\n\t\t\tskynet_free(message->buffer);\n\t\t\tbreak;\n\t\tcase SKYNET_SOCKET_TYPE_ERROR:\n\t\tcase SKYNET_SOCKET_TYPE_CLOSE: {\n\t\t\tint id = harbor_id(h, message->id);\n\t\t\tif (id) {\n\t\t\t\treport_harbor_down(h,id);\n\t\t\t} else {\n\t\t\t\tskynet_error(context, \"Unknown fd (%d) closed\", message->id);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase SKYNET_SOCKET_TYPE_CONNECT:\n\t\t\t// fd forward to this service\n\t\t\tbreak;\n\t\tcase SKYNET_SOCKET_TYPE_WARNING: {\n\t\t\tint id = harbor_id(h, message->id);\n\t\t\tif (id) {\n\t\t\t\tskynet_error(context, \"message havn't send to Harbor (%d) reach %d K\", id, message->ud);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tskynet_error(context, \"recv invalid socket message type %d\", type);\n\t\t\tbreak;\n\t\t}\n\t\treturn 0;\n\t}\n\tcase PTYPE_HARBOR: {\n\t\tharbor_command(h, msg,sz,session,source);\n\t\treturn 0;\n\t}\n\tcase PTYPE_SYSTEM : {\n\t\t// remote message out\n\t\tconst struct remote_message *rmsg = msg;\n\t\tif (rmsg->destination.handle == 0) {\n\t\t\tif (remote_send_name(h, source , rmsg->destination.name, rmsg->type, session, rmsg->message, rmsg->sz)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t} else {\n\t\t\tif (remote_send_handle(h, source , rmsg->destination.handle, rmsg->type, session, rmsg->message, rmsg->sz)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tskynet_free((void *)rmsg->message);\n\t\treturn 0;\n\t}\n\tdefault:\n\t\tskynet_error(context, \"recv invalid message from %x,  type = %d\", source, type);\n\t\tif (session != 0 && type != PTYPE_ERROR) {\n\t\t\tskynet_send(context,0,source,PTYPE_ERROR, session, NULL, 0);\n\t\t}\n\t\treturn 0;\n\t}\n}\n\nint\nharbor_init(struct harbor *h, struct skynet_context *ctx, const char * args) {\n\th->ctx = ctx;\n\tint harbor_id = 0;\n\tuint32_t slave = 0;\n\tsscanf(args,\"%d %u\", &harbor_id, &slave);\n\tif (slave == 0) {\n\t\treturn 1;\n\t}\n\th->id = harbor_id;\n\th->slave = slave;\n\tif (harbor_id == 0) {\n\t\tclose_all_remotes(h);\n\t}\n\tskynet_callback(ctx, h, mainloop);\n\tskynet_harbor_start(ctx);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "service-src/service_logger.c",
    "content": "#include \"skynet.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <time.h>\n\nstruct logger {\n\tFILE * handle;\n\tchar * filename;\n\tuint32_t starttime;\n\tint close;\n};\n\nstruct logger *\nlogger_create(void) {\n\tstruct logger * inst = skynet_malloc(sizeof(*inst));\n\tinst->handle = NULL;\n\tinst->close = 0;\n\tinst->filename = NULL;\n\n\treturn inst;\n}\n\nvoid\nlogger_release(struct logger * inst) {\n\tif (inst->close) {\n\t\tfclose(inst->handle);\n\t}\n\tskynet_free(inst->filename);\n\tskynet_free(inst);\n}\n\n#define SIZETIMEFMT\t250\n\nstatic int\ntimestring(struct logger *inst, char tmp[SIZETIMEFMT]) {\n\tuint64_t now = skynet_now();\n\ttime_t ti = now/100 + inst->starttime;\n\tstruct tm info;\n\t(void)localtime_r(&ti,&info);\n\tstrftime(tmp, SIZETIMEFMT, \"%d/%m/%y %H:%M:%S\", &info);\n\treturn now % 100;\n}\n\nstatic int\nlogger_cb(struct skynet_context * context, void *ud, int type, int session, uint32_t source, const void * msg, size_t sz) {\n\tstruct logger * inst = ud;\n\tswitch (type) {\n\tcase PTYPE_SYSTEM:\n\t\tif (inst->filename) {\n\t\t\tinst->handle = freopen(inst->filename, \"a\", inst->handle);\n\t\t}\n\t\tbreak;\n\tcase PTYPE_TEXT:\n\t\tif (inst->filename) {\n\t\t\tchar tmp[SIZETIMEFMT];\n\t\t\tint csec = timestring(ud, tmp);\n\t\t\tfprintf(inst->handle, \"%s.%02d \", tmp, csec);\n\t\t}\n\t\tfprintf(inst->handle, \"[:%08x] \", source);\n\t\tfwrite(msg, sz , 1, inst->handle);\n\t\tfprintf(inst->handle, \"\\n\");\n\t\tfflush(inst->handle);\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\nint\nlogger_init(struct logger * inst, struct skynet_context *ctx, const char * parm) {\n\tconst char * r = skynet_command(ctx, \"STARTTIME\", NULL);\n\tinst->starttime = strtoul(r, NULL, 10);\n\tif (parm) {\n\t\tinst->handle = fopen(parm,\"a\");\n\t\tif (inst->handle == NULL) {\n\t\t\treturn 1;\n\t\t}\n\t\tinst->filename = skynet_malloc(strlen(parm)+1);\n\t\tstrcpy(inst->filename, parm);\n\t\tinst->close = 1;\n\t} else {\n\t\tinst->handle = stdout;\n\t}\n\tif (inst->handle) {\n\t\tskynet_callback(ctx, inst, logger_cb);\n\t\treturn 0;\n\t}\n\treturn 1;\n}\n"
  },
  {
    "path": "service-src/service_snlua.c",
    "content": "#include \"skynet.h\"\n#include \"atomic.h\"\n\n#include <lua.h>\n#include <lualib.h>\n#include <lauxlib.h>\n\n#include <assert.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n\n#if defined(__APPLE__)\n#include <mach/task.h>\n#include <mach/mach.h>\n#endif\n\n#define NANOSEC 1000000000\n#define MICROSEC 1000000\n\n// #define DEBUG_LOG\n\n#define MEMORY_WARNING_REPORT (1024 * 1024 * 32)\n\nstruct snlua {\n\tlua_State * L;\n\tstruct skynet_context * ctx;\n\tsize_t mem;\n\tsize_t mem_report;\n\tsize_t mem_limit;\n\tlua_State * activeL;\n\tATOM_INT trap;\n};\n\n// LUA_CACHELIB may defined in patched lua for shared proto\n#ifdef LUA_CACHELIB\n\n#define codecache luaopen_cache\n\n#else\n\nstatic int\ncleardummy(lua_State *L) {\n  return 0;\n}\n\nstatic int \ncodecache(lua_State *L) {\n\tluaL_Reg l[] = {\n\t\t{ \"clear\", cleardummy },\n\t\t{ \"mode\", cleardummy },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_newlib(L,l);\n\tlua_getglobal(L, \"loadfile\");\n\tlua_setfield(L, -2, \"loadfile\");\n\treturn 1;\n}\n\n#endif\n\nstatic void\nsignal_hook(lua_State *L, lua_Debug *ar) {\n\tvoid *ud = NULL;\n\tlua_getallocf(L, &ud);\n\tstruct snlua *l = (struct snlua *)ud;\n\n\tlua_sethook (L, NULL, 0, 0);\n\tif (ATOM_LOAD(&l->trap)) {\n\t\tATOM_STORE(&l->trap , 0);\n\t\tluaL_error(L, \"signal 0\");\n\t}\n}\n\nstatic void\nswitchL(lua_State *L, struct snlua *l) {\n\tl->activeL = L;\n\tif (ATOM_LOAD(&l->trap)) {\n\t\tlua_sethook(L, signal_hook, LUA_MASKCOUNT, 1);\n\t}\n}\n\nstatic int\nlua_resumeX(lua_State *L, lua_State *from, int nargs, int *nresults) {\n\tvoid *ud = NULL;\n\tlua_getallocf(L, &ud);\n\tstruct snlua *l = (struct snlua *)ud;\n\tswitchL(L, l);\n\tint err = lua_resume(L, from, nargs, nresults);\n\tif (ATOM_LOAD(&l->trap)) {\n\t\t// wait for lua_sethook. (l->trap == -1)\n\t\twhile (ATOM_LOAD(&l->trap) >= 0) ;\n\t}\n\tswitchL(from, l);\n\treturn err;\n}\n\nstatic double\nget_time() {\n#if  !defined(__APPLE__)\n\tstruct timespec ti;\n\tclock_gettime(CLOCK_THREAD_CPUTIME_ID, &ti);\n\n\tint sec = ti.tv_sec & 0xffff;\n\tint nsec = ti.tv_nsec;\n\n\treturn (double)sec + (double)nsec / NANOSEC;\n#else\n\tstruct task_thread_times_info aTaskInfo;\n\tmach_msg_type_number_t aTaskInfoCount = TASK_THREAD_TIMES_INFO_COUNT;\n\tif (KERN_SUCCESS != task_info(mach_task_self(), TASK_THREAD_TIMES_INFO, (task_info_t )&aTaskInfo, &aTaskInfoCount)) {\n\t\treturn 0;\n\t}\n\n\tint sec = aTaskInfo.user_time.seconds & 0xffff;\n\tint msec = aTaskInfo.user_time.microseconds;\n\n\treturn (double)sec + (double)msec / MICROSEC;\n#endif\n}\n\nstatic inline double\ndiff_time(double start) {\n\tdouble now = get_time();\n\tif (now < start) {\n\t\treturn now + 0x10000 - start;\n\t} else {\n\t\treturn now - start;\n\t}\n}\n\n// coroutine lib, add profile\n\n/*\n** Resumes a coroutine. Returns the number of results for non-error\n** cases or -1 for errors.\n*/\nstatic int auxresume (lua_State *L, lua_State *co, int narg) {\n  int status, nres;\n  if (!lua_checkstack(co, narg)) {\n    lua_pushliteral(L, \"too many arguments to resume\");\n    return -1;  /* error flag */\n  }\n  lua_xmove(L, co, narg);\n  status = lua_resumeX(co, L, narg, &nres);\n  if (status == LUA_OK || status == LUA_YIELD) {\n    if (!lua_checkstack(L, nres + 1)) {\n      lua_pop(co, nres);  /* remove results anyway */\n      lua_pushliteral(L, \"too many results to resume\");\n      return -1;  /* error flag */\n    }\n    lua_xmove(co, L, nres);  /* move yielded values */\n    return nres;\n  }\n  else {\n    lua_xmove(co, L, 1);  /* move error message */\n    return -1;  /* error flag */\n  }\n}\n\nstatic int\ntiming_enable(lua_State *L, int co_index, lua_Number *start_time) {\n\tlua_pushvalue(L, co_index);\n\tlua_rawget(L, lua_upvalueindex(1));\n\tif (lua_isnil(L, -1)) {\t\t// check start time\n\t\tlua_pop(L, 1);\n\t\treturn 0;\n\t}\n\t*start_time = lua_tonumber(L, -1);\n\tlua_pop(L,1);\n\treturn 1;\n}\n\nstatic double\ntiming_total(lua_State *L, int co_index) {\n\tlua_pushvalue(L, co_index);\n\tlua_rawget(L, lua_upvalueindex(2));\n\tdouble total_time = lua_tonumber(L, -1);\n\tlua_pop(L,1);\n\treturn total_time;\n}\n\nstatic int\ntiming_resume(lua_State *L, int co_index, int n) {\n\tlua_State *co = lua_tothread(L, co_index);\n\tlua_Number start_time = 0;\n\tif (timing_enable(L, co_index, &start_time)) {\n\t\tstart_time = get_time();\n#ifdef DEBUG_LOG\n\t\tdouble ti = diff_time(start_time);\n\t\tfprintf(stderr, \"PROFILE [%p] resume %lf\\n\", co, ti);\n#endif\n\t\tlua_pushvalue(L, co_index);\n\t\tlua_pushnumber(L, start_time);\n\t\tlua_rawset(L, lua_upvalueindex(1));\t// set start time\n\t}\n\n\tint r = auxresume(L, co, n);\n\n\tif (timing_enable(L, co_index, &start_time)) {\n\t\tdouble total_time = timing_total(L, co_index);\n\t\tdouble diff = diff_time(start_time);\n\t\ttotal_time += diff;\n#ifdef DEBUG_LOG\n\t\tfprintf(stderr, \"PROFILE [%p] yield (%lf/%lf)\\n\", co, diff, total_time);\n#endif\n\t\tlua_pushvalue(L, co_index);\n\t\tlua_pushnumber(L, total_time);\n\t\tlua_rawset(L, lua_upvalueindex(2));\n\t}\n\n\treturn r;\n}\n\nstatic int luaB_coresume (lua_State *L) {\n  luaL_checktype(L, 1, LUA_TTHREAD);\n  int r = timing_resume(L, 1, lua_gettop(L) - 1);\n  if (r < 0) {\n    lua_pushboolean(L, 0);\n    lua_insert(L, -2);\n    return 2;  /* return false + error message */\n  }\n  else {\n    lua_pushboolean(L, 1);\n    lua_insert(L, -(r + 1));\n    return r + 1;  /* return true + 'resume' returns */\n  }\n}\n\nstatic int luaB_auxwrap (lua_State *L) {\n  lua_State *co = lua_tothread(L, lua_upvalueindex(3));\n  int r = timing_resume(L, lua_upvalueindex(3), lua_gettop(L));\n  if (r < 0) {\n    int stat = lua_status(co);\n    if (stat != LUA_OK && stat != LUA_YIELD)\n      lua_closethread(co, L);  /* close variables in case of errors */\n    if (lua_type(L, -1) == LUA_TSTRING) {  /* error object is a string? */\n      luaL_where(L, 1);  /* add extra info, if available */\n      lua_insert(L, -2);\n      lua_concat(L, 2);\n    }\n    return lua_error(L);  /* propagate error */\n  }\n  return r;\n}\n\nstatic int luaB_cocreate (lua_State *L) {\n  lua_State *NL;\n  luaL_checktype(L, 1, LUA_TFUNCTION);\n  NL = lua_newthread(L);\n  lua_pushvalue(L, 1);  /* move function to top */\n  lua_xmove(L, NL, 1);  /* move function from L to NL */\n  return 1;\n}\n\nstatic int luaB_cowrap (lua_State *L) {\n  lua_pushvalue(L, lua_upvalueindex(1));\n  lua_pushvalue(L, lua_upvalueindex(2));\n  luaB_cocreate(L);\n  lua_pushcclosure(L, luaB_auxwrap, 3);\n  return 1;\n}\n\n// profile lib\n\nstatic int\nlstart(lua_State *L) {\n\tif (lua_gettop(L) != 0) {\n\t\tlua_settop(L,1);\n\t\tluaL_checktype(L, 1, LUA_TTHREAD);\n\t} else {\n\t\tlua_pushthread(L);\n\t}\n\tlua_Number start_time = 0;\n\tif (timing_enable(L, 1, &start_time)) {\n\t\treturn luaL_error(L, \"Thread %p start profile more than once\", lua_topointer(L, 1));\n\t}\n\n\t// reset total time\n\tlua_pushvalue(L, 1);\n\tlua_pushnumber(L, 0);\n\tlua_rawset(L, lua_upvalueindex(2));\n\n\t// set start time\n\tlua_pushvalue(L, 1);\n\tstart_time = get_time();\n#ifdef DEBUG_LOG\n\tfprintf(stderr, \"PROFILE [%p] start\\n\", L);\n#endif\n\tlua_pushnumber(L, start_time);\n\tlua_rawset(L, lua_upvalueindex(1));\n\n\treturn 0;\n}\n\nstatic int\nlstop(lua_State *L) {\n\tif (lua_gettop(L) != 0) {\n\t\tlua_settop(L,1);\n\t\tluaL_checktype(L, 1, LUA_TTHREAD);\n\t} else {\n\t\tlua_pushthread(L);\n\t}\n\tlua_Number start_time = 0;\n\tif (!timing_enable(L, 1, &start_time)) {\n\t\treturn luaL_error(L, \"Call profile.start() before profile.stop()\");\n\t}\n\tdouble ti = diff_time(start_time);\n\tdouble total_time = timing_total(L,1);\n\n\tlua_pushvalue(L, 1);\t// push coroutine\n\tlua_pushnil(L);\n\tlua_rawset(L, lua_upvalueindex(1));\n\n\tlua_pushvalue(L, 1);\t// push coroutine\n\tlua_pushnil(L);\n\tlua_rawset(L, lua_upvalueindex(2));\n\n\ttotal_time += ti;\n\tlua_pushnumber(L, total_time);\n#ifdef DEBUG_LOG\n\tfprintf(stderr, \"PROFILE [%p] stop (%lf/%lf)\\n\", lua_tothread(L,1), ti, total_time);\n#endif\n\n\treturn 1;\n}\n\nstatic int\ninit_profile(lua_State *L) {\n\tluaL_Reg l[] = {\n\t\t{ \"start\", lstart },\n\t\t{ \"stop\", lstop },\n\t\t{ \"resume\", luaB_coresume },\n\t\t{ \"wrap\", luaB_cowrap },\n\t\t{ NULL, NULL },\n\t};\n\tluaL_newlibtable(L,l);\n\tlua_newtable(L);\t// table thread->start time\n\tlua_newtable(L);\t// table thread->total time\n\n\tlua_newtable(L);\t// weak table\n\tlua_pushliteral(L, \"kv\");\n\tlua_setfield(L, -2, \"__mode\");\n\n\tlua_pushvalue(L, -1);\n\tlua_setmetatable(L, -3);\n\tlua_setmetatable(L, -3);\n\n\tluaL_setfuncs(L,l,2);\n\n\treturn 1;\n}\n\n/// end of coroutine\n\nstatic int \ntraceback (lua_State *L) {\n\tconst char *msg = lua_tostring(L, 1);\n\tif (msg)\n\t\tluaL_traceback(L, L, msg, 1);\n\telse {\n\t\tlua_pushliteral(L, \"(no error message)\");\n\t}\n\treturn 1;\n}\n\nstatic void\nreport_launcher_error(struct skynet_context *ctx) {\n\t// sizeof \"ERROR\" == 5\n\tskynet_sendname(ctx, 0, \".launcher\", PTYPE_TEXT, 0, \"ERROR\", 5);\n}\n\nstatic const char *\noptstring(struct skynet_context *ctx, const char *key, const char * str) {\n\tconst char * ret = skynet_command(ctx, \"GETENV\", key);\n\tif (ret == NULL) {\n\t\treturn str;\n\t}\n\treturn ret;\n}\n\nstatic int\ninit_cb(struct snlua *l, struct skynet_context *ctx, const char * args, size_t sz) {\n\tlua_State *L = l->L;\n\tl->ctx = ctx;\n\tlua_gc(L, LUA_GCSTOP, 0);\n\tlua_pushboolean(L, 1);  /* signal for libraries to ignore env. vars. */\n\tlua_setfield(L, LUA_REGISTRYINDEX, \"LUA_NOENV\");\n\tluaL_openlibs(L);\n\tluaL_requiref(L, \"skynet.profile\", init_profile, 0);\n\n\tint profile_lib = lua_gettop(L);\n\t// replace coroutine.resume / coroutine.wrap\n\tlua_getglobal(L, \"coroutine\");\n\tlua_getfield(L, profile_lib, \"resume\");\n\tlua_setfield(L, -2, \"resume\");\n\tlua_getfield(L, profile_lib, \"wrap\");\n\tlua_setfield(L, -2, \"wrap\");\n\n\tlua_settop(L, profile_lib-1);\n\n\tlua_pushlightuserdata(L, ctx);\n\tlua_setfield(L, LUA_REGISTRYINDEX, \"skynet_context\");\n\tluaL_requiref(L, \"skynet.codecache\", codecache , 0);\n\tlua_pop(L,1);\n\n\tlua_gc(L, LUA_GCGEN, 0, 0);\n\n\tconst char *path = optstring(ctx, \"lua_path\",\"./lualib/?.lua;./lualib/?/init.lua\");\n\tlua_pushstring(L, path);\n\tlua_setglobal(L, \"LUA_PATH\");\n\tconst char *cpath = optstring(ctx, \"lua_cpath\",\"./luaclib/?.so\");\n\tlua_pushstring(L, cpath);\n\tlua_setglobal(L, \"LUA_CPATH\");\n\tconst char *service = optstring(ctx, \"luaservice\", \"./service/?.lua\");\n\tlua_pushstring(L, service);\n\tlua_setglobal(L, \"LUA_SERVICE\");\n\tconst char *preload = skynet_command(ctx, \"GETENV\", \"preload\");\n\tlua_pushstring(L, preload);\n\tlua_setglobal(L, \"LUA_PRELOAD\");\n\n\tlua_pushcfunction(L, traceback);\n\tassert(lua_gettop(L) == 1);\n\n\tconst char * loader = optstring(ctx, \"lualoader\", \"./lualib/loader.lua\");\n\n\tint r = luaL_loadfile(L,loader);\n\tif (r != LUA_OK) {\n\t\tskynet_error(ctx, \"Can't load %s : %s\", loader, lua_tostring(L, -1));\n\t\treport_launcher_error(ctx);\n\t\treturn 1;\n\t}\n\tlua_pushlstring(L, args, sz);\n\tr = lua_pcall(L,1,0,1);\n\tif (r != LUA_OK) {\n\t\tskynet_error(ctx, \"lua loader error : %s\", lua_tostring(L, -1));\n\t\treport_launcher_error(ctx);\n\t\treturn 1;\n\t}\n\tlua_settop(L,0);\n\tif (lua_getfield(L, LUA_REGISTRYINDEX, \"memlimit\") == LUA_TNUMBER) {\n\t\tsize_t limit = lua_tointeger(L, -1);\n\t\tl->mem_limit = limit;\n\t\tskynet_error(ctx, \"Set memory limit to %.2f M\", (float)limit / (1024 * 1024));\n\t\tlua_pushnil(L);\n\t\tlua_setfield(L, LUA_REGISTRYINDEX, \"memlimit\");\n\t}\n\tlua_pop(L, 1);\n\n\tlua_gc(L, LUA_GCRESTART, 0);\n\n\treturn 0;\n}\n\nstatic int\nlaunch_cb(struct skynet_context * context, void *ud, int type, int session, uint32_t source , const void * msg, size_t sz) {\n\tassert(type == 0 && session == 0);\n\tstruct snlua *l = ud;\n\tskynet_callback(context, NULL, NULL);\n\tint err = init_cb(l, context, msg, sz);\n\tif (err) {\n\t\tskynet_command(context, \"EXIT\", NULL);\n\t}\n\n\treturn 0;\n}\n\nint\nsnlua_init(struct snlua *l, struct skynet_context *ctx, const char * args) {\n\tint sz = strlen(args);\n\tchar * tmp = skynet_malloc(sz);\n\tmemcpy(tmp, args, sz);\n\tskynet_callback(ctx, l , launch_cb);\n\tconst char * self = skynet_command(ctx, \"REG\", NULL);\n\tuint32_t handle_id = strtoul(self+1, NULL, 16);\n\t// it must be first message\n\tskynet_send(ctx, 0, handle_id, PTYPE_TAG_DONTCOPY,0, tmp, sz);\n\treturn 0;\n}\n\nstatic void *\nlalloc(void * ud, void *ptr, size_t osize, size_t nsize) {\n\tstruct snlua *l = ud;\n\tsize_t mem = l->mem;\n\tl->mem += nsize;\n\tif (ptr)\n\t\tl->mem -= osize;\n\tif (l->mem_limit != 0 && l->mem > l->mem_limit) {\n\t\tif (ptr == NULL || nsize > osize) {\n\t\t\tl->mem = mem;\n\t\t\treturn NULL;\n\t\t}\n\t}\n\tif (l->mem > l->mem_report) {\n\t\tl->mem_report *= 2;\n\t\tskynet_error(l->ctx, \"Memory warning %.2f M\", (float)l->mem / (1024 * 1024));\n\t}\n\treturn skynet_lalloc(ptr, osize, nsize);\n}\n\nstatic unsigned\nglobal_seed() {\n\tstatic ATOM_INT seed = 0;\n\tunsigned ret = ATOM_LOAD(&seed);\n\twhile (ret == 0) {\n\t\tunsigned t = luaL_makeseed(NULL);\n\t\tif (t == 0)\n\t\t\tt = 1;\n\t\tATOM_CAS(&seed, 0, t);\n\t\tret = ATOM_LOAD(&seed);\n\t}\n\treturn ret;\n}\n\nstruct snlua *\nsnlua_create(void) {\n\tstruct snlua * l = skynet_malloc(sizeof(*l));\n\tmemset(l,0,sizeof(*l));\n\tl->mem_report = MEMORY_WARNING_REPORT;\n\tl->mem_limit = 0;\n\tl->L = lua_newstate(lalloc, l, global_seed());\n\tl->activeL = NULL;\n\tATOM_INIT(&l->trap , 0);\n\treturn l;\n}\n\nvoid\nsnlua_release(struct snlua *l) {\n\tlua_close(l->L);\n\tskynet_free(l);\n}\n\nvoid\nsnlua_signal(struct snlua *l, int signal) {\n\tskynet_error(l->ctx, \"recv a signal %d\", signal);\n\tif (signal == 0) {\n\t\tif (ATOM_LOAD(&l->trap) == 0) {\n\t\t\t// only one thread can set trap ( l->trap 0->1 )\n\t\t\tif (!ATOM_CAS(&l->trap, 0, 1))\n\t\t\t\treturn;\n\t\t\tlua_sethook (l->activeL, signal_hook, LUA_MASKCOUNT, 1);\n\t\t\t// finish set ( l->trap 1 -> -1 )\n\t\t\tATOM_CAS(&l->trap, 1, -1);\n\t\t}\n\t} else if (signal == 1) {\n\t\tskynet_error(l->ctx, \"Current Memory %.3fK\", (float)l->mem / 1024);\n\t}\n}\n"
  },
  {
    "path": "skynet-src/atomic.h",
    "content": "#ifndef SKYNET_ATOMIC_H\n#define SKYNET_ATOMIC_H\n\n#include <stddef.h>\n#include <stdint.h>\n\n#ifdef __STDC_NO_ATOMICS__\n\n#define ATOM_INT volatile int\n#define ATOM_POINTER volatile uintptr_t\n#define ATOM_SIZET volatile size_t\n#define ATOM_ULONG volatile unsigned long\n#define ATOM_INIT(ptr, v) (*(ptr) = v)\n#define ATOM_LOAD(ptr) (*(ptr))\n#define ATOM_STORE(ptr, v) (*(ptr) = v)\n#define ATOM_CAS(ptr, oval, nval) __sync_bool_compare_and_swap(ptr, oval, nval)\n#define ATOM_CAS_ULONG(ptr, oval, nval) __sync_bool_compare_and_swap(ptr, oval, nval)\n#define ATOM_CAS_SIZET(ptr, oval, nval) __sync_bool_compare_and_swap(ptr, oval, nval)\n#define ATOM_CAS_POINTER(ptr, oval, nval) __sync_bool_compare_and_swap(ptr, oval, nval)\n#define ATOM_FINC(ptr) __sync_fetch_and_add(ptr, 1)\n#define ATOM_FDEC(ptr) __sync_fetch_and_sub(ptr, 1)\n#define ATOM_FADD(ptr,n) __sync_fetch_and_add(ptr, n)\n#define ATOM_FSUB(ptr,n) __sync_fetch_and_sub(ptr, n)\n#define ATOM_FAND(ptr,n) __sync_fetch_and_and(ptr, n)\n\n#else\n\n#if defined (__cplusplus)\n#include <atomic>\n#define STD_ std::\n#define atomic_value_type_(p, v) decltype((p)->load())(v) \n#else\n#include <stdatomic.h>\n#define STD_\n#define atomic_value_type_(p, v) v\n#endif\n\n#define ATOM_INT  STD_ atomic_int\n#define ATOM_POINTER STD_ atomic_uintptr_t\n#define ATOM_SIZET STD_ atomic_size_t\n#define ATOM_ULONG STD_ atomic_ulong\n#define ATOM_INIT(ref, v) STD_ atomic_init(ref, v)\n#define ATOM_LOAD(ptr) STD_ atomic_load(ptr)\n#define ATOM_STORE(ptr, v) STD_ atomic_store(ptr, v)\n\nstatic inline int\nATOM_CAS(STD_ atomic_int *ptr, int oval, int nval) {\n\treturn STD_ atomic_compare_exchange_weak(ptr, &(oval), nval);\n}\n\nstatic inline int\nATOM_CAS_SIZET(STD_ atomic_size_t *ptr, size_t oval, size_t nval) {\n\treturn STD_ atomic_compare_exchange_weak(ptr, &(oval), nval);\n}\n\nstatic inline int\nATOM_CAS_ULONG(STD_ atomic_ulong *ptr, unsigned long oval, unsigned long nval) {\n\treturn STD_ atomic_compare_exchange_weak(ptr, &(oval), nval);\n}\n\nstatic inline int\nATOM_CAS_POINTER(STD_ atomic_uintptr_t *ptr, uintptr_t oval, uintptr_t nval) {\n\treturn STD_ atomic_compare_exchange_weak(ptr, &(oval), nval);\n}\n\n#define ATOM_FINC(ptr) STD_ atomic_fetch_add(ptr, atomic_value_type_(ptr,1))\n#define ATOM_FDEC(ptr) STD_ atomic_fetch_sub(ptr, atomic_value_type_(ptr, 1))\n#define ATOM_FADD(ptr,n) STD_ atomic_fetch_add(ptr, atomic_value_type_(ptr, n))\n#define ATOM_FSUB(ptr,n) STD_ atomic_fetch_sub(ptr, atomic_value_type_(ptr, n))\n#define ATOM_FAND(ptr,n) STD_ atomic_fetch_and(ptr, atomic_value_type_(ptr, n))\n\n#endif\n\n#endif\n"
  },
  {
    "path": "skynet-src/malloc_hook.c",
    "content": "#include <string.h>\n#include <assert.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include <lauxlib.h>\n\n#include \"skynet.h\"\n#include \"atomic.h\"\n\n#include \"malloc_hook.h\"\n\n// turn on MEMORY_CHECK can do more memory check, such as double free\n// #define MEMORY_CHECK\n\n#define MEMORY_ALLOCTAG 0x20140605\n#define MEMORY_FREETAG 0x0badf00d\n\nstruct mem_data {\n    alignas(CACHE_LINE_SIZE)\n\tATOM_ULONG     handle;\n    AtomicMemInfo  info;\n};\n_Static_assert(sizeof(struct mem_data) % CACHE_LINE_SIZE == 0, \"mem_data must be cache-line aligned\");\n\nstruct mem_cookie {\n\tsize_t size;\n\tuint32_t handle;\n#ifdef MEMORY_CHECK\n\tuint32_t dogtag;\n#endif\n\tuint32_t cookie_size;\t// should be the last\n};\n\n#define SLOT_SIZE 0x10000\n#define PREFIX_SIZE sizeof(struct mem_cookie)\n\nstatic struct mem_data mem_stats[SLOT_SIZE];\n_Static_assert(alignof(mem_stats) % CACHE_LINE_SIZE == 0, \"mem_stats must be cache-line aligned\");\n\nstatic struct mem_data *\nget_mem_stat(uint32_t handle) {\n\tint h = (int)(handle & (SLOT_SIZE - 1));\n\tstruct mem_data *data = &mem_stats[h];\n\treturn data;\n}\n\n#ifndef NOUSE_JEMALLOC\n\n#include \"jemalloc.h\"\n\n// for skynet_lalloc use\n#define raw_realloc je_realloc\n#define raw_free je_free\n\ninline static void\nupdate_xmalloc_stat_alloc(uint32_t handle, size_t __n) {\n\tstruct mem_data *data = get_mem_stat(handle);\n    // 当两个不同的 handle 被哈希到同一个槽位时, 新的服务会覆盖旧服务的数据\n    // 这种情况在实际运行中非常罕见, 因为同时存在的服务数量很难超过 65536\n    ATOM_STORE(&data->handle, handle);\n\tatomic_meminfo_alloc(&data->info, __n);\n}\n\ninline static void\nupdate_xmalloc_stat_free(uint32_t handle, size_t __n) {\n\tstruct mem_data *data = get_mem_stat(handle);\n\tatomic_meminfo_free(&data->info, __n);\n}\n\ninline static void*\nfill_prefix(char* ptr, size_t sz, uint32_t cookie_size) {\n\tuint32_t handle = skynet_current_handle();\n\tstruct mem_cookie *p = (struct mem_cookie *)ptr;\n\tchar * ret = ptr + cookie_size;\n\tsz += cookie_size;\n\tp->size = sz;\n\tp->handle = handle;\n#ifdef MEMORY_CHECK\n\tp->dogtag = MEMORY_ALLOCTAG;\n#endif\n\tupdate_xmalloc_stat_alloc(handle, sz);\n\tmemcpy(ret - sizeof(uint32_t), &cookie_size, sizeof(cookie_size));\n\treturn ret;\n}\n\ninline static uint32_t\nget_cookie_size(char *ptr) {\n\tuint32_t cookie_size;\n\tmemcpy(&cookie_size, ptr - sizeof(cookie_size), sizeof(cookie_size));\n\treturn cookie_size;\n}\n\ninline static void*\nclean_prefix(char* ptr) {\n\tuint32_t cookie_size = get_cookie_size(ptr);\n\tstruct mem_cookie *p = (struct mem_cookie *)(ptr - cookie_size);\n\tuint32_t handle = p->handle;\n#ifdef MEMORY_CHECK\n\tuint32_t dogtag = p->dogtag;\n\tif (dogtag == MEMORY_FREETAG) {\n\t\tfprintf(stderr, \"xmalloc: double free in :%08x\\n\", handle);\n\t}\n\tassert(dogtag == MEMORY_ALLOCTAG);\t// memory out of bounds\n\tp->dogtag = MEMORY_FREETAG;\n#endif\n\tupdate_xmalloc_stat_free(handle, p->size);\n\treturn p;\n}\n\nstatic void malloc_oom(size_t size) {\n\tfprintf(stderr, \"xmalloc: Out of memory trying to allocate %zu bytes\\n\",\n\t\tsize);\n\tfflush(stderr);\n\tabort();\n}\n\nvoid\nmemory_info_dump(const char* opts) {\n\tje_malloc_stats_print(0,0, opts);\n}\n\nbool\nmallctl_bool(const char* name, bool* newval) {\n\tbool v = 0;\n\tsize_t len = sizeof(v);\n\tif(newval) {\n\t\tje_mallctl(name, &v, &len, newval, sizeof(bool));\n\t} else {\n\t\tje_mallctl(name, &v, &len, NULL, 0);\n\t}\n\treturn v;\n}\n\nint\nmallctl_cmd(const char* name) {\n\treturn je_mallctl(name, NULL, NULL, NULL, 0);\n}\n\nsize_t\nmallctl_int64(const char* name, size_t* newval) {\n\tsize_t v = 0;\n\tsize_t len = sizeof(v);\n\tif(newval) {\n\t\tje_mallctl(name, &v, &len, newval, sizeof(size_t));\n\t} else {\n\t\tje_mallctl(name, &v, &len, NULL, 0);\n\t}\n\t// skynet_error(NULL, \"name: %s, value: %zd\\n\", name, v);\n\treturn v;\n}\n\nint\nmallctl_opt(const char* name, int* newval) {\n\tint v = 0;\n\tsize_t len = sizeof(v);\n\tif(newval) {\n\t\tint ret = je_mallctl(name, &v, &len, newval, sizeof(int));\n\t\tif(ret == 0) {\n\t\t\tskynet_error(NULL, \"set new value(%d) for (%s) succeed\\n\", *newval, name);\n\t\t} else {\n\t\t\tskynet_error(NULL, \"set new value(%d) for (%s) failed: error -> %d\\n\", *newval, name, ret);\n\t\t}\n\t} else {\n\t\tje_mallctl(name, &v, &len, NULL, 0);\n\t}\n\n\treturn v;\n}\n\n// hook : malloc, realloc, free, calloc\n\nvoid *\nskynet_malloc(size_t size) {\n\tvoid* ptr = je_malloc(size + PREFIX_SIZE);\n\tif(!ptr) malloc_oom(size);\n\treturn fill_prefix(ptr, size, PREFIX_SIZE);\n}\n\nvoid *\nskynet_realloc(void *ptr, size_t size) {\n\tif (ptr == NULL) return skynet_malloc(size);\n\n\tuint32_t cookie_size = get_cookie_size(ptr);\n\tvoid* rawptr = clean_prefix(ptr);\n\tvoid *newptr = je_realloc(rawptr, size+cookie_size);\n\tif(!newptr) malloc_oom(size);\n\treturn fill_prefix(newptr, size, cookie_size);\n}\n\nvoid\nskynet_free(void *ptr) {\n\tif (ptr == NULL) return;\n\tvoid* rawptr = clean_prefix(ptr);\n\tje_free(rawptr);\n}\n\nvoid *\nskynet_calloc(size_t nmemb, size_t size) {\n\tuint32_t cookie_n = (PREFIX_SIZE+size-1)/size;\n\tvoid* ptr = je_calloc(nmemb + cookie_n, size);\n\tif(!ptr) malloc_oom(nmemb * size);\n\treturn fill_prefix(ptr, nmemb * size, cookie_n * size);\n}\n\nstatic inline uint32_t\nalignment_cookie_size(size_t alignment) {\n\tif (alignment >= PREFIX_SIZE)\n\t\treturn alignment;\n\tswitch (alignment) {\n\tcase 4 :\n\t\treturn (PREFIX_SIZE + 3) / 4 * 4;\n\tcase 8 :\n\t\treturn (PREFIX_SIZE + 7) / 8 * 8;\n\tcase 16 :\n\t\treturn (PREFIX_SIZE + 15) / 16 * 16;\n\t}\n\treturn (PREFIX_SIZE + alignment - 1) / alignment * alignment;\n}\n\nvoid *\nskynet_memalign(size_t alignment, size_t size) {\n\tuint32_t cookie_size = alignment_cookie_size(alignment);\n\tvoid* ptr = je_memalign(alignment, size + cookie_size);\n\tif(!ptr) malloc_oom(size);\n\treturn fill_prefix(ptr, size, cookie_size);\n}\n\nvoid *\nskynet_aligned_alloc(size_t alignment, size_t size) {\n\tuint32_t cookie_size = alignment_cookie_size(alignment);\n\tvoid* ptr = je_aligned_alloc(alignment, size + cookie_size);\n\tif(!ptr) malloc_oom(size);\n\treturn fill_prefix(ptr, size, cookie_size);\n}\n\nint\nskynet_posix_memalign(void **memptr, size_t alignment, size_t size) {\n\tuint32_t cookie_size = alignment_cookie_size(alignment);\n\tint err = je_posix_memalign(memptr, alignment, size + cookie_size);\n\tif (err) malloc_oom(size);\n\tfill_prefix(*memptr, size, cookie_size);\n\treturn err;\n}\n\n#else\n\n// for skynet_lalloc use\n#define raw_realloc realloc\n#define raw_free free\n\nvoid\nmemory_info_dump(const char* opts) {\n\tskynet_error(NULL, \"No jemalloc\");\n}\n\nsize_t\nmallctl_int64(const char* name, size_t* newval) {\n\tskynet_error(NULL, \"No jemalloc : mallctl_int64 %s.\", name);\n\treturn 0;\n}\n\nint\nmallctl_opt(const char* name, int* newval) {\n\tskynet_error(NULL, \"No jemalloc : mallctl_opt %s.\", name);\n\treturn 0;\n}\n\nbool\nmallctl_bool(const char* name, bool* newval) {\n\tskynet_error(NULL, \"No jemalloc : mallctl_bool %s.\", name);\n\treturn 0;\n}\n\nint\nmallctl_cmd(const char* name) {\n\tskynet_error(NULL, \"No jemalloc : mallctl_cmd %s.\", name);\n\treturn 0;\n}\n\n#endif\n\nsize_t\nmalloc_used_memory(void) {\n\tMemInfo total = {};\n\tfor(int i = 0; i < SLOT_SIZE; i++) {\n\t\tstruct mem_data* data = &mem_stats[i];\n\t\tconst uint32_t handle = ATOM_LOAD(&data->handle);\n\t\tif (handle != 0) {\n\t\t\tatomic_meminfo_merge(&total, &data->info);\n\t\t}\n\t}\n\treturn total.alloc - total.free;\n}\n\nsize_t\nmalloc_memory_block(void) {\n\tMemInfo total = {};\n\tfor(int i = 0; i < SLOT_SIZE; i++) {\n\t\tstruct mem_data* data = &mem_stats[i];\n\t\tconst uint32_t handle = ATOM_LOAD(&data->handle);\n\t\tif (handle != 0) {\n\t\t\tatomic_meminfo_merge(&total, &data->info);\n\t\t}\n\t}\n\treturn total.alloc_count - total.free_count;\n}\n\nvoid\ndump_c_mem() {\n\tskynet_error(NULL, \"dump all service mem:\");\n\tMemInfo total = {};\n\tfor(int i = 0; i < SLOT_SIZE; i++) {\n\t\tstruct mem_data* data = &mem_stats[i];\n\t\tconst uint32_t handle = ATOM_LOAD(&data->handle);\n\t\tif (handle != 0) {\n\t\t\tMemInfo info = {};\n\t\t\tatomic_meminfo_merge(&info, &data->info);\n\t\t\tmeminfo_merge(&total, &info);\n\t\t\tconst size_t using = info.alloc - info.free;\n\t\t\tskynet_error(NULL, \":%08x -> %zukb %zub\", handle, using >> 10, using);\n\t\t}\n\t}\n\tconst size_t using = total.alloc - total.free;\n\tskynet_error(NULL, \"+total: %zukb\", using >> 10);\n}\n\nchar *\nskynet_strdup(const char *str) {\n\tsize_t sz = strlen(str);\n\tchar * ret = skynet_malloc(sz+1);\n\tmemcpy(ret, str, sz+1);\n\treturn ret;\n}\n\nvoid *\nskynet_lalloc(void *ptr, size_t osize, size_t nsize) {\n\tif (nsize == 0) {\n\t\traw_free(ptr);\n\t\treturn NULL;\n\t} else {\n\t\treturn raw_realloc(ptr, nsize);\n\t}\n}\n\nint\ndump_mem_lua(lua_State *L) {\n\tint i;\n\tlua_newtable(L);\n\tfor(i=0; i<SLOT_SIZE; i++) {\n\t\tstruct mem_data* data = &mem_stats[i];\n\t\tconst uint32_t handle = ATOM_LOAD(&data->handle);\n\t\tif (handle != 0) {\n\t\t\tMemInfo info = {};\n\t\t\tatomic_meminfo_merge(&info, &data->info);\n\t\t\tlua_pushinteger(L, info.alloc - info.free);\n\t\t\tlua_rawseti(L, -2, handle);\n\t\t}\n\t}\n\treturn 1;\n}\n\nsize_t\nmalloc_current_memory(void) {\n\tuint32_t handle = skynet_current_handle();\n\tstruct mem_data *data = get_mem_stat(handle);\n\tif (ATOM_LOAD(&data->handle) != handle) {\n\t\treturn 0;\n\t}\n\tMemInfo info = {};\n\tatomic_meminfo_merge(&info, &data->info);\n\treturn info.alloc - info.free;\n}\n\nvoid\nskynet_debug_memory(const char *info) {\n\t// for debug use\n\tuint32_t handle = skynet_current_handle();\n\tsize_t mem = malloc_current_memory();\n\tfprintf(stderr, \"[:%08x] %s %p\\n\", handle, info, (void *)mem);\n}\n"
  },
  {
    "path": "skynet-src/malloc_hook.h",
    "content": "#ifndef SKYNET_MALLOC_HOOK_H\n#define SKYNET_MALLOC_HOOK_H\n\n#include <stdlib.h>\n#include <stdbool.h>\n#include <lua.h>\n\n#include \"mem_info.h\"\n\nextern size_t malloc_used_memory(void);\nextern size_t malloc_memory_block(void);\nextern void   memory_info_dump(const char *opts);\nextern size_t mallctl_int64(const char* name, size_t* newval);\nextern int    mallctl_opt(const char* name, int* newval);\nextern bool   mallctl_bool(const char* name, bool* newval);\nextern int    mallctl_cmd(const char* name);\nextern void   dump_c_mem(void);\nextern int    dump_mem_lua(lua_State *L);\nextern size_t malloc_current_memory(void);\n\n#endif /* SKYNET_MALLOC_HOOK_H */\n"
  },
  {
    "path": "skynet-src/mem_info.c",
    "content": "#include <string.h>\n\n#include \"mem_info.h\"\n\nvoid\nmeminfo_init(MemInfo *info) {\n    memset(info, 0, sizeof(*info));\n}\n\nvoid\natomic_meminfo_init(AtomicMemInfo *info) {\n    ATOM_INIT(&info->alloc, 0);\n    ATOM_INIT(&info->alloc_count, 0);\n    ATOM_INIT(&info->free, 0);\n    ATOM_INIT(&info->free_count, 0);\n}\n\nvoid\nmeminfo_alloc(MemInfo *info, size_t size) {\n    info->alloc += size;\n    ++info->alloc_count;\n}\n\nvoid\natomic_meminfo_alloc(AtomicMemInfo *info, size_t size) {\n    ATOM_FADD(&info->alloc, size);\n    ATOM_FADD(&info->alloc_count, 1);\n}\n\nvoid\nmeminfo_free(MemInfo *info, size_t size) {\n    info->free += size;\n    ++info->free_count;\n}\n\nvoid\natomic_meminfo_free(AtomicMemInfo *info, size_t size) {\n    ATOM_FADD(&info->free, size);\n    ATOM_FADD(&info->free_count, 1);\n}\n\nvoid\nmeminfo_merge(MemInfo *dest, const MemInfo *src) {\n    dest->alloc += src->alloc;\n    dest->alloc_count += src->alloc_count;\n    dest->free += src->free;\n    dest->free_count += src->free_count;\n}\n\nvoid\natomic_meminfo_merge(MemInfo *dest, const AtomicMemInfo *src) {\n    MemInfo info;\n    // 先加载 free 后加载 alloc 避免大小错乱\n    info.free_count = ATOM_LOAD(&src->free_count);\n    info.free = ATOM_LOAD(&src->free);\n    info.alloc_count = ATOM_LOAD(&src->alloc_count);\n    info.alloc = ATOM_LOAD(&src->alloc);\n    meminfo_merge(dest, &info);\n}\n"
  },
  {
    "path": "skynet-src/mem_info.h",
    "content": "#ifndef _MEM_INFO_H_\n#define _MEM_INFO_H_\n\n#include <stdalign.h>\n#include <stddef.h>\n\n#include \"atomic.h\"\n\n#define CACHE_LINE_SIZE 64\n\ntypedef struct {\n    size_t alloc;\n    size_t alloc_count;\n    size_t free;\n    size_t free_count;\n} MemInfo;\n\ntypedef struct {\n    // alloc 与 free 可能不在一个线程\n    // 为了避免竞争，这里也拆成两个 CacheLine 大小\n    alignas(CACHE_LINE_SIZE)\n    ATOM_SIZET alloc;\n    ATOM_SIZET alloc_count;\n\n    alignas(CACHE_LINE_SIZE)\n    ATOM_SIZET free;\n    ATOM_SIZET free_count;\n} AtomicMemInfo;\n\nvoid meminfo_init(MemInfo *info);\nvoid atomic_meminfo_init(AtomicMemInfo *info);\n\nvoid meminfo_alloc(MemInfo *info, size_t size);\nvoid atomic_meminfo_alloc(AtomicMemInfo *info, size_t size);\n\nvoid meminfo_free(MemInfo *info, size_t size);\nvoid atomic_meminfo_free(AtomicMemInfo *info, size_t size);\n\nvoid meminfo_merge(MemInfo *dest, const MemInfo *src);\nvoid atomic_meminfo_merge(MemInfo *dest, const AtomicMemInfo *src);\n\n#endif // _MEM_INFO_H_\n"
  },
  {
    "path": "skynet-src/rwlock.h",
    "content": "#ifndef SKYNET_RWLOCK_H\n#define SKYNET_RWLOCK_H\n\n#ifndef USE_PTHREAD_LOCK\n\n#include \"atomic.h\"\n\nstruct rwlock {\n\tATOM_INT write;\n\tATOM_INT read;\n};\n\nstatic inline void\nrwlock_init(struct rwlock *lock) {\n\tATOM_INIT(&lock->write, 0);\n\tATOM_INIT(&lock->read, 0);\n}\n\nstatic inline void\nrwlock_rlock(struct rwlock *lock) {\n\tfor (;;) {\n\t\twhile(ATOM_LOAD(&lock->write)) {}\n\t\tATOM_FINC(&lock->read);\n\t\tif (ATOM_LOAD(&lock->write)) {\n\t\t\tATOM_FDEC(&lock->read);\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nstatic inline void\nrwlock_wlock(struct rwlock *lock) {\n\twhile (!ATOM_CAS(&lock->write,0,1)) {}\n\twhile(ATOM_LOAD(&lock->read)) {}\n}\n\nstatic inline void\nrwlock_wunlock(struct rwlock *lock) {\n\tATOM_STORE(&lock->write, 0);\n}\n\nstatic inline void\nrwlock_runlock(struct rwlock *lock) {\n\tATOM_FDEC(&lock->read);\n}\n\n#else\n\n#include <pthread.h>\n\n// only for some platform doesn't have __sync_*\n// todo: check the result of pthread api\n\nstruct rwlock {\n\tpthread_rwlock_t lock;\n};\n\nstatic inline void\nrwlock_init(struct rwlock *lock) {\n\tpthread_rwlock_init(&lock->lock, NULL);\n}\n\nstatic inline void\nrwlock_rlock(struct rwlock *lock) {\n\t pthread_rwlock_rdlock(&lock->lock);\n}\n\nstatic inline void\nrwlock_wlock(struct rwlock *lock) {\n\t pthread_rwlock_wrlock(&lock->lock);\n}\n\nstatic inline void\nrwlock_wunlock(struct rwlock *lock) {\n\tpthread_rwlock_unlock(&lock->lock);\n}\n\nstatic inline void\nrwlock_runlock(struct rwlock *lock) {\n\tpthread_rwlock_unlock(&lock->lock);\n}\n\n#endif\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet.h",
    "content": "#ifndef SKYNET_H\n#define SKYNET_H\n\n#include \"skynet_malloc.h\"\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define PTYPE_TEXT 0\n#define PTYPE_RESPONSE 1\n#define PTYPE_MULTICAST 2\n#define PTYPE_CLIENT 3\n#define PTYPE_SYSTEM 4\n#define PTYPE_HARBOR 5\n#define PTYPE_SOCKET 6\n// read lualib/skynet.lua examples/simplemonitor.lua\n#define PTYPE_ERROR 7\t\n// read lualib/skynet.lua lualib/mqueue.lua lualib/snax.lua\n#define PTYPE_RESERVED_QUEUE 8\n#define PTYPE_RESERVED_DEBUG 9\n#define PTYPE_RESERVED_LUA 10\n#define PTYPE_RESERVED_SNAX 11\n\n#define PTYPE_TAG_DONTCOPY 0x10000\n#define PTYPE_TAG_ALLOCSESSION 0x20000\n\nstruct skynet_context;\n\nvoid skynet_error(struct skynet_context * context, const char *msg, ...);\nconst char * skynet_command(struct skynet_context * context, const char * cmd , const char * parm);\nuint32_t skynet_queryname(struct skynet_context * context, const char * name);\nint skynet_send(struct skynet_context * context, uint32_t source, uint32_t destination , int type, int session, void * msg, size_t sz);\nint skynet_sendname(struct skynet_context * context, uint32_t source, const char * destination , int type, int session, void * msg, size_t sz);\n\nint skynet_isremote(struct skynet_context *, uint32_t handle, int * harbor);\n\ntypedef int (*skynet_cb)(struct skynet_context * context, void *ud, int type, int session, uint32_t source , const void * msg, size_t sz);\nvoid skynet_callback(struct skynet_context * context, void *ud, skynet_cb cb);\n\nuint32_t skynet_current_handle(void);\nuint64_t skynet_now(void);\nvoid skynet_debug_memory(const char *info);\t// for debug use, output current service memory to stderr\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_daemon.c",
    "content": "#include <stdio.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/file.h>\n#include <signal.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <fcntl.h>\n\n#include \"skynet_daemon.h\"\n\nstatic int\ncheck_pid(const char *pidfile) {\n\tint pid = 0;\n\tFILE *f = fopen(pidfile,\"r\");\n\tif (f == NULL)\n\t\treturn 0;\n\tint n = fscanf(f,\"%d\", &pid);\n\tfclose(f);\n\n\tif (n !=1 || pid == 0 || pid == getpid()) {\n\t\treturn 0;\n\t}\n\n\tif (kill(pid, 0) && errno == ESRCH)\n\t\treturn 0;\n\n\treturn pid;\n}\n\nstatic int\nwrite_pid(const char *pidfile) {\n\tFILE *f;\n\tint pid = 0;\n\tint fd = open(pidfile, O_RDWR|O_CREAT, 0644);\n\tif (fd == -1) {\n\t\tfprintf(stderr, \"Can't create pidfile [%s].\\n\", pidfile);\n\t\treturn 0;\n\t}\n\tf = fdopen(fd, \"w+\");\n\tif (f == NULL) {\n\t\tfprintf(stderr, \"Can't open pidfile [%s].\\n\", pidfile);\n\t\treturn 0;\n\t}\n\n\tif (flock(fd, LOCK_EX|LOCK_NB) == -1) {\n\t\tint n = fscanf(f, \"%d\", &pid);\n\t\tfclose(f);\n\t\tif (n != 1) {\n\t\t\tfprintf(stderr, \"Can't lock and read pidfile.\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Can't lock pidfile, lock is held by pid %d.\\n\", pid);\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpid = getpid();\n\tif (!fprintf(f,\"%d\\n\", pid)) {\n\t\tfprintf(stderr, \"Can't write pid.\\n\");\n\t\tclose(fd);\n\t\treturn 0;\n\t}\n\tfflush(f);\n\n\treturn pid;\n}\n\nstatic int\nredirect_fds() {\n\tint nfd = open(\"/dev/null\", O_RDWR);\n\tif (nfd == -1) {\n\t\tperror(\"Unable to open /dev/null: \");\n\t\treturn -1;\n\t}\n\tif (dup2(nfd, 0) < 0) {\n\t\tperror(\"Unable to dup2 stdin(0): \");\n\t\treturn -1;\n\t}\n\tif (dup2(nfd, 1) < 0) {\n\t\tperror(\"Unable to dup2 stdout(1): \");\n\t\treturn -1;\n\t}\n\tif (dup2(nfd, 2) < 0) {\n\t\tperror(\"Unable to dup2 stderr(2): \");\n\t\treturn -1;\n\t}\n\n\tclose(nfd);\n\n\treturn 0;\n}\n\nint\ndaemon_init(const char *pidfile) {\n\tint pid = check_pid(pidfile);\n\n\tif (pid) {\n\t\tfprintf(stderr, \"Skynet is already running, pid = %d.\\n\", pid);\n\t\treturn 1;\n\t}\n\n#ifdef __APPLE__\n\tfprintf(stderr, \"'daemon' is deprecated: first deprecated in OS X 10.5 , use launchd instead.\\n\");\n#else\n\tif (daemon(1,1)) {\n\t\tfprintf(stderr, \"Can't daemonize.\\n\");\n\t\treturn 1;\n\t}\n#endif\n\n\tpid = write_pid(pidfile);\n\tif (pid == 0) {\n\t\treturn 1;\n\t}\n\n\tif (redirect_fds()) {\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nint\ndaemon_exit(const char *pidfile) {\n\treturn unlink(pidfile);\n}\n"
  },
  {
    "path": "skynet-src/skynet_daemon.h",
    "content": "#ifndef skynet_daemon_h\n#define skynet_daemon_h\n\nint daemon_init(const char *pidfile);\nint daemon_exit(const char *pidfile);\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_env.c",
    "content": "#include \"skynet.h\"\n#include \"skynet_env.h\"\n#include \"spinlock.h\"\n\n#include <lua.h>\n#include <lauxlib.h>\n\n#include <stdlib.h>\n#include <assert.h>\n\nstruct skynet_env {\n\tstruct spinlock lock;\n\tlua_State *L;\n};\n\nstatic struct skynet_env *E = NULL;\n\nconst char * \nskynet_getenv(const char *key) {\n\tSPIN_LOCK(E)\n\n\tlua_State *L = E->L;\n\t\n\tlua_getglobal(L, key);\n\tconst char * result = lua_tostring(L, -1);\n\tlua_pop(L, 1);\n\n\tSPIN_UNLOCK(E)\n\n\treturn result;\n}\n\nvoid \nskynet_setenv(const char *key, const char *value) {\n\tSPIN_LOCK(E)\n\t\n\tlua_State *L = E->L;\n\tlua_getglobal(L, key);\n\tassert(lua_isnil(L, -1));\n\tlua_pop(L,1);\n\tlua_pushstring(L,value);\n\tlua_setglobal(L,key);\n\n\tSPIN_UNLOCK(E)\n}\n\nvoid\nskynet_env_init() {\n\tE = skynet_malloc(sizeof(*E));\n\tSPIN_INIT(E)\n\tE->L = luaL_newstate();\n}\n"
  },
  {
    "path": "skynet-src/skynet_env.h",
    "content": "#ifndef SKYNET_ENV_H\n#define SKYNET_ENV_H\n\nconst char * skynet_getenv(const char *key);\nvoid skynet_setenv(const char *key, const char *value);\n\nvoid skynet_env_init();\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_error.c",
    "content": "#include \"skynet.h\"\n#include \"skynet_handle.h\"\n#include \"skynet_imp.h\"\n#include \"skynet_mq.h\"\n#include \"skynet_server.h\"\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define LOG_MESSAGE_SIZE 256\n\nstatic int\nlog_try_vasprintf(char **strp, const char *fmt, va_list ap) {\n\tif (strcmp(fmt, \"%*s\") == 0) {\n\t\t// for `lerror` in lua-skynet.c\n\t\tconst int len = va_arg(ap, int);\n\t\tconst char *tmp = va_arg(ap, const char*);\n\t\t*strp = skynet_strndup(tmp, len);\n\t\treturn *strp != NULL ? len : -1;\n\t}\n\n\tchar tmp[LOG_MESSAGE_SIZE];\n\tint len = vsnprintf(tmp, LOG_MESSAGE_SIZE, fmt, ap);\n\tif (len >= 0 && len < LOG_MESSAGE_SIZE) {\n\t\t*strp = skynet_strndup(tmp, len);\n\t\tif (*strp == NULL) return -1;\n\t}\n\treturn len;\n}\n\nvoid\nskynet_error(struct skynet_context * context, const char *msg, ...) {\n\tstatic uint32_t logger = 0;\n\tif (logger == 0) {\n\t\tlogger = skynet_handle_findname(\"logger\");\n\t}\n\tif (logger == 0) {\n\t\treturn;\n\t}\n\n\tchar *data = NULL;\n\n\tva_list ap;\n\n\tva_start(ap, msg);\n\tint len = log_try_vasprintf(&data, msg, ap);\n\tva_end(ap);\n\tif (len < 0) {\n\t\tperror(\"vasprintf error :\");\n\t\treturn;\n\t}\n\n\tif (data == NULL) { // unlikely\n\t\tdata = skynet_malloc(len + 1);\n\t\tva_start(ap, msg);\n\t\tlen = vsnprintf(data, len + 1, msg, ap);\n\t\tva_end(ap);\n\t\tif (len < 0) {\n\t\t\tskynet_free(data);\n\t\t\tperror(\"vsnprintf error :\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tstruct skynet_message smsg;\n\tif (context == NULL) {\n\t\tsmsg.source = 0;\n\t} else {\n\t\tsmsg.source = skynet_context_handle(context);\n\t}\n\tsmsg.session = 0;\n\tsmsg.data = data;\n\tsmsg.sz = len | ((size_t)PTYPE_TEXT << MESSAGE_TYPE_SHIFT);\n\tskynet_context_push(logger, &smsg);\n}\n"
  },
  {
    "path": "skynet-src/skynet_handle.c",
    "content": "#include \"skynet.h\"\n\n#include \"skynet_handle.h\"\n#include \"skynet_imp.h\"\n#include \"skynet_server.h\"\n#include \"rwlock.h\"\n\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n\n#define DEFAULT_SLOT_SIZE 4\n#define MAX_SLOT_SIZE 0x40000000\n\nstruct handle_name {\n\tchar * name;\n\tuint32_t handle;\n};\n\nstruct handle_storage {\n\tstruct rwlock lock;\n\n\tuint32_t harbor;\n\tuint32_t handle_index;\n\tint slot_size;\n\tstruct skynet_context ** slot;\n\n\tint name_cap;\n\tint name_count;\n\tstruct handle_name *name;\n};\n\nstatic struct handle_storage *H = NULL;\n\nuint32_t\nskynet_handle_register(struct skynet_context *ctx) {\n\tstruct handle_storage *s = H;\n\n\trwlock_wlock(&s->lock);\n\n\tfor (;;) {\n\t\tint i;\n\t\tuint32_t handle = s->handle_index;\n\t\tfor (i=0;i<s->slot_size;i++,handle++) {\n\t\t\tif (handle > HANDLE_MASK) {\n\t\t\t\t// 0 is reserved\n\t\t\t\thandle = 1;\n\t\t\t}\n\t\t\tint hash = handle & (s->slot_size-1);\n\t\t\tif (s->slot[hash] == NULL) {\n\t\t\t\ts->slot[hash] = ctx;\n\t\t\t\ts->handle_index = handle + 1;\n\n\t\t\t\trwlock_wunlock(&s->lock);\n\n\t\t\t\thandle |= s->harbor;\n\t\t\t\treturn handle;\n\t\t\t}\n\t\t}\n\t\tassert((s->slot_size*2 - 1) <= HANDLE_MASK);\n\t\tstruct skynet_context ** new_slot = skynet_malloc(s->slot_size * 2 * sizeof(struct skynet_context *));\n\t\tmemset(new_slot, 0, s->slot_size * 2 * sizeof(struct skynet_context *));\n\t\tfor (i=0;i<s->slot_size;i++) {\n\t\t\tif (s->slot[i]) {\n\t\t\t\tint hash = skynet_context_handle(s->slot[i]) & (s->slot_size * 2 - 1);\n\t\t\t\tassert(new_slot[hash] == NULL);\n\t\t\t\tnew_slot[hash] = s->slot[i];\n\t\t\t}\n\t\t}\n\t\tskynet_free(s->slot);\n\t\ts->slot = new_slot;\n\t\ts->slot_size *= 2;\n\t}\n}\n\nint\nskynet_handle_retire(uint32_t handle) {\n\tint ret = 0;\n\tstruct handle_storage *s = H;\n\n\trwlock_wlock(&s->lock);\n\n\tuint32_t hash = handle & (s->slot_size-1);\n\tstruct skynet_context * ctx = s->slot[hash];\n\n\tif (ctx != NULL && skynet_context_handle(ctx) == handle) {\n\t\ts->slot[hash] = NULL;\n\t\tret = 1;\n\t\tint i;\n\t\tint j=0, n=s->name_count;\n\t\tfor (i=0; i<n; ++i) {\n\t\t\tif (s->name[i].handle == handle) {\n\t\t\t\tskynet_free(s->name[i].name);\n\t\t\t\tcontinue;\n\t\t\t} else if (i!=j) {\n\t\t\t\ts->name[j] = s->name[i];\n\t\t\t}\n\t\t\t++j;\n\t\t}\n\t\ts->name_count = j;\n\t} else {\n\t\tctx = NULL;\n\t}\n\n\trwlock_wunlock(&s->lock);\n\n\tif (ctx) {\n\t\t// release ctx may call skynet_handle_* , so wunlock first.\n\t\tskynet_context_release(ctx);\n\t}\n\n\treturn ret;\n}\n\nvoid\nskynet_handle_retireall() {\n\tstruct handle_storage *s = H;\n\tfor (;;) {\n\t\tint n=0;\n\t\tint i;\n\t\tfor (i=0;i<s->slot_size;i++) {\n\t\t\trwlock_rlock(&s->lock);\n\t\t\tstruct skynet_context * ctx = s->slot[i];\n\t\t\tuint32_t handle = 0;\n\t\t\tif (ctx) {\n\t\t\t\thandle = skynet_context_handle(ctx);\n\t\t\t\t++n;\n\t\t\t}\n\t\t\trwlock_runlock(&s->lock);\n\t\t\tif (handle != 0) {\n\t\t\t\tskynet_handle_retire(handle);\n\t\t\t}\n\t\t}\n\t\tif (n==0)\n\t\t\treturn;\n\t}\n}\n\nstruct skynet_context *\nskynet_handle_grab(uint32_t handle) {\n\tstruct handle_storage *s = H;\n\tstruct skynet_context * result = NULL;\n\n\trwlock_rlock(&s->lock);\n\n\tuint32_t hash = handle & (s->slot_size-1);\n\tstruct skynet_context * ctx = s->slot[hash];\n\tif (ctx && skynet_context_handle(ctx) == handle) {\n\t\tresult = ctx;\n\t\tskynet_context_grab(result);\n\t}\n\n\trwlock_runlock(&s->lock);\n\n\treturn result;\n}\n\nuint32_t\nskynet_handle_findname(const char * name) {\n\tstruct handle_storage *s = H;\n\n\trwlock_rlock(&s->lock);\n\n\tuint32_t handle = 0;\n\n\tint begin = 0;\n\tint end = s->name_count - 1;\n\twhile (begin<=end) {\n\t\tint mid = (begin+end)/2;\n\t\tstruct handle_name *n = &s->name[mid];\n\t\tint c = strcmp(n->name, name);\n\t\tif (c==0) {\n\t\t\thandle = n->handle;\n\t\t\tbreak;\n\t\t}\n\t\tif (c<0) {\n\t\t\tbegin = mid + 1;\n\t\t} else {\n\t\t\tend = mid - 1;\n\t\t}\n\t}\n\n\trwlock_runlock(&s->lock);\n\n\treturn handle;\n}\n\nstatic void\n_insert_name_before(struct handle_storage *s, char *name, uint32_t handle, int before) {\n\tif (s->name_count >= s->name_cap) {\n\t\ts->name_cap *= 2;\n\t\tassert(s->name_cap <= MAX_SLOT_SIZE);\n\t\tstruct handle_name * n = skynet_malloc(s->name_cap * sizeof(struct handle_name));\n\t\tint i;\n\t\tfor (i=0;i<before;i++) {\n\t\t\tn[i] = s->name[i];\n\t\t}\n\t\tfor (i=before;i<s->name_count;i++) {\n\t\t\tn[i+1] = s->name[i];\n\t\t}\n\t\tskynet_free(s->name);\n\t\ts->name = n;\n\t} else {\n\t\tint i;\n\t\tfor (i=s->name_count;i>before;i--) {\n\t\t\ts->name[i] = s->name[i-1];\n\t\t}\n\t}\n\ts->name[before].name = name;\n\ts->name[before].handle = handle;\n\ts->name_count ++;\n}\n\nstatic const char *\n_insert_name(struct handle_storage *s, const char * name, uint32_t handle) {\n\tint begin = 0;\n\tint end = s->name_count - 1;\n\twhile (begin<=end) {\n\t\tint mid = (begin+end)/2;\n\t\tstruct handle_name *n = &s->name[mid];\n\t\tint c = strcmp(n->name, name);\n\t\tif (c==0) {\n\t\t\treturn NULL;\n\t\t}\n\t\tif (c<0) {\n\t\t\tbegin = mid + 1;\n\t\t} else {\n\t\t\tend = mid - 1;\n\t\t}\n\t}\n\tchar * result = skynet_strdup(name);\n\n\t_insert_name_before(s, result, handle, begin);\n\n\treturn result;\n}\n\nconst char *\nskynet_handle_namehandle(uint32_t handle, const char *name) {\n\trwlock_wlock(&H->lock);\n\n\tconst char * ret = _insert_name(H, name, handle);\n\n\trwlock_wunlock(&H->lock);\n\n\treturn ret;\n}\n\nvoid\nskynet_handle_init(int harbor) {\n\tassert(H==NULL);\n\tstruct handle_storage * s = skynet_malloc(sizeof(*H));\n\ts->slot_size = DEFAULT_SLOT_SIZE;\n\ts->slot = skynet_malloc(s->slot_size * sizeof(struct skynet_context *));\n\tmemset(s->slot, 0, s->slot_size * sizeof(struct skynet_context *));\n\n\trwlock_init(&s->lock);\n\t// reserve 0 for system\n\ts->harbor = (uint32_t) (harbor & 0xff) << HANDLE_REMOTE_SHIFT;\n\ts->handle_index = 1;\n\ts->name_cap = 2;\n\ts->name_count = 0;\n\ts->name = skynet_malloc(s->name_cap * sizeof(struct handle_name));\n\n\tH = s;\n\n\t// Don't need to free H\n}\n"
  },
  {
    "path": "skynet-src/skynet_handle.h",
    "content": "#ifndef SKYNET_CONTEXT_HANDLE_H\n#define SKYNET_CONTEXT_HANDLE_H\n\n#include <stdint.h>\n\n// reserve high 8 bits for remote id\n#define HANDLE_MASK 0xffffff\n#define HANDLE_REMOTE_SHIFT 24\n\nstruct skynet_context;\n\nuint32_t skynet_handle_register(struct skynet_context *);\nint skynet_handle_retire(uint32_t handle);\nstruct skynet_context * skynet_handle_grab(uint32_t handle);\nvoid skynet_handle_retireall();\n\nuint32_t skynet_handle_findname(const char * name);\nconst char * skynet_handle_namehandle(uint32_t handle, const char *name);\n\nvoid skynet_handle_init(int harbor);\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_harbor.c",
    "content": "#include \"skynet.h\"\n#include \"skynet_harbor.h\"\n#include \"skynet_server.h\"\n#include \"skynet_mq.h\"\n#include \"skynet_handle.h\"\n\n#include <string.h>\n#include <stdio.h>\n#include <assert.h>\n\nstatic struct skynet_context * REMOTE = 0;\nstatic unsigned int HARBOR = ~0;\n\nstatic inline int\ninvalid_type(int type) {\n\treturn type != PTYPE_SYSTEM && type != PTYPE_HARBOR;\n}\n\nvoid \nskynet_harbor_send(struct remote_message *rmsg, uint32_t source, int session) {\n\tassert(invalid_type(rmsg->type) && REMOTE);\n\tskynet_context_send(REMOTE, rmsg, sizeof(*rmsg) , source, PTYPE_SYSTEM , session);\n}\n\nint \nskynet_harbor_message_isremote(uint32_t handle) {\n\tassert(HARBOR != ~0);\n\tint h = (handle & ~HANDLE_MASK);\n\treturn h != HARBOR && h !=0;\n}\n\nvoid\nskynet_harbor_init(int harbor) {\n\tHARBOR = (unsigned int)harbor << HANDLE_REMOTE_SHIFT;\n}\n\nvoid\nskynet_harbor_start(void *ctx) {\n\t// the HARBOR must be reserved to ensure the pointer is valid.\n\t// It will be released at last by calling skynet_harbor_exit\n\tskynet_context_reserve(ctx);\n\tREMOTE = ctx;\n}\n\nvoid\nskynet_harbor_exit() {\n\tstruct skynet_context * ctx = REMOTE;\n\tREMOTE= NULL;\n\tif (ctx) {\n\t\tskynet_context_release(ctx);\n\t}\n}\n"
  },
  {
    "path": "skynet-src/skynet_harbor.h",
    "content": "#ifndef SKYNET_HARBOR_H\n#define SKYNET_HARBOR_H\n\n#include <stdint.h>\n#include <stdlib.h>\n\n#define GLOBALNAME_LENGTH 16\n#define REMOTE_MAX 256\n\nstruct remote_name {\n\tchar name[GLOBALNAME_LENGTH];\n\tuint32_t handle;\n};\n\nstruct remote_message {\n\tstruct remote_name destination;\n\tconst void * message;\n\tsize_t sz;\n\tint type;\n};\n\nvoid skynet_harbor_send(struct remote_message *rmsg, uint32_t source, int session);\nint skynet_harbor_message_isremote(uint32_t handle);\nvoid skynet_harbor_init(int harbor);\nvoid skynet_harbor_start(void * ctx);\nvoid skynet_harbor_exit();\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_imp.h",
    "content": "#ifndef SKYNET_IMP_H\n#define SKYNET_IMP_H\n\n#include <string.h>\n\nstruct skynet_config {\n\tint thread;\n\tint harbor;\n\tint profile;\n\tconst char * daemon;\n\tconst char * module_path;\n\tconst char * bootstrap;\n\tconst char * logger;\n\tconst char * logservice;\n};\n\n#define THREAD_WORKER 0\n#define THREAD_MAIN 1\n#define THREAD_SOCKET 2\n#define THREAD_TIMER 3\n#define THREAD_MONITOR 4\n\nvoid skynet_start(struct skynet_config * config);\n\nstatic inline char *\nskynet_strndup(const char *str, size_t size) {\n\tchar * ret = skynet_malloc(size+1);\n\tif (ret == NULL) return NULL;\n\tmemcpy(ret, str, size);\n\tret[size] = '\\0';\n\treturn ret;\n}\n\nstatic inline char *\nskynet_strdup(const char *str) {\n\tsize_t sz = strlen(str);\n\treturn skynet_strndup(str, sz);\n}\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_log.c",
    "content": "#include \"skynet_log.h\"\n#include \"skynet_timer.h\"\n#include \"skynet.h\"\n#include \"skynet_socket.h\"\n#include <string.h>\n#include <time.h>\n\nFILE * \nskynet_log_open(struct skynet_context * ctx, uint32_t handle) {\n\tconst char * logpath = skynet_getenv(\"logpath\");\n\tif (logpath == NULL)\n\t\treturn NULL;\n\tsize_t sz = strlen(logpath);\n\tchar tmp[sz + 16];\n\tsprintf(tmp, \"%s/%08x.log\", logpath, handle);\n\tFILE *f = fopen(tmp, \"ab\");\n\tif (f) {\n\t\tuint32_t starttime = skynet_starttime();\n\t\tuint64_t currenttime = skynet_now();\n\t\ttime_t ti = starttime + currenttime/100;\n\t\tskynet_error(ctx, \"Open log file %s\", tmp);\n\t\tfprintf(f, \"open time: %u %s\", (uint32_t)currenttime, ctime(&ti));\n\t\tfflush(f);\n\t} else {\n\t\tskynet_error(ctx, \"Open log file %s fail\", tmp);\n\t}\n\treturn f;\n}\n\nvoid\nskynet_log_close(struct skynet_context * ctx, FILE *f, uint32_t handle) {\n\tskynet_error(ctx, \"Close log file :%08x\", handle);\n\tfprintf(f, \"close time: %u\\n\", (uint32_t)skynet_now());\n\tfclose(f);\n}\n\nstatic void\nlog_blob(FILE *f, void * buffer, size_t sz) {\n\tsize_t i;\n\tuint8_t * buf = buffer;\n\tfor (i=0;i!=sz;i++) {\n\t\tfprintf(f, \"%02x\", buf[i]);\n\t}\n}\n\nstatic void\nlog_socket(FILE * f, struct skynet_socket_message * message, size_t sz) {\n\tfprintf(f, \"[socket] %d %d %d \", message->type, message->id, message->ud);\n\n\tif (message->buffer == NULL) {\n\t\tconst char *buffer = (const char *)(message + 1);\n\t\tsz -= sizeof(*message);\n\t\tconst char * eol = memchr(buffer, '\\0', sz);\n\t\tif (eol) {\n\t\t\tsz = eol - buffer;\n\t\t}\n\t\tfprintf(f, \"[%*s]\", (int)sz, (const char *)buffer);\n\t} else {\n\t\tsz = message->ud;\n\t\tlog_blob(f, message->buffer, sz);\n\t}\n\tfprintf(f, \"\\n\");\n\tfflush(f);\n}\n\nvoid \nskynet_log_output(FILE *f, uint32_t source, int type, int session, void * buffer, size_t sz) {\n\tif (type == PTYPE_SOCKET) {\n\t\tlog_socket(f, buffer, sz);\n\t} else {\n\t\tuint32_t ti = (uint32_t)skynet_now();\n\t\tfprintf(f, \":%08x %d %d %u \", source, type, session, ti);\n\t\tlog_blob(f, buffer, sz);\n\t\tfprintf(f,\"\\n\");\n\t\tfflush(f);\n\t}\n}\n"
  },
  {
    "path": "skynet-src/skynet_log.h",
    "content": "#ifndef skynet_log_h\n#define skynet_log_h\n\n#include \"skynet_env.h\"\n#include \"skynet.h\"\n\n#include <stdio.h>\n#include <stdint.h>\n\nFILE * skynet_log_open(struct skynet_context * ctx, uint32_t handle);\nvoid skynet_log_close(struct skynet_context * ctx, FILE *f, uint32_t handle);\nvoid skynet_log_output(FILE *f, uint32_t source, int type, int session, void * buffer, size_t sz);\n\n#endif"
  },
  {
    "path": "skynet-src/skynet_main.c",
    "content": "#include \"skynet.h\"\n\n#include \"skynet_imp.h\"\n#include \"skynet_env.h\"\n#include \"skynet_server.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <lua.h>\n#include <lualib.h>\n#include <lauxlib.h>\n#include <signal.h>\n#include <assert.h>\n\n#ifndef SKYNET_MAXTHREAD\n#define SKYNET_MAXTHREAD 1024\n#endif\n\nstatic int\noptint(const char *key, int opt) {\n\tconst char * str = skynet_getenv(key);\n\tif (str == NULL) {\n\t\tchar tmp[20];\n\t\tsprintf(tmp,\"%d\",opt);\n\t\tskynet_setenv(key, tmp);\n\t\treturn opt;\n\t}\n\treturn strtol(str, NULL, 10);\n}\n\nstatic int\noptboolean(const char *key, int opt) {\n\tconst char * str = skynet_getenv(key);\n\tif (str == NULL) {\n\t\tskynet_setenv(key, opt ? \"true\" : \"false\");\n\t\treturn opt;\n\t}\n\treturn strcmp(str,\"true\")==0;\n}\n\nstatic const char *\noptstring(const char *key,const char * opt) {\n\tconst char * str = skynet_getenv(key);\n\tif (str == NULL) {\n\t\tif (opt) {\n\t\t\tskynet_setenv(key, opt);\n\t\t\topt = skynet_getenv(key);\n\t\t}\n\t\treturn opt;\n\t}\n\treturn str;\n}\n\nstatic void\n_init_env(lua_State *L) {\n\tlua_pushnil(L);  /* first key */\n\twhile (lua_next(L, -2) != 0) {\n\t\tint keyt = lua_type(L, -2);\n\t\tif (keyt != LUA_TSTRING) {\n\t\t\tfprintf(stderr, \"Invalid config table\\n\");\n\t\t\texit(1);\n\t\t}\n\t\tconst char * key = lua_tostring(L,-2);\n\t\tif (lua_type(L,-1) == LUA_TBOOLEAN) {\n\t\t\tint b = lua_toboolean(L,-1);\n\t\t\tskynet_setenv(key,b ? \"true\" : \"false\" );\n\t\t} else {\n\t\t\tconst char * value = lua_tostring(L,-1);\n\t\t\tif (value == NULL) {\n\t\t\t\tfprintf(stderr, \"Invalid config table key = %s\\n\", key);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tskynet_setenv(key,value);\n\t\t}\n\t\tlua_pop(L,1);\n\t}\n\tlua_pop(L,1);\n}\n\nint sigign() {\n\tstruct sigaction sa;\n\tsa.sa_handler = SIG_IGN;\n\tsa.sa_flags = 0;\n\tsigemptyset(&sa.sa_mask);\n\tsigaction(SIGPIPE, &sa, 0);\n\treturn 0;\n}\n\nstatic const char * load_config = \"\\\n\tlocal result = {}\\n\\\n\tlocal function getenv(name) return assert(os.getenv(name), [[os.getenv() failed: ]] .. name) end\\n\\\n\tlocal sep = package.config:sub(1,1)\\n\\\n\tlocal current_path = [[.]]..sep\\n\\\n\tlocal function include(filename)\\n\\\n\t\tlocal last_path = current_path\\n\\\n\t\tlocal path, name = filename:match([[(.*]]..sep..[[)(.*)$]])\\n\\\n\t\tif path then\\n\\\n\t\t\tif path:sub(1,1) == sep then\t-- root\\n\\\n\t\t\t\tcurrent_path = path\\n\\\n\t\t\telse\\n\\\n\t\t\t\tcurrent_path = current_path .. path\\n\\\n\t\t\tend\\n\\\n\t\telse\\n\\\n\t\t\tname = filename\\n\\\n\t\tend\\n\\\n\t\tlocal f = assert(io.open(current_path .. name))\\n\\\n\t\tlocal code = assert(f:read [[*a]])\\n\\\n\t\tcode = string.gsub(code, [[%$([%w_%d]+)]], getenv)\\n\\\n\t\tf:close()\\n\\\n\t\tassert(load(code,[[@]]..filename,[[t]],result))()\\n\\\n\t\tcurrent_path = last_path\\n\\\n\tend\\n\\\n\tsetmetatable(result, { __index = { include = include } })\\n\\\n\tlocal config_name = ...\\n\\\n\tinclude(config_name)\\n\\\n\tsetmetatable(result, nil)\\n\\\n\treturn result\\n\\\n\";\n\nint\nmain(int argc, char *argv[]) {\n\tconst char * config_file = NULL ;\n\tif (argc > 1) {\n\t\tconfig_file = argv[1];\n\t} else {\n\t\tfprintf(stderr, \"Need a config file. Please read skynet wiki : https://github.com/cloudwu/skynet/wiki/Config\\n\"\n\t\t\t\"usage: skynet configfilename\\n\");\n\t\treturn 1;\n\t}\n\n\tskynet_globalinit();\n\tskynet_env_init();\n\n\tsigign();\n\n\tstruct skynet_config config;\n\n#ifdef LUA_CACHELIB\n\t// init the lock of code cache\n\tluaL_initcodecache();\n#endif\n\n\tstruct lua_State *L = luaL_newstate();\n\tluaL_openlibs(L);\t// link lua lib\n\n\tint err =  luaL_loadbufferx(L, load_config, strlen(load_config), \"=[skynet config]\", \"t\");\n\tassert(err == LUA_OK);\n\tlua_pushstring(L, config_file);\n\n\terr = lua_pcall(L, 1, 1, 0);\n\tif (err) {\n\t\tfprintf(stderr,\"%s\\n\",lua_tostring(L,-1));\n\t\tlua_close(L);\n\t\treturn 1;\n\t}\n\t_init_env(L);\n\tlua_close(L);\n\n\tconfig.thread =  optint(\"thread\",8);\n\tif (config.thread < 1 || config.thread > SKYNET_MAXTHREAD) {\n\t\tfprintf(stderr, \"Invalid thread %d , should be in [1,%d]\\n\", config.thread, SKYNET_MAXTHREAD);\n\t\treturn 1;\n\t}\n\tconfig.module_path = optstring(\"cpath\",\"./cservice/?.so\");\n\tconfig.harbor = optint(\"harbor\", 1);\n\tconfig.bootstrap = optstring(\"bootstrap\",\"snlua bootstrap\");\n\tconfig.daemon = optstring(\"daemon\", NULL);\n\tconfig.logger = optstring(\"logger\", NULL);\n\tconfig.logservice = optstring(\"logservice\", \"logger\");\n\tconfig.profile = optboolean(\"profile\", 1);\n\n\tskynet_start(&config);\n\tskynet_globalexit();\n\n\treturn 0;\n}\n"
  },
  {
    "path": "skynet-src/skynet_malloc.h",
    "content": "#ifndef skynet_malloc_h\n#define skynet_malloc_h\n\n#include <stddef.h>\n\n#define skynet_malloc malloc\n#define skynet_calloc calloc\n#define skynet_realloc realloc\n#define skynet_free free\n#define skynet_memalign memalign\n#define skynet_aligned_alloc aligned_alloc\n#define skynet_posix_memalign posix_memalign\n\nvoid * skynet_malloc(size_t sz);\nvoid * skynet_calloc(size_t nmemb,size_t size);\nvoid * skynet_realloc(void *ptr, size_t size);\nvoid skynet_free(void *ptr);\nvoid * skynet_lalloc(void *ptr, size_t osize, size_t nsize);\t// use for lua\nvoid * skynet_memalign(size_t alignment, size_t size);\nvoid * skynet_aligned_alloc(size_t alignment, size_t size);\nint skynet_posix_memalign(void **memptr, size_t alignment, size_t size);\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_module.c",
    "content": "#include \"skynet.h\"\n\n#include \"skynet_imp.h\"\n#include \"skynet_module.h\"\n#include \"spinlock.h\"\n\n#include <assert.h>\n#include <string.h>\n#include <dlfcn.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#define MAX_MODULE_TYPE 32\n\nstruct modules {\n\tint count;\n\tstruct spinlock lock;\n\tconst char * path;\n\tstruct skynet_module m[MAX_MODULE_TYPE];\n};\n\nstatic struct modules * M = NULL;\n\nstatic void *\n_try_open(struct modules *m, const char * name) {\n\tconst char *l;\n\tconst char * path = m->path;\n\tsize_t path_size = strlen(path);\n\tsize_t name_size = strlen(name);\n\n\tint sz = path_size + name_size;\n\t//search path\n\tvoid * dl = NULL;\n\tchar tmp[sz];\n\tdo\n\t{\n\t\tmemset(tmp,0,sz);\n\t\twhile (*path == ';') path++;\n\t\tif (*path == '\\0') break;\n\t\tl = strchr(path, ';');\n\t\tif (l == NULL) l = path + strlen(path);\n\t\tint len = l - path;\n\t\tint i;\n\t\tfor (i=0;path[i]!='?' && i < len ;i++) {\n\t\t\ttmp[i] = path[i];\n\t\t}\n\t\tmemcpy(tmp+i,name,name_size);\n\t\tif (path[i] == '?') {\n\t\t\tstrncpy(tmp+i+name_size,path+i+1,len - i - 1);\n\t\t} else {\n\t\t\tfprintf(stderr,\"Invalid C service path\\n\");\n\t\t\texit(1);\n\t\t}\n\t\tdl = dlopen(tmp, RTLD_NOW | RTLD_GLOBAL);\n\t\tpath = l;\n\t}while(dl == NULL);\n\n\tif (dl == NULL) {\n\t\tfprintf(stderr, \"try open %s failed : %s\\n\",name,dlerror());\n\t}\n\n\treturn dl;\n}\n\nstatic struct skynet_module *\n_query(const char * name) {\n\tint i;\n\tfor (i=0;i<M->count;i++) {\n\t\tif (strcmp(M->m[i].name,name)==0) {\n\t\t\treturn &M->m[i];\n\t\t}\n\t}\n\treturn NULL;\n}\n\nstatic void *\nget_api(struct skynet_module *mod, const char *api_name) {\n\tsize_t name_size = strlen(mod->name);\n\tsize_t api_size = strlen(api_name);\n\tchar tmp[name_size + api_size + 1];\n\tmemcpy(tmp, mod->name, name_size);\n\tmemcpy(tmp+name_size, api_name, api_size+1);\n\tchar *ptr = strrchr(tmp, '.');\n\tif (ptr == NULL) {\n\t\tptr = tmp;\n\t} else {\n\t\tptr = ptr + 1;\n\t}\n\treturn dlsym(mod->module, ptr);\n}\n\nstatic int\nopen_sym(struct skynet_module *mod) {\n\tmod->create = get_api(mod, \"_create\");\n\tmod->init = get_api(mod, \"_init\");\n\tmod->release = get_api(mod, \"_release\");\n\tmod->signal = get_api(mod, \"_signal\");\n\n\treturn mod->init == NULL;\n}\n\nstruct skynet_module *\nskynet_module_query(const char * name) {\n\tstruct skynet_module * result = _query(name);\n\tif (result)\n\t\treturn result;\n\n\tSPIN_LOCK(M)\n\n\tresult = _query(name); // double check\n\n\tif (result == NULL && M->count < MAX_MODULE_TYPE) {\n\t\tint index = M->count;\n\t\tvoid * dl = _try_open(M,name);\n\t\tif (dl) {\n\t\t\tM->m[index].name = name;\n\t\t\tM->m[index].module = dl;\n\n\t\t\tif (open_sym(&M->m[index]) == 0) {\n\t\t\t\tM->m[index].name = skynet_strdup(name);\n\t\t\t\tM->count ++;\n\t\t\t\tresult = &M->m[index];\n\t\t\t}\n\t\t}\n\t}\n\n\tSPIN_UNLOCK(M)\n\n\treturn result;\n}\n\nvoid *\nskynet_module_instance_create(struct skynet_module *m) {\n\tif (m->create) {\n\t\treturn m->create();\n\t} else {\n\t\treturn (void *)(intptr_t)(~0);\n\t}\n}\n\nint\nskynet_module_instance_init(struct skynet_module *m, void * inst, struct skynet_context *ctx, const char * parm) {\n\treturn m->init(inst, ctx, parm);\n}\n\nvoid\nskynet_module_instance_release(struct skynet_module *m, void *inst) {\n\tif (m->release) {\n\t\tm->release(inst);\n\t}\n}\n\nvoid\nskynet_module_instance_signal(struct skynet_module *m, void *inst, int signal) {\n\tif (m->signal) {\n\t\tm->signal(inst, signal);\n\t}\n}\n\nvoid\nskynet_module_init(const char *path) {\n\tstruct modules *m = skynet_malloc(sizeof(*m));\n\tm->count = 0;\n\tm->path = skynet_strdup(path);\n\n\tSPIN_INIT(m)\n\n\tM = m;\n}\n"
  },
  {
    "path": "skynet-src/skynet_module.h",
    "content": "#ifndef SKYNET_MODULE_H\n#define SKYNET_MODULE_H\n\nstruct skynet_context;\n\ntypedef void * (*skynet_dl_create)(void);\ntypedef int (*skynet_dl_init)(void * inst, struct skynet_context *, const char * parm);\ntypedef void (*skynet_dl_release)(void * inst);\ntypedef void (*skynet_dl_signal)(void * inst, int signal);\n\nstruct skynet_module {\n\tconst char * name;\n\tvoid * module;\n\tskynet_dl_create create;\n\tskynet_dl_init init;\n\tskynet_dl_release release;\n\tskynet_dl_signal signal;\n};\n\nstruct skynet_module * skynet_module_query(const char * name);\nvoid * skynet_module_instance_create(struct skynet_module *);\nint skynet_module_instance_init(struct skynet_module *, void * inst, struct skynet_context *ctx, const char * parm);\nvoid skynet_module_instance_release(struct skynet_module *, void *inst);\nvoid skynet_module_instance_signal(struct skynet_module *, void *inst, int signal);\n\nvoid skynet_module_init(const char *path);\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_monitor.c",
    "content": "#include \"skynet.h\"\n\n#include \"skynet_monitor.h\"\n#include \"skynet_server.h\"\n#include \"skynet.h\"\n#include \"atomic.h\"\n\n#include <stdlib.h>\n#include <string.h>\n\nstruct skynet_monitor {\n\tATOM_INT version;\n\tint check_version;\n\tuint32_t source;\n\tuint32_t destination;\n};\n\nstruct skynet_monitor * \nskynet_monitor_new() {\n\tstruct skynet_monitor * ret = skynet_malloc(sizeof(*ret));\n\tmemset(ret, 0, sizeof(*ret));\n\treturn ret;\n}\n\nvoid \nskynet_monitor_delete(struct skynet_monitor *sm) {\n\tskynet_free(sm);\n}\n\nvoid \nskynet_monitor_trigger(struct skynet_monitor *sm, uint32_t source, uint32_t destination) {\n\tsm->source = source;\n\tsm->destination = destination;\n\tATOM_FINC(&sm->version);\n}\n\nvoid \nskynet_monitor_check(struct skynet_monitor *sm) {\n\tif (sm->version == sm->check_version) {\n\t\tif (sm->destination) {\n\t\t\tskynet_context_endless(sm->destination);\n\t\t\tskynet_error(NULL, \"error: A message from [ :%08x ] to [ :%08x ] maybe in an endless loop (version = %d)\", sm->source , sm->destination, sm->version);\n\t\t}\n\t} else {\n\t\tsm->check_version = sm->version;\n\t}\n}\n"
  },
  {
    "path": "skynet-src/skynet_monitor.h",
    "content": "#ifndef SKYNET_MONITOR_H\n#define SKYNET_MONITOR_H\n\n#include <stdint.h>\n\nstruct skynet_monitor;\n\nstruct skynet_monitor * skynet_monitor_new();\nvoid skynet_monitor_delete(struct skynet_monitor *);\nvoid skynet_monitor_trigger(struct skynet_monitor *, uint32_t source, uint32_t destination);\nvoid skynet_monitor_check(struct skynet_monitor *);\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_mq.c",
    "content": "#include \"skynet.h\"\n#include \"skynet_mq.h\"\n#include \"skynet_handle.h\"\n#include \"spinlock.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <stdbool.h>\n\n#define DEFAULT_QUEUE_SIZE 64\n#define MAX_GLOBAL_MQ 0x10000\n\n// 0 means mq is not in global mq.\n// 1 means mq is in global mq , or the message is dispatching.\n\n#define MQ_IN_GLOBAL 1\n#define MQ_OVERLOAD 1024\n\nstruct message_queue {\n\tstruct spinlock lock;\n\tuint32_t handle;\n\tint cap;\n\tint head;\n\tint tail;\n\tint release;\n\tint in_global;\n\tint overload;\n\tint overload_threshold;\n\tstruct skynet_message *queue;\n\tstruct message_queue *next;\n};\n\nstruct global_queue {\n\tstruct message_queue *head;\n\tstruct message_queue *tail;\n\tstruct spinlock lock;\n};\n\nstatic struct global_queue *Q = NULL;\n\nvoid \nskynet_globalmq_push(struct message_queue * queue) {\n\tstruct global_queue *q= Q;\n\n\tSPIN_LOCK(q)\n\tassert(queue->next == NULL);\n\tif(q->tail) {\n\t\tq->tail->next = queue;\n\t\tq->tail = queue;\n\t} else {\n\t\tq->head = q->tail = queue;\n\t}\n\tSPIN_UNLOCK(q)\n}\n\nstruct message_queue * \nskynet_globalmq_pop() {\n\tstruct global_queue *q = Q;\n\n\tSPIN_LOCK(q)\n\tstruct message_queue *mq = q->head;\n\tif(mq) {\n\t\tq->head = mq->next;\n\t\tif(q->head == NULL) {\n\t\t\tassert(mq == q->tail);\n\t\t\tq->tail = NULL;\n\t\t}\n\t\tmq->next = NULL;\n\t}\n\tSPIN_UNLOCK(q)\n\n\treturn mq;\n}\n\nstruct message_queue * \nskynet_mq_create(uint32_t handle) {\n\tstruct message_queue *q = skynet_malloc(sizeof(*q));\n\tq->handle = handle;\n\tq->cap = DEFAULT_QUEUE_SIZE;\n\tq->head = 0;\n\tq->tail = 0;\n\tSPIN_INIT(q)\n\t// When the queue is create (always between service create and service init) ,\n\t// set in_global flag to avoid push it to global queue .\n\t// If the service init success, skynet_context_new will call skynet_mq_push to push it to global queue.\n\tq->in_global = MQ_IN_GLOBAL;\n\tq->release = 0;\n\tq->overload = 0;\n\tq->overload_threshold = MQ_OVERLOAD;\n\tq->queue = skynet_malloc(sizeof(struct skynet_message) * q->cap);\n\tq->next = NULL;\n\n\treturn q;\n}\n\nstatic void \n_release(struct message_queue *q) {\n\tassert(q->next == NULL);\n\tSPIN_DESTROY(q)\n\tskynet_free(q->queue);\n\tskynet_free(q);\n}\n\nuint32_t \nskynet_mq_handle(struct message_queue *q) {\n\treturn q->handle;\n}\n\nint\nskynet_mq_length(struct message_queue *q) {\n\tint head, tail,cap;\n\n\tSPIN_LOCK(q)\n\thead = q->head;\n\ttail = q->tail;\n\tcap = q->cap;\n\tSPIN_UNLOCK(q)\n\t\n\tif (head <= tail) {\n\t\treturn tail - head;\n\t}\n\treturn tail + cap - head;\n}\n\nint\nskynet_mq_overload(struct message_queue *q) {\n\tif (q->overload) {\n\t\tint overload = q->overload;\n\t\tq->overload = 0;\n\t\treturn overload;\n\t} \n\treturn 0;\n}\n\nint\nskynet_mq_pop(struct message_queue *q, struct skynet_message *message) {\n\tint ret = 1;\n\tSPIN_LOCK(q)\n\n\tif (q->head != q->tail) {\n\t\t*message = q->queue[q->head++];\n\t\tret = 0;\n\t\tint head = q->head;\n\t\tint tail = q->tail;\n\t\tint cap = q->cap;\n\n\t\tif (head >= cap) {\n\t\t\tq->head = head = 0;\n\t\t}\n\t\tint length = tail - head;\n\t\tif (length < 0) {\n\t\t\tlength += cap;\n\t\t}\n\t\twhile (length > q->overload_threshold) {\n\t\t\tq->overload = length;\n\t\t\tq->overload_threshold *= 2;\n\t\t}\n\t} else {\n\t\t// reset overload_threshold when queue is empty\n\t\tq->overload_threshold = MQ_OVERLOAD;\n\t}\n\n\tif (ret) {\n\t\tq->in_global = 0;\n\t}\n\t\n\tSPIN_UNLOCK(q)\n\n\treturn ret;\n}\n\nstatic void\nexpand_queue(struct message_queue *q) {\n\tstruct skynet_message *new_queue = skynet_malloc(sizeof(struct skynet_message) * q->cap * 2);\n\tint i;\n\tfor (i=0;i<q->cap;i++) {\n\t\tnew_queue[i] = q->queue[(q->head + i) % q->cap];\n\t}\n\tq->head = 0;\n\tq->tail = q->cap;\n\tq->cap *= 2;\n\t\n\tskynet_free(q->queue);\n\tq->queue = new_queue;\n}\n\nvoid \nskynet_mq_push(struct message_queue *q, struct skynet_message *message) {\n\tassert(message);\n\tSPIN_LOCK(q)\n\n\tq->queue[q->tail] = *message;\n\tif (++ q->tail >= q->cap) {\n\t\tq->tail = 0;\n\t}\n\n\tif (q->head == q->tail) {\n\t\texpand_queue(q);\n\t}\n\n\tif (q->in_global == 0) {\n\t\tq->in_global = MQ_IN_GLOBAL;\n\t\tskynet_globalmq_push(q);\n\t}\n\t\n\tSPIN_UNLOCK(q)\n}\n\nvoid \nskynet_mq_init() {\n\tstruct global_queue *q = skynet_malloc(sizeof(*q));\n\tmemset(q,0,sizeof(*q));\n\tSPIN_INIT(q);\n\tQ=q;\n}\n\nvoid \nskynet_mq_mark_release(struct message_queue *q) {\n\tSPIN_LOCK(q)\n\tassert(q->release == 0);\n\tq->release = 1;\n\tif (q->in_global != MQ_IN_GLOBAL) {\n\t\tskynet_globalmq_push(q);\n\t}\n\tSPIN_UNLOCK(q)\n}\n\nstatic void\n_drop_queue(struct message_queue *q, message_drop drop_func, void *ud) {\n\tstruct skynet_message msg;\n\twhile(!skynet_mq_pop(q, &msg)) {\n\t\tdrop_func(&msg, ud);\n\t}\n\t_release(q);\n}\n\nvoid \nskynet_mq_release(struct message_queue *q, message_drop drop_func, void *ud) {\n\tSPIN_LOCK(q)\n\t\n\tif (q->release) {\n\t\tSPIN_UNLOCK(q)\n\t\t_drop_queue(q, drop_func, ud);\n\t} else {\n\t\tskynet_globalmq_push(q);\n\t\tSPIN_UNLOCK(q)\n\t}\n}\n"
  },
  {
    "path": "skynet-src/skynet_mq.h",
    "content": "#ifndef SKYNET_MESSAGE_QUEUE_H\n#define SKYNET_MESSAGE_QUEUE_H\n\n#include <stdlib.h>\n#include <stdint.h>\n\nstruct skynet_message {\n\tuint32_t source;\n\tint session;\n\tvoid * data;\n\tsize_t sz;\n};\n\n// type is encoding in skynet_message.sz high 8bit\n#define MESSAGE_TYPE_MASK (SIZE_MAX >> 8)\n#define MESSAGE_TYPE_SHIFT ((sizeof(size_t)-1) * 8)\n\nstruct message_queue;\n\nvoid skynet_globalmq_push(struct message_queue * queue);\nstruct message_queue * skynet_globalmq_pop(void);\n\nstruct message_queue * skynet_mq_create(uint32_t handle);\nvoid skynet_mq_mark_release(struct message_queue *q);\n\ntypedef void (*message_drop)(struct skynet_message *, void *);\n\nvoid skynet_mq_release(struct message_queue *q, message_drop drop_func, void *ud);\nuint32_t skynet_mq_handle(struct message_queue *);\n\n// 0 for success\nint skynet_mq_pop(struct message_queue *q, struct skynet_message *message);\nvoid skynet_mq_push(struct message_queue *q, struct skynet_message *message);\n\n// return the length of message queue, for debug\nint skynet_mq_length(struct message_queue *q);\nint skynet_mq_overload(struct message_queue *q);\n\nvoid skynet_mq_init();\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_server.c",
    "content": "#include \"skynet.h\"\n\n#include \"skynet_server.h\"\n#include \"skynet_module.h\"\n#include \"skynet_handle.h\"\n#include \"skynet_mq.h\"\n#include \"skynet_timer.h\"\n#include \"skynet_harbor.h\"\n#include \"skynet_env.h\"\n#include \"skynet_monitor.h\"\n#include \"skynet_imp.h\"\n#include \"skynet_log.h\"\n#include \"spinlock.h\"\n#include \"atomic.h\"\n\n#include <pthread.h>\n\n#include <string.h>\n#include <assert.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdbool.h>\n\n#ifdef CALLING_CHECK\n\n#define CHECKCALLING_BEGIN(ctx) if (!(spinlock_trylock(&ctx->calling))) { assert(0); }\n#define CHECKCALLING_END(ctx) spinlock_unlock(&ctx->calling);\n#define CHECKCALLING_INIT(ctx) spinlock_init(&ctx->calling);\n#define CHECKCALLING_DESTROY(ctx) spinlock_destroy(&ctx->calling);\n#define CHECKCALLING_DECL struct spinlock calling;\n\n#else\n\n#define CHECKCALLING_BEGIN(ctx)\n#define CHECKCALLING_END(ctx)\n#define CHECKCALLING_INIT(ctx)\n#define CHECKCALLING_DESTROY(ctx)\n#define CHECKCALLING_DECL\n\n#endif\n\nstruct skynet_context {\n\tvoid * instance;\n\tstruct skynet_module * mod;\n\tvoid * cb_ud;\n\tskynet_cb cb;\n\tstruct message_queue *queue;\n\tATOM_POINTER logfile;\n\tuint64_t cpu_cost;\t// in microsec\n\tuint64_t cpu_start;\t// in microsec\n\tchar result[32];\n\tuint32_t handle;\n\tint session_id;\n\tATOM_INT ref;\n\tsize_t message_count;\n\tbool init;\n\tbool endless;\n\tbool profile;\n\n\tCHECKCALLING_DECL\n};\n\nstruct skynet_node {\n\tATOM_INT total;\n\tint init;\n\tuint32_t monitor_exit;\n\tpthread_key_t handle_key;\n\tbool profile;\t// default is on\n};\n\nstatic struct skynet_node G_NODE;\n\nint\nskynet_context_total() {\n\treturn ATOM_LOAD(&G_NODE.total);\n}\n\nstatic void\ncontext_inc() {\n\tATOM_FINC(&G_NODE.total);\n}\n\nstatic void\ncontext_dec() {\n\tATOM_FDEC(&G_NODE.total);\n}\n\nuint32_t\nskynet_current_handle(void) {\n\tif (G_NODE.init) {\n\t\tvoid * handle = pthread_getspecific(G_NODE.handle_key);\n\t\treturn (uint32_t)(uintptr_t)handle;\n\t} else {\n\t\tuint32_t v = (uint32_t)(-THREAD_MAIN);\n\t\treturn v;\n\t}\n}\n\nstatic void\nid_to_hex(char * str, uint32_t id) {\n\tint i;\n\tstatic char hex[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };\n\tstr[0] = ':';\n\tfor (i=0;i<8;i++) {\n\t\tstr[i+1] = hex[(id >> ((7-i) * 4))&0xf];\n\t}\n\tstr[9] = '\\0';\n}\n\nstruct drop_t {\n\tuint32_t handle;\n};\n\nstatic void\ndrop_message(struct skynet_message *msg, void *ud) {\n\tstruct drop_t *d = ud;\n\tskynet_free(msg->data);\n\tuint32_t source = d->handle;\n\tassert(source);\n\t// report error to the message source\n\tskynet_send(NULL, source, msg->source, PTYPE_ERROR, msg->session, NULL, 0);\n}\n\nuint32_t\nskynet_context_new(const char * name, const char *param) {\n\tstruct skynet_module * mod = skynet_module_query(name);\n\n\tif (mod == NULL)\n\t\treturn 0;\n\n\tvoid *inst = skynet_module_instance_create(mod);\n\tif (inst == NULL)\n\t\treturn 0;\n\tstruct skynet_context * ctx = skynet_malloc(sizeof(*ctx));\n\tCHECKCALLING_INIT(ctx)\n\n\tctx->mod = mod;\n\tctx->instance = inst;\n\tATOM_INIT(&ctx->ref , 2); // skynet_handle_register + skynet_module_instance_init\n\tctx->cb = NULL;\n\tctx->cb_ud = NULL;\n\tctx->session_id = 0;\n\tATOM_INIT(&ctx->logfile, (uintptr_t)NULL);\n\n\tctx->init = false;\n\tctx->endless = false;\n\n\tctx->cpu_cost = 0;\n\tctx->cpu_start = 0;\n\tctx->message_count = 0;\n\tctx->profile = G_NODE.profile;\n\t// Should set to 0 first to avoid skynet_handle_retireall get an uninitialized handle\n\tctx->handle = 0;\n\tconst uint32_t handle = skynet_handle_register(ctx);\n\tctx->handle = handle;\n\tstruct message_queue * queue = ctx->queue = skynet_mq_create(handle);\n\t// init function maybe use ctx->handle, so it must init at last\n\tcontext_inc();\n\n\tCHECKCALLING_BEGIN(ctx)\n\tint r = skynet_module_instance_init(mod, inst, ctx, param);\n\tCHECKCALLING_END(ctx)\n\tif (r == 0) {\n\t\tctx->init = true;\n\t\tskynet_globalmq_push(queue);\n\t\tskynet_error(ctx, \"LAUNCH %s %s\", name, param ? param : \"\");\n\t\tskynet_context_release(ctx);\n\t\treturn handle;\n\t} else {\n\t\tskynet_error(ctx, \"error: launch %s FAILED\", name);\n\t\tuint32_t handle = ctx->handle;\n\t\tskynet_context_release(ctx);\n\t\tskynet_handle_retire(handle);\n\t\tstruct drop_t d = { handle };\n\t\tskynet_mq_release(queue, drop_message, &d);\n\t\treturn 0;\n\t}\n}\n\nint\nskynet_context_newsession(struct skynet_context *ctx) {\n\t// session always be a positive number\n\tint session = ++ctx->session_id;\n\tif (session <= 0) {\n\t\tctx->session_id = 1;\n\t\treturn 1;\n\t}\n\treturn session;\n}\n\nvoid\nskynet_context_grab(struct skynet_context *ctx) {\n\tATOM_FINC(&ctx->ref);\n}\n\nvoid\nskynet_context_reserve(struct skynet_context *ctx) {\n\tskynet_context_grab(ctx);\n\t// don't count the context reserved, because skynet abort (the worker threads terminate) only when the total context is 0 .\n\t// the reserved context will be release at last.\n\tcontext_dec();\n}\n\nstatic void\ndelete_context(struct skynet_context *ctx) {\n\tFILE *f = (FILE *)ATOM_LOAD(&ctx->logfile);\n\tif (f) {\n\t\tfclose(f);\n\t}\n\tskynet_module_instance_release(ctx->mod, ctx->instance);\n\tskynet_mq_mark_release(ctx->queue);\n\tCHECKCALLING_DESTROY(ctx)\n\tskynet_free(ctx);\n\tcontext_dec();\n}\n\nvoid\nskynet_context_release(struct skynet_context *ctx) {\n\tif (ATOM_FDEC(&ctx->ref) == 1) {\n\t\tdelete_context(ctx);\n\t}\n}\n\nint\nskynet_context_push(uint32_t handle, struct skynet_message *message) {\n\tstruct skynet_context * ctx = skynet_handle_grab(handle);\n\tif (ctx == NULL) {\n\t\treturn -1;\n\t}\n\tskynet_mq_push(ctx->queue, message);\n\tskynet_context_release(ctx);\n\n\treturn 0;\n}\n\nvoid\nskynet_context_endless(uint32_t handle) {\n\tstruct skynet_context * ctx = skynet_handle_grab(handle);\n\tif (ctx == NULL) {\n\t\treturn;\n\t}\n\tctx->endless = true;\n\tskynet_context_release(ctx);\n}\n\nint\nskynet_isremote(struct skynet_context * ctx, uint32_t handle, int * harbor) {\n\tint ret = skynet_harbor_message_isremote(handle);\n\tif (harbor) {\n\t\t*harbor = (int)(handle >> HANDLE_REMOTE_SHIFT);\n\t}\n\treturn ret;\n}\n\nstatic void\ndispatch_message(struct skynet_context *ctx, struct skynet_message *msg) {\n\tassert(ctx->init);\n\tCHECKCALLING_BEGIN(ctx)\n\tpthread_setspecific(G_NODE.handle_key, (void *)(uintptr_t)(ctx->handle));\n\tint type = msg->sz >> MESSAGE_TYPE_SHIFT;\n\tsize_t sz = msg->sz & MESSAGE_TYPE_MASK;\n\tFILE *f = (FILE *)ATOM_LOAD(&ctx->logfile);\n\tif (f) {\n\t\tskynet_log_output(f, msg->source, type, msg->session, msg->data, sz);\n\t}\n\t++ctx->message_count;\n\tint reserve_msg;\n\tif (ctx->profile) {\n\t\tctx->cpu_start = skynet_thread_time();\n\t\treserve_msg = ctx->cb(ctx, ctx->cb_ud, type, msg->session, msg->source, msg->data, sz);\n\t\tuint64_t cost_time = skynet_thread_time() - ctx->cpu_start;\n\t\tctx->cpu_cost += cost_time;\n\t} else {\n\t\treserve_msg = ctx->cb(ctx, ctx->cb_ud, type, msg->session, msg->source, msg->data, sz);\n\t}\n\tif (!reserve_msg) {\n\t\tskynet_free(msg->data);\n\t}\n\tCHECKCALLING_END(ctx)\n}\n\nvoid\nskynet_context_dispatchall(struct skynet_context * ctx) {\n\t// for skynet_error\n\tstruct skynet_message msg;\n\tstruct message_queue *q = ctx->queue;\n\twhile (!skynet_mq_pop(q,&msg)) {\n\t\tdispatch_message(ctx, &msg);\n\t}\n}\n\nstruct message_queue *\nskynet_context_message_dispatch(struct skynet_monitor *sm, struct message_queue *q, int weight) {\n\tif (q == NULL) {\n\t\tq = skynet_globalmq_pop();\n\t\tif (q==NULL)\n\t\t\treturn NULL;\n\t}\n\n\tuint32_t handle = skynet_mq_handle(q);\n\n\tstruct skynet_context * ctx = skynet_handle_grab(handle);\n\tif (ctx == NULL) {\n\t\tstruct drop_t d = { handle };\n\t\tskynet_mq_release(q, drop_message, &d);\n\t\treturn skynet_globalmq_pop();\n\t}\n\n\tint i,n=1;\n\tstruct skynet_message msg;\n\n\tfor (i=0;i<n;i++) {\n\t\tif (skynet_mq_pop(q,&msg)) {\n\t\t\tskynet_context_release(ctx);\n\t\t\treturn skynet_globalmq_pop();\n\t\t} else if (i==0 && weight >= 0) {\n\t\t\tn = skynet_mq_length(q);\n\t\t\tn >>= weight;\n\t\t}\n\t\tint overload = skynet_mq_overload(q);\n\t\tif (overload) {\n\t\t\tskynet_error(ctx, \"error: May overload, message queue length = %d\", overload);\n\t\t}\n\n\t\tskynet_monitor_trigger(sm, msg.source , handle);\n\n\t\tif (ctx->cb == NULL) {\n\t\t\tskynet_free(msg.data);\n\t\t} else {\n\t\t\tdispatch_message(ctx, &msg);\n\t\t}\n\n\t\tskynet_monitor_trigger(sm, 0,0);\n\t}\n\n\tassert(q == ctx->queue);\n\tstruct message_queue *nq = skynet_globalmq_pop();\n\tif (nq) {\n\t\t// If global mq is not empty , push q back, and return next queue (nq)\n\t\t// Else (global mq is empty or block, don't push q back, and return q again (for next dispatch)\n\t\tskynet_globalmq_push(q);\n\t\tq = nq;\n\t}\n\tskynet_context_release(ctx);\n\n\treturn q;\n}\n\nstatic void\ncopy_name(char name[GLOBALNAME_LENGTH], const char * addr) {\n\tint i;\n\tfor (i=0;i<GLOBALNAME_LENGTH && addr[i];i++) {\n\t\tname[i] = addr[i];\n\t}\n\tfor (;i<GLOBALNAME_LENGTH;i++) {\n\t\tname[i] = '\\0';\n\t}\n}\n\nuint32_t\nskynet_queryname(struct skynet_context * context, const char * name) {\n\tswitch(name[0]) {\n\tcase ':':\n\t\treturn strtoul(name+1,NULL,16);\n\tcase '.':\n\t\treturn skynet_handle_findname(name + 1);\n\t}\n\tskynet_error(context, \"error: Don't support query global name %s\",name);\n\treturn 0;\n}\n\nstatic void\nhandle_exit(struct skynet_context * context, uint32_t handle) {\n\tif (handle == 0) {\n\t\thandle = context->handle;\n\t\tskynet_error(context, \"KILL self\");\n\t} else {\n\t\tskynet_error(context, \"KILL :%0x\", handle);\n\t}\n\tif (G_NODE.monitor_exit) {\n\t\tskynet_send(context,  handle, G_NODE.monitor_exit, PTYPE_CLIENT, 0, NULL, 0);\n\t}\n\tskynet_handle_retire(handle);\n}\n\n// skynet command\n\nstruct command_func {\n\tconst char *name;\n\tconst char * (*func)(struct skynet_context * context, const char * param);\n};\n\nstatic const char *\ncmd_timeout(struct skynet_context * context, const char * param) {\n\tchar * session_ptr = NULL;\n\tint ti = strtol(param, &session_ptr, 10);\n\tint session = skynet_context_newsession(context);\n\tskynet_timeout(context->handle, ti, session);\n\tsprintf(context->result, \"%d\", session);\n\treturn context->result;\n}\n\nstatic const char *\ncmd_reg(struct skynet_context * context, const char * param) {\n\tif (param == NULL || param[0] == '\\0') {\n\t\tsprintf(context->result, \":%x\", context->handle);\n\t\treturn context->result;\n\t} else if (param[0] == '.') {\n\t\treturn skynet_handle_namehandle(context->handle, param + 1);\n\t} else {\n\t\tskynet_error(context, \"error: Can't register global name %s in C\", param);\n\t\treturn NULL;\n\t}\n}\n\nstatic const char *\ncmd_query(struct skynet_context * context, const char * param) {\n\tif (param[0] == '.') {\n\t\tuint32_t handle = skynet_handle_findname(param+1);\n\t\tif (handle) {\n\t\t\tsprintf(context->result, \":%x\", handle);\n\t\t\treturn context->result;\n\t\t}\n\t}\n\treturn NULL;\n}\n\nstatic const char *\ncmd_name(struct skynet_context * context, const char * param) {\n\tint size = strlen(param);\n\tchar name[size+1];\n\tchar handle[size+1];\n\tsscanf(param,\"%s %s\",name,handle);\n\tif (handle[0] != ':') {\n\t\treturn NULL;\n\t}\n\tuint32_t handle_id = strtoul(handle+1, NULL, 16);\n\tif (handle_id == 0) {\n\t\treturn NULL;\n\t}\n\tif (name[0] == '.') {\n\t\treturn skynet_handle_namehandle(handle_id, name + 1);\n\t} else {\n\t\tskynet_error(context, \"error: Can't set global name %s in C\", name);\n\t}\n\treturn NULL;\n}\n\nstatic const char *\ncmd_exit(struct skynet_context * context, const char * param) {\n\thandle_exit(context, 0);\n\treturn NULL;\n}\n\nstatic uint32_t\ntohandle(struct skynet_context * context, const char * param) {\n\tuint32_t handle = 0;\n\tif (param[0] == ':') {\n\t\thandle = strtoul(param+1, NULL, 16);\n\t} else if (param[0] == '.') {\n\t\thandle = skynet_handle_findname(param+1);\n\t} else {\n\t\tskynet_error(context, \"error: Can't convert %s to handle\",param);\n\t}\n\n\treturn handle;\n}\n\nstatic const char *\ncmd_kill(struct skynet_context * context, const char * param) {\n\tuint32_t handle = tohandle(context, param);\n\tif (handle) {\n\t\thandle_exit(context, handle);\n\t}\n\treturn NULL;\n}\n\nstatic const char *\ncmd_launch(struct skynet_context * context, const char * param) {\n\tsize_t sz = strlen(param);\n\tchar tmp[sz+1];\n\tstrcpy(tmp,param);\n\tchar * args = tmp;\n\tchar * mod = strsep(&args, \" \\t\\r\\n\");\n\targs = strsep(&args, \"\\r\\n\");\n\tconst uint32_t handle = skynet_context_new(mod,args);\n\tif (handle == 0) {\n\t\treturn NULL;\n\t} else {\n\t\tid_to_hex(context->result, handle);\n\t\treturn context->result;\n\t}\n}\n\nstatic const char *\ncmd_getenv(struct skynet_context * context, const char * param) {\n\treturn skynet_getenv(param);\n}\n\nstatic const char *\ncmd_setenv(struct skynet_context * context, const char * param) {\n\tsize_t sz = strlen(param);\n\tchar key[sz+1];\n\tint i;\n\tfor (i=0;param[i] != ' ' && param[i];i++) {\n\t\tkey[i] = param[i];\n\t}\n\tif (param[i] == '\\0')\n\t\treturn NULL;\n\n\tkey[i] = '\\0';\n\tparam += i+1;\n\n\tskynet_setenv(key,param);\n\treturn NULL;\n}\n\nstatic const char *\ncmd_starttime(struct skynet_context * context, const char * param) {\n\tuint32_t sec = skynet_starttime();\n\tsprintf(context->result,\"%u\",sec);\n\treturn context->result;\n}\n\nstatic const char *\ncmd_abort(struct skynet_context * context, const char * param) {\n\tskynet_handle_retireall();\n\treturn NULL;\n}\n\nstatic const char *\ncmd_monitor(struct skynet_context * context, const char * param) {\n\tuint32_t handle=0;\n\tif (param == NULL || param[0] == '\\0') {\n\t\tif (G_NODE.monitor_exit) {\n\t\t\t// return current monitor serivce\n\t\t\tsprintf(context->result, \":%x\", G_NODE.monitor_exit);\n\t\t\treturn context->result;\n\t\t}\n\t\treturn NULL;\n\t} else {\n\t\thandle = tohandle(context, param);\n\t}\n\tG_NODE.monitor_exit = handle;\n\treturn NULL;\n}\n\nstatic const char *\ncmd_stat(struct skynet_context * context, const char * param) {\n\tif (strcmp(param, \"mqlen\") == 0) {\n\t\tint len = skynet_mq_length(context->queue);\n\t\tsprintf(context->result, \"%d\", len);\n\t} else if (strcmp(param, \"endless\") == 0) {\n\t\tif (context->endless) {\n\t\t\tstrcpy(context->result, \"1\");\n\t\t\tcontext->endless = false;\n\t\t} else {\n\t\t\tstrcpy(context->result, \"0\");\n\t\t}\n\t} else if (strcmp(param, \"cpu\") == 0) {\n\t\tdouble t = (double)context->cpu_cost / 1000000.0;\t// microsec\n\t\tsprintf(context->result, \"%lf\", t);\n\t} else if (strcmp(param, \"time\") == 0) {\n\t\tif (context->profile) {\n\t\t\tuint64_t ti = skynet_thread_time() - context->cpu_start;\n\t\t\tdouble t = (double)ti / 1000000.0;\t// microsec\n\t\t\tsprintf(context->result, \"%lf\", t);\n\t\t} else {\n\t\t\tstrcpy(context->result, \"0\");\n\t\t}\n\t} else if (strcmp(param, \"message\") == 0) {\n\t\tsprintf(context->result, \"%zu\", context->message_count);\n\t} else {\n\t\tcontext->result[0] = '\\0';\n\t}\n\treturn context->result;\n}\n\nstatic const char *\ncmd_logon(struct skynet_context * context, const char * param) {\n\tuint32_t handle = tohandle(context, param);\n\tif (handle == 0)\n\t\treturn NULL;\n\tstruct skynet_context * ctx = skynet_handle_grab(handle);\n\tif (ctx == NULL)\n\t\treturn NULL;\n\tFILE *f = NULL;\n\tFILE * lastf = (FILE *)ATOM_LOAD(&ctx->logfile);\n\tif (lastf == NULL) {\n\t\tf = skynet_log_open(context, handle);\n\t\tif (f) {\n\t\t\tif (!ATOM_CAS_POINTER(&ctx->logfile, 0, (uintptr_t)f)) {\n\t\t\t\t// logfile opens in other thread, close this one.\n\t\t\t\tfclose(f);\n\t\t\t}\n\t\t}\n\t}\n\tskynet_context_release(ctx);\n\treturn NULL;\n}\n\nstatic const char *\ncmd_logoff(struct skynet_context * context, const char * param) {\n\tuint32_t handle = tohandle(context, param);\n\tif (handle == 0)\n\t\treturn NULL;\n\tstruct skynet_context * ctx = skynet_handle_grab(handle);\n\tif (ctx == NULL)\n\t\treturn NULL;\n\tFILE * f = (FILE *)ATOM_LOAD(&ctx->logfile);\n\tif (f) {\n\t\t// logfile may close in other thread\n\t\tif (ATOM_CAS_POINTER(&ctx->logfile, (uintptr_t)f, (uintptr_t)NULL)) {\n\t\t\tskynet_log_close(context, f, handle);\n\t\t}\n\t}\n\tskynet_context_release(ctx);\n\treturn NULL;\n}\n\nstatic const char *\ncmd_signal(struct skynet_context * context, const char * param) {\n\tuint32_t handle = tohandle(context, param);\n\tif (handle == 0)\n\t\treturn NULL;\n\tstruct skynet_context * ctx = skynet_handle_grab(handle);\n\tif (ctx == NULL)\n\t\treturn NULL;\n\tparam = strchr(param, ' ');\n\tint sig = 0;\n\tif (param) {\n\t\tsig = strtol(param, NULL, 0);\n\t}\n\t// NOTICE: the signal function should be thread safe.\n\tskynet_module_instance_signal(ctx->mod, ctx->instance, sig);\n\n\tskynet_context_release(ctx);\n\treturn NULL;\n}\n\nstatic struct command_func cmd_funcs[] = {\n\t{ \"TIMEOUT\", cmd_timeout },\n\t{ \"REG\", cmd_reg },\n\t{ \"QUERY\", cmd_query },\n\t{ \"NAME\", cmd_name },\n\t{ \"EXIT\", cmd_exit },\n\t{ \"KILL\", cmd_kill },\n\t{ \"LAUNCH\", cmd_launch },\n\t{ \"GETENV\", cmd_getenv },\n\t{ \"SETENV\", cmd_setenv },\n\t{ \"STARTTIME\", cmd_starttime },\n\t{ \"ABORT\", cmd_abort },\n\t{ \"MONITOR\", cmd_monitor },\n\t{ \"STAT\", cmd_stat },\n\t{ \"LOGON\", cmd_logon },\n\t{ \"LOGOFF\", cmd_logoff },\n\t{ \"SIGNAL\", cmd_signal },\n\t{ NULL, NULL },\n};\n\nconst char *\nskynet_command(struct skynet_context * context, const char * cmd , const char * param) {\n\tstruct command_func * method = &cmd_funcs[0];\n\twhile(method->name) {\n\t\tif (strcmp(cmd, method->name) == 0) {\n\t\t\treturn method->func(context, param);\n\t\t}\n\t\t++method;\n\t}\n\n\treturn NULL;\n}\n\nstatic void\n_filter_args(struct skynet_context * context, int type, int *session, void ** data, size_t * sz) {\n\tint needcopy = !(type & PTYPE_TAG_DONTCOPY);\n\tint allocsession = type & PTYPE_TAG_ALLOCSESSION;\n\ttype &= 0xff;\n\n\tif (allocsession) {\n\t\tassert(*session == 0);\n\t\t*session = skynet_context_newsession(context);\n\t}\n\n\tif (needcopy && *data) {\n\t\tchar * msg = skynet_malloc(*sz+1);\n\t\tmemcpy(msg, *data, *sz);\n\t\tmsg[*sz] = '\\0';\n\t\t*data = msg;\n\t}\n\n\t*sz |= (size_t)type << MESSAGE_TYPE_SHIFT;\n}\n\nint\nskynet_send(struct skynet_context * context, uint32_t source, uint32_t destination , int type, int session, void * data, size_t sz) {\n\tif ((sz & MESSAGE_TYPE_MASK) != sz) {\n\t\tskynet_error(context, \"error: The message to %x is too large\", destination);\n\t\tif (type & PTYPE_TAG_DONTCOPY) {\n\t\t\tskynet_free(data);\n\t\t}\n\t\treturn -2;\n\t}\n\t_filter_args(context, type, &session, (void **)&data, &sz);\n\n\tif (source == 0) {\n\t\tsource = context->handle;\n\t}\n\n\tif (destination == 0) {\n\t\tif (data) {\n\t\t\tskynet_error(context, \"error: Destination address can't be 0\");\n\t\t\tskynet_free(data);\n\t\t\treturn -1;\n\t\t}\n\n\t\treturn session;\n\t}\n\tif (skynet_harbor_message_isremote(destination)) {\n\t\tstruct remote_message * rmsg = skynet_malloc(sizeof(*rmsg));\n\t\trmsg->destination.handle = destination;\n\t\trmsg->message = data;\n\t\trmsg->sz = sz & MESSAGE_TYPE_MASK;\n\t\trmsg->type = sz >> MESSAGE_TYPE_SHIFT;\n\t\tskynet_harbor_send(rmsg, source, session);\n\t} else {\n\t\tstruct skynet_message smsg;\n\t\tsmsg.source = source;\n\t\tsmsg.session = session;\n\t\tsmsg.data = data;\n\t\tsmsg.sz = sz;\n\n\t\tif (skynet_context_push(destination, &smsg)) {\n\t\t\tskynet_free(data);\n\t\t\treturn -1;\n\t\t}\n\t}\n\treturn session;\n}\n\nint\nskynet_sendname(struct skynet_context * context, uint32_t source, const char * addr , int type, int session, void * data, size_t sz) {\n\tif (source == 0) {\n\t\tsource = context->handle;\n\t}\n\tuint32_t des = 0;\n\tif (addr[0] == ':') {\n\t\tdes = strtoul(addr+1, NULL, 16);\n\t} else if (addr[0] == '.') {\n\t\tdes = skynet_handle_findname(addr + 1);\n\t\tif (des == 0) {\n\t\t\tif (type & PTYPE_TAG_DONTCOPY) {\n\t\t\t\tskynet_free(data);\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t} else {\n\t\tif ((sz & MESSAGE_TYPE_MASK) != sz) {\n\t\t\tskynet_error(context, \"error: The message to %s is too large\", addr);\n\t\t\tif (type & PTYPE_TAG_DONTCOPY) {\n\t\t\t\tskynet_free(data);\n\t\t\t}\n\t\t\treturn -2;\n\t\t}\n\t\t_filter_args(context, type, &session, (void **)&data, &sz);\n\n\t\tstruct remote_message * rmsg = skynet_malloc(sizeof(*rmsg));\n\t\tcopy_name(rmsg->destination.name, addr);\n\t\trmsg->destination.handle = 0;\n\t\trmsg->message = data;\n\t\trmsg->sz = sz & MESSAGE_TYPE_MASK;\n\t\trmsg->type = sz >> MESSAGE_TYPE_SHIFT;\n\n\t\tskynet_harbor_send(rmsg, source, session);\n\t\treturn session;\n\t}\n\n\treturn skynet_send(context, source, des, type, session, data, sz);\n}\n\nuint32_t\nskynet_context_handle(struct skynet_context *ctx) {\n\treturn ctx->handle;\n}\n\nvoid\nskynet_callback(struct skynet_context * context, void *ud, skynet_cb cb) {\n\tcontext->cb = cb;\n\tcontext->cb_ud = ud;\n}\n\nvoid\nskynet_context_send(struct skynet_context * ctx, void * msg, size_t sz, uint32_t source, int type, int session) {\n\tstruct skynet_message smsg;\n\tsmsg.source = source;\n\tsmsg.session = session;\n\tsmsg.data = msg;\n\tsmsg.sz = sz | (size_t)type << MESSAGE_TYPE_SHIFT;\n\n\tskynet_mq_push(ctx->queue, &smsg);\n}\n\nvoid\nskynet_globalinit(void) {\n\tATOM_INIT(&G_NODE.total , 0);\n\tG_NODE.monitor_exit = 0;\n\tG_NODE.init = 1;\n\tif (pthread_key_create(&G_NODE.handle_key, NULL)) {\n\t\tfprintf(stderr, \"pthread_key_create failed\");\n\t\texit(1);\n\t}\n\t// set mainthread's key\n\tskynet_initthread(THREAD_MAIN);\n}\n\nvoid\nskynet_globalexit(void) {\n\tpthread_key_delete(G_NODE.handle_key);\n}\n\nvoid\nskynet_initthread(int m) {\n\tuintptr_t v = (uint32_t)(-m);\n\tpthread_setspecific(G_NODE.handle_key, (void *)v);\n}\n\nvoid\nskynet_profile_enable(int enable) {\n\tG_NODE.profile = (bool)enable;\n}\n"
  },
  {
    "path": "skynet-src/skynet_server.h",
    "content": "#ifndef SKYNET_SERVER_H\n#define SKYNET_SERVER_H\n\n#include <stdint.h>\n#include <stdlib.h>\n\nstruct skynet_context;\nstruct skynet_message;\nstruct skynet_monitor;\n\nuint32_t skynet_context_new(const char * name, const char * parm);\nvoid skynet_context_grab(struct skynet_context *);\nvoid skynet_context_reserve(struct skynet_context *ctx);\nvoid skynet_context_release(struct skynet_context *);\nuint32_t skynet_context_handle(struct skynet_context *);\nint skynet_context_push(uint32_t handle, struct skynet_message *message);\nvoid skynet_context_send(struct skynet_context * context, void * msg, size_t sz, uint32_t source, int type, int session);\nint skynet_context_newsession(struct skynet_context *);\nstruct message_queue * skynet_context_message_dispatch(struct skynet_monitor *, struct message_queue *, int weight);\t// return next queue\nint skynet_context_total();\nvoid skynet_context_dispatchall(struct skynet_context * context);\t// for skynet_error output before exit\n\nvoid skynet_context_endless(uint32_t handle);\t// for monitor\n\nvoid skynet_globalinit(void);\nvoid skynet_globalexit(void);\nvoid skynet_initthread(int m);\n\nvoid skynet_profile_enable(int enable);\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_socket.c",
    "content": "#include \"skynet.h\"\n\n#include \"skynet_socket.h\"\n#include \"socket_server.h\"\n#include \"skynet_server.h\"\n#include \"skynet_mq.h\"\n#include \"skynet_harbor.h\"\n\n#include <assert.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n\nstatic struct socket_server * SOCKET_SERVER = NULL;\n\nvoid \nskynet_socket_init() {\n\tSOCKET_SERVER = socket_server_create(skynet_now());\n}\n\nvoid\nskynet_socket_exit() {\n\tsocket_server_exit(SOCKET_SERVER);\n}\n\nvoid\nskynet_socket_free() {\n\tsocket_server_release(SOCKET_SERVER);\n\tSOCKET_SERVER = NULL;\n}\n\nvoid\nskynet_socket_updatetime() {\n\tsocket_server_updatetime(SOCKET_SERVER, skynet_now());\n}\n\n// mainloop thread\nstatic void\nforward_message(int type, bool padding, struct socket_message * result) {\n\tstruct skynet_socket_message *sm;\n\tsize_t sz = sizeof(*sm);\n\tif (padding) {\n\t\tif (result->data) {\n\t\t\tsize_t msg_sz = strlen(result->data);\n\t\t\tif (msg_sz > 128) {\n\t\t\t\tmsg_sz = 128;\n\t\t\t}\n\t\t\tsz += msg_sz;\n\t\t} else {\n\t\t\tresult->data = \"\";\n\t\t}\n\t}\n\tsm = (struct skynet_socket_message *)skynet_malloc(sz);\n\tsm->type = type;\n\tsm->id = result->id;\n\tsm->ud = result->ud;\n\tif (padding) {\n\t\tsm->buffer = NULL;\n\t\tmemcpy(sm+1, result->data, sz - sizeof(*sm));\n\t} else {\n\t\tsm->buffer = result->data;\n\t}\n\n\tstruct skynet_message message;\n\tmessage.source = 0;\n\tmessage.session = 0;\n\tmessage.data = sm;\n\tmessage.sz = sz | ((size_t)PTYPE_SOCKET << MESSAGE_TYPE_SHIFT);\n\t\n\tif (skynet_context_push((uint32_t)result->opaque, &message)) {\n\t\t// todo: report somewhere to close socket\n\t\t// don't call skynet_socket_close here (It will block mainloop)\n\t\tskynet_free(sm->buffer);\n\t\tskynet_free(sm);\n\t}\n}\n\nint \nskynet_socket_poll() {\n\tstruct socket_server *ss = SOCKET_SERVER;\n\tassert(ss);\n\tstruct socket_message result;\n\tint more = 1;\n\tint type = socket_server_poll(ss, &result, &more);\n\tswitch (type) {\n\tcase SOCKET_EXIT:\n\t\treturn 0;\n\tcase SOCKET_DATA:\n\t\tforward_message(SKYNET_SOCKET_TYPE_DATA, false, &result);\n\t\tbreak;\n\tcase SOCKET_CLOSE:\n\t\tforward_message(SKYNET_SOCKET_TYPE_CLOSE, false, &result);\n\t\tbreak;\n\tcase SOCKET_OPEN:\n\t\tforward_message(SKYNET_SOCKET_TYPE_CONNECT, true, &result);\n\t\tbreak;\n\tcase SOCKET_ERR:\n\t\tforward_message(SKYNET_SOCKET_TYPE_ERROR, true, &result);\n\t\tbreak;\n\tcase SOCKET_ACCEPT:\n\t\tforward_message(SKYNET_SOCKET_TYPE_ACCEPT, true, &result);\n\t\tbreak;\n\tcase SOCKET_UDP:\n\t\tforward_message(SKYNET_SOCKET_TYPE_UDP, false, &result);\n\t\tbreak;\n\tcase SOCKET_WARNING:\n\t\tforward_message(SKYNET_SOCKET_TYPE_WARNING, false, &result);\n\t\tbreak;\n\tdefault:\n\t\tskynet_error(NULL, \"error: Unknown socket message type %d.\",type);\n\t\treturn -1;\n\t}\n\tif (more) {\n\t\treturn -1;\n\t}\n\treturn 1;\n}\n\nint\nskynet_socket_sendbuffer(struct skynet_context *ctx, struct socket_sendbuffer *buffer) {\n\treturn socket_server_send(SOCKET_SERVER, buffer);\n}\n\nint\nskynet_socket_sendbuffer_lowpriority(struct skynet_context *ctx, struct socket_sendbuffer *buffer) {\n\treturn socket_server_send_lowpriority(SOCKET_SERVER, buffer);\n}\n\nint \nskynet_socket_listen(struct skynet_context *ctx, const char *host, int port, int backlog) {\n\tuint32_t source = skynet_context_handle(ctx);\n\treturn socket_server_listen(SOCKET_SERVER, source, host, port, backlog);\n}\n\nint \nskynet_socket_connect(struct skynet_context *ctx, const char *host, int port) {\n\tuint32_t source = skynet_context_handle(ctx);\n\treturn socket_server_connect(SOCKET_SERVER, source, host, port);\n}\n\nint \nskynet_socket_bind(struct skynet_context *ctx, int fd) {\n\tuint32_t source = skynet_context_handle(ctx);\n\treturn socket_server_bind(SOCKET_SERVER, source, fd);\n}\n\nvoid \nskynet_socket_close(struct skynet_context *ctx, int id) {\n\tuint32_t source = skynet_context_handle(ctx);\n\tsocket_server_close(SOCKET_SERVER, source, id);\n}\n\nvoid \nskynet_socket_shutdown(struct skynet_context *ctx, int id) {\n\tuint32_t source = skynet_context_handle(ctx);\n\tsocket_server_shutdown(SOCKET_SERVER, source, id);\n}\n\nvoid \nskynet_socket_start(struct skynet_context *ctx, int id) {\n\tuint32_t source = skynet_context_handle(ctx);\n\tsocket_server_start(SOCKET_SERVER, source, id);\n}\n\nvoid\nskynet_socket_pause(struct skynet_context *ctx, int id) {\n\tuint32_t source = skynet_context_handle(ctx);\n\tsocket_server_pause(SOCKET_SERVER, source, id);\n}\n\n\nvoid\nskynet_socket_nodelay(struct skynet_context *ctx, int id) {\n\tsocket_server_nodelay(SOCKET_SERVER, id);\n}\n\nint \nskynet_socket_udp(struct skynet_context *ctx, const char * addr, int port) {\n\tuint32_t source = skynet_context_handle(ctx);\n\treturn socket_server_udp(SOCKET_SERVER, source, addr, port);\n}\n\nint\nskynet_socket_udp_dial(struct skynet_context *ctx, const char * addr, int port){\n\tuint32_t source = skynet_context_handle(ctx);\n\treturn socket_server_udp_dial(SOCKET_SERVER, source, addr, port);\n}\n\nint\nskynet_socket_udp_listen(struct skynet_context *ctx, const char * addr, int port){\n\tuint32_t source = skynet_context_handle(ctx);\n\treturn socket_server_udp_listen(SOCKET_SERVER, source, addr, port);\n}\n\nint \nskynet_socket_udp_connect(struct skynet_context *ctx, int id, const char * addr, int port) {\n\treturn socket_server_udp_connect(SOCKET_SERVER, id, addr, port);\n}\n\nint \nskynet_socket_udp_sendbuffer(struct skynet_context *ctx, const char * address, struct socket_sendbuffer *buffer) {\n\treturn socket_server_udp_send(SOCKET_SERVER, (const struct socket_udp_address *)address, buffer);\n}\n\nconst char *\nskynet_socket_udp_address(struct skynet_socket_message *msg, int *addrsz) {\n\tif (msg->type != SKYNET_SOCKET_TYPE_UDP) {\n\t\treturn NULL;\n\t}\n\tstruct socket_message sm;\n\tsm.id = msg->id;\n\tsm.opaque = 0;\n\tsm.ud = msg->ud;\n\tsm.data = msg->buffer;\n\treturn (const char *)socket_server_udp_address(SOCKET_SERVER, &sm, addrsz);\n}\n\nstruct socket_info *\nskynet_socket_info() {\n\treturn socket_server_info(SOCKET_SERVER);\n}\n"
  },
  {
    "path": "skynet-src/skynet_socket.h",
    "content": "#ifndef skynet_socket_h\n#define skynet_socket_h\n\n#include \"socket_info.h\"\n#include \"socket_buffer.h\"\n\nstruct skynet_context;\n\n#define SKYNET_SOCKET_TYPE_DATA 1\n#define SKYNET_SOCKET_TYPE_CONNECT 2\n#define SKYNET_SOCKET_TYPE_CLOSE 3\n#define SKYNET_SOCKET_TYPE_ACCEPT 4\n#define SKYNET_SOCKET_TYPE_ERROR 5\n#define SKYNET_SOCKET_TYPE_UDP 6\n#define SKYNET_SOCKET_TYPE_WARNING 7\n\nstruct skynet_socket_message {\n\tint type;\n\tint id;\n\tint ud;\n\tchar * buffer;\n};\n\nvoid skynet_socket_init();\nvoid skynet_socket_exit();\nvoid skynet_socket_free();\nint skynet_socket_poll();\nvoid skynet_socket_updatetime();\n\nint skynet_socket_sendbuffer(struct skynet_context *ctx, struct socket_sendbuffer *buffer);\nint skynet_socket_sendbuffer_lowpriority(struct skynet_context *ctx, struct socket_sendbuffer *buffer);\nint skynet_socket_listen(struct skynet_context *ctx, const char *host, int port, int backlog);\nint skynet_socket_connect(struct skynet_context *ctx, const char *host, int port);\nint skynet_socket_bind(struct skynet_context *ctx, int fd);\nvoid skynet_socket_close(struct skynet_context *ctx, int id);\nvoid skynet_socket_shutdown(struct skynet_context *ctx, int id);\nvoid skynet_socket_start(struct skynet_context *ctx, int id);\nvoid skynet_socket_pause(struct skynet_context *ctx, int id);\nvoid skynet_socket_nodelay(struct skynet_context *ctx, int id);\n\nint skynet_socket_udp(struct skynet_context *ctx, const char * addr, int port);\nint skynet_socket_udp_connect(struct skynet_context *ctx, int id, const char * addr, int port);\nint skynet_socket_udp_dial(struct skynet_context *ctx, const char * addr, int port);\nint skynet_socket_udp_listen(struct skynet_context *ctx, const char * addr, int port);\nint skynet_socket_udp_sendbuffer(struct skynet_context *ctx, const char * address, struct socket_sendbuffer *buffer);\nconst char * skynet_socket_udp_address(struct skynet_socket_message *, int *addrsz);\n\nstruct socket_info * skynet_socket_info();\n\n// legacy APIs\n\nstatic inline void sendbuffer_init_(struct socket_sendbuffer *buf, int id, const void *buffer, int sz) {\n\tbuf->id = id;\n\tbuf->buffer = buffer;\n\tif (sz < 0) {\n\t\tbuf->type = SOCKET_BUFFER_OBJECT;\n\t} else {\n\t\tbuf->type = SOCKET_BUFFER_MEMORY;\n\t}\n\tbuf->sz = (size_t)sz;\n}\n\nstatic inline int skynet_socket_send(struct skynet_context *ctx, int id, void *buffer, int sz) {\n\tstruct socket_sendbuffer tmp;\n\tsendbuffer_init_(&tmp, id, buffer, sz);\n\treturn skynet_socket_sendbuffer(ctx, &tmp);\n}\n\nstatic inline int skynet_socket_send_lowpriority(struct skynet_context *ctx, int id, void *buffer, int sz) {\n\tstruct socket_sendbuffer tmp;\n\tsendbuffer_init_(&tmp, id, buffer, sz);\n\treturn skynet_socket_sendbuffer_lowpriority(ctx, &tmp);\n}\n\nstatic inline int skynet_socket_udp_send(struct skynet_context *ctx, int id, const char * address, const void *buffer, int sz) {\n\tstruct socket_sendbuffer tmp;\n\tsendbuffer_init_(&tmp, id, buffer, sz);\n\treturn skynet_socket_udp_sendbuffer(ctx, address, &tmp);\n}\n\n#endif\n"
  },
  {
    "path": "skynet-src/skynet_start.c",
    "content": "#include \"skynet.h\"\n#include \"skynet_server.h\"\n#include \"skynet_imp.h\"\n#include \"skynet_mq.h\"\n#include \"skynet_handle.h\"\n#include \"skynet_module.h\"\n#include \"skynet_timer.h\"\n#include \"skynet_monitor.h\"\n#include \"skynet_socket.h\"\n#include \"skynet_daemon.h\"\n#include \"skynet_harbor.h\"\n\n#include <pthread.h>\n#include <unistd.h>\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <signal.h>\n\nstruct monitor {\n\tint count;\n\tstruct skynet_monitor ** m;\n\tpthread_cond_t cond;\n\tpthread_mutex_t mutex;\n\tint sleep;\n\tint quit;\n};\n\nstruct worker_parm {\n\tstruct monitor *m;\n\tint id;\n\tint weight;\n};\n\nstatic volatile int SIG = 0;\n\nstatic void\nhandle_hup(int signal) {\n\tif (signal == SIGHUP) {\n\t\tSIG = 1;\n\t}\n}\n\n#define CHECK_ABORT if (skynet_context_total()==0) break;\n\nstatic void\ncreate_thread(pthread_t *thread, void *(*start_routine) (void *), void *arg) {\n\tif (pthread_create(thread,NULL, start_routine, arg)) {\n\t\tfprintf(stderr, \"Create thread failed\");\n\t\texit(1);\n\t}\n}\n\nstatic void\nwakeup(struct monitor *m, int busy) {\n\tif (m->sleep >= m->count - busy) {\n\t\t// signal sleep worker, \"spurious wakeup\" is harmless\n\t\tpthread_cond_signal(&m->cond);\n\t}\n}\n\nstatic void *\nthread_socket(void *p) {\n\tstruct monitor * m = p;\n\tskynet_initthread(THREAD_SOCKET);\n\tfor (;;) {\n\t\tint r = skynet_socket_poll();\n\t\tif (r==0)\n\t\t\tbreak;\n\t\tif (r<0) {\n\t\t\tCHECK_ABORT\n\t\t\tcontinue;\n\t\t}\n\t\twakeup(m,0);\n\t}\n\treturn NULL;\n}\n\nstatic void\nfree_monitor(struct monitor *m) {\n\tint i;\n\tint n = m->count;\n\tfor (i=0;i<n;i++) {\n\t\tskynet_monitor_delete(m->m[i]);\n\t}\n\tpthread_mutex_destroy(&m->mutex);\n\tpthread_cond_destroy(&m->cond);\n\tskynet_free(m->m);\n\tskynet_free(m);\n}\n\nstatic void *\nthread_monitor(void *p) {\n\tstruct monitor * m = p;\n\tint i;\n\tint n = m->count;\n\tskynet_initthread(THREAD_MONITOR);\n\tfor (;;) {\n\t\tCHECK_ABORT\n\t\tfor (i=0;i<n;i++) {\n\t\t\tskynet_monitor_check(m->m[i]);\n\t\t}\n\t\tfor (i=0;i<5;i++) {\n\t\t\tCHECK_ABORT\n\t\t\tsleep(1);\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\nstatic void\nsignal_hup() {\n\t// make log file reopen\n\n\tstruct skynet_message smsg;\n\tsmsg.source = 0;\n\tsmsg.session = 0;\n\tsmsg.data = NULL;\n\tsmsg.sz = (size_t)PTYPE_SYSTEM << MESSAGE_TYPE_SHIFT;\n\tuint32_t logger = skynet_handle_findname(\"logger\");\n\tif (logger) {\n\t\tskynet_context_push(logger, &smsg);\n\t}\n}\n\nstatic void *\nthread_timer(void *p) {\n\tstruct monitor * m = p;\n\tskynet_initthread(THREAD_TIMER);\n\tfor (;;) {\n\t\tskynet_updatetime();\n\t\tskynet_socket_updatetime();\n\t\tCHECK_ABORT\n\t\twakeup(m,m->count-1);\n\t\tusleep(2500);\n\t\tif (SIG) {\n\t\t\tsignal_hup();\n\t\t\tSIG = 0;\n\t\t}\n\t}\n\t// wakeup socket thread\n\tskynet_socket_exit();\n\t// wakeup all worker thread\n\tpthread_mutex_lock(&m->mutex);\n\tm->quit = 1;\n\tpthread_cond_broadcast(&m->cond);\n\tpthread_mutex_unlock(&m->mutex);\n\treturn NULL;\n}\n\nstatic void *\nthread_worker(void *p) {\n\tstruct worker_parm *wp = p;\n\tint id = wp->id;\n\tint weight = wp->weight;\n\tstruct monitor *m = wp->m;\n\tstruct skynet_monitor *sm = m->m[id];\n\tskynet_initthread(THREAD_WORKER);\n\tstruct message_queue * q = NULL;\n\twhile (!m->quit) {\n\t\tq = skynet_context_message_dispatch(sm, q, weight);\n\t\tif (q == NULL) {\n\t\t\tif (pthread_mutex_lock(&m->mutex) == 0) {\n\t\t\t\t++ m->sleep;\n\t\t\t\t// \"spurious wakeup\" is harmless,\n\t\t\t\t// because skynet_context_message_dispatch() can be call at any time.\n\t\t\t\tif (!m->quit)\n\t\t\t\t\tpthread_cond_wait(&m->cond, &m->mutex);\n\t\t\t\t-- m->sleep;\n\t\t\t\tif (pthread_mutex_unlock(&m->mutex)) {\n\t\t\t\t\tfprintf(stderr, \"unlock mutex error\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn NULL;\n}\n\nstatic void\nstart(int thread) {\n\tpthread_t pid[thread+3];\n\n\tstruct monitor *m = skynet_malloc(sizeof(*m));\n\tmemset(m, 0, sizeof(*m));\n\tm->count = thread;\n\tm->sleep = 0;\n\n\tm->m = skynet_malloc(thread * sizeof(struct skynet_monitor *));\n\tint i;\n\tfor (i=0;i<thread;i++) {\n\t\tm->m[i] = skynet_monitor_new();\n\t}\n\tif (pthread_mutex_init(&m->mutex, NULL)) {\n\t\tfprintf(stderr, \"Init mutex error\");\n\t\texit(1);\n\t}\n\tif (pthread_cond_init(&m->cond, NULL)) {\n\t\tfprintf(stderr, \"Init cond error\");\n\t\texit(1);\n\t}\n\n\tcreate_thread(&pid[0], thread_monitor, m);\n\tcreate_thread(&pid[1], thread_timer, m);\n\tcreate_thread(&pid[2], thread_socket, m);\n\n\tstatic int weight[] = {\n\t\t-1, -1, -1, -1, 0, 0, 0, 0,\n\t\t1, 1, 1, 1, 1, 1, 1, 1,\n\t\t2, 2, 2, 2, 2, 2, 2, 2,\n\t\t3, 3, 3, 3, 3, 3, 3, 3, };\n\tstruct worker_parm wp[thread];\n\tfor (i=0;i<thread;i++) {\n\t\twp[i].m = m;\n\t\twp[i].id = i;\n\t\tif (i < sizeof(weight)/sizeof(weight[0])) {\n\t\t\twp[i].weight= weight[i];\n\t\t} else {\n\t\t\twp[i].weight = 0;\n\t\t}\n\t\tcreate_thread(&pid[i+3], thread_worker, &wp[i]);\n\t}\n\n\tfor (i=0;i<thread+3;i++) {\n\t\tpthread_join(pid[i], NULL);\n\t}\n\n\tfree_monitor(m);\n}\n\nstatic void\nbootstrap(uint32_t logger_handle, const char * cmdline) {\n\tint sz = strlen(cmdline);\n\tchar name[sz+1];\n\tchar args[sz+1];\n\tint arg_pos;\n\tsscanf(cmdline, \"%s\", name);\n\targ_pos = strlen(name);\n\tif (arg_pos < sz) {\n\t\twhile(cmdline[arg_pos] == ' ') {\n\t\t\targ_pos++;\n\t\t}\n\t\tstrncpy(args, cmdline + arg_pos, sz);\n\t} else {\n\t\targs[0] = '\\0';\n\t}\n\tconst uint32_t handle = skynet_context_new(name, args);\n\tif (handle == 0) {\n\t\tstruct skynet_context *logger = skynet_handle_grab(logger_handle);\n\t\tif (logger != NULL) {\n\t\t\tskynet_error(NULL, \"Bootstrap error : %s\\n\", cmdline);\n\t\t\tskynet_context_dispatchall(logger);\n\t\t\tskynet_context_release(logger);\n\t\t}\n\t\texit(1);\n\t}\n}\n\nvoid\nskynet_start(struct skynet_config * config) {\n\t// register SIGHUP for log file reopen\n\tstruct sigaction sa;\n\tsa.sa_handler = &handle_hup;\n\tsa.sa_flags = SA_RESTART;\n\tsigfillset(&sa.sa_mask);\n\tsigaction(SIGHUP, &sa, NULL);\n\n\tif (config->daemon) {\n\t\tif (daemon_init(config->daemon)) {\n\t\t\texit(1);\n\t\t}\n\t}\n\tskynet_harbor_init(config->harbor);\n\tskynet_handle_init(config->harbor);\n\tskynet_mq_init();\n\tskynet_module_init(config->module_path);\n\tskynet_timer_init();\n\tskynet_socket_init();\n\tskynet_profile_enable(config->profile);\n\n\tconst uint32_t logger_handle = skynet_context_new(config->logservice, config->logger);\n\tif (logger_handle == 0) {\n\t\tfprintf(stderr, \"Can't launch %s service\\n\", config->logservice);\n\t\texit(1);\n\t}\n\n\tskynet_handle_namehandle(logger_handle, \"logger\");\n\n\tbootstrap(logger_handle, config->bootstrap);\n\n\tstart(config->thread);\n\n\t// harbor_exit may call socket send, so it should exit before socket_free\n\tskynet_harbor_exit();\n\tskynet_socket_free();\n\tif (config->daemon) {\n\t\tdaemon_exit(config->daemon);\n\t}\n}\n"
  },
  {
    "path": "skynet-src/skynet_timer.c",
    "content": "#include \"skynet.h\"\n\n#include \"skynet_timer.h\"\n#include \"skynet_mq.h\"\n#include \"skynet_server.h\"\n#include \"skynet_handle.h\"\n#include \"spinlock.h\"\n\n#include <time.h>\n#include <assert.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdint.h>\n\ntypedef void (*timer_execute_func)(void *ud,void *arg);\n\n#define TIME_NEAR_SHIFT 8\n#define TIME_NEAR (1 << TIME_NEAR_SHIFT)\n#define TIME_LEVEL_SHIFT 6\n#define TIME_LEVEL (1 << TIME_LEVEL_SHIFT)\n#define TIME_NEAR_MASK (TIME_NEAR-1)\n#define TIME_LEVEL_MASK (TIME_LEVEL-1)\n\nstruct timer_event {\n\tuint32_t handle;\n\tint session;\n};\n\nstruct timer_node {\n\tstruct timer_node *next;\n\tuint32_t expire;\n};\n\nstruct link_list {\n\tstruct timer_node head;\n\tstruct timer_node *tail;\n};\n\nstruct timer {\n\tstruct link_list near[TIME_NEAR];\n\tstruct link_list t[4][TIME_LEVEL];\n\tstruct spinlock lock;\n\tuint32_t time;\n\tuint32_t starttime;\n\tuint64_t current;\n\tuint64_t current_point;\n};\n\nstatic struct timer * TI = NULL;\n\nstatic inline struct timer_node *\nlink_clear(struct link_list *list) {\n\tstruct timer_node * ret = list->head.next;\n\tlist->head.next = 0;\n\tlist->tail = &(list->head);\n\n\treturn ret;\n}\n\nstatic inline void\nlink(struct link_list *list,struct timer_node *node) {\n\tlist->tail->next = node;\n\tlist->tail = node;\n\tnode->next=0;\n}\n\nstatic void\nadd_node(struct timer *T,struct timer_node *node) {\n\tuint32_t time=node->expire;\n\tuint32_t current_time=T->time;\n\t\n\tif ((time|TIME_NEAR_MASK)==(current_time|TIME_NEAR_MASK)) {\n\t\tlink(&T->near[time&TIME_NEAR_MASK],node);\n\t} else {\n\t\tint i;\n\t\tuint32_t mask=TIME_NEAR << TIME_LEVEL_SHIFT;\n\t\tfor (i=0;i<3;i++) {\n\t\t\tif ((time|(mask-1))==(current_time|(mask-1))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmask <<= TIME_LEVEL_SHIFT;\n\t\t}\n\n\t\tlink(&T->t[i][((time>>(TIME_NEAR_SHIFT + i*TIME_LEVEL_SHIFT)) & TIME_LEVEL_MASK)],node);\t\n\t}\n}\n\nstatic void\ntimer_add(struct timer *T,void *arg,size_t sz,int time) {\n\tstruct timer_node *node = (struct timer_node *)skynet_malloc(sizeof(*node)+sz);\n\tmemcpy(node+1,arg,sz);\n\n\tSPIN_LOCK(T);\n\n\t\tnode->expire=time+T->time;\n\t\tadd_node(T,node);\n\n\tSPIN_UNLOCK(T);\n}\n\nstatic void\nmove_list(struct timer *T, int level, int idx) {\n\tstruct timer_node *current = link_clear(&T->t[level][idx]);\n\twhile (current) {\n\t\tstruct timer_node *temp=current->next;\n\t\tadd_node(T,current);\n\t\tcurrent=temp;\n\t}\n}\n\nstatic void\ntimer_shift(struct timer *T) {\n\tint mask = TIME_NEAR;\n\tuint32_t ct = ++T->time;\n\tif (ct == 0) {\n\t\tmove_list(T, 3, 0);\n\t} else {\n\t\tuint32_t time = ct >> TIME_NEAR_SHIFT;\n\t\tint i=0;\n\n\t\twhile ((ct & (mask-1))==0) {\n\t\t\tint idx=time & TIME_LEVEL_MASK;\n\t\t\tif (idx!=0) {\n\t\t\t\tmove_list(T, i, idx);\n\t\t\t\tbreak;\t\t\t\t\n\t\t\t}\n\t\t\tmask <<= TIME_LEVEL_SHIFT;\n\t\t\ttime >>= TIME_LEVEL_SHIFT;\n\t\t\t++i;\n\t\t}\n\t}\n}\n\nstatic inline void\ndispatch_list(struct timer_node *current) {\n\tdo {\n\t\tstruct timer_event * event = (struct timer_event *)(current+1);\n\t\tstruct skynet_message message;\n\t\tmessage.source = 0;\n\t\tmessage.session = event->session;\n\t\tmessage.data = NULL;\n\t\tmessage.sz = (size_t)PTYPE_RESPONSE << MESSAGE_TYPE_SHIFT;\n\n\t\tskynet_context_push(event->handle, &message);\n\t\t\n\t\tstruct timer_node * temp = current;\n\t\tcurrent=current->next;\n\t\tskynet_free(temp);\t\n\t} while (current);\n}\n\nstatic inline void\ntimer_execute(struct timer *T) {\n\tint idx = T->time & TIME_NEAR_MASK;\n\t\n\twhile (T->near[idx].head.next) {\n\t\tstruct timer_node *current = link_clear(&T->near[idx]);\n\t\tSPIN_UNLOCK(T);\n\t\t// dispatch_list don't need lock T\n\t\tdispatch_list(current);\n\t\tSPIN_LOCK(T);\n\t}\n}\n\nstatic void \ntimer_update(struct timer *T) {\n\tSPIN_LOCK(T);\n\n\t// try to dispatch timeout 0 (rare condition)\n\ttimer_execute(T);\n\n\t// shift time first, and then dispatch timer message\n\ttimer_shift(T);\n\n\ttimer_execute(T);\n\n\tSPIN_UNLOCK(T);\n}\n\nstatic struct timer *\ntimer_create_timer() {\n\tstruct timer *r=(struct timer *)skynet_malloc(sizeof(struct timer));\n\tmemset(r,0,sizeof(*r));\n\n\tint i,j;\n\n\tfor (i=0;i<TIME_NEAR;i++) {\n\t\tlink_clear(&r->near[i]);\n\t}\n\n\tfor (i=0;i<4;i++) {\n\t\tfor (j=0;j<TIME_LEVEL;j++) {\n\t\t\tlink_clear(&r->t[i][j]);\n\t\t}\n\t}\n\n\tSPIN_INIT(r)\n\n\tr->current = 0;\n\n\treturn r;\n}\n\nint\nskynet_timeout(uint32_t handle, int time, int session) {\n\tif (time <= 0) {\n\t\tstruct skynet_message message;\n\t\tmessage.source = 0;\n\t\tmessage.session = session;\n\t\tmessage.data = NULL;\n\t\tmessage.sz = (size_t)PTYPE_RESPONSE << MESSAGE_TYPE_SHIFT;\n\n\t\tif (skynet_context_push(handle, &message)) {\n\t\t\treturn -1;\n\t\t}\n\t} else {\n\t\tstruct timer_event event;\n\t\tevent.handle = handle;\n\t\tevent.session = session;\n\t\ttimer_add(TI, &event, sizeof(event), time);\n\t}\n\n\treturn session;\n}\n\n// centisecond: 1/100 second\nstatic void\nsystime(uint32_t *sec, uint32_t *cs) {\n\tstruct timespec ti;\n\tclock_gettime(CLOCK_REALTIME, &ti);\n\t*sec = (uint32_t)ti.tv_sec;\n\t*cs = (uint32_t)(ti.tv_nsec / 10000000);\n}\n\nstatic uint64_t\ngettime() {\n\tuint64_t t;\n\tstruct timespec ti;\n\tclock_gettime(CLOCK_MONOTONIC, &ti);\n\tt = (uint64_t)ti.tv_sec * 100;\n\tt += ti.tv_nsec / 10000000;\n\treturn t;\n}\n\nvoid\nskynet_updatetime(void) {\n\tuint64_t cp = gettime();\n\tif(cp < TI->current_point) {\n\t\tskynet_error(NULL, \"time diff error: change from %lld to %lld\", cp, TI->current_point);\n\t\tTI->current_point = cp;\n\t} else if (cp != TI->current_point) {\n\t\tuint32_t diff = (uint32_t)(cp - TI->current_point);\n\t\tTI->current_point = cp;\n\t\tTI->current += diff;\n\t\tint i;\n\t\tfor (i=0;i<diff;i++) {\n\t\t\ttimer_update(TI);\n\t\t}\n\t}\n}\n\nuint32_t\nskynet_starttime(void) {\n\treturn TI->starttime;\n}\n\nuint64_t \nskynet_now(void) {\n\treturn TI->current;\n}\n\nvoid \nskynet_timer_init(void) {\n\tTI = timer_create_timer();\n\tuint32_t current = 0;\n\tsystime(&TI->starttime, &current);\n\tTI->current = current;\n\tTI->current_point = gettime();\n}\n\n// for profile\n\n#define NANOSEC 1000000000\n#define MICROSEC 1000000\n\nuint64_t\nskynet_thread_time(void) {\n\tstruct timespec ti;\n\tclock_gettime(CLOCK_THREAD_CPUTIME_ID, &ti);\n\n\treturn (uint64_t)ti.tv_sec * MICROSEC + (uint64_t)ti.tv_nsec / (NANOSEC / MICROSEC);\n}\n"
  },
  {
    "path": "skynet-src/skynet_timer.h",
    "content": "#ifndef SKYNET_TIMER_H\n#define SKYNET_TIMER_H\n\n#include <stdint.h>\n\nint skynet_timeout(uint32_t handle, int time, int session);\nvoid skynet_updatetime(void);\nuint32_t skynet_starttime(void);\nuint64_t skynet_thread_time(void);\t// for profile, in micro second\n\nvoid skynet_timer_init(void);\n\n#endif\n"
  },
  {
    "path": "skynet-src/socket_buffer.h",
    "content": "#ifndef socket_buffer_h\n#define socket_buffer_h\n\n#include <stdlib.h>\n\n#define SOCKET_BUFFER_MEMORY 0\n#define SOCKET_BUFFER_OBJECT 1\n#define SOCKET_BUFFER_RAWPOINTER 2\n\nstruct socket_sendbuffer {\n\tint id;\n\tint type;\n\tconst void *buffer;\n\tsize_t sz;\n};\n\n#endif\n"
  },
  {
    "path": "skynet-src/socket_epoll.h",
    "content": "#ifndef poll_socket_epoll_h\n#define poll_socket_epoll_h\n\n#include <netdb.h>\n#include <unistd.h>\n#include <sys/epoll.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <fcntl.h>\n\nstatic bool \nsp_invalid(int efd) {\n\treturn efd == -1;\n}\n\nstatic int\nsp_create() {\n\treturn epoll_create(1024);\n}\n\nstatic void\nsp_release(int efd) {\n\tclose(efd);\n}\n\nstatic int \nsp_add(int efd, int sock, void *ud) {\n\tstruct epoll_event ev;\n\tev.events = EPOLLIN;\n\tev.data.ptr = ud;\n\tif (epoll_ctl(efd, EPOLL_CTL_ADD, sock, &ev) == -1) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic void \nsp_del(int efd, int sock) {\n\tepoll_ctl(efd, EPOLL_CTL_DEL, sock , NULL);\n}\n\nstatic int\nsp_enable(int efd, int sock, void *ud, bool read_enable, bool write_enable) {\n\tstruct epoll_event ev;\n\tev.events = (read_enable ? EPOLLIN : 0) | (write_enable ? EPOLLOUT : 0);\n\tev.data.ptr = ud;\n\tif (epoll_ctl(efd, EPOLL_CTL_MOD, sock, &ev) == -1) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic int \nsp_wait(int efd, struct event *e, int max) {\n\tstruct epoll_event ev[max];\n\tint n = epoll_wait(efd , ev, max, -1);\n\tint i;\n\tfor (i=0;i<n;i++) {\n\t\te[i].s = ev[i].data.ptr;\n\t\tunsigned flag = ev[i].events;\n\t\te[i].write = (flag & EPOLLOUT) != 0;\n\t\te[i].read = (flag & EPOLLIN) != 0;\n\t\te[i].error = (flag & EPOLLERR) != 0;\n\t\te[i].eof = (flag & EPOLLHUP) != 0;\n\t}\n\n\treturn n;\n}\n\nstatic void\nsp_nonblocking(int fd) {\n\tint flag = fcntl(fd, F_GETFL, 0);\n\tif ( -1 == flag ) {\n\t\treturn;\n\t}\n\n\tfcntl(fd, F_SETFL, flag | O_NONBLOCK);\n}\n\n#endif\n"
  },
  {
    "path": "skynet-src/socket_info.h",
    "content": "#ifndef socket_info_h\n#define socket_info_h\n\n#define SOCKET_INFO_UNKNOWN 0\n#define SOCKET_INFO_LISTEN 1\n#define SOCKET_INFO_TCP 2\n#define SOCKET_INFO_UDP 3\n#define SOCKET_INFO_BIND 4\n#define SOCKET_INFO_CLOSING 5\n\n#include <stdint.h>\n\nstruct socket_info {\n\tint id;\n\tint type;\n\tuint64_t opaque;\n\tuint64_t read;\n\tuint64_t write;\n\tuint64_t rtime;\n\tuint64_t wtime;\n\tint64_t wbuffer;\n\tuint8_t reading;\n\tuint8_t writing;\n\tchar name[128];\n\tstruct socket_info *next;\n};\n\nstruct socket_info * socket_info_create(struct socket_info *last);\nvoid socket_info_release(struct socket_info *);\n\n#endif\n"
  },
  {
    "path": "skynet-src/socket_kqueue.h",
    "content": "#ifndef poll_socket_kqueue_h\n#define poll_socket_kqueue_h\n\n#include <netdb.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/event.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n\nstatic bool \nsp_invalid(int kfd) {\n\treturn kfd == -1;\n}\n\nstatic int\nsp_create() {\n\treturn kqueue();\n}\n\nstatic void\nsp_release(int kfd) {\n\tclose(kfd);\n}\n\nstatic void \nsp_del(int kfd, int sock) {\n\tstruct kevent ke;\n\tEV_SET(&ke, sock, EVFILT_READ, EV_DELETE, 0, 0, NULL);\n\tkevent(kfd, &ke, 1, NULL, 0, NULL);\n\tEV_SET(&ke, sock, EVFILT_WRITE, EV_DELETE, 0, 0, NULL);\n\tkevent(kfd, &ke, 1, NULL, 0, NULL);\n}\n\nstatic int \nsp_add(int kfd, int sock, void *ud) {\n\tstruct kevent ke;\n\tEV_SET(&ke, sock, EVFILT_READ, EV_ADD, 0, 0, ud);\n\tif (kevent(kfd, &ke, 1, NULL, 0, NULL) == -1 ||\tke.flags & EV_ERROR) {\n\t\treturn 1;\n\t}\n\tEV_SET(&ke, sock, EVFILT_WRITE, EV_ADD, 0, 0, ud);\n\tif (kevent(kfd, &ke, 1, NULL, 0, NULL) == -1 ||\tke.flags & EV_ERROR) {\n\t\tEV_SET(&ke, sock, EVFILT_READ, EV_DELETE, 0, 0, NULL);\n\t\tkevent(kfd, &ke, 1, NULL, 0, NULL);\n\t\treturn 1;\n\t}\n\tEV_SET(&ke, sock, EVFILT_WRITE, EV_DISABLE, 0, 0, ud);\n\tif (kevent(kfd, &ke, 1, NULL, 0, NULL) == -1 ||\tke.flags & EV_ERROR) {\n\t\tsp_del(kfd, sock);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic int\nsp_enable(int kfd, int sock, void *ud, bool read_enable, bool write_enable) {\n\tint ret = 0;\n\tstruct kevent ke;\n\tEV_SET(&ke, sock, EVFILT_READ, read_enable ? EV_ENABLE : EV_DISABLE, 0, 0, ud);\n\tif (kevent(kfd, &ke, 1, NULL, 0, NULL) == -1 || ke.flags & EV_ERROR) {\n\t\tret |= 1;\n\t}\n\tEV_SET(&ke, sock, EVFILT_WRITE, write_enable ? EV_ENABLE : EV_DISABLE, 0, 0, ud);\n\tif (kevent(kfd, &ke, 1, NULL, 0, NULL) == -1 || ke.flags & EV_ERROR) {\n\t\tret |= 1;\n\t}\n\treturn ret;\n}\n\nstatic int \nsp_wait(int kfd, struct event *e, int max) {\n\tstruct kevent ev[max];\n\tint n = kevent(kfd, NULL, 0, ev, max, NULL);\n\n\tint i;\n\tfor (i=0;i<n;i++) {\n\t\te[i].s = ev[i].udata;\n\t\tunsigned filter = ev[i].filter;\n\t\tbool eof = (ev[i].flags & EV_EOF) != 0;\n\t\te[i].write = (filter == EVFILT_WRITE) && (!eof);\n\t\te[i].read = (filter == EVFILT_READ);\n\t\te[i].error = (ev[i].flags & EV_ERROR) != 0;\n\t\te[i].eof = eof;\n\t}\n\n\treturn n;\n}\n\nstatic void\nsp_nonblocking(int fd) {\n\tint flag = fcntl(fd, F_GETFL, 0);\n\tif ( -1 == flag ) {\n\t\treturn;\n\t}\n\n\tfcntl(fd, F_SETFL, flag | O_NONBLOCK);\n}\n\n#endif\n"
  },
  {
    "path": "skynet-src/socket_poll.h",
    "content": "#ifndef socket_poll_h\n#define socket_poll_h\n\n#include <stdbool.h>\n\ntypedef int poll_fd;\n\nstruct event {\n\tvoid * s;\n\tbool read;\n\tbool write;\n\tbool error;\n\tbool eof;\n};\n\nstatic bool sp_invalid(poll_fd fd);\nstatic poll_fd sp_create();\nstatic void sp_release(poll_fd fd);\nstatic int sp_add(poll_fd fd, int sock, void *ud);\nstatic void sp_del(poll_fd fd, int sock);\nstatic int sp_enable(poll_fd, int sock, void *ud, bool read_enable, bool write_enable);\nstatic int sp_wait(poll_fd, struct event *e, int max);\nstatic void sp_nonblocking(int sock);\n\n#ifdef __linux__\n#include \"socket_epoll.h\"\n#endif\n\n#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined (__NetBSD__)\n#include \"socket_kqueue.h\"\n#endif\n\n#endif\n"
  },
  {
    "path": "skynet-src/socket_server.c",
    "content": "#include \"skynet.h\"\n\n#include \"socket_server.h\"\n#include \"socket_poll.h\"\n#include \"atomic.h\"\n#include \"spinlock.h\"\n\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/tcp.h>\n#include <unistd.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <assert.h>\n#include <string.h>\n\n#define MAX_INFO 128\n// MAX_SOCKET will be 2^MAX_SOCKET_P\n#define MAX_SOCKET_P 16\n#define MAX_EVENT 64\n#define MIN_READ_BUFFER 64\n#define SOCKET_TYPE_INVALID 0\n#define SOCKET_TYPE_RESERVE 1\n#define SOCKET_TYPE_PLISTEN 2\n#define SOCKET_TYPE_LISTEN 3\n#define SOCKET_TYPE_CONNECTING 4\n#define SOCKET_TYPE_CONNECTED 5\n#define SOCKET_TYPE_HALFCLOSE_READ 6\n#define SOCKET_TYPE_HALFCLOSE_WRITE 7\n#define SOCKET_TYPE_PACCEPT 8\n#define SOCKET_TYPE_BIND 9\n\n#define MAX_SOCKET (1<<MAX_SOCKET_P)\n\n#define PRIORITY_HIGH 0\n#define PRIORITY_LOW 1\n\n#define HASH_ID(id) (((unsigned)id) % MAX_SOCKET)\n#define ID_TAG16(id) ((id>>MAX_SOCKET_P) & 0xffff)\n\n#define PROTOCOL_TCP 0\n#define PROTOCOL_UDP 1\n#define PROTOCOL_UDPv6 2\n#define PROTOCOL_UNKNOWN 255\n\n#define UDP_ADDRESS_SIZE 19\t// ipv6 128bit + port 16bit + 1 byte type\n\n#define MAX_UDP_PACKAGE 65535\n\n// EAGAIN and EWOULDBLOCK may be not the same value.\n#if (EAGAIN != EWOULDBLOCK)\n#define AGAIN_WOULDBLOCK EAGAIN : case EWOULDBLOCK\n#else\n#define AGAIN_WOULDBLOCK EAGAIN\n#endif\n\n#define WARNING_SIZE (1024*1024)\n\n#define USEROBJECT ((size_t)(-1))\n\nstruct write_buffer {\n\tstruct write_buffer * next;\n\tconst void *buffer;\n\tchar *ptr;\n\tsize_t sz;\n\tbool userobject;\n};\n\nstruct write_buffer_udp {\n\tstruct write_buffer buffer;\n\tuint8_t udp_address[UDP_ADDRESS_SIZE];\n};\n\nstruct wb_list {\n\tstruct write_buffer * head;\n\tstruct write_buffer * tail;\n};\n\nstruct socket_stat {\n\tuint64_t rtime;\n\tuint64_t wtime;\n\tuint64_t read;\n\tuint64_t write;\n};\n\nstruct socket {\n\tuintptr_t opaque;\n\tstruct wb_list high;\n\tstruct wb_list low;\n\tint64_t wb_size;\n\tstruct socket_stat stat;\n\tATOM_ULONG sending;\n\tint fd;\n\tint id;\n\tATOM_INT type;\n\tuint8_t protocol;\n\tbool reading;\n\tbool writing;\n\tbool closing;\n\tATOM_INT udpconnecting;\n\tint64_t warn_size;\n\tunion {\n\t\tint size;\n\t\tuint8_t udp_address[UDP_ADDRESS_SIZE];\n\t} p;\n\tstruct spinlock dw_lock;\n\tint dw_offset;\n\tconst void * dw_buffer;\n\tsize_t dw_size;\n};\n\nstruct socket_server {\n\tvolatile uint64_t time;\n\tint reserve_fd;\t// for EMFILE\n\tint recvctrl_fd;\n\tint sendctrl_fd;\n\tint checkctrl;\n\tpoll_fd event_fd;\n\tATOM_INT alloc_id;\n\tint event_n;\n\tint event_index;\n\tstruct socket_object_interface soi;\n\tstruct event ev[MAX_EVENT];\n\tstruct socket slot[MAX_SOCKET];\n\tchar buffer[MAX_INFO];\n\tuint8_t udpbuffer[MAX_UDP_PACKAGE];\n\tfd_set rfds;\n};\n\nstruct request_open {\n\tint id;\n\tint port;\n\tuintptr_t opaque;\n\tchar host[1];\n};\n\nstruct request_send {\n\tint id;\n\tsize_t sz;\n\tconst void * buffer;\n};\n\nstruct request_send_udp {\n\tstruct request_send send;\n\tuint8_t address[UDP_ADDRESS_SIZE];\n};\n\nstruct request_setudp {\n\tint id;\n\tuint8_t address[UDP_ADDRESS_SIZE];\n};\n\nstruct request_close {\n\tint id;\n\tint shutdown;\n\tuintptr_t opaque;\n};\n\nstruct request_listen {\n\tint id;\n\tint fd;\n\tuintptr_t opaque;\n\t// char host[1];\n};\n\nstruct request_bind {\n\tint id;\n\tint fd;\n\tuintptr_t opaque;\n};\n\nstruct request_resumepause {\n\tint id;\n\tuintptr_t opaque;\n};\n\nstruct request_setopt {\n\tint id;\n\tint what;\n\tint value;\n};\n\nstruct request_udp {\n\tint id;\n\tint fd;\n\tint family;\n\tuintptr_t opaque;\n};\n\nstruct request_dial_udp {\n\tint id;\n\tint fd;\n\tuintptr_t opaque;\n\tuint8_t address[UDP_ADDRESS_SIZE];\n};\n\n/*\n\tThe first byte is TYPE\n\tR Resume socket\n\tS Pause socket\n\tB Bind socket\n\tL Listen socket\n\tK Close socket\n\tO Connect to (Open)\n\tX Exit socket thread\n\tW Enable write\n\tD Send package (high)\n\tP Send package (low)\n\tA Send UDP package\n\tC set udp address\n\tN client dial to UDP host port\n\tT Set opt\n\tU Create UDP socket\n */\n\nstruct request_package {\n\tuint8_t header[8];\t// 6 bytes dummy\n\tunion {\n\t\tchar buffer[256];\n\t\tstruct request_open open;\n\t\tstruct request_send send;\n\t\tstruct request_send_udp send_udp;\n\t\tstruct request_close close;\n\t\tstruct request_listen listen;\n\t\tstruct request_bind bind;\n\t\tstruct request_resumepause resumepause;\n\t\tstruct request_setopt setopt;\n\t\tstruct request_udp udp;\n\t\tstruct request_setudp set_udp;\n\t\tstruct request_dial_udp dial_udp;\n\t} u;\n\tuint8_t dummy[256];\n};\n\nunion sockaddr_all {\n\tstruct sockaddr s;\n\tstruct sockaddr_in v4;\n\tstruct sockaddr_in6 v6;\n};\n\nstruct send_object {\n\tconst void * buffer;\n\tsize_t sz;\n\tvoid (*free_func)(void *);\n};\n\n#define MALLOC skynet_malloc\n#define FREE skynet_free\n\nstruct socket_lock {\n\tstruct spinlock *lock;\n\tint count;\n};\n\nstatic inline void\nsocket_lock_init(struct socket *s, struct socket_lock *sl) {\n\tsl->lock = &s->dw_lock;\n\tsl->count = 0;\n}\n\nstatic inline void\nsocket_lock(struct socket_lock *sl) {\n\tif (sl->count == 0) {\n\t\tspinlock_lock(sl->lock);\n\t}\n\t++sl->count;\n}\n\nstatic inline int\nsocket_trylock(struct socket_lock *sl) {\n\tif (sl->count == 0) {\n\t\tif (!spinlock_trylock(sl->lock))\n\t\t\treturn 0;\t// lock failed\n\t}\n\t++sl->count;\n\treturn 1;\n}\n\nstatic inline void\nsocket_unlock(struct socket_lock *sl) {\n\t--sl->count;\n\tif (sl->count <= 0) {\n\t\tassert(sl->count == 0);\n\t\tspinlock_unlock(sl->lock);\n\t}\n}\n\nstatic inline int\nsocket_invalid(struct socket *s, int id) {\n\treturn (s->id != id || ATOM_LOAD(&s->type) == SOCKET_TYPE_INVALID);\n}\n\nstatic inline bool\nsend_object_init(struct socket_server *ss, struct send_object *so, const void *object, size_t sz) {\n\tif (sz == USEROBJECT) {\n\t\tso->buffer = ss->soi.buffer(object);\n\t\tso->sz = ss->soi.size(object);\n\t\tso->free_func = ss->soi.free;\n\t\treturn true;\n\t} else {\n\t\tso->buffer = object;\n\t\tso->sz = sz;\n\t\tso->free_func = FREE;\n\t\treturn false;\n\t}\n}\n\nstatic void\ndummy_free(void *ptr) {\n\t(void)ptr;\n}\n\nstatic inline void\nsend_object_init_from_sendbuffer(struct socket_server *ss, struct send_object *so, struct socket_sendbuffer *buf) {\n\tswitch (buf->type) {\n\tcase SOCKET_BUFFER_MEMORY:\n\t\tsend_object_init(ss, so, buf->buffer, buf->sz);\n\t\tbreak;\n\tcase SOCKET_BUFFER_OBJECT:\n\t\tsend_object_init(ss, so, buf->buffer, USEROBJECT);\n\t\tbreak;\n\tcase SOCKET_BUFFER_RAWPOINTER:\n\t\tso->buffer = buf->buffer;\n\t\tso->sz = buf->sz;\n\t\tso->free_func = dummy_free;\n\t\tbreak;\n\tdefault:\n\t\t// never get here\n\t\tso->buffer = NULL;\n\t\tso->sz = 0;\n\t\tso->free_func = NULL;\n\t\tbreak;\n\t}\n}\n\nstatic inline void\nwrite_buffer_free(struct socket_server *ss, struct write_buffer *wb) {\n\tif (wb->userobject) {\n\t\tss->soi.free((void *)wb->buffer);\n\t} else {\n\t\tFREE((void *)wb->buffer);\n\t}\n\tFREE(wb);\n}\n\nstatic void\nsocket_keepalive(int fd) {\n\tint keepalive = 1;\n\tsetsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive , sizeof(keepalive));\n}\n\nstatic int\nreserve_id(struct socket_server *ss) {\n\tint i;\n\tfor (i=0;i<MAX_SOCKET;i++) {\n\t\tint id = ATOM_FINC(&(ss->alloc_id))+1;\n\t\tif (id < 0) {\n\t\t\tid = ATOM_FAND(&(ss->alloc_id), 0x7fffffff) & 0x7fffffff;\n\t\t}\n\t\tstruct socket *s = &ss->slot[HASH_ID(id)];\n\t\tint type_invalid = ATOM_LOAD(&s->type);\n\t\tif (type_invalid == SOCKET_TYPE_INVALID) {\n\t\t\tif (ATOM_CAS(&s->type, type_invalid, SOCKET_TYPE_RESERVE)) {\n\t\t\t\ts->id = id;\n\t\t\t\ts->protocol = PROTOCOL_UNKNOWN;\n\t\t\t\t// socket_server_udp_connect may inc s->udpconncting directly (from other thread, before new_fd),\n\t\t\t\t// so reset it to 0 here rather than in new_fd.\n\t\t\t\tATOM_INIT(&s->udpconnecting, 0);\n\t\t\t\ts->fd = -1;\n\t\t\t\treturn id;\n\t\t\t} else {\n\t\t\t\t// retry\n\t\t\t\t--i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nstatic inline void\nclear_wb_list(struct wb_list *list) {\n\tlist->head = NULL;\n\tlist->tail = NULL;\n}\n\nstruct socket_server *\nsocket_server_create(uint64_t time) {\n\tint i;\n\tint fd[2];\n\tpoll_fd efd = sp_create();\n\tif (sp_invalid(efd)) {\n\t\tskynet_error(NULL, \"socket-server error: create event pool failed.\");\n\t\treturn NULL;\n\t}\n\tif (pipe(fd)) {\n\t\tsp_release(efd);\n\t\tskynet_error(NULL, \"socket-server error: create socket pair failed.\");\n\t\treturn NULL;\n\t}\n\tif (sp_add(efd, fd[0], NULL)) {\n\t\t// add recvctrl_fd to event poll\n\t\tskynet_error(NULL, \"socket-server error: can't add server fd to event pool.\");\n\t\tclose(fd[0]);\n\t\tclose(fd[1]);\n\t\tsp_release(efd);\n\t\treturn NULL;\n\t}\n\n\tstruct socket_server *ss = MALLOC(sizeof(*ss));\n\tss->time = time;\n\tss->event_fd = efd;\n\tss->recvctrl_fd = fd[0];\n\tss->sendctrl_fd = fd[1];\n\tss->checkctrl = 1;\n\tss->reserve_fd = dup(1);\t// reserve an extra fd for EMFILE\n\n\tfor (i=0;i<MAX_SOCKET;i++) {\n\t\tstruct socket *s = &ss->slot[i];\n\t\tATOM_INIT(&s->type, SOCKET_TYPE_INVALID);\n\t\tclear_wb_list(&s->high);\n\t\tclear_wb_list(&s->low);\n\t\tspinlock_init(&s->dw_lock);\n\t}\n\tATOM_INIT(&ss->alloc_id , 0);\n\tss->event_n = 0;\n\tss->event_index = 0;\n\tmemset(&ss->soi, 0, sizeof(ss->soi));\n\tFD_ZERO(&ss->rfds);\n\tassert(ss->recvctrl_fd < FD_SETSIZE);\n\n\treturn ss;\n}\n\nvoid\nsocket_server_updatetime(struct socket_server *ss, uint64_t time) {\n\tss->time = time;\n}\n\nstatic void\nfree_wb_list(struct socket_server *ss, struct wb_list *list) {\n\tstruct write_buffer *wb = list->head;\n\twhile (wb) {\n\t\tstruct write_buffer *tmp = wb;\n\t\twb = wb->next;\n\t\twrite_buffer_free(ss, tmp);\n\t}\n\tlist->head = NULL;\n\tlist->tail = NULL;\n}\n\nstatic void\nfree_buffer(struct socket_server *ss, struct socket_sendbuffer *buf) {\n\tvoid *buffer = (void *)buf->buffer;\n\tswitch (buf->type) {\n\tcase SOCKET_BUFFER_MEMORY:\n\t\tFREE(buffer);\n\t\tbreak;\n\tcase SOCKET_BUFFER_OBJECT:\n\t\tss->soi.free(buffer);\n\t\tbreak;\n\tcase SOCKET_BUFFER_RAWPOINTER:\n\t\tbreak;\n\t}\n}\n\nstatic const void *\nclone_buffer(struct socket_sendbuffer *buf, size_t *sz) {\n\tswitch (buf->type) {\n\tcase SOCKET_BUFFER_MEMORY:\n\t\t*sz = buf->sz;\n\t\treturn buf->buffer;\n\tcase SOCKET_BUFFER_OBJECT:\n\t\t*sz = USEROBJECT;\n\t\treturn buf->buffer;\n\tcase SOCKET_BUFFER_RAWPOINTER:\n\t\t// It's a raw pointer, we need make a copy\n\t\t*sz = buf->sz;\n\t\tvoid * tmp = MALLOC(*sz);\n\t\tmemcpy(tmp, buf->buffer, *sz);\n\t\treturn tmp;\n\t}\n\t// never get here\n\t*sz = 0;\n\treturn NULL;\n}\n\nstatic void\nforce_close(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message *result) {\n\tresult->id = s->id;\n\tresult->ud = 0;\n\tresult->data = NULL;\n\tresult->opaque = s->opaque;\n\tuint8_t type = ATOM_LOAD(&s->type);\n\tif (type == SOCKET_TYPE_INVALID) {\n\t\treturn;\n\t}\n\tassert(type != SOCKET_TYPE_RESERVE);\n\tfree_wb_list(ss,&s->high);\n\tfree_wb_list(ss,&s->low);\n\tsp_del(ss->event_fd, s->fd);\n\tsocket_lock(l);\n\tif (type != SOCKET_TYPE_BIND) {\n\t\tif (close(s->fd) < 0) {\n\t\t\tperror(\"close socket:\");\n\t\t}\n\t}\n\tATOM_STORE(&s->type, SOCKET_TYPE_INVALID);\n\tif (s->dw_buffer) {\n\t\tstruct socket_sendbuffer tmp;\n\t\ttmp.buffer = s->dw_buffer;\n\t\ttmp.sz = s->dw_size;\n\t\ttmp.id = s->id;\n\t\ttmp.type = (tmp.sz == USEROBJECT) ? SOCKET_BUFFER_OBJECT : SOCKET_BUFFER_MEMORY;\n\t\tfree_buffer(ss, &tmp);\n\t\ts->dw_buffer = NULL;\n\t}\n\tsocket_unlock(l);\n}\n\nvoid\nsocket_server_release(struct socket_server *ss) {\n\tint i;\n\tstruct socket_message dummy;\n\tfor (i=0;i<MAX_SOCKET;i++) {\n\t\tstruct socket *s = &ss->slot[i];\n\t\tstruct socket_lock l;\n\t\tsocket_lock_init(s, &l);\n\t\tif (ATOM_LOAD(&s->type) != SOCKET_TYPE_RESERVE) {\n\t\t\tforce_close(ss, s, &l, &dummy);\n\t\t}\n\t\tspinlock_destroy(&s->dw_lock);\n\t}\n\tclose(ss->sendctrl_fd);\n\tclose(ss->recvctrl_fd);\n\tsp_release(ss->event_fd);\n\tif (ss->reserve_fd >= 0)\n\t\tclose(ss->reserve_fd);\n\tFREE(ss);\n}\n\nstatic inline void\ncheck_wb_list(struct wb_list *s) {\n\tassert(s->head == NULL);\n\tassert(s->tail == NULL);\n}\n\nstatic inline int\nenable_write(struct socket_server *ss, struct socket *s, bool enable) {\n\tif (s->writing != enable) {\n\t\ts->writing = enable;\n\t\treturn sp_enable(ss->event_fd, s->fd, s, s->reading, enable);\n\t}\n\treturn 0;\n}\n\nstatic inline int\nenable_read(struct socket_server *ss, struct socket *s, bool enable) {\n\tif (s->reading != enable) {\n\t\ts->reading = enable;\n\t\treturn sp_enable(ss->event_fd, s->fd, s, enable, s->writing);\n\t}\n\treturn 0;\n}\n\nstatic struct socket *\nnew_fd(struct socket_server *ss, int id, int fd, int protocol, uintptr_t opaque, bool reading) {\n\tstruct socket * s = &ss->slot[HASH_ID(id)];\n\tassert(ATOM_LOAD(&s->type) == SOCKET_TYPE_RESERVE);\n\n\tif (sp_add(ss->event_fd, fd, s)) {\n\t\tATOM_STORE(&s->type, SOCKET_TYPE_INVALID);\n\t\treturn NULL;\n\t}\n\n\ts->id = id;\n\ts->fd = fd;\n\ts->reading = true;\n\ts->writing = false;\n\ts->closing = false;\n\tATOM_INIT(&s->sending , ID_TAG16(id) << 16 | 0);\n\ts->protocol = protocol;\n\ts->p.size = MIN_READ_BUFFER;\n\ts->opaque = opaque;\n\ts->wb_size = 0;\n\ts->warn_size = 0;\n\tcheck_wb_list(&s->high);\n\tcheck_wb_list(&s->low);\n\ts->dw_buffer = NULL;\n\ts->dw_size = 0;\n\tmemset(&s->stat, 0, sizeof(s->stat));\n\tif (enable_read(ss, s, reading)) {\n\t\tATOM_STORE(&s->type , SOCKET_TYPE_INVALID);\n\t\treturn NULL;\n\t}\n\treturn s;\n}\n\nstatic inline void\nstat_read(struct socket_server *ss, struct socket *s, int n) {\n\ts->stat.read += n;\n\ts->stat.rtime = ss->time;\n}\n\nstatic inline void\nstat_write(struct socket_server *ss, struct socket *s, int n) {\n\ts->stat.write += n;\n\ts->stat.wtime = ss->time;\n}\n\n// return -1 when connecting\nstatic int\nopen_socket(struct socket_server *ss, struct request_open * request, struct socket_message *result) {\n\tint id = request->id;\n\tresult->opaque = request->opaque;\n\tresult->id = id;\n\tresult->ud = 0;\n\tresult->data = NULL;\n\tstruct socket *ns;\n\tint status;\n\tstruct addrinfo ai_hints;\n\tstruct addrinfo *ai_list = NULL;\n\tstruct addrinfo *ai_ptr = NULL;\n\tchar port[16];\n\tsprintf(port, \"%d\", request->port);\n\tmemset(&ai_hints, 0, sizeof( ai_hints ) );\n\tai_hints.ai_family = AF_UNSPEC;\n\tai_hints.ai_socktype = SOCK_STREAM;\n\tai_hints.ai_protocol = IPPROTO_TCP;\n\n\tstatus = getaddrinfo( request->host, port, &ai_hints, &ai_list );\n\tif ( status != 0 ) {\n\t\tresult->data = (void *)gai_strerror(status);\n\t\tgoto _failed_getaddrinfo;\n\t}\n\tint sock= -1;\n\tfor (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next ) {\n\t\tsock = socket( ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol );\n\t\tif ( sock < 0 ) {\n\t\t\tcontinue;\n\t\t}\n\t\tsocket_keepalive(sock);\n\t\tsp_nonblocking(sock);\n\t\tstatus = connect( sock, ai_ptr->ai_addr, ai_ptr->ai_addrlen);\n\t\tif ( status != 0 && errno != EINPROGRESS) {\n\t\t\tclose(sock);\n\t\t\tsock = -1;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\n\tif (sock < 0) {\n\t\tresult->data = strerror(errno);\n\t\tgoto _failed;\n\t}\n\n\tns = new_fd(ss, id, sock, PROTOCOL_TCP, request->opaque, true);\n\tif (ns == NULL) {\n\t\tresult->data = \"reach skynet socket number limit\";\n\t\tgoto _failed;\n\t}\n\n\tif(status == 0) {\n\t\tATOM_STORE(&ns->type , SOCKET_TYPE_CONNECTED);\n\t\tstruct sockaddr * addr = ai_ptr->ai_addr;\n\t\tvoid * sin_addr = (ai_ptr->ai_family == AF_INET) ? (void*)&((struct sockaddr_in *)addr)->sin_addr : (void*)&((struct sockaddr_in6 *)addr)->sin6_addr;\n\t\tif (inet_ntop(ai_ptr->ai_family, sin_addr, ss->buffer, sizeof(ss->buffer))) {\n\t\t\tresult->data = ss->buffer;\n\t\t}\n\t\tfreeaddrinfo( ai_list );\n\t\treturn SOCKET_OPEN;\n\t} else {\n\t\tif (enable_write(ss, ns, true)) {\n\t\t\tresult->data = \"enable write failed\";\n\t\t\tgoto _failed;\n\t\t}\n\t\tATOM_STORE(&ns->type , SOCKET_TYPE_CONNECTING);\n\t}\n\n\tfreeaddrinfo( ai_list );\n\treturn -1;\n_failed:\n\tif (sock >= 0)\n\t\tclose(sock);\n\tfreeaddrinfo( ai_list );\n_failed_getaddrinfo:\n\tATOM_STORE(&ss->slot[HASH_ID(id)].type, SOCKET_TYPE_INVALID);\n\treturn SOCKET_ERR;\n}\n\nstatic int\nreport_error(struct socket *s, struct socket_message *result, const char *err) {\n\tresult->id = s->id;\n\tresult->ud = 0;\n\tresult->opaque = s->opaque;\n\tresult->data = (char *)err;\n\treturn SOCKET_ERR;\n}\n\nstatic int\nclose_write(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message *result) {\n\tif (s->closing) {\n\t\tforce_close(ss,s,l,result);\n\t\treturn SOCKET_RST;\n\t} else {\n\t\tint t = ATOM_LOAD(&s->type);\n\t\tif (t == SOCKET_TYPE_HALFCLOSE_READ) {\n\t\t\t// recv 0 before, ignore the error and close fd\n\t\t\tforce_close(ss,s,l,result);\n\t\t\treturn SOCKET_RST;\n\t\t}\n\t\tif (t == SOCKET_TYPE_HALFCLOSE_WRITE) {\n\t\t\t// already raise SOCKET_ERR\n\t\t\treturn SOCKET_RST;\n\t\t}\n\t\tATOM_STORE(&s->type, SOCKET_TYPE_HALFCLOSE_WRITE);\n\t\tshutdown(s->fd, SHUT_WR);\n\t\tenable_write(ss, s, false);\n\t\treturn report_error(s, result, strerror(errno));\n\t}\n}\n\nstatic int\nsend_list_tcp(struct socket_server *ss, struct socket *s, struct wb_list *list, struct socket_lock *l, struct socket_message *result) {\n\twhile (list->head) {\n\t\tstruct write_buffer * tmp = list->head;\n\t\tfor (;;) {\n\t\t\tssize_t sz = write(s->fd, tmp->ptr, tmp->sz);\n\t\t\tif (sz < 0) {\n\t\t\t\tswitch(errno) {\n\t\t\t\tcase EINTR:\n\t\t\t\t\tcontinue;\n\t\t\t\tcase AGAIN_WOULDBLOCK:\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\treturn close_write(ss, s, l, result);\n\t\t\t}\n\t\t\tstat_write(ss,s,(int)sz);\n\t\t\ts->wb_size -= sz;\n\t\t\tif (sz != tmp->sz) {\n\t\t\t\ttmp->ptr += sz;\n\t\t\t\ttmp->sz -= sz;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tlist->head = tmp->next;\n\t\twrite_buffer_free(ss,tmp);\n\t}\n\tlist->tail = NULL;\n\n\treturn -1;\n}\n\nstatic socklen_t\nudp_socket_address(struct socket *s, const uint8_t udp_address[UDP_ADDRESS_SIZE], union sockaddr_all *sa) {\n\tint type = (uint8_t)udp_address[0];\n\tif (type != s->protocol)\n\t\treturn 0;\n\tuint16_t port = 0;\n\tmemcpy(&port, udp_address+1, sizeof(uint16_t));\n\tswitch (s->protocol) {\n\tcase PROTOCOL_UDP:\n\t\tmemset(&sa->v4, 0, sizeof(sa->v4));\n\t\tsa->s.sa_family = AF_INET;\n\t\tsa->v4.sin_port = port;\n\t\tmemcpy(&sa->v4.sin_addr, udp_address + 1 + sizeof(uint16_t), sizeof(sa->v4.sin_addr));\t// ipv4 address is 32 bits\n\t\treturn sizeof(sa->v4);\n\tcase PROTOCOL_UDPv6:\n\t\tmemset(&sa->v6, 0, sizeof(sa->v6));\n\t\tsa->s.sa_family = AF_INET6;\n\t\tsa->v6.sin6_port = port;\n\t\tmemcpy(&sa->v6.sin6_addr, udp_address + 1 + sizeof(uint16_t), sizeof(sa->v6.sin6_addr)); // ipv6 address is 128 bits\n\t\treturn sizeof(sa->v6);\n\t}\n\treturn 0;\n}\n\nstatic void\ndrop_udp(struct socket_server *ss, struct socket *s, struct wb_list *list, struct write_buffer *tmp) {\n\ts->wb_size -= tmp->sz;\n\tlist->head = tmp->next;\n\tif (list->head == NULL)\n\t\tlist->tail = NULL;\n\twrite_buffer_free(ss,tmp);\n}\n\nstatic int\nsend_list_udp(struct socket_server *ss, struct socket *s, struct wb_list *list, struct socket_message *result) {\n\twhile (list->head) {\n\t\tstruct write_buffer * tmp = list->head;\n\t\tstruct write_buffer_udp * udp = (struct write_buffer_udp *)tmp;\n\t\tunion sockaddr_all sa;\n\t\tsocklen_t sasz = udp_socket_address(s, udp->udp_address, &sa);\n\t\tif (sasz == 0) {\n\t\t\tskynet_error(NULL, \"socket-server : udp (%d) error: type mismatch.\", s->id);\n\t\t\tdrop_udp(ss, s, list, tmp);\n\t\t\treturn -1;\n\t\t}\n\t\tint err = sendto(s->fd, tmp->ptr, tmp->sz, 0, &sa.s, sasz);\n\t\tif (err < 0) {\n\t\t\tswitch(errno) {\n\t\t\tcase EINTR:\n\t\t\tcase AGAIN_WOULDBLOCK:\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tskynet_error(NULL, \"socket-server : udp (%d) sendto error %s.\",s->id, strerror(errno));\n\t\t\tdrop_udp(ss, s, list, tmp);\n\t\t\treturn -1;\n\t\t}\n\t\tstat_write(ss,s,tmp->sz);\n\t\ts->wb_size -= tmp->sz;\n\t\tlist->head = tmp->next;\n\t\twrite_buffer_free(ss,tmp);\n\t}\n\tlist->tail = NULL;\n\n\treturn -1;\n}\n\nstatic int\nsend_list(struct socket_server *ss, struct socket *s, struct wb_list *list, struct socket_lock *l, struct socket_message *result) {\n\tif (s->protocol == PROTOCOL_TCP) {\n\t\treturn send_list_tcp(ss, s, list, l, result);\n\t} else {\n\t\treturn send_list_udp(ss, s, list, result);\n\t}\n}\n\nstatic inline int\nlist_uncomplete(struct wb_list *s) {\n\tstruct write_buffer *wb = s->head;\n\tif (wb == NULL)\n\t\treturn 0;\n\n\treturn (void *)wb->ptr != wb->buffer;\n}\n\nstatic void\nraise_uncomplete(struct socket * s) {\n\tstruct wb_list *low = &s->low;\n\tstruct write_buffer *tmp = low->head;\n\tlow->head = tmp->next;\n\tif (low->head == NULL) {\n\t\tlow->tail = NULL;\n\t}\n\n\t// move head of low list (tmp) to the empty high list\n\tstruct wb_list *high = &s->high;\n\tassert(high->head == NULL);\n\n\ttmp->next = NULL;\n\thigh->head = high->tail = tmp;\n}\n\nstatic inline int\nsend_buffer_empty(struct socket *s) {\n\treturn (s->high.head == NULL && s->low.head == NULL);\n}\n\n/*\n\tEach socket has two write buffer list, high priority and low priority.\n\n\t1. send high list as far as possible.\n\t2. If high list is empty, try to send low list.\n\t3. If low list head is uncomplete (send a part before), move the head of low list to empty high list (call raise_uncomplete) .\n\t4. If two lists are both empty, turn off the event. (call check_close)\n */\nstatic int\nsend_buffer_(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message *result) {\n\tassert(!list_uncomplete(&s->low));\n\t// step 1\n\tint ret = send_list(ss,s,&s->high,l,result);\n\tif (ret != -1) {\n\t\tif (ret == SOCKET_ERR) {\n\t\t\t// HALFCLOSE_WRITE\n\t\t\treturn SOCKET_ERR;\n\t\t}\n\t\t// SOCKET_RST (ignore)\n\t\treturn -1;\n\t}\n\tif (s->high.head == NULL) {\n\t\t// step 2\n\t\tif (s->low.head != NULL) {\n\t\t\tint ret = send_list(ss,s,&s->low,l,result);\n\t\t\tif (ret != -1) {\n\t\t\t\tif (ret == SOCKET_ERR) {\n\t\t\t\t\t// HALFCLOSE_WRITE\n\t\t\t\t\treturn SOCKET_ERR;\n\t\t\t\t}\n\t\t\t\t// SOCKET_RST (ignore)\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\t// step 3\n\t\t\tif (list_uncomplete(&s->low)) {\n\t\t\t\traise_uncomplete(s);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (s->low.head)\n\t\t\t\treturn -1;\n\t\t}\n\t\t// step 4\n\t\tassert(send_buffer_empty(s) && s->wb_size == 0);\n\n\t\tif (s->closing) {\n\t\t\t// finish writing\n\t\t\tforce_close(ss, s, l, result);\n\t\t\treturn -1;\n\t\t}\n\n\t\tint err = enable_write(ss, s, false);\n\n\t\tif (err) {\n\t\t\treturn report_error(s, result, \"disable write failed\");\n\t\t}\n\n\t\tif(s->warn_size > 0){\n\t\t\ts->warn_size = 0;\n\t\t\tresult->opaque = s->opaque;\n\t\t\tresult->id = s->id;\n\t\t\tresult->ud = 0;\n\t\t\tresult->data = NULL;\n\t\t\treturn SOCKET_WARNING;\n\t\t}\n\t}\n\n\treturn -1;\n}\n\nstatic int\nsend_buffer(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message *result) {\n\tif (!socket_trylock(l))\n\t\treturn -1;\t// blocked by direct write, send later.\n\tif (s->dw_buffer) {\n\t\t// add direct write buffer before high.head\n\t\tstruct write_buffer * buf = MALLOC(sizeof(*buf));\n\t\tstruct send_object so;\n\t\tbuf->userobject = send_object_init(ss, &so, (void *)s->dw_buffer, s->dw_size);\n\t\tbuf->ptr = (char*)so.buffer+s->dw_offset;\n\t\tbuf->sz = so.sz - s->dw_offset;\n\t\tbuf->buffer = (void *)s->dw_buffer;\n\t\ts->wb_size+=buf->sz;\n\t\tif (s->high.head == NULL) {\n\t\t\ts->high.head = s->high.tail = buf;\n\t\t\tbuf->next = NULL;\n\t\t} else {\n\t\t\tbuf->next = s->high.head;\n\t\t\ts->high.head = buf;\n\t\t}\n\t\ts->dw_buffer = NULL;\n\t}\n\tint r = send_buffer_(ss,s,l,result);\n\tsocket_unlock(l);\n\n\treturn r;\n}\n\nstatic struct write_buffer *\nappend_sendbuffer_(struct socket_server *ss, struct wb_list *s, struct request_send * request, int size) {\n\tstruct write_buffer * buf = MALLOC(size);\n\tstruct send_object so;\n\tbuf->userobject = send_object_init(ss, &so, request->buffer, request->sz);\n\tbuf->ptr = (char*)so.buffer;\n\tbuf->sz = so.sz;\n\tbuf->buffer = request->buffer;\n\tbuf->next = NULL;\n\tif (s->head == NULL) {\n\t\ts->head = s->tail = buf;\n\t} else {\n\t\tassert(s->tail != NULL);\n\t\tassert(s->tail->next == NULL);\n\t\ts->tail->next = buf;\n\t\ts->tail = buf;\n\t}\n\treturn buf;\n}\n\nstatic inline void\nappend_sendbuffer_udp(struct socket_server *ss, struct socket *s, int priority, struct request_send * request, const uint8_t udp_address[UDP_ADDRESS_SIZE]) {\n\tstruct wb_list *wl = (priority == PRIORITY_HIGH) ? &s->high : &s->low;\n\tstruct write_buffer_udp *buf = (struct write_buffer_udp *)append_sendbuffer_(ss, wl, request, sizeof(*buf));\n\tmemcpy(buf->udp_address, udp_address, UDP_ADDRESS_SIZE);\n\ts->wb_size += buf->buffer.sz;\n}\n\nstatic inline void\nappend_sendbuffer(struct socket_server *ss, struct socket *s, struct request_send * request) {\n\tstruct write_buffer *buf = append_sendbuffer_(ss, &s->high, request, sizeof(*buf));\n\ts->wb_size += buf->sz;\n}\n\nstatic inline void\nappend_sendbuffer_low(struct socket_server *ss,struct socket *s, struct request_send * request) {\n\tstruct write_buffer *buf = append_sendbuffer_(ss, &s->low, request, sizeof(*buf));\n\ts->wb_size += buf->sz;\n}\n\nstatic int\ntrigger_write(struct socket_server *ss, struct request_send * request, struct socket_message *result) {\n\tint id = request->id;\n\tstruct socket * s = &ss->slot[HASH_ID(id)];\n\tif (socket_invalid(s, id))\n\t\treturn -1;\n\tif (enable_write(ss, s, true)) {\n\t\treturn report_error(s, result, \"enable write failed\");\n\t}\n\treturn -1;\n}\n\n/*\n\tWhen send a package , we can assign the priority : PRIORITY_HIGH or PRIORITY_LOW\n\n\tIf socket buffer is empty, write to fd directly.\n\t\tIf write a part, append the rest part to high list. (Even priority is PRIORITY_LOW)\n\tElse append package to high (PRIORITY_HIGH) or low (PRIORITY_LOW) list.\n */\nstatic int\nsend_socket(struct socket_server *ss, struct request_send * request, struct socket_message *result, int priority, const uint8_t *udp_address) {\n\tint id = request->id;\n\tstruct socket * s = &ss->slot[HASH_ID(id)];\n\tstruct send_object so;\n\tsend_object_init(ss, &so, request->buffer, request->sz);\n\tuint8_t type = ATOM_LOAD(&s->type);\n\tif (type == SOCKET_TYPE_INVALID || s->id != id\n\t\t|| type == SOCKET_TYPE_HALFCLOSE_WRITE\n\t\t|| type == SOCKET_TYPE_PACCEPT\n\t\t|| s->closing) {\n\t\tso.free_func((void *)request->buffer);\n\t\treturn -1;\n\t}\n\tif (type == SOCKET_TYPE_PLISTEN || type == SOCKET_TYPE_LISTEN) {\n\t\tskynet_error(NULL, \"socket-server error: write to listen fd %d.\", id);\n\t\tso.free_func((void *)request->buffer);\n\t\treturn -1;\n\t}\n\tif (send_buffer_empty(s)) {\n\t\tif (s->protocol == PROTOCOL_TCP) {\n\t\t\tappend_sendbuffer(ss, s, request);\t// add to high priority list, even priority == PRIORITY_LOW\n\t\t} else {\n\t\t\t// udp\n\t\t\tif (udp_address == NULL) {\n\t\t\t\tudp_address = s->p.udp_address;\n\t\t\t}\n\t\t\tunion sockaddr_all sa;\n\t\t\tsocklen_t sasz = udp_socket_address(s, udp_address, &sa);\n\t\t\tif (sasz == 0) {\n\t\t\t\t// udp type mismatch, just drop it.\n\t\t\t\tskynet_error(NULL, \"socket-server: udp socket (%d) error: type mismatch.\", id);\n\t\t\t\tso.free_func((void *)request->buffer);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tint n = sendto(s->fd, so.buffer, so.sz, 0, &sa.s, sasz);\n\t\t\tif (n != so.sz) {\n\t\t\t\tappend_sendbuffer_udp(ss,s,priority,request,udp_address);\n\t\t\t} else {\n\t\t\t\tstat_write(ss,s,n);\n\t\t\t\tso.free_func((void *)request->buffer);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tif (enable_write(ss, s, true)) {\n\t\t\treturn report_error(s, result, \"enable write failed\");\n\t\t}\n\t} else {\n\t\tif (s->protocol == PROTOCOL_TCP) {\n\t\t\tif (priority == PRIORITY_LOW) {\n\t\t\t\tappend_sendbuffer_low(ss, s, request);\n\t\t\t} else {\n\t\t\t\tappend_sendbuffer(ss, s, request);\n\t\t\t}\n\t\t} else {\n\t\t\tif (udp_address == NULL) {\n\t\t\t\tudp_address = s->p.udp_address;\n\t\t\t}\n\t\t\tappend_sendbuffer_udp(ss,s,priority,request,udp_address);\n\t\t}\n\t}\n\tif (s->wb_size >= WARNING_SIZE && s->wb_size >= s->warn_size) {\n\t\ts->warn_size = s->warn_size == 0 ? WARNING_SIZE *2 : s->warn_size*2;\n\t\tresult->opaque = s->opaque;\n\t\tresult->id = s->id;\n\t\tresult->ud = s->wb_size%1024 == 0 ? s->wb_size/1024 : s->wb_size/1024 + 1;\n\t\tresult->data = NULL;\n\t\treturn SOCKET_WARNING;\n\t}\n\treturn -1;\n}\n\nstatic int\nlisten_socket(struct socket_server *ss, struct request_listen * request, struct socket_message *result) {\n\tint id = request->id;\n\tint listen_fd = request->fd;\n\tstruct socket *s = new_fd(ss, id, listen_fd, PROTOCOL_TCP, request->opaque, false);\n\tif (s == NULL) {\n\t\tgoto _failed;\n\t}\n\tATOM_STORE(&s->type , SOCKET_TYPE_PLISTEN);\n\tresult->opaque = request->opaque;\n\tresult->id = id;\n\tresult->ud = 0;\n\tresult->data = \"listen\";\n\n\tunion sockaddr_all u;\n\tsocklen_t slen = sizeof(u);\n\tif (getsockname(listen_fd, &u.s, &slen) == 0) {\n\t\tvoid * sin_addr = (u.s.sa_family == AF_INET) ? (void*)&u.v4.sin_addr : (void *)&u.v6.sin6_addr;\n\t\tif (inet_ntop(u.s.sa_family, sin_addr, ss->buffer, sizeof(ss->buffer)) == 0) {\n\t\t\tresult->data = strerror(errno);\n\t\t\treturn SOCKET_ERR;\n\t\t}\n\t\tint sin_port = ntohs((u.s.sa_family == AF_INET) ? u.v4.sin_port : u.v6.sin6_port);\n\t\tresult->data = ss->buffer;\n\t\tresult->ud = sin_port;\n\t} else {\n\t\tresult->data = strerror(errno);\n\t\treturn SOCKET_ERR;\n\t}\n\n\treturn SOCKET_OPEN;\n_failed:\n\tclose(listen_fd);\n\tresult->opaque = request->opaque;\n\tresult->id = id;\n\tresult->ud = 0;\n\tresult->data = \"reach skynet socket number limit\";\n\tss->slot[HASH_ID(id)].type = SOCKET_TYPE_INVALID;\n\n\treturn SOCKET_ERR;\n}\n\nstatic inline int\nnomore_sending_data(struct socket *s) {\n\treturn (send_buffer_empty(s) && s->dw_buffer == NULL && (ATOM_LOAD(&s->sending) & 0xffff) == 0)\n\t\t|| (ATOM_LOAD(&s->type) == SOCKET_TYPE_HALFCLOSE_WRITE);\n}\n\nstatic void\nclose_read(struct socket_server *ss, struct socket * s, struct socket_message *result) {\n\t// Don't read socket later\n\tATOM_STORE(&s->type , SOCKET_TYPE_HALFCLOSE_READ);\n\tenable_read(ss,s,false);\n\tshutdown(s->fd, SHUT_RD);\n\tresult->id = s->id;\n\tresult->ud = 0;\n\tresult->data = NULL;\n\tresult->opaque = s->opaque;\n}\n\nstatic inline int\nhalfclose_read(struct socket *s) {\n\treturn ATOM_LOAD(&s->type) == SOCKET_TYPE_HALFCLOSE_READ;\n}\n\n// SOCKET_CLOSE can be raised (only once) in one of two conditions.\n// See https://github.com/cloudwu/skynet/issues/1346 for more discussion.\n// 1. close socket by self, See close_socket()\n// 2. recv 0 or eof event (close socket by remote), See forward_message_tcp()\n// It's able to write data after SOCKET_CLOSE (In condition 2), but if remote is closed, SOCKET_ERR may raised.\nstatic int\nclose_socket(struct socket_server *ss, struct request_close *request, struct socket_message *result) {\n\tint id = request->id;\n\tstruct socket * s = &ss->slot[HASH_ID(id)];\n\tif (socket_invalid(s, id)) {\n\t\t// The socket is closed, ignore\n\t\treturn -1;\n\t}\n\tstruct socket_lock l;\n\tsocket_lock_init(s, &l);\n\n\tint shutdown_read = halfclose_read(s);\n\n\tif (request->shutdown || nomore_sending_data(s)) {\n\t\t// If socket is SOCKET_TYPE_HALFCLOSE_READ, Do not raise SOCKET_CLOSE again.\n\t\tint r = shutdown_read ? -1 : SOCKET_CLOSE;\n\t\tforce_close(ss,s,&l,result);\n\t\treturn r;\n\t}\n\ts->closing = true;\n\tif (!shutdown_read) {\n\t\t// don't read socket after socket.close()\n\t\tclose_read(ss, s, result);\n\t\treturn SOCKET_CLOSE;\n\t}\n\t// recv 0 before (socket is SOCKET_TYPE_HALFCLOSE_READ) and waiting for sending data out.\n\treturn -1;\n}\n\nstatic int\nbind_socket(struct socket_server *ss, struct request_bind *request, struct socket_message *result) {\n\tint id = request->id;\n\tresult->id = id;\n\tresult->opaque = request->opaque;\n\tresult->ud = 0;\n\tstruct socket *s = new_fd(ss, id, request->fd, PROTOCOL_TCP, request->opaque, true);\n\tif (s == NULL) {\n\t\tresult->data = \"reach skynet socket number limit\";\n\t\treturn SOCKET_ERR;\n\t}\n\tsp_nonblocking(request->fd);\n\tATOM_STORE(&s->type , SOCKET_TYPE_BIND);\n\tresult->data = \"binding\";\n\treturn SOCKET_OPEN;\n}\n\nstatic int\nresume_socket(struct socket_server *ss, struct request_resumepause *request, struct socket_message *result) {\n\tint id = request->id;\n\tresult->id = id;\n\tresult->opaque = request->opaque;\n\tresult->ud = 0;\n\tresult->data = NULL;\n\tstruct socket *s = &ss->slot[HASH_ID(id)];\n\tif (socket_invalid(s, id)) {\n\t\tresult->data = \"invalid socket\";\n\t\treturn SOCKET_ERR;\n\t}\n\tif (halfclose_read(s)) {\n\t\t// The closing socket may be in transit, so raise an error. See https://github.com/cloudwu/skynet/issues/1374\n\t\tresult->data = \"socket closed\";\n\t\treturn SOCKET_ERR;\n\t}\n\tstruct socket_lock l;\n\tsocket_lock_init(s, &l);\n\tif (enable_read(ss, s, true)) {\n\t\tresult->data = \"enable read failed\";\n\t\treturn SOCKET_ERR;\n\t}\n\tuint8_t type = ATOM_LOAD(&s->type);\n\tif (type == SOCKET_TYPE_PACCEPT || type == SOCKET_TYPE_PLISTEN) {\n\t\tATOM_STORE(&s->type , (type == SOCKET_TYPE_PACCEPT) ? SOCKET_TYPE_CONNECTED : SOCKET_TYPE_LISTEN);\n\t\ts->opaque = request->opaque;\n\t\tresult->data = \"start\";\n\t\treturn SOCKET_OPEN;\n\t} else if (type == SOCKET_TYPE_CONNECTED) {\n\t\t// todo: maybe we should send a message SOCKET_TRANSFER to s->opaque\n\t\ts->opaque = request->opaque;\n\t\tresult->data = \"transfer\";\n\t\treturn SOCKET_OPEN;\n\t}\n\t// if s->type == SOCKET_TYPE_HALFCLOSE_WRITE , SOCKET_CLOSE message will send later\n\treturn -1;\n}\n\nstatic int\npause_socket(struct socket_server *ss, struct request_resumepause *request, struct socket_message *result) {\n\tint id = request->id;\n\tstruct socket *s = &ss->slot[HASH_ID(id)];\n\tif (socket_invalid(s, id)) {\n\t\treturn -1;\n\t}\n\tif (enable_read(ss, s, false)) {\n\t\treturn report_error(s, result, \"enable read failed\");\n\t}\n\treturn -1;\n}\n\nstatic void\nsetopt_socket(struct socket_server *ss, struct request_setopt *request) {\n\tint id = request->id;\n\tstruct socket *s = &ss->slot[HASH_ID(id)];\n\tif (socket_invalid(s, id)) {\n\t\treturn;\n\t}\n\tint v = request->value;\n\tsetsockopt(s->fd, IPPROTO_TCP, request->what, &v, sizeof(v));\n}\n\nstatic void\nblock_readpipe(int pipefd, void *buffer, int sz) {\n\tfor (;;) {\n\t\tint n = read(pipefd, buffer, sz);\n\t\tif (n<0) {\n\t\t\tif (errno == EINTR)\n\t\t\t\tcontinue;\n\t\t\tskynet_error(NULL, \"socket-server : read pipe error %s.\",strerror(errno));\n\t\t\treturn;\n\t\t}\n\t\t// must atomic read from a pipe\n\t\tassert(n == sz);\n\t\treturn;\n\t}\n}\n\nstatic int\nhas_cmd(struct socket_server *ss) {\n\tstruct timeval tv = {0,0};\n\tint retval;\n\n\tFD_SET(ss->recvctrl_fd, &ss->rfds);\n\n\tretval = select(ss->recvctrl_fd+1, &ss->rfds, NULL, NULL, &tv);\n\tif (retval == 1) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic void\nadd_udp_socket(struct socket_server *ss, struct request_udp *udp) {\n\tint id = udp->id;\n\tint protocol;\n\tif (udp->family == AF_INET6) {\n\t\tprotocol = PROTOCOL_UDPv6;\n\t} else {\n\t\tprotocol = PROTOCOL_UDP;\n\t}\n\tstruct socket *ns = new_fd(ss, id, udp->fd, protocol, udp->opaque, true);\n\tif (ns == NULL) {\n\t\tclose(udp->fd);\n\t\tss->slot[HASH_ID(id)].type = SOCKET_TYPE_INVALID;\n\t\treturn;\n\t}\n\tATOM_STORE(&ns->type , SOCKET_TYPE_CONNECTED);\n\tmemset(ns->p.udp_address, 0, sizeof(ns->p.udp_address));\n}\n\nstatic int\nset_udp_address(struct socket_server *ss, struct request_setudp *request, struct socket_message *result) {\n\tint id = request->id;\n\tstruct socket *s = &ss->slot[HASH_ID(id)];\n\tif (socket_invalid(s, id)) {\n\t\treturn -1;\n\t}\n\tint type = request->address[0];\n\tif (type != s->protocol) {\n\t\t// protocol mismatch\n\t\treturn report_error(s, result, \"protocol mismatch\");\n\t}\n\tif (type == PROTOCOL_UDP) {\n\t\tmemcpy(s->p.udp_address, request->address, 1+2+4);\t// 1 type, 2 port, 4 ipv4\n\t} else {\n\t\tmemcpy(s->p.udp_address, request->address, 1+2+16);\t// 1 type, 2 port, 16 ipv6\n\t}\n\tATOM_FDEC(&s->udpconnecting);\n\treturn -1;\n}\n\nstatic int\ndial_udp_socket(struct socket_server *ss, struct request_dial_udp *request, struct socket_message *result){\n\tint id = request->id;\n\tint protocol = request->address[0];\n\n\tstruct socket *ns = new_fd(ss, id, request->fd, protocol, request->opaque, true);\n\tif (ns == NULL){\n\t\tclose(request->fd);\n\t\tss->slot[HASH_ID(id)].type = SOCKET_TYPE_INVALID;\n\t\treturn -1;\n\t}\n\n\tif (protocol == PROTOCOL_UDP){\n\t\tmemcpy(ns->p.udp_address, request->address, 1 + 2 + 4);\n\t} else {\n\t\tmemcpy(ns->p.udp_address, request->address, 1 + 2 + 16);\n\t}\n\n\tATOM_STORE(&ns->type , SOCKET_TYPE_CONNECTED);\n\n\tATOM_FDEC(&ns->udpconnecting);\n\treturn -1;\n}\n\nstatic inline void\ninc_sending_ref(struct socket *s, int id) {\n\tif (s->protocol != PROTOCOL_TCP)\n\t\treturn;\n\tfor (;;) {\n\t\tunsigned long sending = ATOM_LOAD(&s->sending);\n\t\tif ((sending >> 16) == ID_TAG16(id)) {\n\t\t\tif ((sending & 0xffff) == 0xffff) {\n\t\t\t\t// s->sending may overflow (rarely), so busy waiting here for socket thread dec it. see issue #794\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// inc sending only matching the same socket id\n\t\t\tif (ATOM_CAS_ULONG(&s->sending, sending, sending + 1))\n\t\t\t\treturn;\n\t\t\t// atom inc failed, retry\n\t\t} else {\n\t\t\t// socket id changed, just return\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nstatic inline void\ndec_sending_ref(struct socket_server *ss, int id) {\n\tstruct socket * s = &ss->slot[HASH_ID(id)];\n\t// Notice: udp may inc sending while type == SOCKET_TYPE_RESERVE\n\tif (s->id == id && s->protocol == PROTOCOL_TCP) {\n\t\tassert((ATOM_LOAD(&s->sending) & 0xffff) != 0);\n\t\tATOM_FDEC(&s->sending);\n\t}\n}\n\n// return type\nstatic int\nctrl_cmd(struct socket_server *ss, struct socket_message *result) {\n\tint fd = ss->recvctrl_fd;\n\t// the length of message is one byte, so 256 buffer size is enough.\n\tuint8_t buffer[256];\n\tuint8_t header[2];\n\tblock_readpipe(fd, header, sizeof(header));\n\tint type = header[0];\n\tint len = header[1];\n\tblock_readpipe(fd, buffer, len);\n\t// ctrl command only exist in local fd, so don't worry about endian.\n\tswitch (type) {\n\tcase 'R':\n\t\treturn resume_socket(ss,(struct request_resumepause *)buffer, result);\n\tcase 'S':\n\t\treturn pause_socket(ss,(struct request_resumepause *)buffer, result);\n\tcase 'B':\n\t\treturn bind_socket(ss,(struct request_bind *)buffer, result);\n\tcase 'L':\n\t\treturn listen_socket(ss,(struct request_listen *)buffer, result);\n\tcase 'K':\n\t\treturn close_socket(ss,(struct request_close *)buffer, result);\n\tcase 'O':\n\t\treturn open_socket(ss, (struct request_open *)buffer, result);\n\tcase 'X':\n\t\tresult->opaque = 0;\n\t\tresult->id = 0;\n\t\tresult->ud = 0;\n\t\tresult->data = NULL;\n\t\treturn SOCKET_EXIT;\n\tcase 'W':\n\t\treturn trigger_write(ss, (struct request_send *)buffer, result);\n\tcase 'D':\n\tcase 'P': {\n\t\tint priority = (type == 'D') ? PRIORITY_HIGH : PRIORITY_LOW;\n\t\tstruct request_send * request = (struct request_send *) buffer;\n\t\tint ret = send_socket(ss, request, result, priority, NULL);\n\t\tdec_sending_ref(ss, request->id);\n\t\treturn ret;\n\t}\n\tcase 'A': {\n\t\tstruct request_send_udp * rsu = (struct request_send_udp *)buffer;\n\t\treturn send_socket(ss, &rsu->send, result, PRIORITY_HIGH, rsu->address);\n\t}\n\tcase 'C':\n\t\treturn set_udp_address(ss, (struct request_setudp *)buffer, result);\n\tcase 'N':\n\t\treturn dial_udp_socket(ss, (struct request_dial_udp *)buffer, result);\n\tcase 'T':\n\t\tsetopt_socket(ss, (struct request_setopt *)buffer);\n\t\treturn -1;\n\tcase 'U':\n\t\tadd_udp_socket(ss, (struct request_udp *)buffer);\n\t\treturn -1;\n\tdefault:\n\t\tskynet_error(NULL, \"socket-server error: Unknown ctrl %c.\",type);\n\t\treturn -1;\n\t};\n\n\treturn -1;\n}\n\n// return -1 (ignore) when error\nstatic int\nforward_message_tcp(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message * result) {\n\tint sz = s->p.size;\n\tchar * buffer = MALLOC(sz);\n\tint n = (int)read(s->fd, buffer, sz);\n\tif (n<0) {\n\t\tFREE(buffer);\n\t\tswitch(errno) {\n\t\tcase EINTR:\n\t\tcase AGAIN_WOULDBLOCK:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn report_error(s, result, strerror(errno));\n\t\t}\n\t\treturn -1;\n\t}\n\tif (n==0) {\n\t\tFREE(buffer);\n\t\tif (s->closing) {\n\t\t\t// Rare case : if s->closing is true, reading event is disable, and SOCKET_CLOSE is raised.\n\t\t\tif (nomore_sending_data(s)) {\n\t\t\t\tforce_close(ss,s,l,result);\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t\tint t = ATOM_LOAD(&s->type);\n\t\tif (t == SOCKET_TYPE_HALFCLOSE_READ) {\n\t\t\t// Rare case : Already shutdown read.\n\t\t\treturn -1;\n\t\t}\n\t\tif (t == SOCKET_TYPE_HALFCLOSE_WRITE) {\n\t\t\t// Remote shutdown read (write error) before.\n\t\t\tforce_close(ss,s,l,result);\n\t\t} else {\n\t\t\tclose_read(ss, s, result);\n\t\t}\n\t\treturn SOCKET_CLOSE;\n\t}\n\n\tif (halfclose_read(s)) {\n\t\t// discard recv data (Rare case : if socket is HALFCLOSE_READ, reading event is disable.)\n\t\tFREE(buffer);\n\t\treturn -1;\n\t}\n\n\tstat_read(ss,s,n);\n\n\tresult->opaque = s->opaque;\n\tresult->id = s->id;\n\tresult->ud = n;\n\tresult->data = buffer;\n\n\tif (n == sz) {\n\t\ts->p.size *= 2;\n\t\treturn SOCKET_MORE;\n\t} else if (sz > MIN_READ_BUFFER && n*2 < sz) {\n\t\ts->p.size /= 2;\n\t}\n\n\treturn SOCKET_DATA;\n}\n\nstatic int\ngen_udp_address(int protocol, union sockaddr_all *sa, uint8_t * udp_address) {\n\tint addrsz = 1;\n\tudp_address[0] = (uint8_t)protocol;\n\tif (protocol == PROTOCOL_UDP) {\n\t\tmemcpy(udp_address+addrsz, &sa->v4.sin_port, sizeof(sa->v4.sin_port));\n\t\taddrsz += sizeof(sa->v4.sin_port);\n\t\tmemcpy(udp_address+addrsz, &sa->v4.sin_addr, sizeof(sa->v4.sin_addr));\n\t\taddrsz += sizeof(sa->v4.sin_addr);\n\t} else {\n\t\tmemcpy(udp_address+addrsz, &sa->v6.sin6_port, sizeof(sa->v6.sin6_port));\n\t\taddrsz += sizeof(sa->v6.sin6_port);\n\t\tmemcpy(udp_address+addrsz, &sa->v6.sin6_addr, sizeof(sa->v6.sin6_addr));\n\t\taddrsz += sizeof(sa->v6.sin6_addr);\n\t}\n\treturn addrsz;\n}\n\nstatic int\nforward_message_udp(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message * result) {\n\tunion sockaddr_all sa;\n\tsocklen_t slen = sizeof(sa);\n\tint n = recvfrom(s->fd, ss->udpbuffer,MAX_UDP_PACKAGE,0,&sa.s,&slen);\n\tif (n<0) {\n\t\tswitch(errno) {\n\t\tcase EINTR:\n\t\tcase AGAIN_WOULDBLOCK:\n\t\t\treturn -1;\n\t\t}\n\t\tint error = errno;\n\t\t// close when error\n\t\tforce_close(ss, s, l, result);\n\t\tresult->data = strerror(error);\n\t\treturn SOCKET_ERR;\n\t}\n\tstat_read(ss,s,n);\n\n\tuint8_t * data;\n\tif (slen == sizeof(sa.v4)) {\n\t\tif (s->protocol != PROTOCOL_UDP)\n\t\t\treturn -1;\n\t\tdata = MALLOC(n + 1 + 2 + 4);\n\t\tgen_udp_address(PROTOCOL_UDP, &sa, data + n);\n\t} else {\n\t\tif (s->protocol != PROTOCOL_UDPv6)\n\t\t\treturn -1;\n\t\tdata = MALLOC(n + 1 + 2 + 16);\n\t\tgen_udp_address(PROTOCOL_UDPv6, &sa, data + n);\n\t}\n\tmemcpy(data, ss->udpbuffer, n);\n\n\tresult->opaque = s->opaque;\n\tresult->id = s->id;\n\tresult->ud = n;\n\tresult->data = (char *)data;\n\n\treturn SOCKET_UDP;\n}\n\nstatic int\nreport_connect(struct socket_server *ss, struct socket *s, struct socket_lock *l, struct socket_message *result) {\n\tint error;\n\tsocklen_t len = sizeof(error);\n\tint code = getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &error, &len);\n\tif (code < 0 || error) {\n\t\terror = code < 0 ? errno : error;\n\t\tforce_close(ss, s, l, result);\n\t\tresult->data = strerror(error);\n\t\treturn SOCKET_ERR;\n\t} else {\n\t\tATOM_STORE(&s->type , SOCKET_TYPE_CONNECTED);\n\t\tresult->opaque = s->opaque;\n\t\tresult->id = s->id;\n\t\tresult->ud = 0;\n\t\tif (nomore_sending_data(s)) {\n\t\t\tif (enable_write(ss, s, false)) {\n\t\t\t\tforce_close(ss,s,l, result);\n\t\t\t\tresult->data = \"disable write failed\";\n\t\t\t\treturn SOCKET_ERR;\n\t\t\t}\n\t\t}\n\t\tunion sockaddr_all u;\n\t\tsocklen_t slen = sizeof(u);\n\t\tif (getpeername(s->fd, &u.s, &slen) == 0) {\n\t\t\tvoid * sin_addr = (u.s.sa_family == AF_INET) ? (void*)&u.v4.sin_addr : (void *)&u.v6.sin6_addr;\n\t\t\tif (inet_ntop(u.s.sa_family, sin_addr, ss->buffer, sizeof(ss->buffer))) {\n\t\t\t\tresult->data = ss->buffer;\n\t\t\t\treturn SOCKET_OPEN;\n\t\t\t}\n\t\t}\n\t\tresult->data = NULL;\n\t\treturn SOCKET_OPEN;\n\t}\n}\n\nstatic int\ngetname(union sockaddr_all *u, char *buffer, size_t sz) {\n\tchar tmp[INET6_ADDRSTRLEN];\n\tvoid * sin_addr = (u->s.sa_family == AF_INET) ? (void*)&u->v4.sin_addr : (void *)&u->v6.sin6_addr;\n\tif (inet_ntop(u->s.sa_family, sin_addr, tmp, sizeof(tmp))) {\n\t\tint sin_port = ntohs((u->s.sa_family == AF_INET) ? u->v4.sin_port : u->v6.sin6_port);\n\t\tsnprintf(buffer, sz, \"%s:%d\", tmp, sin_port);\n\t\treturn 1;\n\t} else {\n\t\tbuffer[0] = '\\0';\n\t\treturn 0;\n\t}\n}\n\n// return 0 when failed, or -1 when file limit\nstatic int\nreport_accept(struct socket_server *ss, struct socket *s, struct socket_message *result) {\n\tunion sockaddr_all u;\n\tsocklen_t len = sizeof(u);\n\tint client_fd = accept(s->fd, &u.s, &len);\n\tif (client_fd < 0) {\n\t\tif (errno == EMFILE || errno == ENFILE) {\n\t\t\tresult->opaque = s->opaque;\n\t\t\tresult->id = s->id;\n\t\t\tresult->ud = 0;\n\t\t\tresult->data = strerror(errno);\n\n\t\t\t// See https://stackoverflow.com/questions/47179793/how-to-gracefully-handle-accept-giving-emfile-and-close-the-connection\n\t\t\tif (ss->reserve_fd >= 0) {\n\t\t\t\tclose(ss->reserve_fd);\n\t\t\t\tclient_fd = accept(s->fd, &u.s, &len);\n\t\t\t\tif (client_fd >= 0) {\n\t\t\t\t\tclose(client_fd);\n\t\t\t\t}\n\t\t\t\tss->reserve_fd = dup(1);\n\t\t\t}\n\t\t\treturn -1;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\tint id = reserve_id(ss);\n\tif (id < 0) {\n\t\tclose(client_fd);\n\t\treturn 0;\n\t}\n\tsocket_keepalive(client_fd);\n\tsp_nonblocking(client_fd);\n\tstruct socket *ns = new_fd(ss, id, client_fd, PROTOCOL_TCP, s->opaque, false);\n\tif (ns == NULL) {\n\t\tclose(client_fd);\n\t\treturn 0;\n\t}\n\t// accept new one connection\n\tstat_read(ss,s,1);\n\n\tATOM_STORE(&ns->type , SOCKET_TYPE_PACCEPT);\n\tresult->opaque = s->opaque;\n\tresult->id = s->id;\n\tresult->ud = id;\n\tresult->data = NULL;\n\n\tif (getname(&u, ss->buffer, sizeof(ss->buffer))) {\n\t\tresult->data = ss->buffer;\n\t}\n\n\treturn 1;\n}\n\nstatic inline void\nclear_closed_event(struct socket_server *ss, struct socket_message * result, int type) {\n\tif (type == SOCKET_CLOSE || type == SOCKET_ERR) {\n\t\tint id = result->id;\n\t\tint i;\n\t\tfor (i=ss->event_index; i<ss->event_n; i++) {\n\t\t\tstruct event *e = &ss->ev[i];\n\t\t\tstruct socket *s = e->s;\n\t\t\tif (s) {\n\t\t\t\tif (socket_invalid(s, id) && s->id == id) {\n\t\t\t\t\te->s = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// return type\nint\nsocket_server_poll(struct socket_server *ss, struct socket_message * result, int * more) {\n\tfor (;;) {\n\t\tif (ss->checkctrl) {\n\t\t\tif (has_cmd(ss)) {\n\t\t\t\tint type = ctrl_cmd(ss, result);\n\t\t\t\tif (type != -1) {\n\t\t\t\t\tclear_closed_event(ss, result, type);\n\t\t\t\t\treturn type;\n\t\t\t\t} else\n\t\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tss->checkctrl = 0;\n\t\t\t}\n\t\t}\n\t\tif (ss->event_index == ss->event_n) {\n\t\t\tss->event_n = sp_wait(ss->event_fd, ss->ev, MAX_EVENT);\n\t\t\tss->checkctrl = 1;\n\t\t\tif (more) {\n\t\t\t\t*more = 0;\n\t\t\t}\n\t\t\tss->event_index = 0;\n\t\t\tif (ss->event_n <= 0) {\n\t\t\t\tss->event_n = 0;\n\t\t\t\tint err = errno;\n\t\t\t\tif (err != EINTR) {\n\t\t\t\t\tskynet_error(NULL, \"socket-server error: %s\", strerror(err));\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tstruct event *e = &ss->ev[ss->event_index++];\n\t\tstruct socket *s = e->s;\n\t\tif (s == NULL) {\n\t\t\t// dispatch pipe message at beginning\n\t\t\tcontinue;\n\t\t}\n\t\tstruct socket_lock l;\n\t\tsocket_lock_init(s, &l);\n\t\tswitch (ATOM_LOAD(&s->type)) {\n\t\tcase SOCKET_TYPE_CONNECTING:\n\t\t\treturn report_connect(ss, s, &l, result);\n\t\tcase SOCKET_TYPE_LISTEN: {\n\t\t\tint ok = report_accept(ss, s, result);\n\t\t\tif (ok > 0) {\n\t\t\t\treturn SOCKET_ACCEPT;\n\t\t\t} if (ok < 0 ) {\n\t\t\t\treturn SOCKET_ERR;\n\t\t\t}\n\t\t\t// when ok == 0, retry\n\t\t\tbreak;\n\t\t}\n\t\tcase SOCKET_TYPE_INVALID:\n\t\t\tskynet_error(NULL, \"socket-server error: invalid socket\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (e->read) {\n\t\t\t\tint type;\n\t\t\t\tif (s->protocol == PROTOCOL_TCP) {\n\t\t\t\t\ttype = forward_message_tcp(ss, s, &l, result);\n\t\t\t\t\tif (type == SOCKET_MORE) {\n\t\t\t\t\t\t--ss->event_index;\n\t\t\t\t\t\treturn SOCKET_DATA;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttype = forward_message_udp(ss, s, &l, result);\n\t\t\t\t\tif (type == SOCKET_UDP) {\n\t\t\t\t\t\t// try read again\n\t\t\t\t\t\t--ss->event_index;\n\t\t\t\t\t\treturn SOCKET_UDP;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (e->write && type != SOCKET_CLOSE && type != SOCKET_ERR) {\n\t\t\t\t\t// Try to dispatch write message next step if write flag set.\n\t\t\t\t\te->read = false;\n\t\t\t\t\t--ss->event_index;\n\t\t\t\t}\n\t\t\t\tif (type == -1)\n\t\t\t\t\tbreak;\n\t\t\t\treturn type;\n\t\t\t}\n\t\t\tif (e->write) {\n\t\t\t\tint type = send_buffer(ss, s, &l, result);\n\t\t\t\tif (type == -1)\n\t\t\t\t\tbreak;\n\t\t\t\treturn type;\n\t\t\t}\n\t\t\tif (e->error) {\n\t\t\t\tint error;\n\t\t\t\tsocklen_t len = sizeof(error);\n\t\t\t\tint code = getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &error, &len);\n\t\t\t\tconst char * err = NULL;\n\t\t\t\tif (code < 0) {\n\t\t\t\t\terr = strerror(errno);\n\t\t\t\t} else if (error != 0) {\n\t\t\t\t\terr = strerror(error);\n\t\t\t\t} else {\n\t\t\t\t\terr = \"Unknown error\";\n\t\t\t\t}\n\t\t\t\treturn report_error(s, result, err);\n\t\t\t}\n\t\t\tif (e->eof) {\n\t\t\t\t// For epoll (at least), FIN packets are exchanged both ways.\n\t\t\t\t// See: https://stackoverflow.com/questions/52976152/tcp-when-is-epollhup-generated\n\t\t\t\tint halfclose = halfclose_read(s);\n\t\t\t\tforce_close(ss, s, &l, result);\n\t\t\t\tif (!halfclose) {\n\t\t\t\t\treturn SOCKET_CLOSE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nstatic void\nsend_request(struct socket_server *ss, struct request_package *request, char type, int len) {\n\trequest->header[6] = (uint8_t)type;\n\trequest->header[7] = (uint8_t)len;\n\tconst char * req = (const char *)request + offsetof(struct request_package, header[6]);\n\tfor (;;) {\n\t\tssize_t n = write(ss->sendctrl_fd, req, len+2);\n\t\tif (n<0) {\n\t\t\tif (errno != EINTR) {\n\t\t\t\tskynet_error(NULL, \"socket-server : send ctrl command error %s.\", strerror(errno));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tassert(n == len+2);\n\t\treturn;\n\t}\n}\n\nstatic int\nopen_request(struct socket_server *ss, struct request_package *req, uintptr_t opaque, const char *addr, int port) {\n\tint len = strlen(addr);\n\tif (len + sizeof(req->u.open) >= 256) {\n\t\tskynet_error(NULL, \"socket-server error: Invalid addr %s.\",addr);\n\t\treturn -1;\n\t}\n\tint id = reserve_id(ss);\n\tif (id < 0)\n\t\treturn -1;\n\treq->u.open.opaque = opaque;\n\treq->u.open.id = id;\n\treq->u.open.port = port;\n\tmemcpy(req->u.open.host, addr, len);\n\treq->u.open.host[len] = '\\0';\n\n\treturn len;\n}\n\nstatic inline void\nrequest_init(struct request_package *req) {\n\tmemset(req, 0, sizeof(*req));\n}\n\nint\nsocket_server_connect(struct socket_server *ss, uintptr_t opaque, const char * addr, int port) {\n\tstruct request_package request;\n\trequest_init(&request);\n\tint len = open_request(ss, &request, opaque, addr, port);\n\tif (len < 0)\n\t\treturn -1;\n\tsend_request(ss, &request, 'O', sizeof(request.u.open) + len);\n\treturn request.u.open.id;\n}\n\nstatic inline int\ncan_direct_write(struct socket *s, int id) {\n\treturn s->id == id && nomore_sending_data(s) && ATOM_LOAD(&s->type) == SOCKET_TYPE_CONNECTED && ATOM_LOAD(&s->udpconnecting) == 0;\n}\n\n// return -1 when error, 0 when success\nint\nsocket_server_send(struct socket_server *ss, struct socket_sendbuffer *buf) {\n\tint id = buf->id;\n\tstruct socket * s = &ss->slot[HASH_ID(id)];\n\tif (socket_invalid(s, id) || s->closing) {\n\t\tfree_buffer(ss, buf);\n\t\treturn -1;\n\t}\n\n\tstruct socket_lock l;\n\tsocket_lock_init(s, &l);\n\n\tif (can_direct_write(s,id) && socket_trylock(&l)) {\n\t\t// may be we can send directly, double check\n\t\tif (can_direct_write(s,id)) {\n\t\t\t// send directly\n\t\t\tstruct send_object so;\n\t\t\tsend_object_init_from_sendbuffer(ss, &so, buf);\n\t\t\tssize_t n;\n\t\t\tif (s->protocol == PROTOCOL_TCP) {\n\t\t\t\tn = write(s->fd, so.buffer, so.sz);\n\t\t\t} else {\n\t\t\t\tunion sockaddr_all sa;\n\t\t\t\tsocklen_t sasz = udp_socket_address(s, s->p.udp_address, &sa);\n\t\t\t\tif (sasz == 0) {\n\t\t\t\t\tskynet_error(NULL, \"socket-server : set udp (%d) error: address first.\", id);\n\t\t\t\t\tsocket_unlock(&l);\n\t\t\t\t\tso.free_func((void *)buf->buffer);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tn = sendto(s->fd, so.buffer, so.sz, 0, &sa.s, sasz);\n\t\t\t}\n\t\t\tif (n<0) {\n\t\t\t\t// ignore error, let socket thread try again\n\t\t\t\tn = 0;\n\t\t\t}\n\t\t\tstat_write(ss,s,n);\n\t\t\tif (n == so.sz) {\n\t\t\t\t// write done\n\t\t\t\tsocket_unlock(&l);\n\t\t\t\tso.free_func((void *)buf->buffer);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t// write failed, put buffer into s->dw_* , and let socket thread send it. see send_buffer()\n\t\t\ts->dw_buffer = clone_buffer(buf, &s->dw_size);\n\t\t\ts->dw_offset = n;\n\n\t\t\tsocket_unlock(&l);\n\n\t\t\tstruct request_package request;\n\t\t\trequest_init(&request);\n\t\t\trequest.u.send.id = id;\n\t\t\trequest.u.send.sz = 0;\n\t\t\trequest.u.send.buffer = NULL;\n\n\t\t\t// let socket thread enable write event\n\t\t\tsend_request(ss, &request, 'W', sizeof(request.u.send));\n\n\t\t\treturn 0;\n\t\t}\n\t\tsocket_unlock(&l);\n\t}\n\n\tinc_sending_ref(s, id);\n\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.send.id = id;\n\trequest.u.send.buffer = clone_buffer(buf, &request.u.send.sz);\n\n\tsend_request(ss, &request, 'D', sizeof(request.u.send));\n\treturn 0;\n}\n\n// return -1 when error, 0 when success\nint\nsocket_server_send_lowpriority(struct socket_server *ss, struct socket_sendbuffer *buf) {\n\tint id = buf->id;\n\n\tstruct socket * s = &ss->slot[HASH_ID(id)];\n\tif (socket_invalid(s, id)) {\n\t\tfree_buffer(ss, buf);\n\t\treturn -1;\n\t}\n\n\tinc_sending_ref(s, id);\n\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.send.id = id;\n\trequest.u.send.buffer = clone_buffer(buf, &request.u.send.sz);\n\n\tsend_request(ss, &request, 'P', sizeof(request.u.send));\n\treturn 0;\n}\n\nvoid\nsocket_server_exit(struct socket_server *ss) {\n\tstruct request_package request;\n\trequest_init(&request);\n\tsend_request(ss, &request, 'X', 0);\n}\n\nvoid\nsocket_server_close(struct socket_server *ss, uintptr_t opaque, int id) {\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.close.id = id;\n\trequest.u.close.shutdown = 0;\n\trequest.u.close.opaque = opaque;\n\tsend_request(ss, &request, 'K', sizeof(request.u.close));\n}\n\n\nvoid\nsocket_server_shutdown(struct socket_server *ss, uintptr_t opaque, int id) {\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.close.id = id;\n\trequest.u.close.shutdown = 1;\n\trequest.u.close.opaque = opaque;\n\tsend_request(ss, &request, 'K', sizeof(request.u.close));\n}\n\n// return -1 means failed\n// or return AF_INET or AF_INET6\nstatic int\ndo_bind(const char *host, int port, int protocol, int *family) {\n\tint fd;\n\tint status;\n\tint reuse = 1;\n\tstruct addrinfo ai_hints;\n\tstruct addrinfo *ai_list = NULL;\n\tchar portstr[16];\n\tif (host == NULL || host[0] == 0) {\n\t\thost = \"0.0.0.0\";\t// INADDR_ANY\n\t}\n\tsprintf(portstr, \"%d\", port);\n\tmemset( &ai_hints, 0, sizeof( ai_hints ) );\n\tai_hints.ai_family = AF_UNSPEC;\n\tif (protocol == IPPROTO_TCP) {\n\t\tai_hints.ai_socktype = SOCK_STREAM;\n\t} else {\n\t\tassert(protocol == IPPROTO_UDP);\n\t\tai_hints.ai_socktype = SOCK_DGRAM;\n\t}\n\tai_hints.ai_protocol = protocol;\n\n\tstatus = getaddrinfo( host, portstr, &ai_hints, &ai_list );\n\tif ( status != 0 ) {\n\t\treturn -1;\n\t}\n\t*family = ai_list->ai_family;\n\tfd = socket(*family, ai_list->ai_socktype, 0);\n\tif (fd < 0) {\n\t\tgoto _failed_fd;\n\t}\n\tif (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(int))==-1) {\n\t\tgoto _failed;\n\t}\n\tstatus = bind(fd, (struct sockaddr *)ai_list->ai_addr, ai_list->ai_addrlen);\n\tif (status != 0)\n\t\tgoto _failed;\n\n\tfreeaddrinfo( ai_list );\n\treturn fd;\n_failed:\n\tclose(fd);\n_failed_fd:\n\tfreeaddrinfo( ai_list );\n\treturn -1;\n}\n\nstatic int\ndo_listen(const char * host, int port, int backlog) {\n\tint family = 0;\n\tint listen_fd = do_bind(host, port, IPPROTO_TCP, &family);\n\tif (listen_fd < 0) {\n\t\treturn -1;\n\t}\n\tif (listen(listen_fd, backlog) == -1) {\n\t\tclose(listen_fd);\n\t\treturn -1;\n\t}\n\treturn listen_fd;\n}\n\nint\nsocket_server_listen(struct socket_server *ss, uintptr_t opaque, const char * addr, int port, int backlog) {\n\tint fd = do_listen(addr, port, backlog);\n\tif (fd < 0) {\n\t\treturn -1;\n\t}\n\tstruct request_package request;\n\trequest_init(&request);\n\tint id = reserve_id(ss);\n\tif (id < 0) {\n\t\tclose(fd);\n\t\treturn id;\n\t}\n\trequest.u.listen.opaque = opaque;\n\trequest.u.listen.id = id;\n\trequest.u.listen.fd = fd;\n\tsend_request(ss, &request, 'L', sizeof(request.u.listen));\n\treturn id;\n}\n\nint\nsocket_server_bind(struct socket_server *ss, uintptr_t opaque, int fd) {\n\tstruct request_package request;\n\trequest_init(&request);\n\tint id = reserve_id(ss);\n\tif (id < 0)\n\t\treturn -1;\n\trequest.u.bind.opaque = opaque;\n\trequest.u.bind.id = id;\n\trequest.u.bind.fd = fd;\n\tsend_request(ss, &request, 'B', sizeof(request.u.bind));\n\treturn id;\n}\n\nvoid\nsocket_server_start(struct socket_server *ss, uintptr_t opaque, int id) {\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.resumepause.id = id;\n\trequest.u.resumepause.opaque = opaque;\n\tsend_request(ss, &request, 'R', sizeof(request.u.resumepause));\n}\n\nvoid\nsocket_server_pause(struct socket_server *ss, uintptr_t opaque, int id) {\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.resumepause.id = id;\n\trequest.u.resumepause.opaque = opaque;\n\tsend_request(ss, &request, 'S', sizeof(request.u.resumepause));\n}\n\nvoid\nsocket_server_nodelay(struct socket_server *ss, int id) {\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.setopt.id = id;\n\trequest.u.setopt.what = TCP_NODELAY;\n\trequest.u.setopt.value = 1;\n\tsend_request(ss, &request, 'T', sizeof(request.u.setopt));\n}\n\nvoid\nsocket_server_userobject(struct socket_server *ss, struct socket_object_interface *soi) {\n\tss->soi = *soi;\n}\n\n// UDP\n\nint\nsocket_server_udp(struct socket_server *ss, uintptr_t opaque, const char * addr, int port) {\n\tint fd;\n\tint family;\n\tif (port != 0 || addr != NULL) {\n\t\t// bind\n\t\tfd = do_bind(addr, port, IPPROTO_UDP, &family);\n\t\tif (fd < 0) {\n\t\t\treturn -1;\n\t\t}\n\t} else {\n\t\tfamily = AF_INET;\n\t\tfd = socket(family, SOCK_DGRAM, 0);\n\t\tif (fd < 0) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\tsp_nonblocking(fd);\n\n\tint id = reserve_id(ss);\n\tif (id < 0) {\n\t\tclose(fd);\n\t\treturn -1;\n\t}\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.udp.id = id;\n\trequest.u.udp.fd = fd;\n\trequest.u.udp.opaque = opaque;\n\trequest.u.udp.family = family;\n\n\tsend_request(ss, &request, 'U', sizeof(request.u.udp));\n\treturn id;\n}\n\nint\nsocket_server_udp_listen(struct socket_server *ss, uintptr_t opaque, const char* addr, int port){\n\tint fd;\n\tif (port == 0){\n\t\treturn -1;\n\t}\n\n\tint family;\n\t// bind\n\tfd = do_bind(addr, port, IPPROTO_UDP, &family);\n\tif (fd < 0) {\n\t\treturn -1;\n\t}\n\n\tsp_nonblocking(fd);\n\n\tint id = reserve_id(ss);\n\tif (id < 0) {\n\t\tclose(fd);\n\t\treturn -1;\n\t}\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.udp.id = id;\n\trequest.u.udp.fd = fd;\n\trequest.u.udp.opaque = opaque;\n\trequest.u.udp.family = family;\n\n\tsend_request(ss, &request, 'U', sizeof(request.u.udp));\n\treturn id;\n}\n\nint\nsocket_server_udp_dial(struct socket_server *ss, uintptr_t opaque, const char* addr, int port){\n\tint status;\n\tstruct addrinfo ai_hints;\n\tstruct addrinfo *ai_list = NULL;\n\tchar portstr[16];\n\tsprintf(portstr, \"%d\", port);\n\tmemset( &ai_hints, 0, sizeof( ai_hints ) );\n\tai_hints.ai_family = AF_UNSPEC;\n\tai_hints.ai_socktype = SOCK_DGRAM;\n\tai_hints.ai_protocol = IPPROTO_UDP;\n\n\n\tstatus = getaddrinfo(addr, portstr, &ai_hints, &ai_list );\n\tif ( status != 0 ) {\n\t\treturn -1;\n\t}\n\n\tint protocol;\n\n\tif (ai_list->ai_family == AF_INET) {\n\t\tprotocol = PROTOCOL_UDP;\n\t} else if (ai_list->ai_family == AF_INET6) {\n\t\tprotocol = PROTOCOL_UDPv6;\n\t} else {\n\t\tfreeaddrinfo( ai_list );\n\t\treturn -1;\n\t}\n\n\tint fd = socket(ai_list->ai_family, SOCK_DGRAM, 0);\n\tif (fd < 0){\n\t\treturn -1;\n\t}\n\n\tsp_nonblocking(fd);\n\tint id = reserve_id(ss);\n\tif (id < 0){\n\t\tclose(fd);\n\t\treturn -1;\n\t}\n\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.dial_udp.id = id;\n\trequest.u.dial_udp.fd = fd;\n\trequest.u.dial_udp.opaque = opaque;\n\n\n\tint addrsz = gen_udp_address(protocol, (union sockaddr_all *)ai_list->ai_addr, request.u.dial_udp.address);\n\n\tfreeaddrinfo( ai_list );\n\n\tsend_request(ss, &request, 'N', sizeof(request.u.dial_udp) - sizeof(request.u.dial_udp.address) + addrsz);\n\treturn id;\n}\n\nint\nsocket_server_udp_send(struct socket_server *ss, const struct socket_udp_address *addr, struct socket_sendbuffer *buf) {\n\tint id = buf->id;\n\tstruct socket * s = &ss->slot[HASH_ID(id)];\n\tif (socket_invalid(s, id)) {\n\t\tfree_buffer(ss, buf);\n\t\treturn -1;\n\t}\n\n\tconst uint8_t *udp_address = (const uint8_t *)addr;\n\tint addrsz;\n\tswitch (udp_address[0]) {\n\tcase PROTOCOL_UDP:\n\t\taddrsz = 1+2+4;\t\t// 1 type, 2 port, 4 ipv4\n\t\tbreak;\n\tcase PROTOCOL_UDPv6:\n\t\taddrsz = 1+2+16;\t// 1 type, 2 port, 16 ipv6\n\t\tbreak;\n\tdefault:\n\t\tfree_buffer(ss, buf);\n\t\treturn -1;\n\t}\n\n\tstruct socket_lock l;\n\tsocket_lock_init(s, &l);\n\n\tif (can_direct_write(s,id) && socket_trylock(&l)) {\n\t\t// may be we can send directly, double check\n\t\tif (can_direct_write(s,id)) {\n\t\t\t// send directly\n\t\t\tstruct send_object so;\n\t\t\tsend_object_init_from_sendbuffer(ss, &so, buf);\n\t\t\tunion sockaddr_all sa;\n\t\t\tsocklen_t sasz = udp_socket_address(s, udp_address, &sa);\n\t\t\tif (sasz == 0) {\n\t\t\t\tsocket_unlock(&l);\n\t\t\t\tso.free_func((void *)buf->buffer);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tint n = sendto(s->fd, so.buffer, so.sz, 0, &sa.s, sasz);\n\t\t\tif (n >= 0) {\n\t\t\t\t// sendto succ\n\t\t\t\tstat_write(ss,s,n);\n\t\t\t\tsocket_unlock(&l);\n\t\t\t\tso.free_func((void *)buf->buffer);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tsocket_unlock(&l);\n\t\t// let socket thread try again, udp doesn't care the order\n\t}\n\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.send_udp.send.id = id;\n\trequest.u.send_udp.send.buffer = clone_buffer(buf, &request.u.send_udp.send.sz);\n\n\tmemcpy(request.u.send_udp.address, udp_address, addrsz);\n\n\tsend_request(ss, &request, 'A', sizeof(request.u.send_udp.send)+addrsz);\n\treturn 0;\n}\n\nint\nsocket_server_udp_connect(struct socket_server *ss, int id, const char * addr, int port) {\n\tstruct socket * s = &ss->slot[HASH_ID(id)];\n\tif (socket_invalid(s, id)) {\n\t\treturn -1;\n\t}\n\tstruct socket_lock l;\n\tsocket_lock_init(s, &l);\n\tsocket_lock(&l);\n\tif (socket_invalid(s, id)) {\n\t\tsocket_unlock(&l);\n\t\treturn -1;\n\t}\n\tATOM_FINC(&s->udpconnecting);\n\tsocket_unlock(&l);\n\n\tint status;\n\tstruct addrinfo ai_hints;\n\tstruct addrinfo *ai_list = NULL;\n\tchar portstr[16];\n\tsprintf(portstr, \"%d\", port);\n\tmemset( &ai_hints, 0, sizeof( ai_hints ) );\n\tai_hints.ai_family = AF_UNSPEC;\n\tai_hints.ai_socktype = SOCK_DGRAM;\n\tai_hints.ai_protocol = IPPROTO_UDP;\n\n\tstatus = getaddrinfo(addr, portstr, &ai_hints, &ai_list );\n\tif ( status != 0 ) {\n\t\treturn -1;\n\t}\n\tstruct request_package request;\n\trequest_init(&request);\n\trequest.u.set_udp.id = id;\n\tint protocol;\n\n\tif (ai_list->ai_family == AF_INET) {\n\t\tprotocol = PROTOCOL_UDP;\n\t} else if (ai_list->ai_family == AF_INET6) {\n\t\tprotocol = PROTOCOL_UDPv6;\n\t} else {\n\t\tfreeaddrinfo( ai_list );\n\t\treturn -1;\n\t}\n\n\tint addrsz = gen_udp_address(protocol, (union sockaddr_all *)ai_list->ai_addr, request.u.set_udp.address);\n\n\tfreeaddrinfo( ai_list );\n\n\tsend_request(ss, &request, 'C', sizeof(request.u.set_udp) - sizeof(request.u.set_udp.address) +addrsz);\n\n\treturn 0;\n}\n\nconst struct socket_udp_address *\nsocket_server_udp_address(struct socket_server *ss, struct socket_message *msg, int *addrsz) {\n\tuint8_t * address = (uint8_t *)(msg->data + msg->ud);\n\tint type = address[0];\n\tswitch(type) {\n\tcase PROTOCOL_UDP:\n\t\t*addrsz = 1+2+4;\n\t\tbreak;\n\tcase PROTOCOL_UDPv6:\n\t\t*addrsz = 1+2+16;\n\t\tbreak;\n\tdefault:\n\t\treturn NULL;\n\t}\n\treturn (const struct socket_udp_address *)address;\n}\n\n\nstruct socket_info *\nsocket_info_create(struct socket_info *last) {\n\tstruct socket_info *si = skynet_malloc(sizeof(*si));\n\tmemset(si, 0 , sizeof(*si));\n\tsi->next = last;\n\treturn si;\n}\n\nvoid\nsocket_info_release(struct socket_info *si) {\n\twhile (si) {\n\t\tstruct socket_info *temp = si;\n\t\tsi = si->next;\n\t\tskynet_free(temp);\n\t}\n}\n\nstatic int\nquery_info(struct socket *s, struct socket_info *si) {\n\tunion sockaddr_all u;\n\tsocklen_t slen = sizeof(u);\n\tint closing = 0;\n\tswitch (ATOM_LOAD(&s->type)) {\n\tcase SOCKET_TYPE_BIND:\n\t\tsi->type = SOCKET_INFO_BIND;\n\t\tsi->name[0] = '\\0';\n\t\tbreak;\n\tcase SOCKET_TYPE_LISTEN:\n\t\tsi->type = SOCKET_INFO_LISTEN;\n\t\tif (getsockname(s->fd, &u.s, &slen) == 0) {\n\t\t\tgetname(&u, si->name, sizeof(si->name));\n\t\t}\n\t\tbreak;\n\tcase SOCKET_TYPE_HALFCLOSE_READ:\n\tcase SOCKET_TYPE_HALFCLOSE_WRITE:\n\t\tclosing = 1;\n\tcase SOCKET_TYPE_CONNECTED:\n\t\tif (s->protocol == PROTOCOL_TCP) {\n\t\t\tsi->type = closing ? SOCKET_INFO_CLOSING : SOCKET_INFO_TCP;\n\t\t\tif (getpeername(s->fd, &u.s, &slen) == 0) {\n\t\t\t\tgetname(&u, si->name, sizeof(si->name));\n\t\t\t}\n\t\t} else {\n\t\t\tsi->type = SOCKET_INFO_UDP;\n\t\t\tif (udp_socket_address(s, s->p.udp_address, &u)) {\n\t\t\t\tgetname(&u, si->name, sizeof(si->name));\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\treturn 0;\n\t}\n\tsi->id = s->id;\n\tsi->opaque = (uint64_t)s->opaque;\n\tsi->read = s->stat.read;\n\tsi->write = s->stat.write;\n\tsi->rtime = s->stat.rtime;\n\tsi->wtime = s->stat.wtime;\n\tsi->wbuffer = s->wb_size;\n\tsi->reading = s->reading;\n\tsi->writing = s->writing;\n\n\treturn 1;\n}\n\nstruct socket_info *\nsocket_server_info(struct socket_server *ss) {\n\tint i;\n\tstruct socket_info * si = NULL;\n\tfor (i=0;i<MAX_SOCKET;i++) {\n\t\tstruct socket * s = &ss->slot[i];\n\t\tint id = s->id;\n\t\tstruct socket_info temp;\n\t\tif (query_info(s, &temp) && s->id == id) {\n\t\t\t// socket_server_info may call in different thread, so check socket id again\n\t\t\tsi = socket_info_create(si);\n\t\t\ttemp.next = si->next;\n\t\t\t*si = temp;\n\t\t}\n\t}\n\treturn si;\n}\n"
  },
  {
    "path": "skynet-src/socket_server.h",
    "content": "#ifndef skynet_socket_server_h\n#define skynet_socket_server_h\n\n#include <stdint.h>\n#include \"socket_info.h\"\n#include \"socket_buffer.h\"\n\n#define SOCKET_DATA 0\n#define SOCKET_CLOSE 1\n#define SOCKET_OPEN 2\n#define SOCKET_ACCEPT 3\n#define SOCKET_ERR 4\n#define SOCKET_EXIT 5\n#define SOCKET_UDP 6\n#define SOCKET_WARNING 7\n\n// Only for internal use\n#define SOCKET_RST 8\n#define SOCKET_MORE 9\n\nstruct socket_server;\n\nstruct socket_message {\n\tint id;\n\tuintptr_t opaque;\n\tint ud;\t// for accept, ud is new connection id ; for data, ud is size of data \n\tchar * data;\n};\n\nstruct socket_server * socket_server_create(uint64_t time);\nvoid socket_server_release(struct socket_server *);\nvoid socket_server_updatetime(struct socket_server *, uint64_t time);\nint socket_server_poll(struct socket_server *, struct socket_message *result, int *more);\n\nvoid socket_server_exit(struct socket_server *);\nvoid socket_server_close(struct socket_server *, uintptr_t opaque, int id);\nvoid socket_server_shutdown(struct socket_server *, uintptr_t opaque, int id);\nvoid socket_server_start(struct socket_server *, uintptr_t opaque, int id);\nvoid socket_server_pause(struct socket_server *, uintptr_t opaque, int id);\n\n// return -1 when error\nint socket_server_send(struct socket_server *, struct socket_sendbuffer *buffer);\nint socket_server_send_lowpriority(struct socket_server *, struct socket_sendbuffer *buffer);\n\n// ctrl command below returns id\nint socket_server_listen(struct socket_server *, uintptr_t opaque, const char * addr, int port, int backlog);\nint socket_server_connect(struct socket_server *, uintptr_t opaque, const char * addr, int port);\nint socket_server_bind(struct socket_server *, uintptr_t opaque, int fd);\n\n// for tcp\nvoid socket_server_nodelay(struct socket_server *, int id);\n\nstruct socket_udp_address;\n\n// create an udp socket handle, attach opaque with it . udp socket don't need call socket_server_start to recv message\n// if port != 0, bind the socket . if addr == NULL, bind ipv4 0.0.0.0 . If you want to use ipv6, addr can be \"::\" and port 0.\nint socket_server_udp(struct socket_server *, uintptr_t opaque, const char * addr, int port);\n// set default dest address, return 0 when success\nint socket_server_udp_connect(struct socket_server *, int id, const char * addr, int port);\n\n// create an udp client socket handle, and connect to server addr, return id when success\nint socket_server_udp_dial(struct socket_server *ss, uintptr_t opaque, const char* addr, int port);\n// create an udp server socket handle, and bind the host port, return id when success\nint socket_server_udp_listen(struct socket_server *ss, uintptr_t opaque, const char* addr, int port);\n\n// If the socket_udp_address is NULL, use last call socket_server_udp_connect address instead\n// You can also use socket_server_send \nint socket_server_udp_send(struct socket_server *, const struct socket_udp_address *, struct socket_sendbuffer *buffer);\n// extract the address of the message, struct socket_message * should be SOCKET_UDP\nconst struct socket_udp_address * socket_server_udp_address(struct socket_server *, struct socket_message *, int *addrsz);\n\nstruct socket_object_interface {\n\tconst void * (*buffer)(const void *);\n\tsize_t (*size)(const void *);\n\tvoid (*free)(void *);\n};\n\n// if you send package with type SOCKET_BUFFER_OBJECT, use soi.\nvoid socket_server_userobject(struct socket_server *, struct socket_object_interface *soi);\n\nstruct socket_info * socket_server_info(struct socket_server *);\n\n#endif\n"
  },
  {
    "path": "skynet-src/spinlock.h",
    "content": "#ifndef SKYNET_SPINLOCK_H\n#define SKYNET_SPINLOCK_H\n\n#define SPIN_INIT(q) spinlock_init(&(q)->lock);\n#define SPIN_LOCK(q) spinlock_lock(&(q)->lock);\n#define SPIN_UNLOCK(q) spinlock_unlock(&(q)->lock);\n#define SPIN_DESTROY(q) spinlock_destroy(&(q)->lock);\n\n#ifndef USE_PTHREAD_LOCK\n\n#ifdef __STDC_NO_ATOMICS__\n\n#define atomic_flag_ int\n#define ATOMIC_FLAG_INIT_ 0\n#define atomic_flag_test_and_set_(ptr) __sync_lock_test_and_set(ptr, 1)\n#define atomic_flag_clear_(ptr) __sync_lock_release(ptr)\n\nstruct spinlock {\n\tatomic_flag_ lock;\n};\n\nstatic inline void\nspinlock_init(struct spinlock *lock) {\n\tatomic_flag_ v = ATOMIC_FLAG_INIT_;\n\tlock->lock = v;\n}\n\nstatic inline void\nspinlock_lock(struct spinlock *lock) {\n\twhile (atomic_flag_test_and_set_(&lock->lock)) {}\n}\n\nstatic inline int\nspinlock_trylock(struct spinlock *lock) {\n\treturn atomic_flag_test_and_set_(&lock->lock) == 0;\n}\n\nstatic inline void\nspinlock_unlock(struct spinlock *lock) {\n\tatomic_flag_clear_(&lock->lock);\n}\n\nstatic inline void\nspinlock_destroy(struct spinlock *lock) {\n\t(void) lock;\n}\n\n#else  // __STDC_NO_ATOMICS__\n\n#include \"atomic.h\"\n\n#define atomic_test_and_set_(ptr) STD_ atomic_exchange_explicit(ptr, 1, STD_ memory_order_acquire)\n#define atomic_clear_(ptr) STD_ atomic_store_explicit(ptr, 0, STD_ memory_order_release);\n#define atomic_load_relaxed_(ptr) STD_ atomic_load_explicit(ptr, STD_ memory_order_relaxed)\n\n#if defined(__x86_64__)\n#include <immintrin.h> // For _mm_pause\n#define atomic_pause_() _mm_pause()\n#else\n#define atomic_pause_() ((void)0)\n#endif\n\nstruct spinlock {\n\tSTD_ atomic_int lock;\n};\n\nstatic inline void\nspinlock_init(struct spinlock *lock) {\n\tSTD_ atomic_init(&lock->lock, 0);\n}\n\nstatic inline void\nspinlock_lock(struct spinlock *lock) {\n\tfor (;;) {\n\t\tif (!atomic_test_and_set_(&lock->lock))\n\t\t\treturn;\n\t\twhile (atomic_load_relaxed_(&lock->lock))\n\t\t\tatomic_pause_();\n\t}\n}\n\nstatic inline int\nspinlock_trylock(struct spinlock *lock) {\n\treturn !atomic_load_relaxed_(&lock->lock) &&\n\t\t!atomic_test_and_set_(&lock->lock);\n}\n\nstatic inline void\nspinlock_unlock(struct spinlock *lock) {\n\tatomic_clear_(&lock->lock);\n}\n\nstatic inline void\nspinlock_destroy(struct spinlock *lock) {\n\t(void) lock;\n}\n\n#endif  // __STDC_NO_ATOMICS__\n\n#else\n\n#include <pthread.h>\n\n// we use mutex instead of spinlock for some reason\n// you can also replace to pthread_spinlock\n\nstruct spinlock {\n\tpthread_mutex_t lock;\n};\n\nstatic inline void\nspinlock_init(struct spinlock *lock) {\n\tpthread_mutex_init(&lock->lock, NULL);\n}\n\nstatic inline void\nspinlock_lock(struct spinlock *lock) {\n\tpthread_mutex_lock(&lock->lock);\n}\n\nstatic inline int\nspinlock_trylock(struct spinlock *lock) {\n\treturn pthread_mutex_trylock(&lock->lock) == 0;\n}\n\nstatic inline void\nspinlock_unlock(struct spinlock *lock) {\n\tpthread_mutex_unlock(&lock->lock);\n}\n\nstatic inline void\nspinlock_destroy(struct spinlock *lock) {\n\tpthread_mutex_destroy(&lock->lock);\n}\n\n#endif\n\n#endif\n"
  },
  {
    "path": "test/pingserver.lua",
    "content": "local skynet = require \"skynet\"\nlocal queue = require \"skynet.queue\"\nlocal snax = require \"skynet.snax\"\n\nlocal i = 0\nlocal hello = \"hello\"\n\nfunction response.ping(hello)\n\tskynet.sleep(100)\n\treturn hello\nend\n\n-- response.sleep and accept.hello share one lock\nlocal lock\n\nfunction accept.sleep(queue, n)\n\tif queue then\n\t\tlock(\n\t\tfunction()\n\t\t\tprint(\"queue=\",queue, n)\n\t\t\tskynet.sleep(n)\n\t\tend)\n\telse\n\t\tprint(\"queue=\",queue, n)\n\t\tskynet.sleep(n)\n\tend\nend\n\nfunction accept.hello()\n\tlock(function()\n\ti = i + 1\n\tprint (i, hello)\n\tend)\nend\n\nfunction accept.exit(...)\n\tsnax.exit(...)\nend\n\nfunction response.error()\n\terror \"throw an error\"\nend\n\nfunction init( ... )\n\tprint (\"ping server start:\", ...)\n\tsnax.enablecluster()\t-- enable cluster call\n\t-- init queue\n\tlock = queue()\nend\n\nfunction exit(...)\n\tprint (\"ping server exit:\", ...)\nend\n"
  },
  {
    "path": "test/sharemap.sp",
    "content": ".foobar {\n\tx 0 : integer\n\ty 1 : integer\n\ts 2 : string\n}\n"
  },
  {
    "path": "test/testbson.lua",
    "content": "local bson = require \"bson\"\n\nlocal sub = bson.encode_order( \"hello\", 1, \"world\", 2 )\n\ndo\n\t-- check decode encode_order\n\tlocal d = bson.decode(sub)\n\tassert(d.hello == 1 )\n\tassert(d.world == 2 )\nend\n\nlocal function tbl_next(...)\n\tprint(\"--- next.a\", ...)\n\tlocal k, v = next(...)\n\tprint(\"--- next.b\", k, v)\n\treturn k, v\nend\n\nlocal function tbl_pairs(obj)\n\treturn tbl_next, obj.__data, nil\nend\n\nlocal obj_a = {\n\t__data = {\n\t\t[\"1\"] = 2,\n\t\t[\"3\"] = 4,\n\t\t[\"5\"] = 6,\n\t}\n}\n\nsetmetatable(\n\tobj_a,\n\t{\n\t\t__index = obj_a.__data,\n\t\t__pairs = tbl_pairs,\n\t}\n)\n\nlocal obj_b = {\n\t__data = {\n\t\t[\"7\"] = 8,\n\t\t[\"9\"] = 10,\n\t\t[\"11\"] = obj_a,\n\t}\n}\n\nsetmetatable(\n\tobj_b,\n\t{\n\t\t__index = obj_b.__data,\n\t\t__pairs = tbl_pairs,\n\t}\n)\n\nlocal metaarray = setmetatable({ n = 5 }, {\n\t__len = function(self) return self.n end,\n\t__index = function(self, idx) return tostring(idx) end,\n})\n\nb = bson.encode {\n\ta = 1,\n\tb = true,\n\tc = bson.null,\n\td = { 1,2,3,4 },\n\te = bson.binary \"hello\",\n\tf = bson.regex (\"*\",\"i\"),\n\tg = bson.regex \"hello\",\n\th = bson.date (os.time()),\n\ti = bson.timestamp(os.time()),\n\tj = bson.objectid(),\n\tk = { a = false, b = true },\n\tl = {},\n\tm = bson.minkey,\n\tn = bson.maxkey,\n\to = sub,\n\tp = 2^32-1,\n\tq = obj_b,\n\tr = metaarray,\n}\n\nprint \"\\n[before replace]\"\nt = b:decode()\n\nfor k, v in pairs(t) do\n\tprint(k,type(v))\nend\n\nfor k,v in ipairs(t.r) do\n\tprint(k,v)\nend\n\nb:makeindex()\nb.a = 2\nb.b = false\nb.h = bson.date(os.time())\nb.i = bson.timestamp(os.time())\nb.j = bson.objectid()\n\nprint \"\\n[after replace]\"\nt = b:decode()\n\nprint(\"o.hello\", bson.type(t.o.hello))\n"
  },
  {
    "path": "test/testcoroutine.lua",
    "content": "local skynet = require \"skynet\"\n-- You should use skynet.coroutine instead of origin coroutine in skynet\nlocal coroutine = require \"skynet.coroutine\"\nlocal profile = require \"skynet.profile\"\n\nlocal function status(co)\n\trepeat\n\t\tlocal status = coroutine.status(co)\n\t\tprint(\"STATUS\", status)\n\t\tskynet.sleep(100)\n\tuntil status == \"suspended\"\n\n\trepeat\n\t\tlocal ok, n = assert(coroutine.resume(co))\n\t\tprint(\"status thread\", n)\n\tuntil not n\n\tskynet.exit()\nend\n\nlocal function test(n)\n\tlocal co = coroutine.running()\n\tprint (\"begin\", co, coroutine.thread(co))\t-- false\n\tskynet.fork(status, co)\n\tfor i=1,n do\n\t\tskynet.sleep(100)\n\t\tcoroutine.yield(i)\n\tend\n\tprint (\"end\", co)\nend\n\nlocal function main()\n\tlocal f = coroutine.wrap(test)\n\tcoroutine.yield \"begin\"\n\tfor i=1,3 do\n\t\tlocal n = f(5)\n\t\tprint(\"main thread\",n)\n\tend\n\tcoroutine.yield \"end\"\n\tprint(\"main thread time:\", profile.stop(coroutine.thread()))\nend\n\nskynet.start(function()\n\tprint(\"Main thead :\", coroutine.thread())\t-- true\n\tprint(coroutine.resume(coroutine.running()))\t-- always return false\n\n\tprofile.start()\n\n\tlocal f = coroutine.wrap(main)\n\tprint(\"main step\", f())\n\tprint(\"main step\", f())\n\tprint(\"main step\", f())\n--\tprint(\"main thread time:\", profile.stop())\n\tprint(\"close\", coroutine.close(coroutine.create(main)))\nend)\n"
  },
  {
    "path": "test/testcrypt.lua",
    "content": "local skynet = require \"skynet\"\nlocal crypt = require \"skynet.crypt\"\n\nlocal text = \"hello world\"\nlocal key = \"12345678\"\n\nlocal function desencode(key, text, padding)\n\tlocal c = crypt.desencode(key, text, crypt.padding[padding or \"iso7816_4\"])\n\treturn crypt.base64encode(c)\nend\n\nlocal function desdecode(key, text, padding)\n\ttext = crypt.base64decode(text)\n\treturn crypt.desdecode(key, text, crypt.padding[padding or \"iso7816_4\"])\nend\n\nlocal etext = desencode(key, text)\nassert( etext == \"KNugLrX23UcGtcVlk9y+LA==\")\nassert(desdecode(key, etext) == text)\n\nlocal etext = desencode(key, text, \"pkcs7\")\nassert(desdecode(key, etext, \"pkcs7\") == text)\n\nassert(desencode(key, \"\",\"pkcs7\")==\"/rlZt9RkL8s=\")\nassert(desencode(key, \"1\",\"pkcs7\")==\"g6AtgJul6q0=\")\nassert(desencode(key, \"12\",\"pkcs7\")==\"NefFpG+m1O4=\")\nassert(desencode(key, \"123\",\"pkcs7\")==\"LDiFUdf0iew=\")\nassert(desencode(key, \"1234\",\"pkcs7\")==\"T9u7dzBdi+w=\")\nassert(desencode(key, \"12345\",\"pkcs7\")==\"AGgKdx/Qic8=\")\nassert(desencode(key, \"123456\",\"pkcs7\")==\"ED5wLgc3Mnw=\")\nassert(desencode(key, \"1234567\",\"pkcs7\")==\"mYo+BYIT41M=\")\nassert(desencode(key, \"12345678\",\"pkcs7\")==\"ltACiHjVjIn+uVm31GQvyw==\")\n\nskynet.start(skynet.exit)"
  },
  {
    "path": "test/testdatacenter.lua",
    "content": "local skynet = require \"skynet\"\nlocal datacenter = require \"skynet.datacenter\"\n\nlocal function f1()\n\tprint(\"====1==== wait hello\")\n\tprint(\"\\t1>\",datacenter.wait (\"hello\"))\n\tprint(\"====1==== wait key.foobar\")\n\tprint(\"\\t1>\", pcall(datacenter.wait,\"key\"))\t-- will failed, because \"key\" is a branch\n\tprint(\"\\t1>\",datacenter.wait (\"key\", \"foobar\"))\nend\n\nlocal function f2()\n\tskynet.sleep(10)\n\tprint(\"====2==== set key.foobar\")\n\tdatacenter.set(\"key\", \"foobar\", \"bingo\")\nend\n\nskynet.start(function()\n\tdatacenter.set(\"hello\", \"world\")\n\tprint(datacenter.get \"hello\")\n\tskynet.fork(f1)\n\tskynet.fork(f2)\nend)\n"
  },
  {
    "path": "test/testdatasheet.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal mode = ...\n\nlocal function dump(t, prefix)\n\tfor k,v in pairs(t) do\n\t\tprint(prefix, k, v)\n\t\tif type(v) == \"table\" then\n\t\t\tdump(v, prefix .. \".\" .. k)\n\t\tend\n\tend\nend\n\nif mode == \"child\" then\n\n\tlocal datasheet = require \"skynet.datasheet\"\n\n\tskynet.start(function()\n\t\tlocal t = datasheet.query(\"foobar\")\n\t\tdump(t, \"[CHILD]\")\n\n\t\tskynet.sleep(100)\n\t\tskynet.exit()\n\tend)\n\nelse\n\nlocal builder = require \"skynet.datasheet.builder\"\nlocal datasheet = require \"skynet.datasheet\"\n\nskynet.start(function()\n\tbuilder.new(\"foobar\", {a = 1, b = 2 , c = {3} })\n\tskynet.newservice(SERVICE_NAME, \"child\")\n\tlocal t = datasheet.query \"foobar\"\n\tlocal c = t.c\n\tdump(t, \"[1]\")\n\tbuilder.update(\"foobar\", { b = 4, c = { 5 } })\n\tprint(\"sleep\")\n\tskynet.sleep(100)\n\tdump(t, \"[2]\")\n\tdump(c, \"[2.c]\")\n\tbuilder.update(\"foobar\", { a = 6, c = 7, d = 8 })\n\tprint(\"sleep\")\n\tskynet.sleep(100)\n\tdump(t, \"[3]\")\nend)\n\nend"
  },
  {
    "path": "test/testdeadcall.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal mode = ...\n\nif mode == \"test\" then\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function (...)\n\t\tprint(\"====>\", ...)\n\t\tskynet.exit()\n\tend)\nend)\n\nelseif mode == \"dead\" then\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function (...)\n\t\tskynet.sleep(100)\n\t\tprint(\"return\", skynet.ret \"\")\n\tend)\nend)\n\nelse\n\n\tskynet.start(function()\n\t\tlocal test = skynet.newservice(SERVICE_NAME, \"test\")\t-- launch self in test mode\n\n\t\tprint(pcall(function()\n\t\t\tskynet.call(test,\"lua\", \"dead call\")\n\t\tend))\n\n\t\tlocal dead = skynet.newservice(SERVICE_NAME, \"dead\")\t-- launch self in dead mode\n\n\t\tskynet.timeout(0, skynet.exit)\t-- exit after a while, so the call never return\n\t\tskynet.call(dead, \"lua\", \"would not return\")\n\tend)\nend\n"
  },
  {
    "path": "test/testdeadloop.lua",
    "content": "local skynet = require \"skynet\"\nlocal function dead_loop()\n    while true do\n        skynet.sleep(0)\n    end\nend\n\nskynet.start(function()\n    skynet.fork(dead_loop)\nend)\n"
  },
  {
    "path": "test/testdns.lua",
    "content": "local skynet = require \"skynet\"\nlocal dns = require \"skynet.dns\"\n\nlocal resolve_list = {\n\t\"github.com\",\n\t\"stackoverflow.com\",\n\t\"lua.com\",\n}\n\nskynet.start(function()\n\t-- you can specify the server like dns.server(\"8.8.4.4\", 53)\n\tfor _ , name in ipairs(resolve_list) do\n\t\tlocal ip, ips = dns.resolve(name)\n\t\tfor k,v in ipairs(ips) do\n\t\t\tprint(name,v)\n\t\tend\n\t\tskynet.sleep(500)\t-- sleep 5 sec\n\tend\nend)\n"
  },
  {
    "path": "test/testecho.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal mode = ...\n\nif mode == \"slave\" then\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(_,_, ...)\n\t\tskynet.ret(skynet.pack(...))\n\tend)\nend)\n\nelse\n\nskynet.start(function()\n\tlocal slave = skynet.newservice(SERVICE_NAME, \"slave\")\n\tlocal n = 100000\n\tlocal start = skynet.now()\n\tprint(\"call salve\", n, \"times in queue\")\n\tfor i=1,n do\n\t\tskynet.call(slave, \"lua\")\n\tend\n\tprint(\"qps = \", n/ (skynet.now() - start) * 100)\n\n\tstart = skynet.now()\n\n\tlocal worker = 10\n\tlocal task = n/worker\n\tprint(\"call salve\", n, \"times in parallel, worker = \", worker)\n\n\tfor i=1,worker do\n\t\tskynet.fork(function()\n\t\t\tfor i=1,task do\n\t\t\t\tskynet.call(slave, \"lua\")\n\t\t\tend\n\t\t\tworker = worker -1\n\t\t\tif worker == 0 then\n\t\t\t\tprint(\"qps = \", n/ (skynet.now() - start) * 100)\n\t\t\tend\n\t\tend)\n\tend\nend)\n\nend\n"
  },
  {
    "path": "test/testendless.lua",
    "content": "local skynet = require \"skynet\"\n\nskynet.start(function()\n\tfor i = 1, 1000000000 do\t-- very long loop\n\t\tif i%100000000 == 0 then\n\t\t\tprint(\"Endless = \", skynet.stat \"endless\")\n\t\t\tprint(\"Cost time = \", skynet.stat \"time\")\n\t\tend\n\tend\n\tskynet.exit()\nend)\n"
  },
  {
    "path": "test/testhandle.lua",
    "content": "local skynet = require \"skynet\"\nrequire \"skynet.manager\"\n\nlocal mod = ...\nif mod == \"slave\" then\n\nskynet.start(function()\n    skynet.error(\"addr:\", skynet.self())\nend)\n\nelse\n\nskynet.start(function()\n\tskynet.newservice(\"debug_console\",8000)\n\tskynet.error(\"master addr:\", skynet.self())\n\n    skynet.newservice(\"testhandle\", \"slave\")\n    skynet.newservice(\"testhandle\", \"slave\")\n    skynet.newservice(\"testhandle\", \"slave\")\n    skynet.newservice(\"testhandle\", \"slave\")\n    skynet.newservice(\"testhandle\", \"slave\")\n    skynet.newservice(\"testhandle\", \"slave\")\n\n    while true do\n        local addr = skynet.newservice(\"testhandle\", \"slave\")\n        skynet.kill(addr)\n        if addr > 0xfffff0 then\n            break\n        end\n    end\nend)\n\nend\n"
  },
  {
    "path": "test/testharborlink.lua",
    "content": "local skynet = require \"skynet\"\nlocal harbor = require \"skynet.harbor\"\n\nskynet.start(function()\n\tprint(\"wait for harbor 2\")\n\tprint(\"run skynet examples/config_log please\")\n\tharbor.connect(2)\n\tprint(\"harbor 2 connected\")\n\tprint(\"LOG =\", skynet.address(harbor.queryname \"LOG\"))\n\tharbor.link(2)\n\tprint(\"disconnected\")\nend)\n"
  },
  {
    "path": "test/testhttp.lua",
    "content": "local skynet = require \"skynet\"\nlocal httpc = require \"http.httpc\"\nlocal httpurl = require \"http.url\"\nlocal dns = require \"skynet.dns\"\n\nlocal function http_test(protocol)\n\t--httpc.dns()\t-- set dns server\n\thttpc.timeout = 100\t-- set timeout 1 second\n\tprint(\"GET baidu.com\")\n\tprotocol = protocol or \"http\"\n\tlocal respheader = {}\n\tlocal host = string.format(\"%s://baidu.com\", protocol)\n\tprint(\"geting... \".. host)\n\tlocal status, body = httpc.get(host, \"/\", respheader)\n\tprint(\"[header] =====>\")\n\tfor k,v in pairs(respheader) do\n\t\tprint(k,v)\n\tend\n\tprint(\"[body] =====>\", status)\n\tprint(body)\n\n\tlocal respheader = {}\n\tlocal ip = dns.resolve \"baidu.com\"\n\tprint(string.format(\"GET %s (baidu.com)\", ip))\n\tlocal status, body = httpc.get(host, \"/\", respheader, { host = \"baidu.com\" })\n\tprint(status)\nend\n\nlocal function http_stream_test()\n\tfor resp, stream in httpc.request_stream(\"GET\", \"http://baidu.com\", \"/\") do\n\t\tprint(\"STATUS\", stream.status)\n\t\tfor k,v in pairs(stream.header) do\n\t\t\tprint(\"HEADER\",k,v)\n\t\tend\n\t\tprint(\"BODY\", resp)\n\tend\nend\n\nlocal function http_head_test()\n\thttpc.timeout = 100\n\tlocal respheader = {}\n\tlocal status = httpc.head(\"http://baidu.com\", \"/\", respheader)\n\tfor k,v in pairs(respheader) do\n\t\tprint(\"HEAD\", k, v)\n\tend\nend\n\nlocal function http_url_test()\n\tlocal url = \"http://baidu.com/get?k1=1&k2=2&k4=a%20space&k5=b%20space&k5=b%20space&k5=b%20space\"\n\tlocal path, query = httpurl.parse(url)\n\tprint(\"url\", path, query)\n\tlocal qret = httpurl.parse_query(query)\n\tfor k, v in pairs(qret) do\n\t\tprint(k, v)\n\tend\n\tassert(#qret[\"k5\"] == 3)\n\tassert(qret[1] == qret[2])\n\tassert(qret[1] == qret[3])\nend\n\nlocal function main()\n\tdns.server()\n\n\thttp_stream_test()\n\thttp_head_test()\n\thttp_url_test()\n\n\thttp_test(\"http\")\n\tif not pcall(require,\"ltls.c\") then\n\t\tprint \"No ltls module, https is not supported\"\n\telse\n\t\thttp_test(\"https\")\n\tend\nend\n\nskynet.start(function()\n\tprint(pcall(main))\n\tskynet.exit()\nend)\n "
  },
  {
    "path": "test/testmemlimit.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal names = {\n\t\"cluster\",\n\t\"skynet.db.dns\",\n\t\"skynet.db.mongo\",\n\t\"skynet.db.mysql\",\n\t\"skynet.db.redis\",\n\t\"sharedata\",\n\t\"skynet.socket\",\n\t\"sproto\"\n}\n\n-- set sandbox memory limit to 1M, must set here (at start, out of skynet.start)\nskynet.memlimit(1 * 1024 * 1024)\n\nskynet.start(function()\n    local a = {}\n    local limit\n    local ok, err = pcall(function()\n        for i=1, 12355 do\n            limit = i\n            table.insert(a, {})\n        end\n    end)\n    local libs = {}\n    for k,v in ipairs(names) do\n        local ok, m = pcall(require, v)\n        if ok then\n            libs[v] = m\n        end\n    end\n    skynet.error(limit, err)\n    skynet.exit()\nend)\n"
  },
  {
    "path": "test/testmongodb.lua",
    "content": "local skynet = require \"skynet\"\nlocal mongo = require \"skynet.db.mongo\"\nlocal bson = require \"bson\"\n\nlocal host, port, db_name, username, password = ...\nif port then\n\tport = math.tointeger(port)\nend\n\nhost = '127.0.0.1'\nport = 27017\nusername = \"admin\"\npassword = 123456\ndb_name = \"admin\"\n-- print(host, port, db_name, username, password)\n\nlocal function _create_client()\n\treturn mongo.client(\n\t\t{\n\t\t\thost = host, port = port,\n\t\t\tusername = username, password = password,\n\t\t\tauthdb = \"admin\",\n\t\t}\n\t)\nend\n\nlocal function test_auth()\n\tlocal ok, err, ret\n\tlocal c = mongo.client(\n\t\t{\n\t\t\thost = host, port = port,\n\t\t}\n\t)\n\tlocal db = c[db_name]\n\tdb:auth(username, password)\n\n\tdb.testcoll:dropIndex(\"*\")\n\tdb.testcoll:drop()\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1});\n\tassert(ok and ret and ret.n == 1, err)\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1});\n\tassert(ok and ret and ret.n == 1, err)\nend\n\nlocal function test_insert_without_index()\n\tlocal ok, err, ret\n\tlocal c = _create_client()\n\tlocal db = c[db_name]\n\n\tdb.testcoll:dropIndex(\"*\")\n\tdb.testcoll:drop()\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1});\n\tassert(ok and ret and ret.n == 1, err)\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1});\n\tassert(ok and ret and ret.n == 1, err)\nend\n\nlocal function test_insert_with_index()\n\tlocal ok, err, ret\n\tlocal c = _create_client()\n\tlocal db = c[db_name]\n\n\tdb.testcoll:dropIndex(\"*\")\n\tdb.testcoll:drop()\n\n\tdb.testcoll:ensureIndex({test_key = 1}, {unique = true, name = \"test_key_index\"})\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1})\n\tassert(ok and ret and ret.n == 1, err)\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1})\n\tassert(ok == false and string.find(err, \"duplicate key error\"))\nend\n\nlocal function test_find_and_remove()\n\tlocal ok, err, ret\n\tlocal c = _create_client()\n\tlocal db = c[db_name]\n\n\tdb.testcoll:dropIndex(\"*\")\n\tdb.testcoll:drop()\n\n\tlocal cursor = db.testcoll:find()\n\tassert(cursor:hasNext() == false)\n\n\tdb.testcoll:ensureIndex({test_key = 1}, {test_key2 = -1}, {unique = true, name = \"test_index\"})\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1, test_key2 = 1})\n\tassert(ok and ret and ret.n == 1, err)\n\n\tcursor = db.testcoll:find()\n\tassert(cursor:hasNext() == true)\n\tlocal v = cursor:next()\n\tassert(v)\n\tassert(v.test_key == 1)\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1, test_key2 = 2})\n\tassert(ok and ret and ret.n == 1, err)\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 2, test_key2 = 3})\n\tassert(ok and ret and ret.n == 1, err)\n\n\tret = db.testcoll:findOne({test_key2 = 1})\n\tassert(ret and ret.test_key2 == 1, err)\n\n\tret = db.testcoll:find({test_key2 = {['$gt'] = 0}}):sort({test_key = 1}, {test_key2 = -1}):skip(1):limit(1)\n\tassert(ret:count() == 3)\n\tassert(ret:count(true) == 1)\n\tif ret:hasNext() then\n\t\tret = ret:next()\n\tend\n\tassert(ret and ret.test_key2 == 1)\n\n\tdb.testcoll:delete({test_key = 1})\n\tdb.testcoll:delete({test_key = 2})\n\n\tret = db.testcoll:findOne({test_key = 1})\n\tassert(ret == nil)\nend\n\nlocal function test_runcommand()\n\tlocal ok, err, ret\n\tlocal c = _create_client()\n\tlocal db = c[db_name]\n\n\tdb.testcoll:dropIndex(\"*\")\n\tdb.testcoll:drop()\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1, test_key2 = 1})\n\tassert(ok and ret and ret.n == 1, err)\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1, test_key2 = 2})\n\tassert(ok and ret and ret.n == 1, err)\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 2, test_key2 = 3})\n\tassert(ok and ret and ret.n == 1, err)\n\n\tlocal pipeline = {\n\t\t{\n\t\t\t[\"$group\"] = {\n\t\t\t\t_id = mongo.null,\n\t\t\t\ttest_key_total = { [\"$sum\"] = \"$test_key\"},\n\t\t\t\ttest_key2_total = { [\"$sum\"] = \"$test_key2\" },\n\t\t\t}\n\t\t}\n\t}\n\tret = db:runCommand(\"aggregate\", \"testcoll\", \"pipeline\", pipeline, \"cursor\", {})\n\tassert(ret and ret.cursor.firstBatch[1].test_key_total == 4)\n\tassert(ret and ret.cursor.firstBatch[1].test_key2_total == 6)\nend\n\nlocal function test_expire_index()\n\tlocal ok, err, ret\n\tlocal c = _create_client()\n\tlocal db = c[db_name]\n\n\tdb.testcoll:dropIndex(\"*\")\n\tdb.testcoll:drop()\n\n\tdb.testcoll:ensureIndex({test_key = 1}, {unique = true, name = \"test_key_index\", expireAfterSeconds = 1, })\n\tdb.testcoll:ensureIndex({test_date = 1}, {expireAfterSeconds = 1, })\n\n\tok, err, ret = db.testcoll:safe_insert({test_key = 1, test_date = bson.date(os.time())})\n\tassert(ok and ret and ret.n == 1, err)\n\n\tret = db.testcoll:findOne({test_key = 1})\n\tassert(ret and ret.test_key == 1)\n\n\tfor i = 1, 60 do\n\t\tskynet.sleep(100);\n\t\tprint(\"check expire\", i)\n\t\tret = db.testcoll:findOne({test_key = 1})\n\t\tif ret == nil then\n\t\t\treturn\n\t\tend\n\tend\n\tprint(\"test expire index failed\")\n\tassert(false, \"test expire index failed\");\nend\n\nlocal function test_safe_batch_insert()\n\tlocal ok, err, ret\n\tlocal c = _create_client()\n\tlocal db = c[db_name]\n\n\tdb.testcoll:drop()\n\t\n\tlocal docs, length = {}, 10\n\tfor i = 1, length do\n\t\ttable.insert(docs, {test_key = i})\n\tend\n\t\n\tdb.testcoll:safe_batch_insert(docs)\n\n\tlocal ret = db.testcoll:find()\n\tassert(length == ret:count(), \"test safe batch insert failed\")\nend\n\nlocal function test_safe_batch_delete()\n\tlocal ok, err, ret\n\tlocal c = _create_client()\n\tlocal db = c[db_name]\n\n\tdb.testcoll:drop()\n\n\tlocal docs, length = {}, 10\n\tfor i = 1, length do\n\t\ttable.insert(docs, {test_key = i})\n\tend\n\n\tdb.testcoll:safe_batch_insert(docs)\n\n\tdocs = {}\n\tlocal del_num = 5\n\tfor i = 1, del_num do\n\t\ttable.insert(docs, {test_key = i})\n\tend\n\n\tdb.testcoll:safe_batch_delete(docs)\n\n\tlocal ret = db.testcoll:find()\n\tassert((length - del_num) == ret:count(), \"test safe batch delete failed\")\nend\n\nlocal function test_safe_update()\n\tlocal ok, err, ret\n\tlocal c = _create_client()\n\tlocal db = c[db_name]\n\n\tdb.testcoll:drop()\n\n\tdb.testcoll:safe_insert({test_key = 100, test_value = \"hello mongo\"})\n\t\n\tdb.testcoll:ensureIndex({test_key = 1}, {unique = true, name = \"test_key_index\"})\n\n\tlocal query = {test_key = 100}\n\tlocal update = {test_value = \"hi mongo\"}\n\tok, err = db.testcoll:safe_update(query, {['$set'] = update})\n\tassert(ok, err)\n\n\tret = db.testcoll:findOne(query)\n\tassert(ret.test_value == \"hi mongo\")\nend\n\nskynet.start(function()\n\tif username then\n\t\tprint(\"Test auth\")\n\t\ttest_auth()\n\tend\n\tprint(\"Test insert without index\")\n\ttest_insert_without_index()\n\tprint(\"Test insert index\")\n\ttest_insert_with_index()\n\tprint(\"Test find and remove\")\n\ttest_find_and_remove()\n\tprint(\"Test runCommand\")\n\ttest_runcommand()\n\tprint(\"Test expire index\")\n\ttest_expire_index()\n\tprint(\"test safe batch insert\")\n\ttest_safe_batch_insert()\n\tprint(\"test safe batch delete\")\n\ttest_safe_batch_delete()\n\tprint(\"test_safe_update\")\n\ttest_safe_update()\n\tprint(\"mongodb test finish.\");\nend)\n"
  },
  {
    "path": "test/testmulticast.lua",
    "content": "local skynet = require \"skynet\"\nlocal mc = require \"skynet.multicast\"\nlocal dc = require \"skynet.datacenter\"\n\nlocal mode = ...\n\nif mode == \"sub\" then\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function (_,_, cmd, channel)\n\t\tassert(cmd == \"init\")\n\t\tlocal c = mc.new {\n\t\t\tchannel = channel ,\n\t\t\tdispatch = function (channel, source, ...)\n\t\t\t\tprint(string.format(\"%s <=== %s %s\",skynet.address(skynet.self()),skynet.address(source), channel), ...)\n\t\t\tend\n\t\t}\n\t\tprint(skynet.address(skynet.self()), \"sub\", c)\n\t\tc:subscribe()\n\t\tskynet.ret(skynet.pack())\n\tend)\nend)\n\nelse\n\nskynet.start(function()\n\tlocal channel = mc.new()\n\tprint(\"New channel\", channel)\n\tfor i=1,10 do\n\t\tlocal sub = skynet.newservice(SERVICE_NAME, \"sub\")\n\t\tskynet.call(sub, \"lua\", \"init\", channel.channel)\n\tend\n\n\tdc.set(\"MCCHANNEL\", channel.channel)\t-- for multi node test\n\n\tprint(skynet.address(skynet.self()), \"===>\", channel)\n\tchannel:publish(\"Hello World\")\nend)\n\nend"
  },
  {
    "path": "test/testmulticast2.lua",
    "content": "local skynet = require \"skynet\"\nlocal dc = require \"skynet.datacenter\"\nlocal mc = require \"skynet.multicast\"\n\nskynet.start(function()\n\tprint(\"remote start\")\n\tlocal console = skynet.newservice(\"console\")\n\tlocal channel = dc.get \"MCCHANNEL\"\n\tif channel then\n\t\tprint(\"remote channel\", channel)\n\telse\n\t\tprint(\"create local channel\")\n\tend\n\tfor i=1,10 do\n\t\tlocal sub = skynet.newservice(\"testmulticast\", \"sub\")\n\t\tskynet.call(sub, \"lua\", \"init\", channel)\n\tend\n\tlocal c = mc.new {\n\t\tchannel = channel ,\n\t\tdispatch = function(...) print(\"======>\", ...) end,\n\t}\n\tc:subscribe()\n\tc:publish(\"Remote message\")\n\tc:unsubscribe()\n\tc:publish(\"Remote message2\")\n\tc:delete()\n\tskynet.exit()\nend)\n"
  },
  {
    "path": "test/testmysql.lua",
    "content": "local skynet = require \"skynet\"\nlocal mysql = require \"skynet.db.mysql\"\n\nlocal function dump(obj)\n    local getIndent, quoteStr, wrapKey, wrapVal, dumpObj\n    getIndent = function(level)\n        return string.rep(\"\\t\", level)\n    end\n    quoteStr = function(str)\n        return '\"' .. string.gsub(str, '\"', '\\\\\"') .. '\"'\n    end\n    wrapKey = function(val)\n        if type(val) == \"number\" then\n            return \"[\" .. val .. \"]\"\n        elseif type(val) == \"string\" then\n            return \"[\" .. quoteStr(val) .. \"]\"\n        else\n            return \"[\" .. tostring(val) .. \"]\"\n        end\n    end\n    wrapVal = function(val, level)\n        if type(val) == \"table\" then\n            return dumpObj(val, level)\n        elseif type(val) == \"number\" then\n            return val\n        elseif type(val) == \"string\" then\n            return quoteStr(val)\n        else\n            return tostring(val)\n        end\n    end\n    dumpObj = function(obj, level)\n        if type(obj) ~= \"table\" then\n            return wrapVal(obj)\n        end\n        level = level + 1\n        local tokens = {}\n        tokens[#tokens + 1] = \"{\"\n        for k, v in pairs(obj) do\n            tokens[#tokens + 1] = getIndent(level) .. wrapKey(k) .. \" = \" .. wrapVal(v, level) .. \",\"\n        end\n        tokens[#tokens + 1] = getIndent(level - 1) .. \"}\"\n        return table.concat(tokens, \"\\n\")\n    end\n    return dumpObj(obj, 0)\nend\n\nlocal function test2( db)\n    local i=1\n    while true do\n        local    res = db:query(\"select * from cats order by id asc\")\n        print ( \"test2 loop times=\" ,i,\"\\n\",\"query result=\",dump( res ) )\n        res = db:query(\"select * from cats order by id asc\")\n        print ( \"test2 loop times=\" ,i,\"\\n\",\"query result=\",dump( res ) )\n\n        skynet.sleep(1000)\n        i=i+1\n    end\nend\nlocal function test3( db)\n    local i=1\n    while true do\n        local    res = db:query(\"select * from cats order by id asc\")\n        print ( \"test3 loop times=\" ,i,\"\\n\",\"query result=\",dump( res ) )\n        res = db:query(\"select * from cats order by id asc\")\n        print ( \"test3 loop times=\" ,i,\"\\n\",\"query result=\",dump( res ) )\n        skynet.sleep(1000)\n        i=i+1\n    end\nend\nlocal function test4( db)\n\tlocal stmt = db:prepare(\"SELECT * FROM cats WHERE name=?\")\n    print ( \"test4 prepare result=\",dump( stmt ) )\n\tlocal res = db:execute(stmt,'Bob')\n    print ( \"test4 query result=\",dump( res ) )\n    db:stmt_close(stmt)\nend\n\n-- 测试存储过程和blob读写\nlocal function test_sp_blob(db)\n\tprint(\"test stored procedure\")\n\t-- 创建测试表\n\tdb:query \"DROP TABLE IF EXISTS `test`\"\n\tdb:query [[\n\t\tCREATE TABLE `test` (\n\t\t\t`id` int(11) NOT NULL AUTO_INCREMENT,\n\t\t\t`str` varchar(45) COLLATE utf8mb4_bin DEFAULT NULL,\n\t\t\t`dt` timestamp NULL DEFAULT NULL,\n\t\t\t`flt` double DEFAULT NULL,\n\t\t\t`blb` mediumblob,\n\t\t\t`num` int(11) DEFAULT NULL,\n\t\t\tPRIMARY KEY (`id`),\n\t\t\tUNIQUE KEY `id_UNIQUE` (`id`)\n\t\t\t) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;\n\t]]\n\t-- 创建测试存储过程\n\tdb:query \"DROP PROCEDURE IF EXISTS `get_test`\"\n\tdb:query [[\n\t\tCREATE PROCEDURE `get_test`(IN p_id int)\n\t\tBEGIN\n\t\t\tselect * from test where id=p_id;\n\t\tEND\n\t]]\n\tlocal stmt_insert = db:prepare(\"INSERT test (str,dt,flt,num,blb) VALUES (?,?,?,?,?)\")\n\tlocal stmt_csp = db:prepare(\"call get_test(?)\")\n\tlocal test_blob = string.char(0xFF,0x8F,0x03,0x04,0x0a,0x0b,0x0d,0x0e,0x10,0x20,0x30,0x40)\n\n\tlocal r = db:execute(stmt_insert,'test_str','2020-3-20 15:30:40',3.1415,89,test_blob)\n\tprint(\"insert result : insert_id\",r.insert_id,\"affected_rows\",r.affected_rows\n\t\t,\"server_status\",r.server_status,\"warning_count\",r.warning_count)\n\n\tr = db:execute(stmt_csp,1)\n\tlocal rs = r[1][1]\n\tprint(\"call get_test() result : str\",rs.str,\"dt\",rs.dt,\"flt\",rs.flt,\"num\",rs.num\n\t\t,\"blb len\",#rs.blb,\"equal\",test_blob==rs.blb)\n\n\tprint(\"test stored procedure ok\")\nend\n\nlocal function test_signed(db)\n    local res = db:query(\"drop table if exists test_i_u\")\n    res = db:query(\"create table test_i_u (i tinyint primary key, u tinyint unsigned)\")\n    print(dump(res))\n\n    res = db:query(\"insert into test_i_u (i,u) values (-1,1),(127,128),(-127,255)\")\n    print(dump(res))\n\n    local prep = \"SELECT * FROM test_i_u\"\n    local stmt = db:prepare(prep)\n    local res = db:execute(stmt)\n    print(\"test_i_u: \", dump(res))\n    db:stmt_close(stmt)\nend\n\nskynet.start(function()\n\n\tlocal function on_connect(db)\n\t\tdb:query(\"set charset utf8mb4\");\n\tend\n\tlocal db=mysql.connect({\n\t\thost=\"127.0.0.1\",\n\t\tport=3306,\n\t\tdatabase=\"skynet\",\n\t\tuser=\"root\",\n\t\tpassword=\"123456\",\n                charset=\"utf8mb4\",\n\t\tmax_packet_size = 1024 * 1024,\n\t\ton_connect = on_connect\n\t})\n\tif not db then\n\t\tprint(\"failed to connect\")\n\tend\n\tprint(\"testmysql success to connect to mysql server\")\n\n\tlocal res = db:query(\"drop table if exists cats\")\n\tres = db:query(\"create table cats \"\n\t\t               ..\"(id serial primary key, \".. \"name varchar(5))\")\n\tprint( dump( res ) )\n\n\tres = db:query(\"insert into cats (name) \"\n                             .. \"values (\\'Bob\\'),(\\'\\'),(null)\")\n\tprint ( dump( res ) )\n\n\tres = db:query(\"select * from cats order by id asc\")\n\tprint ( dump( res ) )\n\n\t-- 测试存储过程和二进制blob\n\ttest_sp_blob(db)\n\t\n\ttest_signed(db)\n\n    -- test in another coroutine\n\tskynet.fork( test2, db)\n    skynet.fork( test3, db)\n\tskynet.fork( test4, db)\n\t-- multiresultset test\n\tres = db:query(\"select * from cats order by id asc ; select * from cats\")\n\tprint (\"multiresultset test result=\", dump( res ) )\n\n\tprint (\"escape string test result=\", mysql.quote_sql_str([[\\mysql escape %string test'test\"]]) )\n\n\t-- bad sql statement\n\tlocal res =  db:query(\"select * from notexisttable\" )\n\tprint( \"bad query test result=\" ,dump(res) )\n\n    local i=1\n    while true do\n        local    res = db:query(\"select * from cats order by id asc\")\n        print ( \"test1 loop times=\" ,i,\"\\n\",\"query result=\",dump( res ) )\n\n        res = db:query(\"select * from cats order by id asc\")\n        print ( \"test1 loop times=\" ,i,\"\\n\",\"query result=\",dump( res ) )\n\n\n        skynet.sleep(1000)\n        i=i+1\n    end\n\n\t--db:disconnect()\n\t--skynet.exit()\nend)\n\n"
  },
  {
    "path": "test/testoverload.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal mode = ...\n\nif mode == \"slave\" then\n\nlocal CMD = {}\n\nfunction CMD.sum(n)\n\tskynet.error(\"for loop begin\")\n\tlocal s = 0\n\tfor i = 1, n do\n\t\ts = s + i\n\tend\n\tskynet.error(\"for loop end\")\nend\n\nfunction CMD.blackhole()\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(_,_, cmd, ...)\n\t\tlocal f = CMD[cmd]\n\t\tf(...)\n\tend)\nend)\n\nelse\n\nskynet.start(function()\n\tlocal slave = skynet.newservice(SERVICE_NAME, \"slave\")\n\tfor step = 1, 20 do\n\t\tskynet.error(\"overload test \".. step)\n\t\tfor i = 1, 512 * step do\n\t\t\tskynet.send(slave, \"lua\", \"blackhole\")\n\t\tend\n\t\tskynet.sleep(step)\n\tend\n\tlocal n = 1000000000\n\tskynet.error(string.format(\"endless test n=%d\", n))\n\tskynet.send(slave, \"lua\", \"sum\", n)\nend)\n\nend\n"
  },
  {
    "path": "test/testping.lua",
    "content": "local skynet = require \"skynet\"\nlocal snax = require \"skynet.snax\"\n\nskynet.start(function()\n\tskynet.trace()\n\tlocal ps = snax.newservice (\"pingserver\", \"hello world\")\n\tprint(ps.req.ping(\"foobar\"))\n\tprint(ps.post.hello())\n\tprint(pcall(ps.req.error))\n\tprint(\"Hotfix (i) :\", snax.hotfix(ps, [[\n\nlocal i\nlocal hello\n\nfunction accept.hello()\n\ti = i + 1\n\tprint (\"fix\", i, hello)\nend\n\nfunction hotfix(...)\n\tlocal temp = i\n\ti = 100\n\treturn temp\nend\n\n\t]]))\n\tprint(ps.post.hello())\n\n\tlocal info = skynet.call(ps.handle, \"debug\", \"INFO\")\n\n\tfor name,v in pairs(info) do\n\t\tprint(string.format(\"%s\\tcount:%d time:%f\", name, v.count, v.time))\n\tend\n\n\tprint(ps.post.exit(\"exit\")) -- == snax.kill(ps, \"exit\")\n\tskynet.exit()\nend)\n"
  },
  {
    "path": "test/testpipeline.lua",
    "content": "local skynet = require \"skynet\"\nlocal redis = require \"skynet.db.redis\"\n\nlocal conf = {\n\thost = \"127.0.0.1\",\n\tport = 6379,\n\tdb = 0\n}\n\nlocal function read_table(t)\n    local result = { }\n    for i = 1, #t, 2 do result[t[i]] = t[i + 1] end\n    return result\nend\n\nskynet.start(function()\n\tlocal db = redis.connect(conf)\n\n\tdb.pipelining = function (self, block)\n\t\tlocal ops = {}\n\n\t\tblock(setmetatable({}, {\n\t\t\t__index = function (_, name)\n\t\t\t\treturn function (_, ...)\n\t\t\t\t\ttable.insert(ops, {name, ...})\n\t\t\t\tend\n\t\t\tend\n\t\t}))\n\n\t\treturn self:pipeline(ops)\n\tend\n\n\tdo\n\t\tprint(\"test function\")\n\t\tlocal ret = db:pipelining(function (red)\n\t\t\tred:multi()\n\t\t\tred:hincrby(\"hello\", 1, 1)\n\t\t\tred:del(\"hello\")\n\t\t\tred:hmset(\"hello\", 1, 1, 2, 2, 3, 3)\n\t\t\tred:hgetall(\"hello\")\n\t\t\tred:exec()\n\t\tend)\n\t\t-- ret is the result of red:exec()\n\t\tfor k, v in pairs(read_table(ret[4])) do\n\t\t\tprint(k, v)\n\t\tend\n\tend\n\n\tdo\n\t\tprint(\"test table\")\n\t\tlocal ret = db:pipeline({\n\t\t\t{\"hincrby\", \"hello\", 1, 1},\n\t\t\t{\"del\", \"hello\"},\n\t\t\t{\"hmset\", \"hello\", 1, 1, 2, 2, 3, 3},\n\t\t\t{\"hgetall\", \"hello\"},\n\t\t}, {})\t-- offer a {} for result\n\n\t\tprint(ret[1].out)\n\t\tprint(ret[2].out)\n\t\tprint(ret[3].out)\n\n\t\tfor k, v in pairs(read_table(ret[4].out)) do\n\t\t\tprint(k, v)\n\t\tend\n\tend\n\n\tdb:disconnect()\n\tskynet.exit()\nend)\n\n"
  },
  {
    "path": "test/testqueue.lua",
    "content": "local skynet = require \"skynet\"\nlocal snax = require \"skynet.snax\"\n\nskynet.start(function()\n\tlocal ps = snax.uniqueservice (\"pingserver\", \"test queue\")\n\tfor i=1, 10 do\n\t\tps.post.sleep(true,i*10)\n\t\tps.post.hello()\n\tend\n\tfor i=1, 10 do\n\t\tps.post.sleep(false,i*10)\n\t\tps.post.hello()\n\tend\n\n\tskynet.exit()\nend)\n\n\n"
  },
  {
    "path": "test/testredis.lua",
    "content": "local skynet = require \"skynet\"\nlocal redis = require \"skynet.db.redis\"\n\nlocal conf = {\n\thost = \"127.0.0.1\" ,\n\tport = 6379 ,\n\tdb = 0\n}\n\nlocal function watching()\n\tlocal w = redis.watch(conf)\n\tw:subscribe \"foo\"\n\tw:psubscribe \"hello.*\"\n\twhile true do\n\t\tprint(\"Watch\", w:message())\n\tend\nend\n\nskynet.start(function()\n\tskynet.fork(watching)\n\tlocal db = redis.connect(conf)\n\n\tdb:del \"C\"\n\tdb:set(\"A\", \"hello\")\n\tdb:set(\"B\", \"world\")\n\tdb:sadd(\"C\", \"one\")\n\n\tprint(db:get(\"A\"))\n\tprint(db:get(\"B\"))\n\n\tdb:del \"D\"\n\tfor i=1,10 do\n\t\tdb:hset(\"D\",i,i)\n\tend\n\tlocal r = db:hvals \"D\"\n\tfor k,v in pairs(r) do\n\t\tprint(k,v)\n\tend\n\n\tdb:multi()\n\tdb:get \"A\"\n\tdb:get \"B\"\n\tlocal t = db:exec()\n\tfor k,v in ipairs(t) do\n\t\tprint(\"Exec\", v)\n\tend\n\n\tprint(db:exists \"A\")\n\tprint(db:get \"A\")\n\tprint(db:set(\"A\",\"hello world\"))\n\tprint(db:get(\"A\"))\n\tprint(db:sismember(\"C\",\"one\"))\n\tprint(db:sismember(\"C\",\"two\"))\n\n\tprint(\"===========publish============\")\n\n\tfor i=1,10 do\n\t\tdb:publish(\"foo\", i)\n\tend\n\tfor i=11,20 do\n\t\tdb:publish(\"hello.foo\", i)\n\tend\n\n\tdb:disconnect()\n--\tskynet.exit()\nend)\n\n"
  },
  {
    "path": "test/testredis2.lua",
    "content": "local skynet = require \"skynet\"\nlocal redis  = require \"skynet.db.redis\"\n\nlocal db\n\nfunction add1(key, count)\n    local t = {}\n    for i = 1, count do\n        t[2*i -1] = \"key\" ..i\n        t[2*i] = \"value\" .. i\n    end\n    db:hmset(key, table.unpack(t))\nend\n\nfunction add2(key, count)\n    local t = {}\n    for i = 1, count do\n        t[2*i -1] = \"key\" ..i\n        t[2*i] = \"value\" .. i\n    end\n    table.insert(t, 1, key)\n    db:hmset(t)\nend\n\nfunction __init__()\n    db = redis.connect {\n        host = \"127.0.0.1\",\n        port = 6300,\n        db   = 0,\n        auth = \"foobared\"\n    }\n    print(\"dbsize:\", db:dbsize())\n    local ok, msg = xpcall(add1, debug.traceback, \"test1\", 250000)\n    if not ok then\n        print(\"add1 failed\", msg)\n    else\n        print(\"add1 succeed\")\n\n    end\n\n    local ok, msg = xpcall(add2, debug.traceback, \"test2\", 250000)\n    if not ok then\n        print(\"add2 failed\", msg)\n    else\n        print(\"add2 succeed\")\n    end\n    print(\"dbsize:\", db:dbsize())\n\n    print(\"redistest launched\")\nend\n\nskynet.start(__init__)\n\n"
  },
  {
    "path": "test/testrediscluster.lua",
    "content": "local skynet = require \"skynet\"\nlocal rediscluster = require \"skynet.db.redis.cluster\"\n\nlocal test_more = ...\n\n-- subscribe mode's callback\nlocal function onmessage(data,channel,pchannel)\n\tprint(\"onmessage\",data,channel,pchannel)\nend\n\nskynet.start(function ()\n\tlocal db = rediscluster.new({\n\t\t{host=\"127.0.0.1\",port=7000},\n\t\t{host=\"127.0.0.1\",port=7001},},\n\t\t{read_slave=true,auth=nil,db=0,},\n\t\tonmessage\n\t)\n\tdb:del(\"list\")\n\tdb:del(\"map\")\n\tdb:rpush(\"list\",1,2,3)\n\tlocal list = db:lrange(\"list\",0,-1)\n\tfor i,v in ipairs(list) do\n\t\tprint(v)\n\tend\n\tdb:hmset(\"map\",\"key1\",1,\"key2\",2)\n\tlocal map = db:hgetall(\"map\")\n\tfor i=1,#map,2 do\n\t\tlocal key = map[i]\n\t\tlocal val = map[i+1]\n\t\tprint(key,val)\n\tend\n\t-- test MOVED\n\tdb:flush_slots_cache()\n\tprint(db:set(\"A\",1))\n\tprint(db:get(\"A\"))\n\t-- reconnect\n\tlocal cnt = 0\n\tfor name,conn in pairs(db.connections) do\n\t\tprint(name,conn)\n\t\tcnt = cnt + 1\n\tend\n\tprint(\"cnt:\",cnt)\n\tdb:close_all_connection()\n\tprint(db:set(\"A\",1))\n\tprint(db:del(\"A\"))\n\n\tlocal slot = db:keyslot(\"{foo}\")\n\tlocal conn = db:get_connection_by_slot(slot)\n\t-- You must ensure keys at one slot: use same key or hash tags\n\tlocal ret = conn:pipeline({\n\t\t{\"hincrby\", \"{foo}hello\", 1, 1},\n\t\t{\"del\", \"{foo}hello\"},\n\t\t{\"hmset\", \"{foo}hello\", 1, 1, 2, 2, 3, 3},\n\t\t{\"hgetall\", \"{foo}hello\"},\n\t},{})\n\tprint(ret[1].ok,ret[1].out)\n\tprint(ret[2].ok,ret[2].out)\n\tprint(ret[3].ok,ret[3].out)\n\tprint(ret[4].ok)\n\tif ret[4].ok then\n\t\tfor i,v in ipairs(ret[4].out) do\n\t\t\tprint(v)\n\t\tend\n\telse\n\t\tprint(ret[4].out)\n\tend\n\t-- dbsize/info/keys\n\tlocal conn = db:get_random_connection()\n\tprint(\"dbsize:\",conn:dbsize())\n\tprint(\"info:\",conn:info())\n\tlocal keys = conn:keys(\"list*\")\n\tfor i,key in ipairs(keys) do\n\t\tprint(key)\n\tend\n\tprint(\"cluster nodes\")\n\tlocal nodes = db:cluster(\"nodes\")\n\tprint(nodes)\n\tprint(\"cluster slots\")\n\tlocal slots = db:cluster(\"slots\")\n\tfor i,slot_map in ipairs(slots) do\n\t\tlocal start_slot = slot_map[1]\n\t\tlocal end_slot = slot_map[2]\n\t\tlocal master_node = slot_map[3]\n\t\tprint(start_slot,end_slot)\n\t\tfor i,v in ipairs(master_node) do\n\t\t\tprint(v)\n\t\tend\n\t\tfor i=4,#slot_map do\n\t\t\tlocal slave_node = slot_map[i]\n\t\t\tfor i,v in ipairs(slave_node) do\n\t\t\t\tprint(v)\n\t\t\tend\n\t\tend\n\tend\n\n\t-- test subscribe/publish\n\tdb:subscribe(\"world\")\n\tdb:subscribe(\"myteam\")\n\tdb:publish(\"world\",\"hello,world\")\n\tdb:publish(\"myteam\",\"hello,my team\")\n\t-- low-version(such as 3.0.2) redis-server psubscribe is locally\n\t-- if publish and psubscribe not map to same node,\n\t-- we may lost message. so upgrade your redis or use tag to resolved!\n\tdb:psubscribe(\"{tag}*team\")\n\tdb:publish(\"{tag}1team\",\"hello,1team\")\n\tdb:publish(\"{tag}2team\",\"hello,2team\")\n\n\t-- i test in redis-4.0.9, it's ok\n\tdb:psubscribe(\"*team\")\n\tdb:publish(\"1team\",\"hello,1team\")\n\tdb:publish(\"2team\",\"hello,2team\")\n\n\t-- test eval\n\tdb:set(\"A\",1)\n\tlocal script = [[\n\t\tif redis.call(\"get\",KEYS[1]) == ARGV[1] then\n\t\t\treturn \"ok\"\n\t\telse\n\t\t\treturn \"fail\"\n\t\tend]]\n\tprint(\"eval#get\",db:eval(script,1,\"A\",1))\n\tdb:del(\"A\")\n\n\tif not test_more then\n\t\tskynet.exit()\n\t\treturn\n\tend\n\tlocal last = false\n\twhile not last do\n\t\tlast = db:get(\"__last__\")\n\t\tif last == nil then\n\t\t\tlast = 0\n\t\tend\n\t\tlast = tonumber(last)\n\tend\n\tfor val=last,1000000000 do\n\t\tlocal ok,errmsg = pcall(function ()\n\t\t\tlocal key = string.format(\"foo%s\",val)\n\t\t\tdb:set(key,val)\n\t\t\tprint(key,db:get(key))\n\t\t\tdb:set(\"__last__\",val)\n\t\tend)\n\t\tif not ok then\n\t\t\tprint(\"error:\",errmsg)\n\t\tend\n\tend\n\tskynet.exit()\nend)\n"
  },
  {
    "path": "test/testresponse.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal mode = ...\n\nif mode == \"TICK\" then\n-- this service whould response the request every 1s.\n\nlocal response_queue = {}\n\nlocal function response()\n\twhile true do\n\t\tskynet.sleep(100)\t-- sleep 1s\n\t\tfor k,v in ipairs(response_queue) do\n\t\t\tv(true, skynet.now())\t\t-- true means succ, false means error\n\t\t\tresponse_queue[k] = nil\n\t\tend\n\tend\nend\n\nskynet.start(function()\n\tskynet.fork(response)\n\tskynet.dispatch(\"lua\", function()\n\t\ttable.insert(response_queue, skynet.response())\n\tend)\nend)\n\nelse\n\nlocal function request(tick, i)\n\tprint(i, \"call\", skynet.now())\n\tprint(i, \"response\", skynet.call(tick, \"lua\"))\n\tprint(i, \"end\", skynet.now())\nend\n\nskynet.start(function()\n\tlocal tick = skynet.newservice(SERVICE_NAME, \"TICK\")\n\n\tfor i=1,5 do\n\t\tskynet.fork(request, tick, i)\n\t\tskynet.sleep(10)\n\tend\nend)\n\nend"
  },
  {
    "path": "test/testselect.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal mode = ...\n\nif mode == \"slave\" then\n\nlocal COMMAND = {}\n\nfunction COMMAND.ping(ti, str)\n\tskynet.sleep(ti)\n\treturn str\nend\n\nfunction COMMAND.error()\n\terror \"ERROR\"\nend\n\nfunction COMMAND.exit()\n\tskynet.exit()\nend\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function(_,_, cmd, ...)\n\t\tskynet.ret(skynet.pack(COMMAND[cmd](...)))\n\tend)\nend)\n\nelse\n\nlocal function info(fmt, ...)\n\tskynet.error(string.format(fmt, ...))\nend\n\nskynet.start(function()\n\tlocal slave = skynet.newservice(SERVICE_NAME, \"slave\")\n\n\tfor req, resp in skynet.request\n\t\t{ slave, \"lua\", \"ping\", 6, \"SLEEP 6\" }\n\t\t{ slave, \"lua\", \"ping\", 5, \"SLEEP 5\" }\n\t\t{ slave, \"lua\", \"ping\", 4, \"SLEEP 4\" }\n\t\t{ slave, \"lua\", \"ping\", 3, \"SLEEP 3\" }\n\t\t{ slave, \"lua\", \"ping\", 2, \"SLEEP 2\" }\n\t\t{ slave, \"lua\", \"ping\", 1, \"SLEEP 1\" }\n\t\t:select() do\n\t\tinfo(\"RESP %s\", resp[1])\n\tend\n\n\t-- test timeout\n\tlocal reqs = skynet.request()\n\n\tfor i = 1, 10 do\n\t\treqs:add { slave, \"lua\", \"ping\", i*10, \"SLEEP \" .. i, token = i }\n\tend\n\n\tfor req, resp in reqs:select(50) do\n\t\tinfo(\"RESP %s token<%s>\", resp[1], req.token)\n\tend\n\n\t-- test error\n\n\tfor req, resp in skynet.request\n\t\t{ slave, \"lua\", \"error\" }\n\t\t{ slave, \"lua\", \"ping\", 0, \"PING\" }\n\t\t: select() do\n\t\tif resp then\n\t\t\tinfo(\"Ping : %s\", resp[1])\n\t\telse\n\t\t\tinfo(\"Error\")\n\t\tend\n\tend\n\n\t-- timeout call\n\n\tlocal reqs = skynet.request { slave, \"lua\", \"ping\", 100 , \"PING\" }\n\tfor req, resp in reqs:select(10) do\n\t\tinfo(\"%s\", resp[1])\n\tend\n\n\tinfo(\"Timeout : %s\", reqs.timeout)\n\n\t-- call in select\n\tfor req, resp in skynet.request\n\t\t{ slave, \"lua\", \"ping\", 20, \"CALL 20\" }\n\t\t{ slave, \"lua\", \"ping\", 10, \"CALL 10\" }\n\t\t: select() do\n\t\tinfo(\"%s\", skynet.call( slave, \"lua\", \"ping\", 0, \"ping in \" .. resp[1]) )\n\t\tskynet.sleep(50)\n\tend\n\n\tskynet.send(slave, \"lua\", \"exit\")\n\tskynet.exit()\nend)\n\nend\n"
  },
  {
    "path": "test/testservice/init.lua",
    "content": "local skynet = require \"skynet\"\nlocal kvdb = require \"kvdb\"\n\nlocal function dbname(i)\n\treturn \"db\"..i\nend\nskynet.start(function()\n\tfor i=1,10 do\n\t\tkvdb.new(dbname(i))\n\tend\n\tlocal idx=1\n\tfor i=1,10 do\n\t\tlocal db=dbname(i)\n\t\tkvdb.set(db,\"A\",idx)\n\t\tidx=idx+1\n\t\tkvdb.set(db,\"B\",idx)\n\t\tidx=idx+1\n\tend\n\tfor i=1,10 do\n\t\tlocal db=dbname(i)\n\t\tprint(db,kvdb.get(db,\"A\"),kvdb.get(db,\"B\"))\n\tend\nend)\n"
  },
  {
    "path": "test/testservice/kvdb.lua",
    "content": "local skynet = require \"skynet\"\nlocal service = require \"skynet.service\"\n\nlocal kvdb = {}\n\nfunction kvdb.get(db,key)\n\treturn skynet.call(service.query(db), \"lua\", \"get\", key)\nend\n\nfunction kvdb.set(db,key, value)\n\tskynet.call(service.query(db), \"lua\", \"set\", key , value)\nend\n\n-- this function will be injected into an unique service, so don't refer any upvalues\nlocal function service_mainfunc(...)\n\tlocal skynet = require \"skynet\"\n\n\tskynet.error(...)\t-- (...) passed from service.new\n\n\tlocal db = {}\n\n\tlocal command = {}\n\n\tfunction command.get(key)\n\t\treturn db[key]\n\tend\n\n\tfunction command.set(key, value)\n\t\tdb[key] = value\n\tend\n\n\t-- skynet.start is compatible\n\tskynet.dispatch(\"lua\", function(session, address, cmd, ...)\n\t\tskynet.ret(skynet.pack(command[cmd](...)))\n\tend)\nend\n\nfunction kvdb.new(db)\n\treturn service.new(db, service_mainfunc, \"Service Init\")\nend\n\nreturn kvdb\n"
  },
  {
    "path": "test/testsha.lua",
    "content": "local skynet = require \"skynet\"\nlocal crypt = require \"skynet.crypt\"\n\nlocal function sha1(text)\n\tlocal c = crypt.sha1(text)\n\treturn crypt.hexencode(c)\nend\n\nlocal function hmac_sha1(key, text)\n\tlocal c = crypt.hmac_sha1(key, text)\n\treturn crypt.hexencode(c)\nend\n\n-- test case from http://regex.info/code/sha1.lua\n\nprint(1) assert(sha1 \"http://regex.info/blog/\"                                  == \"7f103bf600de51dfe91062300c14738b32725db5\", 1)\nprint(2) assert(sha1(string.rep(\"a\", 10000))                                    == \"a080cbda64850abb7b7f67ee875ba068074ff6fe\", 2)\nprint(3) assert(sha1 \"abc\"                                                      == \"a9993e364706816aba3e25717850c26c9cd0d89d\", 3)\nprint(4) assert(sha1 \"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\" == \"84983e441c3bd26ebaae4aa1f95129e5e54670f1\", 4)\nprint(5) assert(sha1 \"The quick brown fox jumps over the lazy dog\"              == \"2fd4e1c67a2d28fced849ee1bb76e7391b93eb12\", 5)\nprint(6) assert(sha1 \"The quick brown fox jumps over the lazy cog\"              == \"de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3\", 6)\nprint(7) assert(\"efb750130b6cc9adf4be219435e575442ec68b7c\" == sha1(string.char(136,43,218,202,158,86,64,140,154,173,20,184,170,125,37,54,208,68,171,24,164,89,142,111,148,235,187,181,122):rep(76)), 7)\nprint(8) assert(\"432dff9d4023e13194170287103d0377ed182d96\" == sha1(string.char(20,174):rep(407)), 8)\nprint(9) assert(\"ccba5c47946530726bb86034dbee1dbf0c203e99\" == sha1(string.char(20,54,149,252,176,4,96,100,223):rep(753)), 9)\nprint(10) assert(\"4d6fea4f8576cd6648ae2d2ee4dc5df0a8309115\" == sha1(string.char(118,171,221,33,54,209,223,152,35,67,88,50):rep(985)), 10)\nprint(11) assert(\"f560412aabf813d01f15fdc6650489584aabd266\" == sha1(string.char(23,85,29,13,146,55,164,14,206,196,109,183,53,92,97,123,242,220,112,15,43,113,22,246,114,29,209,219,190):rep(177)), 11)\nprint(12) assert(\"b56795e12f3857b3ba1cbbcedb4d92dd9c419328\" == sha1(string.char(21,216):rep(131)), 12)\nprint(13) assert(\"54f292ecb7561e8ce27984685b427234c9465095\" == sha1(string.char(15,205,12,181,4,114,128,118,219):rep(818)), 13)\nprint(14) assert(\"fe265c1b5a848e5f3ada94a7e1bb98a8ce319835\" == sha1(string.char(136,165,10,46,167,184,86,255,58,206,237,21,255,15,198,211,145,112,228,146,26,69,92,158,182,165,244,39,152):rep(605)), 14)\nprint(15) assert(\"96f186998825075d528646059edadb55fdd96659\" == sha1(string.char(100,226,28,248,132,70,221,54,92,181,82,128,191,12,250,244):rep(94)), 15)\nprint(16) assert(\"e29c68e4d6ffd3998b2180015be9caee59dd8c8a\" == sha1(string.char(247,14,15,163,0,53,50,113,84,121):rep(967)), 16)\nprint(17) assert(\"6d2332a82b3600cbc5d2417f944c38be9f1081ae\" == sha1(string.char(93,98,119,201,41,27,89,144,25,141,117,26,111,132):rep(632)), 17)\nprint(18) assert(\"d84a91da8fb3aa7cd59b99f347113939406ef8eb\" == sha1(string.char(28,252,0,4,150,164,91):rep(568)), 18)\nprint(19) assert(\"8edf1b92ad5a90ed762def9a873a799b4bda97f9\" == sha1(string.char(166,67,113,111,161,253,169,195,158,97,96,150,49,219,103,16,186,184,37,109,228,111):rep(135)), 19)\nprint(20) assert(\"d5b2c7019f9ff2f75c38dc040c827ab9d1a42157\" == sha1(string.char(38,252,110,224,168,60,2,133,8,153,200,0,199,104,191,62,28,168,73,48,199,217,83):rep(168)), 20)\nprint(21) assert(\"5aeb57041bfada3b72e3514f493d7b9f4ca96620\" == sha1(string.char(57):rep(738)), 21)\nprint(22) assert(\"4548238c8c2124c6398427ed447ae8abbb8ead27\" == sha1(string.char(221,131,171):rep(230)), 22)\nprint(23) assert(\"ed0960b87a790a24eb2890d8ea8b18043f1a87d5\" == sha1(string.char(151,113,144,19,249,148,75,51,164,233,102,232,3,58,81,99,101,255,93,231,147,150,212,216,109,62):rep(110)), 23)\nprint(24) assert(\"d7ac6233298783af55901907bb99c13b2afbca99\" == sha1(string.char(44,239,189,203,196,79,82,143,99,21,125,75,167,26,108,161,9,193,72):rep(919)), 24)\nprint(25) assert(\"43600b41a3c5267e625bbdfde95027429c330c60\" == sha1(string.char(122,70,129,24,192,213,205,224,62,79,81,129,22,171):rep(578)), 25)\nprint(26) assert(\"5816df09a78e4594c1b02b170aa57333162def38\" == sha1(string.char(76,103,48,150,115,161,86,42,247,82,197,213,155,108,215,18,119):rep(480)), 26)\nprint(27) assert(\"ef7903b1e811a086a9a5a5142242132e1367ae1d\" == sha1(string.char(143,70):rep(65)), 27)\nprint(28) assert(\"6e16b2dac71e338a4bd26f182fdd5a2de3c30e6c\" == sha1(string.char(130,114,144,219,245,72,205,44,149,68,150,169,243):rep(197)), 28)\nprint(29) assert(\"6cc772f978ca5ef257273f046030f84b170f90c9\" == sha1(string.char(26,49,141,64,30,61,12):rep(362)), 29)\nprint(30) assert(\"54231fc19a04a64fc1aa3dce0882678b04062012\" == sha1(string.char(76,252,160,253,253,167,27,179,237,15,219,46,141,255,23,53,184,190,233,125,211,11):rep(741)), 30)\nprint(31) assert(\"5511a993b808e572999e508c3ce27d5f12bb4730\" == sha1(string.char(197,139,184,188,200,31,171,236,252,147,123,75,7,138,111,167,68,114,73,80,51,233,241,233,91):rep(528)), 31)\nprint(32) assert(\"64c4577d4763c95f47ac5d21a292836a34b8b124\" == sha1(string.char(177,114,100,216,18,57,2,110,108,60,81,80,253,144,179,47,228,42,105,72,86,18,30,167):rep(901)), 32)\nprint(33) assert(\"bb0467117e3b630c2b3d9cdf063a7e6766a3eae1\" == sha1(string.char(249,99,174,228,15,211,121,152,203,115,197,198,66,17,196,6,159,170,116):rep(800)), 33)\nprint(34) assert(\"1f9c66fca93bc33a071eef7d25cf0b492861e679\" == sha1(string.char(205,64,237,65,171,0,176,17,104,6,101,29,128,200,214,24,32,91,115,71,26,11,226,69,141,83,249,129):rep(288)), 34)\nprint(35) assert(\"55d228d9bfd522105fe1e1f1b5b09a1e8ee9f782\" == sha1(string.char(96,37,252,185,137,194,215,191,190,235,73,224,125,18,146,74,32,82,58,95,49,102,85,57,241,54,55):rep(352)), 35)\nprint(36) assert(\"58c3167e666bf3b4062315a84a72172688ad08b1\" == sha1(string.char(65,91,96,147,212,18,32,144,138,187,70,26,105,42,71,13,229,137,185,10,86,124,171,204,104,42,2,172):rep(413)), 36)\nprint(37) assert(\"f97936ca990d1c11a9967fd12fc717dcd10b8e9e\" == sha1(string.char(253,159,59,76,230,153,22,198,15,9,223,3,31):rep(518)), 37)\nprint(38) assert(\"5d15229ad10d2276d45c54b83fc0879579c2828e\" == sha1(string.char(149,20,176,144,39,216,82,80,56,38,152,49,167,120,222,20,26,51,157,131,160,52,6):rep(895)), 38)\nprint(39) assert(\"3757d3e98d46205a6b129e09b0beefaa0e453e64\" == sha1(string.char(120,131,113,78,7,19,59,120,210,220,73,118,36,240,64,46,149,3,120,223,80,232,255,212,250,76,109,108,133):rep(724)), 39)\nprint(40) assert(\"5e62539caa6c16752739f4f9fd33ca9032fff7e1\" == sha1(string.char(216,240,166,165,2,203,2,189,137,219,231,229):rep(61)), 40)\nprint(41) assert(\"3ff1c031417e7e9a34ce21be6d26033f66cb72c9\" == sha1(string.char(4,178,215,183,17,198,184,253,137,108,178,74,244,126,32):rep(942)), 41)\nprint(42) assert(\"8c20831fc3c652e5ce53b9612878e0478ab11ee6\" == sha1(string.char(115,157,59,188,221,67,52,151,147,233,84,30,243,250,109,103,101,0,219,13,176,38,21):rep(767)), 42)\nprint(43) assert(\"09c7c977cb39893c096449770e1ed75eebb9e5a1\" == sha1(string.char(184,131,17,61,201,164,19,25,36,141,173,74,134,132,104,23,104,136,121,232,12,203,115,111,54,114,251,223,61,126):rep(458)), 43)\nprint(44) assert(\"9534d690768bc85d2919a059b05561ec94547fc2\" == sha1(string.char(49,93,136,112,92,42,117,28,31):rep(187)), 44)\nprint(45) assert(\"7dfca0671de92a62de78f63c0921ff087f2ba61d\" == sha1(string.char(194,78,252,112,175,6,26,103,4,47,195,99,78,130,40,58,84,175,240,180,255,108,3,42,51,111,35,49,217,160):rep(72)), 45)\nprint(46) assert(\"62bf20c51473c6a0f23752e369cabd6c167c9415\" == sha1(string.char(28,126,243,196,155,31,158,50):rep(166)), 46)\nprint(47) assert(\"2ece95e43aba523cdbf248d07c05f569ecd0bd12\" == sha1(string.char(76,230,117,248,231,228):rep(294)), 47)\nprint(48) assert(\"722752e863386b737f29a08f23a0ec21c4313519\" == sha1(string.char(61,102,1,118):rep(470)), 48)\nprint(49) assert(\"a638db01b5af10a828c6e5b73f4ca881974124a0\" == sha1(string.char(130,8,4):rep(768)), 49)\nprint(50) assert(\"54c7f932548703cc75877195276bc2aa9643cf9b\" == sha1(string.char(193,232,122,142,213,243,224,29,201,6,127,45,4,36,92,200,148,111,106,110,221,235,197,51,66,221,123,155,222,186):rep(290)), 50)\nprint(51) assert(\"ecfc29397445d85c0f6dd6dc50a1272accba0920\" == sha1(string.char(221,76,21,148,12,109,232,113,230,110,96,82,36):rep(196)), 51)\nprint(52) assert(\"31d966d9540f77b49598fa22be4b599c3ba307aa\" == sha1(string.char(148,237,212,223,44,133,153):rep(53)), 52)\nprint(53) assert(\"9f97c8ace98db9f61d173bf2b705404eb2e9e283\" == sha1(string.char(190,233,29,208,161,231,248,214,210):rep(451)), 53)\nprint(54) assert(\"63449cfce29849d882d9552947ebf82920392aea\" == sha1(string.char(216,12,113,137,33,99,200,140,6,222,170,2,115,50,138,134,211,244,176,250,42,95):rep(721)), 54)\nprint(55) assert(\"15dc62f4469fb9eae76cd86a84d576905c4bbfe7\" == sha1(string.char(50,194,13,88,156,226,39,135,165,204):rep(417)), 55)\nprint(56) assert(\"abbc342bcfdb67944466e7086d284500e25aa103\" == sha1(string.char(35,39,227,31,206,163,148,163,172,253,98,21,215,43,226,227,130,151,236,177,176,63,30,47,74):rep(960)), 56)\nprint(57) assert(\"77ae3a7d3948eaa2c60d6bc165ba2812122f0cce\" == sha1(string.char(166,83,82,49,153,89,58,79,131,163,125,18,43,135,120,17,48,94,136):rep(599)), 57)\nprint(58) assert(\"d62e1c4395c8657ab1b1c776b924b29a8e009de1\" == sha1(string.char(196,199,71,80,10,233,9,229,91,72,73,205,75,77,122,243,219,152):rep(964)), 58)\nprint(59) assert(\"15d98d5279651f4a2566eda6eec573812d050ff7\" == sha1(string.char(78,70,7,229,21,78,164,158,114,232,100,102,92,18,133,160,56,177,160,49,168,149,13,39,249,214,54,41):rep(618)), 59)\nprint(60) assert(\"c3d9bc6535736f09fbb018427c994e58bbcb98f6\" == sha1(string.char(129,208,110,40,135,3):rep(618)), 60)\nprint(61) assert(\"7dc6b3f309cbe9fa3b2947c2526870a39bf96dc4\" == sha1(string.char(126,184,110,39,55,177,108,179,214,200,175,118,125,212,19,147,137,133,89,209,89,189,233,164,71,81,156,215,152):rep(908)), 61)\nprint(62) assert(\"b2d4ca3e787a1e475f6608136e89134ae279be57\" == sha1(string.char(182,80,145,53,128,194,228,155,53):rep(475)), 62)\nprint(63) assert(\"fbe6b9c3a7442806c5b9491642c69f8e56fdd576\" == sha1(string.char(9,208,72,179,222,245,140,143,123,111,236,241,40,36,49,68,61,16,169,124,104,42,136,82,172):rep(189)), 63)\nprint(64) assert(\"f87d96380201954801004f6b82af1953427dfdcb\" == sha1(string.char(153,133,37,2,24,150,93,242,223,68,202,54,118,141,76,35,100,137,13):rep(307)), 64)\nprint(65) assert(\"a953e2d054dd77f75337dd9dfa58ec4d3978cfb4\" == sha1(string.char(112,215,41,50,221,94):rep(155)), 65)\nprint(66) assert(\"e5c3047f9abfdd60f0c386b9a820f11d7028bc70\" == sha1(string.char(247,177,124,213,47,175,139,203,81,21,85):rep(766)), 66)\nprint(67) assert(\"ee6fe88911a13abfc0006f8809f51b9de7f5920f\" == sha1(string.char(81,84,151,242,186,133,39,245,175,79,66,170,246,216,0,88,100,190,137,2,146,58):rep(10)), 67)\nprint(68) assert(\"091db84d93bb68349eecf6bfa9378251ecd85500\" == sha1(string.char(180,71,122,187):rep(129)), 68)\nprint(69) assert(\"d8041c7d65201cc5a77056a5c7eb94a524494754\" == sha1(string.char(188,99,87,126,152,214,159,151,234,223,199,247,213,107,63,59,12,146,175,57,79,200,132,202):rep(81)), 69)\nprint(70) assert(\"cca1d77faf56f70c82fcb7bc2c0ac9daf553adff\" == sha1(string.char(199,1,184,22,113,25,95,87,169,114,130,205,125,159,170,99):rep(865)), 70)\nprint(71) assert(\"c009245d9767d4f56464a7b3d6b8ad62eba5ddeb\" == sha1(string.char(39,168,16,191,95,82,184,102,242,224,15,108):rep(175)), 71)\nprint(72) assert(\"8ce115679600324b58dc8745e38d9bea0a9fb4d6\" == sha1(string.char(164,247,250,142,139,131,158,241,27,36,81,239,26,233,105,64,38,249,151,75,142,17,56,217,125,74,132,213,213):rep(426)), 72)\nprint(73) assert(\"75f1e55718fd7a3c27792634e70760c6a390d40f\" == sha1(string.char(32,145,170,90,188,97,251,159,244,153,21,126,2,67,36,110,31,251,66):rep(659)), 73)\nprint(74) assert(\"615722261d6ec8cef4a4e7698200582958193f26\" == sha1(string.char(51,24,1,69,81,157,34,185,26,159,231,119):rep(994)), 74)\nprint(75) assert(\"4f61d2c1b60d342c51bc47641e0993d42e89c0f9\" == sha1(string.char(175,25,99,122,247,217,204,100,0,35,57,65,150,182,51,79,169,99,9,33,113,113,113):rep(211)), 75)\nprint(76) assert(\"7d9842e115fc2af17a90a6d85416dbadb663cef3\" == sha1(string.char(136,42,39,219,103,95,119,125,205,72,174,15,210,213,23,75,120,56,104,31,63,255,253,100,61,55):rep(668)), 76)\nprint(77) assert(\"3eccab72b375de3ba95a9f0fa715ae13cae82c08\" == sha1(string.char(190,254,173,227,195,41,49,122,135,57,100):rep(729)), 77)\nprint(78) assert(\"7dd68f741731211e0442ce7251e56950e0d05f96\" == sha1(string.char(101,155,117,8,143,40,192,100,162,121,142,191,92):rep(250)), 78)\nprint(79) assert(\"5e98cdb7f6d7e4e2466f9be23ec20d9177c5ddff\" == sha1(string.char(84,67,182,136,89):rep(551)), 79)\nprint(80) assert(\"dba1c76e22e2c391bde336c50319fbff2d66c3bb\" == sha1(string.char(99,226,185,1,192):rep(702)), 80)\nprint(81) assert(\"4b160b8bfe24147b01a247bfdc7a5296b6354e38\" == sha1(string.char(144,141,254,1,166,144,129,232,203,31,192,75,145,12):rep(724)), 81)\nprint(82) assert(\"27625ad9833144f6b818ef1cf54245dd4897d8aa\" == sha1(string.char(31,187,82,156,224,133,116,251,180,165,246,8):rep(661)), 82)\nprint(83) assert(\"0ce5e059d22a7ba5e2af9f0c6551d010b08ba197\" == sha1(string.char(228):rep(672)), 83)\nprint(84) assert(\"290982513a7f67a876c043d3c7819facb9082ea6\" == sha1(string.char(150,44,52,144,68,76,207,114,106,153,99,39,219,81,73,140,71,4,228,220,55,244,210,225,221,32):rep(881)), 84)\nprint(85) assert(\"14cf924aafceea393a8eb5dd06616c1fe1ccd735\" == sha1(string.char(140,194,247,253,117,121,184,216,249,84,41,12,199):rep(738)), 85)\nprint(86) assert(\"91e9cc620573db9a692bb0171c5c11b5946ad5c3\" == sha1(string.char(48,77,182,152,26,145,231,116,179,95,21,248,120,55,73,66):rep(971)), 86)\nprint(87) assert(\"3eb85ec3db474d01acafcbc5ec6e942b3a04a382\" == sha1(string.char(68,211):rep(184)), 87)\nprint(88) assert(\"f9bd0e886c74d730cb2457c484d30ce6a47f7afa\" == sha1(string.char(168,73,19,144,110,93,7,216,40,111,212,192,33,9,136,28,210,175,140,47,125,243,206,157,151,252,26):rep(511)), 88)\nprint(89) assert(\"64461476eb8bba70e322e4b83db2beaee5b495d4\" == sha1(string.char(33,141):rep(359)), 89)\nprint(90) assert(\"761e44ffa4df3b4e28ca22020dee1e0018107d21\" == sha1(string.char(254,172,185,30,245,135,14,5,186,42,47,22):rep(715)), 90)\nprint(91) assert(\"41161168b99104087bae0f5287b10a15c805596f\" == sha1(string.char(79):rep(625)), 91)\nprint(92) assert(\"7088f4d88146e6e7784172c2ad1f59ec39fa7768\" == sha1(string.char(20,138,80,102,138,182,54,210,38,214,125,123,157,209,215,37):rep(315)), 92)\nprint(93) assert(\"2e498e938cb3126ac1291cee8c483a91479900c1\" == sha1(string.char(140,197,97,112,205,97,134,190):rep(552)), 93)\nprint(94) assert(\"81a2491b727ef2b46fb84e4da2ced84d43587f4e\" == sha1(string.char(109,44,17,199,17,107,170,54,113,153,212,161,174):rep(136)), 94)\nprint(95) assert(\"0e4f8a07072968fbc4fe32deccbb95f113b32df7\" == sha1(string.char(181,247,203,166,34,61,180,48,46,77,98,251,72,210,217,242,135,133,38,12,177,163,249,31,1,162):rep(282)), 95)\nprint(96) assert(\"8d15dddd48575a1a0330976b57e2104629afe559\" == sha1(string.char(15,60,105,249,158,45,14,208,202,232,255,181,234,217):rep(769)), 96)\nprint(97) assert(\"98a9dd7b57418937cbd42f758baac4754d5a4a4b\" == sha1(string.char(115,121,91,76,175,110,149,190,56,178,191,157,101,220,190,251,62,41,190,37):rep(879)), 97)\nprint(98) assert(\"578487979de082f69e657d165df5031f1fa84030\" == sha1(string.char(189,240,198,207,102,142,241,154):rep(684)), 98)\nprint(99) assert(\"3e6667b40afb6bcc052654dd64a653ad4b4f9689\" == sha1(string.char(85,82,55,80,43,17,57,20,157,10,148,85,154,58,254,254,221,132,53,105,43,234,251,110,111):rep(712)), 99)\n\nprint(100) assert(\"31285f3fa3c6a086d030cf0f06b07e7a96b5cbd0\" == hmac_sha1(\"63xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",   \"data\"), 100)\nprint(101) assert(\"2d183212abc09247e21282d366eeb14d0bc41fb4\" == hmac_sha1(\"64xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",  \"data\"), 101)\nprint(102) assert(\"ff825333e64e696fc13d82c19071fa46dc94a066\" == hmac_sha1(\"65xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\", \"data\"),  102)\nprint(103) assert(\"ecc8b5d3abb5182d3d570a6f060fef2ee6c11a44\" == hmac_sha1(string.char(220,58,17,206,77,234,240,187,69,25,179,182,186,38,57,83,120,107,198,148,234,246,46,96,83,28,231,89,3,169,42,62,125,235,137), string.char(1,225,98,83,100,71,237,241,239,170,244,215,3,254,14,24,216,66,69,30,124,126,96,177,241,20,44,3,92,111,243,169,100,119,198,167,146,242,30,124,7,22,251,52,235,95,211,145,56,204,236,37,107,139,17,184,65,207,245,101,241,12,50,149,19,118,208,133,198,33,80,94,87,133,146,202,27,89,201,218,171,206,21,191,43,77,127,30,187,194,166,39,191,208,42,167,77,202,186,225,4,86,218,237,157,117,175,106,63,166,132,136,153,243,187)), 103)\nprint(104) assert(\"bd1577a9417d804ee2969636fa9dde838beb967d\" == hmac_sha1(string.char(216,76,38,50,235,99,92,110,245,5,134,195,113,7), string.char(144,3,250,84,145,227,206,87,188,42,169,182,106,31,207,205,33,76,52,158,255,49,129,169,9,145,203,225,90,228,163,33,49,99,29,135,60,112,152,5,200,121,35,77,56,116,68,109,190,136,184,248,144,172,47,107,30,16,105,232,146,137,24,81,245,94,28,76,27,82,105,146,252,219,119,164,21,14,74,192,209,208,156,56,172,124,89,218,51,108,44,174,193,161,228,147,219,129,172,210,248,239,22,11,62,128,1,50,98,233,141,224,102,152,44,68,66,46,210,114,138,113,121,90,7,70,125,191,192,222,225,200,217,48,22,10,132,29,236,71,108,140,102,96,51,142,51,220,4)), 104)\nprint(105) assert(\"e8ddf90f0c117ee61b33db4df49d7fc31beca7f7\" == hmac_sha1(string.char(189,213,184,86,24,160,198,82,138,223,71,149,249,70,183,47,0,106,27,39,85,102,57,190,237,182,2,10,21,253,252,3,68,73,154,75,79,247,28,132,229,50,2,197,204,213,170,213,255,83,100,213,60,67,202,61,137,125,16,215,254,157,106,5), string.char(78,103,249,15,43,214,87,62,52,57,135,84,44,92,142,209,120,139,76,216,33,223,203,96,218,12,6,126,241,195,47,203,196,22,113,138,228,44,122,37,215,166,184,195,91,97,175,153,115,243,37,225,82,250,54,240,20,237,149,183,5,43,142,113,214,130,100,149,83,232,70,106,152,110,25,74,46,60,159,239,193,173,235,146,173,142,110,71,1,97,54,217,52,228,250,42,223,53,105,24,87,98,117,245,101,189,147,238,48,111,68,52,169,78,151,38,21,249)), 105)\nprint(106) assert(\"e33c987c31bb45b842868d49e7636bd840a1ffd3\" == hmac_sha1(string.char(154,60,91,199,157,45,32,99,248,5,163,234,114,223,234,48,238,82,43,242,52,176,243,5,135,26,141,49,105,120,220,135,192,96,219,152,126,74,58,110,200,56,108,1,68,175,82,235,149,191,67,72,195,46,35,131,237,188,177,223,145,122,26,234,136,93,34,96,71,214,55,27,13,116,235,109,58,83,175,226,59,13,218,93,5,132,43,235), string.char(182,10,154)), 106)\nprint(107) assert(\"f6039d217c16afadfcfae7c5e3d1859801a0fe22\" == hmac_sha1(string.char(73,120,173,165,190,159,174,100,255,56,217,98,249,11,166,25,66,95,96,99,70,73,223,132,231,147,220,151,79,102,111,98), string.char(134,93,229,103)), 107)\nprint(108) assert(\"f6056b19cf6b070e62a0917a46f4b3aefcf6262d\" == hmac_sha1(string.char(49,40,62,214,208,180,147,74,162,196,193,9,118,47,100,9,235,94,3,122,226,163,145,175,233,148,251,88,49,216,208,110,13,97,255,189,120,252,223,241,55,210,77,4), string.char(92,185,37,240,36,97,21,132,188,80,103,36,162,245,63,104,19,106,242,44,96,28,197,26,46,168,73,46,76,105,30,167,101,64,67,119,65,140,177,226,223,108,206,60,59,0,182,125,42,200,101,159,109,6,62,85,67,66,88,137,92,234,61,19,22,177,144,127,129,129,195,230,180,149,128,148,45,18,94,163,196,55,70,184,251,3,200,162,16,210,188,61,186,218,173,227,212,8,125,20,138,82,68,170,24,158,90,98,228,166,246,96,74,24,217,93,91,102,246,221,121,115,157,243,45,158,45,90,186,11,127,179,59,72,37,71,148,123,62,150,114,167,248,197,18,251,92,164,158,83,129,58,127,162,181,92,85,121,13,118,250,221,220,150,231,5,230,28,213,25,251,17,71,68,234,173,10,206,111,72,123,205,49,73,62,209,173,46,94,91,151,122)), 108)\nprint(109) assert(\"15ddfa1baa0a3723d8aff00aeefa27b5b02ede95\" == hmac_sha1(string.char(91,117,129,150,117,169,221,182,193,130,126,206,129,177,184,171,174,224,91,234,60,197,243,158,59,0,122,240,145,106,192,179,96,84,46,239,170,123,120,51,142,101,45,34), string.char(27,71,38,183,232,93,23,174,151,181,121,91,142,138,180,125,75,243,160,220,225,205,205,72,13,162,104,218,47,162,77,23,16,154,31,156,122,67,227,25,190,102,200,57,116,190,131,8,208,76,174,53,204,88,227,239,71,67,208,32,57,72,165,121,80,139,80,29,90,32,229,208,115,169,238,189,206,82,180,68,157,124,119,1,75,27,122,246,197,178,90,225,138,244,73,12,226,104,191,70,53,210,245,250,239,238,3,229,196,22,28,199,122,158,9,33,109,182,109,87,25,159,159,146,217,77,37,25,173,211,38,173,70,252,18,193,7,167,160,135,63,190,149,14,221,143,173,152,184,143,157,245,137,219,74,239,185,40,14,0,29,87,169,84,67,75,255,252,201,131,75,108,43,129,210,193,108,139,60,228,29,36,150,15,86)), 109)\nprint(110) assert(\"d7cba04970a79f5d04c772fbe74bcc0951ff9c67\" == hmac_sha1(string.char(159,179,206,236,86,25,53,102,163,243,239,139,134,14,243), string.char(106,160,249,31,114,205,9,66,139,182,209,218,31,151,57,132,182,85,218,220,103,15,210,218,101,244,240,227,12,184,127,137,40,127,232,195,234,182,0,214,125,122,141,207,61,244,143,202,159,229,100,76,165,44,226,137,100,61,1,107,132,142,144,158,223,249,151,78,186,194,189,83,45,66,178,41,23,172,195,137,170,216,208,27,149,112,68,188,0)), 110)\nprint(111) assert(\"84625a20dc9ada78ec9de910d37734a299f01c5d\" == hmac_sha1(string.char(85,239,250,237,210,126,142,84,119,107,100,163,15,179,132,206,112,85,119,101,44,163,240,10,14,69,169,158,170,190,95,66,129,69,218,229), string.char(210,103,131,185,91,224,115,108,129,11,50,16,90,98,64,124,157,177,50,21,30,201,244,101,136,104,149,102,34,166,25,62,1,79,216,4,221,113,168,169,5,151,172,22,166,28,130,137,251,164,220,189,253,45,149,80,247,84,130,208,69,49,120,8,90,154,100,191,121,81,230,207,23,189,7,164,112,123,158,192,224,255,218,200,70,238,211,161,35,251,150,125,24,10,131,220,57,178,196,38,231,196,206,94,118,32,56,197,136,148,145,247,188,64,56,53,195,140,92,202,22,122,229,105,115,14,42,27,107,223,105)), 111)\nprint(112) assert(\"c463318ac1878cd770ec93b2710b706296316894\" == hmac_sha1(string.char(162,21,153,195,254,135,203,75,152,144,200,187,226,4,248,93,161,180,219,181,99,130,122,28,179,140,152,9,21,115,34,140,162,45,88,4,33,238,179,125,58,23,108,194,158,48,191,40,3,50,81,247,114,241,0,88,147,93,57,178,73,187,11,195,254,171,106,167,245,190,117,160,1,219,200,249,107,233,58,19,122), string.char(246,179,198,163,52,106,45,38,131,22,142,185,149,121,79,211,0,16,102,52,46,176,83,7,32,42,103,184,234,107,180,128,128,130,21,27,236)), 112)\nprint(113) assert(\"e2d37df980593b3e52aadb0d99d61114fb2c1182\" == hmac_sha1(string.char(43,84,125,158,182,211,26,238,222,247,6,171,184,54,70,44,169,4,74,34,98,71,118,189,138,53,8,164,117,22,76,171,57,255,122,230,110,122,228,22,252,123,174,218,222,77,80,150,159,43,236,137,234,48,122,138,100,137,112), string.char(249,234,226,86,109,2,157,76,229,42,178,223,196,247,42,194,17,17,117,3,45,6,80,202,22,105,44,242,84,25,21,189,5,216,35,200,220,192,110,81,215,145,109,179,48,44,40,35,216,240,48,240,33,210,79,35,64,189,81,15,135,228,83,14,254,32,211,229,158,79,188,230,84,106,78,126,226,106,203,59,67,134,186,52,21,48,2,142,231,116,241,167,177,175,74,188,232,234,56,41,181,118,232,190,184,76,64,109,167,178,123,118,3,50,46,254,253,83,156,116,220,247,69,27,160,167,210,205,79,60,28,253,17,219,32,44,217,223,77,153,229,55,113,75,234,154,247,13,133,49,220,200,241,111,136,205,14,78,222,55,181,250,160,143,224,37,63,227,155,12,39,173,209,45,171,93,93,70,36,129,111,173,183,112,31,231,22,146,129,171,75,128,45)), 113)\nprint(114) assert(\"666f9c282cf544c9c28006713a7461c7efbbdbda\" == hmac_sha1(string.char(71,33,203,83,173,199,175,245,206,13,237,187,54,61,85,15,153,125,168,223,231,56,46,250,173,192,247,189,45,166,225,223,109,254,15,79,144,188,71,201,70,25,218,205,13,184,204,219,221,82,133,189,144,179,242,125,211,108,100,1,132,110,231,87,107,91,169,101,241,105,30), string.char(98,122,51,157,136,38,149,9,82,27,218,155,76,61,254,154,43,172,59,105,123,45,97,146,191,58,50,153,139,40,37,116)), 114)\nprint(115) assert(\"6904a4ce463002b03923c71cdac6c38f57315b63\" == hmac_sha1(string.char(15,40,41,76,105,201,153,223,174,12,100,114,234,95,204,95,84,31,26,28,69,85,48,111,40,173,162,6,198,36,252,179,244,9,112,213,64,87,58,186,4,147,229,211,161,30,226,159,75,38,91,89,224,245,156,110,229,50,210), string.char(213,155,72,86,75,185,138,211,199,57,75,9,1,141,184,89,82,180,105,17,193,63,161,202,25,60,16,201,72,179,74,129,73,172,84,39,140,33,25,122,136,143,116,100,100,234,246,108,135,180,85,12,85,151,176,154,172,147,249,242,180,207,126,126,235,203,55,8,251,29,135,134,166,152,80,76,242,15,69,225,199,221,133,118,194,227,9,185,190,125,120,116,182,15,241,209,113,253,241,58,145,106,136,25,60,47,174,209,251,54,159,98,103,88,245,61,108,91,12,245,119,191,232,36)), 115)\nprint(116) assert(\"c57c742c772f92cce60cf3a1ddc263b8df0950f3\" == hmac_sha1(string.char(193,178,151,175,44,234,140,18,10,183,92,17,232,95,94,198,229,188,188,131,247,236,215,129,243,171,223,83,42,173,88,157,29,46,221,57,80,179,139,80), string.char(214,95,30,179,51,95,183,198,185,9,76,215,255,122,91,103,133,117,42,33,0,145,60,129,129,237,203,59,141,214,108,79,247,244,187,250,157,177,245,72,191,63,176,211)), 116)\nprint(117) assert(\"092336f7f1767874098a54d5f27092fbb92b7c94\" == hmac_sha1(string.char(208,10,217,108,72,232,56,67,6,179,160,172,29,67,115,171,118,82,124,118,61,111,21,132,209,92,212,166,181,129,43,55,198,96,169,112,86,212,68,214,81,239,122,216,104,73,114,209,60,182,248,118,74,100,26,1,176,3,166,188), string.char(42,4,235,56,198,119,175,244,93,77)), 117)\nprint(118) assert(\"c1d58ad2b611c4d9d59e339da7952bdae4a70737\" == hmac_sha1(string.char(100,129,37,207,188,116,232,140,204,90,90,93,124,132,140,81,102,156,67,254,228,192,150,161,10,62,143,218,237,111,151,98,78,168,188,87,170,190,35,228,169,228,143,252,213,85,11,124,92,91,18,27,122,141,98,6,77,106,205,209,2,185,249), string.char(58,190,56,255,176,80,220,228,0,251,108,108,220,197,51,131,164,162,60,181,21,54,122,174,31,13,4,84,198,203,105,11,64,230,1,30,218,208,252,219,44,147,2,108,227,66,49,71,21,95,248,93,193,180,165,240,224,226,13,9,208,186,12,118,243,28,113,49,122,192,212,164,43,41,151,183,187,126,115,85,174,40,125,9,54,193,164,95,21,77,200,226,50,115,187,122,34,141,255,224,239,12,132,191,48,102,205,248,128,164,116,48,39,191,98,53,169,230,249,215,231,152,45,27,226,10,143,15,209,157,208,181,15,210,195,5,29,48,29,125,62,59,191,216,170,179,226,110,40,46,32,130,235,48,234,233,17)), 118)\nprint(119) assert(\"3de84c915278a7d5e7d5629ec88193fb5bbadd15\" == hmac_sha1(string.char(89,175,111,33,154,12,173,230,28,117), string.char(188,233,41,180,142,157,96,76,105,212,92,202,155,167,179,28,12,156,64,73,32,253,253,166,9,240,7,0,248,43,101,135,226,231,173,221,180,43,160,217,6,38,183,186,214,217,137,83,148,148,40,141,217,98,209,12,167,102,95,166,136,231,232,84,59,112,148,201,166,104,135,124,189,85,160,183,143,122,200,190,144,205,25,254,180,188,108,225,171,131,240,185,86,243,192,173,130,50,150,57,242,180,132,193,11,110,247,121,25,24,110,199,156,121,233,149,79,103,15,173,184,143,45,125,164,242,125,10,183,189,189,135,121,59,148,106,77,9,16,123,176,100,142,246,156,180,202,87,43,102,113,123)), 119)\nprint(120) assert(\"e8cc5a50f80e7d52edd7ae4ec037414b70798598\" == hmac_sha1(string.char(139,243,17,238,11,156,138,122,212,86,201,213,100,167,65,199,92,182,255,36,221,82,192,213,199,162,69,42,222,95,65,170,146,48,39,185,147,18,140,122,168,141), string.char(141,216,25,29,235,207,123,188,85,53,131,180,125,226,97,244,250,138,64,39,30,250,146,101,219,171,213,158,164,172,137,22,136,86,46,77,95,213,66,198,15,24,164,148,29,166,169,195,196,111,122,147,247,215,148,9,129,40,133,178,69,242,171,235,181,83,241,208,237,17,37,30,188,152,47,214,69,229,114,225,75,172,163,184,38,158,230,177,187,124,33,240,238,148,197,235,237,98,33,237,59,205,147,128,108,254,95,5,6,49,10,224,78,139,164,235,220,78,224,15,213,136,198,217,114,156,130,247,167,64,36,10,183,221,193,220,195,80,125,143,248,228,254,6,221,137,170,211,66)), 120)\nprint(121) assert(\"80d9a0bc9600e6a0130681158a1787ef6b9c91d6\" == hmac_sha1(string.char(152,28,190,131,179,120,137,63,214,85,213,89,116,246,171,92,0,47,44,102,120,206,185,116,71,106,195), string.char(250,9,181,163,46,88,166,238,164,40,207,236,152,104,201,42,14,255,125,57,173,176,230,171,63,6,254,130,140,201,45,152,164,216,171,27,172,105,19,103,128,33,255,93,64,155,55,210,140,2,94,168,168,164,5,218,249,227,221,133,72,112,97,243,140,149,193,80)), 121)\nprint(122) assert(\"cb4182de586a30d606a057c948fe33733145790a\" == hmac_sha1(string.char(193,229,65,81,159,93,162,173,74,64,195,41,80,189,104,238,119,67,255,63,209,247,146,247,210,208,86,14,102,153,246,175,242,209,42,4,243,138,217,58,206,147,19,163,152,239,154,78,5,1,175,97,251,24,185,10,67,107,174,145,178,121,36,238,108,85,214,162,78,195,107,135,114,76,180,37,99,103,78,232,29,244,11,60,236,112,18,241,39,164,107,18), string.char(222,85,11,36,12,191,252,103,180,161,84,168,21,125,50,76,4,148,195,230,210,114,35,116,225,176,16,64,44,20,17,224,227,243,175,251,204,177,41,223,76,216,228,221,54,226,150,209,145,175,142,137,140,25,196,99,252,175,125,15,39,76,47,127,188,51,88,227,194,171,249,141,12,249,225,199,241,112,153,26,107,204,191,23,241,46,223,143,9,9,46,64,197,209,23,18,208,139,148,45,146,94,80,86,49,12,122,218,14,210,133,164,39,227,102,60,129,6,43)), 122)\nprint(123) assert(\"864e291ec69124c3a43976bae4ba1788f181f027\" == hmac_sha1(string.char(231,211,73,154,64,125,224,253,200,234,208,210,83,9), string.char(33,248,155,139,159,173,90,40,200,95,96,12,81,103,8,139,211,189,87,75,8,6,36,103,116,204,137,181,81,233,97,171,47,27,143,164,63,3,223,107,80,232,182,154,7,255,190,171,209,115,219,6,34,109,1,254,214,73,2)), 123)\nprint(124) assert(\"bee434914e65818f81bd07e4e0bbb58328be3ca1\" == hmac_sha1(string.char(222,123,148,175,157,117,104,212,169,13,252,113,231,104,37,8,147,119,92,27,100,132,250,105,63,13,195,90,251,122,185,97,159,68,36,7,75,163,179,3,6,170,164,152,86,30,49,239,201,245,43,220,78,62,154,206,95,24,149,138,138,15,24,68,58,255,99,88,143,192,12), string.char(97,76,73,171,140,99,57,217,56,73,182,189,58,19,177,104,85,85,45,31,170,132,53,51,155,143,70,169,189,5,41,231,34,132,235,228,114,58,100,105,146,27,67,89,32,34,78,133,155,222,88,26,83,198,128,183,19,243,27,186,192,77,184,54,142,57,24)), 124)\nprint(125) assert(\"0268f79ef55c3651a66a64a21f47495c5beeb212\" == hmac_sha1(string.char(181,166,229,31,47,25,64,129,95,242,221,96,73,42,243,170,15,33,14,198,78,194,235,139,177,112,191,190,52,224,93,95,107,125,245,17,170,161,53,148,19,180,83,154,45,98,76,170,51,178,114,71,34,242,184,75,1,130,199,40,197,88,203,86,169,109,206,67,86,175,201,135,101,76,130,144,248,80,212,14,119,186), string.char(53,208,22,216,93,88,59,64,135,112,49,253,34,11,210,160,117,40,219,36,226,45,207,163,134,133,199,101)), 125)\nprint(126) assert(\"bcb2473c745d7dee1ec17207d1d804d401828035\" == hmac_sha1(string.char(143,117,182,35), string.char(110,95,240,139,124,96,238,255,165,146,205,18,155,244,252,176,24,19,253,39,33,248,90,95,34,115,70,63,195,91,124,144,243,91,110,80,173,47,46,231,73,228,207,37,183,28,42,144,66,248,178,255,129,52,55,232,1,33,193,185,184,237,8)), 126)\nprint(127) assert(\"402ed75be595f59519e3dd52323817a65e9ff95b\" == hmac_sha1(string.char(247,77,247,124,27,156,148,227,12,21,17,94,56,14,118,47,140,239,200,249,216,139,7,172,16,211,237,94,62,201,227,42,250,8,179,21,39,85,186,145,147,106,127,67,111,250,163,89,152,115,166,254,8,246,141,238,43,45,194,131,191,202), string.char(138,227,90,40,221,37,181,54,26,20,24,125,19,101,12,120,111,20,104,10,225,140,64,218,8,33,179,95,215,142,203,127,243,231,166,76,234,159,59,160,132,56,215,143,103,75,155,158,56,126,71,252,229,54,34,240,30,133,110,67,146,213,116,73,14,160,186,169,155,196,84,132,171,200,171,56,92,38,136,90,57,155,145,67,190,198,235,112,242,120,150,191,216,41,21,36,205,42,68,145,226,246,178,70,60,157,254,206,70,84,189,36,197,48,208,249,144,223,6,72,17,253,236,106,205,245,30,1,80,121,165,103,12,202,115,227,192,64,42,223,113,200,195,156,120,202,110,131,130,39,64,217,108,23,133,140,56,144,167,77,45,236,145,161,150,229,85,231,203,159,203,85,125,221,226)), 127)\nprint(128) assert(\"20231b6abcdd7e5d5e22f83706652acf1ae5255e\" == hmac_sha1(string.char(132,122,252,170,107,28,195,210,121,194,245,252,42,64,42,103,220,18,61,68,19,78,182,234,93,130,175,20,4,199,66,91,247,247,87,107,89,205,68,125,19,254,59,47,228,134,200,145,148,78,52,236,51,255,152,231,47,168,213,124,228,34,48), string.char(61,232,69,199,207,49,72,159,37,230,105,207,63,141,245,127,142,77,168,111,126,92,145,26,202,215,116,19,125,81,203,11,86,36,19,218,90,255,4,10,21,185,151,111,188,125,123,2,137,151,171,178,195,199,106,55,42,42,20,164,35,177,237,41,207,24,102,218,213,223,204,186,212,30,59,121,52,34,84,76,142,179,75,6,84,8,72,210,72,177,45,103,218,70,165,69,36,152,50,228,147,192,61,104,209,76,155,147,169,162,151,178,72,109,241,41,76,0,60,251,107,99,92,37,95,215,172,154,172,93,254,65,176,43,99,242,151,78,48,58,35,49,23,174,115,224,227,106,49,30,9)), 128)\nprint(129) assert(\"b5a24d7aadc1e8fb71f914e1fa581085a8114b27\" == hmac_sha1(string.char(233,21,254,12,70,129,236,10,187,36,119,197,152,242,131,11,10,243,169,217,128,247,196,111,183,109,146,155,92,91,71,83,0,136,109,1,130,143,0,8,6,22,160,153,190,164,199,56,152,229), string.char(152,112,218,132,38,125,94,106,64,9,137,105)), 129)\nprint(130) assert(\"7fd9169b441711bef04ea08ed87b1cd8f245aeb2\" == hmac_sha1(string.char(108,226,105,159), string.char(103,218,254,85,50,58,111,74,108,60,174,27,113,65,100,217,97,208,125,38,170,151,72,125,82,114,185,58,4,143,39,223,250,168,66,182,37,216,130,111,103,157,59,0,245,222,8,65,240)), 130)\nprint(131) assert(\"98038102f8476b28dd11b535b6c1b93eb8089360\" == hmac_sha1(string.char(77,121,52,138,71,149,161,87,106,75,232,247,8,148,175,24,23,60,151,104,176,208,148,227,226,191,73,123,164,36,177,235,101,190,128,202,139,116,201,125,61,41,204,187,48,107,63,231,12,137,11,228,93,136,178,243,90), string.char(90,6,232,110,12,66,45,86,141,121,2,6,177,135,64,208,45,178,129,37,253,246,74,48,71,211,243,121,31,209,138,147,185,141,65,185,245,9,137,134,148,123,181,128,204,74,222,150,239,169,179,36,236,104,147,255,251,204,5,191,198,185,153,195,26,112,179,170,232,101,238,143,143)), 131)\nprint(132) assert(\"ba43c9b8e98b4b7176a1bb63fcbed5b004dc4fcd\" == hmac_sha1(string.char(133,107,178,183,204,2,203,106,242,180,87,58,134), string.char(211,208,255,34,198,99,119,185,171,52,118,94,65,241,45,24,40,6,2,203,126,216,21,51,245,154,92,198,201,220,190,135,182,137,113,68,250,94,126,233,140,94,118,244,244,98,252,97,217,204,239,218,178,240,65,150,246,217,231,142,157,33,113,135,135,214,137,103,211,213,48,132,171,43,96,51,241,45,42,237,53,247,134,102,163,214,96,147,131,74,180,19,7,12,174,60,37,60,78,85,92,186,121,27,234,128,132,64,47,106,127,218,52,30,59,230,85,240,164,54,168,232,131,110,145,125,255,238,145,237,134,196,197,138,105,74,34,134,29,249,222,119,194,104,230)), 132)\nprint(133) assert(\"0c1ad0332f0c6c1f61e6cc86f0a343065635ecb3\" == hmac_sha1(string.char(230,111,251,74,216,102,12,134,90,44,121,175,56,221,225,235,180,246,56,12,236,119,119,109,97,59,224,121,27,37,72,219,138,193,50,219,193,152,1,229,224,197,233,76,188,62,120,17,63,158,186,198,87,135,34,60,164,139,3,200,20,188,203,110,212,137,91,70,35,255,146,213,216,71,73,143,55,219,54,142,105,83,175,193,32,226,150,51,59), string.char(185,250,11,8,121,214,91,27,1,50,67,204,219,252,212,198,117,234,57,127,214,12,220,104,44,177,225,238,103,138,144,162,28,69,143,108,192,4,160,63,175,185,123,46,151,221,127,145,55,32,85,245,251,178,125,223,107,192,206,207,232,231,190,44,221,173,1,59,12,178,112,22,253,222,14,40,18,141,128,144,196,6,112,206,183,144,215,156,159,79,132,152,170,22,68,106,137,248,12,242,231,98,96,144,148,20,212,30,242,109,36,112,50,51,57,212,181,191,80,73,215,119,244,209,57,108,147,182,67,204,154,48,216,116)), 133)\nprint(134) assert(\"466442888b6989fd380f918d0476a16ae26279cf\" == hmac_sha1(string.char(250,60,248,215,154,159,2,121), string.char(236,249,8,10,180,146,36,144,83,196,49,166,17,81,51,72,28)), 134)\nprint(135) assert(\"f9febfeda402b930ec1b95c1325788305cb9fde8\" == hmac_sha1(string.char(124,195,165,216,158,253,119,86,162,36,185,72,162,141,160,225,183,25,54,123,73,61,40,165,101,154,157,200,113,14,117,144,185,64,236,219,3,87,90,49), string.char(73,1,223,35,5,159,39,85,95,170,227,61,14,227,142,222,255,253,152,123,104,35,229,6,195,106,30,59,5,36,2,173,71,161,217,189,47,193,3,216,34,10,25,30,212,255,141,94,25,72,52,58,50,56,180,99,173,155)), 135)\nprint(136) assert(\"53fe70b7e825d017ef0bdecbacdda4e8a76cbc6f\" == hmac_sha1(string.char(144,144,130,150,207,183,143,100,188,177,90,5,4,95,116,105,252,118,187,251,35,113,251,86,36,234,176,165,55,165,158,4,182,85,62,255,18,146,128,67,221,183,78,71,158,184,140,14,84,44,36,79,244,158,37,1,122,43,103,228,217,253,72,113,228,121,160,29,87,5,158,64,38,253,179,122,187,157,106,99,161,79,97,176,119,86,101,40,142,241,217,85), string.char(12,89,157,112,207,206,171,254,87,106,42,113,70,72,222,239,88,94,14,41,14,175,206,56,219,244,230,40,33,154,107,249,45,70,55,104,151,193,246,133,99,59,244,179,8,145,225,100,146,142,128,74,40,155,99,93,204,253,249,222,64,99,156,121,142,49,166,62,171,223,135,55,212,183,144,218,56,12,211,99,254,58,249,219,197,189,173,141,60,196,241,157,67,151,251,172,49,105,200,88,224,175,9,79,65,40,5,255,222,14,152,149,228,83,154,207,104,132,106,96,40,229,182,120,100,207,223,81,171,141,1,171)), 136)\nprint(137) assert(\"81b1df7265954a8aee4e119800169660ff9e75c8\" == hmac_sha1(string.char(232,167,4,53,90,111,79,91,163,125,230,202,52,242,160,135,66,211,246,17,131,109,109,235,91), string.char(111,177,251,180,63,13,33,205,231,130,203,167,177,156,87,70,33,148,229,163,158,224,123,37,18,204,185,89,235,2,30,252,229,202,170,157,175,157,208,254,135,190,34,14,42,211,154,243,31,100,71,53,169,76,36)), 137)\nprint(138) assert(\"caf986508402b3feb70c5b44d902f4a9428a44d2\" == hmac_sha1(string.char(127,2,162,53,6,172,189,169,176,254,107,46,57,207,23,25,182,72,34,228,164,113,12,179,149,45,169,19,3,204,202,10,126,153,130,41,143,200,198,47,215,15,58,124,225,60,171,98,8,211,72,235,211,187,172,37,119,96,55,243,98,198,225,191,79,207,94,215,255,21,101,128,153,233,88,101,57,195,70,194), string.char(97,24,129,203,10,176,242,39,165,95,51,30,187,106,207,160,18,154,16,130,178,80,206,128,148,56,213,55,46,85,76,100,50,131,41,167,130,12,81,161,158,55,181,12,12,38,89,193,136,220,81,114,191,157,20,221,171,245)), 138)\nprint(139) assert(\"83bd91a9e8072010f3b54d215c56ada0cd810bb6\" == hmac_sha1(string.char(215,33,57,193,51,126,38,114,7,29,93,101,78,152,222,121,42,0,236,169,48,137,202,48,90,249,235,46,44,126,78,251,15,84,200,235,43,108,8,196,210,57,152,86,254), string.char(153,35,68,230,52,95,243,220,32,101,148,76,80,168,187,172,170,254,10,70,31,117,40,131,61,155,200,189,25,198,120,41,181,53,14,175,64,89,126,94,242,61,52,1,188,255,121,254,74,88,19,10,126,225,89,31,21,104,199,82,149,60,110,194,123,236,13,38,7,213,176,182,202,211,178,185,99,8,173,220,168,166,108,208,71,152,174,5,134,167,220,47,74,177,231,90,114,208,168,47,112,74,58,73,94,224,101,64,128,255,186,179,119,159,117,110,2,188,38,73,230,39,50,73,162,22,117,185,182,168,70,252,11,242,243,165,32,104,220,211)), 139)\nprint(140) assert(\"c123d92ee67689922dfb3b68a45584e7e5dc5dc3\" == hmac_sha1(string.char(167,32,181,181,249,210), string.char(249,7,96,196,48,157,109,129,192,227,82,84,196,167,224,145,61,177,60,74,217,117,199,147,147,54,198,138,5,51,135,112,29,184,49,16,0,240,172,21,214,114,146,57,2,154,205,60,113,32,113,255,165,5,178,15,159)), 140)\nprint(141) assert(\"454d9ba00ac4e0e90a2866ba2abefba40dac9aab\" == hmac_sha1(string.char(116,2,170,84,236,37), string.char(219,144,86,39,237,166,110,90,213,70)), 141)\nprint(142) assert(\"e919cce3908786205511fee0283e1eb41c0c45a1\" == hmac_sha1(string.char(180,76,140,201,56,232,48,183,173,36,111,94,208,153,234,255,52,18,121,118,117,77,92,74,241,103,193,164,169,1,60,46,101,73,61,221,26,253,209,124,99,154,177,218,59,238,159,191,0,65,117,78,15,12,92,35,254,40,11,112,112,91,49,248,198,229,161,247,130,170,76,146,8,220,134,96,155,68,50,168,186,135,188,186,36), string.char(26,47,201,201,197,232,196,239,204,197,162,14,53,254,88,75,43,254,11,20,52,61,136,206,162,29,223,55,125,50,200,239,135,51,154,54,78,191,188,0,137,191,149,162,191,103,0,168,52,178,147,251,253,86,98,17,15,202,231,0,122,10,131,25,15,129,48,190,60,205,185,114,193,122,19,47,52,142,124,107,45,174,221,196,18,32,79,12,129,84,40)), 142)\nprint(143) assert(\"fa770f6b76984edb0f7fa514a19d3c7ef9c82c51\" == hmac_sha1(string.char(70,55,200,82,238,241,84,180,129,122,103,199,170,177), string.char(88,236,14,60,249,2,197,242,76,152,248,241,158,232,113,242,209,93,232,113,147,210,80,180,44,124,186,150,172,177,138,131,117,151,174,231,93,248,244,200,191,169,159,206,232,246,2,121,106,183,107,79,210,73,145,244,254,248,85,217,156,221,238,120,224,176,31,56,246,26,3,186,189,86,41,17,34,8,208,58,46,130,226,139,209,194,3,34,55,213,154,12,250,229,201,122,89,47,177,229,80,165,183,77,178,139,3,241,165,196,239,93,98,101,99,210,99,5,135,132,151,197,4,154,87,130,145,175,243,238,132,0,146,14,6,205,227,78,150,59,191,223,74,145,57,82,30,223,90,205,248,47,195,220,215,167,112,216,20,130,26,88,170,101,26,14,216,62,169,217,1,135,193,147,218)), 143)\nprint(144) assert(\"d3418e6e6d0a96f8ea7c511273423651a63590c8\" == hmac_sha1(string.char(61,175,211,89,77,91,143,76,18,30,252,16,181,45,211,37,207,204,174,174,60,208,36,85,23,106,141,215,62,8,158,98,209,49,96,143,129,99,11,159,79,116,98,244,51,237,227,250,73,196,36,216,181,157,159,87,248,108,29,22,181,175,72,92,160,127,46,204,202,175,61,108,172,50,225,48,84,167,116,67,183), string.char(174,62,218,81,85,89,4,35,26)), 144)\nprint(145) assert(\"f2fbe13b442bff3c09dcdaeaf375cb2f5214f821\" == hmac_sha1(string.char(188,80,129,208,85,53,8,122,92,99,56,251,59,108,97,145,1,97,157,181,156,243,30,204,227,88,205,151), string.char(137,30,19,71,50,239,11,212,91,234,79,248,244,118,108,245,251,78,53,136,249,55,210,231,109,207,153,83,10,63,98,225,79,113,124,64,100,16,195,9,136,28,50,215,93,93,153,25,97,77,4,13,46,34,164,59,33,206,62,125,8,79,219,42,155,39,241,96,18)), 145)\nprint(146) assert(\"aeacb03e8284a01b93e51e483df58a9492035668\" == hmac_sha1(string.char(62,67,97,44,112,68,107,91,105,4,183,154,9,14,164,180,87,140,195,231,62,49,250,154,193,186,219,18,100,156,176,124,223,164,68,64,105,214,144,200,65), string.char(221,20,36,192,59,234,90,174,232,184,75,15,92,229,59,191,36,51,4,190,226,35,237,189,21,100,135,138,171,202,163,227,176,231,72,185,43,197,134,157,44,86,26,42,230,251,2,124,220,245,242,116,77,35,197,154,237,73,117,131,126,242,167,242,8,72,163,171,60,29,77,152,142,69,25,234,195,2,159,49,178,63,48,56,131,143,165,22,142,116,109,11,57,71,101,99,84,204,56,233,173,65,180,228,211,10,197,204,26,70,198,81,217,83,130,70,79,54,93,96,116,32,21,219,193,70,55,84,161,89,47,206,13,167,46,104,205,218)), 146)\nprint(147) assert(\"e163c334e08bd3fa537c1ea309ce99cfbcd97930\" == hmac_sha1(string.char(238,187,29,13,100,125,10,129,46,251,49,62,207,74,243,25,25,73,196,100,114,64,141,173,143,144,70,13,162,227,33,255,83,58,254,138,23,146,90,86,17,33,152,227,15,100,200,147,81,114,166,234,47,60,70,190,208,28,16,44,71,150,101,197,182,57,143,79,29,135,45,211,194,62,234,28,244,74,56,104,187,94,146,174,190,198,55,143,134,60,186,144,190,100,102,0,171,151), string.char(177,90,20,162,64,145,130,87,137,70,153,237,51,138,248,29,166,134,168,68,133,121,161,26,228,137,145,116,243,224,201,229,61,107,250,198,214,208,72,169,248,155,247,54,163,167,71,248,69,106,105,139,224,138,85,94,31,143,4,215,83,239,21,198,28,1,120,83,91,92,58,150,110,77,111,166,222,236,170,129,2,121,86,66,42,129,146,232,46,248,136,175,130,118,126,205,184,136,6,35,180,174,194,59,89,243,199,38,97,48,80,98,45,111)), 147)\nprint(148) assert(\"6a82b3a54ed409f612a934caf96e6c4799286f19\" == hmac_sha1(string.char(11,59,108,100,113,56,239,211,2,138,219,101,50,50,111,31,171,212,228,55,89,196,44,158,77,252,212,134,106,7,250,223,219,46,231,87,9,62,213,104,169,49,1,75,3,10,50,238,5,150,47,14,47,45,171,183,40,245,194,249,228,216,85), string.char(97,131,91,189,9,52,88,203,250,245,46,96,7,95,176,61,57,192,91,231,193,32,41,169,96,101,39,240,29,143,24,56,57,177,70,135,225,90,42,192,134,103,239,175,243,246,76,137,14,237,82,215,7,76,246,219,132,50,175,25,164,4,216,65,102,0,114,216,159,80,58,32,4,100,22,35,71,140,49,16,216,182,91,80,181,129,151,55,130,7,77,84,211,111,45,51,192,123,213,192,11,81,138,60,225,21,37,182,180,223,170,163,110,9,47,214,200,249,164,98,215)), 148)\nprint(149) assert(\"79caa9946fcf0ccdd882bc409abe77d3470d28f7\" == hmac_sha1(string.char(202,142,21,201,45,72,11,211,67,134,42,192,96,255,210,211,252,6,101,131,25,195,101,76,250,161,148,242,30,129,241,85,68,173,236,140,120,80,71,62,55,4,33,104,52,160,143,118,252,72), string.char(100,188,93,165,75,34,224,223,6,130,52,160,83,157,253,27,200,125,117,249,41,203,19,242,4,188,209,213,211,20,162,252,215,238,221,30,219,252,246,110,117,77,89,204,221,246,69,62,160,186,37,144,43,151,39,133,254,134,24,223)), 149)\nprint(150) assert(\"bd1e60a3df42e2687746766d7d67d57e262f3c9b\" == hmac_sha1(string.char(57,212,172,224,206,230,13,50,80,54,19,87,147,166,245,67,118,37,101,214,207,60,66,29,197,236,146,140,192,15,36,155,108,121,215,211,210,118,22,20,56,245,42,153,150,32,224,201,171,2,238,41,70,140,73,60,215,243,86,20,169,152,220,104,95,215,187), string.char(245,123,43,109,29,108,197,27,55,167,255,177,226,205,111,126,146,75,93,70,180,90,139,218,243,232,221,247,129,77,115,101,144,42,13,249,223,127,200,213,140,113,23,10,149,107,244,86,41,133,147,26,167,85,189,76,176,12,190,52,90,54,78,29,97,204,161,224,59,243,128,64,133,95,192,19,137,220,96,228,97,161,51,21,157,172,127,76,53,38,83,126,178,26,203,206,165,241,101,130,79,122,75,29,205,240,1,68,222,48,101,7,29,6,82,240,133,112)), 150)\nprint(151) assert(\"fe249fa66eb1e6228e1e5166d7862d119ffa0dcf\" == hmac_sha1(string.char(152,13,170,129,7,65,32,194,85,196,85,12,170,227,139,215,70,137,246,105,100,111,252,221,54,174,90,169,59,11,198,33,110,94,246,195,174,13,212,47,18,94,17,67,68,56,251,213,92,67,243,114,181,166,24,182,238,146,48,196,11,238,91,213,46,184,187,199,15,221,193,36,73,244,30,222,175,132,165,177,162,54,215,130,171,58,26,144,218,62,172,120,188,20,182,242,47,178,120,175), string.char(129,126,32,58,251,104,186,25,18,204,5,240,65,194,32,205,194,18,151,173,185,249,237,55,145,8,41,18,171,28,59,234,62,163,32,173,197,176,206,224,95,176,218,168,183,82,53,172,205,6,223,190,189,16,3,34,212,201,54,152,89,231,194,95,8,238,133,56,139,157,115,35,74,58,21,162,111,36,105,135,151,30,207,33,198,186,122,221,98,36,196,251,27)), 151)\nprint(152) assert(\"88aef9bb450b75bf96e8b5fd7831ed0d16d7fe7a\" == hmac_sha1(string.char(162,225,9,204,87,95,132,152,211,133,93,120,105,156,131,55,245,224,33,115,182,10,28,49,80,175,241,67,66,52,21,55,174,108,66,100,77,20), string.char(55,61,250,187,157,98,212,245,5,54,170,60,235,228,197,182,230,24,195,215,202,55,56,153,9,94,164,107,67,93,143,1,235,195,133,201,103,57,130,177,71,73,169,80,21,251,130,247,21,61,228,39,166,173,211,203,149,55,11,224,70,52,248,118,112,219,39,188,147,5,203,101,158,134,53,250,103,73,154,249,71,181,53,171,227,26,79,200,145,178,24,80,102,26,90,101,70,143,233,17,150,181,170)), 152)\nprint(153) assert(\"a057dd823478540bbe9a6fcdf2d4dcfcac663545\" == hmac_sha1(string.char(83,17,204,150,211,96,88,52,225,90,61,59,28,127,135), string.char(49,226,129,162,111,75,221,186,24,219,219,178,226,132,19,126,192,69,124,114,214,31,7,127,194,134,202,147,45,176,215,141,41,94,69,38,199,231,185,223,10,104,108,50,237,20,76,194,33,43,117,117,176,3,117,117,55,68,112,207,74,72,163)), 153)\nprint(154) assert(\"b11757ccfafc8feadc4e9402c820f4903f20032b\" == hmac_sha1(string.char(34,11,53,219), string.char(225,194,251,106,223,229,212,105,164,172,25,25,224,199,225,172,197,42,167,1,227,165,17,247,75,250,10,208,99,124,254,158,103,74,89,60,78,141,201,44,253,87,248,239,74,86,75,64,249,189,21,170,249,18,139,21,130,226,66,200,231,35,227,147,95,213,133,35,47,236,52,64,122,115,80,170,27,50,182,151,180,106,120,85,103,255,143,27,233,43,217,152,70,82,8,229,103,42,153,38,130,184,108,160,199,69,38,184)), 154)\nprint(155) assert(\"bfd0994350b2e1e0d6a1faed059f67f1dd8b361f\" == hmac_sha1(string.char(221,156,128,63,215,109,55,123,41,27,110,127,209,144,178,143,120,12,226,47,56,212,131,228,3,40,186,208,233,135,33,206,92,214,153,77,12,220,72,240,176,53,22,37,130,58,180,4,111,124,135,31,192,71,117,87,11,41,231,101,37,164,112,3,55,141,250,131,191,117,90,159,224,244,9,251,154), string.char(35,88,113,69,231,5,150,40,123,13,197,27,49,72,161,1,212,222,252,74,197,170,137,72,231,245,117,236,29,12,36,59,225,103,44,119,136,34,241,17,142,239,46,152,129,163,107,17,165,112,187,15,122,217,67,13,215,157,212,26,103,226,237,161,213,3,152,88,247,236,130,133,84,200,132,191,166,8,96,247,4,142,14,81,179,64,88,202,156,242,181,95,162,19,97,223,51,76,176,218,22,116,24,238,204,128,241,236,204,2,56,86,77,211,4,52,221,82,94,76,9,21,182,112,199,161,29,39,183,120,13,0,124,136,95,182,241,3,73,167,51,237,152,149,84,147,41,42,241,174,12,30,226,245,139,230,127,34,205,41,166,228,242,105,251,4,150,29,106,42,27,239,89,249,230,246,242,149,4,60,240,93,13,166,102,239,81,216,137,196)), 155)\nprint(156) assert(\"15c4527be05987a9b5c33b920be4a4402f7cf941\" == hmac_sha1(string.char(132,158,227,135,167,32,19,192,144,48,232,68,79,78,135,122,136,140,97,67,34,91,225,48,126,67,77,115,154,189,13,45,8,234,59,233,245,77,34,76,95,78,3,250,179,224,20,25,6,202,214,115,165,230,85,115,250,236,135,34,32,158,196,45,207,61,71,51,93,27,187,232,175,233,147,68,231,110,12,198,233,165,24,209,206,25,16,252,127,72), string.char(210,162,121,23,181,21,75,54,110,47,15,166,133,206,100,217,57,133,228,32,112,208,186,28,140,8,207,74,185,17,128,29,181,172,20,156,64,192,112,8,207,131,53,10,182,147,224,71,218,94,71,86,215,2,133,46,160,27,51,189,38,130,224,120,185,144,253,117,193,24,154,229,247,132,62,103,65,163,106,172,22,5,2,32,129,38,213,118,110,125,156,14,48,240,170,225,158,89,92,190,254,231,51,220,8,174,188,233,226,106,224,99,218,82,64,219,206,75,166,111,25,7,87,248,145,251,109,106,243,241,89,200,85,184,155,183,249,61,70,87,115,182,81,80,155,24,245,123,184,102,214,255,122,83,61,214,88,235,169,28,147,196,247,97,28,82,193,72,71,96,243,176,35,189,236,44,184,52,151,249,186,189,150,184,142,238,88,113,120,68,234,50,136,104,80,145,179,57,6,186)), 156)\nprint(157) assert(\"b9f87f5f23583bdd21b1ea18e7e647513b7b0596\" == hmac_sha1(string.char(216,79,247,98,215,219,128,232,135,111,179,168,80,76,36,250,224,157,229,209,238,186,212,188,200,52,208,200,210,79,182,186,22,22,37,34,86,107,89,238,168,90,53,30,151,191,89,163,253,24,204,152,118,1,158,25,168,2,123,91,111,39,101,239,247,37,200,51,215,31,146,211,163,136,208), string.char(153,134,211,81,255,219,50,91,67,48,102,63,244,170,129,66,3,151,110,167,142,150,153,95,89,90,23,87,12,85,42,209,197,36,41,189,199,136,196,159,125,53,253,192,135,234,94,34,87,79,143,213,237,149,212,170,231,181,22,72,81,233,151,243,134,71,160,155,121,32,233,251,187,179,139,48,254,206,172,165,202,105,222,31,223,95,203,87,114,52,218,59,187,41,43,135,200,108,102,201,85,199,8,176,249,44,96,104,160,85,149,177,25,88,55,231,85,120,227,6,180,24)), 157)\nprint(158) assert(\"0b586895674ab11d3b395c07ddb01151a6e562f5\" == hmac_sha1(string.char(26,110,222,147,168,18,74,206,186,238,154,250,229,207,138,175,126,82,236,148,74,180,27,168,159,89,211,34,39,115,227,239,22,199,252,96,100,16,193,117,111,102,75,70,2,114,214,196,29,26,43,189,183,0,194,217,204), string.char(90,15,17,198,223,30,20,138,203,132,6,170,107,40,167,58,194,212,244,49,174,60,209,164,26,87,174,177,41,166,95,173,40,61,47,136,147,239,125,167,146,180,97,167,33,185,5,110,128,36,61,52,140,20,189,16,216,83,164,46,74,16,251,250,72,50,47,5,86,60,56,77,101,64,11,120,124,194,212,199,136,87,157,160,90,172,101,222,235,23,111,11,36,11,68,20,43,251,65,212,206,150,0,50,146,170,183,93,89,142,161,50,110,237,95,191,22,184,62,194,81)), 158)\nprint(159) assert(\"38b25a1d9d927ba5e6b294d2aa69c0ab8ab0a0c5\" == hmac_sha1(string.char(93,218,103,160,235,71,107,150,18,170,193,9,63,245,77,150,71,242,137,52,243,12,207,183,222,252,20,215,210,194,241,79), string.char(87,97,35,201,134,196,180)), 159)\nprint(160) assert(\"a72ce76565c2876e78f86ce9e137a9881328fddc\" == hmac_sha1(string.char(48,215,222,182,164,136,31,53,160,28,61,171,220,159,243,154,169,101,191,193,99,28,140,59,60,215,77,170,51,136,50,145,159,135,237,149,83,154,219,223,29,200,85,193,173,201,66,142,100,21,89,144,111,5,24,229,228,154,160,32,210,71,19,63,244,230,61,185,221,158,151,51), string.char(196,237,178,172,24,232,144,251,253,31,8,63,69,58,202,88,120,219,39,34,223,173,196,164,135,93,188,69,126,58,153,37,72,219,50,152,76,235,244,223,205,60,74,12,109,203,134,239,40,181,207,99,118,149,179,84,14,53,189,201,55,110,67,81,116,140,31,247,163,135,53,254,82,230,55,162,255,230,149,144,217,62,164,59,124,59,78,177,115,47,26,169,228,18,167,232,89,161,56,105,127,111,230,93,230,181,222,212,254,85,32,117,140,80,246,117,21,140,221,198,11,196,112,69,122,125,156)), 160)\nprint(161) assert(\"cd324faf8204be01296bea85a22d991533fd353e\" == hmac_sha1(string.char(25,136,140,2,222,149,164,20,148,15,90,33,106,111,10,252,67,120,57,49,251,171,99,173,114,16,102,240,206,188,231,174,51,124,38,1,217,142,4,15,78,4,5,128,207,82), string.char(84,0,42,233,157,150,105,1,216,32,170,11,100,98,103,220,137,102,32,185,55,211,207,179,252,190,248,117,253,189,196,71,112,32,4,198,87,5,133,125,238,107,210,227,149,206,12,124,31,59,213,66,105,100,240,237,149,232,174,140,127,9,65,204,162,243,100,120,6,229,71,56,140,128,228,102,121,14,43,166,252,230,172,93,96,25,214,174,151,2,50,64,152,164,132,115,109,176,25,144,171,252,231,72)), 161)\nprint(162) assert(\"fb6e40ddbf3df49d4b44ccecf9e9bc74567df49e\" == hmac_sha1(string.char(31,41,38,118,207,197,83,231,45,187,105,1,246,6,34,16,214,148,97,64,139,27,73,129,71,129,183,182,228,12,74,242,94,43,121,163,188,242,92,43,154,103,20,208,89,213,63,46,81,60,69,217,238,237,97,18), string.char(126,99,64,121,143,219,76,227,119,32,135,246,48,55,214,38,179,255,33,43,32,140,228,44,218,40,187,117,172,131,225,222,72,61,213,132,167,121,190,167,66,213,199,59,212,61,69,242,46,169,89,191,74,0,228,208,46,112,7,81,88,203,95,180,179,75,116,222,115,239,1,132,178,73,139,252,77,1,151,222,108,84,196,161,79,220,80,44,223,44,131,252,58,28,201,3,77,211,33,208,237,47,251,79,134,223,48,8,0,236,139,11,232,186,188,134,249,29,208,154,137,169,218,228,203,254,106,88,35,252,155,111,119,14,147,161,19,60,145,157,120,236,108,122,218,168,105,59,10,44,99,208,86)), 162)\nprint(163) assert(\"373f21bf8fe4e855f882cc976ebed31717f4c791\" == hmac_sha1(string.char(198,41,45,129,159,48,37,183,170,144,24,223,108,176,68,60,197,245,254,165,24,152,14,25,243,46,6,25,142,99,64,10,145,229,74,232,162,201,72,215,116,26,179,127,107,45,193,232,96,170,168,153,79,47), string.char(79,250,224,177,254,56,111,120,135,79,55,200,199,71,65,132,222,7,106,170,26,179,235,237,47,172,88,28,244,88,137,177,92,178,147,129,147,85,88,157,30,207,235,246,132,98,232,18,201,57,151,90,174,148,126,22,38,118,133,49,83,156,56,195,10,95,180,250,215,220,251,5,131,243,70,2,162,239,197,153,196,28,181,167,26,14,247,86,244,69,190,100,255,158,217,222,58,116,126,245,240,139,255,213,7,28,222,99,12,127,57,2,212,33,136,220,203,251,87,205,213,160,146,162,73,55,112,203,60,243,139,167,45,91,68,62,204,245,206,221,52,253,5,193,69,19,190,131,64,250,12,127,77,212,53,83,102,212,11,215,253,143,111,201)), 163)\nprint(164) assert(\"df709285c8a1917aaa6d570bd1d4225ca916b110\" == hmac_sha1(string.char(193,124,34,185,160,71,134,56,178,152,165,219,223,89,174,116,11,237), string.char(47,110,24,9,42,187,179,71,114,43,155,129,158,24,130,32,208,3,46,63,16,1,192,210,72,220,200,89,120,80,82,65,199,119,167,86,57,33,105,118,215,60,18,155,17,154,63,59,189,153,236,78,219,89,4,116,208,122,56,65,253,220,57,147,162,242,193,86,45,145,151,61,30,138,105,139,99,89)), 164)\nprint(165) assert(\"66be81c24c87feeecfd805872c6cde41cb1dd732\" == hmac_sha1(string.char(128,186,31,231,128,48,206,237,59), string.char(56,228,42,58,98,45,202,132,30,78,80,52,36,128,7,55,209,148,181,52,185,220,137,85,111,128,220,109,55,70,185,242,253,155,165,193,240,63,144,253,240,147,18,161,7,46,40,148,201,0,127,1,33,145,180,247,90,206,178,96,62,137,130,99,248,248,227,135,213,21,230,40,88,162,106,240,218,93,226,108,9,121,173,70,255,106,137,222,135,206,104,153,171,1,52,156,166,27,98,7,74,180,206,11,193,129,77,194,86,224,175,79,77,95,134,62,58,252,180,100,191,53,28,59,121,123,146,107,121,249,168,51,204,170,141,26,84,126,38,77,203,11,58,123,155,167,60,176,151,7,39,75,217,254,32,110,79,123,188,133,158,178,132,198,169,23,5,104,124,44,206,191,239,139,152,110,207,42)), 165)\nprint(166) assert(\"2d1dd80c3f0fc323ca46ebd0f73c628caa03f88b\" == hmac_sha1(string.char(142,87,50,47,146,180,251,164,35,75,53,50,101,115,90,97,66,12), string.char(174,244,41,143,173,27,117,79,53,73,0,189,83,91,13,71,117,85,96,32,199,168,244,72,218,249,207,107,244,1,113,203,160,156,89,244,132,5,4,220,254,112,77,156,158,105,180,98,40,99,198,236,134,209,13,237,93,220,177,70,97,76,178,106,60,60,92,248)), 166)\nprint(167) assert(\"444ef9725523ad1aac3d1c20f4954cdf1550d706\" == hmac_sha1(string.char(242,169,63,243,133,158,118,205,250,154,66,127,178,170,214,241,96,22,173,138,6,189,90,45,108,70,236,108,93,58,54,204,85,241,194,55,55,184), string.char(30,52,200,164,245,80,75)), 167)\nprint(168) assert(\"2170bcfb79e4ab2164287a30ee26535681e34505\" == hmac_sha1(string.char(121,111,11,221,34,216,169,179,73,247,222,122,96,168,61,168,201,230,139,158,110,154,74,83,118,254,237,255,99,212,46,218,83,69,185,10,249,78,46,76,206,206,137,133,118,57,241,114,228,54,51,68,71,224,188,188,0,119,173,94,120,1,25,13,237,4,181,170,222,92,106,28,9,111,128,137,228,2,110,4,137,171,219,70), string.char(108,95,232,156,70,235,149,211,52,84,86,25,251,127,119,231,109,144,54,177,96,118,213,3,8,119,95,192,187,221,115,83,67,39,207,82,215,85,156,198,179,246,177,202,115,103,79,97,222,133,113,201,27,92,185,48,227,223,142,96,143,181,175,238,115,112,29,30,126,59,109,252,136,153,28,112,50,138,155,249,223,114,93,107,122,114,163,226,53,219,44,15,172,233,76,98,175,107,246,181,249,112,230,173,152,211,183,120,227,165,187,10,240,94)), 168)\nprint(169) assert(\"2bcd1eb6df83aed8bcdfbb36474651f466b1fb22\" == hmac_sha1(string.char(178,135,218,237,192,188,60,157,46,65,76,100,66,248,152,23,200,194,67,107,95,127,67,111,149,64,60,158,199,115,159,64,45,192,212,179,46,13,171,104,139,49,185,254,235,183,65,52,140,30,89), string.char(106,32,155,133,229,130,33,200,31,51,242)), 169)\nprint(170) assert(\"505910401632c487cd9482ecd6ad16928f21d6f4\" == hmac_sha1(string.char(170,34,244,62,31,230,158,102,235,63,93,33,111,253,232,211,132,160,120,156,107), string.char(43,16,194,149,208,76,252,14,73,11,1,172,79,41,132,217,125,96,221,110,199,248,129,122,45,63,77,145,21,98,40,149,154,9,127,27,168,224,204,167,203,74,218,196,236,230,47,29,122,138,65,239,123,120,29,68,236,137,130,95,114,230,185,146,32,69,201,48,251,233,103,61,132,167,245,42,68,249,145,166,137,204,186)), 170)\nprint(171) assert(\"6d5f9ae7e8a51f2e615ae3aa8525a41b0bf77282\" == hmac_sha1(string.char(166,8,119,187,177,166,23,183,147,37,177,162,102,16,93,204,247,119,248,179,23,89,48,145,188,37,197,176,238,218,173,6,216,229,224,108,58,78,40,199,9,241,191,154,88,124,237,142,228,7,235,102,142,123,4,124,38,46,170,229,116,243,104,106,26,163,94,2,118,71,173,171,104), string.char(41,12,123,197,199,117,129,177,132,149,175,83,168,79,76,58,236,204,99,121,155,207,228,89,236,154,103,137,183,221,208,93,22,222,28,237,140,21,25,149,188,111,6,85,251,31,73,79,239,246,66,46,215,157,184,5,207,4)), 171)\nprint(172) assert(\"8c20120cd131e07d9fa46467602d57c9017ca22d\" == hmac_sha1(string.char(12,24,169,75,70,190,156,115,112,233,245,216,85,248,62,24,91,179,204,185,0,129,209,137,116,97,242,183,35,151,91,170,41,4,81,12,120,47,78,145,193,50,237,224,62,203,171,169,6,141,126,75,29,40), string.char(47,165,0,107,170,77,37,219,45,135,102,68,144,218,213,74,35,58,246,179,171,3,148,55,216,32,29,102,83,58,29,11,166,75,243,60,21,9,202,179,236,129,212,62,217,203,6,193,18,176,156,198,86,140,135,222,109,48,195,112,167,218,92,76,71,40,128,221,235,43,81,109,198,51,77,122,183,111,173,195,8,249,40,159,212,136,180,215,171,70,60,108,26,185,11,222,67,47,142,179,158,131,135,153,168,251,199,21,44,7,164,68,212,209,54,75,18,200,117,213,16,175,152,29,146,154,151,236,143,173,86,70,224,138,71,33,33,151,122,205,128,223,166,51,149,125,178,225,234,164,180)), 172)\nprint(173) assert(\"1ef2a94a2e620a164e07590f006c5a46b722fe7e\" == hmac_sha1(string.char(78,109,133,245,198,165,112,63,135,53,124,251,110,183,41,34,153,68,22,253,66,201,9,41,15,99,105,14,252,172,212,39,100,14,128,16,64,47,104,37,33,27,203,120,163,182,52,37,27,224,212,40,134,81,70,29,155,101,246,141,238,41,253,124,222,216,49,49,85,46,51,51,122,39,221,156,104,7,14,52,71,93,31,219), string.char(191,94,78,159,209,12,118,97,214,190,238,108,175,252,192,244,8,104,145,30,236,242,45,49,215,185,251,73,46,101,156,221,136,245,45,240,138,174,187,151,0,122,113,154,195,94,245,186,218,211,203,189,37,251,21,33,225,66,168,152,102,200,245,101,102,217,193,215,194,214,48,131,153,140,75,100,237,240,32,89,113,17,125,177,189,188,212,101,211,212,102,57,251,213,216,14,86,204,198,147,122,97,203,127,100,107,126,107,116,34,220,122,154,130,135,199,9,243,9,194,214)), 173)\nprint(174) assert(\"ad924bedf84061c998029fb2f168877f0b3939bb\" == hmac_sha1(string.char(174,37,249,22,190,230,152,74,215,14,1,180,201,164,238,160,59,157,213,35,36,43,116,160,158,144,131,30,213,232,29,183,205,87,35,85,252,120,126,5,54,113,176), string.char(25,233,197,224,170,150,207,83,58,255,63,236,20,13,179,143,48,248,212,16,220,143,14,123,207,59,28,124,19)), 174)\nprint(175) assert(\"75a6cfbedde0f1b196209a282b25f5f8b9fef3d1\" == hmac_sha1(string.char(131,192,35,70,146,214,224,190,220,240,195,81,129,33,207,253,47,230,111,169,187,136,52,244,217,178,143,140,225,154,105,95,112,201,136,90,221,255,44,31,48,178,90,178,218,122,228,165,90,189,107,45,217,249,89,213,136,139,91,187,202,204,26,250,112), string.char(41,13,202,37,1,104,116,166,245,50,221,59,115,68,187,115,80,93,202,147,10,96,209,213,76,103,143,237,217,21,124,152,82,54,147,207,164,43,89,83,118,67,43,179,79,64,127,252,9,26,125,101,80,192,111,224,104,243,45,67,54,251,238,146,154,212,193,181,138,168,231,171,203,62,93,97,46,55,109,253,214,79,60,62,126,183,235,63,121,46,99,3,223,174,223,2,208,78,7,15,161,56,160,59,205,122,138,77,47,250,107,136,65,199,98,86,131,217,96,226,11,166,185,131,231,76,28,83,140,7,146,87,158,20,102,224,86,5,232,96,34,129,172,236,146,1,139,63,252,1,48,196,242,41,145,97,254,174,88,107,169,70,158,165,246,160,4,16,212,109,236)), 175)\nprint(176) assert(\"c6f51cc53b0a341dafa4607ee834cffaa8c7c2a2\" == hmac_sha1(string.char(85,193,15,80,156,124,171,95,40,75,229,181,147,237,153,83,232,67,210,131,57,69,7,226,226,195,164,46,185,83,120,177,67,77,119,201,9,123,117,111,148,176,12,145,14,80,225,95,71,136,179,94,136,6,78,230,149,135,176,131,19,125,185,48,200,244,111,8,28,170,82,121,242,200,208,145,73,59,234,19,87,61,79,137,245,148,212,94,96,253,227,60,162,170,49,102), string.char(200,235,229,185,225,227,209,209,199,11,112,58,19,202,246,237,94,60,90,176,145,87,191,138,171,88,242,239,21,146,3,92,255,188,99,146,74,134,252,19,201,111,239,76,249,231,71,109,230,240,192,234,253,52,58,173,153,24,131,161,97,222,0,203,177,179,186,160,46,206,73,176,154,39,248,22,66,164,232,120,188,5,73,245,68,8,40,157,155,93,50,207)), 176)\nprint(177) assert(\"a07ef6f8799ef46062ffea5a43bb3edd30c1fdde\" == hmac_sha1(string.char(81,90,37,124,211,22,19,34,50,56,90,45,17,230,233,38,76,24,250), string.char(142,185,46,191,103,207,110,48,71,10,217,115,193,52,131,87,106,39,9,80,216,15,235,169,30,143,3,7,188,78,34,136,18,200,181,140,22,253,141,59,235,25,59,204,147,80,162,108,237,101,167,249,7,168,24,123,215,220,198,38,133,253,72,168,10,139,84,22,195,36,241,128,70,132,28,242,56,40,159,113,184,187,89,38,198,255,176,88,112,125,68,12,57,207,3,251,72,198,135,48,118,244,199,192,205,164,181,243,40,33,195,204,9,78,108,253,114,211,173,121,245,104,13,116,143,160,241,139,210,162,78,62,69,232,40,248,254,177,6,148,177,168,51,253,177,84,152,29,107,91,186,68,118,30,125,62,196,24,14,87,158,83,39,240,192,79,78,61,133,109,106,98,120,232,144,18,49,96,17,202,208,189,152,171,219,19,41,132,179,219,83,220,201,36,191)), 177)\nprint(178) assert(\"63585793821f635534879a8576194f385f4a551a\" == hmac_sha1(string.char(78,213,189,105,102,116,246,215), string.char(162,53,102,158,78,125,120,189,186,214,237,16,219,220,44,24,30,62,32,177,104,217,225,27,92,128,95,202,50,177,239,152,151,161,31,152,93,108,29,125,23,63,55,243,160,169,99,102,15,188,196,129,217,239,132,180,177,251,132,173,62,172,21,139,16,137,231,6,243,185,218,60,60,156,166,153,99,149,144,192,151,249,141,165,222,254,4,111,58,46,106,78,160,215,49,128,252,4,114,236,132,108,114,189,143,45,42,84,134,81,47,140,247,146,247,179,63,14,92,136,120,139)), 178)\nprint(179) assert(\"95bb1229d26df63839ba4846a41505d48ff98290\" == hmac_sha1(string.char(121,190,21,20,39,101,53,249,44,132,19,132,4,114,199,22,32,143,38,33,184,181,66,55,183,240,31,204,225,230,125,186,87,25,90,229,11,55,239,62,101,67,238,1,104,178,191,144,148,105,6,26,127,154,135,247,248,171,41,44,57,83,186,220,42,40,68,153,189,221), string.char(99,150,114,100,37,53,229,202,20,171,246,91,188,188,46,232,70,26,151,35,223,28,97,132,9,242,55,238,98,75,108,91,226,48,236,209,133,92,68,194,241,199,188,86,59,255,230,128,252,193,94,113,134,27,32,50,191,176,159,185,89,209,255,192,9,214,252,63,147,8,92,162,114,72,50,101,136,180,95,39,55,143,137,118,40,14,104,3,149,153,230,135,98,93,72,180,72,86,185,80,107,69,68,20,73)), 179)\nprint(180) assert(\"9e7c9a258a32e6b3667549cef7a61f307f49b4b9\" == hmac_sha1(string.char(105,200,69,23,156,169,151,107,30,139,196,145,128,108,52,7,181,248,255,83,176,169,152,51,158,236,49,191,65,208,155,204,105,179,148,226,142,194,63,253,217,184,69,11,135,185,203,150,146,57,129,80,87,84,231,168,63,186,149,85,128,236,135,217,246,255,121,70,251,68,139,215,199,143,87,13,196,20,50,92,55,116,34,141,117,89,228,94,63,142,250,182,58,91,68,214), string.char(38,52,86,63,109,91,84,11,33,250,194,192,178,94,37,17,65,111,173,17,37,54,163,168,142,91,191,197,161,229,44,163,163,125,81,204,167,185,244,119,75,28,211,87,159)), 180)\nprint(181) assert(\"7fb01c88e7e519265c18e714efd38bc66f831071\" == hmac_sha1(string.char(138,214,212,108,83,152,165,123), string.char(148,223,186,162,237,166,230,68,59,78,220,164,231,42,46,211,239,38,39,150,174,50,58,4,0,135,87,123,123,5,33,252,197,6,53,83,27,178,189,228,166,252,91,141,67,44,68,106,222,17,46,84,214,252,110,181,216,132,14,246,209,57,183,155,238,64,215,121,8,169,157,175,182,191,169,94,116,105,91,49,203,30,155,202,39,140,146,6,115,162,112,130,175,86,143,128,126,249,148,185,39,174,63,83,19,76,164,34,228,97,198,250,65,3,168,158,61,130,167,166,144,185,146,184,160,39,189,11,243,125,255,60,217,46)), 181)\nprint(182) assert(\"15ab3da2a97592c5f2e22586b4c8a8653411e756\" == hmac_sha1(string.char(6,242,91,101,37,118,105,53,170,56,114,144,117,49,53,203,169,216,9,232,9,170,204,129,82,41,210,45,86,176,139,80,152,168,1,154,32,111,89,165,143,205,21,236,105,62,231,106,232,205,7,189,245,52,145,100,78,140,200,183,209,232,196,88,109,175,70,153,150,231,252,7,189,119,97,176,216,201,186,245,24,128,33,57,113,188,184,0,146,248,69,255,77,144,101), string.char(186,246,72,178,189,127,22,42,22,217,81,156,253,142,152,86,42,41,164,77,150,11,208,155,154,185,18,81,156,185,140,224,215,98,1,97,33,194,137,206,144,219,207,210,52,203,198,1,109,182,65,138,122,227,168,207,213,110,206,102,12,181,198,195,133,218,23,187,117,190,56,140,154,239,105,62,96,148,126,187,47,24,139,194,18,211,225,252,195,49,102,138,165,160,90,153,100,140,105,154,242,59,133,226,19,68,125,59,83,140,48,240,226,129,151,79,130,59,96,111,27,73,198)), 182)\nprint(183) assert(\"7b06792805f4e8062ee9dfbbaffccd787c6f98e1\" == hmac_sha1(string.char(83,132,152,16,245,136,91,241,37,158,80,92,65,223,79,3,189,213,89,253,159,93,194,52,218), string.char(212,242,37,98,229,190,238,23,210,197,147,253,82,105,146,168,198,253,2,160,165,188,165,221,179,112,136,72,149,79,138,70,101,95,210,73,157,14,211,92,27,230,177,84,170,183,15,40,0,92,222,252,166,48,1,139,40,16,186,178,231,109,100,125,253,125,123,94,115,94,150,157,186,230,115,163,194,164,30,131,162,90,28,61,44,248,137,8,246,173,31,177,236,39,8,10,192,148,211,36,215,57)), 183)\nprint(184) assert(\"a28fe22ba0845ae3d57273febbbf1d13e8fde928\" == hmac_sha1(string.char(149), string.char(11,139,249,120,214,252,67,75)), 184)\nprint(185) assert(\"87a9daa85402f6c4b02f1e9fd6edd7e5d178bb88\" == hmac_sha1(string.char(114,92,75,169,228,153,182,206,125,139,162,232,77,38,72,129,132,81,11,153,91,92,152,253,10,79,138,142,17,191,161,194,147,213,43,214,39,32,146,46,132,40,77,192,82,54,55,239,50,47), string.char(114,8,110,153,77,155,178,113,203,30,21,41,136,111,176,255,74,214,117,12,189,194,198,37,73,152,196,108,207,188,187,31,227,237,17,1,66,200,73,83,31,61,161,61,31,149,1,152,140,202,163,175,140,136,51,59,121,28,125,192,238,96,192,65,33,177,136,135,173,13,52,101,42,55,189,201,157,244,104,235,148,114,84,154,10,99,153,41,208,213,41,83,193,129,216,46,4,226,81,184,1,249,70,93,183,173,9,29,57,75,209,67,227,49,253,132,129,13,157,55,66,191,136,67,95,108,155,116,17,125,151,217,242,204,110,143,189,201,118)), 185)\nprint(186) assert(\"6300b2f6236b83de0c84ff1816d246231a5d3b79\" == hmac_sha1(string.char(215,10,19,7,73,236,63,23,34,49,11,240,186,195,32,171,67,85,7,95,190,237,77,216,115,36,230,204,139,95,229,37,201,115,81,96,217,205,49,22,169,32,90,2,90,93,137,247,83,229,39,88,235,175,191,246,80,40,228,114,188,115,14,252,35,40,130,240,20,25,202,80,184,27,227,175,149,64,110,223,25,64,57,189,153,176,143,30,76,2,68), string.char(13,245,250,139,223,128,3,6,189,59,12,139,38,153,215,76,250,198,91,117,242,118,34,26,133,244,143,5,56,182,213,167,144,71,250,40,202,81,22,14,72,201,143,10,177,4,166,75,160,156,100,5,147,138,104,98,9,125,81,202,44,120,241,221,181,0,169,155,96,1,4,205,145,105,150,122,135,231,42,165,179,83,39,122,159,193,139,28,4,201,178,41,168,11,177,61,39,14,196,60,29,131,201,91,46,35,128,63,167,48,132,134,105,224,246,244,81,144,209,123,222,190,167,138,76,194,42,152,23,125,52,156,18,217,101,207,239,63,235,3,3,49,147,172,158,97,179,86,233,85,155,245,206,205,165,195,180,223,20,62,197,143,149,126,152)), 186)\nprint(187) assert(\"35fe4e0cf2417a783d5bdbc17bbc0ab77d2699e7\" == hmac_sha1(string.char(15,157,117,128,204,42,12,183,229,129,132,234,228,150,235,100,100,77,160,26,154,230,246,138,150,120,252,20,188,138,171,189,208,62,201,58,158,152,167,165,98,249,52,143,7,26,109,227,144,81,213,157,31,155,26,12,206,103,193,29,142,126,205,123,83,111,179,166,31,32,183,183,100,54,51,205,180,186,160,220,176,233,42,94,62,241,88,74,31,24,22,115,179,124,136,206,78,83), string.char(248,157,191,249,76,86,187,243,10,116,1,227,141,21,104,154,167,72,30,245,6,57,40,170,253,15,4,192,237,237,142,141,196,243,231,245,121,219,150,237,212,118,78,25,201,249,174,21,76,98,187,155,82,243,218,142,239,101,235,240,134,70,212,205,136,165,170,71,121,137,44,8,110,14,167,162,233,92,51,191,178,227,85,134,168,222,121,62,35,127,57,92,80,142,91,112,9,248,129,127,236,2,190,165,125,236,188,117,158,241,181,134,54,133,16,64,100,156,59,83,249,105,235,187,160,186,158,173,52,25,129,20,156,209,102,170,209,10,3,233,12,228,205,138,16,140,108,74,75,65,238,155,251,129,73,236,118,93,202,217,46,180,165,27,84,120,61,186,173,148,131,161,187,30,175,21,249,12,245,145,89,93,61,151,254,29,247,51,198,238,111,52,30,254)), 187)\nprint(188) assert(\"83c2a380e55ecbc6190b9817bb291a00c36de5e8\" == hmac_sha1(string.char(61,128,92,30,94,101,187,67,197,177,98,100,191,221,190,196,86,62,8,238,225,3,93,127,28,126,217,206,56,192,90,9,74,34,43,228,190,162,57,99,170,238,230,196,99,213,31,6,184,11,79,82,100,68,255,40,63), string.char(78,173,248,128,215,226,77,57,233,135,163,11,241,74,59,78,169,219,125,37,182,56,139,89,32,52,80,165,233,52,179,54,216,45,205,209,173,33,12,148,231,66,126,155,191,91,155,174,23,15,14,28,77,186,139,113,48,141,153,177,252,194,23,61,181,189,66,151,45,11,119,74,236,107,206,244,41,117,161,182,233,138,57,196,90,118,28,99,186,150,54,180,105,230,2,41,246,19,80,211,173,102,72,78,82,253,5,183,248,101,173,204,2,145,105,4,160,44,110,211,63,45,46,78)), 188)\nprint(189) assert(\"bd59d0dcf812107a613a2d892322f532c16ec210\" == hmac_sha1(string.char(161,183,101,160,169,208,82,58,88,198,190,85,53,240,56,6,20,136,86,18,216,63,190), string.char(39,227,142,194,37,34,121,168,239,99,70,39,179,128,26,113,47,95,70,129,255,219,63,233,44,33,19,127,22,24,208,50,19,141,185,19,54,82,147,138,44,69)), 189)\nprint(190) assert(\"6aa92cb64b2e390fbf04dc7edfe3af068109ffba\" == hmac_sha1(string.char(202,230,55,100,136,80,156,240,98,73,97,72,191,195,185,105,150,97,148,33,167,140,212,100,247,154,5,152,117,24,128,221,150,49,143,86,12,211,161,75,177,75,145,46,112,143,37,181,84,50,230,81), string.char(131,200,0,161,117,217,5,10,64,79,178,147,64,248,35,147,135,103,157,181,194,123,76,13,150,118,204,63,32,203,155,222,227,148,31,28,218,83,245,17,208,200,104,78,85,31,114,194,67,159,184,167,42,199,241,6,182,195,3,79,22,236,124)), 190)\nprint(191) assert(\"a42cf08fa6d8ad6ae00251aeed0357dca80645c7\" == hmac_sha1(string.char(170,52,245,172,122,225,164,248,23,35,54,243,118,35,165,16,6), string.char(245,115,59,162,179,146,39,213,64,240,80,108,190,127,116,16,154,211,33,171,150,46,77,213,99,88,160,101,236,202,70,26,61,83,79,110,127,74,97,34,18,243,140,34,244,249,225,88,132,102,7,99,220,140,46,111,96,48,93,44,47,186,86,246,244,127,236,150,35,69,111,238,54,24,71,157,254,21,2,194,69,47,190,87,72,235,60,243,40,153,111,55,220,25,91,17,156,195,57,207,107,145,6,82,104,232,209)), 191)\nprint(192) assert(\"8dd62dcf68ef2d193005921161341839b8cac487\" == hmac_sha1(string.char(136,5,195,241,18,208,11,46,252,182,96,183,164,87,248,13), string.char(78,49,162,9,47,79,26,139,66,194,248,90,171,207,167,43,201,223,102,192,49,145,83,42,1,52,250,116,216,133,224,224,17,143,41,153,65,214,231,109,160,5,31,85,17,186,199,226,214,92,21,194,148,98,68,209,50,74,26,150,97,59,223,8,131,173,145,6,31,126,248,86,226,2,94,15,3,202,239,99,177,237,61,99,14,253,26,246,0,151,2,7,159,40,249,166)), 192)\nprint(193) assert(\"eff66e7a69ae7d2a90b2d80c64ce7c41fe560a19\" == hmac_sha1(string.char(123,54,89,205,103,116,21,97,164,41,23,224,151,195,22,196,90,52,253,92), string.char(141,12,168,171,49,30,165,57,107,214,157,224,36,163,182,184,103,186,133,22,2,215,52,220,95,205,231,180,221,139,67,184,21,46,172,95,183,220,31,27,227,122,183,196,114,206,132,162,51,164,84,212,172,63,218,236,127,215,218,77,119,105,14,19,164,53,149,11,13,1,29,246,69,200,208,239,154,60,245,31,172,82,158,165,197,250,151,83,12,156,215,201,66,45,238,228,77,125,157,35,235,162,78,220,132,14,137,168,238,127,10,24,41,132,181,43,95,73,33,32,129,149,145,55,80,156,171,73,90,183,166,182,163,154,31,104,14,56,59,102,72,210,121,191,251,239,1,5,76,116,158,89,40,69,220,107,23,168,106,93,92,95,21,91,118,118,71,29,64,142,84,15,153,193,47,214,30,117,236,217)), 193)\nprint(194) assert(\"0f1adc518afcca2ed7ad0adaaedd544835ddb76e\" == hmac_sha1(string.char(142,36,199,16,52,54,62,146,153,25,162,85,251,247), string.char(110,70,53,237,120,53,50,196,24,82,199,210,156,178,110,124,7,24,229,89,39,1,10,96,74,211,36,79,166,4,33,238,64,220,239,129,48,232,244,172,142,79,154,73,36,107,182,208,191,25,201,19,233,23,60,236,180,76,116,53,232,181,101,62,160,252,213,171,166,113,193,73,75,13,209,63,76,92,95,176,119,0,125,174,42,138,77,23,212,81,180,10,193,118,244,242,163,246,206,150,162,92,20,208,51,71,254,197,11,222,203,153,208,251,243,193,124,141,215,171,55,244,230,78,158,32,223,138,156,43,98,39,191,108,111,6,117,130,195,100,221,233,17,98,180,49,132,139,171,20,180,7,206,35,54,17,48,253,130,185,249,2,52,17,207,73,24,33)), 194)\nprint(195) assert(\"5e87f8d9a653312fd7b070a33a5d9e67b28b9a84\" == hmac_sha1(string.char(255,237,33,255,4,170,95,90,88,77,217,10,94,118,134,20,33,208,17,136,77,18,169,205,112,36,203,231,67,47,186,91,7,17,29), string.char(97,211,98,53,135,238,42,101,144,12,75,185,119,223,114,81,201,94,21,118,16,152,74,215,56,61,131,151,83,96,83,59,49,199,255,207,153,90,231,39,181,4,59,9,2,150,207,124,209,120,37,236,195,66,189,209,137,9,165,78,172,142,209,243,237,145,204,210,222,153,52,127,39,174,133,17,186,219,87,142,209,212,223,60,249,57,244,251,44,254,73,238,52,99,94,237,189,185,237,1,101,166,220,170,103,209)), 195)\nprint(196) assert(\"837c7cc92e0d2c725b1d1d2f02ef787be37896fa\" == hmac_sha1(string.char(150,241,64,89,79,72,88,157,113,139,190,43,211,214,202,52,124,91,111,198,47,161,120,17,120,157,112,248,245,154,254,25,233,96,216), string.char(214,251,73,193,181,158,253,28,23,48,186,168,162,26,124,103,22,195,165,63,189,196,162,229,69,1,208,85,249,24,73,101,243,149,68,236,124,147,108,67,37,75,202,143,57,124,71,176,27,216,208,183,164,173,219,170,79,10,198,1,232,35,9,19,70,131,211,60,37,94,146,98,92,31,150,95,89,189,46,38,156,118,171,137,86,87,32,173,77,14,135,233,233,114,162,136,57,113,73,115,134,87,184)), 196)\nprint(197) assert(\"64534553f76e55b890101380ad9149d3cacb5b76\" == hmac_sha1(string.char(231,24,192,54,17,14,98,122,119,170,71,54,206,207,223,109,164,181,124,186,122,111,122,34,157,24,237,130,207,206,117,76,183,162,174,124,60,60,77,114,139,170,194,143,232,74,160,141,161,171,51,178,162,159,234,208,55), string.char(141,184,241,185,112,45,53,192,72,152,139,145,146,149,145,151,12,140,111,79,158,172,212,175,75,225,127,4,252,104,5,94,105,24,141,183,79,208,240,227,63,126,213,4,13,109,216,244,237,24,196,52,212,245,147,109,18,63,69,107,122,245,101,67,212,232,92,25,135,67,127,247,187,143,224,198,105,38,147,12,238,6,57,53,105,246,0,127,222,69,163,44,11,245,82,220,32,108,33,70,93,177,89,75,192,214,104,236,84,28,221,209,27,12,80,239,111,249,57,39,236,193,17,69,66,180,63,193,242,248,72,22,225,56,198,235,111,102,33,171,159,124,220,143,108,10,71,186,219,213,28,209,145,188,36,70,59,9,235,154,57,12,211,146,6,87,83)), 197)\nprint(198) assert(\"b7efbbc21ac1a746e22368e814ef5921056331ac\" == hmac_sha1(string.char(137,153,151,252,88,36,165,92,194,50,19,117), string.char(155,113,35,47,22,52,144,77,130,20,178,133,75,207,168,146,132,209,160,7,123,190,117,196,147,212,142,25,182,222,56,249,192,228,6,224,250,221,89,7,176,27,37,49,215,192,74,132,127,101,32,23,34,131,23,74,37,226,208,205,162,242,102)), 198)\nprint(199) assert(\"950ad3222f4917f868d09feab237a909fb6d50b7\" == hmac_sha1(string.char(78,46,85,132,231,4,243,255,22,45,240,155,151,119,94,213,50,111,10,83,40,204,49,52,17,69,132,44,213,83,54,251,211,159,123,55,17,58,162,170,210,3,35,237,165,181,217,27,7,249,158,22,158,207,77,121,37,63,37,39,204,68,99,158,78,175,73,183,47,99,134,65,74,234,154,33,14,117,126,98,167,242,106,112,145,82), string.char(144,133,184,16,9,8,227,98,190,60,141,255,87,69,63,214,12,67,14,206,32,120,59,232,176,82,32,194,115,52,148,143,126,86,82,101,167,249,17,169,9,105,228)), 199)\n\nskynet.start(skynet.exit)"
  },
  {
    "path": "test/testsharetable.lua",
    "content": "local skynet = require \"skynet\"\nlocal sharetable = require \"skynet.sharetable\"\n\nlocal function queryall_test()\n\tsharetable.loadtable(\"test_one\", {[\"message\"] = \"hello one\", x = 1, 1})\n\tsharetable.loadtable(\"test_two\", {[\"message\"] = \"hello two\", x = 2, 2})\n\tsharetable.loadtable(\"test_three\", {[\"message\"] = \"hello three\", x = 3, 3})\n\tlocal list = sharetable.queryall({\"test_one\", \"test_two\"})\n\tfor filename, tbl in pairs(list) do\n\t\tfor k, v in pairs(tbl) do\n\t\t\tprint(filename, k, v)\n\t\tend\n\tend\n\n\tprint(\"test queryall default\")\n\tlocal defaultlist = sharetable.queryall()\n\tfor filename, tbl in pairs(defaultlist) do\n\t\tfor k, v in pairs(tbl) do\n\t\t\tprint(filename, k, v)\n\t\tend\n\tend\nend\n\nskynet.start(function()\n\t-- You can also use sharetable.loadfile / sharetable.loadstring\n\tsharetable.loadtable (\"test\", { x=1,y={ 'hello world' },['hello world'] = true })\n\tlocal t = sharetable.query(\"test\")\n\tfor k,v in pairs(t) do\n\t\tprint(k,v)\n\tend\n\tsharetable.loadstring (\"test\", \"return { ... }\", 1,2,3)\n\tlocal t = sharetable.query(\"test\")\n\tfor k,v in pairs(t) do\n\t\tprint(k,v)\n\tend\n\n\tqueryall_test()\nend)\n"
  },
  {
    "path": "test/testsm.lua",
    "content": "local skynet = require \"skynet\"\nlocal sharemap = require \"skynet.sharemap\"\n\nlocal mode = ...\n\nif mode == \"slave\" then\n--slave\n\nlocal function dump(reader)\n\treader:update()\n\tprint(\"x=\", reader.x)\n\tprint(\"y=\", reader.y)\n\tprint(\"s=\", reader.s)\nend\n\nskynet.start(function()\n\tlocal reader\n\tskynet.dispatch(\"lua\", function(_,_,cmd,...)\n\t\tif cmd == \"init\" then\n\t\t\treader = sharemap.reader(...)\n\t\telse\n\t\t\tassert(cmd == \"ping\")\n\t\t\tdump(reader)\n\t\tend\n\t\tskynet.ret()\n\tend)\nend)\n\nelse\n-- master\nskynet.start(function()\n\t-- register share type schema\n\tsharemap.register(\"./test/sharemap.sp\")\n\tlocal slave = skynet.newservice(SERVICE_NAME, \"slave\")\n\tlocal writer = sharemap.writer(\"foobar\", { x=0,y=0,s=\"hello\" })\n\tskynet.call(slave, \"lua\", \"init\", \"foobar\", writer:copy())\n\twriter.x = 1\n\twriter:commit()\n\tskynet.call(slave, \"lua\", \"ping\")\n\twriter.y = 2\n\twriter:commit()\n\tskynet.call(slave, \"lua\", \"ping\")\n\twriter.s = \"world\"\n\twriter:commit()\n\tskynet.call(slave, \"lua\", \"ping\")\nend)\n\nend"
  },
  {
    "path": "test/testsocket.lua",
    "content": "local skynet = require \"skynet\"\nlocal socket = require \"skynet.socket\"\n\nlocal mode , id = ...\n\nlocal function echo(id)\n\tsocket.start(id)\n\tsocket.write(id, \"Hello Skynet\\n\")\n\n\twhile true do\n\t\tlocal str = socket.read(id)\n\t\tif str then\n\t\t\tsocket.write(id, str)\n\t\telse\n\t\t\tsocket.close(id)\n\t\t\treturn\n\t\tend\n\tend\nend\n\nif mode == \"agent\" then\n\tid = tonumber(id)\n\n\tskynet.start(function()\n\t\tskynet.fork(function()\n\t\t\techo(id)\n\t\t\tskynet.exit()\n\t\tend)\n\tend)\nelse\n\tlocal function accept(id)\n\t\tskynet.newservice(SERVICE_NAME, \"agent\", id)\n\tend\n\n\tskynet.start(function()\n\t\tlocal id = socket.listen(\"127.0.0.1\", 8001)\n\t\tprint(\"Listen socket :\", \"127.0.0.1\", 8001)\n\n\t\tsocket.start(id , function(id, addr)\n\t\t\tprint(\"connect from \" .. addr .. \" \" .. id)\n\t\t\t-- you have choices :\n\t\t\t-- 1. skynet.newservice(\"testsocket\", \"agent\", id)\n\t\t\t-- 2. skynet.fork(echo, id)\n\t\t\t-- 3. accept(id)\n\t\t\taccept(id)\n\t\tend)\n\tend)\nend"
  },
  {
    "path": "test/teststm.lua",
    "content": "local skynet = require \"skynet\"\nlocal stm = require \"skynet.stm\"\n\nlocal mode = ...\n\nif mode == \"slave\" then\n\nskynet.start(function()\n\tskynet.dispatch(\"lua\", function (_,_, obj)\n\t\tlocal obj = stm.newcopy(obj)\n\t\tprint(\"read:\", obj(skynet.unpack))\n\t\tskynet.ret()\n\t\tskynet.error(\"sleep and read\")\n\t\tfor i=1,10 do\n\t\t\tskynet.sleep(10)\n\t\t\tprint(\"read:\", obj(skynet.unpack))\n\t\tend\n\t\tskynet.exit()\n\tend)\nend)\n\nelse\n\nskynet.start(function()\n\tlocal slave = skynet.newservice(SERVICE_NAME, \"slave\")\n\tlocal obj = stm.new(skynet.pack(1,2,3,4,5))\n\tlocal copy = stm.copy(obj)\n\tskynet.call(slave, \"lua\", copy)\n\tfor i=1,5 do\n\t\tskynet.sleep(20)\n\t\tprint(\"write\", i)\n\t\tobj(skynet.pack(\"hello world\", i))\n\tend\n \tskynet.exit()\nend)\nend\n"
  },
  {
    "path": "test/testterm.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal function term()\n\tskynet.error(\"Sleep one second, and term the call to UNEXIST\")\n\tskynet.sleep(100)\n\tlocal self = skynet.self()\n\tskynet.send(skynet.self(), \"debug\", \"TERM\", \"UNEXIST\")\nend\n\nskynet.start(function()\n\tskynet.fork(term)\n\tskynet.error(\"call an unexist named service UNEXIST, may block\")\n\tpcall(skynet.call, \"UNEXIST\", \"lua\", \"test\")\n\tskynet.error(\"unblock the unexisted service call\")\nend)\n"
  },
  {
    "path": "test/testtimeout.lua",
    "content": "local skynet = require \"skynet\"\nlocal service = require \"skynet.service\"\n\nlocal function test_service()\n\tlocal skynet = require \"skynet\"\n\n\tskynet.start(function()\n\t\tskynet.dispatch(\"lua\", function()\n\t\t\tskynet.error(\"Wait for 1s\")\n\t\t\tskynet.sleep(100)\t-- response after 1s for any request\n\t\t\tskynet.ret()\n\t\tend)\n\tend)\nend\n\nlocal function timeout_call(ti, ...)\n\tlocal token = {}\n\tlocal ret\n\n\tskynet.fork(function(...)\n\t\tret = table.pack(pcall(skynet.call, ...))\n\t\tskynet.wakeup(token)\n\tend, ...)\n\n\tskynet.sleep(ti, token)\n\tif ret then\n\t\tif ret[1] then\n\t\t\treturn table.unpack(ret, 1, ret.n)\n\t\telse\n\t\t\terror(ret[2])\n\t\tend\n\telse\n\t\t-- timeout\n\t\treturn false\n\tend\nend\n\nskynet.start(function()\n\tlocal test = service.new(\"testtimeout\", test_service)\n\tskynet.error(\"1\", skynet.now())\n\tskynet.call(test, \"lua\")\n\tskynet.error(\"2\", skynet.now())\n\tskynet.error(timeout_call(50, test, \"lua\"))\n\tskynet.error(\"3\", skynet.now())\n\tskynet.error(timeout_call(150, test, \"lua\"))\n\tskynet.error(\"4\", skynet.now())\n\tskynet.exit()\nend)\n\n\n\n\n"
  },
  {
    "path": "test/testtimer.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal function timeout(t)\n\tprint(t)\nend\n\nlocal function wakeup(co)\n\tfor i=1,5 do\n\t\tskynet.sleep(50)\n\t\tskynet.wakeup(co)\n\tend\nend\n\nlocal function test()\n\tskynet.timeout(10, function() print(\"test timeout 10\") end)\n\tlocal taskinfo = {}\n\tskynet.task(taskinfo)\n\tfor session, info in pairs(taskinfo) do\n\t\tprint(\"session = \", session, \"trace = \", info)\n\tend\n\tfor i=1,10 do\n\t\tprint(\"test sleep\",i,skynet.now())\n\t\tskynet.sleep(1)\n\tend\nend\n\nskynet.start(function()\n\tskynet.trace_timeout(true)\t-- turn on trace for timeout, skynet.task will returns more info.\n\ttest()\n\n\tskynet.fork(wakeup, coroutine.running())\n\tskynet.timeout(300, function() timeout \"Hello World\" end)\n\tfor i = 1, 10 do\n\t\tprint(i, skynet.now())\n\t\tprint(skynet.sleep(100))\n\tend\n\tskynet.exit()\n\tprint(\"Test timer exit\")\n\nend)\n"
  },
  {
    "path": "test/testtobeclosed.lua",
    "content": "local skynet = require \"skynet\"\n\nlocal function new_test(name)\n    return setmetatable({}, { __close = function(...)\n        skynet.error(...)\n    end, __name = \"closemeta:\" .. name})\nend\n\nlocal i = 0\nskynet.dispatch(\"lua\", function()\n    i = i + 1\n    if i==2 then\n        local c<close> = new_test(\"dispatch_error\")\n        error(\"dispatch_error\")\n    else\n        local c<close> = new_test(\"dispatch_wait\")\n        skynet.wait()\n    end\nend)\n\nskynet.start(function()\n    local c<close> = new_test(\"skynet.exit\")\n    skynet.fork(function()\n        local a<close> = new_test(\"stack_raise_error\")\n        error(\"raise error\")\n    end)\n    skynet.fork(function()\n        local a<close> = new_test(\"session_id_coroutine_wait\")\n        skynet.wait()\n    end)\n    skynet.fork(function()\n        local a<close> = new_test(\"session_id_coroutine_call\")\n        skynet.call(skynet.self(), \"lua\")\n    end)\n    skynet.fork(function()\n        skynet.call(skynet.self(), \"lua\")\n    end)\n    skynet.sleep(100)\n    skynet.fork(function()\n        local a<close> = new_test(\"no_running\")\n        skynet.wait()\n    end)\n    skynet.exit()\nend)\n\n--[[\ntesttobeclosed\n]]"
  },
  {
    "path": "test/testudp.lua",
    "content": "local skynet = require \"skynet\"\nlocal socket = require \"skynet.socket\"\n\nlocal function server()\n\tlocal host\n\thost = socket.udp(function(str, from)\n\t\tprint(\"server v4 recv\", str, socket.udp_address(from))\n\t\tsocket.sendto(host, from, \"OK \" .. str)\n\tend , \"127.0.0.1\", 8765)\t-- bind an address\nend\n\nlocal function client()\n\tlocal c = socket.udp(function(str, from)\n\t\tprint(\"client v4 recv\", str, socket.udp_address(from))\n\tend)\n\tsocket.udp_connect(c, \"127.0.0.1\", 8765)\n\tfor i=1,20 do\n\t\tsocket.write(c, \"hello \" .. i)\t-- write to the address by udp_connect binding\n\tend\nend\n\nlocal function server_v6()\n\tlocal server\n\tserver = socket.udp_listen(\"::1\", 8766, function(str, from)\n\t\tprint(string.format(\"server_v6 recv str:%s from:%s\", str, socket.udp_address(from)))\n\t\tsocket.sendto(server, from, \"OK \" .. str)\n\tend)\t-- bind an address\n\tprint(\"create server succeed. \"..server)\n\treturn server\nend\n\nlocal function client_v6()\n\tlocal c = socket.udp_dial(\"::1\", 8766, function(str, from)\n\t\tprint(string.format(\"client recv v6 response str:%s from:%s\", str, socket.udp_address(from)))\n\tend)\n\t\n\tprint(\"create client succeed. \"..c)\n\tfor i=1,20 do\n\t\tsocket.write(c, \"hello \" .. i)\t-- write to the address by udp_connect binding\n\tend\nend\n\nskynet.start(function()\n\tskynet.fork(server)\n\tskynet.fork(client)\n\tskynet.fork(server_v6)\n\tskynet.fork(client_v6)\nend)\n"
  },
  {
    "path": "test/time.lua",
    "content": "local skynet = require \"skynet\"\nskynet.start(function()\n    print(skynet.starttime())\n    print(skynet.now())\n\n    skynet.timeout(1, function()\n        print(\"in 1\", skynet.now())\n    end)\n    skynet.timeout(2, function()\n        print(\"in 2\", skynet.now())\n    end)\n    skynet.timeout(3, function()\n        print(\"in 3\", skynet.now())\n    end)\n\n    skynet.timeout(4, function()\n        print(\"in 4\", skynet.now())\n    end)\n    skynet.timeout(100, function()\n        print(\"in 100\", skynet.now())\n    end)\nend)\n"
  }
]