[
  {
    "path": ".gitattributes",
    "content": "src/lua/* linguist-vendored"
  },
  {
    "path": ".gitignore",
    "content": "*.o\nprojects/vs2017/libs/**\nprojects/opendingux/**\nprojects/funkey/**\n**/.vs/**\n**/Debug/**\n**/Release/**\n.DS_Store\n"
  },
  {
    "path": ".gitlab-ci.yml",
    "content": "# DESCRIPTION: GitLab CI/CD for libRetro (NOT FOR GitLab-proper)\n\n##############################################################################\n################################# BOILERPLATE ################################\n##############################################################################\n\n# Core definitions\n.core-defs:\n  variables:\n    JNI_PATH: .\n    CORENAME: retro8\n    MAKEFILE: Makefile\n \n# Inclusion templates, required for the build to work\ninclude:\n  ################################## DESKTOPS ################################\n  # Windows 64-bit\n  - project: 'libretro-infrastructure/ci-templates'\n    file: '/windows-x64-mingw.yml'\n    \n  # Windows 32-bit\n  - project: 'libretro-infrastructure/ci-templates'\n    file: '/windows-i686-mingw.yml'\n    \n  # Linux 64-bit\n  - project: 'libretro-infrastructure/ci-templates'\n    file: '/linux-x64.yml'\n\n  # Linux 32-bit\n  - project: 'libretro-infrastructure/ci-templates'\n    file: '/linux-i686.yml'\n\n  # MacOS 64-bit\n  - project: 'libretro-infrastructure/ci-templates'\n    file: '/osx-x64.yml'\n    \n  ################################## CELLULAR ################################\n  # Android\n  - project: 'libretro-infrastructure/ci-templates'\n    file: '/android-jni.yml'\n\n  ################################## CONSOLES ################################\n  # PlayStation Vita\n  #- project: 'libretro-infrastructure/ci-templates'\n    #file: '/vita-static.yml'\n    \n  # Nintendo GameCube\n  #- project: 'libretro-infrastructure/ci-templates'\n    #file: '/ngc-static.yml'\n\n  # Nintendo Wii\n  #- project: 'libretro-infrastructure/ci-templates'\n    #file: '/wii-static.yml'\n\n# Stages for building\nstages:\n  - build-prepare\n  - build-shared\n  - build-static\n\n##############################################################################\n#################################### STAGES ##################################\n##############################################################################\n#\n################################### DESKTOPS #################################\n# Windows 64-bit\nlibretro-build-windows-x64:\n  extends:\n    - .libretro-windows-x64-mingw-make-default\n    - .core-defs\n    \n# Windows 32-bit\nlibretro-build-windows-i686:\n  extends:\n    - .libretro-windows-i686-mingw-make-default\n    - .core-defs\n    \n# Linux 64-bit\nlibretro-build-linux-x64:\n  extends:\n    - .libretro-linux-x64-make-default\n    - .core-defs\n\n# Linux 32-bit\nlibretro-build-linux-i686:\n  extends:\n    - .libretro-linux-i686-make-default\n    - .core-defs\n\n# MacOS 64-bit\nlibretro-build-osx-x64:\n  extends:\n    - .libretro-osx-x64-make-default\n    - .core-defs\n    \n################################### CELLULAR #################################\n# Android ARMv7a\nandroid-armeabi-v7a:\n  extends:\n    - .libretro-android-jni-armeabi-v7a\n    - .core-defs\n\n# Android ARMv8a\nandroid-arm64-v8a:\n  extends:\n    - .libretro-android-jni-arm64-v8a\n    - .core-defs\n\n# Android 64-bit x86\nandroid-x86_64:\n  extends:\n    - .libretro-android-jni-x86_64\n    - .core-defs\n\n# Android 32-bit x86\nandroid-x86:\n  extends:\n    - .libretro-android-jni-x86\n    - .core-defs\n    \n################################### CONSOLES #################################\n# Nintendo GameCube\n#libretro-build-ngc:\n  #extends:\n    #- .libretro-ngc-static-retroarch-master\n    #- .core-defs\n\n# Nintendo Wii\n#libretro-build-wii:\n  #extends:\n    #- .libretro-wii-static-retroarch-master\n    #- .core-defs\n    \n# PlayStation Vita\n#libretro-build-vita:\n  #extends:\n    #- .libretro-vita-static-retroarch-master\n    #- .core-defs\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.5.0)\n\nproject (retro8)\n\nset(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} \"${CMAKE_SOURCE_DIR}/projects/cmake\")\n\noption(FUNKEY_S \"Building for FunKey-S\" OFF)\noption(OPENDINGUX \"Build on opendingux toolchain\" OFF)\noption(RETROFW \"Build for retrofw\" OFF)\n\n# RETROFW is an OPENDINGUX variant\nif (RETROFW)\n  set(OPENDINGUX ON)\nendif()\n\nif (\"${CMAKE_BUILD_TYPE}\" STREQUAL \"\")\n  set(CMAKE_BUILD_TYPE \"Debug\")\nendif()\n\nif(OPENDINGUX)\n  set(CMAKE_CXX_COMPILER \"$ENV{CROSS}g++\" CACHE PATH \"\" FORCE)\n  set(CMAKE_C_COMPILER \"$ENV{CROSS}gcc\" CACHE PATH \"\" FORCE)\n  if(RETROFW)\n    set(CMAKE_SYSROOT \"/opt/mipsel-linux-uclibc/mipsel-buildroot-linux-uclibc/sysroot\")\n  else()\n    set(CMAKE_SYSROOT \"/opt/gcw0-toolchain/usr/mipsel-gcw0-linux-uclibc/sysroot\")\n  endif()\nelseif(FUNKEY_S)\n  add_definitions(-DFUNKEY_S)\nendif()\n\nif (FUNKEY_S OR RETROFW)\n  find_package(SDL REQUIRED)\n  include_directories(${SDL_INCLUDE_DIR})\nelse()\n  find_package(SDL2 REQUIRED)\n  include_directories(${SDL2_INCLUDE_DIR})\nendif()\n\nadd_compile_options(-Wno-unused-parameter -Wno-missing-field-initializers\n  -Wno-sign-compare -Wno-parentheses -Wno-unused-variable -Wno-char-subscripts\n)\n\nadd_compile_options(-g -O2 -W -Wall -Wextra)\nadd_compile_options(\n  $<$<COMPILE_LANGUAGE:CXX>:-Wno-reorder>\n)\n\nif(APPLE)\n  add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-std=c++14>)\nelse()\n  add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-std=c++11>)\nendif()\n\ninclude_directories(src)\nset(SRC_ROOT \"${CMAKE_SOURCE_DIR}/src\")\n\nfile(GLOB SOURCES_ROOT \"${SRC_ROOT}/*.cpp\")\nfile(GLOB SOURCES_VIEWS \"${SRC_ROOT}/views/*.cpp\")\nfile(GLOB SOURCES_IO \"${SRC_ROOT}/io/*.cpp\")\nfile(GLOB SOURCES_VM \"${SRC_ROOT}/vm/*.cpp\")\nfile(GLOB SOURCES_LUA \"${SRC_ROOT}/lua/*.c\")\n\nset(SOURCES ${SOURCES_ROOT} ${SOURCES_VIEWS} ${SOURCES_IO} ${SOURCES_VM} ${SOURCES_LUA})\n\nadd_executable(retro8 ${SOURCES})\n\nif (SDL_FOUND)\n  target_link_libraries(retro8 ${SDL_LIBRARY})\nelse()\n  target_link_libraries(retro8 ${SDL2_LIBRARY})\nendif()\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "Makefile",
    "content": "STATIC_LINKING := 0\nAR             := ar\n\nifneq ($(V),1)\n   Q := @\nendif\n\nifneq ($(SANITIZER),)\n   CFLAGS   := -fsanitize=$(SANITIZER) $(CFLAGS)\n   CXXFLAGS := -fsanitize=$(SANITIZER) $(CXXFLAGS)\n   LDFLAGS  := -fsanitize=$(SANITIZER) $(LDFLAGS)\nendif\n\nifeq ($(platform),)\nplatform = unix\nifeq ($(shell uname -a),)\n   platform = win\nelse ifneq ($(findstring MINGW,$(shell uname -a)),)\n   platform = win\nelse ifneq ($(findstring Darwin,$(shell uname -a)),)\n   platform = osx\nelse ifneq ($(findstring win,$(shell uname -a)),)\n   platform = win\nendif\nendif\n\n# system platform\nsystem_platform = unix\nifeq ($(shell uname -a),)\n\tEXE_EXT = .exe\n\tsystem_platform = win\nelse ifneq ($(findstring Darwin,$(shell uname -a)),)\n\tsystem_platform = osx\n\tarch = intel\nifeq ($(shell uname -p),powerpc)\n\tarch = ppc\nendif\nelse ifneq ($(findstring MINGW,$(shell uname -a)),)\n\tsystem_platform = win\nendif\n\nCORE_DIR    += .\nTARGET_NAME := retro8\nLIBM\t\t    = -lm\n\nifeq ($(ARCHFLAGS),)\nifeq ($(archs),ppc)\n   ARCHFLAGS = -arch ppc -arch ppc64\nelse\n   ARCHFLAGS = -arch i386 -arch x86_64\nendif\nendif\n\nifeq ($(platform), osx)\nifndef ($(NOUNIVERSAL))\n   CXXFLAGS += $(ARCHFLAGS)\n   LFLAGS += $(ARCHFLAGS)\nendif\nendif\n\nifeq ($(STATIC_LINKING), 1)\nEXT := a\nendif\n\nifneq (,$(findstring unix,$(platform)))\n\tEXT ?= so\n   TARGET := $(TARGET_NAME)_libretro.$(EXT)\n   fpic := -fPIC\n   SHARED := -shared -Wl,--version-script=$(CORE_DIR)/link.T -Wl,--no-undefined\n   LIBS += -lpthread\nelse ifeq ($(platform), linux-portable)\n   TARGET := $(TARGET_NAME)_libretro.$(EXT)\n   fpic := -fPIC -nostdlib\n   SHARED := -shared -Wl,--version-script=$(CORE_DIR)/link.T\n\tLIBM :=\nelse ifneq (,$(findstring osx,$(platform)))\n   TARGET := $(TARGET_NAME)_libretro.dylib\n   fpic := -fPIC\n   SHARED := -dynamiclib\nelse ifneq (,$(findstring ios,$(platform)))\n   TARGET := $(TARGET_NAME)_libretro_ios.dylib\n\tfpic := -fPIC\n\tSHARED := -dynamiclib\n\nifeq ($(IOSSDK),)\n   IOSSDK := $(shell xcodebuild -version -sdk iphoneos Path)\nendif\n\n\tDEFINES := -DIOS\n\tCC = cc -arch armv7 -isysroot $(IOSSDK)\nifeq ($(platform),ios9)\nCC     += -miphoneos-version-min=8.0\nCXXFLAGS += -miphoneos-version-min=8.0\nelse\nCC     += -miphoneos-version-min=5.0\nCXXFLAGS += -miphoneos-version-min=5.0\nendif\nelse ifneq (,$(findstring qnx,$(platform)))\n\tTARGET := $(TARGET_NAME)_libretro_qnx.so\n   fpic := -fPIC\n   SHARED := -shared -Wl,--version-script=$(CORE_DIR)/link.T -Wl,--no-undefined\nelse ifeq ($(platform), emscripten)\n   TARGET := $(TARGET_NAME)_libretro_emscripten.bc\n   fpic := -fPIC\n   SHARED := -shared -Wl,--version-script=$(CORE_DIR)/link.T -Wl,--no-undefined\nelse ifeq ($(platform), libnx)\n   include $(DEVKITPRO)/libnx/switch_rules\n   TARGET := $(TARGET_NAME)_libretro_$(platform).a\n   DEFINES := -DSWITCH=1 -D__SWITCH__ -DARM\n   CFLAGS := $(DEFINES) -fPIE -I$(LIBNX)/include/ -ffunction-sections -fdata-sections -ftls-model=local-exec\n   CFLAGS += -march=armv8-a -mtune=cortex-a57 -mtp=soft -mcpu=cortex-a57+crc+fp+simd -ffast-math\n   CXXFLAGS := $(ASFLAGS) $(CFLAGS)\n   STATIC_LINKING = 1\nelse ifeq ($(platform), vita)\n   TARGET := $(TARGET_NAME)_vita.a\n   CC = arm-vita-eabi-gcc\n   AR = arm-vita-eabi-ar\n   CXXFLAGS += -Wl,-q -Wall -O3\n\tSTATIC_LINKING = 1\nelse\n   CC ?= gcc\n   TARGET := $(TARGET_NAME)_libretro.dll\n   SHARED := -shared -static-libgcc -static-libstdc++ -s -Wl,--version-script=$(CORE_DIR)/link.T -Wl,--no-undefined\nendif\n\nLDFLAGS += $(LIBM)\n\nifeq ($(DEBUG), 1)\n   CFLAGS += -O0 -g -DDEBUG\n   CXXFLAGS += -O0 -g -DDEBUG\nelse\n   CFLAGS += -O3\n   CXXFLAGS += -O3\nendif\n\ninclude Makefile.common\n\nOBJECTS := $(SOURCES_C:.c=.o) $(SOURCES_CXX:.cpp=.o)\n\nCFLAGS   += -Wall -D__LIBRETRO__ $(fpic) $(INCFLAGS) \nCXXFLAGS += -Wall -D__LIBRETRO__ $(fpic) $(INCFLAGS) -std=c++14\n\nall: $(TARGET)\n\n$(TARGET): $(OBJECTS)\nifeq ($(STATIC_LINKING), 1)\n\t$(AR) rcs $@ $(OBJECTS)\nelse\n\t@$(if $(Q), $(shell echo echo LD $@),)\n\t$(CXX) $(fpic) $(SHARED) -o $@ $(OBJECTS) $(LIBS) $(LDFLAGS)\nendif\n\n\n%.o: %.c\n\t@$(if $(Q), $(shell echo echo CC $<),)\n\t$(Q)$(CC) $(CFLAGS) $(fpic) -c -o $@ $<\n\n%.o: %.cpp\n\t@$(if $(Q), $(shell echo echo CXX $<),)\n\t$(Q)$(CXX) $(CXXFLAGS) $(fpic) -c -o $@ $<\n\nclean:\n\trm -f $(OBJECTS) $(TARGET)\n\n.PHONY: clean\n\nprint-%:\n\t@echo '$*=$($*)'\n"
  },
  {
    "path": "Makefile.common",
    "content": "SRC_FOLDERS\t:= \\\n\t$(CORE_DIR)/src/io \\\n\t$(CORE_DIR)/src/libretro \\\n\t$(CORE_DIR)/src/vm\n\nSRC_FOLDERS_C\t:= \\\n\t$(CORE_DIR)/src/lua\n\nINCLUDES\t:=  \\\n\t$(CORE_DIR)/src \\\n\t$(CORE_DIR)/src/io \\\n\t$(CORE_DIR)/src/lua \\\n\t$(CORE_DIR)/src/libretro \\\n\t$(CORE_DIR)/src/vm\n\nINCFLAGS   := $(foreach dir,$(INCLUDES), -I$(dir))\n\nSRC_CORE_CXX := $(foreach dir, $(SRC_FOLDERS), $(wildcard $(dir)/*.cpp))\n\nSRC_CORE_C  := $(foreach dir,$(SRC_FOLDERS_C), $(wildcard $(dir)/*.c))\n\nSOURCES_CXX\t:= $(SRC_CORE_CXX)\t\n\nSOURCES_C\t:= $(SRC_CORE_C)\t\n"
  },
  {
    "path": "README.md",
    "content": "## Introduction\n\nThis is an attempt to have an open source reimplementation of PICO-8 fantasy console to be used on Desktop platforms but especially wherever you want to compile it.\n\nIt was born as an attempt to make PICO-8 games playable on OpenDingux devices (GCW0, RG350, ..).\nIt has now been extended to be compiled as a RetroArch core too.\n\n## Implementation\n\nThe emulator is written in C++11 and embeds Lua source code (to allow extensions to the language that PICO-8 has). It has a SDL2.0 back-end but a SDL1.2 back-end wouldn't be hard to implement.\n\n## Status\n\nCurrently much of the API is already working with good performance, even basic sound and music are working.\n\nMany demos already work and even some full games.\n\n- All graphics functions have been implemented but not all their subfeatures,\n- All math functions have been implemented,\n- Sound functions have been implemented together with an audio renderer stack but many effects still missing\n- Common platform functions have been implemented\n- Some Lua language extensions have been implemented\n- Many quirks of the Lua extensions are implemented but some of most obscure things are still missing\n\nFixed arithmetic support is still missing.\n\n## Screenshots\n\n![](projects/screenshots/screenshot1.png)\n![](projects/screenshots/screenshot2.png)\n![](projects/screenshots/screenshot3.png)\n\n## Building\n\nIf you want to build a libretro backend:\n\n```\nmake\n```\n\nIf you want to build a local binary you can run:\n\n```\ncmake .\nmake\n```\n\nIf you want to cross-compile for OpenDingux:\n\n```\ncmake -DOPENDINGUX=ON .\nmake\n```\n\nIf you want to compile for retrofw (assuming your compiler is installed per [retrofw instructions](https://github.com/retrofw/retrofw.github.io/wiki/Making-Games)):\n\n```\nCROSS=/opt/mipsel-linux-uclibc/bin/mipsel-buildroot-linux-uclibc- cmake -DRETROFW=ON .\nmake\n```\n\nTo build an OpenDingux OPK file once your binary is built:\n\n```\nmkdir -p projects/opendingux\ncp -a retro8 projects/opendingux/\ncd projects\n./build_opk_od.sh\n```\n"
  },
  {
    "path": "data/api.lua",
    "content": "function all(t)\n  if t ~= nil then\n    local nt = {}\n    local ni = 1\n    for _,v in pairs(t) do\n      nt[ni] = v\n      ni = ni + 1\n    end\n    for k,v in pairs(nt) do\n    end\n\n    local i = 0\n    return function() i = i + 1; return nt[i] end\n  end\n  return function() end\nend\n\nfunction add(t, v)\n  if t ~= nil then\n    t[#t+1] = v\n    return v\n  end\nend\n\nfunction foreach(c, f)\n  if c ~= nil then\n    for value in all(c) do\n      f(value)\n    end\n  end\nend\n\n\nfunction mapdraw(...)\n  map(table.unpack(arg))\nend\n\nfunction count(t)\n  if t ~= nil then\n    return #t\n  end\nend\n\nfunction del(t, v)\n  if t ~= nil then\n    local found = false\n    for i = 1, #t do\n      if t[i] == v then\n        found = true\n      end\n      if found then\n        t[i] = t[i+1]\n      end\n    end\n    if found then\n      return v\n    end\n  end\nend\n\nfunction cocreate(f)\n  return coroutine.create(f)\nend\n\nfunction yield()\n  coroutine.yield()\nend\n\n-- TODO: missing vararg\nfunction coresume(f)\n  return coroutine.resume(f)\nend\n\nfunction costatus(f)\n  return coroutine.status(f)\nend"
  },
  {
    "path": "data/default.funkey-s.desktop",
    "content": "[Desktop Entry]\nType=Emulator\nName=retro-8\nComment=PICO-8 Emulator\nTerminal=false\nStartupNotify=true\nExec=retro8 %f\nIcon=icon\nCategories=emulators;\nX-OD-Filter=.png,.p8\n"
  },
  {
    "path": "data/default.gcw0.desktop",
    "content": "[Desktop Entry]\nType=Emulator\nName=retro-8\nComment=PICO-8 Emulator\nTerminal=false\nStartupNotify=true\nExec=retro8 %f\nIcon=icon\nCategories=emulators;\nX-OD-Filter=.png,.p8\n"
  },
  {
    "path": "data/default.retrofw.desktop",
    "content": "[Desktop Entry]\nType=Application\nName=Retro8\nComment=PICO-8 Emulator\nExec=retro8 %f\nIcon=icon\nTerminal=false\nType=Application\nCategories=emulators;\nX-OD-NeedsDownscaling=true\nX-OD-Filter=.png,.p8\n"
  },
  {
    "path": "jni/Android.mk",
    "content": "LOCAL_PATH := $(call my-dir)\n\nCORE_DIR := $(LOCAL_PATH)/..\n\nINCFLAGS :=\n\ninclude $(CORE_DIR)/Makefile.common\n\nCOREFLAGS := -D__LIBRETRO__ -DNOGDB $(INCFLAGS)\n\nGIT_VERSION := \" $(shell git rev-parse --short HEAD || echo unknown)\"\nifneq ($(GIT_VERSION),\" unknown\")\n  COREFLAGS += -DGIT_VERSION=\\\"$(GIT_VERSION)\\\"\nendif\n\ninclude $(CLEAR_VARS)\nLOCAL_MODULE    := retro\nLOCAL_SRC_FILES := $(SOURCES_CXX) $(SOURCES_C)\nLOCAL_CFLAGS    := $(COREFLAGS)\nLOCAL_LDFLAGS   := -Wl,-version-script=$(CORE_DIR)/link.T\ninclude $(BUILD_SHARED_LIBRARY)\n"
  },
  {
    "path": "jni/Application.mk",
    "content": "APP_ABI := all\nAPP_STL := c++_static\n"
  },
  {
    "path": "link.T",
    "content": "{\n   global: retro_*;\n   local: *;\n};\n\n"
  },
  {
    "path": "projects/Makefile",
    "content": ".PHONY: all clean info\n\nCXX := $(CROSS)g++\nCC := $(CROSS)gcc\n\nSYSROOT:= $(shell $(CXX) -print-sysroot)\nCXXFLAGS += $(shell $(SYSROOT)/usr/bin/sdl2-config --cflags)\nLDFLAGS += $(shell $(SYSROOT)/usr/bin/sdl2-config --libs)\nLDFLAGS += -lSDL2_image -L$(shell pwd) -flto\n\nDISABLED_WARNINGS += -Wno-unused-parameter -Wno-missing-field-initializers -Wno-sign-compare -Wno-parentheses -Wno-unused-variable -Wno-reorder\nCXXFLAGS += -g -O2 -W -Wall -Wextra -std=c++0x $(DISABLED_WARNINGS) -I../../src\nCCFLAGS +=\n# -O2\n\nSRC_BASE := \"../../src\"\nSRC_FOLDERS := $(SRC_BASE) $(SRC_BASE)/views $(SRC_BASE)/vm $(SRC_BASE)/io $(SRC_BASE)/lua\nTEST := $(wildcard $(SRC_BASE)/views/*.cpp)\nFULL_SOURCES := $(foreach dir, $(SRC_FOLDERS), $(wildcard $(dir)/*.cpp))\nSOURCES := $(patsubst $(SRC_BASE)/%, %, $(foreach dir, $(SRC_FOLDERS), $(wildcard $(dir)/*.cpp)))\nBINARIES:= $(foreach source, $(SOURCES), $(source:%.cpp=%.o) )\n\nEXECUTABLE:= ./retro8\n\nall: $(EXECUTABLE)\n\n$(EXECUTABLE): $(BINARIES)\n\t$(CXX) $(BINARIES) -o $@ $(LDFLAGS)\n\tmkdir -p data\n\n#.cpp.o:\n#\t$(CC) $(CXXFLAGS) $< -o $@\n\nclean:\n\trm -f $(BINARIES) $(EXECUTABLE)\n\ninfo:\n\t@echo Source base: $(SRC_BASE)\n\t@echo Source subfolders: $(SRC_FOLDERS)\n\t@echo Source files: $(TEST)\n\t@echo Test: $(SRC_BASE)/views/*.cpp\n"
  },
  {
    "path": "projects/build_opk_funkey.sh",
    "content": "rm -rf opk\nmkdir -p opk\ncp funkey/retro8 opk\ncp vs2017/retro8/api.lua opk\ncp ../data/default.funkey-s.desktop opk\ncp ../data/icon.png opk\nmksquashfs opk retro8.opk -all-root -noappend -no-exports -no-xattrs -no-progress > /dev/null\n# rm -rf opk\n"
  },
  {
    "path": "projects/build_opk_od.sh",
    "content": "rm -rf opk\nmkdir -p opk\ncp opendingux/retro8 opk\ncp vs2017/retro8/api.lua opk\ncp ../data/default.gcw0.desktop opk\ncp ../data/pico8_font.png opk\ncp ../data/icon.png opk\nmksquashfs opk retro8.opk -all-root -noappend -no-exports -no-xattrs -no-progress > /dev/null\n# rm -rf opk\n"
  },
  {
    "path": "projects/build_opk_retrofw.sh",
    "content": "rm -rf opk\nmkdir -p opk\ncp ../retro8 opk\ncp vs2017/retro8/api.lua opk\ncp ../data/default.retrofw.desktop opk\ncp ../data/pico8_font.png opk\ncp ../data/icon.png opk\nmksquashfs opk retro8.opk -all-root -noappend -no-exports -no-xattrs -no-progress > /dev/null\n# rm -rf opk\n"
  },
  {
    "path": "projects/cmake/FindSDL2.cmake",
    "content": "\n# This module defines\n# SDL2_LIBRARY, the name of the library to link against\n# SDL2_FOUND, if false, do not try to link to SDL2\n# SDL2_INCLUDE_DIR, where to find SDL.h\n#\n# This module responds to the the flag:\n# SDL2_BUILDING_LIBRARY\n# If this is defined, then no SDL2main will be linked in because\n# only applications need main().\n# Otherwise, it is assumed you are building an application and this\n# module will attempt to locate and set the the proper link flags\n# as part of the returned SDL2_LIBRARY variable.\n#\n# Don't forget to include SDLmain.h and SDLmain.m your project for the\n# OS X framework based version. (Other versions link to -lSDL2main which\n# this module will try to find on your behalf.) Also for OS X, this\n# module will automatically add the -framework Cocoa on your behalf.\n#\n#\n# Additional Note: If you see an empty SDL2_LIBRARY_TEMP in your configuration\n# and no SDL2_LIBRARY, it means CMake did not find your SDL2 library\n# (SDL2.dll, libsdl2.so, SDL2.framework, etc).\n# Set SDL2_LIBRARY_TEMP to point to your SDL2 library, and configure again.\n# Similarly, if you see an empty SDL2MAIN_LIBRARY, you should set this value\n# as appropriate. These values are used to generate the final SDL2_LIBRARY\n# variable, but when these values are unset, SDL2_LIBRARY does not get created.\n#\n#\n# $SDL2DIR is an environment variable that would\n# correspond to the ./configure --prefix=$SDL2DIR\n# used in building SDL2.\n# l.e.galup  9-20-02\n#\n# Modified by Eric Wing.\n# Added code to assist with automated building by using environmental variables\n# and providing a more controlled/consistent search behavior.\n# Added new modifications to recognize OS X frameworks and\n# additional Unix paths (FreeBSD, etc).\n# Also corrected the header search path to follow \"proper\" SDL guidelines.\n# Added a search for SDL2main which is needed by some platforms.\n# Added a search for threads which is needed by some platforms.\n# Added needed compile switches for MinGW.\n#\n# On OSX, this will prefer the Framework version (if found) over others.\n# People will have to manually change the cache values of\n# SDL2_LIBRARY to override this selection or set the CMake environment\n# CMAKE_INCLUDE_PATH to modify the search paths.\n#\n# Note that the header path has changed from SDL2/SDL.h to just SDL.h\n# This needed to change because \"proper\" SDL convention\n# is #include \"SDL.h\", not <SDL2/SDL.h>. This is done for portability\n# reasons because not all systems place things in SDL2/ (see FreeBSD).\n\n#=============================================================================\n# Copyright 2003-2009 Kitware, Inc.\n#\n# Distributed under the OSI-approved BSD License (the \"License\");\n# see accompanying file Copyright.txt for details.\n#\n# This software is distributed WITHOUT ANY WARRANTY; without even the\n# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the License for more information.\n#=============================================================================\n# (To distribute this file outside of CMake, substitute the full\n#  License text for the above reference.)\n\n# message(\"<FindSDL2.cmake>\")\n\nSET(SDL2_SEARCH_PATHS\n\t~/Library/Frameworks\n\t/Library/Frameworks\n\t/usr/local\n\t/usr\n\t/sw # Fink\n\t/opt/local # DarwinPorts\n\t/opt/csw # Blastwave\n\t/opt\n\t${SDL2_PATH}\n)\n\nFIND_PATH(SDL2_INCLUDE_DIR SDL.h\n\tHINTS\n\t$ENV{SDL2DIR}\n\tPATH_SUFFIXES include/SDL2 include\n\tPATHS ${SDL2_SEARCH_PATHS}\n)\n\nif(CMAKE_SIZEOF_VOID_P EQUAL 8) \n\tset(PATH_SUFFIXES lib64 lib/x64 lib)\nelse() \n\tset(PATH_SUFFIXES lib/x86 lib)\nendif() \n\nFIND_LIBRARY(SDL2_LIBRARY_TEMP\n\tNAMES SDL2\n\tHINTS\n\t$ENV{SDL2DIR}\n\tPATH_SUFFIXES ${PATH_SUFFIXES}\n\tPATHS ${SDL2_SEARCH_PATHS}\n)\n\nIF(NOT SDL2_BUILDING_LIBRARY)\n\tIF(NOT ${SDL2_INCLUDE_DIR} MATCHES \".framework\")\n\t\t# Non-OS X framework versions expect you to also dynamically link to\n\t\t# SDL2main. This is mainly for Windows and OS X. Other (Unix) platforms\n\t\t# seem to provide SDL2main for compatibility even though they don't\n\t\t# necessarily need it.\n\t\tFIND_LIBRARY(SDL2MAIN_LIBRARY\n\t\t\tNAMES SDL2main\n\t\t\tHINTS\n\t\t\t$ENV{SDL2DIR}\n\t\t\tPATH_SUFFIXES ${PATH_SUFFIXES}\n\t\t\tPATHS ${SDL2_SEARCH_PATHS}\n\t\t)\n\tENDIF(NOT ${SDL2_INCLUDE_DIR} MATCHES \".framework\")\nENDIF(NOT SDL2_BUILDING_LIBRARY)\n\n# SDL2 may require threads on your system.\n# The Apple build may not need an explicit flag because one of the\n# frameworks may already provide it.\n# But for non-OSX systems, I will use the CMake Threads package.\nIF(NOT APPLE)\n\tFIND_PACKAGE(Threads)\nENDIF(NOT APPLE)\n\n# MinGW needs an additional link flag, -mwindows\n# It's total link flags should look like -lmingw32 -lSDL2main -lSDL2 -mwindows\nIF(MINGW)\n\tSET(MINGW32_LIBRARY mingw32 \"-mwindows\" CACHE STRING \"mwindows for MinGW\")\nENDIF(MINGW)\n\nIF(SDL2_LIBRARY_TEMP)\n\t# For SDL2main\n\tIF(NOT SDL2_BUILDING_LIBRARY)\n\t\tIF(SDL2MAIN_LIBRARY)\n\t\t\tSET(SDL2_LIBRARY_TEMP ${SDL2MAIN_LIBRARY} ${SDL2_LIBRARY_TEMP})\n\t\tENDIF(SDL2MAIN_LIBRARY)\n\tENDIF(NOT SDL2_BUILDING_LIBRARY)\n\n\t# For OS X, SDL2 uses Cocoa as a backend so it must link to Cocoa.\n\t# CMake doesn't display the -framework Cocoa string in the UI even\n\t# though it actually is there if I modify a pre-used variable.\n\t# I think it has something to do with the CACHE STRING.\n\t# So I use a temporary variable until the end so I can set the\n\t# \"real\" variable in one-shot.\n\tIF(APPLE)\n\t\tSET(SDL2_LIBRARY_TEMP ${SDL2_LIBRARY_TEMP} \"-framework Cocoa\")\n\tENDIF(APPLE)\n\n\t# For threads, as mentioned Apple doesn't need this.\n\t# In fact, there seems to be a problem if I used the Threads package\n\t# and try using this line, so I'm just skipping it entirely for OS X.\n\tIF(NOT APPLE)\n\t\tSET(SDL2_LIBRARY_TEMP ${SDL2_LIBRARY_TEMP} ${CMAKE_THREAD_LIBS_INIT})\n\tENDIF(NOT APPLE)\n\n\t# For MinGW library\n\tIF(MINGW)\n\t\tSET(SDL2_LIBRARY_TEMP ${MINGW32_LIBRARY} ${SDL2_LIBRARY_TEMP})\n\tENDIF(MINGW)\n\n\t# Set the final string here so the GUI reflects the final state.\n\tSET(SDL2_LIBRARY ${SDL2_LIBRARY_TEMP} CACHE STRING \"Where the SDL2 Library can be found\")\n\t# Set the temp variable to INTERNAL so it is not seen in the CMake GUI\n\tSET(SDL2_LIBRARY_TEMP \"${SDL2_LIBRARY_TEMP}\" CACHE INTERNAL \"\")\nENDIF(SDL2_LIBRARY_TEMP)\n\n# message(\"</FindSDL2.cmake>\")\n\nINCLUDE(FindPackageHandleStandardArgs)\n\nFIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2 REQUIRED_VARS SDL2_LIBRARY SDL2_INCLUDE_DIR)\n"
  },
  {
    "path": "projects/cmake/FindSDL2_image.cmake",
    "content": "# Locate SDL_image library\n#\n# This module defines:\n#\n# ::\n#\n#   SDL2_IMAGE_LIBRARIES, the name of the library to link against\n#   SDL2_IMAGE_INCLUDE_DIRS, where to find the headers\n#   SDL2_IMAGE_FOUND, if false, do not try to link against\n#   SDL2_IMAGE_VERSION_STRING - human-readable string containing the version of SDL_image\n#\n#\n#\n# For backward compatibility the following variables are also set:\n#\n# ::\n#\n#   SDLIMAGE_LIBRARY (same value as SDL2_IMAGE_LIBRARIES)\n#   SDLIMAGE_INCLUDE_DIR (same value as SDL2_IMAGE_INCLUDE_DIRS)\n#   SDLIMAGE_FOUND (same value as SDL2_IMAGE_FOUND)\n#\n#\n#\n# $SDLDIR is an environment variable that would correspond to the\n# ./configure --prefix=$SDLDIR used in building SDL.\n#\n# Created by Eric Wing.  This was influenced by the FindSDL.cmake\n# module, but with modifications to recognize OS X frameworks and\n# additional Unix paths (FreeBSD, etc).\n\n#=============================================================================\n# Copyright 2005-2009 Kitware, Inc.\n# Copyright 2012 Benjamin Eikel\n#\n# Distributed under the OSI-approved BSD License (the \"License\");\n# see accompanying file Copyright.txt for details.\n#\n# This software is distributed WITHOUT ANY WARRANTY; without even the\n# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the License for more information.\n#=============================================================================\n# (To distribute this file outside of CMake, substitute the full\n#  License text for the above reference.)\n\nfind_path(SDL2_IMAGE_INCLUDE_DIR SDL_image.h\n        HINTS\n        ENV SDL2IMAGEDIR\n        ENV SDL2DIR\n        PATH_SUFFIXES SDL2\n        # path suffixes to search inside ENV{SDLDIR}\n        include/SDL2 include\n        PATHS ${SDL2_IMAGE_PATH}\n        )\n\nif(CMAKE_SIZEOF_VOID_P EQUAL 8)\n    set(VC_LIB_PATH_SUFFIX lib/x64)\nelse()\n    set(VC_LIB_PATH_SUFFIX lib/x86)\nendif()\n\nfind_library(SDL2_IMAGE_LIBRARY\n        NAMES SDL2_image\n        HINTS\n        ENV SDL2IMAGEDIR\n        ENV SDL2DIR\n        PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX}\n        PATHS ${SDL2_IMAGE_PATH}\n        )\n\nif(SDL2_IMAGE_INCLUDE_DIR AND EXISTS \"${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h\")\n    file(STRINGS \"${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h\" SDL2_IMAGE_VERSION_MAJOR_LINE REGEX \"^#define[ \\t]+SDL_IMAGE_MAJOR_VERSION[ \\t]+[0-9]+$\")\n    file(STRINGS \"${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h\" SDL2_IMAGE_VERSION_MINOR_LINE REGEX \"^#define[ \\t]+SDL_IMAGE_MINOR_VERSION[ \\t]+[0-9]+$\")\n    file(STRINGS \"${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h\" SDL2_IMAGE_VERSION_PATCH_LINE REGEX \"^#define[ \\t]+SDL_IMAGE_PATCHLEVEL[ \\t]+[0-9]+$\")\n    string(REGEX REPLACE \"^#define[ \\t]+SDL_IMAGE_MAJOR_VERSION[ \\t]+([0-9]+)$\" \"\\\\1\" SDL2_IMAGE_VERSION_MAJOR \"${SDL2_IMAGE_VERSION_MAJOR_LINE}\")\n    string(REGEX REPLACE \"^#define[ \\t]+SDL_IMAGE_MINOR_VERSION[ \\t]+([0-9]+)$\" \"\\\\1\" SDL2_IMAGE_VERSION_MINOR \"${SDL2_IMAGE_VERSION_MINOR_LINE}\")\n    string(REGEX REPLACE \"^#define[ \\t]+SDL_IMAGE_PATCHLEVEL[ \\t]+([0-9]+)$\" \"\\\\1\" SDL2_IMAGE_VERSION_PATCH \"${SDL2_IMAGE_VERSION_PATCH_LINE}\")\n    set(SDL2_IMAGE_VERSION_STRING ${SDL2_IMAGE_VERSION_MAJOR}.${SDL2_IMAGE_VERSION_MINOR}.${SDL2_IMAGE_VERSION_PATCH})\n    unset(SDL2_IMAGE_VERSION_MAJOR_LINE)\n    unset(SDL2_IMAGE_VERSION_MINOR_LINE)\n    unset(SDL2_IMAGE_VERSION_PATCH_LINE)\n    unset(SDL2_IMAGE_VERSION_MAJOR)\n    unset(SDL2_IMAGE_VERSION_MINOR)\n    unset(SDL2_IMAGE_VERSION_PATCH)\nendif()\n\nset(SDL2_IMAGE_LIBRARIES ${SDL2_IMAGE_LIBRARY})\nset(SDL2_IMAGE_INCLUDE_DIRS ${SDL2_IMAGE_INCLUDE_DIR})\n\ninclude(FindPackageHandleStandardArgs)\n\nFIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_image\n        REQUIRED_VARS SDL2_IMAGE_LIBRARIES SDL2_IMAGE_INCLUDE_DIRS\n        VERSION_VAR SDL2_IMAGE_VERSION_STRING)\n\n# for backward compatibility\nset(SDLIMAGE_LIBRARY ${SDL2_IMAGE_LIBRARIES})\nset(SDLIMAGE_INCLUDE_DIR ${SDL2_IMAGE_INCLUDE_DIRS})\nset(SDLIMAGE_FOUND ${SDL2_IMAGE_FOUND})\n\nmark_as_advanced(SDL2_IMAGE_LIBRARY SDL2_IMAGE_INCLUDE_DIR)\n"
  },
  {
    "path": "projects/cmake/FindSDL2_mixer.cmake",
    "content": "# Locate SDL_MIXER library\n#\n# This module defines:\n#\n# ::\n#\n#   SDL2_MIXER_LIBRARIES, the name of the library to link against\n#   SDL2_MIXER_INCLUDE_DIRS, where to find the headers\n#   SDL2_MIXER_FOUND, if false, do not try to link against\n#   SDL2_MIXER_VERSION_STRING - human-readable string containing the version of SDL_MIXER\n#\n#\n#\n# For backward compatibility the following variables are also set:\n#\n# ::\n#\n#   SDLMIXER_LIBRARY (same value as SDL2_MIXER_LIBRARIES)\n#   SDLMIXER_INCLUDE_DIR (same value as SDL2_MIXER_INCLUDE_DIRS)\n#   SDLMIXER_FOUND (same value as SDL2_MIXER_FOUND)\n#\n#\n#\n# $SDLDIR is an environment variable that would correspond to the\n# ./configure --prefix=$SDLDIR used in building SDL.\n#\n# Created by Eric Wing.  This was influenced by the FindSDL.cmake\n# module, but with modifications to recognize OS X frameworks and\n# additional Unix paths (FreeBSD, etc).\n\n#=============================================================================\n# Copyright 2005-2009 Kitware, Inc.\n# Copyright 2012 Benjamin Eikel\n#\n# Distributed under the OSI-approved BSD License (the \"License\");\n# see accompanying file Copyright.txt for details.\n#\n# This software is distributed WITHOUT ANY WARRANTY; without even the\n# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the License for more information.\n#=============================================================================\n# (To distribute this file outside of CMake, substitute the full\n#  License text for the above reference.)\n\nfind_path(SDL2_MIXER_INCLUDE_DIR SDL_mixer.h\n        HINTS\n        ENV SDL2MIXERDIR\n        ENV SDL2DIR\n        PATH_SUFFIXES SDL2\n        # path suffixes to search inside ENV{SDLDIR}\n        include/SDL2 include\n        PATHS ${SDL2_MIXER_PATH}\n        )\n\nif(CMAKE_SIZEOF_VOID_P EQUAL 8)\n    set(VC_LIB_PATH_SUFFIX lib/x64)\nelse()\n    set(VC_LIB_PATH_SUFFIX lib/x86)\nendif()\n\nfind_library(SDL2_MIXER_LIBRARY\n        NAMES SDL2_mixer\n        HINTS\n        ENV SDL2MIXERDIR\n        ENV SDL2DIR\n        PATH_SUFFIXES lib bin ${VC_LIB_PATH_SUFFIX}\n        PATHS ${SDL2_MIXER_PATH}\n        )\n\nif(SDL2_MIXER_INCLUDE_DIR AND EXISTS \"${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h\")\n    file(STRINGS \"${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h\" SDL2_MIXER_VERSION_MAJOR_LINE REGEX \"^#define[ \\t]+SDL_MIXER_MAJOR_VERSION[ \\t]+[0-9]+$\")\n    file(STRINGS \"${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h\" SDL2_MIXER_VERSION_MINOR_LINE REGEX \"^#define[ \\t]+SDL_MIXER_MINOR_VERSION[ \\t]+[0-9]+$\")\n    file(STRINGS \"${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h\" SDL2_MIXER_VERSION_PATCH_LINE REGEX \"^#define[ \\t]+SDL_MIXER_PATCHLEVEL[ \\t]+[0-9]+$\")\n    string(REGEX REPLACE \"^#define[ \\t]+SDL_MIXER_MAJOR_VERSION[ \\t]+([0-9]+)$\" \"\\\\1\" SDL2_MIXER_VERSION_MAJOR \"${SDL2_MIXER_VERSION_MAJOR_LINE}\")\n    string(REGEX REPLACE \"^#define[ \\t]+SDL_MIXER_MINOR_VERSION[ \\t]+([0-9]+)$\" \"\\\\1\" SDL2_MIXER_VERSION_MINOR \"${SDL2_MIXER_VERSION_MINOR_LINE}\")\n    string(REGEX REPLACE \"^#define[ \\t]+SDL_MIXER_PATCHLEVEL[ \\t]+([0-9]+)$\" \"\\\\1\" SDL2_MIXER_VERSION_PATCH \"${SDL2_MIXER_VERSION_PATCH_LINE}\")\n    set(SDL2_MIXER_VERSION_STRING ${SDL2_MIXER_VERSION_MAJOR}.${SDL2_MIXER_VERSION_MINOR}.${SDL2_MIXER_VERSION_PATCH})\n    unset(SDL2_MIXER_VERSION_MAJOR_LINE)\n    unset(SDL2_MIXER_VERSION_MINOR_LINE)\n    unset(SDL2_MIXER_VERSION_PATCH_LINE)\n    unset(SDL2_MIXER_VERSION_MAJOR)\n    unset(SDL2_MIXER_VERSION_MINOR)\n    unset(SDL2_MIXER_VERSION_PATCH)\nendif()\n\nset(SDL2_MIXER_LIBRARIES ${SDL2_MIXER_LIBRARY})\nset(SDL2_MIXER_INCLUDE_DIRS ${SDL2_MIXER_INCLUDE_DIR})\n\ninclude(FindPackageHandleStandardArgs)\n\nFIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_mixer\n        REQUIRED_VARS SDL2_MIXER_LIBRARIES SDL2_MIXER_INCLUDE_DIRS\n        VERSION_VAR SDL2_MIXER_VERSION_STRING)\n\n# for backward compatibility\nset(SDLMIXER_LIBRARY ${SDL2_MIXER_LIBRARIES})\nset(SDLMIXER_INCLUDE_DIR ${SDL2_MIXER_INCLUDE_DIRS})\nset(SDLMIXER_FOUND ${SDL2_MIXER_FOUND})\n\nmark_as_advanced(SDL2_MIXER_LIBRARY SDL2_MIXER_INCLUDE_DIR)\n"
  },
  {
    "path": "projects/cmake/FindSDL2_ttf.cmake",
    "content": "# Locate SDL_ttf library\n#\n# This module defines:\n#\n# ::\n#\n#   SDL2_TTF_LIBRARIES, the name of the library to link against\n#   SDL2_TTF_INCLUDE_DIRS, where to find the headers\n#   SDL2_TTF_FOUND, if false, do not try to link against\n#   SDL2_TTF_VERSION_STRING - human-readable string containing the version of SDL_ttf\n#\n#\n#\n# For backward compatibility the following variables are also set:\n#\n# ::\n#\n#   SDLTTF_LIBRARY (same value as SDL2_TTF_LIBRARIES)\n#   SDLTTF_INCLUDE_DIR (same value as SDL2_TTF_INCLUDE_DIRS)\n#   SDLTTF_FOUND (same value as SDL2_TTF_FOUND)\n#\n#\n#\n# $SDLDIR is an environment variable that would correspond to the\n# ./configure --prefix=$SDLDIR used in building SDL.\n#\n# Created by Eric Wing.  This was influenced by the FindSDL.cmake\n# module, but with modifications to recognize OS X frameworks and\n# additional Unix paths (FreeBSD, etc).\n\n#=============================================================================\n# Copyright 2005-2009 Kitware, Inc.\n# Copyright 2012 Benjamin Eikel\n#\n# Distributed under the OSI-approved BSD License (the \"License\");\n# see accompanying file Copyright.txt for details.\n#\n# This software is distributed WITHOUT ANY WARRANTY; without even the\n# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the License for more information.\n#=============================================================================\n# (To distribute this file outside of CMake, substitute the full\n#  License text for the above reference.)\n\nfind_path(SDL2_TTF_INCLUDE_DIR SDL_ttf.h\n        HINTS\n        ENV SDL2TTFDIR\n        ENV SDL2DIR\n        PATH_SUFFIXES SDL2\n        # path suffixes to search inside ENV{SDLDIR}\n        include/SDL2 include\n        PATHS ${SDL2_TTF_PATH}\n        )\n\nif (CMAKE_SIZEOF_VOID_P EQUAL 8)\n    set(VC_LIB_PATH_SUFFIX lib/x64)\nelse ()\n    set(VC_LIB_PATH_SUFFIX lib/x86)\nendif ()\n\nfind_library(SDL2_TTF_LIBRARY\n        NAMES SDL2_ttf\n        HINTS\n        ENV SDL2TTFDIR\n        ENV SDL2DIR\n        PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX}\n        PATHS ${SDL2_TTF_PATH}\n        )\n\nif (SDL2_TTF_INCLUDE_DIR AND EXISTS \"${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h\")\n    file(STRINGS \"${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h\" SDL2_TTF_VERSION_MAJOR_LINE REGEX \"^#define[ \\t]+SDL_TTF_MAJOR_VERSION[ \\t]+[0-9]+$\")\n    file(STRINGS \"${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h\" SDL2_TTF_VERSION_MINOR_LINE REGEX \"^#define[ \\t]+SDL_TTF_MINOR_VERSION[ \\t]+[0-9]+$\")\n    file(STRINGS \"${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h\" SDL2_TTF_VERSION_PATCH_LINE REGEX \"^#define[ \\t]+SDL_TTF_PATCHLEVEL[ \\t]+[0-9]+$\")\n    string(REGEX REPLACE \"^#define[ \\t]+SDL_TTF_MAJOR_VERSION[ \\t]+([0-9]+)$\" \"\\\\1\" SDL2_TTF_VERSION_MAJOR \"${SDL2_TTF_VERSION_MAJOR_LINE}\")\n    string(REGEX REPLACE \"^#define[ \\t]+SDL_TTF_MINOR_VERSION[ \\t]+([0-9]+)$\" \"\\\\1\" SDL2_TTF_VERSION_MINOR \"${SDL2_TTF_VERSION_MINOR_LINE}\")\n    string(REGEX REPLACE \"^#define[ \\t]+SDL_TTF_PATCHLEVEL[ \\t]+([0-9]+)$\" \"\\\\1\" SDL2_TTF_VERSION_PATCH \"${SDL2_TTF_VERSION_PATCH_LINE}\")\n    set(SDL2_TTF_VERSION_STRING ${SDL2_TTF_VERSION_MAJOR}.${SDL2_TTF_VERSION_MINOR}.${SDL2_TTF_VERSION_PATCH})\n    unset(SDL2_TTF_VERSION_MAJOR_LINE)\n    unset(SDL2_TTF_VERSION_MINOR_LINE)\n    unset(SDL2_TTF_VERSION_PATCH_LINE)\n    unset(SDL2_TTF_VERSION_MAJOR)\n    unset(SDL2_TTF_VERSION_MINOR)\n    unset(SDL2_TTF_VERSION_PATCH)\nendif ()\n\nset(SDL2_TTF_LIBRARIES ${SDL2_TTF_LIBRARY})\nset(SDL2_TTF_INCLUDE_DIRS ${SDL2_TTF_INCLUDE_DIR})\n\ninclude(FindPackageHandleStandardArgs)\n\nFIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_ttf\n        REQUIRED_VARS SDL2_TTF_LIBRARIES SDL2_TTF_INCLUDE_DIRS\n        VERSION_VAR SDL2_TTF_VERSION_STRING)\n\n# for backward compatibility\nset(SDLTTF_LIBRARY ${SDL2_TTF_LIBRARIES})\nset(SDLTTF_INCLUDE_DIR ${SDL2_TTF_INCLUDE_DIRS})\nset(SDLTTF_FOUND ${SDL2_TTF_FOUND})\n"
  },
  {
    "path": "projects/cmake/readme.md",
    "content": "\nThis repository contains CMake scripts for finding the `SDL2`, `SDL2_image` and\n`SDL2_ttf` libraries and headers.\n\nCMake itself comes with corresponding scripts for SDL 1.2, which hopefully in\ntime will be updated for SDL2 and make this repo redundant. In the mean\ntime, I'm putting them up here in case anyone else finds them useful.\n\nI've tested them on Linux and Mac OS using the Makefile and XCode targets.\nOn Linux, you'll need the SDL2 development packages installed from your distro\npackage manager. On Mac OS you can install the development frameworks\nfrom the SDL website or alternatively, if you use Homebrew you can run\n`brew install sdl2` to install the development packages.\n\n## Usage\n\n### General\n\nIn order to use these scripts, you first need to tell CMake where to find them, via\nthe `CMAKE_MODULE_PATH` variable. For example, if you put them in a\nsubdirectory called `cmake`, then in your root `CMakeLists.txt` add the line\n\n```cmake\nset(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} \"${project_SOURCE_DIR}/cmake\")\n```\n\nwhere `project` is the name of your project. You can then use the packages\nthemselves by adding\n\n```cmake\nfind_package(SDL2 REQUIRED)\nfind_package(SDL2_image REQUIRED)\nfind_package(SDL2_ttf REQUIRED)\n\ninclude_directories(${SDL2_INCLUDE_DIR}\n                    ${SDL2_IMAGE_INCLUDE_DIR}\n                    ${SDL2_TTF_INCLUDE_DIR})\ntarget_link_libraries(target ${SDL2_LIBRARY}\n                             ${SDL2_IMAGE_LIBRARIES}\n                             ${SDL2_TTF_LIBRARIES})\n\n```\n\nor whatever is appropriate for your project.\n\n### mingw32 / msys\n\nThis section supplements ```Usage -> General``` section. You still are required\nto incorporate ```General``` configuration settings in you CMakeLists.txt.\n\nBecause cmake binaries for windows aren't aware of *nix/win paths conversion,\ndefault paths FindSDL2 will look in won't do any good. For that you should set SDL2_PATH variable.\nFor example:\n```cmake\nset(SDL2_PATH \"D:\\\\apps\\\\SDL2\\\\i686-w64-mingw32\")\n```\n\n```bash\nmkdir build\ncd build\ncmake .. -G\"MSYS Makefiles\"\nmake\n```\n\n\n## Licence\n\nI am not the original author of these scripts. I found `FindSDL2.cmake`\nafter some Googling, and hacked up the `image` and `ttf` scripts from the\nSDL1 versions that come with CMake. The original scripts, and my changes,\nare released under the two-clause BSD licence.\n\n## Bugs\n\nThese scripts are provided in the hope that you might find them useful. They\nwork for me and hopefully they'll work for you too. If you fix any\nissues with them then I'd appreciate a pull request so other\nusers can get your fixes too, but that's up to you :-).\n\n\n"
  },
  {
    "path": "projects/vs2017/.gitignore",
    "content": "*.png\n*.dll\n*.p8"
  },
  {
    "path": "projects/vs2017/retro8/api.lua",
    "content": "function all(t)\n  if t ~= nil then\n    local nt = {}\n    local ni = 1\n    for _,v in pairs(t) do\n      nt[ni] = v\n      ni = ni + 1\n    end\n    for k,v in pairs(nt) do\n    end\n\n    local i = 0\n    return function() i = i + 1; return nt[i] end\n  end\n  return function() end\nend\n\nfunction add(t, v)\n  if t ~= nil then\n    t[#t+1] = v\n  end\n  return t\nend\n\nfunction foreach(c, f)\n  if c ~= nil then\n    for key, value in ipairs(c) do\n      f(value)\n    end\n  end\nend\n\n\nfunction mapdraw(...)\n  map(table.unpack(arg))\nend\n\nfunction count(t)\n  if t ~= nil then\n    return #t\n  end\nend\n\n-- check semantics\nfunction del(t, v)\n  if t ~= nil then\n    local found = false\n    for i = 1, #t do\n      if t[i] == v then\n        found = true\n      end\n      if found then\n        t[i] = t[i+1]\n      end\n    end\n  end\nend\n\nfunction cocreate(f)\n  return coroutine.create(f)\nend\n\nfunction yield()\n  coroutine.yield()\nend\n\n-- TODO: missing vararg\nfunction coresume(f)\n  return coroutine.resume(f)\nend\n\nfunction costatus(f)\n  return coroutine.status(f)\nend"
  },
  {
    "path": "projects/vs2017/retro8/libretro.vcxproj",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project DefaultTargets=\"Build\" ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup Label=\"ProjectConfigurations\">\r\n    <ProjectConfiguration Include=\"Debug|x64\">\r\n      <Configuration>Debug</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Release|x64\">\r\n      <Configuration>Release</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n  </ItemGroup>\r\n  <PropertyGroup Label=\"Globals\">\r\n    <VCProjectVersion>15.0</VCProjectVersion>\r\n    <ProjectGuid>{0E0E60BF-5A2C-4690-9E9A-6990DA1715B4}</ProjectGuid>\r\n    <RootNamespace>libretro</RootNamespace>\r\n    <WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>\r\n    <ProjectName>libretro</ProjectName>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\r\n    <UseDebugLibraries>true</UseDebugLibraries>\r\n    <PlatformToolset>v141</PlatformToolset>\r\n    <CharacterSet>MultiByte</CharacterSet>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\r\n    <UseDebugLibraries>false</UseDebugLibraries>\r\n    <PlatformToolset>v141</PlatformToolset>\r\n    <WholeProgramOptimization>true</WholeProgramOptimization>\r\n    <CharacterSet>MultiByte</CharacterSet>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\r\n  <ImportGroup Label=\"ExtensionSettings\">\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"Shared\">\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <PropertyGroup Label=\"UserMacros\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <TargetName>retro8_libretro</TargetName>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <TargetName>retro8_libretro</TargetName>\r\n  </PropertyGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <ClCompile>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <Optimization>MaxSpeed</Optimization>\r\n      <FunctionLevelLinking>true</FunctionLevelLinking>\r\n      <IntrinsicFunctions>true</IntrinsicFunctions>\r\n      <SDLCheck>true</SDLCheck>\r\n      <ConformanceMode>true</ConformanceMode>\r\n      <AdditionalIncludeDirectories>$(SolutionDir)../../../src</AdditionalIncludeDirectories>\r\n      <PreprocessorDefinitions>__LIBRETRO__;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n    </ClCompile>\r\n    <Link>\r\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r\n      <OptimizeReferences>true</OptimizeReferences>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <ClCompile>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <Optimization>Disabled</Optimization>\r\n      <SDLCheck>true</SDLCheck>\r\n      <ConformanceMode>true</ConformanceMode>\r\n      <AdditionalIncludeDirectories>$(SolutionDir)../../../src</AdditionalIncludeDirectories>\r\n      <PreprocessorDefinitions>__LIBRETRO__;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n    </ClCompile>\r\n  </ItemDefinitionGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\loader.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\picopng.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\stegano.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lapi.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lauxlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbaselib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbitlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcode.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcorolib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lctype.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldblib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldebug.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldo.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldump.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lfunc.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lgc.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\linit.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\liolib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\llex.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmathlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmem.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loadlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lobject.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lopcodes.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loslib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lparser.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstate.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstring.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstrlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltable.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltablib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltests.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltm.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lundump.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lutf8lib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lvm.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lzio.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\libretro\\libretro.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\gfx.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\lua_bridge.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\machine.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\memory.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\sound.cpp\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"..\\..\\..\\src\\common.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\config.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\lua_api.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\pico_font.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\loader.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\stegano.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lapi.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lauxlib.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lcode.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lctype.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldebug.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldo.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lfunc.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lgc.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llex.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llimits.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lmem.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lobject.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lopcodes.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lparser.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lprefix.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstate.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstring.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltable.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltests.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltm.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.hpp\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\luaconf.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lualib.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lundump.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lvm.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lzio.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\libretro\\libretro.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\defines.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\gfx.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\input.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\lua_api.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\lua_bridge.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\machine.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\memory.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\pico_font.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\sound.h\" />\r\n  </ItemGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\r\n  <ImportGroup Label=\"ExtensionTargets\">\r\n  </ImportGroup>\r\n</Project>"
  },
  {
    "path": "projects/vs2017/retro8/libretro.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup>\r\n    <Filter Include=\"src\">\r\n      <UniqueIdentifier>{a471f701-0e6a-4004-b161-ca280a2be93a}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\vm\">\r\n      <UniqueIdentifier>{f5eb0eee-f070-4775-8d48-90cef3473e3b}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\io\">\r\n      <UniqueIdentifier>{b05b286e-5e6e-4a96-9f06-fcbcf3fd06c0}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\lua\">\r\n      <UniqueIdentifier>{2368e1b6-dcbf-4a03-9ec7-31a181f8f28a}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\libretro\">\r\n      <UniqueIdentifier>{84f3008f-35b1-4fc8-a328-0386a6107d2b}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\gen\">\r\n      <UniqueIdentifier>{29585708-f023-42b3-ab4f-f94a5094a00a}</UniqueIdentifier>\r\n    </Filter>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\gfx.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\lua_bridge.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\machine.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\memory.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\sound.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\loader.cpp\">\r\n      <Filter>src\\io</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\stegano.cpp\">\r\n      <Filter>src\\io</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lapi.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lauxlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbaselib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbitlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcode.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcorolib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lctype.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldblib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldebug.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldo.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldump.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lfunc.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lgc.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\linit.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\liolib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\llex.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmathlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmem.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loadlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lobject.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lopcodes.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loslib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lparser.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstate.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstring.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstrlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltable.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltablib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltests.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltm.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lundump.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lutf8lib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lvm.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lzio.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\libretro\\libretro.cpp\">\r\n      <Filter>src\\libretro</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\picopng.cpp\">\r\n      <Filter>src\\io</Filter>\r\n    </ClCompile>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"..\\..\\..\\src\\common.h\">\r\n      <Filter>src</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\defines.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\gfx.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\lua_bridge.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\machine.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\memory.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\sound.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\loader.h\">\r\n      <Filter>src\\io</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\stegano.h\">\r\n      <Filter>src\\io</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lapi.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lauxlib.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lcode.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lctype.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldebug.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldo.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lfunc.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lgc.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llex.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llimits.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lmem.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lobject.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lopcodes.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lparser.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lprefix.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstate.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstring.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltable.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltests.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltm.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.hpp\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\luaconf.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lualib.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lundump.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lvm.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lzio.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\libretro\\libretro.h\">\r\n      <Filter>src\\libretro</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\lua_api.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\pico_font.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\input.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\lua_api.h\">\r\n      <Filter>src\\gen</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\pico_font.h\">\r\n      <Filter>src\\gen</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\config.h\">\r\n      <Filter>src</Filter>\r\n    </ClInclude>\r\n  </ItemGroup>\r\n</Project>"
  },
  {
    "path": "projects/vs2017/retro8/retro8-sdl1.2.vcxproj",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project DefaultTargets=\"Build\" ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup Label=\"ProjectConfigurations\">\r\n    <ProjectConfiguration Include=\"Debug|x64\">\r\n      <Configuration>Debug</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Release|x64\">\r\n      <Configuration>Release</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n  </ItemGroup>\r\n  <PropertyGroup Label=\"Globals\">\r\n    <VCProjectVersion>15.0</VCProjectVersion>\r\n    <ProjectGuid>{6AA50535-4009-46CB-9B64-9624BC3F9169}</ProjectGuid>\r\n    <RootNamespace>retro8sdl12</RootNamespace>\r\n    <WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>true</UseDebugLibraries>\r\n    <PlatformToolset>v141</PlatformToolset>\r\n    <CharacterSet>MultiByte</CharacterSet>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>false</UseDebugLibraries>\r\n    <PlatformToolset>v141</PlatformToolset>\r\n    <WholeProgramOptimization>true</WholeProgramOptimization>\r\n    <CharacterSet>MultiByte</CharacterSet>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\r\n  <ImportGroup Label=\"ExtensionSettings\">\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"Shared\">\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <PropertyGroup Label=\"UserMacros\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <OutDir>$(SolutionDir)$(Platform)\\$(ProjectName)-$(Configuration)\\</OutDir>\r\n    <IntDir>$(Platform)\\$(ProjectName)-$(Configuration)\\</IntDir>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <OutDir>$(SolutionDir)$(Platform)\\$(ProjectName)-$(Configuration)\\</OutDir>\r\n    <IntDir>$(Platform)\\$(ProjectName)-$(Configuration)\\</IntDir>\r\n  </PropertyGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <ClCompile>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <Optimization>MaxSpeed</Optimization>\r\n      <FunctionLevelLinking>true</FunctionLevelLinking>\r\n      <IntrinsicFunctions>true</IntrinsicFunctions>\r\n      <SDLCheck>true</SDLCheck>\r\n      <ConformanceMode>true</ConformanceMode>\r\n      <AdditionalIncludeDirectories>D:\\dev\\sdl\\SDL1.2.15\\include;$(SolutionDir)../../../src;D:\\dev\\odreader\\projects\\vs2017\\zlib\\include;D:\\dev\\retro8\\projects\\vs2017\\libs\\lua\\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r\n      <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n    </ClCompile>\r\n    <Link>\r\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r\n      <OptimizeReferences>true</OptimizeReferences>\r\n      <AdditionalDependencies>D:\\dev\\retro8\\projects\\vs2017\\libs\\zlib\\lib\\win_x64\\zlib.lib;D:\\dev\\sdl\\SDL1.2.15\\lib\\x64\\SDL.lib;D:\\dev\\sdl\\SDL1.2.15\\lib\\x64\\SDLmain.lib;%(AdditionalDependencies)</AdditionalDependencies>\r\n      <SubSystem>Console</SubSystem>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <ClCompile>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <Optimization>Disabled</Optimization>\r\n      <SDLCheck>true</SDLCheck>\r\n      <ConformanceMode>true</ConformanceMode>\r\n      <AdditionalIncludeDirectories>D:\\dev\\sdl\\SDL1.2.15\\include;$(SolutionDir)../../../src;D:\\dev\\odreader\\projects\\vs2017\\zlib\\include;C:\\Users\\Jack\\Documents\\dev\\retro-8\\projects\\vs2017\\libs\\lua\\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r\n      <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n    </ClCompile>\r\n    <Link>\r\n      <AdditionalDependencies>D:\\dev\\retro8\\projects\\vs2017\\libs\\zlib\\lib\\win_x64\\zlib.lib;D:\\dev\\sdl\\SDL1.2.15\\lib\\x64\\SDL.lib;D:\\dev\\sdl\\SDL1.2.15\\lib\\x64\\SDLmain.lib;%(AdditionalDependencies)</AdditionalDependencies>\r\n      <SubSystem>Console</SubSystem>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\loader.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\picopng.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\stegano.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lapi.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lauxlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbaselib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbitlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcode.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcorolib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lctype.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldblib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldebug.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldo.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldump.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lfunc.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lgc.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\linit.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\liolib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\llex.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmathlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmem.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loadlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lobject.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lopcodes.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loslib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lparser.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstate.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstring.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstrlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltable.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltablib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltests.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltm.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lundump.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lutf8lib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lvm.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lzio.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\main.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\game_view.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\menu_view.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\view_manager.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\gfx.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\lua_bridge.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\machine.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\memory.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\sound.cpp\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"..\\..\\..\\src\\common.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\config.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\lua_api.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\pico_font.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\loader.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\stegano.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lapi.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lauxlib.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lcode.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lctype.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldebug.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldo.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lfunc.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lgc.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llex.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llimits.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lmem.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lobject.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lopcodes.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lparser.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lprefix.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstate.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstring.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltable.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltests.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltm.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.hpp\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\luaconf.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lualib.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lundump.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lvm.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lzio.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\main_view.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\sdl_helper.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\sdl_impl12.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\view_manager.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\defines.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\gfx.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\input.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\lua_bridge.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\machine.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\memory.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\sound.h\" />\r\n  </ItemGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\r\n  <ImportGroup Label=\"ExtensionTargets\">\r\n  </ImportGroup>\r\n</Project>"
  },
  {
    "path": "projects/vs2017/retro8/retro8-sdl1.2.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup>\r\n    <Filter Include=\"src\">\r\n      <UniqueIdentifier>{42385b49-0ab6-4132-85d7-e32a6d86680a}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\gen\">\r\n      <UniqueIdentifier>{0459b9e3-12af-4756-9b9a-50cd2756d16f}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\io\">\r\n      <UniqueIdentifier>{02b98048-b55c-4da3-b643-d900d371ef7e}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\lua\">\r\n      <UniqueIdentifier>{3ae2ecb6-c5c2-494b-9e27-24734c408507}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\vm\">\r\n      <UniqueIdentifier>{da7a994f-80a9-4361-9d36-c441cd2c4090}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\views\">\r\n      <UniqueIdentifier>{f916d59d-e58f-46bd-b334-34632fc018a0}</UniqueIdentifier>\r\n    </Filter>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"..\\..\\..\\src\\main.cpp\">\r\n      <Filter>src</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\picopng.cpp\">\r\n      <Filter>src\\io</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\stegano.cpp\">\r\n      <Filter>src\\io</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\loader.cpp\">\r\n      <Filter>src\\io</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcode.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcorolib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lctype.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldblib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldebug.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldo.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldump.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lfunc.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lgc.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\linit.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\liolib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\llex.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmathlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmem.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loadlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lobject.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lopcodes.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loslib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lparser.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstate.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstring.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstrlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltable.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltablib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltests.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltm.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lundump.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lutf8lib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lvm.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lzio.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lapi.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lauxlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbaselib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbitlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\gfx.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\lua_bridge.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\machine.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\memory.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\sound.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\menu_view.cpp\">\r\n      <Filter>src\\views</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\view_manager.cpp\">\r\n      <Filter>src\\views</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\game_view.cpp\">\r\n      <Filter>src\\views</Filter>\r\n    </ClCompile>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"..\\..\\..\\src\\common.h\">\r\n      <Filter>src</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\lua_api.h\">\r\n      <Filter>src\\gen</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\pico_font.h\">\r\n      <Filter>src\\gen</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\stegano.h\">\r\n      <Filter>src\\io</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\loader.h\">\r\n      <Filter>src\\io</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lcode.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lctype.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldebug.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldo.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lfunc.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lgc.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llex.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llimits.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lmem.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lobject.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lopcodes.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lparser.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lprefix.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstate.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstring.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltable.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltests.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltm.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.hpp\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\luaconf.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lualib.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lundump.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lvm.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lzio.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lapi.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lauxlib.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\sound.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\defines.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\gfx.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\input.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\lua_bridge.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\machine.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\memory.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\sdl_helper.h\">\r\n      <Filter>src\\views</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\view_manager.h\">\r\n      <Filter>src\\views</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\main_view.h\">\r\n      <Filter>src\\views</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\sdl_impl12.h\">\r\n      <Filter>src\\views</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\config.h\">\r\n      <Filter>src</Filter>\r\n    </ClInclude>\r\n  </ItemGroup>\r\n</Project>"
  },
  {
    "path": "projects/vs2017/retro8/retro8.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 15\nVisualStudioVersion = 15.0.28307.421\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"retro8\", \"retro8.vcxproj\", \"{9834F81E-B512-4925-ADA7-746E485735D1}\"\nEndProject\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"libretro\", \"libretro.vcxproj\", \"{0E0E60BF-5A2C-4690-9E9A-6990DA1715B4}\"\nEndProject\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"retro8-sdl1.2\", \"retro8-sdl1.2.vcxproj\", \"{6AA50535-4009-46CB-9B64-9624BC3F9169}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|x64 = Debug|x64\n\t\tRelease|x64 = Release|x64\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{9834F81E-B512-4925-ADA7-746E485735D1}.Debug|x64.ActiveCfg = Debug|x64\n\t\t{9834F81E-B512-4925-ADA7-746E485735D1}.Debug|x64.Build.0 = Debug|x64\n\t\t{9834F81E-B512-4925-ADA7-746E485735D1}.Release|x64.ActiveCfg = Release|x64\n\t\t{9834F81E-B512-4925-ADA7-746E485735D1}.Release|x64.Build.0 = Release|x64\n\t\t{0E0E60BF-5A2C-4690-9E9A-6990DA1715B4}.Debug|x64.ActiveCfg = Debug|x64\n\t\t{0E0E60BF-5A2C-4690-9E9A-6990DA1715B4}.Debug|x64.Build.0 = Debug|x64\n\t\t{0E0E60BF-5A2C-4690-9E9A-6990DA1715B4}.Release|x64.ActiveCfg = Release|x64\n\t\t{0E0E60BF-5A2C-4690-9E9A-6990DA1715B4}.Release|x64.Build.0 = Release|x64\n\t\t{6AA50535-4009-46CB-9B64-9624BC3F9169}.Debug|x64.ActiveCfg = Debug|x64\n\t\t{6AA50535-4009-46CB-9B64-9624BC3F9169}.Debug|x64.Build.0 = Debug|x64\n\t\t{6AA50535-4009-46CB-9B64-9624BC3F9169}.Release|x64.ActiveCfg = Release|x64\n\t\t{6AA50535-4009-46CB-9B64-9624BC3F9169}.Release|x64.Build.0 = Release|x64\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {C9B2834F-9565-43CC-82A8-40713A7448F4}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "projects/vs2017/retro8/retro8.vcxproj",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project DefaultTargets=\"Build\" ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup Label=\"ProjectConfigurations\">\r\n    <ProjectConfiguration Include=\"Debug|x64\">\r\n      <Configuration>Debug</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Release|x64\">\r\n      <Configuration>Release</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n  </ItemGroup>\r\n  <PropertyGroup Label=\"Globals\">\r\n    <VCProjectVersion>15.0</VCProjectVersion>\r\n    <ProjectGuid>{9834F81E-B512-4925-ADA7-746E485735D1}</ProjectGuid>\r\n    <RootNamespace>odcalc</RootNamespace>\r\n    <WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>true</UseDebugLibraries>\r\n    <PlatformToolset>v141</PlatformToolset>\r\n    <CharacterSet>MultiByte</CharacterSet>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>false</UseDebugLibraries>\r\n    <PlatformToolset>v141</PlatformToolset>\r\n    <WholeProgramOptimization>true</WholeProgramOptimization>\r\n    <CharacterSet>MultiByte</CharacterSet>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\r\n  <ImportGroup Label=\"ExtensionSettings\">\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"Shared\">\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <PropertyGroup Label=\"UserMacros\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <OutDir>$(SolutionDir)$(Platform)\\$(ProjectName)-$(Configuration)\\</OutDir>\r\n    <IntDir>$(Platform)\\$(ProjectName)-$(Configuration)\\</IntDir>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <OutDir>$(SolutionDir)$(Platform)\\$(ProjectName)-$(Configuration)\\</OutDir>\r\n    <IntDir>$(Platform)\\$(ProjectName)-$(Configuration)\\</IntDir>\r\n  </PropertyGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <ClCompile>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <Optimization>Disabled</Optimization>\r\n      <SDLCheck>true</SDLCheck>\r\n      <ConformanceMode>true</ConformanceMode>\r\n      <AdditionalIncludeDirectories>D:\\dev\\openmom\\libs\\sdl2\\win\\include;D:\\dev\\sdl\\SDL2_ttf\\include;$(SolutionDir)../../../src;D:\\dev\\odreader\\projects\\vs2017\\zlib\\include;C:\\Users\\Jack\\Documents\\dev\\retro-8\\projects\\vs2017\\libs\\lua\\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r\n      <LanguageStandard>stdcpp17</LanguageStandard>\r\n      <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n    </ClCompile>\r\n    <Link>\r\n      <AdditionalDependencies>D:\\dev\\openmom\\libs\\sdl2\\win\\lib\\x64\\SDL2.lib;D:\\dev\\openmom\\libs\\sdl2\\win\\lib\\x64\\SDL2main.lib;D:\\dev/retro8\\projects\\vs2017\\libs\\zlib\\lib\\win_x64\\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>\r\n      <SubSystem>Console</SubSystem>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <ClCompile>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <Optimization>MaxSpeed</Optimization>\r\n      <FunctionLevelLinking>true</FunctionLevelLinking>\r\n      <IntrinsicFunctions>true</IntrinsicFunctions>\r\n      <SDLCheck>true</SDLCheck>\r\n      <ConformanceMode>true</ConformanceMode>\r\n      <AdditionalIncludeDirectories>D:\\dev\\openmom\\libs\\sdl2\\win\\include;D:\\dev\\sdl\\SDL2_ttf\\include;$(SolutionDir)../../../src;D:\\dev\\odreader\\projects\\vs2017\\zlib\\include;C:\\Users\\Jack\\Documents\\dev\\retro-8\\projects\\vs2017\\libs\\lua\\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r\n      <LanguageStandard>stdcpp17</LanguageStandard>\r\n      <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n    </ClCompile>\r\n    <Link>\r\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r\n      <OptimizeReferences>true</OptimizeReferences>\r\n      <AdditionalDependencies>D:\\dev\\openmom\\libs\\sdl2\\win\\lib\\x64\\SDL2.lib;D:\\dev\\openmom\\libs\\sdl2\\win\\lib\\x64\\SDL2main.lib;D:\\dev/retro8\\projects\\vs2017\\libs\\zlib\\lib\\win_x64\\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>\r\n      <SubSystem>Console</SubSystem>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\loader.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\picopng.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\stegano.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lapi.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lauxlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbaselib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbitlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcode.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcorolib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lctype.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldblib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldebug.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldo.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldump.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lfunc.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lgc.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\linit.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\liolib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\llex.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmathlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmem.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loadlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lobject.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lopcodes.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loslib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lparser.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstate.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstring.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstrlib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltable.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltablib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltests.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltm.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lundump.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lutf8lib.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lvm.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lzio.c\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\main.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\test\\test.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\game_view.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\menu_view.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\view_manager.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\gfx.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\lua_bridge.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\machine.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\memory.cpp\" />\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\sound.cpp\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"..\\..\\..\\src\\common.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\config.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\lua_api.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\pico_font.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\loader.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\stegano.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lapi.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lauxlib.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lcode.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lctype.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldebug.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldo.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lfunc.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lgc.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llex.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llimits.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lmem.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lobject.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lopcodes.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lparser.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lprefix.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstate.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstring.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltable.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltests.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltm.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.hpp\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\luaconf.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lualib.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lundump.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lvm.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lzio.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\test\\catch.hpp\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\main_view.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\sdl_helper.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\sdl_impl.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\view_manager.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\defines.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\gfx.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\input.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\lua_api.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\lua_bridge.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\machine.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\memory.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\pico_font.h\" />\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\sound.h\" />\r\n  </ItemGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\r\n  <ImportGroup Label=\"ExtensionTargets\">\r\n  </ImportGroup>\r\n</Project>"
  },
  {
    "path": "projects/vs2017/retro8/retro8.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup>\r\n    <Filter Include=\"src\">\r\n      <UniqueIdentifier>{3f009d6b-1e09-4eeb-a437-a4a81b3ab9f9}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\views\">\r\n      <UniqueIdentifier>{27152753-2e36-4acb-81f1-c3410bd2a257}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\vm\">\r\n      <UniqueIdentifier>{6e666e1e-d48a-4580-bc53-58b7673c2cfd}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\io\">\r\n      <UniqueIdentifier>{191051b8-b13d-4e65-a79b-12a98cfc6288}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\test\">\r\n      <UniqueIdentifier>{91c70d3b-3da5-4d36-9075-f3004a94a914}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\lua\">\r\n      <UniqueIdentifier>{b501b260-9d32-44c3-8fa8-7ea19ecaa1c6}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"src\\gen\">\r\n      <UniqueIdentifier>{fae37348-b6e8-4580-a006-48440daab96a}</UniqueIdentifier>\r\n    </Filter>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"..\\..\\..\\src\\common.h\">\r\n      <Filter>src</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\view_manager.h\">\r\n      <Filter>src\\views</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\main_view.h\">\r\n      <Filter>src\\views</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\machine.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\gfx.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\defines.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\lua_bridge.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\loader.h\">\r\n      <Filter>src\\io</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\test\\catch.hpp\">\r\n      <Filter>src\\test</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lcode.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lctype.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldebug.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ldo.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lfunc.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lgc.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llex.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\llimits.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lmem.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lobject.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lopcodes.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lparser.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lprefix.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstate.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lstring.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltable.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltests.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\ltm.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\luaconf.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lualib.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lundump.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lvm.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lzio.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lapi.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lauxlib.h\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\lua\\lua.hpp\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\sound.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\io\\stegano.h\">\r\n      <Filter>src\\io</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\memory.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\lua_api.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\pico_font.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\vm\\input.h\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\sdl_helper.h\">\r\n      <Filter>src\\views</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\pico_font.h\">\r\n      <Filter>src\\gen</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\gen\\lua_api.h\">\r\n      <Filter>src\\gen</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\views\\sdl_impl.h\">\r\n      <Filter>src\\views</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\..\\..\\src\\config.h\">\r\n      <Filter>src</Filter>\r\n    </ClInclude>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"..\\..\\..\\src\\main.cpp\">\r\n      <Filter>src</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\view_manager.cpp\">\r\n      <Filter>src\\views</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\machine.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\gfx.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\lua_bridge.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\loader.cpp\">\r\n      <Filter>src\\io</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\test\\test.cpp\">\r\n      <Filter>src\\test</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\game_view.cpp\">\r\n      <Filter>src\\views</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcorolib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lctype.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldblib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldebug.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldo.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ldump.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lfunc.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lgc.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\linit.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\liolib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\llex.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmem.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loadlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lobject.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lopcodes.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\loslib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lparser.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstate.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstring.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lstrlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltable.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltablib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltests.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\ltm.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lundump.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lutf8lib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lvm.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lzio.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lapi.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lauxlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbaselib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lbitlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lcode.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\lua\\lmathlib.c\">\r\n      <Filter>src\\lua</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\sound.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\stegano.cpp\">\r\n      <Filter>src\\io</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\vm\\memory.cpp\">\r\n      <Filter>src\\vm</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\views\\menu_view.cpp\">\r\n      <Filter>src\\views</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\..\\..\\src\\io\\picopng.cpp\">\r\n      <Filter>src\\io</Filter>\r\n    </ClCompile>\r\n  </ItemGroup>\r\n</Project>"
  },
  {
    "path": "projects/xcode/retro8.xcodeproj/project.pbxproj",
    "content": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 46;\n\tobjects = {\n\n/* Begin PBXBuildFile section */\n\t\t045273B723C3E9CC00F67C90 /* loader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0452735E23C3E9CC00F67C90 /* loader.cpp */; };\n\t\t045273B823C3E9CC00F67C90 /* stegano.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0452736023C3E9CC00F67C90 /* stegano.cpp */; };\n\t\t045273B923C3E9CC00F67C90 /* lapi.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736323C3E9CC00F67C90 /* lapi.c */; };\n\t\t045273BA23C3E9CC00F67C90 /* lauxlib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736523C3E9CC00F67C90 /* lauxlib.c */; };\n\t\t045273BB23C3E9CC00F67C90 /* lbaselib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736723C3E9CC00F67C90 /* lbaselib.c */; };\n\t\t045273BC23C3E9CC00F67C90 /* lbitlib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736823C3E9CC00F67C90 /* lbitlib.c */; };\n\t\t045273BD23C3E9CC00F67C90 /* lcode.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736923C3E9CC00F67C90 /* lcode.c */; };\n\t\t045273BE23C3E9CC00F67C90 /* lcorolib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736B23C3E9CC00F67C90 /* lcorolib.c */; };\n\t\t045273BF23C3E9CC00F67C90 /* lctype.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736C23C3E9CC00F67C90 /* lctype.c */; };\n\t\t045273C023C3E9CC00F67C90 /* ldblib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736E23C3E9CC00F67C90 /* ldblib.c */; };\n\t\t045273C123C3E9CC00F67C90 /* ldebug.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736F23C3E9CC00F67C90 /* ldebug.c */; };\n\t\t045273C223C3E9CC00F67C90 /* ldo.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737123C3E9CC00F67C90 /* ldo.c */; };\n\t\t045273C323C3E9CC00F67C90 /* ldump.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737323C3E9CC00F67C90 /* ldump.c */; };\n\t\t045273C423C3E9CC00F67C90 /* lfunc.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737423C3E9CC00F67C90 /* lfunc.c */; };\n\t\t045273C523C3E9CC00F67C90 /* lgc.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737623C3E9CC00F67C90 /* lgc.c */; };\n\t\t045273C623C3E9CC00F67C90 /* linit.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737823C3E9CC00F67C90 /* linit.c */; };\n\t\t045273C723C3E9CC00F67C90 /* liolib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737923C3E9CC00F67C90 /* liolib.c */; };\n\t\t045273C823C3E9CC00F67C90 /* llex.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737A23C3E9CC00F67C90 /* llex.c */; };\n\t\t045273C923C3E9CC00F67C90 /* lmathlib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737D23C3E9CC00F67C90 /* lmathlib.c */; };\n\t\t045273CA23C3E9CC00F67C90 /* lmem.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737E23C3E9CC00F67C90 /* lmem.c */; };\n\t\t045273CB23C3E9CC00F67C90 /* loadlib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738023C3E9CC00F67C90 /* loadlib.c */; };\n\t\t045273CC23C3E9CC00F67C90 /* lobject.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738123C3E9CC00F67C90 /* lobject.c */; };\n\t\t045273CD23C3E9CC00F67C90 /* lopcodes.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738323C3E9CC00F67C90 /* lopcodes.c */; };\n\t\t045273CE23C3E9CC00F67C90 /* loslib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738523C3E9CC00F67C90 /* loslib.c */; };\n\t\t045273CF23C3E9CC00F67C90 /* lparser.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738623C3E9CC00F67C90 /* lparser.c */; };\n\t\t045273D023C3E9CC00F67C90 /* lstate.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738923C3E9CC00F67C90 /* lstate.c */; };\n\t\t045273D123C3E9CC00F67C90 /* lstring.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738B23C3E9CC00F67C90 /* lstring.c */; };\n\t\t045273D223C3E9CC00F67C90 /* lstrlib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738D23C3E9CC00F67C90 /* lstrlib.c */; };\n\t\t045273D323C3E9CC00F67C90 /* ltable.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738E23C3E9CC00F67C90 /* ltable.c */; };\n\t\t045273D423C3E9CC00F67C90 /* ltablib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739023C3E9CC00F67C90 /* ltablib.c */; };\n\t\t045273D523C3E9CC00F67C90 /* ltests.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739123C3E9CC00F67C90 /* ltests.c */; };\n\t\t045273D623C3E9CC00F67C90 /* ltm.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739323C3E9CC00F67C90 /* ltm.c */; };\n\t\t045273D723C3E9CC00F67C90 /* lundump.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739923C3E9CC00F67C90 /* lundump.c */; };\n\t\t045273D823C3E9CC00F67C90 /* lutf8lib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739B23C3E9CC00F67C90 /* lutf8lib.c */; };\n\t\t045273D923C3E9CC00F67C90 /* lvm.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739C23C3E9CC00F67C90 /* lvm.c */; };\n\t\t045273DA23C3E9CC00F67C90 /* lzio.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739E23C3E9CC00F67C90 /* lzio.c */; };\n\t\t045273DB23C3E9CC00F67C90 /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273A023C3E9CC00F67C90 /* main.cpp */; };\n\t\t045273DD23C3E9CC00F67C90 /* game_view.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273A623C3E9CC00F67C90 /* game_view.cpp */; };\n\t\t045273DE23C3E9CC00F67C90 /* menu_view.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273A823C3E9CC00F67C90 /* menu_view.cpp */; };\n\t\t045273DF23C3E9CC00F67C90 /* view_manager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273A923C3E9CC00F67C90 /* view_manager.cpp */; };\n\t\t045273E023C3E9CC00F67C90 /* gfx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273AD23C3E9CC00F67C90 /* gfx.cpp */; };\n\t\t045273E123C3E9CC00F67C90 /* lua_bridge.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273AF23C3E9CC00F67C90 /* lua_bridge.cpp */; };\n\t\t045273E223C3E9CC00F67C90 /* machine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273B123C3E9CC00F67C90 /* machine.cpp */; };\n\t\t045273E323C3E9CC00F67C90 /* memory.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273B323C3E9CC00F67C90 /* memory.cpp */; };\n\t\t045273E423C3E9CC00F67C90 /* sound.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273B523C3E9CC00F67C90 /* sound.cpp */; };\n\t\t0485411F249216DF003B2EF1 /* libretro.h in Headers */ = {isa = PBXBuildFile; fileRef = 0485411D249216DF003B2EF1 /* libretro.h */; };\n\t\t04854120249216DF003B2EF1 /* libretro.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0485411E249216DF003B2EF1 /* libretro.cpp */; };\n\t\t0485412124921717003B2EF1 /* loader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0452735E23C3E9CC00F67C90 /* loader.cpp */; };\n\t\t0485412224921717003B2EF1 /* stegano.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0452736023C3E9CC00F67C90 /* stegano.cpp */; };\n\t\t0485412424921717003B2EF1 /* gfx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273AD23C3E9CC00F67C90 /* gfx.cpp */; };\n\t\t0485412524921717003B2EF1 /* lua_bridge.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273AF23C3E9CC00F67C90 /* lua_bridge.cpp */; };\n\t\t0485412624921717003B2EF1 /* machine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273B123C3E9CC00F67C90 /* machine.cpp */; };\n\t\t0485412724921717003B2EF1 /* memory.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273B323C3E9CC00F67C90 /* memory.cpp */; };\n\t\t0485412824921717003B2EF1 /* sound.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 045273B523C3E9CC00F67C90 /* sound.cpp */; };\n\t\t0485412C24921739003B2EF1 /* pico_font.h in Headers */ = {isa = PBXBuildFile; fileRef = 0485412A24921739003B2EF1 /* pico_font.h */; };\n\t\t0485412D24921739003B2EF1 /* lua_api.h in Headers */ = {isa = PBXBuildFile; fileRef = 0485412B24921739003B2EF1 /* lua_api.h */; };\n\t\t0485412E249217C6003B2EF1 /* lapi.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736323C3E9CC00F67C90 /* lapi.c */; };\n\t\t0485412F249217C6003B2EF1 /* lauxlib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736523C3E9CC00F67C90 /* lauxlib.c */; };\n\t\t04854130249217C6003B2EF1 /* lbaselib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736723C3E9CC00F67C90 /* lbaselib.c */; };\n\t\t04854131249217C6003B2EF1 /* lbitlib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736823C3E9CC00F67C90 /* lbitlib.c */; };\n\t\t04854132249217C6003B2EF1 /* lcode.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736923C3E9CC00F67C90 /* lcode.c */; };\n\t\t04854133249217C6003B2EF1 /* lcorolib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736B23C3E9CC00F67C90 /* lcorolib.c */; };\n\t\t04854134249217C6003B2EF1 /* lctype.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736C23C3E9CC00F67C90 /* lctype.c */; };\n\t\t04854135249217C6003B2EF1 /* ldblib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736E23C3E9CC00F67C90 /* ldblib.c */; };\n\t\t04854136249217C6003B2EF1 /* ldebug.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452736F23C3E9CC00F67C90 /* ldebug.c */; };\n\t\t04854137249217C6003B2EF1 /* ldo.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737123C3E9CC00F67C90 /* ldo.c */; };\n\t\t04854138249217C6003B2EF1 /* ldump.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737323C3E9CC00F67C90 /* ldump.c */; };\n\t\t04854139249217C6003B2EF1 /* lfunc.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737423C3E9CC00F67C90 /* lfunc.c */; };\n\t\t0485413A249217C6003B2EF1 /* lgc.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737623C3E9CC00F67C90 /* lgc.c */; };\n\t\t0485413B249217C6003B2EF1 /* linit.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737823C3E9CC00F67C90 /* linit.c */; };\n\t\t0485413C249217C6003B2EF1 /* liolib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737923C3E9CC00F67C90 /* liolib.c */; };\n\t\t0485413D249217C6003B2EF1 /* llex.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737A23C3E9CC00F67C90 /* llex.c */; };\n\t\t0485413E249217C6003B2EF1 /* lmathlib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737D23C3E9CC00F67C90 /* lmathlib.c */; };\n\t\t0485413F249217C6003B2EF1 /* lmem.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452737E23C3E9CC00F67C90 /* lmem.c */; };\n\t\t04854140249217C6003B2EF1 /* loadlib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738023C3E9CC00F67C90 /* loadlib.c */; };\n\t\t04854141249217C6003B2EF1 /* lobject.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738123C3E9CC00F67C90 /* lobject.c */; };\n\t\t04854142249217C6003B2EF1 /* lopcodes.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738323C3E9CC00F67C90 /* lopcodes.c */; };\n\t\t04854143249217C6003B2EF1 /* loslib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738523C3E9CC00F67C90 /* loslib.c */; };\n\t\t04854144249217C6003B2EF1 /* lparser.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738623C3E9CC00F67C90 /* lparser.c */; };\n\t\t04854145249217C6003B2EF1 /* lstate.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738923C3E9CC00F67C90 /* lstate.c */; };\n\t\t04854146249217C6003B2EF1 /* lstring.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738B23C3E9CC00F67C90 /* lstring.c */; };\n\t\t04854147249217C6003B2EF1 /* lstrlib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738D23C3E9CC00F67C90 /* lstrlib.c */; };\n\t\t04854148249217C6003B2EF1 /* ltable.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452738E23C3E9CC00F67C90 /* ltable.c */; };\n\t\t04854149249217C6003B2EF1 /* ltablib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739023C3E9CC00F67C90 /* ltablib.c */; };\n\t\t0485414A249217C6003B2EF1 /* ltests.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739123C3E9CC00F67C90 /* ltests.c */; };\n\t\t0485414B249217C6003B2EF1 /* ltm.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739323C3E9CC00F67C90 /* ltm.c */; };\n\t\t0485414C249217C6003B2EF1 /* lundump.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739923C3E9CC00F67C90 /* lundump.c */; };\n\t\t0485414D249217C6003B2EF1 /* lutf8lib.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739B23C3E9CC00F67C90 /* lutf8lib.c */; };\n\t\t0485414E249217C6003B2EF1 /* lvm.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739C23C3E9CC00F67C90 /* lvm.c */; };\n\t\t0485414F249217C6003B2EF1 /* lzio.c in Sources */ = {isa = PBXBuildFile; fileRef = 0452739E23C3E9CC00F67C90 /* lzio.c */; };\n\t\t04854150249217D1003B2EF1 /* picopng.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 04ECF30D23F1631500BA0410 /* picopng.cpp */; };\n\t\t04ECF30E23F1631500BA0410 /* picopng.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 04ECF30D23F1631500BA0410 /* picopng.cpp */; };\n/* End PBXBuildFile section */\n\n/* Begin PBXCopyFilesBuildPhase section */\n\t\t0452734F23C3E98B00F67C90 /* CopyFiles */ = {\n\t\t\tisa = PBXCopyFilesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tdstPath = /usr/share/man/man1/;\n\t\t\tdstSubfolderSpec = 0;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 1;\n\t\t};\n/* End PBXCopyFilesBuildPhase section */\n\n/* Begin PBXFileReference section */\n\t\t0452735123C3E98B00F67C90 /* retro8 */ = {isa = PBXFileReference; explicitFileType = \"compiled.mach-o.executable\"; includeInIndex = 0; path = retro8; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t0452735C23C3E9CC00F67C90 /* common.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = common.h; sourceTree = \"<group>\"; };\n\t\t0452735E23C3E9CC00F67C90 /* loader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = loader.cpp; sourceTree = \"<group>\"; };\n\t\t0452735F23C3E9CC00F67C90 /* loader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = loader.h; sourceTree = \"<group>\"; };\n\t\t0452736023C3E9CC00F67C90 /* stegano.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = stegano.cpp; sourceTree = \"<group>\"; };\n\t\t0452736123C3E9CC00F67C90 /* stegano.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = stegano.h; sourceTree = \"<group>\"; };\n\t\t0452736323C3E9CC00F67C90 /* lapi.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lapi.c; sourceTree = \"<group>\"; };\n\t\t0452736423C3E9CC00F67C90 /* lapi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lapi.h; sourceTree = \"<group>\"; };\n\t\t0452736523C3E9CC00F67C90 /* lauxlib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lauxlib.c; sourceTree = \"<group>\"; };\n\t\t0452736623C3E9CC00F67C90 /* lauxlib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lauxlib.h; sourceTree = \"<group>\"; };\n\t\t0452736723C3E9CC00F67C90 /* lbaselib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lbaselib.c; sourceTree = \"<group>\"; };\n\t\t0452736823C3E9CC00F67C90 /* lbitlib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lbitlib.c; sourceTree = \"<group>\"; };\n\t\t0452736923C3E9CC00F67C90 /* lcode.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lcode.c; sourceTree = \"<group>\"; };\n\t\t0452736A23C3E9CC00F67C90 /* lcode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lcode.h; sourceTree = \"<group>\"; };\n\t\t0452736B23C3E9CC00F67C90 /* lcorolib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lcorolib.c; sourceTree = \"<group>\"; };\n\t\t0452736C23C3E9CC00F67C90 /* lctype.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lctype.c; sourceTree = \"<group>\"; };\n\t\t0452736D23C3E9CC00F67C90 /* lctype.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lctype.h; sourceTree = \"<group>\"; };\n\t\t0452736E23C3E9CC00F67C90 /* ldblib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ldblib.c; sourceTree = \"<group>\"; };\n\t\t0452736F23C3E9CC00F67C90 /* ldebug.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ldebug.c; sourceTree = \"<group>\"; };\n\t\t0452737023C3E9CC00F67C90 /* ldebug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ldebug.h; sourceTree = \"<group>\"; };\n\t\t0452737123C3E9CC00F67C90 /* ldo.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ldo.c; sourceTree = \"<group>\"; };\n\t\t0452737223C3E9CC00F67C90 /* ldo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ldo.h; sourceTree = \"<group>\"; };\n\t\t0452737323C3E9CC00F67C90 /* ldump.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ldump.c; sourceTree = \"<group>\"; };\n\t\t0452737423C3E9CC00F67C90 /* lfunc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lfunc.c; sourceTree = \"<group>\"; };\n\t\t0452737523C3E9CC00F67C90 /* lfunc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lfunc.h; sourceTree = \"<group>\"; };\n\t\t0452737623C3E9CC00F67C90 /* lgc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lgc.c; sourceTree = \"<group>\"; };\n\t\t0452737723C3E9CC00F67C90 /* lgc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lgc.h; sourceTree = \"<group>\"; };\n\t\t0452737823C3E9CC00F67C90 /* linit.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = linit.c; sourceTree = \"<group>\"; };\n\t\t0452737923C3E9CC00F67C90 /* liolib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = liolib.c; sourceTree = \"<group>\"; };\n\t\t0452737A23C3E9CC00F67C90 /* llex.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = llex.c; sourceTree = \"<group>\"; };\n\t\t0452737B23C3E9CC00F67C90 /* llex.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = llex.h; sourceTree = \"<group>\"; };\n\t\t0452737C23C3E9CC00F67C90 /* llimits.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = llimits.h; sourceTree = \"<group>\"; };\n\t\t0452737D23C3E9CC00F67C90 /* lmathlib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lmathlib.c; sourceTree = \"<group>\"; };\n\t\t0452737E23C3E9CC00F67C90 /* lmem.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lmem.c; sourceTree = \"<group>\"; };\n\t\t0452737F23C3E9CC00F67C90 /* lmem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lmem.h; sourceTree = \"<group>\"; };\n\t\t0452738023C3E9CC00F67C90 /* loadlib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = loadlib.c; sourceTree = \"<group>\"; };\n\t\t0452738123C3E9CC00F67C90 /* lobject.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lobject.c; sourceTree = \"<group>\"; };\n\t\t0452738223C3E9CC00F67C90 /* lobject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lobject.h; sourceTree = \"<group>\"; };\n\t\t0452738323C3E9CC00F67C90 /* lopcodes.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lopcodes.c; sourceTree = \"<group>\"; };\n\t\t0452738423C3E9CC00F67C90 /* lopcodes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lopcodes.h; sourceTree = \"<group>\"; };\n\t\t0452738523C3E9CC00F67C90 /* loslib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = loslib.c; sourceTree = \"<group>\"; };\n\t\t0452738623C3E9CC00F67C90 /* lparser.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lparser.c; sourceTree = \"<group>\"; };\n\t\t0452738723C3E9CC00F67C90 /* lparser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lparser.h; sourceTree = \"<group>\"; };\n\t\t0452738823C3E9CC00F67C90 /* lprefix.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lprefix.h; sourceTree = \"<group>\"; };\n\t\t0452738923C3E9CC00F67C90 /* lstate.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lstate.c; sourceTree = \"<group>\"; };\n\t\t0452738A23C3E9CC00F67C90 /* lstate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lstate.h; sourceTree = \"<group>\"; };\n\t\t0452738B23C3E9CC00F67C90 /* lstring.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lstring.c; sourceTree = \"<group>\"; };\n\t\t0452738C23C3E9CC00F67C90 /* lstring.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lstring.h; sourceTree = \"<group>\"; };\n\t\t0452738D23C3E9CC00F67C90 /* lstrlib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lstrlib.c; sourceTree = \"<group>\"; };\n\t\t0452738E23C3E9CC00F67C90 /* ltable.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ltable.c; sourceTree = \"<group>\"; };\n\t\t0452738F23C3E9CC00F67C90 /* ltable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ltable.h; sourceTree = \"<group>\"; };\n\t\t0452739023C3E9CC00F67C90 /* ltablib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ltablib.c; sourceTree = \"<group>\"; };\n\t\t0452739123C3E9CC00F67C90 /* ltests.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ltests.c; sourceTree = \"<group>\"; };\n\t\t0452739223C3E9CC00F67C90 /* ltests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ltests.h; sourceTree = \"<group>\"; };\n\t\t0452739323C3E9CC00F67C90 /* ltm.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ltm.c; sourceTree = \"<group>\"; };\n\t\t0452739423C3E9CC00F67C90 /* ltm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ltm.h; sourceTree = \"<group>\"; };\n\t\t0452739523C3E9CC00F67C90 /* lua.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lua.h; sourceTree = \"<group>\"; };\n\t\t0452739623C3E9CC00F67C90 /* lua.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = lua.hpp; sourceTree = \"<group>\"; };\n\t\t0452739723C3E9CC00F67C90 /* luaconf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = luaconf.h; sourceTree = \"<group>\"; };\n\t\t0452739823C3E9CC00F67C90 /* lualib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lualib.h; sourceTree = \"<group>\"; };\n\t\t0452739923C3E9CC00F67C90 /* lundump.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lundump.c; sourceTree = \"<group>\"; };\n\t\t0452739A23C3E9CC00F67C90 /* lundump.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lundump.h; sourceTree = \"<group>\"; };\n\t\t0452739B23C3E9CC00F67C90 /* lutf8lib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lutf8lib.c; sourceTree = \"<group>\"; };\n\t\t0452739C23C3E9CC00F67C90 /* lvm.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lvm.c; sourceTree = \"<group>\"; };\n\t\t0452739D23C3E9CC00F67C90 /* lvm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lvm.h; sourceTree = \"<group>\"; };\n\t\t0452739E23C3E9CC00F67C90 /* lzio.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lzio.c; sourceTree = \"<group>\"; };\n\t\t0452739F23C3E9CC00F67C90 /* lzio.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lzio.h; sourceTree = \"<group>\"; };\n\t\t045273A023C3E9CC00F67C90 /* main.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = main.cpp; sourceTree = \"<group>\"; };\n\t\t045273A623C3E9CC00F67C90 /* game_view.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = game_view.cpp; sourceTree = \"<group>\"; };\n\t\t045273A723C3E9CC00F67C90 /* main_view.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = main_view.h; sourceTree = \"<group>\"; };\n\t\t045273A823C3E9CC00F67C90 /* menu_view.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = menu_view.cpp; sourceTree = \"<group>\"; };\n\t\t045273A923C3E9CC00F67C90 /* view_manager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = view_manager.cpp; sourceTree = \"<group>\"; };\n\t\t045273AA23C3E9CC00F67C90 /* view_manager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = view_manager.h; sourceTree = \"<group>\"; };\n\t\t045273AC23C3E9CC00F67C90 /* defines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = defines.h; sourceTree = \"<group>\"; };\n\t\t045273AD23C3E9CC00F67C90 /* gfx.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = gfx.cpp; sourceTree = \"<group>\"; };\n\t\t045273AE23C3E9CC00F67C90 /* gfx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = gfx.h; sourceTree = \"<group>\"; };\n\t\t045273AF23C3E9CC00F67C90 /* lua_bridge.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = lua_bridge.cpp; sourceTree = \"<group>\"; };\n\t\t045273B023C3E9CC00F67C90 /* lua_bridge.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lua_bridge.h; sourceTree = \"<group>\"; };\n\t\t045273B123C3E9CC00F67C90 /* machine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = machine.cpp; sourceTree = \"<group>\"; };\n\t\t045273B223C3E9CC00F67C90 /* machine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = machine.h; sourceTree = \"<group>\"; };\n\t\t045273B323C3E9CC00F67C90 /* memory.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = memory.cpp; sourceTree = \"<group>\"; };\n\t\t045273B423C3E9CC00F67C90 /* memory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = memory.h; sourceTree = \"<group>\"; };\n\t\t045273B523C3E9CC00F67C90 /* sound.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = sound.cpp; sourceTree = \"<group>\"; };\n\t\t045273B623C3E9CC00F67C90 /* sound.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sound.h; sourceTree = \"<group>\"; };\n\t\t0485411024921697003B2EF1 /* retro8_libretro.dylib */ = {isa = PBXFileReference; explicitFileType = \"compiled.mach-o.dylib\"; includeInIndex = 0; path = retro8_libretro.dylib; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t0485411D249216DF003B2EF1 /* libretro.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = libretro.h; sourceTree = \"<group>\"; };\n\t\t0485411E249216DF003B2EF1 /* libretro.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = libretro.cpp; sourceTree = \"<group>\"; };\n\t\t0485412A24921739003B2EF1 /* pico_font.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = pico_font.h; sourceTree = \"<group>\"; };\n\t\t0485412B24921739003B2EF1 /* lua_api.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lua_api.h; sourceTree = \"<group>\"; };\n\t\t04ECF30A23E066CC00BA0410 /* sdl_helper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sdl_helper.h; sourceTree = \"<group>\"; };\n\t\t04ECF30D23F1631500BA0410 /* picopng.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = picopng.cpp; sourceTree = \"<group>\"; };\n/* End PBXFileReference section */\n\n/* Begin PBXFrameworksBuildPhase section */\n\t\t0452734E23C3E98B00F67C90 /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t0485410E24921697003B2EF1 /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXFrameworksBuildPhase section */\n\n/* Begin PBXGroup section */\n\t\t0452734823C3E98B00F67C90 = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t0452735B23C3E9CC00F67C90 /* src */,\n\t\t\t\t0452735223C3E98B00F67C90 /* Products */,\n\t\t\t);\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t0452735223C3E98B00F67C90 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t0452735123C3E98B00F67C90 /* retro8 */,\n\t\t\t\t0485411024921697003B2EF1 /* retro8_libretro.dylib */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t0452735B23C3E9CC00F67C90 /* src */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t0452735C23C3E9CC00F67C90 /* common.h */,\n\t\t\t\t0485412924921739003B2EF1 /* gen */,\n\t\t\t\t0485411C249216DF003B2EF1 /* libretro */,\n\t\t\t\t0452735D23C3E9CC00F67C90 /* io */,\n\t\t\t\t0452736223C3E9CC00F67C90 /* lua */,\n\t\t\t\t045273A023C3E9CC00F67C90 /* main.cpp */,\n\t\t\t\t045273A523C3E9CC00F67C90 /* views */,\n\t\t\t\t045273AB23C3E9CC00F67C90 /* vm */,\n\t\t\t);\n\t\t\tname = src;\n\t\t\tpath = ../../src;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t0452735D23C3E9CC00F67C90 /* io */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t04ECF30D23F1631500BA0410 /* picopng.cpp */,\n\t\t\t\t0452735E23C3E9CC00F67C90 /* loader.cpp */,\n\t\t\t\t0452735F23C3E9CC00F67C90 /* loader.h */,\n\t\t\t\t0452736023C3E9CC00F67C90 /* stegano.cpp */,\n\t\t\t\t0452736123C3E9CC00F67C90 /* stegano.h */,\n\t\t\t);\n\t\t\tpath = io;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t0452736223C3E9CC00F67C90 /* lua */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t0452736323C3E9CC00F67C90 /* lapi.c */,\n\t\t\t\t0452736423C3E9CC00F67C90 /* lapi.h */,\n\t\t\t\t0452736523C3E9CC00F67C90 /* lauxlib.c */,\n\t\t\t\t0452736623C3E9CC00F67C90 /* lauxlib.h */,\n\t\t\t\t0452736723C3E9CC00F67C90 /* lbaselib.c */,\n\t\t\t\t0452736823C3E9CC00F67C90 /* lbitlib.c */,\n\t\t\t\t0452736923C3E9CC00F67C90 /* lcode.c */,\n\t\t\t\t0452736A23C3E9CC00F67C90 /* lcode.h */,\n\t\t\t\t0452736B23C3E9CC00F67C90 /* lcorolib.c */,\n\t\t\t\t0452736C23C3E9CC00F67C90 /* lctype.c */,\n\t\t\t\t0452736D23C3E9CC00F67C90 /* lctype.h */,\n\t\t\t\t0452736E23C3E9CC00F67C90 /* ldblib.c */,\n\t\t\t\t0452736F23C3E9CC00F67C90 /* ldebug.c */,\n\t\t\t\t0452737023C3E9CC00F67C90 /* ldebug.h */,\n\t\t\t\t0452737123C3E9CC00F67C90 /* ldo.c */,\n\t\t\t\t0452737223C3E9CC00F67C90 /* ldo.h */,\n\t\t\t\t0452737323C3E9CC00F67C90 /* ldump.c */,\n\t\t\t\t0452737423C3E9CC00F67C90 /* lfunc.c */,\n\t\t\t\t0452737523C3E9CC00F67C90 /* lfunc.h */,\n\t\t\t\t0452737623C3E9CC00F67C90 /* lgc.c */,\n\t\t\t\t0452737723C3E9CC00F67C90 /* lgc.h */,\n\t\t\t\t0452737823C3E9CC00F67C90 /* linit.c */,\n\t\t\t\t0452737923C3E9CC00F67C90 /* liolib.c */,\n\t\t\t\t0452737A23C3E9CC00F67C90 /* llex.c */,\n\t\t\t\t0452737B23C3E9CC00F67C90 /* llex.h */,\n\t\t\t\t0452737C23C3E9CC00F67C90 /* llimits.h */,\n\t\t\t\t0452737D23C3E9CC00F67C90 /* lmathlib.c */,\n\t\t\t\t0452737E23C3E9CC00F67C90 /* lmem.c */,\n\t\t\t\t0452737F23C3E9CC00F67C90 /* lmem.h */,\n\t\t\t\t0452738023C3E9CC00F67C90 /* loadlib.c */,\n\t\t\t\t0452738123C3E9CC00F67C90 /* lobject.c */,\n\t\t\t\t0452738223C3E9CC00F67C90 /* lobject.h */,\n\t\t\t\t0452738323C3E9CC00F67C90 /* lopcodes.c */,\n\t\t\t\t0452738423C3E9CC00F67C90 /* lopcodes.h */,\n\t\t\t\t0452738523C3E9CC00F67C90 /* loslib.c */,\n\t\t\t\t0452738623C3E9CC00F67C90 /* lparser.c */,\n\t\t\t\t0452738723C3E9CC00F67C90 /* lparser.h */,\n\t\t\t\t0452738823C3E9CC00F67C90 /* lprefix.h */,\n\t\t\t\t0452738923C3E9CC00F67C90 /* lstate.c */,\n\t\t\t\t0452738A23C3E9CC00F67C90 /* lstate.h */,\n\t\t\t\t0452738B23C3E9CC00F67C90 /* lstring.c */,\n\t\t\t\t0452738C23C3E9CC00F67C90 /* lstring.h */,\n\t\t\t\t0452738D23C3E9CC00F67C90 /* lstrlib.c */,\n\t\t\t\t0452738E23C3E9CC00F67C90 /* ltable.c */,\n\t\t\t\t0452738F23C3E9CC00F67C90 /* ltable.h */,\n\t\t\t\t0452739023C3E9CC00F67C90 /* ltablib.c */,\n\t\t\t\t0452739123C3E9CC00F67C90 /* ltests.c */,\n\t\t\t\t0452739223C3E9CC00F67C90 /* ltests.h */,\n\t\t\t\t0452739323C3E9CC00F67C90 /* ltm.c */,\n\t\t\t\t0452739423C3E9CC00F67C90 /* ltm.h */,\n\t\t\t\t0452739523C3E9CC00F67C90 /* lua.h */,\n\t\t\t\t0452739623C3E9CC00F67C90 /* lua.hpp */,\n\t\t\t\t0452739723C3E9CC00F67C90 /* luaconf.h */,\n\t\t\t\t0452739823C3E9CC00F67C90 /* lualib.h */,\n\t\t\t\t0452739923C3E9CC00F67C90 /* lundump.c */,\n\t\t\t\t0452739A23C3E9CC00F67C90 /* lundump.h */,\n\t\t\t\t0452739B23C3E9CC00F67C90 /* lutf8lib.c */,\n\t\t\t\t0452739C23C3E9CC00F67C90 /* lvm.c */,\n\t\t\t\t0452739D23C3E9CC00F67C90 /* lvm.h */,\n\t\t\t\t0452739E23C3E9CC00F67C90 /* lzio.c */,\n\t\t\t\t0452739F23C3E9CC00F67C90 /* lzio.h */,\n\t\t\t);\n\t\t\tpath = lua;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t045273A523C3E9CC00F67C90 /* views */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t045273A623C3E9CC00F67C90 /* game_view.cpp */,\n\t\t\t\t045273A723C3E9CC00F67C90 /* main_view.h */,\n\t\t\t\t045273A823C3E9CC00F67C90 /* menu_view.cpp */,\n\t\t\t\t04ECF30A23E066CC00BA0410 /* sdl_helper.h */,\n\t\t\t\t045273A923C3E9CC00F67C90 /* view_manager.cpp */,\n\t\t\t\t045273AA23C3E9CC00F67C90 /* view_manager.h */,\n\t\t\t);\n\t\t\tpath = views;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t045273AB23C3E9CC00F67C90 /* vm */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t045273AC23C3E9CC00F67C90 /* defines.h */,\n\t\t\t\t045273AD23C3E9CC00F67C90 /* gfx.cpp */,\n\t\t\t\t045273AE23C3E9CC00F67C90 /* gfx.h */,\n\t\t\t\t045273AF23C3E9CC00F67C90 /* lua_bridge.cpp */,\n\t\t\t\t045273B023C3E9CC00F67C90 /* lua_bridge.h */,\n\t\t\t\t045273B123C3E9CC00F67C90 /* machine.cpp */,\n\t\t\t\t045273B223C3E9CC00F67C90 /* machine.h */,\n\t\t\t\t045273B323C3E9CC00F67C90 /* memory.cpp */,\n\t\t\t\t045273B423C3E9CC00F67C90 /* memory.h */,\n\t\t\t\t045273B523C3E9CC00F67C90 /* sound.cpp */,\n\t\t\t\t045273B623C3E9CC00F67C90 /* sound.h */,\n\t\t\t);\n\t\t\tpath = vm;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t0485411C249216DF003B2EF1 /* libretro */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t0485411D249216DF003B2EF1 /* libretro.h */,\n\t\t\t\t0485411E249216DF003B2EF1 /* libretro.cpp */,\n\t\t\t);\n\t\t\tpath = libretro;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t0485412924921739003B2EF1 /* gen */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t0485412A24921739003B2EF1 /* pico_font.h */,\n\t\t\t\t0485412B24921739003B2EF1 /* lua_api.h */,\n\t\t\t);\n\t\t\tpath = gen;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXGroup section */\n\n/* Begin PBXHeadersBuildPhase section */\n\t\t0485410C24921697003B2EF1 /* Headers */ = {\n\t\t\tisa = PBXHeadersBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t0485412C24921739003B2EF1 /* pico_font.h in Headers */,\n\t\t\t\t0485412D24921739003B2EF1 /* lua_api.h in Headers */,\n\t\t\t\t0485411F249216DF003B2EF1 /* libretro.h in Headers */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXHeadersBuildPhase section */\n\n/* Begin PBXNativeTarget section */\n\t\t0452735023C3E98B00F67C90 /* retro8 */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 0452735823C3E98B00F67C90 /* Build configuration list for PBXNativeTarget \"retro8\" */;\n\t\t\tbuildPhases = (\n\t\t\t\t0452734D23C3E98B00F67C90 /* Sources */,\n\t\t\t\t0452734E23C3E98B00F67C90 /* Frameworks */,\n\t\t\t\t0452734F23C3E98B00F67C90 /* CopyFiles */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = retro8;\n\t\t\tproductName = retro8;\n\t\t\tproductReference = 0452735123C3E98B00F67C90 /* retro8 */;\n\t\t\tproductType = \"com.apple.product-type.tool\";\n\t\t};\n\t\t0485410F24921697003B2EF1 /* libretro */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 0485411A24921697003B2EF1 /* Build configuration list for PBXNativeTarget \"libretro\" */;\n\t\t\tbuildPhases = (\n\t\t\t\t0485410C24921697003B2EF1 /* Headers */,\n\t\t\t\t0485410D24921697003B2EF1 /* Sources */,\n\t\t\t\t0485410E24921697003B2EF1 /* Frameworks */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = libretro;\n\t\t\tproductName = libretro;\n\t\t\tproductReference = 0485411024921697003B2EF1 /* retro8_libretro.dylib */;\n\t\t\tproductType = \"com.apple.product-type.library.dynamic\";\n\t\t};\n/* End PBXNativeTarget section */\n\n/* Begin PBXProject section */\n\t\t0452734923C3E98B00F67C90 /* Project object */ = {\n\t\t\tisa = PBXProject;\n\t\t\tattributes = {\n\t\t\t\tLastUpgradeCheck = 0730;\n\t\t\t\tORGANIZATIONNAME = Jack;\n\t\t\t\tTargetAttributes = {\n\t\t\t\t\t0452735023C3E98B00F67C90 = {\n\t\t\t\t\t\tCreatedOnToolsVersion = 7.3.1;\n\t\t\t\t\t};\n\t\t\t\t\t0485410F24921697003B2EF1 = {\n\t\t\t\t\t\tCreatedOnToolsVersion = 10.1;\n\t\t\t\t\t\tProvisioningStyle = Automatic;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t\tbuildConfigurationList = 0452734C23C3E98B00F67C90 /* Build configuration list for PBXProject \"retro8\" */;\n\t\t\tcompatibilityVersion = \"Xcode 3.2\";\n\t\t\tdevelopmentRegion = English;\n\t\t\thasScannedForEncodings = 0;\n\t\t\tknownRegions = (\n\t\t\t\ten,\n\t\t\t);\n\t\t\tmainGroup = 0452734823C3E98B00F67C90;\n\t\t\tproductRefGroup = 0452735223C3E98B00F67C90 /* Products */;\n\t\t\tprojectDirPath = \"\";\n\t\t\tprojectRoot = \"\";\n\t\t\ttargets = (\n\t\t\t\t0452735023C3E98B00F67C90 /* retro8 */,\n\t\t\t\t0485410F24921697003B2EF1 /* libretro */,\n\t\t\t);\n\t\t};\n/* End PBXProject section */\n\n/* Begin PBXSourcesBuildPhase section */\n\t\t0452734D23C3E98B00F67C90 /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t045273BD23C3E9CC00F67C90 /* lcode.c in Sources */,\n\t\t\t\t045273BE23C3E9CC00F67C90 /* lcorolib.c in Sources */,\n\t\t\t\t045273C423C3E9CC00F67C90 /* lfunc.c in Sources */,\n\t\t\t\t045273D623C3E9CC00F67C90 /* ltm.c in Sources */,\n\t\t\t\t045273D723C3E9CC00F67C90 /* lundump.c in Sources */,\n\t\t\t\t045273E323C3E9CC00F67C90 /* memory.cpp in Sources */,\n\t\t\t\t045273D523C3E9CC00F67C90 /* ltests.c in Sources */,\n\t\t\t\t045273B723C3E9CC00F67C90 /* loader.cpp in Sources */,\n\t\t\t\t045273C123C3E9CC00F67C90 /* ldebug.c in Sources */,\n\t\t\t\t045273C723C3E9CC00F67C90 /* liolib.c in Sources */,\n\t\t\t\t045273CE23C3E9CC00F67C90 /* loslib.c in Sources */,\n\t\t\t\t045273BB23C3E9CC00F67C90 /* lbaselib.c in Sources */,\n\t\t\t\t045273C023C3E9CC00F67C90 /* ldblib.c in Sources */,\n\t\t\t\t045273D923C3E9CC00F67C90 /* lvm.c in Sources */,\n\t\t\t\t045273DE23C3E9CC00F67C90 /* menu_view.cpp in Sources */,\n\t\t\t\t045273DD23C3E9CC00F67C90 /* game_view.cpp in Sources */,\n\t\t\t\t045273E023C3E9CC00F67C90 /* gfx.cpp in Sources */,\n\t\t\t\t045273E123C3E9CC00F67C90 /* lua_bridge.cpp in Sources */,\n\t\t\t\t045273BC23C3E9CC00F67C90 /* lbitlib.c in Sources */,\n\t\t\t\t045273C623C3E9CC00F67C90 /* linit.c in Sources */,\n\t\t\t\t045273CA23C3E9CC00F67C90 /* lmem.c in Sources */,\n\t\t\t\t045273D823C3E9CC00F67C90 /* lutf8lib.c in Sources */,\n\t\t\t\t045273DA23C3E9CC00F67C90 /* lzio.c in Sources */,\n\t\t\t\t045273C323C3E9CC00F67C90 /* ldump.c in Sources */,\n\t\t\t\t045273D123C3E9CC00F67C90 /* lstring.c in Sources */,\n\t\t\t\t045273B923C3E9CC00F67C90 /* lapi.c in Sources */,\n\t\t\t\t045273D023C3E9CC00F67C90 /* lstate.c in Sources */,\n\t\t\t\t045273CD23C3E9CC00F67C90 /* lopcodes.c in Sources */,\n\t\t\t\t045273C823C3E9CC00F67C90 /* llex.c in Sources */,\n\t\t\t\t045273E223C3E9CC00F67C90 /* machine.cpp in Sources */,\n\t\t\t\t045273B823C3E9CC00F67C90 /* stegano.cpp in Sources */,\n\t\t\t\t045273C223C3E9CC00F67C90 /* ldo.c in Sources */,\n\t\t\t\t045273CB23C3E9CC00F67C90 /* loadlib.c in Sources */,\n\t\t\t\t045273CC23C3E9CC00F67C90 /* lobject.c in Sources */,\n\t\t\t\t045273DF23C3E9CC00F67C90 /* view_manager.cpp in Sources */,\n\t\t\t\t045273D423C3E9CC00F67C90 /* ltablib.c in Sources */,\n\t\t\t\t045273D223C3E9CC00F67C90 /* lstrlib.c in Sources */,\n\t\t\t\t045273C923C3E9CC00F67C90 /* lmathlib.c in Sources */,\n\t\t\t\t045273E423C3E9CC00F67C90 /* sound.cpp in Sources */,\n\t\t\t\t045273C523C3E9CC00F67C90 /* lgc.c in Sources */,\n\t\t\t\t045273BF23C3E9CC00F67C90 /* lctype.c in Sources */,\n\t\t\t\t045273BA23C3E9CC00F67C90 /* lauxlib.c in Sources */,\n\t\t\t\t04ECF30E23F1631500BA0410 /* picopng.cpp in Sources */,\n\t\t\t\t045273CF23C3E9CC00F67C90 /* lparser.c in Sources */,\n\t\t\t\t045273D323C3E9CC00F67C90 /* ltable.c in Sources */,\n\t\t\t\t045273DB23C3E9CC00F67C90 /* main.cpp in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t0485410D24921697003B2EF1 /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t04854150249217D1003B2EF1 /* picopng.cpp in Sources */,\n\t\t\t\t0485412E249217C6003B2EF1 /* lapi.c in Sources */,\n\t\t\t\t0485412F249217C6003B2EF1 /* lauxlib.c in Sources */,\n\t\t\t\t04854130249217C6003B2EF1 /* lbaselib.c in Sources */,\n\t\t\t\t04854131249217C6003B2EF1 /* lbitlib.c in Sources */,\n\t\t\t\t04854132249217C6003B2EF1 /* lcode.c in Sources */,\n\t\t\t\t04854133249217C6003B2EF1 /* lcorolib.c in Sources */,\n\t\t\t\t04854134249217C6003B2EF1 /* lctype.c in Sources */,\n\t\t\t\t04854135249217C6003B2EF1 /* ldblib.c in Sources */,\n\t\t\t\t04854136249217C6003B2EF1 /* ldebug.c in Sources */,\n\t\t\t\t04854137249217C6003B2EF1 /* ldo.c in Sources */,\n\t\t\t\t04854138249217C6003B2EF1 /* ldump.c in Sources */,\n\t\t\t\t04854139249217C6003B2EF1 /* lfunc.c in Sources */,\n\t\t\t\t0485413A249217C6003B2EF1 /* lgc.c in Sources */,\n\t\t\t\t0485413B249217C6003B2EF1 /* linit.c in Sources */,\n\t\t\t\t0485413C249217C6003B2EF1 /* liolib.c in Sources */,\n\t\t\t\t0485413D249217C6003B2EF1 /* llex.c in Sources */,\n\t\t\t\t0485413E249217C6003B2EF1 /* lmathlib.c in Sources */,\n\t\t\t\t0485413F249217C6003B2EF1 /* lmem.c in Sources */,\n\t\t\t\t04854140249217C6003B2EF1 /* loadlib.c in Sources */,\n\t\t\t\t04854141249217C6003B2EF1 /* lobject.c in Sources */,\n\t\t\t\t04854142249217C6003B2EF1 /* lopcodes.c in Sources */,\n\t\t\t\t04854143249217C6003B2EF1 /* loslib.c in Sources */,\n\t\t\t\t04854144249217C6003B2EF1 /* lparser.c in Sources */,\n\t\t\t\t04854145249217C6003B2EF1 /* lstate.c in Sources */,\n\t\t\t\t04854146249217C6003B2EF1 /* lstring.c in Sources */,\n\t\t\t\t04854147249217C6003B2EF1 /* lstrlib.c in Sources */,\n\t\t\t\t04854148249217C6003B2EF1 /* ltable.c in Sources */,\n\t\t\t\t04854149249217C6003B2EF1 /* ltablib.c in Sources */,\n\t\t\t\t0485414A249217C6003B2EF1 /* ltests.c in Sources */,\n\t\t\t\t0485414B249217C6003B2EF1 /* ltm.c in Sources */,\n\t\t\t\t0485414C249217C6003B2EF1 /* lundump.c in Sources */,\n\t\t\t\t0485414D249217C6003B2EF1 /* lutf8lib.c in Sources */,\n\t\t\t\t0485414E249217C6003B2EF1 /* lvm.c in Sources */,\n\t\t\t\t0485414F249217C6003B2EF1 /* lzio.c in Sources */,\n\t\t\t\t0485412124921717003B2EF1 /* loader.cpp in Sources */,\n\t\t\t\t0485412224921717003B2EF1 /* stegano.cpp in Sources */,\n\t\t\t\t0485412424921717003B2EF1 /* gfx.cpp in Sources */,\n\t\t\t\t0485412524921717003B2EF1 /* lua_bridge.cpp in Sources */,\n\t\t\t\t0485412624921717003B2EF1 /* machine.cpp in Sources */,\n\t\t\t\t0485412724921717003B2EF1 /* memory.cpp in Sources */,\n\t\t\t\t0485412824921717003B2EF1 /* sound.cpp in Sources */,\n\t\t\t\t04854120249216DF003B2EF1 /* libretro.cpp in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXSourcesBuildPhase section */\n\n/* Begin XCBuildConfiguration section */\n\t\t0452735623C3E98B00F67C90 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_ANALYZER_NONNULL = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++0x\";\n\t\t\t\tCLANG_CXX_LIBRARY = \"libc++\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCODE_SIGN_IDENTITY = \"-\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tENABLE_TESTABILITY = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu99;\n\t\t\t\tGCC_DYNAMIC_NO_PIC = NO;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\t\"DEBUG=1\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.11;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = YES;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t0452735723C3E98B00F67C90 /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_ANALYZER_NONNULL = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++0x\";\n\t\t\t\tCLANG_CXX_LIBRARY = \"libc++\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCODE_SIGN_IDENTITY = \"-\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";\n\t\t\t\tENABLE_NS_ASSERTIONS = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu99;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.11;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = NO;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t0452735923C3E98B00F67C90 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++14\";\n\t\t\t\tHEADER_SEARCH_PATHS = \"${SRCROOT}/../../src\";\n\t\t\t\tLIBRARY_SEARCH_PATHS = \"$(inherited)\";\n\t\t\t\tOTHER_CFLAGS = (\n\t\t\t\t\t\"-I/usr/local/include/SDL2\",\n\t\t\t\t\t\"-D_THREAD_SAFE\\n-I/usr/local/include/SDL2\",\n\t\t\t\t\t\"-D_THREAD_SAFE\",\n\t\t\t\t);\n\t\t\t\tOTHER_LDFLAGS = (\n\t\t\t\t\t\"-L/usr/local/lib\",\n\t\t\t\t\t\"-lSDL2\",\n\t\t\t\t);\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t0452735A23C3E98B00F67C90 /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++14\";\n\t\t\t\tHEADER_SEARCH_PATHS = \"${SRCROOT}/../../src\";\n\t\t\t\tLIBRARY_SEARCH_PATHS = \"$(inherited)\";\n\t\t\t\tOTHER_CFLAGS = (\n\t\t\t\t\t\"-I/usr/local/include/SDL2\",\n\t\t\t\t\t\"-D_THREAD_SAFE\\n-I/usr/local/include/SDL2\",\n\t\t\t\t\t\"-D_THREAD_SAFE\",\n\t\t\t\t);\n\t\t\t\tOTHER_LDFLAGS = (\n\t\t\t\t\t\"-L/usr/local/lib\",\n\t\t\t\t\t\"-lSDL2\",\n\t\t\t\t);\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t0485411824921697003B2EF1 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++14\";\n\t\t\t\tCLANG_ENABLE_OBJC_WEAK = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_LITERAL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;\n\t\t\t\tCODE_SIGN_STYLE = Automatic;\n\t\t\t\tDYLIB_COMPATIBILITY_VERSION = 1;\n\t\t\t\tDYLIB_CURRENT_VERSION = 1;\n\t\t\t\tEXECUTABLE_PREFIX = \"\";\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu11;\n\t\t\t\tGCC_ENABLE_CPP_EXCEPTIONS = YES;\n\t\t\t\tGCC_ENABLE_CPP_RTTI = YES;\n\t\t\t\tGCC_SYMBOLS_PRIVATE_EXTERN = YES;\n\t\t\t\tHEADER_SEARCH_PATHS = \"${SRCROOT}/../../src\";\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.13;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;\n\t\t\t\tMTL_FAST_MATH = YES;\n\t\t\t\tPRODUCT_NAME = retro8_libretro;\n\t\t\t\tSKIP_INSTALL = YES;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t0485411924921697003B2EF1 /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++14\";\n\t\t\t\tCLANG_ENABLE_OBJC_WEAK = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_LITERAL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;\n\t\t\t\tCODE_SIGN_STYLE = Automatic;\n\t\t\t\tDYLIB_COMPATIBILITY_VERSION = 1;\n\t\t\t\tDYLIB_CURRENT_VERSION = 1;\n\t\t\t\tEXECUTABLE_PREFIX = \"\";\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu11;\n\t\t\t\tGCC_ENABLE_CPP_EXCEPTIONS = YES;\n\t\t\t\tGCC_ENABLE_CPP_RTTI = YES;\n\t\t\t\tGCC_SYMBOLS_PRIVATE_EXTERN = YES;\n\t\t\t\tHEADER_SEARCH_PATHS = \"${SRCROOT}/../../src\";\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.13;\n\t\t\t\tMTL_FAST_MATH = YES;\n\t\t\t\tPRODUCT_NAME = retro8_libretro;\n\t\t\t\tSKIP_INSTALL = YES;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n/* End XCBuildConfiguration section */\n\n/* Begin XCConfigurationList section */\n\t\t0452734C23C3E98B00F67C90 /* Build configuration list for PBXProject \"retro8\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t0452735623C3E98B00F67C90 /* Debug */,\n\t\t\t\t0452735723C3E98B00F67C90 /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t0452735823C3E98B00F67C90 /* Build configuration list for PBXNativeTarget \"retro8\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t0452735923C3E98B00F67C90 /* Debug */,\n\t\t\t\t0452735A23C3E98B00F67C90 /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t0485411A24921697003B2EF1 /* Build configuration list for PBXNativeTarget \"libretro\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t0485411824921697003B2EF1 /* Debug */,\n\t\t\t\t0485411924921697003B2EF1 /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n/* End XCConfigurationList section */\n\t};\n\trootObject = 0452734923C3E98B00F67C90 /* Project object */;\n}\n"
  },
  {
    "path": "src/common.h",
    "content": "#pragma once\n\n#include <cstdint>\n#include <type_traits>\n#include <vector>\n\nusing u32 = uint32_t;\nusing u16 = uint16_t;\n\nusing s32 = int32_t;\nusing s64 = int64_t;\n\nusing byte = uint8_t;\n\ntemplate<typename T>\nstruct bit_mask\n{\n  using utype = typename std::underlying_type<T>::type;\n  utype value;\n\n  inline bool isSet(T flag) const { return value & static_cast<utype>(flag); }\n  inline void set(T flag) { value |= static_cast<utype>(flag); }\n  inline void reset(T flag) { value &= ~static_cast<utype>(flag); }\n  inline void set(T flag, bool value) { if (value) set(flag); else reset(flag); }\n\n  inline bit_mask<T> operator~() const\n  {\n    return bit_mask<T>(~value);\n  }\n\n  inline bit_mask<T> operator&(T flag) const\n  {\n    return bit_mask<T>(value & static_cast<utype>(flag));\n\n  }\n\n  inline bit_mask<T> operator|(T flag) const\n  {\n    return bit_mask<T>(value | static_cast<utype>(flag));\n  }\n\n  inline bit_mask<T> operator&(const bit_mask<T>& other) const\n  {\n    return bit_mask<T>(value & other.value);\n  }\n\n  bit_mask<T>() : value(0) { }\n\nprivate:\n  bit_mask<T>(utype value) : value(value) { }\n};\n\nstruct Platform\n{\n  static uint32_t getTicks();\n  static int loadPNG(std::vector<unsigned char>& out_image, unsigned long& image_width, unsigned long& image_height, const unsigned char* in_png, size_t in_size, bool convert_to_rgba32 = true);\n};\n\n#include \"config.h\"\n"
  },
  {
    "path": "src/config.h",
    "content": "#pragma once\r\n\n#define PLATFORM_WIN32 0\n#define PLATFORM_LIBRETRO 1\n#define PLATFORM_OPENDINGUX 2\n#define PLATFORM_FUNKEY 3\n\n#define SOUND_ENABLED true\n\n#if defined(FUNKEY_S)\n#define PLATFORM PLATFORM_FUNKEY\n#elif defined(__LIBRETRO__)\n#define PLATFORM PLATFORM_LIBRETRO\n#elif defined(_WIN32)\n#define PLATFORM PLATFORM_WIN32\n#endif\n\n#define MOUSE_ENABLED false\n#define TEST_MODE false\n\n#define R8_OPTS_ENABLED true\n#define R8_USE_LODE_PNG true\n\n#if PLATFORM != PLATFORM_LIBRETRO\n\n  #include \"SDL.h\"\n  #define LOGD(x , ...) printf(x\"\\n\", ## __VA_ARGS__)\n\n  #if PLATFORM == PLATFORM_WIN32\n    static constexpr int SCREEN_WIDTH = 240;\n    static constexpr int SCREEN_HEIGHT = 240;\n\n    #undef MOUSE_ENABLED\n    #define MOUSE_ENABLED true\n\n    static constexpr auto KEY_UP = SDLK_UP;\n    static constexpr auto KEY_DOWN = SDLK_DOWN;\n    static constexpr auto KEY_LEFT = SDLK_LEFT;\n    static constexpr auto KEY_RIGHT = SDLK_RIGHT;\n\n    static constexpr auto KEY_ACTION1_1 = SDLK_z;\n    static constexpr auto KEY_ACTION1_2 = SDLK_x;\n    static constexpr auto KEY_ACTION2_1 = SDLK_a;\n    static constexpr auto KEY_ACTION2_2 = SDLK_s;\n\n    static constexpr auto KEY_MUTE = SDLK_m;\n    static constexpr auto KEY_PAUSE = SDLK_p;\n\n    static constexpr auto KEY_NEXT_SCALER = SDLK_v;\n\n    static constexpr auto KEY_MENU = SDLK_RETURN;\n    static constexpr auto KEY_EXIT = SDLK_ESCAPE;\n\n  #elif PLATFORM == PLATFORM_OPENDINGUX\n    static constexpr int SCREEN_WIDTH = 320;\n    static constexpr int SCREEN_HEIGHT = 240;\n\n    static constexpr auto KEY_UP = SDLK_UP;\n    static constexpr auto KEY_DOWN = SDLK_DOWN;\n    static constexpr auto KEY_LEFT = SDLK_LEFT;\n    static constexpr auto KEY_RIGHT = SDLK_RIGHT;\n\n    static constexpr auto KEY_ACTION1_1 = SDLK_LCTRL; // A\n    static constexpr auto KEY_ACTION1_2 = SDLK_LALT; // B\n    static constexpr auto KEY_ACTION2_1 = SDLK_SPACE; // Y\n    static constexpr auto KEY_ACTION2_2 = SDLK_LSHIFT; // X\n\n    static constexpr auto KEY_MUTE = 0xffff;\n    static constexpr auto KEY_PAUSE = 0xffff + 1;\n\n    static constexpr auto KEY_NEXT_SCALER = SDLK_TAB; // L\n\n    static constexpr auto KEY_MENU = SDLK_RETURN;\n    static constexpr auto KEY_EXIT = SDLK_ESCAPE;\n\n  #elif PLATFORM == PLATFORM_FUNKEY\n    static constexpr int SCREEN_WIDTH = 240;\n    static constexpr int SCREEN_HEIGHT = 240;\n\n    static constexpr auto KEY_UP = SDLK_u;\n    static constexpr auto KEY_DOWN = SDLK_d;\n    static constexpr auto KEY_LEFT = SDLK_l;\n    static constexpr auto KEY_RIGHT = SDLK_r;\n\n    static constexpr auto KEY_ACTION1_1 = SDLK_b; // A\n    static constexpr auto KEY_ACTION1_2 = SDLK_a; // B\n    static constexpr auto KEY_ACTION2_1 = SDLK_y; // Y\n    static constexpr auto KEY_ACTION2_2 = SDLK_x; // X\n\n    static constexpr auto KEY_MUTE = 0xffff;\n    static constexpr auto KEY_PAUSE = 0xffff + 1;\n\n    static constexpr auto KEY_NEXT_SCALER = SDLK_h; // L\n\n    static constexpr auto KEY_MENU = SDLK_s;\n    static constexpr auto KEY_EXIT = 0xffff + 2;\n\n  #endif\n\n#else\n\n#define LOGD(x, ...)\n\n#endif\n"
  },
  {
    "path": "src/gen/lua_api.h",
    "content": "const char* lua_api_string =\n\"function all(t)\\n\"\n\"  if t ~= nil then\\n\"\n\"    local nt = {}\\n\"\n\"    local ni = 1\\n\"\n\"    for _,v in pairs(t) do\\n\"\n\"      nt[ni] = v\\n\"\n\"      ni = ni + 1\\n\"\n\"    end\\n\"\n\"    for k,v in pairs(nt) do\\n\"\n\"    end\\n\"\n\"\\n\"\n\"    local i = 0\\n\"\n\"    return function() i = i + 1; return nt[i] end\\n\"\n\"  end\\n\"\n\"  return function() end\\n\"\n\"end\\n\"\n\"\\n\"\n\"function add(t, v)\\n\"\n\"  if t ~= nil then\\n\"\n\"    t[#t+1] = v\\n\"\n\"    return v\\n\"\n\"  end\\n\"\n\"end\\n\"\n\"\\n\"\n\"function foreach(c, f)\\n\"\n\"  if c ~= nil then\\n\"\n\"    for value in all(c) do\\n\"\n\"      f(value)\\n\"\n\"    end\\n\"\n\"  end\\n\"\n\"end\\n\"\n\"\\n\"\n\"\\n\"\n\"function mapdraw(...)\\n\"\n\"  map(table.unpack(arg))\\n\"\n\"end\\n\"\n\"\\n\"\n\"function count(t)\\n\"\n\"  if t ~= nil then\\n\"\n\"    return #t\\n\"\n\"  end\\n\"\n\"end\\n\"\n\"\\n\"\n\"function del(t, v)\\n\"\n\"  if t ~= nil then\\n\"\n\"    local found = false\\n\"\n\"    for i = 1, #t do\\n\"\n\"      if t[i] == v then\\n\"\n\"        found = true\\n\"\n\"      end\\n\"\n\"      if found then\\n\"\n\"        t[i] = t[i+1]\\n\"\n\"      end\\n\"\n\"    end\\n\"\n\"    if found then\\n\"\n\"      return v\\n\"\n\"    end\\n\"\n\"  end\\n\"\n\"end\\n\"\n\"\\n\"\n\"function cocreate(f)\\n\"\n\"  return coroutine.create(f)\\n\"\n\"end\\n\"\n\"\\n\"\n\"function yield()\\n\"\n\"  coroutine.yield()\\n\"\n\"end\\n\"\n\"\\n\"\n\"-- TODO: missing vararg\\n\"\n\"function coresume(f)\\n\"\n\"  return coroutine.resume(f)\\n\"\n\"end\\n\"\n\"\\n\"\n\"function costatus(f)\\n\"\n\"  return coroutine.status(f)\\n\"\n\"end\";\n"
  },
  {
    "path": "src/gen/pico_font.h",
    "content": "#include \"common.h\"\n\nnamespace retro8\n{\n  namespace gfx\n  {\n    static constexpr  uint8_t font_map[] = {\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x40, 0xa0, 0xa0, 0xe0, 0xa0, 0xc0, 0x40, 0x40, 0x40, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x20,\n      0x00, 0x40, 0xa0, 0xe0, 0xc0, 0x20, 0xc0, 0x80, 0x80, 0x20, 0x40, 0x40, 0x00, 0x00, 0x00, 0x40,\n      0x00, 0x40, 0x00, 0xa0, 0x60, 0x40, 0xc0, 0x00, 0x80, 0x20, 0xe0, 0xe0, 0x00, 0xe0, 0x00, 0x40,\n      0x00, 0x00, 0x00, 0xe0, 0xe0, 0x80, 0xa0, 0x00, 0x80, 0x20, 0x40, 0x40, 0x40, 0x00, 0x00, 0x40,\n      0x00, 0x40, 0x00, 0xa0, 0x40, 0xa0, 0xe0, 0x00, 0x40, 0x40, 0xa0, 0x00, 0x80, 0x00, 0x40, 0x80,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0xe0, 0xc0, 0xe0, 0xe0, 0xa0, 0xe0, 0x80, 0xe0, 0xe0, 0xe0, 0x00, 0x00, 0x20, 0x00, 0x80, 0xe0,\n      0xa0, 0x40, 0x20, 0x20, 0xa0, 0x80, 0x80, 0x20, 0xa0, 0xa0, 0x40, 0x40, 0x40, 0xe0, 0x40, 0x20,\n      0xa0, 0x40, 0xe0, 0x60, 0xe0, 0xe0, 0xe0, 0x20, 0xe0, 0xe0, 0x00, 0x00, 0x80, 0x00, 0x20, 0x60,\n      0xa0, 0x40, 0x80, 0x20, 0x20, 0x20, 0xa0, 0x20, 0xa0, 0x20, 0x40, 0x40, 0x40, 0xe0, 0x40, 0x00,\n      0xe0, 0xe0, 0xe0, 0xe0, 0x20, 0xe0, 0xe0, 0x20, 0xe0, 0x20, 0x00, 0x80, 0x20, 0x00, 0x80, 0x40,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0xa0, 0xe0, 0xc0, 0xe0, 0xc0, 0xe0, 0xe0, 0xe0, 0xa0, 0xe0, 0xe0, 0xa0, 0x80, 0xe0, 0xc0, 0x60,\n      0xa0, 0xa0, 0xc0, 0x80, 0xa0, 0xc0, 0xc0, 0x80, 0xa0, 0x40, 0x40, 0xc0, 0x80, 0xe0, 0xa0, 0xa0,\n      0x80, 0xe0, 0xa0, 0x80, 0xa0, 0x80, 0x80, 0xa0, 0xe0, 0x40, 0x40, 0xa0, 0x80, 0xa0, 0xa0, 0xa0,\n      0x60, 0xa0, 0xe0, 0xe0, 0xc0, 0xe0, 0x80, 0xe0, 0xa0, 0xe0, 0xc0, 0xa0, 0xe0, 0xa0, 0xa0, 0xc0,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x80, 0x60, 0x40, 0x00,\n      0xe0, 0x40, 0xe0, 0x60, 0xe0, 0xa0, 0xa0, 0xa0, 0xa0, 0xa0, 0xe0, 0x80, 0x40, 0x20, 0xa0, 0x00,\n      0xa0, 0xa0, 0xa0, 0x80, 0x40, 0xa0, 0xa0, 0xa0, 0x40, 0xe0, 0x20, 0x80, 0x40, 0x20, 0x00, 0x00,\n      0xe0, 0xc0, 0xc0, 0x20, 0x40, 0xa0, 0xe0, 0xe0, 0xa0, 0x20, 0x80, 0x80, 0x40, 0x20, 0x00, 0x00,\n      0x80, 0x60, 0xa0, 0xc0, 0x40, 0x60, 0x40, 0xe0, 0xa0, 0xe0, 0xe0, 0xc0, 0x20, 0x60, 0x00, 0xe0,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x40, 0xe0, 0xe0, 0x60, 0xc0, 0xe0, 0xe0, 0x60, 0xa0, 0xe0, 0xe0, 0xa0, 0x80, 0xe0, 0xc0, 0x60,\n      0x20, 0xa0, 0xa0, 0x80, 0xa0, 0x80, 0x80, 0x80, 0xa0, 0x40, 0x40, 0xa0, 0x80, 0xe0, 0xa0, 0xa0,\n      0x00, 0xe0, 0xc0, 0x80, 0xa0, 0xc0, 0xc0, 0x80, 0xe0, 0x40, 0x40, 0xc0, 0x80, 0xa0, 0xa0, 0xa0,\n      0x00, 0xa0, 0xa0, 0x80, 0xa0, 0x80, 0x80, 0xa0, 0xa0, 0x40, 0x40, 0xa0, 0x80, 0xa0, 0xa0, 0xa0,\n      0x00, 0xa0, 0xe0, 0x60, 0xe0, 0xe0, 0x80, 0xe0, 0xa0, 0xe0, 0xc0, 0xa0, 0xe0, 0xa0, 0xa0, 0xc0,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0xe0, 0x40, 0xe0, 0x60, 0xe0, 0xa0, 0xa0, 0xa0, 0xa0, 0xa0, 0xe0, 0x60, 0x40, 0xc0, 0x00, 0x00,\n      0xa0, 0xa0, 0xa0, 0x80, 0x40, 0xa0, 0xa0, 0xa0, 0xa0, 0xa0, 0x20, 0x40, 0x40, 0x40, 0x20, 0x40,\n      0xe0, 0xa0, 0xc0, 0xe0, 0x40, 0xa0, 0xa0, 0xa0, 0x40, 0xe0, 0x40, 0xc0, 0x40, 0x60, 0xe0, 0xa0,\n      0x80, 0xc0, 0xa0, 0x20, 0x40, 0xa0, 0xe0, 0xe0, 0xa0, 0x20, 0x80, 0x40, 0x40, 0x40, 0x80, 0xa0,\n      0x80, 0x60, 0xa0, 0xc0, 0x40, 0x60, 0x40, 0xe0, 0xa0, 0xe0, 0xe0, 0x60, 0x40, 0xc0, 0x00, 0xe0,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0xfe, 0xaa, 0x82, 0x7c, 0x88, 0x20, 0x38, 0x6c, 0x38, 0x38, 0x38, 0x7c, 0xfe, 0x1c, 0x7c, 0x10,\n      0xfe, 0x54, 0xfe, 0xc6, 0x22, 0x3c, 0x74, 0x7c, 0x6c, 0x38, 0x7c, 0xe6, 0xba, 0x10, 0xc6, 0x38,\n      0xfe, 0xaa, 0xba, 0xc6, 0x88, 0x38, 0x7c, 0x7c, 0xee, 0x7c, 0xfe, 0xc6, 0xfe, 0x10, 0xd6, 0x7c,\n      0xfe, 0x54, 0xba, 0xee, 0x22, 0x78, 0x7c, 0x38, 0x6c, 0x38, 0x54, 0xe6, 0x82, 0x70, 0xc6, 0x38,\n      0xfe, 0xaa, 0x7c, 0x7c, 0x88, 0x08, 0x38, 0x10, 0x38, 0x28, 0x5c, 0x7c, 0xfe, 0x70, 0x7c, 0x10,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x7c, 0x10, 0x7c, 0x7c, 0x00, 0x00, 0x7c, 0xfe, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0xce, 0x38, 0x38, 0xee, 0xa0, 0x88, 0xd6, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0xaa, 0xc6, 0xfe, 0x10, 0xc6, 0x4a, 0x54, 0xee, 0xfe, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0xce, 0x7c, 0x38, 0xc6, 0x04, 0x22, 0xd6, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x7c, 0x44, 0x7c, 0x7c, 0x00, 0x00, 0x7c, 0xfe, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    };\n  }\n}"
  },
  {
    "path": "src/io/loader.cpp",
    "content": "#include \"loader.h\"\n\n#include \"stegano.h\"\n\n#include <fstream>\n#include <algorithm>\n#include <iterator>\n#include <cassert>\n#include <sstream>\n//#include <cctype>\n\nusing namespace retro8;\nusing namespace retro8::io;\n\nvoid Loader::fixLine(std::string& line)\n{\n  /* inline ? print operator */\n  if (!line.empty() && line[0] == '?')\n    line = \"print(\" + line.substr(1) + \")\";\n}\n\nint Loader::valueForHexDigit(char c)\n{\n  int v = (c >= 'A') ? (c >= 'a') ? (c - 'a' + 10) : (c - 'A' + 10) : (c - '0');\n  assert(v >= 0 && v <= 0xf);\n  return v;\n}\n\ncolor_t Loader::colorFromDigit(char d)\n{\n  return static_cast<color_t>(valueForHexDigit(d));\n}\n\nsprite_index_t Loader::spriteIndexFromString(const char* c)\n{\n  int h = valueForHexDigit(c[0]);\n  int l = valueForHexDigit(c[1]);\n  return (h << 4) | l;\n}\n\nuint8_t Loader::valueForUint8(const char* c)\n{\n  int h = valueForHexDigit(c[0]);\n  int l = valueForHexDigit(c[1]);\n  return (h << 4) | l;\n}\n\nretro8::sprite_flags_t Loader::spriteFlagsFromString(const char* c)\n{\n  int h = valueForHexDigit(c[0]);\n  int l = valueForHexDigit(c[1]);\n  return (h << 4) | l;\n}\n\nbool Loader::isPngCartridge(const std::string& path)\n{\n  return path.length() >= 4 && path.substr(path.length() - 4) == \".png\";\n}\n\ntemplate<typename T>\nstd::vector<std::string> Loader::loadLines(T& input)\n{\n  std::vector<std::string> lines;\n\n  for (std::string line; std::getline(input, line); /**/)\n    lines.push_back(line);\n\n  for (auto& line : lines)\n    if (!line.empty() && line.back() == '\\r')\n      line.resize(line.length() - 1);\n\n  return lines;\n}\n\nvoid Loader::loadFile(const std::string& path, Machine& dest)\n{\n  auto stream = std::ifstream(path);\n  assert(stream.good());\n  load(loadLines(stream), dest);\n}\n\nvoid Loader::loadRaw(const std::string& data, Machine& dest)\n{\n  auto stream = std::stringstream(data);\n  load(loadLines(stream), dest);\n}\n\nvoid Loader::load(const std::vector<std::string>& lines, Machine& m)\n{ \n  enum class State { HEADER, CODE, GFX, GFF, LABEL, MAP, SFX, MUSIC };\n\n  State state = State::HEADER;\n\n  //TODO: not efficient but for now it's fine\n  std::stringstream code;\n\n  coord_t sy = 0, my = 0, fy = 0, snd = 0, msc = 0;\n\n  static constexpr size_t DIGITS_PER_PIXEL_ROW = 128;\n  static constexpr size_t BYTES_PER_GFX_ROW = DIGITS_PER_PIXEL_ROW / 2;\n\n  static constexpr size_t DIGITS_PER_MAP_ROW = 256;\n  static constexpr size_t DIGITS_PER_SPRITE_FLAGS_ROW = 128*2;\n\n  static constexpr size_t DIGITS_PER_SOUND = 168;\n  static constexpr size_t DIGITS_PER_MUSIC_PATTERN = 2 + 1 + 8;\n\n\n  for (auto& line : lines)\n  {\n    /* change state according to */\n    if (line == \"__lua__\")\n      state = State::CODE;\n    else if (line == \"__gfx__\")\n      state = State::GFX;\n    else if (line == \"__gff__\")\n      state = State::GFF;\n    else if (line == \"__label__\")\n      state = State::LABEL;\n    else if (line == \"__map__\")\n      state = State::MAP;\n    else if (line == \"__sfx__\")\n      state = State::SFX;\n    else if (line == \"__music__\")\n      state = State::MUSIC;\n    else if (line.empty()) /* skip empty lines */\n      continue;\n    /*else if (std::all_of(line.begin(), line.end(), [](char c) { return std::isspace(c); }))\n      continue;*/\n    else\n    {\n      switch (state)\n      {\n      case State::CODE:\n        //fixOperators(line);\n        code << line << std::endl;\n        break;\n\n      case State::GFX:\n        assert(line.length() == DIGITS_PER_PIXEL_ROW);\n        for (coord_t x = 0; x < BYTES_PER_GFX_ROW; ++x)\n        {\n          const char* pair = line.c_str() + x * 2;\n          auto* dest = m.memory().as<gfx::color_byte_t>(address::SPRITE_SHEET + sy * BYTES_PER_GFX_ROW + x);\n\n          dest->setBoth(colorFromDigit(pair[0]), colorFromDigit(pair[1]));\n        }\n\n        ++sy;\n        break;\n\n      case State::MAP:\n      {\n        assert(line.length() == DIGITS_PER_MAP_ROW);\n        for (coord_t x = 0; x < gfx::TILE_MAP_WIDTH; ++x)\n        {\n          const char* index = line.c_str() + x * 2;\n          sprite_index_t sindex = spriteIndexFromString(index);\n          *m.memory().spriteInTileMap(x, my) = sindex;\n        }\n        ++my;\n        break;\n      }\n      case State::GFF:\n      {\n        assert(line.length() == DIGITS_PER_SPRITE_FLAGS_ROW);\n        for (coord_t x = 0; x < DIGITS_PER_SPRITE_FLAGS_ROW/2; ++x)\n        {\n          const char* sflags = line.c_str() + x * 2;\n          sprite_flags_t flags = spriteFlagsFromString(sflags);\n          *m.memory().spriteFlagsFor(128*fy + x) = flags;\n        }\n        ++fy;\n        break;\n      }\n      case State::SFX:\n      {\n        assert(line.length() == DIGITS_PER_SOUND);\n        const char* p = line.c_str();\n\n        sfx::Sound* sound = m.memory().sound(snd);\n        sound->speed = valueForUint8(p+2);\n        sound->loopStart = valueForUint8(p+4);\n        sound->loopEnd = valueForUint8(p+6);\n\n        p = p + 8;\n\n        for (size_t i = 0; i < sound->samples.size(); ++i)\n        {\n          const char* s = p + (i * 5);\n          \n          auto& sample = sound->samples[i];\n          \n          sample.setPitch(valueForUint8(s));\n          sample.setWaveform(sfx::Waveform(valueForHexDigit(s[2])));\n          sample.setVolume(valueForHexDigit(s[3]));\n          sample.setEffect(sfx::Effect(valueForHexDigit(s[4])));\n        }\n\n        ++snd;\n        break;\n\n      }\n      case State::MUSIC:\n      {\n        const char* p = line.c_str();\n\n        if (!line.empty())\n        {\n          sfx::Music* music = m.memory().music(msc);\n\n          /* XX AABBCCDD*/\n          constexpr sfx::sound_index_t UNUSED_CHANNEL = 0x40;\n\n          uint8_t flags = valueForUint8(p);\n\n          if (flags & 0b1) music->markLoopBegin();\n          else if (flags & 0b10) music->markLoopEnd();\n          else if (flags & 0b100) music->markStop();\n\n          for (sfx::channel_index_t i = 0; i < sfx::APU::CHANNEL_COUNT; ++i)\n          {\n            sfx::sound_index_t index = valueForUint8(p + 3 + 2 * i);\n\n            if (index < UNUSED_CHANNEL)\n              music->setSound(i, index);\n            else\n              assert(true || (index == UNUSED_CHANNEL + i + 1));\n          }\n\n          ++msc;\n\n        }\n        \n        break;\n      }\n      }\n\n    }\n  }\n\n  m.code().initFromSource(code.str());\n}\n"
  },
  {
    "path": "src/io/loader.h",
    "content": "#include \"common.h\"\n\n#include \"vm/machine.h\"\n\n#include <vector>\n#include <string>\n\nnamespace retro8\n{\n  namespace io\n  {\n    class Loader\n    {\n    private:\n      int valueForHexDigit(char c);\n      retro8::color_t colorFromDigit(char d);\n      retro8::sprite_index_t spriteIndexFromString(const char* c);\n      retro8::sprite_flags_t spriteFlagsFromString(const char* c);\n      uint8_t valueForUint8(const char* c);\n\n      template<typename T> std::vector<std::string> loadLines(T& stream);\n      void load(const std::vector<std::string>& lines, Machine& dest);\n\n    public:\n\n      void loadRaw(const std::string& data, Machine& dest);\n      void loadFile(const std::string& path, Machine& dest);\n\n      static bool isPngCartridge(const std::string& path);\n\n      static void fixLine(std::string& line);\n\n      \n    };\n  }\n}"
  },
  {
    "path": "src/io/picopng.cpp",
    "content": "#include <vector>\n#include \"common.h\"\n\n\n#if R8_USE_LODE_PNG\n\n/*\ndecodePNG: The picoPNG function, decodes a PNG file buffer in memory, into a raw pixel buffer.\nout_image: output parameter, this will contain the raw pixels after decoding.\n  By default the output is 32-bit RGBA color.\n  The std::vector is automatically resized to the correct size.\nimage_width: output_parameter, this will contain the width of the image in pixels.\nimage_height: output_parameter, this will contain the height of the image in pixels.\nin_png: pointer to the buffer of the PNG file in memory. To get it from a file on\n  disk, load it and store it in a memory buffer yourself first.\nin_size: size of the input PNG file in bytes.\nconvert_to_rgba32: optional parameter, true by default.\n  Set to true to get the output in RGBA 32-bit (8 bit per channel) color format\n  no matter what color type the original PNG image had. This gives predictable,\n  useable data from any random input PNG.\n  Set to false to do no color conversion at all. The result then has the same data\n  type as the PNG image, which can range from 1 bit to 64 bits per pixel.\n  Information about the color type or palette colors are not provided. You need\n  to know this information yourself to be able to use the data so this only\n  works for trusted PNG files. Use LodePNG instead of picoPNG if you need this information.\nreturn: 0 if success, not 0 if some error occured.\n*/\n\nint decodePNG(std::vector<unsigned char>& out_image, unsigned long& image_width, unsigned long& image_height, const unsigned char* in_png, size_t in_size, bool convert_to_rgba32 = true)\n{\n  // picoPNG version 20101224\n  // Copyright (c) 2005-2010 Lode Vandevenne\n  //\n  // This software is provided 'as-is', without any express or implied\n  // warranty. In no event will the authors be held liable for any damages\n  // arising from the use of this software.\n  //\n  // Permission is granted to anyone to use this software for any purpose,\n  // including commercial applications, and to alter it and redistribute it\n  // freely, subject to the following restrictions:\n  //\n  //     1. The origin of this software must not be misrepresented; you must not\n  //     claim that you wrote the original software. If you use this software\n  //     in a product, an acknowledgment in the product documentation would be\n  //     appreciated but is not required.\n  //     2. Altered source versions must be plainly marked as such, and must not be\n  //     misrepresented as being the original software.\n  //     3. This notice may not be removed or altered from any source distribution.\n\n  // picoPNG is a PNG decoder in one C++ function of around 500 lines. Use picoPNG for\n  // programs that need only 1 .cpp file. Since it's a single function, it's very limited,\n  // it can convert a PNG to raw pixel data either converted to 32-bit RGBA color or\n  // with no color conversion at all. For anything more complex, another tiny library\n  // is available: LodePNG (lodepng.c(pp)), which is a single source and header file.\n  // Apologies for the compact code style, it's to make this tiny.\n\n  static const unsigned long LENBASE[29] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258 };\n  static const unsigned long LENEXTRA[29] = { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,  4,  5,  5,  5,  5,  0 };\n  static const unsigned long DISTBASE[30] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577 };\n  static const unsigned long DISTEXTRA[30] = { 0,0,0,0,1,1,2, 2, 3, 3, 4, 4, 5, 5,  6,  6,  7,  7,  8,  8,   9,   9,  10,  10,  11,  11,  12,   12,   13,   13 };\n  static const unsigned long CLCL[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; //code length code lengths\n  struct Zlib //nested functions for zlib decompression\n  {\n    static unsigned long readBitFromStream(size_t& bitp, const unsigned char* bits) { unsigned long result = (bits[bitp >> 3] >> (bitp & 0x7)) & 1; bitp++; return result; }\n    static unsigned long readBitsFromStream(size_t& bitp, const unsigned char* bits, size_t nbits)\n    {\n      unsigned long result = 0;\n      for (size_t i = 0; i < nbits; i++) result += (readBitFromStream(bitp, bits)) << i;\n      return result;\n    }\n    struct HuffmanTree\n    {\n      int makeFromLengths(const std::vector<unsigned long>& bitlen, unsigned long maxbitlen)\n      { //make tree given the lengths\n        unsigned long numcodes = (unsigned long)(bitlen.size()), treepos = 0, nodefilled = 0;\n        std::vector<unsigned long> tree1d(numcodes), blcount(maxbitlen + 1, 0), nextcode(maxbitlen + 1, 0);\n        for (unsigned long bits = 0; bits < numcodes; bits++) blcount[bitlen[bits]]++; //count number of instances of each code length\n        for (unsigned long bits = 1; bits <= maxbitlen; bits++) nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1;\n        for (unsigned long n = 0; n < numcodes; n++) if (bitlen[n] != 0) tree1d[n] = nextcode[bitlen[n]]++; //generate all the codes\n        tree2d.clear(); tree2d.resize(numcodes * 2, 32767); //32767 here means the tree2d isn't filled there yet\n        for (unsigned long n = 0; n < numcodes; n++) //the codes\n          for (unsigned long i = 0; i < bitlen[n]; i++) //the bits for this code\n          {\n            unsigned long bit = (tree1d[n] >> (bitlen[n] - i - 1)) & 1;\n            if (treepos > numcodes - 2) return 55;\n            if (tree2d[2 * treepos + bit] == 32767) //not yet filled in\n            {\n              if (i + 1 == bitlen[n]) { tree2d[2 * treepos + bit] = n; treepos = 0; } //last bit\n              else { tree2d[2 * treepos + bit] = ++nodefilled + numcodes; treepos = nodefilled; } //addresses are encoded as values > numcodes\n            }\n            else treepos = tree2d[2 * treepos + bit] - numcodes; //subtract numcodes from address to get address value\n          }\n        return 0;\n      }\n      int decode(bool& decoded, unsigned long& result, size_t& treepos, unsigned long bit) const\n      { //Decodes a symbol from the tree\n        unsigned long numcodes = (unsigned long)tree2d.size() / 2;\n        if (treepos >= numcodes) return 11; //error: you appeared outside the codetree\n        result = tree2d[2 * treepos + bit];\n        decoded = (result < numcodes);\n        treepos = decoded ? 0 : result - numcodes;\n        return 0;\n      }\n      std::vector<unsigned long> tree2d; //2D representation of a huffman tree: The one dimension is \"0\" or \"1\", the other contains all nodes and leaves of the tree.\n    };\n    struct Inflator\n    {\n      int error;\n      void inflate(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, size_t inpos = 0)\n      {\n        size_t bp = 0, pos = 0; //bit pointer and byte pointer\n        error = 0;\n        unsigned long BFINAL = 0;\n        while (!BFINAL && !error)\n        {\n          if (bp >> 3 >= in.size()) { error = 52; return; } //error, bit pointer will jump past memory\n          BFINAL = readBitFromStream(bp, &in[inpos]);\n          unsigned long BTYPE = readBitFromStream(bp, &in[inpos]); BTYPE += 2 * readBitFromStream(bp, &in[inpos]);\n          if (BTYPE == 3) { error = 20; return; } //error: invalid BTYPE\n          else if (BTYPE == 0) inflateNoCompression(out, &in[inpos], bp, pos, in.size());\n          else inflateHuffmanBlock(out, &in[inpos], bp, pos, in.size(), BTYPE);\n        }\n        if (!error) out.resize(pos); //Only now we know the true size of out, resize it to that\n      }\n      void generateFixedTrees(HuffmanTree& tree, HuffmanTree& treeD) //get the tree of a deflated block with fixed tree\n      {\n        std::vector<unsigned long> bitlen(288, 8), bitlenD(32, 5);;\n        for (size_t i = 144; i <= 255; i++) bitlen[i] = 9;\n        for (size_t i = 256; i <= 279; i++) bitlen[i] = 7;\n        tree.makeFromLengths(bitlen, 15);\n        treeD.makeFromLengths(bitlenD, 15);\n      }\n      HuffmanTree codetree, codetreeD, codelengthcodetree; //the code tree for Huffman codes, dist codes, and code length codes\n      unsigned long huffmanDecodeSymbol(const unsigned char* in, size_t& bp, const HuffmanTree& codetree, size_t inlength)\n      { //decode a single symbol from given list of bits with given code tree. return value is the symbol\n        bool decoded; unsigned long ct;\n        for (size_t treepos = 0;;)\n        {\n          if ((bp & 0x07) == 0 && (bp >> 3) > inlength) { error = 10; return 0; } //error: end reached without endcode\n          error = codetree.decode(decoded, ct, treepos, readBitFromStream(bp, in)); if (error) return 0; //stop, an error happened\n          if (decoded) return ct;\n        }\n      }\n      void getTreeInflateDynamic(HuffmanTree& tree, HuffmanTree& treeD, const unsigned char* in, size_t& bp, size_t inlength)\n      { //get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree\n        std::vector<unsigned long> bitlen(288, 0), bitlenD(32, 0);\n        if (bp >> 3 >= inlength - 2) { error = 49; return; } //the bit pointer is or will go past the memory\n        size_t HLIT = readBitsFromStream(bp, in, 5) + 257; //number of literal/length codes + 257\n        size_t HDIST = readBitsFromStream(bp, in, 5) + 1; //number of dist codes + 1\n        size_t HCLEN = readBitsFromStream(bp, in, 4) + 4; //number of code length codes + 4\n        std::vector<unsigned long> codelengthcode(19); //lengths of tree to decode the lengths of the dynamic tree\n        for (size_t i = 0; i < 19; i++) codelengthcode[CLCL[i]] = (i < HCLEN) ? readBitsFromStream(bp, in, 3) : 0;\n        error = codelengthcodetree.makeFromLengths(codelengthcode, 7); if (error) return;\n        size_t i = 0, replength;\n        while (i < HLIT + HDIST)\n        {\n          unsigned long code = huffmanDecodeSymbol(in, bp, codelengthcodetree, inlength); if (error) return;\n          if (code <= 15) { if (i < HLIT) bitlen[i++] = code; else bitlenD[i++ - HLIT] = code; } //a length code\n          else if (code == 16) //repeat previous\n          {\n            if (bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory\n            replength = 3 + readBitsFromStream(bp, in, 2);\n            unsigned long value; //set value to the previous code\n            if ((i - 1) < HLIT) value = bitlen[i - 1];\n            else value = bitlenD[i - HLIT - 1];\n            for (size_t n = 0; n < replength; n++) //repeat this value in the next lengths\n            {\n              if (i >= HLIT + HDIST) { error = 13; return; } //error: i is larger than the amount of codes\n              if (i < HLIT) bitlen[i++] = value; else bitlenD[i++ - HLIT] = value;\n            }\n          }\n          else if (code == 17) //repeat \"0\" 3-10 times\n          {\n            if (bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory\n            replength = 3 + readBitsFromStream(bp, in, 3);\n            for (size_t n = 0; n < replength; n++) //repeat this value in the next lengths\n            {\n              if (i >= HLIT + HDIST) { error = 14; return; } //error: i is larger than the amount of codes\n              if (i < HLIT) bitlen[i++] = 0; else bitlenD[i++ - HLIT] = 0;\n            }\n          }\n          else if (code == 18) //repeat \"0\" 11-138 times\n          {\n            if (bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory\n            replength = 11 + readBitsFromStream(bp, in, 7);\n            for (size_t n = 0; n < replength; n++) //repeat this value in the next lengths\n            {\n              if (i >= HLIT + HDIST) { error = 15; return; } //error: i is larger than the amount of codes\n              if (i < HLIT) bitlen[i++] = 0; else bitlenD[i++ - HLIT] = 0;\n            }\n          }\n          else { error = 16; return; } //error: somehow an unexisting code appeared. This can never happen.\n        }\n        if (bitlen[256] == 0) { error = 64; return; } //the length of the end code 256 must be larger than 0\n        error = tree.makeFromLengths(bitlen, 15); if (error) return; //now we've finally got HLIT and HDIST, so generate the code trees, and the function is done\n        error = treeD.makeFromLengths(bitlenD, 15); if (error) return;\n      }\n      void inflateHuffmanBlock(std::vector<unsigned char>& out, const unsigned char* in, size_t& bp, size_t& pos, size_t inlength, unsigned long btype)\n      {\n        if (btype == 1) { generateFixedTrees(codetree, codetreeD); }\n        else if (btype == 2) { getTreeInflateDynamic(codetree, codetreeD, in, bp, inlength); if (error) return; }\n        for (;;)\n        {\n          unsigned long code = huffmanDecodeSymbol(in, bp, codetree, inlength); if (error) return;\n          if (code == 256) return; //end code\n          else if (code <= 255) //literal symbol\n          {\n            if (pos >= out.size()) out.resize((pos + 1) * 2); //reserve more room\n            out[pos++] = (unsigned char)(code);\n          }\n          else if (code >= 257 && code <= 285) //length code\n          {\n            size_t length = LENBASE[code - 257], numextrabits = LENEXTRA[code - 257];\n            if ((bp >> 3) >= inlength) { error = 51; return; } //error, bit pointer will jump past memory\n            length += readBitsFromStream(bp, in, numextrabits);\n            unsigned long codeD = huffmanDecodeSymbol(in, bp, codetreeD, inlength); if (error) return;\n            if (codeD > 29) { error = 18; return; } //error: invalid dist code (30-31 are never used)\n            unsigned long dist = DISTBASE[codeD], numextrabitsD = DISTEXTRA[codeD];\n            if ((bp >> 3) >= inlength) { error = 51; return; } //error, bit pointer will jump past memory\n            dist += readBitsFromStream(bp, in, numextrabitsD);\n            size_t start = pos, back = start - dist; //backwards\n            if (pos + length >= out.size()) out.resize((pos + length) * 2); //reserve more room\n            for (size_t i = 0; i < length; i++) { out[pos++] = out[back++]; if (back >= start) back = start - dist; }\n          }\n        }\n      }\n      void inflateNoCompression(std::vector<unsigned char>& out, const unsigned char* in, size_t& bp, size_t& pos, size_t inlength)\n      {\n        while ((bp & 0x7) != 0) bp++; //go to first boundary of byte\n        size_t p = bp / 8;\n        if (p >= inlength - 4) { error = 52; return; } //error, bit pointer will jump past memory\n        unsigned long LEN = in[p] + 256 * in[p + 1], NLEN = in[p + 2] + 256 * in[p + 3]; p += 4;\n        if (LEN + NLEN != 65535) { error = 21; return; } //error: NLEN is not one's complement of LEN\n        if (pos + LEN >= out.size()) out.resize(pos + LEN);\n        if (p + LEN > inlength) { error = 23; return; } //error: reading outside of in buffer\n        for (unsigned long n = 0; n < LEN; n++) out[pos++] = in[p++]; //read LEN bytes of literal data\n        bp = p * 8;\n      }\n    };\n    int decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in) //returns error value\n    {\n      Inflator inflator;\n      if (in.size() < 2) { return 53; } //error, size of zlib data too small\n      if ((in[0] * 256 + in[1]) % 31 != 0) { return 24; } //error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way\n      unsigned long CM = in[0] & 15, CINFO = (in[0] >> 4) & 15, FDICT = (in[1] >> 5) & 1;\n      if (CM != 8 || CINFO > 7) { return 25; } //error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec\n      if (FDICT != 0) { return 26; } //error: the specification of PNG says about the zlib stream: \"The additional flags shall not specify a preset dictionary.\"\n      inflator.inflate(out, in, 2);\n      return inflator.error; //note: adler32 checksum was skipped and ignored\n    }\n  };\n  struct PNG //nested functions for PNG decoding\n  {\n    struct Info\n    {\n      unsigned long width, height, colorType, bitDepth, compressionMethod, filterMethod, interlaceMethod, key_r, key_g, key_b;\n      bool key_defined; //is a transparent color key given?\n      std::vector<unsigned char> palette;\n    } info;\n    int error;\n    void decode(std::vector<unsigned char>& out, const unsigned char* in, size_t size, bool convert_to_rgba32)\n    {\n      error = 0;\n      if (size == 0 || in == 0) { error = 48; return; } //the given data is empty\n      readPngHeader(&in[0], size); if (error) return;\n      size_t pos = 33; //first byte of the first chunk after the header\n      std::vector<unsigned char> idat; //the data from idat chunks\n      bool IEND = false, known_type = true;\n      info.key_defined = false;\n      while (!IEND) //loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. IDAT data is put at the start of the in buffer\n      {\n        if (pos + 8 >= size) { error = 30; return; } //error: size of the in buffer too small to contain next chunk\n        size_t chunkLength = read32bitInt(&in[pos]); pos += 4;\n        if (chunkLength > 2147483647) { error = 63; return; }\n        if (pos + chunkLength >= size) { error = 35; return; } //error: size of the in buffer too small to contain next chunk\n        if (in[pos + 0] == 'I' && in[pos + 1] == 'D' && in[pos + 2] == 'A' && in[pos + 3] == 'T') //IDAT chunk, containing compressed image data\n        {\n          idat.insert(idat.end(), &in[pos + 4], &in[pos + 4 + chunkLength]);\n          pos += (4 + chunkLength);\n        }\n        else if (in[pos + 0] == 'I' && in[pos + 1] == 'E' && in[pos + 2] == 'N' && in[pos + 3] == 'D') { pos += 4; IEND = true; }\n        else if (in[pos + 0] == 'P' && in[pos + 1] == 'L' && in[pos + 2] == 'T' && in[pos + 3] == 'E') //palette chunk (PLTE)\n        {\n          pos += 4; //go after the 4 letters\n          info.palette.resize(4 * (chunkLength / 3));\n          if (info.palette.size() > (4 * 256)) { error = 38; return; } //error: palette too big\n          for (size_t i = 0; i < info.palette.size(); i += 4)\n          {\n            for (size_t j = 0; j < 3; j++) info.palette[i + j] = in[pos++]; //RGB\n            info.palette[i + 3] = 255; //alpha\n          }\n        }\n        else if (in[pos + 0] == 't' && in[pos + 1] == 'R' && in[pos + 2] == 'N' && in[pos + 3] == 'S') //palette transparency chunk (tRNS)\n        {\n          pos += 4; //go after the 4 letters\n          if (info.colorType == 3)\n          {\n            if (4 * chunkLength > info.palette.size()) { error = 39; return; } //error: more alpha values given than there are palette entries\n            for (size_t i = 0; i < chunkLength; i++) info.palette[4 * i + 3] = in[pos++];\n          }\n          else if (info.colorType == 0)\n          {\n            if (chunkLength != 2) { error = 40; return; } //error: this chunk must be 2 bytes for greyscale image\n            info.key_defined = 1; info.key_r = info.key_g = info.key_b = 256 * in[pos] + in[pos + 1]; pos += 2;\n          }\n          else if (info.colorType == 2)\n          {\n            if (chunkLength != 6) { error = 41; return; } //error: this chunk must be 6 bytes for RGB image\n            info.key_defined = 1;\n            info.key_r = 256 * in[pos] + in[pos + 1]; pos += 2;\n            info.key_g = 256 * in[pos] + in[pos + 1]; pos += 2;\n            info.key_b = 256 * in[pos] + in[pos + 1]; pos += 2;\n          }\n          else { error = 42; return; } //error: tRNS chunk not allowed for other color models\n        }\n        else //it's not an implemented chunk type, so ignore it: skip over the data\n        {\n          if (!(in[pos + 0] & 32)) { error = 69; return; } //error: unknown critical chunk (5th bit of first byte of chunk type is 0)\n          pos += (chunkLength + 4); //skip 4 letters and uninterpreted data of unimplemented chunk\n          known_type = false;\n        }\n        pos += 4; //step over CRC (which is ignored)\n      }\n      unsigned long bpp = getBpp(info);\n      std::vector<unsigned char> scanlines(((info.width * (info.height * bpp + 7)) / 8) + info.height); //now the out buffer will be filled\n      Zlib zlib; //decompress with the Zlib decompressor\n      error = zlib.decompress(scanlines, idat); if (error) return; //stop if the zlib decompressor returned an error\n      size_t bytewidth = (bpp + 7) / 8, outlength = (info.height * info.width * bpp + 7) / 8;\n      out.resize(outlength); //time to fill the out buffer\n      unsigned char* out_ = outlength ? &out[0] : 0; //use a regular pointer to the std::vector for faster code if compiled without optimization\n      if (info.interlaceMethod == 0) //no interlace, just filter\n      {\n        size_t linestart = 0, linelength = (info.width * bpp + 7) / 8; //length in bytes of a scanline, excluding the filtertype byte\n        if (bpp >= 8) //byte per byte\n          for (unsigned long y = 0; y < info.height; y++)\n          {\n            unsigned long filterType = scanlines[linestart];\n            const unsigned char* prevline = (y == 0) ? 0 : &out_[(y - 1) * info.width * bytewidth];\n            unFilterScanline(&out_[linestart - y], &scanlines[linestart + 1], prevline, bytewidth, filterType, linelength); if (error) return;\n            linestart += (1 + linelength); //go to start of next scanline\n          }\n        else //less than 8 bits per pixel, so fill it up bit per bit\n        {\n          std::vector<unsigned char> templine((info.width * bpp + 7) >> 3); //only used if bpp < 8\n          for (size_t y = 0, obp = 0; y < info.height; y++)\n          {\n            unsigned long filterType = scanlines[linestart];\n            const unsigned char* prevline = (y == 0) ? 0 : &out_[(y - 1) * info.width * bytewidth];\n            unFilterScanline(&templine[0], &scanlines[linestart + 1], prevline, bytewidth, filterType, linelength); if (error) return;\n            for (size_t bp = 0; bp < info.width * bpp;) setBitOfReversedStream(obp, out_, readBitFromReversedStream(bp, &templine[0]));\n            linestart += (1 + linelength); //go to start of next scanline\n          }\n        }\n      }\n      else //interlaceMethod is 1 (Adam7)\n      {\n        size_t passw[7] = { (info.width + 7) / 8, (info.width + 3) / 8, (info.width + 3) / 4, (info.width + 1) / 4, (info.width + 1) / 2, (info.width + 0) / 2, (info.width + 0) / 1 };\n        size_t passh[7] = { (info.height + 7) / 8, (info.height + 7) / 8, (info.height + 3) / 8, (info.height + 3) / 4, (info.height + 1) / 4, (info.height + 1) / 2, (info.height + 0) / 2 };\n        size_t passstart[7] = { 0 };\n        size_t pattern[28] = { 0,4,0,2,0,1,0,0,0,4,0,2,0,1,8,8,4,4,2,2,1,8,8,8,4,4,2,2 }; //values for the adam7 passes\n        for (int i = 0; i < 6; i++) passstart[i + 1] = passstart[i] + passh[i] * ((passw[i] ? 1 : 0) + (passw[i] * bpp + 7) / 8);\n        std::vector<unsigned char> scanlineo((info.width * bpp + 7) / 8), scanlinen((info.width * bpp + 7) / 8); //\"old\" and \"new\" scanline\n        for (int i = 0; i < 7; i++)\n          adam7Pass(&out_[0], &scanlinen[0], &scanlineo[0], &scanlines[passstart[i]], info.width, pattern[i], pattern[i + 7], pattern[i + 14], pattern[i + 21], passw[i], passh[i], bpp);\n      }\n      if (convert_to_rgba32 && (info.colorType != 6 || info.bitDepth != 8)) //conversion needed\n      {\n        std::vector<unsigned char> data = out;\n        error = convert(out, &data[0], info, info.width, info.height);\n      }\n    }\n    void readPngHeader(const unsigned char* in, size_t inlength) //read the information from the header and store it in the Info\n    {\n      if (inlength < 29) { error = 27; return; } //error: the data length is smaller than the length of the header\n      if (in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) { error = 28; return; } //no PNG signature\n      if (in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R') { error = 29; return; } //error: it doesn't start with a IHDR chunk!\n      info.width = read32bitInt(&in[16]); info.height = read32bitInt(&in[20]);\n      info.bitDepth = in[24]; info.colorType = in[25];\n      info.compressionMethod = in[26]; if (in[26] != 0) { error = 32; return; } //error: only compression method 0 is allowed in the specification\n      info.filterMethod = in[27]; if (in[27] != 0) { error = 33; return; } //error: only filter method 0 is allowed in the specification\n      info.interlaceMethod = in[28]; if (in[28] > 1) { error = 34; return; } //error: only interlace methods 0 and 1 exist in the specification\n      error = checkColorValidity(info.colorType, info.bitDepth);\n    }\n    void unFilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, size_t bytewidth, unsigned long filterType, size_t length)\n    {\n      switch (filterType)\n      {\n      case 0: for (size_t i = 0; i < length; i++) recon[i] = scanline[i]; break;\n      case 1:\n        for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i];\n        for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth];\n        break;\n      case 2:\n        if (precon) for (size_t i = 0; i < length; i++) recon[i] = scanline[i] + precon[i];\n        else       for (size_t i = 0; i < length; i++) recon[i] = scanline[i];\n        break;\n      case 3:\n        if (precon)\n        {\n          for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i] + precon[i] / 2;\n          for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2);\n        }\n        else\n        {\n          for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i];\n          for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth] / 2;\n        }\n        break;\n      case 4:\n        if (precon)\n        {\n          for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i] + paethPredictor(0, precon[i], 0);\n          for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]);\n        }\n        else\n        {\n          for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i];\n          for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + paethPredictor(recon[i - bytewidth], 0, 0);\n        }\n        break;\n      default: error = 36; return; //error: unexisting filter type given\n      }\n    }\n    void adam7Pass(unsigned char* out, unsigned char* linen, unsigned char* lineo, const unsigned char* in, unsigned long w, size_t passleft, size_t passtop, size_t spacex, size_t spacey, size_t passw, size_t passh, unsigned long bpp)\n    { //filter and reposition the pixels into the output when the image is Adam7 interlaced. This function can only do it after the full image is already decoded. The out buffer must have the correct allocated memory size already.\n      if (passw == 0) return;\n      size_t bytewidth = (bpp + 7) / 8, linelength = 1 + ((bpp * passw + 7) / 8);\n      for (unsigned long y = 0; y < passh; y++)\n      {\n        unsigned char filterType = in[y * linelength], *prevline = (y == 0) ? 0 : lineo;\n        unFilterScanline(linen, &in[y * linelength + 1], prevline, bytewidth, filterType, (w * bpp + 7) / 8); if (error) return;\n        if (bpp >= 8) for (size_t i = 0; i < passw; i++) for (size_t b = 0; b < bytewidth; b++) //b = current byte of this pixel\n          out[bytewidth * w * (passtop + spacey * y) + bytewidth * (passleft + spacex * i) + b] = linen[bytewidth * i + b];\n        else for (size_t i = 0; i < passw; i++)\n        {\n          size_t obp = bpp * w * (passtop + spacey * y) + bpp * (passleft + spacex * i), bp = i * bpp;\n          for (size_t b = 0; b < bpp; b++) setBitOfReversedStream(obp, out, readBitFromReversedStream(bp, &linen[0]));\n        }\n        unsigned char* temp = linen; linen = lineo; lineo = temp; //swap the two buffer pointers \"line old\" and \"line new\"\n      }\n    }\n    static unsigned long readBitFromReversedStream(size_t& bitp, const unsigned char* bits) { unsigned long result = (bits[bitp >> 3] >> (7 - (bitp & 0x7))) & 1; bitp++; return result; }\n    static unsigned long readBitsFromReversedStream(size_t& bitp, const unsigned char* bits, unsigned long nbits)\n    {\n      unsigned long result = 0;\n      for (size_t i = nbits - 1; i < nbits; i--) result += ((readBitFromReversedStream(bitp, bits)) << i);\n      return result;\n    }\n    void setBitOfReversedStream(size_t& bitp, unsigned char* bits, unsigned long bit) { bits[bitp >> 3] |= (bit << (7 - (bitp & 0x7))); bitp++; }\n    unsigned long read32bitInt(const unsigned char* buffer) { return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; }\n    int checkColorValidity(unsigned long colorType, unsigned long bd) //return type is a LodePNG error code\n    {\n      if ((colorType == 2 || colorType == 4 || colorType == 6)) { if (!(bd == 8 || bd == 16)) return 37; else return 0; }\n      else if (colorType == 0) { if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; else return 0; }\n      else if (colorType == 3) { if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8)) return 37; else return 0; }\n      else return 31; //unexisting color type\n    }\n    unsigned long getBpp(const Info& info)\n    {\n      if (info.colorType == 2) return (3 * info.bitDepth);\n      else if (info.colorType >= 4) return (info.colorType - 2) * info.bitDepth;\n      else return info.bitDepth;\n    }\n    int convert(std::vector<unsigned char>& out, const unsigned char* in, Info& infoIn, unsigned long w, unsigned long h)\n    { //converts from any color type to 32-bit. return value = LodePNG error code\n      size_t numpixels = w * h, bp = 0;\n      out.resize(numpixels * 4);\n      unsigned char* out_ = out.empty() ? 0 : &out[0]; //faster if compiled without optimization\n      if (infoIn.bitDepth == 8 && infoIn.colorType == 0) //greyscale\n        for (size_t i = 0; i < numpixels; i++)\n        {\n          out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[i];\n          out_[4 * i + 3] = (infoIn.key_defined && in[i] == infoIn.key_r) ? 0 : 255;\n        }\n      else if (infoIn.bitDepth == 8 && infoIn.colorType == 2) //RGB color\n        for (size_t i = 0; i < numpixels; i++)\n        {\n          for (size_t c = 0; c < 3; c++) out_[4 * i + c] = in[3 * i + c];\n          out_[4 * i + 3] = (infoIn.key_defined == 1 && in[3 * i + 0] == infoIn.key_r && in[3 * i + 1] == infoIn.key_g && in[3 * i + 2] == infoIn.key_b) ? 0 : 255;\n        }\n      else if (infoIn.bitDepth == 8 && infoIn.colorType == 3) //indexed color (palette)\n        for (size_t i = 0; i < numpixels; i++)\n        {\n          if (4U * in[i] >= infoIn.palette.size()) return 46;\n          for (size_t c = 0; c < 4; c++) out_[4 * i + c] = infoIn.palette[4 * in[i] + c]; //get rgb colors from the palette\n        }\n      else if (infoIn.bitDepth == 8 && infoIn.colorType == 4) //greyscale with alpha\n        for (size_t i = 0; i < numpixels; i++)\n        {\n          out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[2 * i + 0];\n          out_[4 * i + 3] = in[2 * i + 1];\n        }\n      else if (infoIn.bitDepth == 8 && infoIn.colorType == 6) for (size_t i = 0; i < numpixels; i++) for (size_t c = 0; c < 4; c++) out_[4 * i + c] = in[4 * i + c]; //RGB with alpha\n      else if (infoIn.bitDepth == 16 && infoIn.colorType == 0) //greyscale\n        for (size_t i = 0; i < numpixels; i++)\n        {\n          out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[2 * i];\n          out_[4 * i + 3] = (infoIn.key_defined && 256U * in[i] + in[i + 1] == infoIn.key_r) ? 0 : 255;\n        }\n      else if (infoIn.bitDepth == 16 && infoIn.colorType == 2) //RGB color\n        for (size_t i = 0; i < numpixels; i++)\n        {\n          for (size_t c = 0; c < 3; c++) out_[4 * i + c] = in[6 * i + 2 * c];\n          out_[4 * i + 3] = (infoIn.key_defined && 256U * in[6 * i + 0] + in[6 * i + 1] == infoIn.key_r && 256U * in[6 * i + 2] + in[6 * i + 3] == infoIn.key_g && 256U * in[6 * i + 4] + in[6 * i + 5] == infoIn.key_b) ? 0 : 255;\n        }\n      else if (infoIn.bitDepth == 16 && infoIn.colorType == 4) //greyscale with alpha\n        for (size_t i = 0; i < numpixels; i++)\n        {\n          out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[4 * i]; //most significant byte\n          out_[4 * i + 3] = in[4 * i + 2];\n        }\n      else if (infoIn.bitDepth == 16 && infoIn.colorType == 6) for (size_t i = 0; i < numpixels; i++) for (size_t c = 0; c < 4; c++) out_[4 * i + c] = in[8 * i + 2 * c]; //RGB with alpha\n      else if (infoIn.bitDepth < 8 && infoIn.colorType == 0) //greyscale\n        for (size_t i = 0; i < numpixels; i++)\n        {\n          unsigned long value = (readBitsFromReversedStream(bp, in, infoIn.bitDepth) * 255) / ((1 << infoIn.bitDepth) - 1); //scale value from 0 to 255\n          out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = (unsigned char)(value);\n          out_[4 * i + 3] = (infoIn.key_defined && value && ((1U << infoIn.bitDepth) - 1U) == infoIn.key_r && ((1U << infoIn.bitDepth) - 1U)) ? 0 : 255;\n        }\n      else if (infoIn.bitDepth < 8 && infoIn.colorType == 3) //palette\n        for (size_t i = 0; i < numpixels; i++)\n        {\n          unsigned long value = readBitsFromReversedStream(bp, in, infoIn.bitDepth);\n          if (4 * value >= infoIn.palette.size()) return 47;\n          for (size_t c = 0; c < 4; c++) out_[4 * i + c] = infoIn.palette[4 * value + c]; //get rgb colors from the palette\n        }\n      return 0;\n    }\n    unsigned char paethPredictor(short a, short b, short c) //Paeth predicter, used by PNG filter type 4\n    {\n      short p = a + b - c, pa = p > a ? (p - a) : (a - p), pb = p > b ? (p - b) : (b - p), pc = p > c ? (p - c) : (c - p);\n      return (unsigned char)((pa <= pb && pa <= pc) ? a : pb <= pc ? b : c);\n    }\n  };\n  PNG decoder; decoder.decode(out_image, in_png, in_size, convert_to_rgba32);\n  image_width = decoder.info.width; image_height = decoder.info.height;\n  return decoder.error;\n}\n\nint Platform::loadPNG(std::vector<unsigned char>& out_image, unsigned long& image_width, unsigned long& image_height, const unsigned char* in_png, size_t in_size, bool convert_to_rgba32) \n{\n  return decodePNG(out_image, image_width, image_height, in_png, in_size, convert_to_rgba32);\n}\n\n#endif"
  },
  {
    "path": "src/io/stegano.cpp",
    "content": "#include \"stegano.h\"\r\n\r\n#include <cassert>\r\n#include <algorithm>\r\n\r\nusing namespace retro8;\r\nusing namespace io;\r\n\r\nconstexpr size_t RAW_DATA_LENGTH = 0x4300;\r\nconstexpr size_t MAGIC_LENGTH = 4;\r\nconstexpr size_t HEADER_20_LENGTH = 8;\r\n\r\n#if DEBUGGER\r\n#include <fstream>\r\nstatic std::string fileName = \"foo.p8\";\r\n#endif\r\n\r\nuint8_t Stegano::assembleByte(const uint32_t v)\r\n{\r\n  constexpr uint32_t MASK_ALPHA = 0xff000000;\r\n  constexpr uint32_t MASK_RED = 0x00ff0000;\r\n  constexpr uint32_t MASK_GREEN = 0x0000ff00;\r\n  constexpr uint32_t MASK_BLUE = 0x000000ff;\r\n\r\n  constexpr uint32_t SHIFT_ALPHA = 24;\r\n  constexpr uint32_t SHIFT_RED = 16;\r\n  constexpr uint32_t SHIFT_GREEN = 8;\r\n  constexpr uint32_t SHIFT_BLUE = 0;\r\n\r\n  return\r\n    ((((v & MASK_ALPHA) >> SHIFT_ALPHA) & 0b11) << 6) |\r\n    ((((v & MASK_RED) >> SHIFT_RED) & 0b11) << 0) |\r\n    ((((v & MASK_GREEN) >> SHIFT_GREEN) & 0b11) << 2) |\r\n    ((((v & MASK_BLUE) >> SHIFT_BLUE) & 0b11) << 4);\r\n}\r\n\r\n\r\n\r\nclass PXADecoder\r\n{\r\npublic:\r\n  const uint8_t* data;\r\n  size_t b; /* bit index */\r\n  size_t o; /* byte index */\r\n  size_t expected;\r\n  std::array<uint8_t, 256> m;\r\n\r\nprivate:\r\n  bool readBit()\r\n  {\r\n    int v = data[o] & (1 << b);\r\n    ++b;\r\n\r\n    if (b == 8)\r\n    {\r\n      b = 0;\r\n      ++o;\r\n    }\r\n\r\n    return v;\r\n  }\r\n\r\n  int32_t readBits(size_t c)\r\n  {\r\n    int32_t r = 0;\r\n    for (size_t i = 0; i < c; ++i)\r\n      if (readBit())\r\n        r |= 1 << i;\r\n\r\n    return r;\r\n  }\r\n\r\n  void moveToFront(size_t i)\r\n  {\r\n    int v = m[i];\r\n    for (int j = i; j > 0; --j)\r\n      m[j] = m[j - 1];\r\n    m[0] = v;\r\n  }\r\n\r\npublic:\r\n  PXADecoder(const uint8_t* data, size_t expected) : data(data), b(0), o(0), expected(expected)\r\n  {\r\n    /* initalize mapping, each value to itself */\r\n    //TODO\r\n    for (size_t i = 0; i < m.size(); ++i)\r\n      m[i] = i;\r\n  }\r\n\r\n  std::string process()\r\n  {\r\n    std::string code;\r\n    while (code.size() < expected)\r\n    {\r\n      bool h = readBit();\r\n\r\n      /* read index to move to front, and output value */\r\n      if (h == 1)\r\n      {\r\n        int unary = 0;\r\n        while (readBit())\r\n          ++unary;\r\n\r\n        uint8_t unaryMask = ((1 << unary) - 1);\r\n        uint8_t index = readBits(4 + unary) + (unaryMask << 4);\r\n\r\n        code += m[index];\r\n        moveToFront(index);\r\n      }\r\n      /* copy section */\r\n      else\r\n      {\r\n        /* read offset */\r\n        int32_t offsetBits;\r\n\r\n        if (readBit())\r\n          offsetBits = readBit() ? 5 : 10;\r\n        else\r\n          offsetBits = 15;\r\n\r\n        auto offset = readBits(offsetBits) + 1;\r\n\r\n        /* special hacky case in which bytes are directly emitted without\r\n           affecting move-to-front\r\n         */\r\n        if (offsetBits == 10 && offset == 1)\r\n        {\r\n          uint8_t v = readBits(8);\r\n          while (v)\r\n          {\r\n            code += v;\r\n            v = readBits(8);\r\n          }\r\n        }\r\n        else\r\n        {\r\n          /* read length */\r\n          int32_t length = 3, part = 0;\r\n          do\r\n          {\r\n            part = readBits(3);\r\n            length += part;\r\n          } while (part == 0b111);\r\n\r\n          assert(offset <= code.size());\r\n\r\n          size_t start = code.size() - offset;\r\n          for (int32_t l = 0; l < length; ++l)\r\n          {\r\n            code += code[start + l];\r\n          }\r\n        }\r\n      }\r\n\r\n    }\r\n\r\n    return code;\r\n  }\r\n\r\n};\r\n\r\n\r\nvoid Stegano::load20(const PngData& data, Machine& m)\r\n{\r\n  auto* d = data.data;\r\n  size_t o = RAW_DATA_LENGTH + MAGIC_LENGTH;\r\n\r\n  size_t decompressedLength = assembleByte(d[o++]) << 8 | assembleByte(d[o++]);\r\n  size_t compressedLength = assembleByte(d[o++]) << 8 | assembleByte(d[o++]);\r\n  compressedLength -= HEADER_20_LENGTH; /* subtract header length */\r\n\r\n  compressedLength = std::min(size_t(32769ULL - RAW_DATA_LENGTH), compressedLength);\r\n\r\n  assert(o == RAW_DATA_LENGTH + HEADER_20_LENGTH);\r\n\r\n  std::vector<uint8_t> assembled(compressedLength);\r\n  std::generate(assembled.begin(), assembled.end(), [this, &d, &o] () { return assembleByte(d[o++]); });\r\n\r\n  assert(o == RAW_DATA_LENGTH + HEADER_20_LENGTH + compressedLength);\r\n\r\n  auto decoder = PXADecoder(assembled.data(), decompressedLength);\r\n  std::string code = decoder.process();\r\n\r\n#if DEBUGGER\r\n  std::ofstream output(fileName);\r\n  output << code;\r\n  output.close();\r\n#endif\r\n\r\n  m.code().initFromSource(code);\r\n}\r\n\r\nvoid Stegano::load10(const PngData& data, Machine& m)\r\n{\r\n  auto* d = data.data;\r\n  size_t o = RAW_DATA_LENGTH + MAGIC_LENGTH;\r\n\r\n  /* read uint6_t msb compressed length*/\r\n  size_t compressedLength = assembleByte(d[o]) << 8 | assembleByte(d[o + 1]);\r\n  o += 2;\r\n  /* skip 2 null*/\r\n  o += 2;\r\n\r\n  compressedLength = std::min(size_t(32769ULL - RAW_DATA_LENGTH), compressedLength);\r\n\r\n  const std::string lookup = \"\\n 0123456789abcdefghijklmnopqrstuvwxyz!#%(){}[]<>+=/*:;.,~_\";\r\n  std::string code;\r\n\r\n  assert(0x3b == lookup.length());\r\n  //TODO: optimize concatenation on string by reserving space\r\n\r\n  for (size_t i = 0; i < compressedLength; ++i)\r\n  {\r\n    uint8_t v = assembleByte(d[o + i]);\r\n\r\n    /* copy next */\r\n    if (v == 0x00)\r\n    {\r\n      uint8_t vn = assembleByte(d[o + i + 1]);\r\n      code += vn;\r\n      ++i;\r\n    }\r\n    /* lookup */\r\n    else if (v <= 0x3b)\r\n    {\r\n      code += lookup[v - 1];\r\n    }\r\n    else\r\n    {\r\n      uint8_t vn = assembleByte(d[o + i + 1]);\r\n\r\n      auto offset = ((v - 0x3c) << 4) + (vn & 0xf);\r\n      auto length = (vn >> 4) + 2;\r\n\r\n      const size_t start = code.length() - offset;\r\n      for (size_t j = 0; j < length; ++j)\r\n        code += code[start + j];\r\n\r\n      ++i;\r\n    }\r\n  }\r\n\r\n#if DEBUGGER\r\n  std::ofstream output(fileName);\r\n  output << code;\r\n  output.close();\r\n#endif\r\n\r\n  m.code().initFromSource(code);\r\n}\r\n\r\n\r\nvoid Stegano::load(const PngData& data, Machine& m)\r\n{\r\n  constexpr size_t SPRITE_SHEET_SIZE = gfx::SPRITE_SHEET_HEIGHT * gfx::SPRITE_SHEET_WIDTH / gfx::PIXEL_TO_BYTE_RATIO;\r\n  constexpr size_t TILE_MAP_SIZE = gfx::TILE_MAP_WIDTH * gfx::TILE_MAP_HEIGHT * sizeof(sprite_index_t) / 2;\r\n  constexpr size_t SPRITE_FLAGS_SIZE = gfx::SPRITE_COUNT * sizeof(sprite_flags_t);\r\n  constexpr size_t MUSIC_SIZE = sfx::MUSIC_COUNT * sizeof(sfx::music_t);\r\n  constexpr size_t SOUND_SIZE = sfx::SOUND_COUNT * sizeof(sfx::sound_t);\r\n\r\n  static_assert(sizeof(sfx::music_t) == 4, \"Must be 4 bytes\");\r\n  static_assert(sizeof(sfx::sound_t) == 68, \"Must be 68 bytes\");\r\n\r\n  static_assert(RAW_DATA_LENGTH == SPRITE_SHEET_SIZE + TILE_MAP_SIZE + SPRITE_FLAGS_SIZE + MUSIC_SIZE + SOUND_SIZE, \"Must be equal\");\r\n  assert(data.length == IMAGE_WIDTH * IMAGE_HEIGHT);\r\n\r\n  auto* d = data.data;\r\n\r\n  /* first 0x4300 are read directly into the cart */\r\n  for (size_t i = 0; i < RAW_DATA_LENGTH; ++i)\r\n    m.memory().base()[i] = assembleByte(d[i]);\r\n\r\n  size_t o = RAW_DATA_LENGTH;\r\n  std::array<uint8_t, MAGIC_LENGTH> magic;\r\n\r\n  /* two different magic numbers according to version */\r\n  std::array<uint8_t, MAGIC_LENGTH> expected = { { ':', 'c', ':', '\\0' } };\r\n  std::array<uint8_t, MAGIC_LENGTH> expected2 = { { '\\0', 'p', 'x', 'a' } };\r\n\r\n  /* read magic code heaader */\r\n  for (size_t i = 0; i < magic.size(); ++i)\r\n    magic[i] = assembleByte(d[o++]);\r\n\r\n  /* use different algorithms according to cartridge version */\r\n  if (magic == expected)\r\n    load10(data, m);\r\n  else if (magic == expected2)\r\n    load20(data, m);\r\n  else\r\n    assert(false);\r\n\r\n\r\n}\r\n"
  },
  {
    "path": "src/io/stegano.h",
    "content": "#pragma once\r\n\r\n#include \"common.h\"\r\n\r\n#include \"vm/machine.h\"\r\n\r\nnamespace retro8\r\n{\r\n  namespace io\r\n  {\r\n    struct PngData\r\n    {\r\n      const uint32_t* data;\r\n      void* userData;\r\n      size_t length;\r\n    };\r\n\r\n    class Stegano\r\n    {\r\n    public:\r\n      static constexpr size_t IMAGE_WIDTH = 160;\r\n      static constexpr size_t IMAGE_HEIGHT = 205;\r\n\r\n    private:\r\n      uint8_t assembleByte(const uint32_t v);\r\n\r\n      void load10(const PngData& data, Machine& dest);\r\n      void load20(const PngData& data, Machine& dest);\r\n\r\n    public:\r\n      void load(const PngData& data, Machine& dest);\r\n    };\r\n  }\r\n}"
  },
  {
    "path": "src/libretro/libretro.cpp",
    "content": "#include \"libretro.h\"\n\n#include \"common.h\"\n#include \"vm/gfx.h\"\n\n#include \"io/loader.h\"\n#include \"io/stegano.h\"\n#include \"vm/machine.h\"\n#include \"vm/input.h\"\n\n#include <cstdarg>\n#include <cstring>\n\n#define LIBRETRO_LOG(x, ...) env.logger(retro_log_level::RETRO_LOG_INFO, x # __VA_ARGS__)\n\nnamespace r8 = retro8;\nusing pixel_t = uint32_t;\n\nconstexpr int SAMPLE_RATE = 44100;\nconstexpr int SAMPLES_PER_FRAME = SAMPLE_RATE / 60;\nconstexpr int SOUND_CHANNELS = 2;\n\nr8::Machine machine;\nr8::io::Loader loader;\n\nr8::input::InputManager input;\nr8::gfx::ColorTable colorTable;\npixel_t* screen;\nint16_t* audioBuffer;\n\nstatic void fallback_log(enum retro_log_level level, const char *fmt, ...)\n{\n  (void)level;\n  va_list va;\n  va_start(va, fmt);\n  vfprintf(stderr, fmt, va);\n  va_end(va);\n}\n\nstruct RetroArchEnv\n{\n  retro_video_refresh_t video;\n  retro_audio_sample_t audio;\n  retro_audio_sample_batch_t audioBatch;\n  retro_input_poll_t inputPoll;\n  retro_input_state_t inputState;\n  retro_log_printf_t logger = fallback_log;\n\n  uint32_t frameCounter;\n  uint16_t buttonState;\n};\n\nRetroArchEnv env;\n\nstruct ColorMapper\n{\n  r8::gfx::ColorTable::pixel_t operator()(uint8_t r, uint8_t g, uint8_t b) const { return 0xff000000 | (r << 16) | (g << 8) | b; }\n};\n\n//TODO\nuint32_t Platform::getTicks() { return 0; }\n\nextern \"C\"\n{\n  unsigned retro_api_version()\n  {\n    return RETRO_API_VERSION;\n  }\n\n  void retro_init()\n  {\n    screen = new pixel_t[r8::gfx::SCREEN_WIDTH * r8::gfx::SCREEN_HEIGHT];\n    env.logger(retro_log_level::RETRO_LOG_INFO, \"Initializing screen buffer of %d bytes\\n\", sizeof(pixel_t)*r8::gfx::SCREEN_WIDTH*r8::gfx::SCREEN_HEIGHT);\n\n    audioBuffer = new int16_t[SAMPLE_RATE * 2];\n    env.logger(retro_log_level::RETRO_LOG_INFO, \"Initializing audio buffer of %d bytes\\n\", sizeof(int16_t) * SAMPLE_RATE * 2);\n\n    colorTable.init(ColorMapper());\n    machine.font().load();\n    machine.code().loadAPI();\n    input.setMachine(&machine);\n  }\n\n  void retro_deinit()\n  {\n    delete[] screen;\n    delete[] audioBuffer;\n    //TODO: release all structures bound to Lua etc\n  }\n\n  void retro_get_system_info(retro_system_info* info)\n  {\n    std::memset(info, 0, sizeof(info));\n\n    info->library_name = \"retro-8 (alpha)\";\n    info->library_version = \"0.1b\";\n    info->need_fullpath = false;\n    info->valid_extensions = \"p8|png\";\n  }\n\n  void retro_get_system_av_info(retro_system_av_info* info)\n  {\n    info->timing.fps = 60.0f;\n    info->timing.sample_rate = SAMPLE_RATE;\n    info->geometry.base_width = retro8::gfx::SCREEN_WIDTH;\n    info->geometry.base_height = retro8::gfx::SCREEN_HEIGHT;\n    info->geometry.max_width = retro8::gfx::SCREEN_WIDTH;\n    info->geometry.max_height = retro8::gfx::SCREEN_HEIGHT;\n    info->geometry.aspect_ratio = retro8::gfx::SCREEN_WIDTH / float(retro8::gfx::SCREEN_HEIGHT);\n  }\n\n  void retro_set_environment(retro_environment_t e)\n  {\n    retro_pixel_format pixelFormat = RETRO_PIXEL_FORMAT_XRGB8888;\n    e(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &pixelFormat);\n\n    retro_log_callback logger;\n    if (e(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &logger))\n      env.logger = logger.log;\n  }\n\n  void retro_set_video_refresh(retro_video_refresh_t callback) { env.video = callback; }\n  void retro_set_audio_sample(retro_audio_sample_t callback) { env.audio = callback; }\n  void retro_set_audio_sample_batch(retro_audio_sample_batch_t callback) { env.audioBatch = callback; }\n  void retro_set_input_poll(retro_input_poll_t callback) { env.inputPoll = callback; }\n  void retro_set_input_state(retro_input_state_t callback) { env.inputState = callback; }\n  void retro_set_controller_port_device(unsigned port, unsigned device) { /* TODO */ }\n  \n\n  size_t retro_serialize_size(void) { return 0; }\n  bool retro_serialize(void *data, size_t size) { return true; }\n  bool retro_unserialize(const void *data, size_t size) { return true; }\n  void retro_cheat_reset(void) { }\n  void retro_cheat_set(unsigned index, bool enabled, const char *code) { }\n  unsigned retro_get_region(void) { return 0; }\n  void *retro_get_memory_data(unsigned id) { return nullptr; }\n  size_t retro_get_memory_size(unsigned id) { return 0; }\n\n  bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info) { return false; }\n  bool retro_load_game(const retro_game_info* info)\n  {\n    if (info && info->data)\n    {\n      input.reset();\n\n      const char* bdata = static_cast<const char*>(info->data);\n\n      env.logger(RETRO_LOG_INFO, \"[Retro8] Loading %s\\n\", info->path);\n\n\n      if (std::memcmp(bdata, \"\\x89PNG\", 4) == 0)\n      {\n        env.logger(RETRO_LOG_INFO, \"[Retro8] Game is in PNG format, decoding it.\\n\");\n\n        std::vector<uint8_t> out;\n        unsigned long width, height;\n        auto result = Platform::loadPNG(out, width, height, (uint8_t*)bdata, info->size, true);\n        assert(result == 0);\n        r8::io::Stegano stegano;\n        stegano.load({ reinterpret_cast<const uint32_t*>(out.data()), nullptr, out.size() / 4 }, machine);\n      }\n      else\n      {\n        //TODO: not efficient since it's copied and it's not checking for '\\0'\n        std::string raw(bdata);\n        loader.loadRaw(raw, machine);\n      }\n\n      machine.memory().backupCartridge();\n\n      if (machine.code().hasInit())\n      {\n        //_initFuture = std::async(std::launch::async, []() {\n        LIBRETRO_LOG(\"[Retro8] Cartridge has _init() function, calling it.\");\n          machine.code().init();\n          LIBRETRO_LOG(\"[Retro8] _init() function completed execution.\");\n        //});\n      }\n\n      machine.sound().init();\n\n      env.frameCounter = 0;\n\n      return true;\n    }\n\n    return false;\n  }\n\n  void retro_unload_game(void)\n  {\n    /* TODO */\n  }\n\n  void retro_run()\n  {\n    /* if code is at 60fps or every 2 frames (30fps) */\n    if (machine.code().require60fps() || env.frameCounter % 2 == 0)\n    {\n      /* call _update and _draw of PICO-8 code */\n      machine.code().update();\n      machine.code().draw();\n\n      /* rasterize screen memory to ARGB framebuffer */\n      auto* data = machine.memory().screenData();\n      auto* screenPalette = machine.memory().paletteAt(retro8::gfx::SCREEN_PALETTE_INDEX);\n\n      auto pointer = screen;\n\n      for (size_t i = 0; i < r8::gfx::BYTES_PER_SCREEN; ++i)\n      {\n        const r8::gfx::color_byte_t* pixels = data + i;\n        const auto rc1 = colorTable.get(screenPalette->get((pixels)->low()));\n        const auto rc2 = colorTable.get(screenPalette->get((pixels)->high()));\n\n        *(pointer) = rc1;\n        *((pointer)+1) = rc2;\n        (pointer) += 2;\n      }\n\n      input.manageKeyRepeat();\n    }\n\n    env.video(screen, r8::gfx::SCREEN_WIDTH, r8::gfx::SCREEN_HEIGHT, r8::gfx::SCREEN_WIDTH * sizeof(pixel_t));\n    ++env.frameCounter;\n\n    machine.sound().renderSounds(audioBuffer, SAMPLES_PER_FRAME);\n    \n    /* duplicate channels */\n    auto* audioBuffer2 = audioBuffer + SAMPLE_RATE;\n    for (size_t i = 0; i < SAMPLES_PER_FRAME; ++i)\n    {\n      audioBuffer2[2*i] = audioBuffer[i];\n      audioBuffer2[2*i + 1] = audioBuffer[i];\n    }\n    \n    env.audioBatch(audioBuffer2, SAMPLES_PER_FRAME);\n\n    /* manage input */\n    {\n      struct BtPair {\n        unsigned player;\n        int16_t rabt;\n        size_t r8bt;\n        bool isSet;\n      };\n\n      static std::array<BtPair, retro8::BUTTON_COUNT + 2> mapping = { {\n        { 0, RETRO_DEVICE_ID_JOYPAD_LEFT, 0, false },\n        { 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, 1, false },\n        { 0, RETRO_DEVICE_ID_JOYPAD_UP, 2, false },\n        { 0, RETRO_DEVICE_ID_JOYPAD_DOWN, 3, false },\n        { 0, RETRO_DEVICE_ID_JOYPAD_A, 4, false },\n        { 0, RETRO_DEVICE_ID_JOYPAD_B, 5, false },\n        { 1, RETRO_DEVICE_ID_JOYPAD_X, 4, false },\n        { 1, RETRO_DEVICE_ID_JOYPAD_Y, 5, false },\n\n      } };\n\n\n      //TODO: add mapping for action1/2 of player 2 because it's used by some games\n\n      env.inputPoll();\n      for (auto& entry : mapping)\n      {\n        const bool isSet = env.inputState(entry.player, RETRO_DEVICE_JOYPAD, 0, entry.rabt);\n        const bool wasSet = entry.isSet;\n\n        if (wasSet != isSet)\n          input.manageKey(entry.player, entry.r8bt, isSet);\n\n        entry.isSet = isSet;\n      }\n\n      input.tick();\n    }\n\n  }\n\n  void retro_reset()\n  {\n\n  }\n}\n\n"
  },
  {
    "path": "src/libretro/libretro.h",
    "content": "/* Copyright (C) 2010-2018 The RetroArch team\n *\n * ---------------------------------------------------------------------------------------\n * The following license statement only applies to this libretro API header (libretro.h).\n * ---------------------------------------------------------------------------------------\n *\n * Permission is hereby granted, free of charge,\n * to any person obtaining a copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\n * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#ifndef LIBRETRO_H__\n#define LIBRETRO_H__\n\n#include <stdint.h>\n#include <stddef.h>\n#include <limits.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef __cplusplus\n#if defined(_MSC_VER) && _MSC_VER < 1800 && !defined(SN_TARGET_PS3)\n/* Hack applied for MSVC when compiling in C89 mode\n * as it isn't C99-compliant. */\n#define bool unsigned char\n#define true 1\n#define false 0\n#else\n#include <stdbool.h>\n#endif\n#endif\n\n#ifndef RETRO_CALLCONV\n#  if defined(__GNUC__) && defined(__i386__) && !defined(__x86_64__)\n#    define RETRO_CALLCONV __attribute__((cdecl))\n#  elif defined(_MSC_VER) && defined(_M_X86) && !defined(_M_X64)\n#    define RETRO_CALLCONV __cdecl\n#  else\n#    define RETRO_CALLCONV /* all other platforms only have one calling convention each */\n#  endif\n#endif\n\n#ifndef RETRO_API\n#  if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)\n#    ifdef RETRO_IMPORT_SYMBOLS\n#      ifdef __GNUC__\n#        define RETRO_API RETRO_CALLCONV __attribute__((__dllimport__))\n#      else\n#        define RETRO_API RETRO_CALLCONV __declspec(dllimport)\n#      endif\n#    else\n#      ifdef __GNUC__\n#        define RETRO_API RETRO_CALLCONV __attribute__((__dllexport__))\n#      else\n#        define RETRO_API RETRO_CALLCONV __declspec(dllexport)\n#      endif\n#    endif\n#  else\n#      if defined(__GNUC__) && __GNUC__ >= 4 && !defined(__CELLOS_LV2__)\n#        define RETRO_API RETRO_CALLCONV __attribute__((__visibility__(\"default\")))\n#      else\n#        define RETRO_API RETRO_CALLCONV\n#      endif\n#  endif\n#endif\n\n/* Used for checking API/ABI mismatches that can break libretro\n * implementations.\n * It is not incremented for compatible changes to the API.\n */\n#define RETRO_API_VERSION         1\n\n/*\n * Libretro's fundamental device abstractions.\n *\n * Libretro's input system consists of some standardized device types,\n * such as a joypad (with/without analog), mouse, keyboard, lightgun\n * and a pointer.\n *\n * The functionality of these devices are fixed, and individual cores\n * map their own concept of a controller to libretro's abstractions.\n * This makes it possible for frontends to map the abstract types to a\n * real input device, and not having to worry about binding input\n * correctly to arbitrary controller layouts.\n */\n\n#define RETRO_DEVICE_TYPE_SHIFT         8\n#define RETRO_DEVICE_MASK               ((1 << RETRO_DEVICE_TYPE_SHIFT) - 1)\n#define RETRO_DEVICE_SUBCLASS(base, id) (((id + 1) << RETRO_DEVICE_TYPE_SHIFT) | base)\n\n/* Input disabled. */\n#define RETRO_DEVICE_NONE         0\n\n/* The JOYPAD is called RetroPad. It is essentially a Super Nintendo\n * controller, but with additional L2/R2/L3/R3 buttons, similar to a\n * PS1 DualShock. */\n#define RETRO_DEVICE_JOYPAD       1\n\n/* The mouse is a simple mouse, similar to Super Nintendo's mouse.\n * X and Y coordinates are reported relatively to last poll (poll callback).\n * It is up to the libretro implementation to keep track of where the mouse\n * pointer is supposed to be on the screen.\n * The frontend must make sure not to interfere with its own hardware\n * mouse pointer.\n */\n#define RETRO_DEVICE_MOUSE        2\n\n/* KEYBOARD device lets one poll for raw key pressed.\n * It is poll based, so input callback will return with the current\n * pressed state.\n * For event/text based keyboard input, see\n * RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK.\n */\n#define RETRO_DEVICE_KEYBOARD     3\n\n/* LIGHTGUN device is similar to Guncon-2 for PlayStation 2.\n * It reports X/Y coordinates in screen space (similar to the pointer)\n * in the range [-0x8000, 0x7fff] in both axes, with zero being center and\n * -0x8000 being out of bounds.\n * As well as reporting on/off screen state. It features a trigger,\n * start/select buttons, auxiliary action buttons and a\n * directional pad. A forced off-screen shot can be requested for\n * auto-reloading function in some games.\n */\n#define RETRO_DEVICE_LIGHTGUN     4\n\n/* The ANALOG device is an extension to JOYPAD (RetroPad).\n * Similar to DualShock2 it adds two analog sticks and all buttons can\n * be analog. This is treated as a separate device type as it returns\n * axis values in the full analog range of [-0x7fff, 0x7fff],\n * although some devices may return -0x8000.\n * Positive X axis is right. Positive Y axis is down.\n * Buttons are returned in the range [0, 0x7fff].\n * Only use ANALOG type when polling for analog values.\n */\n#define RETRO_DEVICE_ANALOG       5\n\n/* Abstracts the concept of a pointing mechanism, e.g. touch.\n * This allows libretro to query in absolute coordinates where on the\n * screen a mouse (or something similar) is being placed.\n * For a touch centric device, coordinates reported are the coordinates\n * of the press.\n *\n * Coordinates in X and Y are reported as:\n * [-0x7fff, 0x7fff]: -0x7fff corresponds to the far left/top of the screen,\n * and 0x7fff corresponds to the far right/bottom of the screen.\n * The \"screen\" is here defined as area that is passed to the frontend and\n * later displayed on the monitor.\n *\n * The frontend is free to scale/resize this screen as it sees fit, however,\n * (X, Y) = (-0x7fff, -0x7fff) will correspond to the top-left pixel of the\n * game image, etc.\n *\n * To check if the pointer coordinates are valid (e.g. a touch display\n * actually being touched), PRESSED returns 1 or 0.\n *\n * If using a mouse on a desktop, PRESSED will usually correspond to the\n * left mouse button, but this is a frontend decision.\n * PRESSED will only return 1 if the pointer is inside the game screen.\n *\n * For multi-touch, the index variable can be used to successively query\n * more presses.\n * If index = 0 returns true for _PRESSED, coordinates can be extracted\n * with _X, _Y for index = 0. One can then query _PRESSED, _X, _Y with\n * index = 1, and so on.\n * Eventually _PRESSED will return false for an index. No further presses\n * are registered at this point. */\n#define RETRO_DEVICE_POINTER      6\n\n/* Buttons for the RetroPad (JOYPAD).\n * The placement of these is equivalent to placements on the\n * Super Nintendo controller.\n * L2/R2/L3/R3 buttons correspond to the PS1 DualShock.\n * Also used as id values for RETRO_DEVICE_INDEX_ANALOG_BUTTON */\n#define RETRO_DEVICE_ID_JOYPAD_B        0\n#define RETRO_DEVICE_ID_JOYPAD_Y        1\n#define RETRO_DEVICE_ID_JOYPAD_SELECT   2\n#define RETRO_DEVICE_ID_JOYPAD_START    3\n#define RETRO_DEVICE_ID_JOYPAD_UP       4\n#define RETRO_DEVICE_ID_JOYPAD_DOWN     5\n#define RETRO_DEVICE_ID_JOYPAD_LEFT     6\n#define RETRO_DEVICE_ID_JOYPAD_RIGHT    7\n#define RETRO_DEVICE_ID_JOYPAD_A        8\n#define RETRO_DEVICE_ID_JOYPAD_X        9\n#define RETRO_DEVICE_ID_JOYPAD_L       10\n#define RETRO_DEVICE_ID_JOYPAD_R       11\n#define RETRO_DEVICE_ID_JOYPAD_L2      12\n#define RETRO_DEVICE_ID_JOYPAD_R2      13\n#define RETRO_DEVICE_ID_JOYPAD_L3      14\n#define RETRO_DEVICE_ID_JOYPAD_R3      15\n\n#define RETRO_DEVICE_ID_JOYPAD_MASK    256\n\n/* Index / Id values for ANALOG device. */\n#define RETRO_DEVICE_INDEX_ANALOG_LEFT       0\n#define RETRO_DEVICE_INDEX_ANALOG_RIGHT      1\n#define RETRO_DEVICE_INDEX_ANALOG_BUTTON     2\n#define RETRO_DEVICE_ID_ANALOG_X             0\n#define RETRO_DEVICE_ID_ANALOG_Y             1\n\n/* Id values for MOUSE. */\n#define RETRO_DEVICE_ID_MOUSE_X                0\n#define RETRO_DEVICE_ID_MOUSE_Y                1\n#define RETRO_DEVICE_ID_MOUSE_LEFT             2\n#define RETRO_DEVICE_ID_MOUSE_RIGHT            3\n#define RETRO_DEVICE_ID_MOUSE_WHEELUP          4\n#define RETRO_DEVICE_ID_MOUSE_WHEELDOWN        5\n#define RETRO_DEVICE_ID_MOUSE_MIDDLE           6\n#define RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELUP    7\n#define RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELDOWN  8\n#define RETRO_DEVICE_ID_MOUSE_BUTTON_4         9\n#define RETRO_DEVICE_ID_MOUSE_BUTTON_5         10\n\n/* Id values for LIGHTGUN. */\n#define RETRO_DEVICE_ID_LIGHTGUN_SCREEN_X        13 /*Absolute Position*/\n#define RETRO_DEVICE_ID_LIGHTGUN_SCREEN_Y        14 /*Absolute*/\n#define RETRO_DEVICE_ID_LIGHTGUN_IS_OFFSCREEN    15 /*Status Check*/\n#define RETRO_DEVICE_ID_LIGHTGUN_TRIGGER          2\n#define RETRO_DEVICE_ID_LIGHTGUN_RELOAD          16 /*Forced off-screen shot*/\n#define RETRO_DEVICE_ID_LIGHTGUN_AUX_A            3\n#define RETRO_DEVICE_ID_LIGHTGUN_AUX_B            4\n#define RETRO_DEVICE_ID_LIGHTGUN_START            6\n#define RETRO_DEVICE_ID_LIGHTGUN_SELECT           7\n#define RETRO_DEVICE_ID_LIGHTGUN_AUX_C            8\n#define RETRO_DEVICE_ID_LIGHTGUN_DPAD_UP          9\n#define RETRO_DEVICE_ID_LIGHTGUN_DPAD_DOWN       10\n#define RETRO_DEVICE_ID_LIGHTGUN_DPAD_LEFT       11\n#define RETRO_DEVICE_ID_LIGHTGUN_DPAD_RIGHT      12\n/* deprecated */\n#define RETRO_DEVICE_ID_LIGHTGUN_X                0 /*Relative Position*/\n#define RETRO_DEVICE_ID_LIGHTGUN_Y                1 /*Relative*/\n#define RETRO_DEVICE_ID_LIGHTGUN_CURSOR           3 /*Use Aux:A*/\n#define RETRO_DEVICE_ID_LIGHTGUN_TURBO            4 /*Use Aux:B*/\n#define RETRO_DEVICE_ID_LIGHTGUN_PAUSE            5 /*Use Start*/\n\n/* Id values for POINTER. */\n#define RETRO_DEVICE_ID_POINTER_X         0\n#define RETRO_DEVICE_ID_POINTER_Y         1\n#define RETRO_DEVICE_ID_POINTER_PRESSED   2\n#define RETRO_DEVICE_ID_POINTER_COUNT     3\n\n/* Returned from retro_get_region(). */\n#define RETRO_REGION_NTSC  0\n#define RETRO_REGION_PAL   1\n\n/* Id values for LANGUAGE */\nenum retro_language\n{\n   RETRO_LANGUAGE_ENGLISH             = 0,\n   RETRO_LANGUAGE_JAPANESE            = 1,\n   RETRO_LANGUAGE_FRENCH              = 2,\n   RETRO_LANGUAGE_SPANISH             = 3,\n   RETRO_LANGUAGE_GERMAN              = 4,\n   RETRO_LANGUAGE_ITALIAN             = 5,\n   RETRO_LANGUAGE_DUTCH               = 6,\n   RETRO_LANGUAGE_PORTUGUESE_BRAZIL   = 7,\n   RETRO_LANGUAGE_PORTUGUESE_PORTUGAL = 8,\n   RETRO_LANGUAGE_RUSSIAN             = 9,\n   RETRO_LANGUAGE_KOREAN              = 10,\n   RETRO_LANGUAGE_CHINESE_TRADITIONAL = 11,\n   RETRO_LANGUAGE_CHINESE_SIMPLIFIED  = 12,\n   RETRO_LANGUAGE_ESPERANTO           = 13,\n   RETRO_LANGUAGE_POLISH              = 14,\n   RETRO_LANGUAGE_VIETNAMESE          = 15,\n   RETRO_LANGUAGE_ARABIC              = 16,\n   RETRO_LANGUAGE_GREEK               = 17,\n   RETRO_LANGUAGE_TURKISH             = 18,\n   RETRO_LANGUAGE_LAST,\n\n   /* Ensure sizeof(enum) == sizeof(int) */\n   RETRO_LANGUAGE_DUMMY          = INT_MAX\n};\n\n/* Passed to retro_get_memory_data/size().\n * If the memory type doesn't apply to the\n * implementation NULL/0 can be returned.\n */\n#define RETRO_MEMORY_MASK        0xff\n\n/* Regular save RAM. This RAM is usually found on a game cartridge,\n * backed up by a battery.\n * If save game data is too complex for a single memory buffer,\n * the SAVE_DIRECTORY (preferably) or SYSTEM_DIRECTORY environment\n * callback can be used. */\n#define RETRO_MEMORY_SAVE_RAM    0\n\n/* Some games have a built-in clock to keep track of time.\n * This memory is usually just a couple of bytes to keep track of time.\n */\n#define RETRO_MEMORY_RTC         1\n\n/* System ram lets a frontend peek into a game systems main RAM. */\n#define RETRO_MEMORY_SYSTEM_RAM  2\n\n/* Video ram lets a frontend peek into a game systems video RAM (VRAM). */\n#define RETRO_MEMORY_VIDEO_RAM   3\n\n/* Keysyms used for ID in input state callback when polling RETRO_KEYBOARD. */\nenum retro_key\n{\n   RETROK_UNKNOWN        = 0,\n   RETROK_FIRST          = 0,\n   RETROK_BACKSPACE      = 8,\n   RETROK_TAB            = 9,\n   RETROK_CLEAR          = 12,\n   RETROK_RETURN         = 13,\n   RETROK_PAUSE          = 19,\n   RETROK_ESCAPE         = 27,\n   RETROK_SPACE          = 32,\n   RETROK_EXCLAIM        = 33,\n   RETROK_QUOTEDBL       = 34,\n   RETROK_HASH           = 35,\n   RETROK_DOLLAR         = 36,\n   RETROK_AMPERSAND      = 38,\n   RETROK_QUOTE          = 39,\n   RETROK_LEFTPAREN      = 40,\n   RETROK_RIGHTPAREN     = 41,\n   RETROK_ASTERISK       = 42,\n   RETROK_PLUS           = 43,\n   RETROK_COMMA          = 44,\n   RETROK_MINUS          = 45,\n   RETROK_PERIOD         = 46,\n   RETROK_SLASH          = 47,\n   RETROK_0              = 48,\n   RETROK_1              = 49,\n   RETROK_2              = 50,\n   RETROK_3              = 51,\n   RETROK_4              = 52,\n   RETROK_5              = 53,\n   RETROK_6              = 54,\n   RETROK_7              = 55,\n   RETROK_8              = 56,\n   RETROK_9              = 57,\n   RETROK_COLON          = 58,\n   RETROK_SEMICOLON      = 59,\n   RETROK_LESS           = 60,\n   RETROK_EQUALS         = 61,\n   RETROK_GREATER        = 62,\n   RETROK_QUESTION       = 63,\n   RETROK_AT             = 64,\n   RETROK_LEFTBRACKET    = 91,\n   RETROK_BACKSLASH      = 92,\n   RETROK_RIGHTBRACKET   = 93,\n   RETROK_CARET          = 94,\n   RETROK_UNDERSCORE     = 95,\n   RETROK_BACKQUOTE      = 96,\n   RETROK_a              = 97,\n   RETROK_b              = 98,\n   RETROK_c              = 99,\n   RETROK_d              = 100,\n   RETROK_e              = 101,\n   RETROK_f              = 102,\n   RETROK_g              = 103,\n   RETROK_h              = 104,\n   RETROK_i              = 105,\n   RETROK_j              = 106,\n   RETROK_k              = 107,\n   RETROK_l              = 108,\n   RETROK_m              = 109,\n   RETROK_n              = 110,\n   RETROK_o              = 111,\n   RETROK_p              = 112,\n   RETROK_q              = 113,\n   RETROK_r              = 114,\n   RETROK_s              = 115,\n   RETROK_t              = 116,\n   RETROK_u              = 117,\n   RETROK_v              = 118,\n   RETROK_w              = 119,\n   RETROK_x              = 120,\n   RETROK_y              = 121,\n   RETROK_z              = 122,\n   RETROK_LEFTBRACE      = 123,\n   RETROK_BAR            = 124,\n   RETROK_RIGHTBRACE     = 125,\n   RETROK_TILDE          = 126,\n   RETROK_DELETE         = 127,\n\n   RETROK_KP0            = 256,\n   RETROK_KP1            = 257,\n   RETROK_KP2            = 258,\n   RETROK_KP3            = 259,\n   RETROK_KP4            = 260,\n   RETROK_KP5            = 261,\n   RETROK_KP6            = 262,\n   RETROK_KP7            = 263,\n   RETROK_KP8            = 264,\n   RETROK_KP9            = 265,\n   RETROK_KP_PERIOD      = 266,\n   RETROK_KP_DIVIDE      = 267,\n   RETROK_KP_MULTIPLY    = 268,\n   RETROK_KP_MINUS       = 269,\n   RETROK_KP_PLUS        = 270,\n   RETROK_KP_ENTER       = 271,\n   RETROK_KP_EQUALS      = 272,\n\n   RETROK_UP             = 273,\n   RETROK_DOWN           = 274,\n   RETROK_RIGHT          = 275,\n   RETROK_LEFT           = 276,\n   RETROK_INSERT         = 277,\n   RETROK_HOME           = 278,\n   RETROK_END            = 279,\n   RETROK_PAGEUP         = 280,\n   RETROK_PAGEDOWN       = 281,\n\n   RETROK_F1             = 282,\n   RETROK_F2             = 283,\n   RETROK_F3             = 284,\n   RETROK_F4             = 285,\n   RETROK_F5             = 286,\n   RETROK_F6             = 287,\n   RETROK_F7             = 288,\n   RETROK_F8             = 289,\n   RETROK_F9             = 290,\n   RETROK_F10            = 291,\n   RETROK_F11            = 292,\n   RETROK_F12            = 293,\n   RETROK_F13            = 294,\n   RETROK_F14            = 295,\n   RETROK_F15            = 296,\n\n   RETROK_NUMLOCK        = 300,\n   RETROK_CAPSLOCK       = 301,\n   RETROK_SCROLLOCK      = 302,\n   RETROK_RSHIFT         = 303,\n   RETROK_LSHIFT         = 304,\n   RETROK_RCTRL          = 305,\n   RETROK_LCTRL          = 306,\n   RETROK_RALT           = 307,\n   RETROK_LALT           = 308,\n   RETROK_RMETA          = 309,\n   RETROK_LMETA          = 310,\n   RETROK_LSUPER         = 311,\n   RETROK_RSUPER         = 312,\n   RETROK_MODE           = 313,\n   RETROK_COMPOSE        = 314,\n\n   RETROK_HELP           = 315,\n   RETROK_PRINT          = 316,\n   RETROK_SYSREQ         = 317,\n   RETROK_BREAK          = 318,\n   RETROK_MENU           = 319,\n   RETROK_POWER          = 320,\n   RETROK_EURO           = 321,\n   RETROK_UNDO           = 322,\n   RETROK_OEM_102        = 323,\n\n   RETROK_LAST,\n\n   RETROK_DUMMY          = INT_MAX /* Ensure sizeof(enum) == sizeof(int) */\n};\n\nenum retro_mod\n{\n   RETROKMOD_NONE       = 0x0000,\n\n   RETROKMOD_SHIFT      = 0x01,\n   RETROKMOD_CTRL       = 0x02,\n   RETROKMOD_ALT        = 0x04,\n   RETROKMOD_META       = 0x08,\n\n   RETROKMOD_NUMLOCK    = 0x10,\n   RETROKMOD_CAPSLOCK   = 0x20,\n   RETROKMOD_SCROLLOCK  = 0x40,\n\n   RETROKMOD_DUMMY = INT_MAX /* Ensure sizeof(enum) == sizeof(int) */\n};\n\n/* If set, this call is not part of the public libretro API yet. It can\n * change or be removed at any time. */\n#define RETRO_ENVIRONMENT_EXPERIMENTAL 0x10000\n/* Environment callback to be used internally in frontend. */\n#define RETRO_ENVIRONMENT_PRIVATE 0x20000\n\n/* Environment commands. */\n#define RETRO_ENVIRONMENT_SET_ROTATION  1  /* const unsigned * --\n                                            * Sets screen rotation of graphics.\n                                            * Valid values are 0, 1, 2, 3, which rotates screen by 0, 90, 180,\n                                            * 270 degrees counter-clockwise respectively.\n                                            */\n#define RETRO_ENVIRONMENT_GET_OVERSCAN  2  /* bool * --\n                                            * NOTE: As of 2019 this callback is considered deprecated in favor of\n                                            * using core options to manage overscan in a more nuanced, core-specific way.\n                                            *\n                                            * Boolean value whether or not the implementation should use overscan,\n                                            * or crop away overscan.\n                                            */\n#define RETRO_ENVIRONMENT_GET_CAN_DUPE  3  /* bool * --\n                                            * Boolean value whether or not frontend supports frame duping,\n                                            * passing NULL to video frame callback.\n                                            */\n\n                                           /* Environ 4, 5 are no longer supported (GET_VARIABLE / SET_VARIABLES),\n                                            * and reserved to avoid possible ABI clash.\n                                            */\n\n#define RETRO_ENVIRONMENT_SET_MESSAGE   6  /* const struct retro_message * --\n                                            * Sets a message to be displayed in implementation-specific manner\n                                            * for a certain amount of 'frames'.\n                                            * Should not be used for trivial messages, which should simply be\n                                            * logged via RETRO_ENVIRONMENT_GET_LOG_INTERFACE (or as a\n                                            * fallback, stderr).\n                                            */\n#define RETRO_ENVIRONMENT_SHUTDOWN      7  /* N/A (NULL) --\n                                            * Requests the frontend to shutdown.\n                                            * Should only be used if game has a specific\n                                            * way to shutdown the game from a menu item or similar.\n                                            */\n#define RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL 8\n                                           /* const unsigned * --\n                                            * Gives a hint to the frontend how demanding this implementation\n                                            * is on a system. E.g. reporting a level of 2 means\n                                            * this implementation should run decently on all frontends\n                                            * of level 2 and up.\n                                            *\n                                            * It can be used by the frontend to potentially warn\n                                            * about too demanding implementations.\n                                            *\n                                            * The levels are \"floating\".\n                                            *\n                                            * This function can be called on a per-game basis,\n                                            * as certain games an implementation can play might be\n                                            * particularly demanding.\n                                            * If called, it should be called in retro_load_game().\n                                            */\n#define RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY 9\n                                           /* const char ** --\n                                            * Returns the \"system\" directory of the frontend.\n                                            * This directory can be used to store system specific\n                                            * content such as BIOSes, configuration data, etc.\n                                            * The returned value can be NULL.\n                                            * If so, no such directory is defined,\n                                            * and it's up to the implementation to find a suitable directory.\n                                            *\n                                            * NOTE: Some cores used this folder also for \"save\" data such as\n                                            * memory cards, etc, for lack of a better place to put it.\n                                            * This is now discouraged, and if possible, cores should try to\n                                            * use the new GET_SAVE_DIRECTORY.\n                                            */\n#define RETRO_ENVIRONMENT_SET_PIXEL_FORMAT 10\n                                           /* const enum retro_pixel_format * --\n                                            * Sets the internal pixel format used by the implementation.\n                                            * The default pixel format is RETRO_PIXEL_FORMAT_0RGB1555.\n                                            * This pixel format however, is deprecated (see enum retro_pixel_format).\n                                            * If the call returns false, the frontend does not support this pixel\n                                            * format.\n                                            *\n                                            * This function should be called inside retro_load_game() or\n                                            * retro_get_system_av_info().\n                                            */\n#define RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS 11\n                                           /* const struct retro_input_descriptor * --\n                                            * Sets an array of retro_input_descriptors.\n                                            * It is up to the frontend to present this in a usable way.\n                                            * The array is terminated by retro_input_descriptor::description\n                                            * being set to NULL.\n                                            * This function can be called at any time, but it is recommended\n                                            * to call it as early as possible.\n                                            */\n#define RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK 12\n                                           /* const struct retro_keyboard_callback * --\n                                            * Sets a callback function used to notify core about keyboard events.\n                                            */\n#define RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE 13\n                                           /* const struct retro_disk_control_callback * --\n                                            * Sets an interface which frontend can use to eject and insert\n                                            * disk images.\n                                            * This is used for games which consist of multiple images and\n                                            * must be manually swapped out by the user (e.g. PSX).\n                                            */\n#define RETRO_ENVIRONMENT_SET_HW_RENDER 14\n                                           /* struct retro_hw_render_callback * --\n                                            * Sets an interface to let a libretro core render with\n                                            * hardware acceleration.\n                                            * Should be called in retro_load_game().\n                                            * If successful, libretro cores will be able to render to a\n                                            * frontend-provided framebuffer.\n                                            * The size of this framebuffer will be at least as large as\n                                            * max_width/max_height provided in get_av_info().\n                                            * If HW rendering is used, pass only RETRO_HW_FRAME_BUFFER_VALID or\n                                            * NULL to retro_video_refresh_t.\n                                            */\n#define RETRO_ENVIRONMENT_GET_VARIABLE 15\n                                           /* struct retro_variable * --\n                                            * Interface to acquire user-defined information from environment\n                                            * that cannot feasibly be supported in a multi-system way.\n                                            * 'key' should be set to a key which has already been set by\n                                            * SET_VARIABLES.\n                                            * 'data' will be set to a value or NULL.\n                                            */\n#define RETRO_ENVIRONMENT_SET_VARIABLES 16\n                                           /* const struct retro_variable * --\n                                            * Allows an implementation to signal the environment\n                                            * which variables it might want to check for later using\n                                            * GET_VARIABLE.\n                                            * This allows the frontend to present these variables to\n                                            * a user dynamically.\n                                            * This should be called the first time as early as\n                                            * possible (ideally in retro_set_environment).\n                                            * Afterward it may be called again for the core to communicate\n                                            * updated options to the frontend, but the number of core\n                                            * options must not change from the number in the initial call.\n                                            *\n                                            * 'data' points to an array of retro_variable structs\n                                            * terminated by a { NULL, NULL } element.\n                                            * retro_variable::key should be namespaced to not collide\n                                            * with other implementations' keys. E.g. A core called\n                                            * 'foo' should use keys named as 'foo_option'.\n                                            * retro_variable::value should contain a human readable\n                                            * description of the key as well as a '|' delimited list\n                                            * of expected values.\n                                            *\n                                            * The number of possible options should be very limited,\n                                            * i.e. it should be feasible to cycle through options\n                                            * without a keyboard.\n                                            *\n                                            * First entry should be treated as a default.\n                                            *\n                                            * Example entry:\n                                            * { \"foo_option\", \"Speed hack coprocessor X; false|true\" }\n                                            *\n                                            * Text before first ';' is description. This ';' must be\n                                            * followed by a space, and followed by a list of possible\n                                            * values split up with '|'.\n                                            *\n                                            * Only strings are operated on. The possible values will\n                                            * generally be displayed and stored as-is by the frontend.\n                                            */\n#define RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE 17\n                                           /* bool * --\n                                            * Result is set to true if some variables are updated by\n                                            * frontend since last call to RETRO_ENVIRONMENT_GET_VARIABLE.\n                                            * Variables should be queried with GET_VARIABLE.\n                                            */\n#define RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME 18\n                                           /* const bool * --\n                                            * If true, the libretro implementation supports calls to\n                                            * retro_load_game() with NULL as argument.\n                                            * Used by cores which can run without particular game data.\n                                            * This should be called within retro_set_environment() only.\n                                            */\n#define RETRO_ENVIRONMENT_GET_LIBRETRO_PATH 19\n                                           /* const char ** --\n                                            * Retrieves the absolute path from where this libretro\n                                            * implementation was loaded.\n                                            * NULL is returned if the libretro was loaded statically\n                                            * (i.e. linked statically to frontend), or if the path cannot be\n                                            * determined.\n                                            * Mostly useful in cooperation with SET_SUPPORT_NO_GAME as assets can\n                                            * be loaded without ugly hacks.\n                                            */\n\n                                           /* Environment 20 was an obsolete version of SET_AUDIO_CALLBACK.\n                                            * It was not used by any known core at the time,\n                                            * and was removed from the API. */\n#define RETRO_ENVIRONMENT_SET_FRAME_TIME_CALLBACK 21\n                                           /* const struct retro_frame_time_callback * --\n                                            * Lets the core know how much time has passed since last\n                                            * invocation of retro_run().\n                                            * The frontend can tamper with the timing to fake fast-forward,\n                                            * slow-motion, frame stepping, etc.\n                                            * In this case the delta time will use the reference value\n                                            * in frame_time_callback..\n                                            */\n#define RETRO_ENVIRONMENT_SET_AUDIO_CALLBACK 22\n                                           /* const struct retro_audio_callback * --\n                                            * Sets an interface which is used to notify a libretro core about audio\n                                            * being available for writing.\n                                            * The callback can be called from any thread, so a core using this must\n                                            * have a thread safe audio implementation.\n                                            * It is intended for games where audio and video are completely\n                                            * asynchronous and audio can be generated on the fly.\n                                            * This interface is not recommended for use with emulators which have\n                                            * highly synchronous audio.\n                                            *\n                                            * The callback only notifies about writability; the libretro core still\n                                            * has to call the normal audio callbacks\n                                            * to write audio. The audio callbacks must be called from within the\n                                            * notification callback.\n                                            * The amount of audio data to write is up to the implementation.\n                                            * Generally, the audio callback will be called continously in a loop.\n                                            *\n                                            * Due to thread safety guarantees and lack of sync between audio and\n                                            * video, a frontend  can selectively disallow this interface based on\n                                            * internal configuration. A core using this interface must also\n                                            * implement the \"normal\" audio interface.\n                                            *\n                                            * A libretro core using SET_AUDIO_CALLBACK should also make use of\n                                            * SET_FRAME_TIME_CALLBACK.\n                                            */\n#define RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE 23\n                                           /* struct retro_rumble_interface * --\n                                            * Gets an interface which is used by a libretro core to set\n                                            * state of rumble motors in controllers.\n                                            * A strong and weak motor is supported, and they can be\n                                            * controlled indepedently.\n                                            */\n#define RETRO_ENVIRONMENT_GET_INPUT_DEVICE_CAPABILITIES 24\n                                           /* uint64_t * --\n                                            * Gets a bitmask telling which device type are expected to be\n                                            * handled properly in a call to retro_input_state_t.\n                                            * Devices which are not handled or recognized always return\n                                            * 0 in retro_input_state_t.\n                                            * Example bitmask: caps = (1 << RETRO_DEVICE_JOYPAD) | (1 << RETRO_DEVICE_ANALOG).\n                                            * Should only be called in retro_run().\n                                            */\n#define RETRO_ENVIRONMENT_GET_SENSOR_INTERFACE (25 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* struct retro_sensor_interface * --\n                                            * Gets access to the sensor interface.\n                                            * The purpose of this interface is to allow\n                                            * setting state related to sensors such as polling rate,\n                                            * enabling/disable it entirely, etc.\n                                            * Reading sensor state is done via the normal\n                                            * input_state_callback API.\n                                            */\n#define RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE (26 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* struct retro_camera_callback * --\n                                            * Gets an interface to a video camera driver.\n                                            * A libretro core can use this interface to get access to a\n                                            * video camera.\n                                            * New video frames are delivered in a callback in same\n                                            * thread as retro_run().\n                                            *\n                                            * GET_CAMERA_INTERFACE should be called in retro_load_game().\n                                            *\n                                            * Depending on the camera implementation used, camera frames\n                                            * will be delivered as a raw framebuffer,\n                                            * or as an OpenGL texture directly.\n                                            *\n                                            * The core has to tell the frontend here which types of\n                                            * buffers can be handled properly.\n                                            * An OpenGL texture can only be handled when using a\n                                            * libretro GL core (SET_HW_RENDER).\n                                            * It is recommended to use a libretro GL core when\n                                            * using camera interface.\n                                            *\n                                            * The camera is not started automatically. The retrieved start/stop\n                                            * functions must be used to explicitly\n                                            * start and stop the camera driver.\n                                            */\n#define RETRO_ENVIRONMENT_GET_LOG_INTERFACE 27\n                                           /* struct retro_log_callback * --\n                                            * Gets an interface for logging. This is useful for\n                                            * logging in a cross-platform way\n                                            * as certain platforms cannot use stderr for logging.\n                                            * It also allows the frontend to\n                                            * show logging information in a more suitable way.\n                                            * If this interface is not used, libretro cores should\n                                            * log to stderr as desired.\n                                            */\n#define RETRO_ENVIRONMENT_GET_PERF_INTERFACE 28\n                                           /* struct retro_perf_callback * --\n                                            * Gets an interface for performance counters. This is useful\n                                            * for performance logging in a cross-platform way and for detecting\n                                            * architecture-specific features, such as SIMD support.\n                                            */\n#define RETRO_ENVIRONMENT_GET_LOCATION_INTERFACE 29\n                                           /* struct retro_location_callback * --\n                                            * Gets access to the location interface.\n                                            * The purpose of this interface is to be able to retrieve\n                                            * location-based information from the host device,\n                                            * such as current latitude / longitude.\n                                            */\n#define RETRO_ENVIRONMENT_GET_CONTENT_DIRECTORY 30 /* Old name, kept for compatibility. */\n#define RETRO_ENVIRONMENT_GET_CORE_ASSETS_DIRECTORY 30\n                                           /* const char ** --\n                                            * Returns the \"core assets\" directory of the frontend.\n                                            * This directory can be used to store specific assets that the\n                                            * core relies upon, such as art assets,\n                                            * input data, etc etc.\n                                            * The returned value can be NULL.\n                                            * If so, no such directory is defined,\n                                            * and it's up to the implementation to find a suitable directory.\n                                            */\n#define RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY 31\n                                           /* const char ** --\n                                            * Returns the \"save\" directory of the frontend, unless there is no\n                                            * save directory available. The save directory should be used to\n                                            * store SRAM, memory cards, high scores, etc, if the libretro core\n                                            * cannot use the regular memory interface (retro_get_memory_data()).\n                                            *\n                                            * If the frontend cannot designate a save directory, it will return\n                                            * NULL to indicate that the core should attempt to operate without a\n                                            * save directory set.\n                                            *\n                                            * NOTE: early libretro cores used the system directory for save\n                                            * files. Cores that need to be backwards-compatible can still check\n                                            * GET_SYSTEM_DIRECTORY.\n                                            */\n#define RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO 32\n                                           /* const struct retro_system_av_info * --\n                                            * Sets a new av_info structure. This can only be called from\n                                            * within retro_run().\n                                            * This should *only* be used if the core is completely altering the\n                                            * internal resolutions, aspect ratios, timings, sampling rate, etc.\n                                            * Calling this can require a full reinitialization of video/audio\n                                            * drivers in the frontend,\n                                            *\n                                            * so it is important to call it very sparingly, and usually only with\n                                            * the users explicit consent.\n                                            * An eventual driver reinitialize will happen so that video and\n                                            * audio callbacks\n                                            * happening after this call within the same retro_run() call will\n                                            * target the newly initialized driver.\n                                            *\n                                            * This callback makes it possible to support configurable resolutions\n                                            * in games, which can be useful to\n                                            * avoid setting the \"worst case\" in max_width/max_height.\n                                            *\n                                            * ***HIGHLY RECOMMENDED*** Do not call this callback every time\n                                            * resolution changes in an emulator core if it's\n                                            * expected to be a temporary change, for the reasons of possible\n                                            * driver reinitialization.\n                                            * This call is not a free pass for not trying to provide\n                                            * correct values in retro_get_system_av_info(). If you need to change\n                                            * things like aspect ratio or nominal width/height,\n                                            * use RETRO_ENVIRONMENT_SET_GEOMETRY, which is a softer variant\n                                            * of SET_SYSTEM_AV_INFO.\n                                            *\n                                            * If this returns false, the frontend does not acknowledge a\n                                            * changed av_info struct.\n                                            */\n#define RETRO_ENVIRONMENT_SET_PROC_ADDRESS_CALLBACK 33\n                                           /* const struct retro_get_proc_address_interface * --\n                                            * Allows a libretro core to announce support for the\n                                            * get_proc_address() interface.\n                                            * This interface allows for a standard way to extend libretro where\n                                            * use of environment calls are too indirect,\n                                            * e.g. for cases where the frontend wants to call directly into the core.\n                                            *\n                                            * If a core wants to expose this interface, SET_PROC_ADDRESS_CALLBACK\n                                            * **MUST** be called from within retro_set_environment().\n                                            */\n#define RETRO_ENVIRONMENT_SET_SUBSYSTEM_INFO 34\n                                           /* const struct retro_subsystem_info * --\n                                            * This environment call introduces the concept of libretro \"subsystems\".\n                                            * A subsystem is a variant of a libretro core which supports\n                                            * different kinds of games.\n                                            * The purpose of this is to support e.g. emulators which might\n                                            * have special needs, e.g. Super Nintendo's Super GameBoy, Sufami Turbo.\n                                            * It can also be used to pick among subsystems in an explicit way\n                                            * if the libretro implementation is a multi-system emulator itself.\n                                            *\n                                            * Loading a game via a subsystem is done with retro_load_game_special(),\n                                            * and this environment call allows a libretro core to expose which\n                                            * subsystems are supported for use with retro_load_game_special().\n                                            * A core passes an array of retro_game_special_info which is terminated\n                                            * with a zeroed out retro_game_special_info struct.\n                                            *\n                                            * If a core wants to use this functionality, SET_SUBSYSTEM_INFO\n                                            * **MUST** be called from within retro_set_environment().\n                                            */\n#define RETRO_ENVIRONMENT_SET_CONTROLLER_INFO 35\n                                           /* const struct retro_controller_info * --\n                                            * This environment call lets a libretro core tell the frontend\n                                            * which controller subclasses are recognized in calls to\n                                            * retro_set_controller_port_device().\n                                            *\n                                            * Some emulators such as Super Nintendo support multiple lightgun\n                                            * types which must be specifically selected from. It is therefore\n                                            * sometimes necessary for a frontend to be able to tell the core\n                                            * about a special kind of input device which is not specifcally\n                                            * provided by the Libretro API.\n                                            *\n                                            * In order for a frontend to understand the workings of those devices,\n                                            * they must be defined as a specialized subclass of the generic device\n                                            * types already defined in the libretro API.\n                                            *\n                                            * The core must pass an array of const struct retro_controller_info which\n                                            * is terminated with a blanked out struct. Each element of the\n                                            * retro_controller_info struct corresponds to the ascending port index\n                                            * that is passed to retro_set_controller_port_device() when that function\n                                            * is called to indicate to the core that the frontend has changed the\n                                            * active device subclass. SEE ALSO: retro_set_controller_port_device()\n                                            *\n                                            * The ascending input port indexes provided by the core in the struct\n                                            * are generally presented by frontends as ascending User # or Player #,\n                                            * such as Player 1, Player 2, Player 3, etc. Which device subclasses are\n                                            * supported can vary per input port.\n                                            *\n                                            * The first inner element of each entry in the retro_controller_info array\n                                            * is a retro_controller_description struct that specifies the names and\n                                            * codes of all device subclasses that are available for the corresponding\n                                            * User or Player, beginning with the generic Libretro device that the\n                                            * subclasses are derived from. The second inner element of each entry is the\n                                            * total number of subclasses that are listed in the retro_controller_description.\n                                            *\n                                            * NOTE: Even if special device types are set in the libretro core,\n                                            * libretro should only poll input based on the base input device types.\n                                            */\n#define RETRO_ENVIRONMENT_SET_MEMORY_MAPS (36 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* const struct retro_memory_map * --\n                                            * This environment call lets a libretro core tell the frontend\n                                            * about the memory maps this core emulates.\n                                            * This can be used to implement, for example, cheats in a core-agnostic way.\n                                            *\n                                            * Should only be used by emulators; it doesn't make much sense for\n                                            * anything else.\n                                            * It is recommended to expose all relevant pointers through\n                                            * retro_get_memory_* as well.\n                                            *\n                                            * Can be called from retro_init and retro_load_game.\n                                            */\n#define RETRO_ENVIRONMENT_SET_GEOMETRY 37\n                                           /* const struct retro_game_geometry * --\n                                            * This environment call is similar to SET_SYSTEM_AV_INFO for changing\n                                            * video parameters, but provides a guarantee that drivers will not be\n                                            * reinitialized.\n                                            * This can only be called from within retro_run().\n                                            *\n                                            * The purpose of this call is to allow a core to alter nominal\n                                            * width/heights as well as aspect ratios on-the-fly, which can be\n                                            * useful for some emulators to change in run-time.\n                                            *\n                                            * max_width/max_height arguments are ignored and cannot be changed\n                                            * with this call as this could potentially require a reinitialization or a\n                                            * non-constant time operation.\n                                            * If max_width/max_height are to be changed, SET_SYSTEM_AV_INFO is required.\n                                            *\n                                            * A frontend must guarantee that this environment call completes in\n                                            * constant time.\n                                            */\n#define RETRO_ENVIRONMENT_GET_USERNAME 38\n                                           /* const char **\n                                            * Returns the specified username of the frontend, if specified by the user.\n                                            * This username can be used as a nickname for a core that has online facilities\n                                            * or any other mode where personalization of the user is desirable.\n                                            * The returned value can be NULL.\n                                            * If this environ callback is used by a core that requires a valid username,\n                                            * a default username should be specified by the core.\n                                            */\n#define RETRO_ENVIRONMENT_GET_LANGUAGE 39\n                                           /* unsigned * --\n                                            * Returns the specified language of the frontend, if specified by the user.\n                                            * It can be used by the core for localization purposes.\n                                            */\n#define RETRO_ENVIRONMENT_GET_CURRENT_SOFTWARE_FRAMEBUFFER (40 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* struct retro_framebuffer * --\n                                            * Returns a preallocated framebuffer which the core can use for rendering\n                                            * the frame into when not using SET_HW_RENDER.\n                                            * The framebuffer returned from this call must not be used\n                                            * after the current call to retro_run() returns.\n                                            *\n                                            * The goal of this call is to allow zero-copy behavior where a core\n                                            * can render directly into video memory, avoiding extra bandwidth cost by copying\n                                            * memory from core to video memory.\n                                            *\n                                            * If this call succeeds and the core renders into it,\n                                            * the framebuffer pointer and pitch can be passed to retro_video_refresh_t.\n                                            * If the buffer from GET_CURRENT_SOFTWARE_FRAMEBUFFER is to be used,\n                                            * the core must pass the exact\n                                            * same pointer as returned by GET_CURRENT_SOFTWARE_FRAMEBUFFER;\n                                            * i.e. passing a pointer which is offset from the\n                                            * buffer is undefined. The width, height and pitch parameters\n                                            * must also match exactly to the values obtained from GET_CURRENT_SOFTWARE_FRAMEBUFFER.\n                                            *\n                                            * It is possible for a frontend to return a different pixel format\n                                            * than the one used in SET_PIXEL_FORMAT. This can happen if the frontend\n                                            * needs to perform conversion.\n                                            *\n                                            * It is still valid for a core to render to a different buffer\n                                            * even if GET_CURRENT_SOFTWARE_FRAMEBUFFER succeeds.\n                                            *\n                                            * A frontend must make sure that the pointer obtained from this function is\n                                            * writeable (and readable).\n                                            */\n#define RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE (41 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* const struct retro_hw_render_interface ** --\n                                            * Returns an API specific rendering interface for accessing API specific data.\n                                            * Not all HW rendering APIs support or need this.\n                                            * The contents of the returned pointer is specific to the rendering API\n                                            * being used. See the various headers like libretro_vulkan.h, etc.\n                                            *\n                                            * GET_HW_RENDER_INTERFACE cannot be called before context_reset has been called.\n                                            * Similarly, after context_destroyed callback returns,\n                                            * the contents of the HW_RENDER_INTERFACE are invalidated.\n                                            */\n#define RETRO_ENVIRONMENT_SET_SUPPORT_ACHIEVEMENTS (42 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* const bool * --\n                                            * If true, the libretro implementation supports achievements\n                                            * either via memory descriptors set with RETRO_ENVIRONMENT_SET_MEMORY_MAPS\n                                            * or via retro_get_memory_data/retro_get_memory_size.\n                                            *\n                                            * This must be called before the first call to retro_run.\n                                            */\n#define RETRO_ENVIRONMENT_SET_HW_RENDER_CONTEXT_NEGOTIATION_INTERFACE (43 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* const struct retro_hw_render_context_negotiation_interface * --\n                                            * Sets an interface which lets the libretro core negotiate with frontend how a context is created.\n                                            * The semantics of this interface depends on which API is used in SET_HW_RENDER earlier.\n                                            * This interface will be used when the frontend is trying to create a HW rendering context,\n                                            * so it will be used after SET_HW_RENDER, but before the context_reset callback.\n                                            */\n#define RETRO_ENVIRONMENT_SET_SERIALIZATION_QUIRKS 44\n                                           /* uint64_t * --\n                                            * Sets quirk flags associated with serialization. The frontend will zero any flags it doesn't\n                                            * recognize or support. Should be set in either retro_init or retro_load_game, but not both.\n                                            */\n#define RETRO_ENVIRONMENT_SET_HW_SHARED_CONTEXT (44 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* N/A (null) * --\n                                            * The frontend will try to use a 'shared' hardware context (mostly applicable\n                                            * to OpenGL) when a hardware context is being set up.\n                                            *\n                                            * Returns true if the frontend supports shared hardware contexts and false\n                                            * if the frontend does not support shared hardware contexts.\n                                            *\n                                            * This will do nothing on its own until SET_HW_RENDER env callbacks are\n                                            * being used.\n                                            */\n#define RETRO_ENVIRONMENT_GET_VFS_INTERFACE (45 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* struct retro_vfs_interface_info * --\n                                            * Gets access to the VFS interface.\n                                            * VFS presence needs to be queried prior to load_game or any\n                                            * get_system/save/other_directory being called to let front end know\n                                            * core supports VFS before it starts handing out paths.\n                                            * It is recomended to do so in retro_set_environment\n                                            */\n#define RETRO_ENVIRONMENT_GET_LED_INTERFACE (46 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* struct retro_led_interface * --\n                                            * Gets an interface which is used by a libretro core to set\n                                            * state of LEDs.\n                                            */\n#define RETRO_ENVIRONMENT_GET_AUDIO_VIDEO_ENABLE (47 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* int * --\n                                            * Tells the core if the frontend wants audio or video.\n                                            * If disabled, the frontend will discard the audio or video,\n                                            * so the core may decide to skip generating a frame or generating audio.\n                                            * This is mainly used for increasing performance.\n                                            * Bit 0 (value 1): Enable Video\n                                            * Bit 1 (value 2): Enable Audio\n                                            * Bit 2 (value 4): Use Fast Savestates.\n                                            * Bit 3 (value 8): Hard Disable Audio\n                                            * Other bits are reserved for future use and will default to zero.\n                                            * If video is disabled:\n                                            * * The frontend wants the core to not generate any video,\n                                            *   including presenting frames via hardware acceleration.\n                                            * * The frontend's video frame callback will do nothing.\n                                            * * After running the frame, the video output of the next frame should be\n                                            *   no different than if video was enabled, and saving and loading state\n                                            *   should have no issues.\n                                            * If audio is disabled:\n                                            * * The frontend wants the core to not generate any audio.\n                                            * * The frontend's audio callbacks will do nothing.\n                                            * * After running the frame, the audio output of the next frame should be\n                                            *   no different than if audio was enabled, and saving and loading state\n                                            *   should have no issues.\n                                            * Fast Savestates:\n                                            * * Guaranteed to be created by the same binary that will load them.\n                                            * * Will not be written to or read from the disk.\n                                            * * Suggest that the core assumes loading state will succeed.\n                                            * * Suggest that the core updates its memory buffers in-place if possible.\n                                            * * Suggest that the core skips clearing memory.\n                                            * * Suggest that the core skips resetting the system.\n                                            * * Suggest that the core may skip validation steps.\n                                            * Hard Disable Audio:\n                                            * * Used for a secondary core when running ahead.\n                                            * * Indicates that the frontend will never need audio from the core.\n                                            * * Suggests that the core may stop synthesizing audio, but this should not\n                                            *   compromise emulation accuracy.\n                                            * * Audio output for the next frame does not matter, and the frontend will\n                                            *   never need an accurate audio state in the future.\n                                            * * State will never be saved when using Hard Disable Audio.\n                                            */\n#define RETRO_ENVIRONMENT_GET_MIDI_INTERFACE (48 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                           /* struct retro_midi_interface ** --\n                                            * Returns a MIDI interface that can be used for raw data I/O.\n                                            */\n\n#define RETRO_ENVIRONMENT_GET_FASTFORWARDING (49 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                            /* bool * --\n                                            * Boolean value that indicates whether or not the frontend is in\n                                            * fastforwarding mode.\n                                            */\n\n#define RETRO_ENVIRONMENT_GET_TARGET_REFRESH_RATE (50 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                            /* float * --\n                                            * Float value that lets us know what target refresh rate \n                                            * is curently in use by the frontend.\n                                            *\n                                            * The core can use the returned value to set an ideal \n                                            * refresh rate/framerate.\n                                            */\n\n#define RETRO_ENVIRONMENT_GET_INPUT_BITMASKS (51 | RETRO_ENVIRONMENT_EXPERIMENTAL)\n                                            /* bool * --\n                                            * Boolean value that indicates whether or not the frontend supports\n                                            * input bitmasks being returned by retro_input_state_t. The advantage\n                                            * of this is that retro_input_state_t has to be only called once to \n                                            * grab all button states instead of multiple times.\n                                            *\n                                            * If it returns true, you can pass RETRO_DEVICE_ID_JOYPAD_MASK as 'id'\n                                            * to retro_input_state_t (make sure 'device' is set to RETRO_DEVICE_JOYPAD).\n                                            * It will return a bitmask of all the digital buttons.\n                                            */\n\n#define RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION 52\n                                           /* unsigned * --\n                                            * Unsigned value is the API version number of the core options\n                                            * interface supported by the frontend. If callback return false,\n                                            * API version is assumed to be 0.\n                                            *\n                                            * In legacy code, core options are set by passing an array of\n                                            * retro_variable structs to RETRO_ENVIRONMENT_SET_VARIABLES.\n                                            * This may be still be done regardless of the core options\n                                            * interface version.\n                                            *\n                                            * If version is >= 1 however, core options may instead be set by\n                                            * passing an array of retro_core_option_definition structs to\n                                            * RETRO_ENVIRONMENT_SET_CORE_OPTIONS, or a 2D array of\n                                            * retro_core_option_definition structs to RETRO_ENVIRONMENT_SET_CORE_OPTIONS_INTL.\n                                            * This allows the core to additionally set option sublabel information\n                                            * and/or provide localisation support.\n                                            */\n\n#define RETRO_ENVIRONMENT_SET_CORE_OPTIONS 53\n                                           /* const struct retro_core_option_definition ** --\n                                            * Allows an implementation to signal the environment\n                                            * which variables it might want to check for later using\n                                            * GET_VARIABLE.\n                                            * This allows the frontend to present these variables to\n                                            * a user dynamically.\n                                            * This should only be called if RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION\n                                            * returns an API version of >= 1.\n                                            * This should be called instead of RETRO_ENVIRONMENT_SET_VARIABLES.\n                                            * This should be called the first time as early as\n                                            * possible (ideally in retro_set_environment).\n                                            * Afterwards it may be called again for the core to communicate\n                                            * updated options to the frontend, but the number of core\n                                            * options must not change from the number in the initial call.\n                                            *\n                                            * 'data' points to an array of retro_core_option_definition structs\n                                            * terminated by a { NULL, NULL, NULL, {{0}}, NULL } element.\n                                            * retro_core_option_definition::key should be namespaced to not collide\n                                            * with other implementations' keys. e.g. A core called\n                                            * 'foo' should use keys named as 'foo_option'.\n                                            * retro_core_option_definition::desc should contain a human readable\n                                            * description of the key.\n                                            * retro_core_option_definition::info should contain any additional human\n                                            * readable information text that a typical user may need to\n                                            * understand the functionality of the option.\n                                            * retro_core_option_definition::values is an array of retro_core_option_value\n                                            * structs terminated by a { NULL, NULL } element.\n                                            * > retro_core_option_definition::values[index].value is an expected option\n                                            *   value.\n                                            * > retro_core_option_definition::values[index].label is a human readable\n                                            *   label used when displaying the value on screen. If NULL,\n                                            *   the value itself is used.\n                                            * retro_core_option_definition::default_value is the default core option\n                                            * setting. It must match one of the expected option values in the\n                                            * retro_core_option_definition::values array. If it does not, or the\n                                            * default value is NULL, the first entry in the\n                                            * retro_core_option_definition::values array is treated as the default.\n                                            *\n                                            * The number of possible options should be very limited,\n                                            * and must be less than RETRO_NUM_CORE_OPTION_VALUES_MAX.\n                                            * i.e. it should be feasible to cycle through options\n                                            * without a keyboard.\n                                            *\n                                            * Example entry:\n                                            * {\n                                            *     \"foo_option\",\n                                            *     \"Speed hack coprocessor X\",\n                                            *     \"Provides increased performance at the expense of reduced accuracy\",\n                                            * \t  {\n                                            *         { \"false\",    NULL },\n                                            *         { \"true\",     NULL },\n                                            *         { \"unstable\", \"Turbo (Unstable)\" },\n                                            *         { NULL, NULL },\n                                            *     },\n                                            *     \"false\"\n                                            * }\n                                            *\n                                            * Only strings are operated on. The possible values will\n                                            * generally be displayed and stored as-is by the frontend.\n                                            */\n\n#define RETRO_ENVIRONMENT_SET_CORE_OPTIONS_INTL 54\n                                           /* const struct retro_core_options_intl * --\n                                            * Allows an implementation to signal the environment\n                                            * which variables it might want to check for later using\n                                            * GET_VARIABLE.\n                                            * This allows the frontend to present these variables to\n                                            * a user dynamically.\n                                            * This should only be called if RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION\n                                            * returns an API version of >= 1.\n                                            * This should be called instead of RETRO_ENVIRONMENT_SET_VARIABLES.\n                                            * This should be called the first time as early as\n                                            * possible (ideally in retro_set_environment).\n                                            * Afterwards it may be called again for the core to communicate\n                                            * updated options to the frontend, but the number of core\n                                            * options must not change from the number in the initial call.\n                                            *\n                                            * This is fundamentally the same as RETRO_ENVIRONMENT_SET_CORE_OPTIONS,\n                                            * with the addition of localisation support. The description of the\n                                            * RETRO_ENVIRONMENT_SET_CORE_OPTIONS callback should be consulted\n                                            * for further details.\n                                            *\n                                            * 'data' points to a retro_core_options_intl struct.\n                                            *\n                                            * retro_core_options_intl::us is a pointer to an array of\n                                            * retro_core_option_definition structs defining the US English\n                                            * core options implementation. It must point to a valid array.\n                                            *\n                                            * retro_core_options_intl::local is a pointer to an array of\n                                            * retro_core_option_definition structs defining core options for\n                                            * the current frontend language. It may be NULL (in which case\n                                            * retro_core_options_intl::us is used by the frontend). Any items\n                                            * missing from this array will be read from retro_core_options_intl::us\n                                            * instead.\n                                            *\n                                            * NOTE: Default core option values are always taken from the\n                                            * retro_core_options_intl::us array. Any default values in\n                                            * retro_core_options_intl::local array will be ignored.\n                                            */\n\n#define RETRO_ENVIRONMENT_SET_CORE_OPTIONS_DISPLAY 55\n                                           /* struct retro_core_option_display * --\n                                            *\n                                            * Allows an implementation to signal the environment to show\n                                            * or hide a variable when displaying core options. This is\n                                            * considered a *suggestion*. The frontend is free to ignore\n                                            * this callback, and its implementation not considered mandatory.\n                                            *\n                                            * 'data' points to a retro_core_option_display struct\n                                            *\n                                            * retro_core_option_display::key is a variable identifier\n                                            * which has already been set by SET_VARIABLES/SET_CORE_OPTIONS.\n                                            *\n                                            * retro_core_option_display::visible is a boolean, specifying\n                                            * whether variable should be displayed\n                                            *\n                                            * Note that all core option variables will be set visible by\n                                            * default when calling SET_VARIABLES/SET_CORE_OPTIONS.\n                                            */\n\n#define RETRO_ENVIRONMENT_GET_PREFERRED_HW_RENDER 56\n                                           /* unsigned * --\n                                            *\n                                            * Allows an implementation to ask frontend preferred hardware\n                                            * context to use. Core should use this information to deal\n                                            * with what specific context to request with SET_HW_RENDER.\n                                            *\n                                            * 'data' points to an unsigned variable\n                                            */\n\n#define RETRO_ENVIRONMENT_GET_DISK_CONTROL_INTERFACE_VERSION 57\n                                           /* unsigned * --\n                                            * Unsigned value is the API version number of the disk control\n                                            * interface supported by the frontend. If callback return false,\n                                            * API version is assumed to be 0.\n                                            *\n                                            * In legacy code, the disk control interface is defined by passing\n                                            * a struct of type retro_disk_control_callback to\n                                            * RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE.\n                                            * This may be still be done regardless of the disk control\n                                            * interface version.\n                                            *\n                                            * If version is >= 1 however, the disk control interface may\n                                            * instead be defined by passing a struct of type\n                                            * retro_disk_control_ext_callback to\n                                            * RETRO_ENVIRONMENT_SET_DISK_CONTROL_EXT_INTERFACE.\n                                            * This allows the core to provide additional information about\n                                            * disk images to the frontend and/or enables extra\n                                            * disk control functionality by the frontend.\n                                            */\n\n#define RETRO_ENVIRONMENT_SET_DISK_CONTROL_EXT_INTERFACE 58\n                                           /* const struct retro_disk_control_ext_callback * --\n                                            * Sets an interface which frontend can use to eject and insert\n                                            * disk images, and also obtain information about individual\n                                            * disk image files registered by the core.\n                                            * This is used for games which consist of multiple images and\n                                            * must be manually swapped out by the user (e.g. PSX, floppy disk\n                                            * based systems).\n                                            */\n\n/* VFS functionality */\n\n/* File paths:\n * File paths passed as parameters when using this API shall be well formed UNIX-style,\n * using \"/\" (unquoted forward slash) as directory separator regardless of the platform's native separator.\n * Paths shall also include at least one forward slash (\"game.bin\" is an invalid path, use \"./game.bin\" instead).\n * Other than the directory separator, cores shall not make assumptions about path format:\n * \"C:/path/game.bin\", \"http://example.com/game.bin\", \"#game/game.bin\", \"./game.bin\" (without quotes) are all valid paths.\n * Cores may replace the basename or remove path components from the end, and/or add new components;\n * however, cores shall not append \"./\", \"../\" or multiple consecutive forward slashes (\"//\") to paths they request to front end.\n * The frontend is encouraged to make such paths work as well as it can, but is allowed to give up if the core alters paths too much.\n * Frontends are encouraged, but not required, to support native file system paths (modulo replacing the directory separator, if applicable).\n * Cores are allowed to try using them, but must remain functional if the front rejects such requests.\n * Cores are encouraged to use the libretro-common filestream functions for file I/O,\n * as they seamlessly integrate with VFS, deal with directory separator replacement as appropriate\n * and provide platform-specific fallbacks in cases where front ends do not support VFS. */\n\n/* Opaque file handle\n * Introduced in VFS API v1 */\nstruct retro_vfs_file_handle;\n\n/* Opaque directory handle\n * Introduced in VFS API v3 */\nstruct retro_vfs_dir_handle;\n\n/* File open flags\n * Introduced in VFS API v1 */\n#define RETRO_VFS_FILE_ACCESS_READ            (1 << 0) /* Read only mode */\n#define RETRO_VFS_FILE_ACCESS_WRITE           (1 << 1) /* Write only mode, discard contents and overwrites existing file unless RETRO_VFS_FILE_ACCESS_UPDATE is also specified */\n#define RETRO_VFS_FILE_ACCESS_READ_WRITE      (RETRO_VFS_FILE_ACCESS_READ | RETRO_VFS_FILE_ACCESS_WRITE) /* Read-write mode, discard contents and overwrites existing file unless RETRO_VFS_FILE_ACCESS_UPDATE is also specified*/\n#define RETRO_VFS_FILE_ACCESS_UPDATE_EXISTING (1 << 2) /* Prevents discarding content of existing files opened for writing */\n\n/* These are only hints. The frontend may choose to ignore them. Other than RAM/CPU/etc use,\n   and how they react to unlikely external interference (for example someone else writing to that file,\n   or the file's server going down), behavior will not change. */\n#define RETRO_VFS_FILE_ACCESS_HINT_NONE              (0)\n/* Indicate that the file will be accessed many times. The frontend should aggressively cache everything. */\n#define RETRO_VFS_FILE_ACCESS_HINT_FREQUENT_ACCESS   (1 << 0)\n\n/* Seek positions */\n#define RETRO_VFS_SEEK_POSITION_START    0\n#define RETRO_VFS_SEEK_POSITION_CURRENT  1\n#define RETRO_VFS_SEEK_POSITION_END      2\n\n/* stat() result flags\n * Introduced in VFS API v3 */\n#define RETRO_VFS_STAT_IS_VALID               (1 << 0)\n#define RETRO_VFS_STAT_IS_DIRECTORY           (1 << 1)\n#define RETRO_VFS_STAT_IS_CHARACTER_SPECIAL   (1 << 2)\n\n/* Get path from opaque handle. Returns the exact same path passed to file_open when getting the handle\n * Introduced in VFS API v1 */\ntypedef const char *(RETRO_CALLCONV *retro_vfs_get_path_t)(struct retro_vfs_file_handle *stream);\n\n/* Open a file for reading or writing. If path points to a directory, this will\n * fail. Returns the opaque file handle, or NULL for error.\n * Introduced in VFS API v1 */\ntypedef struct retro_vfs_file_handle *(RETRO_CALLCONV *retro_vfs_open_t)(const char *path, unsigned mode, unsigned hints);\n\n/* Close the file and release its resources. Must be called if open_file returns non-NULL. Returns 0 on success, -1 on failure.\n * Whether the call succeeds ot not, the handle passed as parameter becomes invalid and should no longer be used.\n * Introduced in VFS API v1 */\ntypedef int (RETRO_CALLCONV *retro_vfs_close_t)(struct retro_vfs_file_handle *stream);\n\n/* Return the size of the file in bytes, or -1 for error.\n * Introduced in VFS API v1 */\ntypedef int64_t (RETRO_CALLCONV *retro_vfs_size_t)(struct retro_vfs_file_handle *stream);\n\n/* Truncate file to specified size. Returns 0 on success or -1 on error\n * Introduced in VFS API v2 */\ntypedef int64_t (RETRO_CALLCONV *retro_vfs_truncate_t)(struct retro_vfs_file_handle *stream, int64_t length);\n\n/* Get the current read / write position for the file. Returns -1 for error.\n * Introduced in VFS API v1 */\ntypedef int64_t (RETRO_CALLCONV *retro_vfs_tell_t)(struct retro_vfs_file_handle *stream);\n\n/* Set the current read/write position for the file. Returns the new position, -1 for error.\n * Introduced in VFS API v1 */\ntypedef int64_t (RETRO_CALLCONV *retro_vfs_seek_t)(struct retro_vfs_file_handle *stream, int64_t offset, int seek_position);\n\n/* Read data from a file. Returns the number of bytes read, or -1 for error.\n * Introduced in VFS API v1 */\ntypedef int64_t (RETRO_CALLCONV *retro_vfs_read_t)(struct retro_vfs_file_handle *stream, void *s, uint64_t len);\n\n/* Write data to a file. Returns the number of bytes written, or -1 for error.\n * Introduced in VFS API v1 */\ntypedef int64_t (RETRO_CALLCONV *retro_vfs_write_t)(struct retro_vfs_file_handle *stream, const void *s, uint64_t len);\n\n/* Flush pending writes to file, if using buffered IO. Returns 0 on sucess, or -1 on failure.\n * Introduced in VFS API v1 */\ntypedef int (RETRO_CALLCONV *retro_vfs_flush_t)(struct retro_vfs_file_handle *stream);\n\n/* Delete the specified file. Returns 0 on success, -1 on failure\n * Introduced in VFS API v1 */\ntypedef int (RETRO_CALLCONV *retro_vfs_remove_t)(const char *path);\n\n/* Rename the specified file. Returns 0 on success, -1 on failure\n * Introduced in VFS API v1 */\ntypedef int (RETRO_CALLCONV *retro_vfs_rename_t)(const char *old_path, const char *new_path);\n\n/* Stat the specified file. Retruns a bitmask of RETRO_VFS_STAT_* flags, none are set if path was not valid.\n * Additionally stores file size in given variable, unless NULL is given.\n * Introduced in VFS API v3 */\ntypedef int (RETRO_CALLCONV *retro_vfs_stat_t)(const char *path, int32_t *size);\n\n/* Create the specified directory. Returns 0 on success, -1 on unknown failure, -2 if already exists.\n * Introduced in VFS API v3 */\ntypedef int (RETRO_CALLCONV *retro_vfs_mkdir_t)(const char *dir);\n\n/* Open the specified directory for listing. Returns the opaque dir handle, or NULL for error.\n * Support for the include_hidden argument may vary depending on the platform.\n * Introduced in VFS API v3 */\ntypedef struct retro_vfs_dir_handle *(RETRO_CALLCONV *retro_vfs_opendir_t)(const char *dir, bool include_hidden);\n\n/* Read the directory entry at the current position, and move the read pointer to the next position.\n * Returns true on success, false if already on the last entry.\n * Introduced in VFS API v3 */\ntypedef bool (RETRO_CALLCONV *retro_vfs_readdir_t)(struct retro_vfs_dir_handle *dirstream);\n\n/* Get the name of the last entry read. Returns a string on success, or NULL for error.\n * The returned string pointer is valid until the next call to readdir or closedir.\n * Introduced in VFS API v3 */\ntypedef const char *(RETRO_CALLCONV *retro_vfs_dirent_get_name_t)(struct retro_vfs_dir_handle *dirstream);\n\n/* Check if the last entry read was a directory. Returns true if it was, false otherwise (or on error).\n * Introduced in VFS API v3 */\ntypedef bool (RETRO_CALLCONV *retro_vfs_dirent_is_dir_t)(struct retro_vfs_dir_handle *dirstream);\n\n/* Close the directory and release its resources. Must be called if opendir returns non-NULL. Returns 0 on success, -1 on failure.\n * Whether the call succeeds ot not, the handle passed as parameter becomes invalid and should no longer be used.\n * Introduced in VFS API v3 */\ntypedef int (RETRO_CALLCONV *retro_vfs_closedir_t)(struct retro_vfs_dir_handle *dirstream);\n\nstruct retro_vfs_interface\n{\n   /* VFS API v1 */\n\tretro_vfs_get_path_t get_path;\n\tretro_vfs_open_t open;\n\tretro_vfs_close_t close;\n\tretro_vfs_size_t size;\n\tretro_vfs_tell_t tell;\n\tretro_vfs_seek_t seek;\n\tretro_vfs_read_t read;\n\tretro_vfs_write_t write;\n\tretro_vfs_flush_t flush;\n\tretro_vfs_remove_t remove;\n\tretro_vfs_rename_t rename;\n   /* VFS API v2 */\n   retro_vfs_truncate_t truncate;\n   /* VFS API v3 */\n   retro_vfs_stat_t stat;\n   retro_vfs_mkdir_t mkdir;\n   retro_vfs_opendir_t opendir;\n   retro_vfs_readdir_t readdir;\n   retro_vfs_dirent_get_name_t dirent_get_name;\n   retro_vfs_dirent_is_dir_t dirent_is_dir;\n   retro_vfs_closedir_t closedir;\n};\n\nstruct retro_vfs_interface_info\n{\n   /* Set by core: should this be higher than the version the front end supports,\n    * front end will return false in the RETRO_ENVIRONMENT_GET_VFS_INTERFACE call\n    * Introduced in VFS API v1 */\n   uint32_t required_interface_version;\n\n   /* Frontend writes interface pointer here. The frontend also sets the actual\n    * version, must be at least required_interface_version.\n    * Introduced in VFS API v1 */\n   struct retro_vfs_interface *iface;\n};\n\nenum retro_hw_render_interface_type\n{\n\tRETRO_HW_RENDER_INTERFACE_VULKAN = 0,\n\tRETRO_HW_RENDER_INTERFACE_D3D9   = 1,\n\tRETRO_HW_RENDER_INTERFACE_D3D10  = 2,\n\tRETRO_HW_RENDER_INTERFACE_D3D11  = 3,\n\tRETRO_HW_RENDER_INTERFACE_D3D12  = 4,\n   RETRO_HW_RENDER_INTERFACE_GSKIT_PS2  = 5,\n   RETRO_HW_RENDER_INTERFACE_DUMMY  = INT_MAX\n};\n\n/* Base struct. All retro_hw_render_interface_* types\n * contain at least these fields. */\nstruct retro_hw_render_interface\n{\n   enum retro_hw_render_interface_type interface_type;\n   unsigned interface_version;\n};\n\ntypedef void (RETRO_CALLCONV *retro_set_led_state_t)(int led, int state);\nstruct retro_led_interface\n{\n    retro_set_led_state_t set_led_state;\n};\n\n/* Retrieves the current state of the MIDI input.\n * Returns true if it's enabled, false otherwise. */\ntypedef bool (RETRO_CALLCONV *retro_midi_input_enabled_t)(void);\n\n/* Retrieves the current state of the MIDI output.\n * Returns true if it's enabled, false otherwise */\ntypedef bool (RETRO_CALLCONV *retro_midi_output_enabled_t)(void);\n\n/* Reads next byte from the input stream.\n * Returns true if byte is read, false otherwise. */\ntypedef bool (RETRO_CALLCONV *retro_midi_read_t)(uint8_t *byte);\n\n/* Writes byte to the output stream.\n * 'delta_time' is in microseconds and represent time elapsed since previous write.\n * Returns true if byte is written, false otherwise. */\ntypedef bool (RETRO_CALLCONV *retro_midi_write_t)(uint8_t byte, uint32_t delta_time);\n\n/* Flushes previously written data.\n * Returns true if successful, false otherwise. */\ntypedef bool (RETRO_CALLCONV *retro_midi_flush_t)(void);\n\nstruct retro_midi_interface\n{\n   retro_midi_input_enabled_t input_enabled;\n   retro_midi_output_enabled_t output_enabled;\n   retro_midi_read_t read;\n   retro_midi_write_t write;\n   retro_midi_flush_t flush;\n};\n\nenum retro_hw_render_context_negotiation_interface_type\n{\n   RETRO_HW_RENDER_CONTEXT_NEGOTIATION_INTERFACE_VULKAN = 0,\n   RETRO_HW_RENDER_CONTEXT_NEGOTIATION_INTERFACE_DUMMY = INT_MAX\n};\n\n/* Base struct. All retro_hw_render_context_negotiation_interface_* types\n * contain at least these fields. */\nstruct retro_hw_render_context_negotiation_interface\n{\n   enum retro_hw_render_context_negotiation_interface_type interface_type;\n   unsigned interface_version;\n};\n\n/* Serialized state is incomplete in some way. Set if serialization is\n * usable in typical end-user cases but should not be relied upon to\n * implement frame-sensitive frontend features such as netplay or\n * rerecording. */\n#define RETRO_SERIALIZATION_QUIRK_INCOMPLETE (1 << 0)\n/* The core must spend some time initializing before serialization is\n * supported. retro_serialize() will initially fail; retro_unserialize()\n * and retro_serialize_size() may or may not work correctly either. */\n#define RETRO_SERIALIZATION_QUIRK_MUST_INITIALIZE (1 << 1)\n/* Serialization size may change within a session. */\n#define RETRO_SERIALIZATION_QUIRK_CORE_VARIABLE_SIZE (1 << 2)\n/* Set by the frontend to acknowledge that it supports variable-sized\n * states. */\n#define RETRO_SERIALIZATION_QUIRK_FRONT_VARIABLE_SIZE (1 << 3)\n/* Serialized state can only be loaded during the same session. */\n#define RETRO_SERIALIZATION_QUIRK_SINGLE_SESSION (1 << 4)\n/* Serialized state cannot be loaded on an architecture with a different\n * endianness from the one it was saved on. */\n#define RETRO_SERIALIZATION_QUIRK_ENDIAN_DEPENDENT (1 << 5)\n/* Serialized state cannot be loaded on a different platform from the one it\n * was saved on for reasons other than endianness, such as word size\n * dependence */\n#define RETRO_SERIALIZATION_QUIRK_PLATFORM_DEPENDENT (1 << 6)\n\n#define RETRO_MEMDESC_CONST      (1 << 0)   /* The frontend will never change this memory area once retro_load_game has returned. */\n#define RETRO_MEMDESC_BIGENDIAN  (1 << 1)   /* The memory area contains big endian data. Default is little endian. */\n#define RETRO_MEMDESC_SYSTEM_RAM (1 << 2)   /* The memory area is system RAM.  This is main RAM of the gaming system. */\n#define RETRO_MEMDESC_SAVE_RAM   (1 << 3)   /* The memory area is save RAM. This RAM is usually found on a game cartridge, backed up by a battery. */\n#define RETRO_MEMDESC_VIDEO_RAM  (1 << 4)   /* The memory area is video RAM (VRAM) */\n#define RETRO_MEMDESC_ALIGN_2    (1 << 16)  /* All memory access in this area is aligned to their own size, or 2, whichever is smaller. */\n#define RETRO_MEMDESC_ALIGN_4    (2 << 16)\n#define RETRO_MEMDESC_ALIGN_8    (3 << 16)\n#define RETRO_MEMDESC_MINSIZE_2  (1 << 24)  /* All memory in this region is accessed at least 2 bytes at the time. */\n#define RETRO_MEMDESC_MINSIZE_4  (2 << 24)\n#define RETRO_MEMDESC_MINSIZE_8  (3 << 24)\nstruct retro_memory_descriptor\n{\n   uint64_t flags;\n\n   /* Pointer to the start of the relevant ROM or RAM chip.\n    * It's strongly recommended to use 'offset' if possible, rather than\n    * doing math on the pointer.\n    *\n    * If the same byte is mapped my multiple descriptors, their descriptors\n    * must have the same pointer.\n    * If 'start' does not point to the first byte in the pointer, put the\n    * difference in 'offset' instead.\n    *\n    * May be NULL if there's nothing usable here (e.g. hardware registers and\n    * open bus). No flags should be set if the pointer is NULL.\n    * It's recommended to minimize the number of descriptors if possible,\n    * but not mandatory. */\n   void *ptr;\n   size_t offset;\n\n   /* This is the location in the emulated address space\n    * where the mapping starts. */\n   size_t start;\n\n   /* Which bits must be same as in 'start' for this mapping to apply.\n    * The first memory descriptor to claim a certain byte is the one\n    * that applies.\n    * A bit which is set in 'start' must also be set in this.\n    * Can be zero, in which case each byte is assumed mapped exactly once.\n    * In this case, 'len' must be a power of two. */\n   size_t select;\n\n   /* If this is nonzero, the set bits are assumed not connected to the\n    * memory chip's address pins. */\n   size_t disconnect;\n\n   /* This one tells the size of the current memory area.\n    * If, after start+disconnect are applied, the address is higher than\n    * this, the highest bit of the address is cleared.\n    *\n    * If the address is still too high, the next highest bit is cleared.\n    * Can be zero, in which case it's assumed to be infinite (as limited\n    * by 'select' and 'disconnect'). */\n   size_t len;\n\n   /* To go from emulated address to physical address, the following\n    * order applies:\n    * Subtract 'start', pick off 'disconnect', apply 'len', add 'offset'. */\n\n   /* The address space name must consist of only a-zA-Z0-9_-,\n    * should be as short as feasible (maximum length is 8 plus the NUL),\n    * and may not be any other address space plus one or more 0-9A-F\n    * at the end.\n    * However, multiple memory descriptors for the same address space is\n    * allowed, and the address space name can be empty. NULL is treated\n    * as empty.\n    *\n    * Address space names are case sensitive, but avoid lowercase if possible.\n    * The same pointer may exist in multiple address spaces.\n    *\n    * Examples:\n    * blank+blank - valid (multiple things may be mapped in the same namespace)\n    * 'Sp'+'Sp' - valid (multiple things may be mapped in the same namespace)\n    * 'A'+'B' - valid (neither is a prefix of each other)\n    * 'S'+blank - valid ('S' is not in 0-9A-F)\n    * 'a'+blank - valid ('a' is not in 0-9A-F)\n    * 'a'+'A' - valid (neither is a prefix of each other)\n    * 'AR'+blank - valid ('R' is not in 0-9A-F)\n    * 'ARB'+blank - valid (the B can't be part of the address either, because\n    *                      there is no namespace 'AR')\n    * blank+'B' - not valid, because it's ambigous which address space B1234\n    *             would refer to.\n    * The length can't be used for that purpose; the frontend may want\n    * to append arbitrary data to an address, without a separator. */\n   const char *addrspace;\n\n   /* TODO: When finalizing this one, add a description field, which should be\n    * \"WRAM\" or something roughly equally long. */\n\n   /* TODO: When finalizing this one, replace 'select' with 'limit', which tells\n    * which bits can vary and still refer to the same address (limit = ~select).\n    * TODO: limit? range? vary? something else? */\n\n   /* TODO: When finalizing this one, if 'len' is above what 'select' (or\n    * 'limit') allows, it's bankswitched. Bankswitched data must have both 'len'\n    * and 'select' != 0, and the mappings don't tell how the system switches the\n    * banks. */\n\n   /* TODO: When finalizing this one, fix the 'len' bit removal order.\n    * For len=0x1800, pointer 0x1C00 should go to 0x1400, not 0x0C00.\n    * Algorithm: Take bits highest to lowest, but if it goes above len, clear\n    * the most recent addition and continue on the next bit.\n    * TODO: Can the above be optimized? Is \"remove the lowest bit set in both\n    * pointer and 'len'\" equivalent? */\n\n   /* TODO: Some emulators (MAME?) emulate big endian systems by only accessing\n    * the emulated memory in 32-bit chunks, native endian. But that's nothing\n    * compared to Darek Mihocka <http://www.emulators.com/docs/nx07_vm101.htm>\n    * (section Emulation 103 - Nearly Free Byte Reversal) - he flips the ENTIRE\n    * RAM backwards! I'll want to represent both of those, via some flags.\n    *\n    * I suspect MAME either didn't think of that idea, or don't want the #ifdef.\n    * Not sure which, nor do I really care. */\n\n   /* TODO: Some of those flags are unused and/or don't really make sense. Clean\n    * them up. */\n};\n\n/* The frontend may use the largest value of 'start'+'select' in a\n * certain namespace to infer the size of the address space.\n *\n * If the address space is larger than that, a mapping with .ptr=NULL\n * should be at the end of the array, with .select set to all ones for\n * as long as the address space is big.\n *\n * Sample descriptors (minus .ptr, and RETRO_MEMFLAG_ on the flags):\n * SNES WRAM:\n * .start=0x7E0000, .len=0x20000\n * (Note that this must be mapped before the ROM in most cases; some of the\n * ROM mappers\n * try to claim $7E0000, or at least $7E8000.)\n * SNES SPC700 RAM:\n * .addrspace=\"S\", .len=0x10000\n * SNES WRAM mirrors:\n * .flags=MIRROR, .start=0x000000, .select=0xC0E000, .len=0x2000\n * .flags=MIRROR, .start=0x800000, .select=0xC0E000, .len=0x2000\n * SNES WRAM mirrors, alternate equivalent descriptor:\n * .flags=MIRROR, .select=0x40E000, .disconnect=~0x1FFF\n * (Various similar constructions can be created by combining parts of\n * the above two.)\n * SNES LoROM (512KB, mirrored a couple of times):\n * .flags=CONST, .start=0x008000, .select=0x408000, .disconnect=0x8000, .len=512*1024\n * .flags=CONST, .start=0x400000, .select=0x400000, .disconnect=0x8000, .len=512*1024\n * SNES HiROM (4MB):\n * .flags=CONST,                 .start=0x400000, .select=0x400000, .len=4*1024*1024\n * .flags=CONST, .offset=0x8000, .start=0x008000, .select=0x408000, .len=4*1024*1024\n * SNES ExHiROM (8MB):\n * .flags=CONST, .offset=0,                  .start=0xC00000, .select=0xC00000, .len=4*1024*1024\n * .flags=CONST, .offset=4*1024*1024,        .start=0x400000, .select=0xC00000, .len=4*1024*1024\n * .flags=CONST, .offset=0x8000,             .start=0x808000, .select=0xC08000, .len=4*1024*1024\n * .flags=CONST, .offset=4*1024*1024+0x8000, .start=0x008000, .select=0xC08000, .len=4*1024*1024\n * Clarify the size of the address space:\n * .ptr=NULL, .select=0xFFFFFF\n * .len can be implied by .select in many of them, but was included for clarity.\n */\n\nstruct retro_memory_map\n{\n   const struct retro_memory_descriptor *descriptors;\n   unsigned num_descriptors;\n};\n\nstruct retro_controller_description\n{\n   /* Human-readable description of the controller. Even if using a generic\n    * input device type, this can be set to the particular device type the\n    * core uses. */\n   const char *desc;\n\n   /* Device type passed to retro_set_controller_port_device(). If the device\n    * type is a sub-class of a generic input device type, use the\n    * RETRO_DEVICE_SUBCLASS macro to create an ID.\n    *\n    * E.g. RETRO_DEVICE_SUBCLASS(RETRO_DEVICE_JOYPAD, 1). */\n   unsigned id;\n};\n\nstruct retro_controller_info\n{\n   const struct retro_controller_description *types;\n   unsigned num_types;\n};\n\nstruct retro_subsystem_memory_info\n{\n   /* The extension associated with a memory type, e.g. \"psram\". */\n   const char *extension;\n\n   /* The memory type for retro_get_memory(). This should be at\n    * least 0x100 to avoid conflict with standardized\n    * libretro memory types. */\n   unsigned type;\n};\n\nstruct retro_subsystem_rom_info\n{\n   /* Describes what the content is (SGB BIOS, GB ROM, etc). */\n   const char *desc;\n\n   /* Same definition as retro_get_system_info(). */\n   const char *valid_extensions;\n\n   /* Same definition as retro_get_system_info(). */\n   bool need_fullpath;\n\n   /* Same definition as retro_get_system_info(). */\n   bool block_extract;\n\n   /* This is set if the content is required to load a game.\n    * If this is set to false, a zeroed-out retro_game_info can be passed. */\n   bool required;\n\n   /* Content can have multiple associated persistent\n    * memory types (retro_get_memory()). */\n   const struct retro_subsystem_memory_info *memory;\n   unsigned num_memory;\n};\n\nstruct retro_subsystem_info\n{\n   /* Human-readable string of the subsystem type, e.g. \"Super GameBoy\" */\n   const char *desc;\n\n   /* A computer friendly short string identifier for the subsystem type.\n    * This name must be [a-z].\n    * E.g. if desc is \"Super GameBoy\", this can be \"sgb\".\n    * This identifier can be used for command-line interfaces, etc.\n    */\n   const char *ident;\n\n   /* Infos for each content file. The first entry is assumed to be the\n    * \"most significant\" content for frontend purposes.\n    * E.g. with Super GameBoy, the first content should be the GameBoy ROM,\n    * as it is the most \"significant\" content to a user.\n    * If a frontend creates new file paths based on the content used\n    * (e.g. savestates), it should use the path for the first ROM to do so. */\n   const struct retro_subsystem_rom_info *roms;\n\n   /* Number of content files associated with a subsystem. */\n   unsigned num_roms;\n\n   /* The type passed to retro_load_game_special(). */\n   unsigned id;\n};\n\ntypedef void (RETRO_CALLCONV *retro_proc_address_t)(void);\n\n/* libretro API extension functions:\n * (None here so far).\n *\n * Get a symbol from a libretro core.\n * Cores should only return symbols which are actual\n * extensions to the libretro API.\n *\n * Frontends should not use this to obtain symbols to standard\n * libretro entry points (static linking or dlsym).\n *\n * The symbol name must be equal to the function name,\n * e.g. if void retro_foo(void); exists, the symbol must be called \"retro_foo\".\n * The returned function pointer must be cast to the corresponding type.\n */\ntypedef retro_proc_address_t (RETRO_CALLCONV *retro_get_proc_address_t)(const char *sym);\n\nstruct retro_get_proc_address_interface\n{\n   retro_get_proc_address_t get_proc_address;\n};\n\nenum retro_log_level\n{\n   RETRO_LOG_DEBUG = 0,\n   RETRO_LOG_INFO,\n   RETRO_LOG_WARN,\n   RETRO_LOG_ERROR,\n\n   RETRO_LOG_DUMMY = INT_MAX\n};\n\n/* Logging function. Takes log level argument as well. */\ntypedef void (RETRO_CALLCONV *retro_log_printf_t)(enum retro_log_level level,\n      const char *fmt, ...);\n\nstruct retro_log_callback\n{\n   retro_log_printf_t log;\n};\n\n/* Performance related functions */\n\n/* ID values for SIMD CPU features */\n#define RETRO_SIMD_SSE      (1 << 0)\n#define RETRO_SIMD_SSE2     (1 << 1)\n#define RETRO_SIMD_VMX      (1 << 2)\n#define RETRO_SIMD_VMX128   (1 << 3)\n#define RETRO_SIMD_AVX      (1 << 4)\n#define RETRO_SIMD_NEON     (1 << 5)\n#define RETRO_SIMD_SSE3     (1 << 6)\n#define RETRO_SIMD_SSSE3    (1 << 7)\n#define RETRO_SIMD_MMX      (1 << 8)\n#define RETRO_SIMD_MMXEXT   (1 << 9)\n#define RETRO_SIMD_SSE4     (1 << 10)\n#define RETRO_SIMD_SSE42    (1 << 11)\n#define RETRO_SIMD_AVX2     (1 << 12)\n#define RETRO_SIMD_VFPU     (1 << 13)\n#define RETRO_SIMD_PS       (1 << 14)\n#define RETRO_SIMD_AES      (1 << 15)\n#define RETRO_SIMD_VFPV3    (1 << 16)\n#define RETRO_SIMD_VFPV4    (1 << 17)\n#define RETRO_SIMD_POPCNT   (1 << 18)\n#define RETRO_SIMD_MOVBE    (1 << 19)\n#define RETRO_SIMD_CMOV     (1 << 20)\n#define RETRO_SIMD_ASIMD    (1 << 21)\n\ntypedef uint64_t retro_perf_tick_t;\ntypedef int64_t retro_time_t;\n\nstruct retro_perf_counter\n{\n   const char *ident;\n   retro_perf_tick_t start;\n   retro_perf_tick_t total;\n   retro_perf_tick_t call_cnt;\n\n   bool registered;\n};\n\n/* Returns current time in microseconds.\n * Tries to use the most accurate timer available.\n */\ntypedef retro_time_t (RETRO_CALLCONV *retro_perf_get_time_usec_t)(void);\n\n/* A simple counter. Usually nanoseconds, but can also be CPU cycles.\n * Can be used directly if desired (when creating a more sophisticated\n * performance counter system).\n * */\ntypedef retro_perf_tick_t (RETRO_CALLCONV *retro_perf_get_counter_t)(void);\n\n/* Returns a bit-mask of detected CPU features (RETRO_SIMD_*). */\ntypedef uint64_t (RETRO_CALLCONV *retro_get_cpu_features_t)(void);\n\n/* Asks frontend to log and/or display the state of performance counters.\n * Performance counters can always be poked into manually as well.\n */\ntypedef void (RETRO_CALLCONV *retro_perf_log_t)(void);\n\n/* Register a performance counter.\n * ident field must be set with a discrete value and other values in\n * retro_perf_counter must be 0.\n * Registering can be called multiple times. To avoid calling to\n * frontend redundantly, you can check registered field first. */\ntypedef void (RETRO_CALLCONV *retro_perf_register_t)(struct retro_perf_counter *counter);\n\n/* Starts a registered counter. */\ntypedef void (RETRO_CALLCONV *retro_perf_start_t)(struct retro_perf_counter *counter);\n\n/* Stops a registered counter. */\ntypedef void (RETRO_CALLCONV *retro_perf_stop_t)(struct retro_perf_counter *counter);\n\n/* For convenience it can be useful to wrap register, start and stop in macros.\n * E.g.:\n * #ifdef LOG_PERFORMANCE\n * #define RETRO_PERFORMANCE_INIT(perf_cb, name) static struct retro_perf_counter name = {#name}; if (!name.registered) perf_cb.perf_register(&(name))\n * #define RETRO_PERFORMANCE_START(perf_cb, name) perf_cb.perf_start(&(name))\n * #define RETRO_PERFORMANCE_STOP(perf_cb, name) perf_cb.perf_stop(&(name))\n * #else\n * ... Blank macros ...\n * #endif\n *\n * These can then be used mid-functions around code snippets.\n *\n * extern struct retro_perf_callback perf_cb;  * Somewhere in the core.\n *\n * void do_some_heavy_work(void)\n * {\n *    RETRO_PERFORMANCE_INIT(cb, work_1;\n *    RETRO_PERFORMANCE_START(cb, work_1);\n *    heavy_work_1();\n *    RETRO_PERFORMANCE_STOP(cb, work_1);\n *\n *    RETRO_PERFORMANCE_INIT(cb, work_2);\n *    RETRO_PERFORMANCE_START(cb, work_2);\n *    heavy_work_2();\n *    RETRO_PERFORMANCE_STOP(cb, work_2);\n * }\n *\n * void retro_deinit(void)\n * {\n *    perf_cb.perf_log();  * Log all perf counters here for example.\n * }\n */\n\nstruct retro_perf_callback\n{\n   retro_perf_get_time_usec_t    get_time_usec;\n   retro_get_cpu_features_t      get_cpu_features;\n\n   retro_perf_get_counter_t      get_perf_counter;\n   retro_perf_register_t         perf_register;\n   retro_perf_start_t            perf_start;\n   retro_perf_stop_t             perf_stop;\n   retro_perf_log_t              perf_log;\n};\n\n/* FIXME: Document the sensor API and work out behavior.\n * It will be marked as experimental until then.\n */\nenum retro_sensor_action\n{\n   RETRO_SENSOR_ACCELEROMETER_ENABLE = 0,\n   RETRO_SENSOR_ACCELEROMETER_DISABLE,\n   RETRO_SENSOR_GYROSCOPE_ENABLE,\n   RETRO_SENSOR_GYROSCOPE_DISABLE,\n   RETRO_SENSOR_ILLUMINANCE_ENABLE,\n   RETRO_SENSOR_ILLUMINANCE_DISABLE,\n\n   RETRO_SENSOR_DUMMY = INT_MAX\n};\n\n/* Id values for SENSOR types. */\n#define RETRO_SENSOR_ACCELEROMETER_X 0\n#define RETRO_SENSOR_ACCELEROMETER_Y 1\n#define RETRO_SENSOR_ACCELEROMETER_Z 2\n#define RETRO_SENSOR_GYROSCOPE_X 3\n#define RETRO_SENSOR_GYROSCOPE_Y 4\n#define RETRO_SENSOR_GYROSCOPE_Z 5\n#define RETRO_SENSOR_ILLUMINANCE 6\n\ntypedef bool (RETRO_CALLCONV *retro_set_sensor_state_t)(unsigned port,\n      enum retro_sensor_action action, unsigned rate);\n\ntypedef float (RETRO_CALLCONV *retro_sensor_get_input_t)(unsigned port, unsigned id);\n\nstruct retro_sensor_interface\n{\n   retro_set_sensor_state_t set_sensor_state;\n   retro_sensor_get_input_t get_sensor_input;\n};\n\nenum retro_camera_buffer\n{\n   RETRO_CAMERA_BUFFER_OPENGL_TEXTURE = 0,\n   RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER,\n\n   RETRO_CAMERA_BUFFER_DUMMY = INT_MAX\n};\n\n/* Starts the camera driver. Can only be called in retro_run(). */\ntypedef bool (RETRO_CALLCONV *retro_camera_start_t)(void);\n\n/* Stops the camera driver. Can only be called in retro_run(). */\ntypedef void (RETRO_CALLCONV *retro_camera_stop_t)(void);\n\n/* Callback which signals when the camera driver is initialized\n * and/or deinitialized.\n * retro_camera_start_t can be called in initialized callback.\n */\ntypedef void (RETRO_CALLCONV *retro_camera_lifetime_status_t)(void);\n\n/* A callback for raw framebuffer data. buffer points to an XRGB8888 buffer.\n * Width, height and pitch are similar to retro_video_refresh_t.\n * First pixel is top-left origin.\n */\ntypedef void (RETRO_CALLCONV *retro_camera_frame_raw_framebuffer_t)(const uint32_t *buffer,\n      unsigned width, unsigned height, size_t pitch);\n\n/* A callback for when OpenGL textures are used.\n *\n * texture_id is a texture owned by camera driver.\n * Its state or content should be considered immutable, except for things like\n * texture filtering and clamping.\n *\n * texture_target is the texture target for the GL texture.\n * These can include e.g. GL_TEXTURE_2D, GL_TEXTURE_RECTANGLE, and possibly\n * more depending on extensions.\n *\n * affine points to a packed 3x3 column-major matrix used to apply an affine\n * transform to texture coordinates. (affine_matrix * vec3(coord_x, coord_y, 1.0))\n * After transform, normalized texture coord (0, 0) should be bottom-left\n * and (1, 1) should be top-right (or (width, height) for RECTANGLE).\n *\n * GL-specific typedefs are avoided here to avoid relying on gl.h in\n * the API definition.\n */\ntypedef void (RETRO_CALLCONV *retro_camera_frame_opengl_texture_t)(unsigned texture_id,\n      unsigned texture_target, const float *affine);\n\nstruct retro_camera_callback\n{\n   /* Set by libretro core.\n    * Example bitmask: caps = (1 << RETRO_CAMERA_BUFFER_OPENGL_TEXTURE) | (1 << RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER).\n    */\n   uint64_t caps;\n\n   /* Desired resolution for camera. Is only used as a hint. */\n   unsigned width;\n   unsigned height;\n\n   /* Set by frontend. */\n   retro_camera_start_t start;\n   retro_camera_stop_t stop;\n\n   /* Set by libretro core if raw framebuffer callbacks will be used. */\n   retro_camera_frame_raw_framebuffer_t frame_raw_framebuffer;\n\n   /* Set by libretro core if OpenGL texture callbacks will be used. */\n   retro_camera_frame_opengl_texture_t frame_opengl_texture;\n\n   /* Set by libretro core. Called after camera driver is initialized and\n    * ready to be started.\n    * Can be NULL, in which this callback is not called.\n    */\n   retro_camera_lifetime_status_t initialized;\n\n   /* Set by libretro core. Called right before camera driver is\n    * deinitialized.\n    * Can be NULL, in which this callback is not called.\n    */\n   retro_camera_lifetime_status_t deinitialized;\n};\n\n/* Sets the interval of time and/or distance at which to update/poll\n * location-based data.\n *\n * To ensure compatibility with all location-based implementations,\n * values for both interval_ms and interval_distance should be provided.\n *\n * interval_ms is the interval expressed in milliseconds.\n * interval_distance is the distance interval expressed in meters.\n */\ntypedef void (RETRO_CALLCONV *retro_location_set_interval_t)(unsigned interval_ms,\n      unsigned interval_distance);\n\n/* Start location services. The device will start listening for changes to the\n * current location at regular intervals (which are defined with\n * retro_location_set_interval_t). */\ntypedef bool (RETRO_CALLCONV *retro_location_start_t)(void);\n\n/* Stop location services. The device will stop listening for changes\n * to the current location. */\ntypedef void (RETRO_CALLCONV *retro_location_stop_t)(void);\n\n/* Get the position of the current location. Will set parameters to\n * 0 if no new  location update has happened since the last time. */\ntypedef bool (RETRO_CALLCONV *retro_location_get_position_t)(double *lat, double *lon,\n      double *horiz_accuracy, double *vert_accuracy);\n\n/* Callback which signals when the location driver is initialized\n * and/or deinitialized.\n * retro_location_start_t can be called in initialized callback.\n */\ntypedef void (RETRO_CALLCONV *retro_location_lifetime_status_t)(void);\n\nstruct retro_location_callback\n{\n   retro_location_start_t         start;\n   retro_location_stop_t          stop;\n   retro_location_get_position_t  get_position;\n   retro_location_set_interval_t  set_interval;\n\n   retro_location_lifetime_status_t initialized;\n   retro_location_lifetime_status_t deinitialized;\n};\n\nenum retro_rumble_effect\n{\n   RETRO_RUMBLE_STRONG = 0,\n   RETRO_RUMBLE_WEAK = 1,\n\n   RETRO_RUMBLE_DUMMY = INT_MAX\n};\n\n/* Sets rumble state for joypad plugged in port 'port'.\n * Rumble effects are controlled independently,\n * and setting e.g. strong rumble does not override weak rumble.\n * Strength has a range of [0, 0xffff].\n *\n * Returns true if rumble state request was honored.\n * Calling this before first retro_run() is likely to return false. */\ntypedef bool (RETRO_CALLCONV *retro_set_rumble_state_t)(unsigned port,\n      enum retro_rumble_effect effect, uint16_t strength);\n\nstruct retro_rumble_interface\n{\n   retro_set_rumble_state_t set_rumble_state;\n};\n\n/* Notifies libretro that audio data should be written. */\ntypedef void (RETRO_CALLCONV *retro_audio_callback_t)(void);\n\n/* True: Audio driver in frontend is active, and callback is\n * expected to be called regularily.\n * False: Audio driver in frontend is paused or inactive.\n * Audio callback will not be called until set_state has been\n * called with true.\n * Initial state is false (inactive).\n */\ntypedef void (RETRO_CALLCONV *retro_audio_set_state_callback_t)(bool enabled);\n\nstruct retro_audio_callback\n{\n   retro_audio_callback_t callback;\n   retro_audio_set_state_callback_t set_state;\n};\n\n/* Notifies a libretro core of time spent since last invocation\n * of retro_run() in microseconds.\n *\n * It will be called right before retro_run() every frame.\n * The frontend can tamper with timing to support cases like\n * fast-forward, slow-motion and framestepping.\n *\n * In those scenarios the reference frame time value will be used. */\ntypedef int64_t retro_usec_t;\ntypedef void (RETRO_CALLCONV *retro_frame_time_callback_t)(retro_usec_t usec);\nstruct retro_frame_time_callback\n{\n   retro_frame_time_callback_t callback;\n   /* Represents the time of one frame. It is computed as\n    * 1000000 / fps, but the implementation will resolve the\n    * rounding to ensure that framestepping, etc is exact. */\n   retro_usec_t reference;\n};\n\n/* Pass this to retro_video_refresh_t if rendering to hardware.\n * Passing NULL to retro_video_refresh_t is still a frame dupe as normal.\n * */\n#define RETRO_HW_FRAME_BUFFER_VALID ((void*)-1)\n\n/* Invalidates the current HW context.\n * Any GL state is lost, and must not be deinitialized explicitly.\n * If explicit deinitialization is desired by the libretro core,\n * it should implement context_destroy callback.\n * If called, all GPU resources must be reinitialized.\n * Usually called when frontend reinits video driver.\n * Also called first time video driver is initialized,\n * allowing libretro core to initialize resources.\n */\ntypedef void (RETRO_CALLCONV *retro_hw_context_reset_t)(void);\n\n/* Gets current framebuffer which is to be rendered to.\n * Could change every frame potentially.\n */\ntypedef uintptr_t (RETRO_CALLCONV *retro_hw_get_current_framebuffer_t)(void);\n\n/* Get a symbol from HW context. */\ntypedef retro_proc_address_t (RETRO_CALLCONV *retro_hw_get_proc_address_t)(const char *sym);\n\nenum retro_hw_context_type\n{\n   RETRO_HW_CONTEXT_NONE             = 0,\n   /* OpenGL 2.x. Driver can choose to use latest compatibility context. */\n   RETRO_HW_CONTEXT_OPENGL           = 1,\n   /* OpenGL ES 2.0. */\n   RETRO_HW_CONTEXT_OPENGLES2        = 2,\n   /* Modern desktop core GL context. Use version_major/\n    * version_minor fields to set GL version. */\n   RETRO_HW_CONTEXT_OPENGL_CORE      = 3,\n   /* OpenGL ES 3.0 */\n   RETRO_HW_CONTEXT_OPENGLES3        = 4,\n   /* OpenGL ES 3.1+. Set version_major/version_minor. For GLES2 and GLES3,\n    * use the corresponding enums directly. */\n   RETRO_HW_CONTEXT_OPENGLES_VERSION = 5,\n\n   /* Vulkan, see RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE. */\n   RETRO_HW_CONTEXT_VULKAN           = 6,\n\n   /* Direct3D, set version_major to select the type of interface\n    * returned by RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE */\n   RETRO_HW_CONTEXT_DIRECT3D         = 7,\n\n   RETRO_HW_CONTEXT_DUMMY = INT_MAX\n};\n\nstruct retro_hw_render_callback\n{\n   /* Which API to use. Set by libretro core. */\n   enum retro_hw_context_type context_type;\n\n   /* Called when a context has been created or when it has been reset.\n    * An OpenGL context is only valid after context_reset() has been called.\n    *\n    * When context_reset is called, OpenGL resources in the libretro\n    * implementation are guaranteed to be invalid.\n    *\n    * It is possible that context_reset is called multiple times during an\n    * application lifecycle.\n    * If context_reset is called without any notification (context_destroy),\n    * the OpenGL context was lost and resources should just be recreated\n    * without any attempt to \"free\" old resources.\n    */\n   retro_hw_context_reset_t context_reset;\n\n   /* Set by frontend.\n    * TODO: This is rather obsolete. The frontend should not\n    * be providing preallocated framebuffers. */\n   retro_hw_get_current_framebuffer_t get_current_framebuffer;\n\n   /* Set by frontend.\n    * Can return all relevant functions, including glClear on Windows. */\n   retro_hw_get_proc_address_t get_proc_address;\n\n   /* Set if render buffers should have depth component attached.\n    * TODO: Obsolete. */\n   bool depth;\n\n   /* Set if stencil buffers should be attached.\n    * TODO: Obsolete. */\n   bool stencil;\n\n   /* If depth and stencil are true, a packed 24/8 buffer will be added.\n    * Only attaching stencil is invalid and will be ignored. */\n\n   /* Use conventional bottom-left origin convention. If false,\n    * standard libretro top-left origin semantics are used.\n    * TODO: Move to GL specific interface. */\n   bool bottom_left_origin;\n\n   /* Major version number for core GL context or GLES 3.1+. */\n   unsigned version_major;\n\n   /* Minor version number for core GL context or GLES 3.1+. */\n   unsigned version_minor;\n\n   /* If this is true, the frontend will go very far to avoid\n    * resetting context in scenarios like toggling fullscreen, etc.\n    * TODO: Obsolete? Maybe frontend should just always assume this ...\n    */\n   bool cache_context;\n\n   /* The reset callback might still be called in extreme situations\n    * such as if the context is lost beyond recovery.\n    *\n    * For optimal stability, set this to false, and allow context to be\n    * reset at any time.\n    */\n\n   /* A callback to be called before the context is destroyed in a\n    * controlled way by the frontend. */\n   retro_hw_context_reset_t context_destroy;\n\n   /* OpenGL resources can be deinitialized cleanly at this step.\n    * context_destroy can be set to NULL, in which resources will\n    * just be destroyed without any notification.\n    *\n    * Even when context_destroy is non-NULL, it is possible that\n    * context_reset is called without any destroy notification.\n    * This happens if context is lost by external factors (such as\n    * notified by GL_ARB_robustness).\n    *\n    * In this case, the context is assumed to be already dead,\n    * and the libretro implementation must not try to free any OpenGL\n    * resources in the subsequent context_reset.\n    */\n\n   /* Creates a debug context. */\n   bool debug_context;\n};\n\n/* Callback type passed in RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK.\n * Called by the frontend in response to keyboard events.\n * down is set if the key is being pressed, or false if it is being released.\n * keycode is the RETROK value of the char.\n * character is the text character of the pressed key. (UTF-32).\n * key_modifiers is a set of RETROKMOD values or'ed together.\n *\n * The pressed/keycode state can be indepedent of the character.\n * It is also possible that multiple characters are generated from a\n * single keypress.\n * Keycode events should be treated separately from character events.\n * However, when possible, the frontend should try to synchronize these.\n * If only a character is posted, keycode should be RETROK_UNKNOWN.\n *\n * Similarily if only a keycode event is generated with no corresponding\n * character, character should be 0.\n */\ntypedef void (RETRO_CALLCONV *retro_keyboard_event_t)(bool down, unsigned keycode,\n      uint32_t character, uint16_t key_modifiers);\n\nstruct retro_keyboard_callback\n{\n   retro_keyboard_event_t callback;\n};\n\n/* Callbacks for RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE &\n * RETRO_ENVIRONMENT_SET_DISK_CONTROL_EXT_INTERFACE.\n * Should be set for implementations which can swap out multiple disk\n * images in runtime.\n *\n * If the implementation can do this automatically, it should strive to do so.\n * However, there are cases where the user must manually do so.\n *\n * Overview: To swap a disk image, eject the disk image with\n * set_eject_state(true).\n * Set the disk index with set_image_index(index). Insert the disk again\n * with set_eject_state(false).\n */\n\n/* If ejected is true, \"ejects\" the virtual disk tray.\n * When ejected, the disk image index can be set.\n */\ntypedef bool (RETRO_CALLCONV *retro_set_eject_state_t)(bool ejected);\n\n/* Gets current eject state. The initial state is 'not ejected'. */\ntypedef bool (RETRO_CALLCONV *retro_get_eject_state_t)(void);\n\n/* Gets current disk index. First disk is index 0.\n * If return value is >= get_num_images(), no disk is currently inserted.\n */\ntypedef unsigned (RETRO_CALLCONV *retro_get_image_index_t)(void);\n\n/* Sets image index. Can only be called when disk is ejected.\n * The implementation supports setting \"no disk\" by using an\n * index >= get_num_images().\n */\ntypedef bool (RETRO_CALLCONV *retro_set_image_index_t)(unsigned index);\n\n/* Gets total number of images which are available to use. */\ntypedef unsigned (RETRO_CALLCONV *retro_get_num_images_t)(void);\n\nstruct retro_game_info;\n\n/* Replaces the disk image associated with index.\n * Arguments to pass in info have same requirements as retro_load_game().\n * Virtual disk tray must be ejected when calling this.\n *\n * Replacing a disk image with info = NULL will remove the disk image\n * from the internal list.\n * As a result, calls to get_image_index() can change.\n *\n * E.g. replace_image_index(1, NULL), and previous get_image_index()\n * returned 4 before.\n * Index 1 will be removed, and the new index is 3.\n */\ntypedef bool (RETRO_CALLCONV *retro_replace_image_index_t)(unsigned index,\n      const struct retro_game_info *info);\n\n/* Adds a new valid index (get_num_images()) to the internal disk list.\n * This will increment subsequent return values from get_num_images() by 1.\n * This image index cannot be used until a disk image has been set\n * with replace_image_index. */\ntypedef bool (RETRO_CALLCONV *retro_add_image_index_t)(void);\n\n/* Sets initial image to insert in drive when calling\n * core_load_game().\n * Since we cannot pass the initial index when loading\n * content (this would require a major API change), this\n * is set by the frontend *before* calling the core's\n * retro_load_game()/retro_load_game_special() implementation.\n * A core should therefore cache the index/path values and handle\n * them inside retro_load_game()/retro_load_game_special().\n * - If 'index' is invalid (index >= get_num_images()), the\n *   core should ignore the set value and instead use 0\n * - 'path' is used purely for error checking - i.e. when\n *   content is loaded, the core should verify that the\n *   disk specified by 'index' has the specified file path.\n *   This is to guard against auto selecting the wrong image\n *   if (for example) the user should modify an existing M3U\n *   playlist. We have to let the core handle this because\n *   set_initial_image() must be called before loading content,\n *   i.e. the frontend cannot access image paths in advance\n *   and thus cannot perform the error check itself.\n *   If set path and content path do not match, the core should\n *   ignore the set 'index' value and instead use 0\n * Returns 'false' if index or 'path' are invalid, or core\n * does not support this functionality\n */\ntypedef bool (RETRO_CALLCONV *retro_set_initial_image_t)(unsigned index, const char *path);\n\n/* Fetches the path of the specified disk image file.\n * Returns 'false' if index is invalid (index >= get_num_images())\n * or path is otherwise unavailable.\n */\ntypedef bool (RETRO_CALLCONV *retro_get_image_path_t)(unsigned index, char *path, size_t len);\n\n/* Fetches a core-provided 'label' for the specified disk\n * image file. In the simplest case this may be a file name\n * (without extension), but for cores with more complex\n * content requirements information may be provided to\n * facilitate user disk swapping - for example, a core\n * running floppy-disk-based content may uniquely label\n * save disks, data disks, level disks, etc. with names\n * corresponding to in-game disk change prompts (so the\n * frontend can provide better user guidance than a 'dumb'\n * disk index value).\n * Returns 'false' if index is invalid (index >= get_num_images())\n * or label is otherwise unavailable.\n */\ntypedef bool (RETRO_CALLCONV *retro_get_image_label_t)(unsigned index, char *label, size_t len);\n\nstruct retro_disk_control_callback\n{\n   retro_set_eject_state_t set_eject_state;\n   retro_get_eject_state_t get_eject_state;\n\n   retro_get_image_index_t get_image_index;\n   retro_set_image_index_t set_image_index;\n   retro_get_num_images_t  get_num_images;\n\n   retro_replace_image_index_t replace_image_index;\n   retro_add_image_index_t add_image_index;\n};\n\nstruct retro_disk_control_ext_callback\n{\n   retro_set_eject_state_t set_eject_state;\n   retro_get_eject_state_t get_eject_state;\n\n   retro_get_image_index_t get_image_index;\n   retro_set_image_index_t set_image_index;\n   retro_get_num_images_t  get_num_images;\n\n   retro_replace_image_index_t replace_image_index;\n   retro_add_image_index_t add_image_index;\n\n   /* NOTE: Frontend will only attempt to record/restore\n    * last used disk index if both set_initial_image()\n    * and get_image_path() are implemented */\n   retro_set_initial_image_t set_initial_image; /* Optional - may be NULL */\n\n   retro_get_image_path_t get_image_path;       /* Optional - may be NULL */\n   retro_get_image_label_t get_image_label;     /* Optional - may be NULL */\n};\n\nenum retro_pixel_format\n{\n   /* 0RGB1555, native endian.\n    * 0 bit must be set to 0.\n    * This pixel format is default for compatibility concerns only.\n    * If a 15/16-bit pixel format is desired, consider using RGB565. */\n   RETRO_PIXEL_FORMAT_0RGB1555 = 0,\n\n   /* XRGB8888, native endian.\n    * X bits are ignored. */\n   RETRO_PIXEL_FORMAT_XRGB8888 = 1,\n\n   /* RGB565, native endian.\n    * This pixel format is the recommended format to use if a 15/16-bit\n    * format is desired as it is the pixel format that is typically\n    * available on a wide range of low-power devices.\n    *\n    * It is also natively supported in APIs like OpenGL ES. */\n   RETRO_PIXEL_FORMAT_RGB565   = 2,\n\n   /* Ensure sizeof() == sizeof(int). */\n   RETRO_PIXEL_FORMAT_UNKNOWN  = INT_MAX\n};\n\nstruct retro_message\n{\n   const char *msg;        /* Message to be displayed. */\n   unsigned    frames;     /* Duration in frames of message. */\n};\n\n/* Describes how the libretro implementation maps a libretro input bind\n * to its internal input system through a human readable string.\n * This string can be used to better let a user configure input. */\nstruct retro_input_descriptor\n{\n   /* Associates given parameters with a description. */\n   unsigned port;\n   unsigned device;\n   unsigned index;\n   unsigned id;\n\n   /* Human readable description for parameters.\n    * The pointer must remain valid until\n    * retro_unload_game() is called. */\n   const char *description;\n};\n\nstruct retro_system_info\n{\n   /* All pointers are owned by libretro implementation, and pointers must\n    * remain valid until retro_deinit() is called. */\n\n   const char *library_name;      /* Descriptive name of library. Should not\n                                   * contain any version numbers, etc. */\n   const char *library_version;   /* Descriptive version of core. */\n\n   const char *valid_extensions;  /* A string listing probably content\n                                   * extensions the core will be able to\n                                   * load, separated with pipe.\n                                   * I.e. \"bin|rom|iso\".\n                                   * Typically used for a GUI to filter\n                                   * out extensions. */\n\n   /* Libretro cores that need to have direct access to their content\n    * files, including cores which use the path of the content files to\n    * determine the paths of other files, should set need_fullpath to true.\n    *\n    * Cores should strive for setting need_fullpath to false,\n    * as it allows the frontend to perform patching, etc.\n    *\n    * If need_fullpath is true and retro_load_game() is called:\n    *    - retro_game_info::path is guaranteed to have a valid path\n    *    - retro_game_info::data and retro_game_info::size are invalid\n    *\n    * If need_fullpath is false and retro_load_game() is called:\n    *    - retro_game_info::path may be NULL\n    *    - retro_game_info::data and retro_game_info::size are guaranteed\n    *      to be valid\n    *\n    * See also:\n    *    - RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY\n    *    - RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY\n    */\n   bool        need_fullpath;\n\n   /* If true, the frontend is not allowed to extract any archives before\n    * loading the real content.\n    * Necessary for certain libretro implementations that load games\n    * from zipped archives. */\n   bool        block_extract;\n};\n\nstruct retro_game_geometry\n{\n   unsigned base_width;    /* Nominal video width of game. */\n   unsigned base_height;   /* Nominal video height of game. */\n   unsigned max_width;     /* Maximum possible width of game. */\n   unsigned max_height;    /* Maximum possible height of game. */\n\n   float    aspect_ratio;  /* Nominal aspect ratio of game. If\n                            * aspect_ratio is <= 0.0, an aspect ratio\n                            * of base_width / base_height is assumed.\n                            * A frontend could override this setting,\n                            * if desired. */\n};\n\nstruct retro_system_timing\n{\n   double fps;             /* FPS of video content. */\n   double sample_rate;     /* Sampling rate of audio. */\n};\n\nstruct retro_system_av_info\n{\n   struct retro_game_geometry geometry;\n   struct retro_system_timing timing;\n};\n\nstruct retro_variable\n{\n   /* Variable to query in RETRO_ENVIRONMENT_GET_VARIABLE.\n    * If NULL, obtains the complete environment string if more\n    * complex parsing is necessary.\n    * The environment string is formatted as key-value pairs\n    * delimited by semicolons as so:\n    * \"key1=value1;key2=value2;...\"\n    */\n   const char *key;\n\n   /* Value to be obtained. If key does not exist, it is set to NULL. */\n   const char *value;\n};\n\nstruct retro_core_option_display\n{\n   /* Variable to configure in RETRO_ENVIRONMENT_SET_CORE_OPTIONS_DISPLAY */\n   const char *key;\n\n   /* Specifies whether variable should be displayed\n    * when presenting core options to the user */\n   bool visible;\n};\n\n/* Maximum number of values permitted for a core option\n * > Note: We have to set a maximum value due the limitations\n *   of the C language - i.e. it is not possible to create an\n *   array of structs each containing a variable sized array,\n *   so the retro_core_option_definition values array must\n *   have a fixed size. The size limit of 128 is a balancing\n *   act - it needs to be large enough to support all 'sane'\n *   core options, but setting it too large may impact low memory\n *   platforms. In practise, if a core option has more than\n *   128 values then the implementation is likely flawed.\n *   To quote the above API reference:\n *      \"The number of possible options should be very limited\n *       i.e. it should be feasible to cycle through options\n *       without a keyboard.\"\n */\n#define RETRO_NUM_CORE_OPTION_VALUES_MAX 128\n\nstruct retro_core_option_value\n{\n   /* Expected option value */\n   const char *value;\n\n   /* Human-readable value label. If NULL, value itself\n    * will be displayed by the frontend */\n   const char *label;\n};\n\nstruct retro_core_option_definition\n{\n   /* Variable to query in RETRO_ENVIRONMENT_GET_VARIABLE. */\n   const char *key;\n\n   /* Human-readable core option description (used as menu label) */\n   const char *desc;\n\n   /* Human-readable core option information (used as menu sublabel) */\n   const char *info;\n\n   /* Array of retro_core_option_value structs, terminated by NULL */\n   struct retro_core_option_value values[RETRO_NUM_CORE_OPTION_VALUES_MAX];\n\n   /* Default core option value. Must match one of the values\n    * in the retro_core_option_value array, otherwise will be\n    * ignored */\n   const char *default_value;\n};\n\nstruct retro_core_options_intl\n{\n   /* Pointer to an array of retro_core_option_definition structs\n    * - US English implementation\n    * - Must point to a valid array */\n   struct retro_core_option_definition *us;\n\n   /* Pointer to an array of retro_core_option_definition structs\n    * - Implementation for current frontend language\n    * - May be NULL */\n   struct retro_core_option_definition *local;\n};\n\nstruct retro_game_info\n{\n   const char *path;       /* Path to game, UTF-8 encoded.\n                            * Sometimes used as a reference for building other paths.\n                            * May be NULL if game was loaded from stdin or similar,\n                            * but in this case some cores will be unable to load `data`.\n                            * So, it is preferable to fabricate something here instead\n                            * of passing NULL, which will help more cores to succeed.\n                            * retro_system_info::need_fullpath requires\n                            * that this path is valid. */\n   const void *data;       /* Memory buffer of loaded game. Will be NULL\n                            * if need_fullpath was set. */\n   size_t      size;       /* Size of memory buffer. */\n   const char *meta;       /* String of implementation specific meta-data. */\n};\n\n#define RETRO_MEMORY_ACCESS_WRITE (1 << 0)\n   /* The core will write to the buffer provided by retro_framebuffer::data. */\n#define RETRO_MEMORY_ACCESS_READ (1 << 1)\n   /* The core will read from retro_framebuffer::data. */\n#define RETRO_MEMORY_TYPE_CACHED (1 << 0)\n   /* The memory in data is cached.\n    * If not cached, random writes and/or reading from the buffer is expected to be very slow. */\nstruct retro_framebuffer\n{\n   void *data;                      /* The framebuffer which the core can render into.\n                                       Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER.\n                                       The initial contents of data are unspecified. */\n   unsigned width;                  /* The framebuffer width used by the core. Set by core. */\n   unsigned height;                 /* The framebuffer height used by the core. Set by core. */\n   size_t pitch;                    /* The number of bytes between the beginning of a scanline,\n                                       and beginning of the next scanline.\n                                       Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER. */\n   enum retro_pixel_format format;  /* The pixel format the core must use to render into data.\n                                       This format could differ from the format used in\n                                       SET_PIXEL_FORMAT.\n                                       Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER. */\n\n   unsigned access_flags;           /* How the core will access the memory in the framebuffer.\n                                       RETRO_MEMORY_ACCESS_* flags.\n                                       Set by core. */\n   unsigned memory_flags;           /* Flags telling core how the memory has been mapped.\n                                       RETRO_MEMORY_TYPE_* flags.\n                                       Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER. */\n};\n\n/* Callbacks */\n\n/* Environment callback. Gives implementations a way of performing\n * uncommon tasks. Extensible. */\ntypedef bool (RETRO_CALLCONV *retro_environment_t)(unsigned cmd, void *data);\n\n/* Render a frame. Pixel format is 15-bit 0RGB1555 native endian\n * unless changed (see RETRO_ENVIRONMENT_SET_PIXEL_FORMAT).\n *\n * Width and height specify dimensions of buffer.\n * Pitch specifices length in bytes between two lines in buffer.\n *\n * For performance reasons, it is highly recommended to have a frame\n * that is packed in memory, i.e. pitch == width * byte_per_pixel.\n * Certain graphic APIs, such as OpenGL ES, do not like textures\n * that are not packed in memory.\n */\ntypedef void (RETRO_CALLCONV *retro_video_refresh_t)(const void *data, unsigned width,\n      unsigned height, size_t pitch);\n\n/* Renders a single audio frame. Should only be used if implementation\n * generates a single sample at a time.\n * Format is signed 16-bit native endian.\n */\ntypedef void (RETRO_CALLCONV *retro_audio_sample_t)(int16_t left, int16_t right);\n\n/* Renders multiple audio frames in one go.\n *\n * One frame is defined as a sample of left and right channels, interleaved.\n * I.e. int16_t buf[4] = { l, r, l, r }; would be 2 frames.\n * Only one of the audio callbacks must ever be used.\n */\ntypedef size_t (RETRO_CALLCONV *retro_audio_sample_batch_t)(const int16_t *data,\n      size_t frames);\n\n/* Polls input. */\ntypedef void (RETRO_CALLCONV *retro_input_poll_t)(void);\n\n/* Queries for input for player 'port'. device will be masked with\n * RETRO_DEVICE_MASK.\n *\n * Specialization of devices such as RETRO_DEVICE_JOYPAD_MULTITAP that\n * have been set with retro_set_controller_port_device()\n * will still use the higher level RETRO_DEVICE_JOYPAD to request input.\n */\ntypedef int16_t (RETRO_CALLCONV *retro_input_state_t)(unsigned port, unsigned device,\n      unsigned index, unsigned id);\n\n/* Sets callbacks. retro_set_environment() is guaranteed to be called\n * before retro_init().\n *\n * The rest of the set_* functions are guaranteed to have been called\n * before the first call to retro_run() is made. */\nRETRO_API void retro_set_environment(retro_environment_t);\nRETRO_API void retro_set_video_refresh(retro_video_refresh_t);\nRETRO_API void retro_set_audio_sample(retro_audio_sample_t);\nRETRO_API void retro_set_audio_sample_batch(retro_audio_sample_batch_t);\nRETRO_API void retro_set_input_poll(retro_input_poll_t);\nRETRO_API void retro_set_input_state(retro_input_state_t);\n\n/* Library global initialization/deinitialization. */\nRETRO_API void retro_init(void);\nRETRO_API void retro_deinit(void);\n\n/* Must return RETRO_API_VERSION. Used to validate ABI compatibility\n * when the API is revised. */\nRETRO_API unsigned retro_api_version(void);\n\n/* Gets statically known system info. Pointers provided in *info\n * must be statically allocated.\n * Can be called at any time, even before retro_init(). */\nRETRO_API void retro_get_system_info(struct retro_system_info *info);\n\n/* Gets information about system audio/video timings and geometry.\n * Can be called only after retro_load_game() has successfully completed.\n * NOTE: The implementation of this function might not initialize every\n * variable if needed.\n * E.g. geom.aspect_ratio might not be initialized if core doesn't\n * desire a particular aspect ratio. */\nRETRO_API void retro_get_system_av_info(struct retro_system_av_info *info);\n\n/* Sets device to be used for player 'port'.\n * By default, RETRO_DEVICE_JOYPAD is assumed to be plugged into all\n * available ports.\n * Setting a particular device type is not a guarantee that libretro cores\n * will only poll input based on that particular device type. It is only a\n * hint to the libretro core when a core cannot automatically detect the\n * appropriate input device type on its own. It is also relevant when a\n * core can change its behavior depending on device type.\n *\n * As part of the core's implementation of retro_set_controller_port_device,\n * the core should call RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS to notify the\n * frontend if the descriptions for any controls have changed as a\n * result of changing the device type.\n */\nRETRO_API void retro_set_controller_port_device(unsigned port, unsigned device);\n\n/* Resets the current game. */\nRETRO_API void retro_reset(void);\n\n/* Runs the game for one video frame.\n * During retro_run(), input_poll callback must be called at least once.\n *\n * If a frame is not rendered for reasons where a game \"dropped\" a frame,\n * this still counts as a frame, and retro_run() should explicitly dupe\n * a frame if GET_CAN_DUPE returns true.\n * In this case, the video callback can take a NULL argument for data.\n */\nRETRO_API void retro_run(void);\n\n/* Returns the amount of data the implementation requires to serialize\n * internal state (save states).\n * Between calls to retro_load_game() and retro_unload_game(), the\n * returned size is never allowed to be larger than a previous returned\n * value, to ensure that the frontend can allocate a save state buffer once.\n */\nRETRO_API size_t retro_serialize_size(void);\n\n/* Serializes internal state. If failed, or size is lower than\n * retro_serialize_size(), it should return false, true otherwise. */\nRETRO_API bool retro_serialize(void *data, size_t size);\nRETRO_API bool retro_unserialize(const void *data, size_t size);\n\nRETRO_API void retro_cheat_reset(void);\nRETRO_API void retro_cheat_set(unsigned index, bool enabled, const char *code);\n\n/* Loads a game.\n * Return true to indicate successful loading and false to indicate load failure.\n */\nRETRO_API bool retro_load_game(const struct retro_game_info *game);\n\n/* Loads a \"special\" kind of game. Should not be used,\n * except in extreme cases. */\nRETRO_API bool retro_load_game_special(\n  unsigned game_type,\n  const struct retro_game_info *info, size_t num_info\n);\n\n/* Unloads the currently loaded game. Called before retro_deinit(void). */\nRETRO_API void retro_unload_game(void);\n\n/* Gets region of game. */\nRETRO_API unsigned retro_get_region(void);\n\n/* Gets region of memory. */\nRETRO_API void *retro_get_memory_data(unsigned id);\nRETRO_API size_t retro_get_memory_size(unsigned id);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "src/lua/lapi.c",
    "content": "/*\n** $Id: lapi.c,v 2.259.1.2 2017/12/06 18:35:12 roberto Exp $\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 <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/* value at a non-valid index */\n#define NONVALIDVALUE\t\tcast(TValue *, luaO_nilobject)\n\n/* corresponding test */\n#define isvalid(o)\t((o) != luaO_nilobject)\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/* test for valid but not pseudo index */\n#define isstackindex(i, o)\t(isvalid(o) && !ispseudo(i))\n\n#define api_checkvalidindex(l,o)  api_check(l, isvalid(o), \"invalid index\")\n\n#define api_checkstackindex(l, i, o)  \\\n\tapi_check(l, isstackindex(i, o), \"index not in the stack\")\n\n\nstatic TValue *index2addr (lua_State *L, int idx) {\n  CallInfo *ci = L->ci;\n  if (idx > 0) {\n    TValue *o = ci->func + idx;\n    api_check(L, idx <= ci->top - (ci->func + 1), \"unacceptable index\");\n    if (o >= L->top) return NONVALIDVALUE;\n    else return o;\n  }\n  else if (!ispseudo(idx)) {  /* negative index */\n    api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), \"invalid index\");\n    return L->top + 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 (ttislcf(ci->func))  /* light C function? */\n      return NONVALIDVALUE;  /* it has no upvalues */\n    else {\n      CClosure *func = clCvalue(ci->func);\n      return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : NONVALIDVALUE;\n    }\n  }\n}\n\n\n/*\n** to be called by 'lua_checkstack' in protected mode, to grow stack\n** capturing memory errors\n*/\nstatic void growstack (lua_State *L, void *ud) {\n  int size = *(int *)ud;\n  luaD_growstack(L, size);\n}\n\n\nLUA_API int lua_checkstack (lua_State *L, int n) {\n  int res;\n  CallInfo *ci = L->ci;\n  lua_lock(L);\n  api_check(L, n >= 0, \"negative 'n'\");\n  if (L->stack_last - L->top > n)  /* stack large enough? */\n    res = 1;  /* yes; check is OK */\n  else {  /* no; need to grow stack */\n    int inuse = cast_int(L->top - L->stack) + EXTRA_STACK;\n    if (inuse > LUAI_MAXSTACK - n)  /* can grow without overflow? */\n      res = 0;  /* no */\n    else  /* try to grow stack */\n      res = (luaD_rawrunprotected(L, &growstack, &n) == LUA_OK);\n  }\n  if (res && ci->top < L->top + n)\n    ci->top = L->top + 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_checknelems(from, n);\n  api_check(from, G(from) == G(to), \"moving among independent states\");\n  api_check(from, to->ci->top - to->top >= n, \"stack overflow\");\n  from->top -= n;\n  for (i = 0; i < n; i++) {\n    setobj2s(to, to->top, from->top + i);\n    to->top++;  /* 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 const lua_Number *lua_version (lua_State *L) {\n  static const lua_Number version = LUA_VERSION_NUM;\n  if (L == NULL) return &version;\n  else return G(L)->version;\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 - L->ci->func) + idx;\n}\n\n\nLUA_API int lua_gettop (lua_State *L) {\n  return cast_int(L->top - (L->ci->func + 1));\n}\n\n\nLUA_API void lua_settop (lua_State *L, int idx) {\n  StkId func = L->ci->func;\n  lua_lock(L);\n  if (idx >= 0) {\n    api_check(L, idx <= L->stack_last - (func + 1), \"new top too large\");\n    while (L->top < (func + 1) + idx)\n      setnilvalue(L->top++);\n    L->top = (func + 1) + idx;\n  }\n  else {\n    api_check(L, -(idx+1) <= (L->top - (func + 1)), \"invalid new top\");\n    L->top += idx+1;  /* 'subtract' index (index is negative) */\n  }\n  lua_unlock(L);\n}\n\n\n/*\n** Reverse the stack segment from 'from' to 'to'\n** (auxiliary to 'lua_rotate')\n*/\nstatic void reverse (lua_State *L, StkId from, StkId to) {\n  for (; from < to; from++, to--) {\n    TValue temp;\n    setobj(L, &temp, 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 - 1;  /* end of stack segment being rotated */\n  p = index2addr(L, idx);  /* start of segment */\n  api_checkstackindex(L, idx, p);\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 = index2addr(L, fromidx);\n  to = index2addr(L, toidx);\n  api_checkvalidindex(L, to);\n  setobj(L, to, fr);\n  if (isupvalue(toidx))  /* function upvalue? */\n    luaC_barrier(L, clCvalue(L->ci->func), 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, index2addr(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  StkId o = index2addr(L, idx);\n  return (isvalid(o) ? ttnov(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_NUMTAGS, \"invalid tag\");\n  return ttypename(t);\n}\n\n\nLUA_API int lua_iscfunction (lua_State *L, int idx) {\n  StkId o = index2addr(L, idx);\n  return (ttislcf(o) || (ttisCclosure(o)));\n}\n\n\nLUA_API int lua_isinteger (lua_State *L, int idx) {\n  StkId o = index2addr(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 = index2addr(L, idx);\n  return tonumber(o, &n);\n}\n\n\nLUA_API int lua_isstring (lua_State *L, int idx) {\n  const TValue *o = index2addr(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 = index2addr(L, idx);\n  return (ttisfulluserdata(o) || ttislightuserdata(o));\n}\n\n\nLUA_API int lua_rawequal (lua_State *L, int index1, int index2) {\n  StkId o1 = index2addr(L, index1);\n  StkId o2 = index2addr(L, index2);\n  return (isvalid(o1) && isvalid(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_checknelems(L, 2);  /* all other operations expect two operands */\n  else {  /* for unary operations, add fake 2nd operand */\n    api_checknelems(L, 1);\n    setobjs2s(L, L->top, L->top - 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, L->top - 2, L->top - 1, L->top - 2);\n  L->top--;  /* remove second operand */\n  lua_unlock(L);\n}\n\n\nLUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {\n  StkId o1, o2;\n  int i = 0;\n  lua_lock(L);  /* may call tag method */\n  o1 = index2addr(L, index1);\n  o2 = index2addr(L, index2);\n  if (isvalid(o1) && isvalid(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 size_t lua_stringtonumber (lua_State *L, const char *s) {\n  size_t sz = luaO_str2num(s, L->top);\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;\n  const TValue *o = index2addr(L, idx);\n  int isnum = tonumber(o, &n);\n  if (!isnum)\n    n = 0;  /* call to 'tonumber' may change 'n' even if it fails */\n  if (pisnum) *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;\n  const TValue *o = index2addr(L, idx);\n  int isnum = tointeger(o, &res);\n  if (!isnum)\n    res = 0;  /* call to 'tointeger' may change 'n' even if it fails */\n  if (pisnum) *pisnum = isnum;\n  return res;\n}\n\n\nLUA_API int lua_toboolean (lua_State *L, int idx) {\n  const TValue *o = index2addr(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  StkId o = index2addr(L, idx);\n  if (!ttisstring(o)) {\n    if (!cvt2str(o)) {  /* not convertible? */\n      if (len != NULL) *len = 0;\n      return NULL;\n    }\n    lua_lock(L);  /* 'luaO_tostring' may create a new string */\n    luaO_tostring(L, o);\n    luaC_checkGC(L);\n    o = index2addr(L, idx);  /* previous call may reallocate the stack */\n    lua_unlock(L);\n  }\n  if (len != NULL)\n    *len = vslen(o);\n  return svalue(o);\n}\n\n\nLUA_API size_t lua_rawlen (lua_State *L, int idx) {\n  StkId o = index2addr(L, idx);\n  switch (ttype(o)) {\n    case LUA_TSHRSTR: return tsvalue(o)->shrlen;\n    case LUA_TLNGSTR: return tsvalue(o)->u.lnglen;\n    case LUA_TUSERDATA: return uvalue(o)->len;\n    case LUA_TTABLE: return luaH_getn(hvalue(o));\n    default: return 0;\n  }\n}\n\n\nLUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {\n  StkId o = index2addr(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\nLUA_API void *lua_touserdata (lua_State *L, int idx) {\n  StkId o = index2addr(L, idx);\n  switch (ttnov(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 lua_State *lua_tothread (lua_State *L, int idx) {\n  StkId o = index2addr(L, idx);\n  return (!ttisthread(o)) ? NULL : thvalue(o);\n}\n\n\nLUA_API const void *lua_topointer (lua_State *L, int idx) {\n  StkId o = index2addr(L, idx);\n  switch (ttype(o)) {\n    case LUA_TTABLE: return hvalue(o);\n    case LUA_TLCL: return clLvalue(o);\n    case LUA_TCCL: return clCvalue(o);\n    case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o)));\n    case LUA_TTHREAD: return thvalue(o);\n    case LUA_TUSERDATA: return getudatamem(uvalue(o));\n    case LUA_TLIGHTUSERDATA: return pvalue(o);\n    default: return NULL;\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(L->top);\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(L->top, 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(L->top, 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, 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(L->top);\n  else {\n    TString *ts;\n    ts = luaS_new(L, s);\n    setsvalue2s(L, L->top, 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  va_start(argp, fmt);\n  ret = luaO_pushvfstring(L, fmt, argp);\n  va_end(argp);\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(L->top, fn);\n    api_incr_top(L);\n  }\n  else {\n    CClosure *cl;\n    api_checknelems(L, n);\n    api_check(L, n <= MAXUPVAL, \"upvalue index too large\");\n    cl = luaF_newCclosure(L, n);\n    cl->f = fn;\n    L->top -= n;\n    while (n--) {\n      setobj2n(L, &cl->upvalue[n], L->top + n);\n      /* does not need barrier because closure is white */\n    }\n    setclCvalue(L, L->top, 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  setbvalue(L->top, (b != 0));  /* ensure that true is 1 */\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(L->top, 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, L->top, L);\n  api_incr_top(L);\n  lua_unlock(L);\n  return (G(L)->mainthread == 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  const TValue *slot;\n  TString *str = luaS_new(L, k);\n  if (luaV_fastget(L, t, str, slot, luaH_getstr)) {\n    setobj2s(L, L->top, slot);\n    api_incr_top(L);\n  }\n  else {\n    setsvalue2s(L, L->top, str);\n    api_incr_top(L);\n    luaV_finishget(L, t, L->top - 1, L->top - 1, slot);\n  }\n  lua_unlock(L);\n  return ttnov(L->top - 1);\n}\n\n\nLUA_API int lua_getglobal (lua_State *L, const char *name) {\n  Table *reg = hvalue(&G(L)->l_registry);\n  lua_lock(L);\n  return auxgetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name);\n}\n\n\nLUA_API int lua_gettable (lua_State *L, int idx) {\n  StkId t;\n  lua_lock(L);\n  t = index2addr(L, idx);\n  luaV_gettable(L, t, L->top - 1, L->top - 1);\n  lua_unlock(L);\n  return ttnov(L->top - 1);\n}\n\n\nLUA_API int lua_getfield (lua_State *L, int idx, const char *k) {\n  lua_lock(L);\n  return auxgetstr(L, index2addr(L, idx), k);\n}\n\n\nLUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {\n  StkId t;\n  const TValue *slot;\n  lua_lock(L);\n  t = index2addr(L, idx);\n  if (luaV_fastget(L, t, n, slot, luaH_getint)) {\n    setobj2s(L, L->top, slot);\n    api_incr_top(L);\n  }\n  else {\n    setivalue(L->top, n);\n    api_incr_top(L);\n    luaV_finishget(L, t, L->top - 1, L->top - 1, slot);\n  }\n  lua_unlock(L);\n  return ttnov(L->top - 1);\n}\n\n\nLUA_API int lua_rawget (lua_State *L, int idx) {\n  StkId t;\n  lua_lock(L);\n  t = index2addr(L, idx);\n  api_check(L, ttistable(t), \"table expected\");\n  setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));\n  lua_unlock(L);\n  return ttnov(L->top - 1);\n}\n\n\nLUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {\n  StkId t;\n  lua_lock(L);\n  t = index2addr(L, idx);\n  api_check(L, ttistable(t), \"table expected\");\n  setobj2s(L, L->top, luaH_getint(hvalue(t), n));\n  api_incr_top(L);\n  lua_unlock(L);\n  return ttnov(L->top - 1);\n}\n\n\nLUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {\n  StkId t;\n  TValue k;\n  lua_lock(L);\n  t = index2addr(L, idx);\n  api_check(L, ttistable(t), \"table expected\");\n  setpvalue(&k, cast(void *, p));\n  setobj2s(L, L->top, luaH_get(hvalue(t), &k));\n  api_incr_top(L);\n  lua_unlock(L);\n  return ttnov(L->top - 1);\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  sethvalue(L, L->top, t);\n  api_incr_top(L);\n  if (narray > 0 || nrec > 0)\n    luaH_resize(L, t, narray, 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 = index2addr(L, objindex);\n  switch (ttnov(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[ttnov(obj)];\n      break;\n  }\n  if (mt != NULL) {\n    sethvalue(L, L->top, mt);\n    api_incr_top(L);\n    res = 1;\n  }\n  lua_unlock(L);\n  return res;\n}\n\n\nLUA_API int lua_getuservalue (lua_State *L, int idx) {\n  StkId o;\n  lua_lock(L);\n  o = index2addr(L, idx);\n  api_check(L, ttisfulluserdata(o), \"full userdata expected\");\n  getuservalue(L, uvalue(o), L->top);\n  api_incr_top(L);\n  lua_unlock(L);\n  return ttnov(L->top - 1);\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  const TValue *slot;\n  TString *str = luaS_new(L, k);\n  api_checknelems(L, 1);\n  if (luaV_fastset(L, t, str, slot, luaH_getstr, L->top - 1))\n    L->top--;  /* pop value */\n  else {\n    setsvalue2s(L, L->top, str);  /* push 'str' (to make it a TValue) */\n    api_incr_top(L);\n    luaV_finishset(L, t, L->top - 1, L->top - 2, slot);\n    L->top -= 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  Table *reg = hvalue(&G(L)->l_registry);\n  lua_lock(L);  /* unlock done in 'auxsetstr' */\n  auxsetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name);\n}\n\n\nLUA_API void lua_settable (lua_State *L, int idx) {\n  StkId t;\n  lua_lock(L);\n  api_checknelems(L, 2);\n  t = index2addr(L, idx);\n  luaV_settable(L, t, L->top - 2, L->top - 1);\n  L->top -= 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, index2addr(L, idx), k);\n}\n\n\nLUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {\n  StkId t;\n  const TValue *slot;\n  lua_lock(L);\n  api_checknelems(L, 1);\n  t = index2addr(L, idx);\n  if (luaV_fastset(L, t, n, slot, luaH_getint, L->top - 1))\n    L->top--;  /* pop value */\n  else {\n    setivalue(L->top, n);\n    api_incr_top(L);\n    luaV_finishset(L, t, L->top - 1, L->top - 2, slot);\n    L->top -= 2;  /* pop value and key */\n  }\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_rawset (lua_State *L, int idx) {\n  StkId o;\n  TValue *slot;\n  lua_lock(L);\n  api_checknelems(L, 2);\n  o = index2addr(L, idx);\n  api_check(L, ttistable(o), \"table expected\");\n  slot = luaH_set(L, hvalue(o), L->top - 2);\n  setobj2t(L, slot, L->top - 1);\n  invalidateTMcache(hvalue(o));\n  luaC_barrierback(L, hvalue(o), L->top-1);\n  L->top -= 2;\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {\n  StkId o;\n  lua_lock(L);\n  api_checknelems(L, 1);\n  o = index2addr(L, idx);\n  api_check(L, ttistable(o), \"table expected\");\n  luaH_setint(L, hvalue(o), n, L->top - 1);\n  luaC_barrierback(L, hvalue(o), L->top-1);\n  L->top--;\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {\n  StkId o;\n  TValue k, *slot;\n  lua_lock(L);\n  api_checknelems(L, 1);\n  o = index2addr(L, idx);\n  api_check(L, ttistable(o), \"table expected\");\n  setpvalue(&k, cast(void *, p));\n  slot = luaH_set(L, hvalue(o), &k);\n  setobj2t(L, slot, L->top - 1);\n  luaC_barrierback(L, hvalue(o), L->top - 1);\n  L->top--;\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_checknelems(L, 1);\n  obj = index2addr(L, objindex);\n  if (ttisnil(L->top - 1))\n    mt = NULL;\n  else {\n    api_check(L, ttistable(L->top - 1), \"table expected\");\n    mt = hvalue(L->top - 1);\n  }\n  switch (ttnov(obj)) {\n    case LUA_TTABLE: {\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[ttnov(obj)] = mt;\n      break;\n    }\n  }\n  L->top--;\n  lua_unlock(L);\n  return 1;\n}\n\n\nLUA_API void lua_setuservalue (lua_State *L, int idx) {\n  StkId o;\n  lua_lock(L);\n  api_checknelems(L, 1);\n  o = index2addr(L, idx);\n  api_check(L, ttisfulluserdata(o), \"full userdata expected\");\n  setuservalue(L, uvalue(o), L->top - 1);\n  luaC_barrier(L, gcvalue(o), L->top - 1);\n  L->top--;\n  lua_unlock(L);\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 || (L->ci->top - L->top >= (nr) - (na)), \\\n\t\"results from function overflow current stack size\")\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_checknelems(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 - (nargs+1);\n  if (k != NULL && L->nny == 0) {  /* 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  int 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_checknelems(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 = index2addr(L, errfunc);\n    api_checkstackindex(L, errfunc, o);\n    func = savestack(L, o);\n  }\n  c.func = L->top - (nargs+1);  /* function to be called */\n  if (k == NULL || L->nny > 0) {  /* 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->extra = savestack(L, c.func);\n    ci->u.c.old_errfunc = L->errfunc;\n    L->errfunc = func;\n    setoah(ci->callstatus, 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 status;\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  int 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(L->top - 1);  /* get newly created function */\n    if (f->nupvalues >= 1) {  /* does it have an upvalue? */\n      /* get global table from registry */\n      Table *reg = hvalue(&G(L)->l_registry);\n      const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);\n      /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */\n      setobj(L, f->upvals[0]->v, gt);\n      luaC_upvalbarrier(L, f->upvals[0]);\n    }\n  }\n  lua_unlock(L);\n  return status;\n}\n\n\nLUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) {\n  int status;\n  TValue *o;\n  lua_lock(L);\n  api_checknelems(L, 1);\n  o = L->top - 1;\n  if (isLfunction(o))\n    status = luaU_dump(L, getproto(o), writer, data, strip);\n  else\n    status = 1;\n  lua_unlock(L);\n  return status;\n}\n\n\nLUA_API int lua_status (lua_State *L) {\n  return L->status;\n}\n\n\n/*\n** Garbage-collection function\n*/\n\nLUA_API int lua_gc (lua_State *L, int what, int data) {\n  int res = 0;\n  global_State *g;\n  lua_lock(L);\n  g = G(L);\n  switch (what) {\n    case LUA_GCSTOP: {\n      g->gcrunning = 0;\n      break;\n    }\n    case LUA_GCRESTART: {\n      luaE_setdebt(g, 0);\n      g->gcrunning = 1;\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      l_mem debt = 1;  /* =1 to signal that it did an actual step */\n      lu_byte oldrunning = g->gcrunning;\n      g->gcrunning = 1;  /* allow GC to run */\n      if (data == 0) {\n        luaE_setdebt(g, -GCSTEPSIZE);  /* to do a \"small\" step */\n        luaC_step(L);\n      }\n      else {  /* add 'data' to total debt */\n        debt = cast(l_mem, data) * 1024 + g->GCdebt;\n        luaE_setdebt(g, debt);\n        luaC_checkGC(L);\n      }\n      g->gcrunning = oldrunning;  /* restore previous state */\n      if (debt > 0 && g->gcstate == GCSpause)  /* end of cycle? */\n        res = 1;  /* signal it */\n      break;\n    }\n    case LUA_GCSETPAUSE: {\n      res = g->gcpause;\n      g->gcpause = data;\n      break;\n    }\n    case LUA_GCSETSTEPMUL: {\n      res = g->gcstepmul;\n      if (data < 40) data = 40;  /* avoid ridiculous low values (and 0) */\n      g->gcstepmul = data;\n      break;\n    }\n    case LUA_GCISRUNNING: {\n      res = g->gcrunning;\n      break;\n    }\n    default: res = -1;  /* invalid option */\n  }\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  lua_lock(L);\n  api_checknelems(L, 1);\n  luaG_errormsg(L);\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  StkId t;\n  int more;\n  lua_lock(L);\n  t = index2addr(L, idx);\n  api_check(L, ttistable(t), \"table expected\");\n  more = luaH_next(L, hvalue(t), L->top - 1);\n  if (more) {\n    api_incr_top(L);\n  }\n  else  /* no more elements */\n    L->top -= 1;  /* remove key */\n  lua_unlock(L);\n  return more;\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 >= 2) {\n    luaV_concat(L, n);\n  }\n  else if (n == 0) {  /* push empty string */\n    setsvalue2s(L, L->top, luaS_newlstr(L, \"\", 0));\n    api_incr_top(L);\n  }\n  /* else n == 1; nothing to do */\n  luaC_checkGC(L);\n  lua_unlock(L);\n}\n\n\nLUA_API void lua_len (lua_State *L, int idx) {\n  StkId t;\n  lua_lock(L);\n  t = index2addr(L, idx);\n  luaV_objlen(L, L->top, 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\nLUA_API void *lua_newuserdata (lua_State *L, size_t size) {\n  Udata *u;\n  lua_lock(L);\n  u = luaS_newudata(L, size);\n  setuvalue(L, L->top, 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 (StkId fi, int n, TValue **val,\n                                CClosure **owner, UpVal **uv) {\n  switch (ttype(fi)) {\n    case LUA_TCCL: {  /* C closure */\n      CClosure *f = clCvalue(fi);\n      if (!(1 <= n && n <= f->nupvalues)) return NULL;\n      *val = &f->upvalue[n-1];\n      if (owner) *owner = f;\n      return \"\";\n    }\n    case LUA_TLCL: {  /* Lua closure */\n      LClosure *f = clLvalue(fi);\n      TString *name;\n      Proto *p = f->p;\n      if (!(1 <= n && n <= p->sizeupvalues)) return NULL;\n      *val = f->upvals[n-1]->v;\n      if (uv) *uv = 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(index2addr(L, funcindex), n, &val, NULL, NULL);\n  if (name) {\n    setobj2s(L, L->top, 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  CClosure *owner = NULL;\n  UpVal *uv = NULL;\n  StkId fi;\n  lua_lock(L);\n  fi = index2addr(L, funcindex);\n  api_checknelems(L, 1);\n  name = aux_upvalue(fi, n, &val, &owner, &uv);\n  if (name) {\n    L->top--;\n    setobj(L, val, L->top);\n    if (owner) { luaC_barrier(L, owner, L->top); }\n    else if (uv) { luaC_upvalbarrier(L, uv); }\n  }\n  lua_unlock(L);\n  return name;\n}\n\n\nstatic UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {\n  LClosure *f;\n  StkId fi = index2addr(L, fidx);\n  api_check(L, ttisLclosure(fi), \"Lua function expected\");\n  f = clLvalue(fi);\n  api_check(L, (1 <= n && n <= f->p->sizeupvalues), \"invalid upvalue index\");\n  if (pf) *pf = f;\n  return &f->upvals[n - 1];  /* get its upvalue pointer */\n}\n\n\nLUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {\n  StkId fi = index2addr(L, fidx);\n  switch (ttype(fi)) {\n    case LUA_TLCL: {  /* lua closure */\n      return *getupvalref(L, fidx, n, NULL);\n    }\n    case LUA_TCCL: {  /* C closure */\n      CClosure *f = clCvalue(fi);\n      api_check(L, 1 <= n && n <= f->nupvalues, \"invalid upvalue index\");\n      return &f->upvalue[n - 1];\n    }\n    default: {\n      api_check(L, 0, \"closure 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  luaC_upvdeccount(L, *up1);\n  *up1 = *up2;\n  (*up1)->refcount++;\n  if (upisopen(*up1)) (*up1)->u.open.touched = 1;\n  luaC_upvalbarrier(L, *up1);\n}\n\n\n"
  },
  {
    "path": "src/lua/lapi.h",
    "content": "/*\n** $Id: lapi.h,v 2.9.1.1 2017/04/19 17:20:42 roberto Exp $\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#define api_incr_top(L)   {L->top++; api_check(L, L->top <= L->ci->top, \\\n\t\t\t\t\"stack overflow\");}\n\n#define adjustresults(L,nres) \\\n    { if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; }\n\n#define api_checknelems(L,n)\tapi_check(L, (n) < (L->top - L->ci->func), \\\n\t\t\t\t  \"not enough elements in the stack\")\n\n\n#endif\n"
  },
  {
    "path": "src/lua/lauxlib.c",
    "content": "/*\n** $Id: lauxlib.c,v 1.289.1.1 2017/04/19 17:20:42 roberto Exp $\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\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.\n** return 1 + string at top if find 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        lua_remove(L, -2);  /* remove table (but keep name) */\n        lua_pushliteral(L, \".\");\n        lua_insert(L, -2);  /* place '.' between the two names */\n        lua_concat(L, 3);\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  if (findfield(L, top + 1, 2)) {\n    const char *name = lua_tostring(L, -1);\n    if (strncmp(name, \"_G.\", 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);  /* move name to proper place */\n    lua_pop(L, 2);  /* remove pushed values */\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 (pushglobalfuncname(L, ar)) {  /* try first 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->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 (*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  lua_Debug ar;\n  int top = lua_gettop(L);\n  int last = lastlevel(L1);\n  int n1 = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;\n  if (msg)\n    lua_pushfstring(L, \"%s\\n\", msg);\n  luaL_checkstack(L, 10, NULL);\n  lua_pushliteral(L, \"stack traceback:\");\n  while (lua_getstack(L1, level++, &ar)) {\n    if (n1-- == 0) {  /* too many levels? */\n      lua_pushliteral(L, \"\\n\\t...\");  /* add a '...' */\n      level = last - LEVELS2 + 1;  /* and skip to last ones */\n    }\n    else {\n      lua_getinfo(L1, \"Slnt\", &ar);\n      lua_pushfstring(L, \"\\n\\t%s:\", ar.short_src);\n      if (ar.currentline > 0)\n        lua_pushfstring(L, \"%d:\", ar.currentline);\n      lua_pushliteral(L, \" in \");\n      pushfuncname(L, &ar);\n      if (ar.istailcall)\n        lua_pushliteral(L, \"\\n\\t(...tail calls...)\");\n      lua_concat(L, lua_gettop(L) - top);\n    }\n  }\n  lua_concat(L, lua_gettop(L) - top);\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  if (!lua_getstack(L, 0, &ar))  /* no stack frame? */\n    return luaL_error(L, \"bad argument #%d (%s)\", arg, extramsg);\n  lua_getinfo(L, \"n\", &ar);\n  if (strcmp(ar.namewhat, \"method\") == 0) {\n    arg--;  /* do not count 'self' */\n    if (arg == 0)  /* error is in the self argument itself? */\n      return luaL_error(L, \"calling '%s' on bad self (%s)\",\n                           ar.name, extramsg);\n  }\n  if (ar.name == NULL)\n    ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : \"?\";\n  return luaL_error(L, \"bad argument #%d to '%s' (%s)\",\n                        arg, ar.name, extramsg);\n}\n\n\nstatic int 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  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** an error with \"stack overflow\" 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    lua_pushnil(L);\n    if (fname)\n      lua_pushfstring(L, \"%s: %s\", fname, strerror(en));\n    else\n      lua_pushstring(L, strerror(en));\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  const char *what = \"exit\";  /* type of termination */\n  if (stat == -1)  /* error? */\n    return luaL_fileresult(L, 0, NULL);\n  else {\n    l_inspectstat(stat, what);  /* interpret result */\n    if (*what == 'e' && stat == 0)  /* successful termination? */\n      lua_pushboolean(L, 1);\n    else\n      lua_pushnil(L);\n    lua_pushstring(L, what);\n    lua_pushinteger(L, stat);\n    return 3;  /* return true/nil,what,code */\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  if (p == NULL) typeerror(L, 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 (!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 (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 (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 (!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 (!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 (!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\nstatic void *resizebox (lua_State *L, int idx, size_t newsize) {\n  void *ud;\n  lua_Alloc allocf = lua_getallocf(L, &ud);\n  UBox *box = (UBox *)lua_touserdata(L, idx);\n  void *temp = allocf(ud, box->box, box->bsize, newsize);\n  if (temp == NULL && newsize > 0) {  /* allocation error? */\n    resizebox(L, idx, 0);  /* free buffer */\n    luaL_error(L, \"not enough memory for buffer allocation\");\n  }\n  box->box = temp;\n  box->bsize = newsize;\n  return temp;\n}\n\n\nstatic int boxgc (lua_State *L) {\n  resizebox(L, 1, 0);\n  return 0;\n}\n\n\nstatic void *newbox (lua_State *L, size_t newsize) {\n  UBox *box = (UBox *)lua_newuserdata(L, sizeof(UBox));\n  box->box = NULL;\n  box->bsize = 0;\n  if (luaL_newmetatable(L, \"LUABOX\")) {  /* creating metatable? */\n    lua_pushcfunction(L, boxgc);\n    lua_setfield(L, -2, \"__gc\");  /* metatable.__gc = boxgc */\n  }\n  lua_setmetatable(L, -2);\n  return resizebox(L, -1, newsize);\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)->initb)\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  lua_State *L = B->L;\n  if (B->size - B->n < sz) {  /* not enough space? */\n    char *newbuff;\n    size_t newsize = B->size * 2;  /* double buffer size */\n    if (newsize - B->n < sz)  /* not big enough? */\n      newsize = B->n + sz;\n    if (newsize < B->n || newsize - B->n < sz)\n      luaL_error(L, \"buffer too large\");\n    /* create larger buffer */\n    if (buffonstack(B))\n      newbuff = (char *)resizebox(L, -1, newsize);\n    else {  /* no buffer yet */\n      newbuff = (char *)newbox(L, newsize);\n      memcpy(newbuff, B->b, B->n * sizeof(char));  /* copy original content */\n    }\n    B->b = newbuff;\n    B->size = newsize;\n  }\n  return &B->b[B->n];\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 = luaL_prepbuffsize(B, l);\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  lua_pushlstring(L, B->b, B->n);\n  if (buffonstack(B)) {\n    resizebox(L, -2, 0);  /* delete old buffer */\n    lua_remove(L, -2);  /* remove its header from the stack */\n  }\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\nLUALIB_API void luaL_addvalue (luaL_Buffer *B) {\n  lua_State *L = B->L;\n  size_t l;\n  const char *s = lua_tolstring(L, -1, &l);\n  if (buffonstack(B))\n    lua_insert(L, -2);  /* put value below buffer */\n  luaL_addlstring(B, s, l);\n  lua_remove(L, (buffonstack(B)) ? -2 : -1);  /* remove value */\n}\n\n\nLUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {\n  B->L = L;\n  B->b = B->initb;\n  B->n = 0;\n  B->size = LUAL_BUFFERSIZE;\n}\n\n\nLUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {\n  luaL_buffinit(L, B);\n  return luaL_prepbuffsize(B, sz);\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Reference system\n** =======================================================\n*/\n\n/* index of free-list header */\n#define freelist\t0\n\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  lua_rawgeti(L, t, freelist);  /* get first free element */\n  ref = (int)lua_tointeger(L, -1);  /* ref = t[freelist] */\n  lua_pop(L, 1);  /* remove it from stack */\n  if (ref != 0) {  /* any free element? */\n    lua_rawgeti(L, t, ref);  /* remove it from list */\n    lua_rawseti(L, t, freelist);  /* (t[freelist] = 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, freelist);\n    lua_rawseti(L, t, ref);  /* t[ref] = t[freelist] */\n    lua_pushinteger(L, ref);\n    lua_rawseti(L, t, freelist);  /* t[freelist] = ref */\n  }\n}\n\n/* }====================================================== */\n\n\n/*\n** {======================================================\n** Load functions\n** =======================================================\n*/\n\ntypedef struct LoadF {\n  int 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  (void)L;  /* not used */\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  const char *serr = strerror(errno);\n  const char *filename = lua_tostring(L, fnameindex) + 1;\n  lua_pushfstring(L, \"cannot %s %s: %s\", what, filename, serr);\n  lua_remove(L, fnameindex);\n  return LUA_ERRFILE;\n}\n\n\nstatic int skipBOM (LoadF *lf) {\n  const char *p = \"\\xEF\\xBB\\xBF\";  /* UTF-8 BOM mark */\n  int c;\n  lf->n = 0;\n  do {\n    c = getc(lf->f);\n    if (c == EOF || c != *(const unsigned char *)p++) return c;\n    lf->buff[lf->n++] = c;  /* to be read by the parser */\n  } while (*p != '\\0');\n  lf->n = 0;  /* prefix matched; discard it */\n  return getc(lf->f);  /* return next 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 (LoadF *lf, int *cp) {\n  int c = *cp = skipBOM(lf);\n  if (c == '#') {  /* first line is a comment (Unix exec. file)? */\n    do {  /* skip first line */\n      c = getc(lf->f);\n    } while (c != EOF && c != '\\n');\n    *cp = getc(lf->f);  /* skip end-of-line, 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    lf.f = fopen(filename, \"r\");\n    if (lf.f == NULL) return errfile(L, \"open\", fnameindex);\n  }\n  if (skipcomment(&lf, &c))  /* read initial portion */\n    lf.buff[lf.n++] = '\\n';  /* add line to correct line numbers */\n  if (c == LUA_SIGNATURE[0] && filename) {  /* binary file? */\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, &c);  /* re-read initial portion */\n  }\n  if (c != EOF)\n    lf.buff[lf.n++] = c;  /* 'c' is the first character of the stream */\n  status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);\n  readstatus = ferror(lf.f);\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  (void)L;  /* not used */\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 (!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  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        if (lua_isinteger(L, idx))\n          lua_pushfstring(L, \"%I\", (LUAI_UACINT)lua_tointeger(L, idx));\n        else\n          lua_pushfstring(L, \"%f\", (LUAI_UACNUMBER)lua_tonumber(L, idx));\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** {======================================================\n** Compatibility with 5.1 module functions\n** =======================================================\n*/\n#if defined(LUA_COMPAT_MODULE)\n\nstatic const char *luaL_findtable (lua_State *L, int idx,\n                                   const char *fname, int szhint) {\n  const char *e;\n  if (idx) lua_pushvalue(L, idx);\n  do {\n    e = strchr(fname, '.');\n    if (e == NULL) e = fname + strlen(fname);\n    lua_pushlstring(L, fname, e - fname);\n    if (lua_rawget(L, -2) == LUA_TNIL) {  /* no such field? */\n      lua_pop(L, 1);  /* remove this nil */\n      lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */\n      lua_pushlstring(L, fname, e - fname);\n      lua_pushvalue(L, -2);\n      lua_settable(L, -4);  /* set new table into field */\n    }\n    else if (!lua_istable(L, -1)) {  /* field has a non-table value? */\n      lua_pop(L, 2);  /* remove table and value */\n      return fname;  /* return problematic part of the name */\n    }\n    lua_remove(L, -2);  /* remove previous table */\n    fname = e + 1;\n  } while (*e == '.');\n  return NULL;\n}\n\n\n/*\n** Count number of elements in a luaL_Reg list.\n*/\nstatic int libsize (const luaL_Reg *l) {\n  int size = 0;\n  for (; l && l->name; l++) size++;\n  return size;\n}\n\n\n/*\n** Find or create a module table with a given name. The function\n** first looks at the LOADED table and, if that fails, try a\n** global variable with that name. In any case, leaves on the stack\n** the module table.\n*/\nLUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,\n                                 int sizehint) {\n  luaL_findtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE, 1);\n  if (lua_getfield(L, -1, modname) != LUA_TTABLE) {  /* no LOADED[modname]? */\n    lua_pop(L, 1);  /* remove previous result */\n    /* try global variable (and create one if it does not exist) */\n    lua_pushglobaltable(L);\n    if (luaL_findtable(L, 0, modname, sizehint) != NULL)\n      luaL_error(L, \"name conflict for module '%s'\", modname);\n    lua_pushvalue(L, -1);\n    lua_setfield(L, -3, modname);  /* LOADED[modname] = new table */\n  }\n  lua_remove(L, -2);  /* remove LOADED table */\n}\n\n\nLUALIB_API void luaL_openlib (lua_State *L, const char *libname,\n                               const luaL_Reg *l, int nup) {\n  luaL_checkversion(L);\n  if (libname) {\n    luaL_pushmodule(L, libname, libsize(l));  /* get/create library table */\n    lua_insert(L, -(nup + 1));  /* move library table to below upvalues */\n  }\n  if (l)\n    luaL_setfuncs(L, l, nup);\n  else\n    lua_pop(L, nup);  /* remove upvalues */\n}\n\n#endif\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    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    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 const char *luaL_gsub (lua_State *L, const char *s, const char *p,\n                                                               const char *r) {\n  const char *wild;\n  size_t l = strlen(p);\n  luaL_Buffer b;\n  luaL_buffinit(L, &b);\n  while ((wild = strstr(s, p)) != NULL) {\n    luaL_addlstring(&b, s, 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  luaL_pushresult(&b);\n  return lua_tostring(L, -1);\n}\n\n\nstatic void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {\n  (void)ud; (void)osize;  /* not used */\n  if (nsize == 0) {\n    free(ptr);\n    return NULL;\n  }\n  else\n    return realloc(ptr, nsize);\n}\n\n\nstatic int panic (lua_State *L) {\n  lua_writestringerror(\"PANIC: unprotected error in call to Lua API (%s)\\n\",\n                        lua_tostring(L, -1));\n  return 0;  /* return to Lua to abort */\n}\n\n\nLUALIB_API lua_State *luaL_newstate (void) {\n  lua_State *L = lua_newstate(l_alloc, NULL);\n  if (L) lua_atpanic(L, &panic);\n  return L;\n}\n\n\nLUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {\n  const 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  if (v != lua_version(NULL))\n    luaL_error(L, \"multiple Lua VMs detected\");\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"
  },
  {
    "path": "src/lua/lauxlib.h",
    "content": "/*\n** $Id: lauxlib.h,v 1.131.1.1 2017/04/19 17:20:42 roberto Exp $\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 \"lua.h\"\n\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 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\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);\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 lua_Integer (luaL_len) (lua_State *L, int idx);\n\nLUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,\n                                                  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\t((void)((cond) || luaL_argerror(L, (arg), (extramsg))))\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** {======================================================\n** Generic Buffer manipulation\n** =======================================================\n*/\n\ntypedef struct 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  char initb[LUAL_BUFFERSIZE];  /* initial buffer */\n} luaL_Buffer;\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\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/* compatibility with old module system */\n#if defined(LUA_COMPAT_MODULE)\n\nLUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname,\n                                   int sizehint);\nLUALIB_API void (luaL_openlib) (lua_State *L, const char *libname,\n                                const luaL_Reg *l, int nup);\n\n#define luaL_register(L,n,l)\t(luaL_openlib(L,(n),(l),0))\n\n#endif\n\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\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": "src/lua/lbaselib.c",
    "content": "/*\n** $Id: lbaselib.c,v 1.314.1.1 2017/04/19 17:39:34 roberto Exp $\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\n\nstatic int luaB_print (lua_State *L) {\n  int n = lua_gettop(L);  /* number of arguments */\n  int i;\n  lua_getglobal(L, \"tostring\");\n  for (i=1; i<=n; i++) {\n    const char *s;\n    size_t l;\n    lua_pushvalue(L, -1);  /* function to be called */\n    lua_pushvalue(L, i);   /* value to print */\n    lua_call(L, 1, 1);\n    s = lua_tolstring(L, -1, &l);  /* get result */\n    if (s == NULL)\n      return luaL_error(L, \"'tostring' must return a string to 'print'\");\n    if (i>1) lua_writestring(\"\\t\", 1);\n    lua_writestring(s, l);\n    lua_pop(L, 1);  /* pop result */\n  }\n  lua_writeline();\n  return 0;\n}\n\n\n#define SPACECHARS\t\" \\f\\n\\r\\t\\v\"\n\nstatic const char *b_str2int (const char *s, int 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 signal */\n  else if (*s == '+') s++;\n  if (!isalnum((unsigned char)*s))  /* no digit? */\n    return NULL;\n  do {\n    int digit = (isdigit((unsigned char)*s)) ? *s - '0'\n                   : (toupper((unsigned char)*s) - 'A') + 10;\n    if (digit >= base) return NULL;  /* invalid numeral */\n    n = n * base + digit;\n    s++;\n  } while (isalnum((unsigned char)*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    luaL_checkany(L, 1);\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    }\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, (int)base, &n) == s + l) {\n      lua_pushinteger(L, n);\n      return 1;\n    }  /* else not a number */\n  }  /* else not a number */\n  lua_pushnil(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_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,\n                    \"nil or table expected\");\n  if (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_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,\n                   \"table or string expected\");\n  lua_pushinteger(L, 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 luaB_collectgarbage (lua_State *L) {\n  static const char *const opts[] = {\"stop\", \"restart\", \"collect\",\n    \"count\", \"step\", \"setpause\", \"setstepmul\",\n    \"isrunning\", NULL};\n  static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,\n    LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,\n    LUA_GCISRUNNING};\n  int o = optsnum[luaL_checkoption(L, 1, \"collect\", opts)];\n  int ex = (int)luaL_optinteger(L, 2, 0);\n  int res = lua_gc(L, o, ex);\n  switch (o) {\n    case LUA_GCCOUNT: {\n      int b = lua_gc(L, LUA_GCCOUNTB, 0);\n      lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024));\n      return 1;\n    }\n    case LUA_GCSTEP: case LUA_GCISRUNNING: {\n      lua_pushboolean(L, res);\n      return 1;\n    }\n    default: {\n      lua_pushinteger(L, res);\n      return 1;\n    }\n  }\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 pairsmeta (lua_State *L, const char *method, int iszero,\n                      lua_CFunction iter) {\n  luaL_checkany(L, 1);\n  if (luaL_getmetafield(L, 1, method) == LUA_TNIL) {  /* no metamethod? */\n    lua_pushcfunction(L, iter);  /* will return generator, */\n    lua_pushvalue(L, 1);  /* state, */\n    if (iszero) lua_pushinteger(L, 0);  /* and initial value */\n    else lua_pushnil(L);\n  }\n  else {\n    lua_pushvalue(L, 1);  /* argument 'self' to metamethod */\n    lua_call(L, 1, 3);  /* get 3 values from metamethod */\n  }\n  return 3;\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 luaB_pairs (lua_State *L) {\n  return pairsmeta(L, \"__pairs\", 0, luaB_next);\n}\n\n\n/*\n** Traversal function for 'ipairs'\n*/\nstatic int ipairsaux (lua_State *L) {\n  lua_Integer i = luaL_checkinteger(L, 2) + 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#if defined(LUA_COMPAT_IPAIRS)\n  return pairsmeta(L, \"__ipairs\", 1, ipairsaux);\n#else\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#endif\n}\n\n\nstatic int load_aux (lua_State *L, int status, int envidx) {\n  if (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    lua_pushnil(L);\n    lua_insert(L, -2);  /* put before error message */\n    return 2;  /* return nil plus error message */\n  }\n}\n\n\nstatic int luaB_loadfile (lua_State *L) {\n  const char *fname = luaL_optstring(L, 1, NULL);\n  const char *mode = luaL_optstring(L, 2, NULL);\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 (!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 = luaL_optstring(L, 3, \"bt\");\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 (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 (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 (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#if defined(LUA_COMPAT_LOADSTRING)\n  {\"loadstring\", luaB_load},\n#endif\n  {\"next\", luaB_next},\n  {\"pairs\", luaB_pairs},\n  {\"pcall\", luaB_pcall},\n  {\"print\", luaB_print},\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  {\"_G\", 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, \"_G\");\n  /* set global _VERSION */\n  lua_pushliteral(L, LUA_VERSION);\n  lua_setfield(L, -2, \"_VERSION\");\n  return 1;\n}\n\n"
  },
  {
    "path": "src/lua/lbitlib.c",
    "content": "/*\n** $Id: lbitlib.c,v 1.30.1.1 2017/04/19 17:20:42 roberto Exp $\n** Standard library for bitwise operations\n** See Copyright Notice in lua.h\n*/\n\n#define lbitlib_c\n#define LUA_LIB\n\n#include \"lprefix.h\"\n\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n\n\n#if defined(LUA_COMPAT_BITLIB)\t\t/* { */\n\n\n#define pushunsigned(L,n)\tlua_pushinteger(L, (lua_Integer)(n))\n#define checkunsigned(L,i)\t((lua_Unsigned)luaL_checkinteger(L,i))\n\n\n/* number of bits to consider in a number */\n#if !defined(LUA_NBITS)\n#define LUA_NBITS\t32\n#endif\n\n\n/*\n** a lua_Unsigned with its first LUA_NBITS bits equal to 1. (Shift must\n** be made in two parts to avoid problems when LUA_NBITS is equal to the\n** number of bits in a lua_Unsigned.)\n*/\n#define ALLONES\t\t(~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1))\n\n\n/* macro to trim extra bits */\n#define trim(x)\t\t((x) & ALLONES)\n\n\n/* builds a number with 'n' ones (1 <= n <= LUA_NBITS) */\n#define mask(n)\t\t(~((ALLONES << 1) << ((n) - 1)))\n\n\n\nstatic lua_Unsigned andaux (lua_State *L) {\n  int i, n = lua_gettop(L);\n  lua_Unsigned r = ~(lua_Unsigned)0;\n  for (i = 1; i <= n; i++)\n    r &= checkunsigned(L, i);\n  return trim(r);\n}\n\n\nstatic int b_and (lua_State *L) {\n  lua_Unsigned r = andaux(L);\n  pushunsigned(L, r);\n  return 1;\n}\n\n\nstatic int b_test (lua_State *L) {\n  lua_Unsigned r = andaux(L);\n  lua_pushboolean(L, r != 0);\n  return 1;\n}\n\n\nstatic int b_or (lua_State *L) {\n  int i, n = lua_gettop(L);\n  lua_Unsigned r = 0;\n  for (i = 1; i <= n; i++)\n    r |= checkunsigned(L, i);\n  pushunsigned(L, trim(r));\n  return 1;\n}\n\n\nstatic int b_xor (lua_State *L) {\n  int i, n = lua_gettop(L);\n  lua_Unsigned r = 0;\n  for (i = 1; i <= n; i++)\n    r ^= checkunsigned(L, i);\n  pushunsigned(L, trim(r));\n  return 1;\n}\n\n\nstatic int b_not (lua_State *L) {\n  lua_Unsigned r = ~checkunsigned(L, 1);\n  pushunsigned(L, trim(r));\n  return 1;\n}\n\n\nstatic int b_shift (lua_State *L, lua_Unsigned r, lua_Integer i) {\n  if (i < 0) {  /* shift right? */\n    i = -i;\n    r = trim(r);\n    if (i >= LUA_NBITS) r = 0;\n    else r >>= i;\n  }\n  else {  /* shift left */\n    if (i >= LUA_NBITS) r = 0;\n    else r <<= i;\n    r = trim(r);\n  }\n  pushunsigned(L, r);\n  return 1;\n}\n\n\nstatic int b_lshift (lua_State *L) {\n  return b_shift(L, checkunsigned(L, 1), luaL_checkinteger(L, 2));\n}\n\n\nstatic int b_rshift (lua_State *L) {\n  return b_shift(L, checkunsigned(L, 1), -luaL_checkinteger(L, 2));\n}\n\n\nstatic int b_arshift (lua_State *L) {\n  lua_Unsigned r = checkunsigned(L, 1);\n  lua_Integer i = luaL_checkinteger(L, 2);\n  if (i < 0 || !(r & ((lua_Unsigned)1 << (LUA_NBITS - 1))))\n    return b_shift(L, r, -i);\n  else {  /* arithmetic shift for 'negative' number */\n    if (i >= LUA_NBITS) r = ALLONES;\n    else\n      r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i));  /* add signal bit */\n    pushunsigned(L, r);\n    return 1;\n  }\n}\n\n\nstatic int b_rot (lua_State *L, lua_Integer d) {\n  lua_Unsigned r = checkunsigned(L, 1);\n  int i = d & (LUA_NBITS - 1);  /* i = d % NBITS */\n  r = trim(r);\n  if (i != 0)  /* avoid undefined shift of LUA_NBITS when i == 0 */\n    r = (r << i) | (r >> (LUA_NBITS - i));\n  pushunsigned(L, trim(r));\n  return 1;\n}\n\n\nstatic int b_lrot (lua_State *L) {\n  return b_rot(L, luaL_checkinteger(L, 2));\n}\n\n\nstatic int b_rrot (lua_State *L) {\n  return b_rot(L, -luaL_checkinteger(L, 2));\n}\n\n\n/*\n** get field and width arguments for field-manipulation functions,\n** checking whether they are valid.\n** ('luaL_error' called without 'return' to avoid later warnings about\n** 'width' being used uninitialized.)\n*/\nstatic int fieldargs (lua_State *L, int farg, int *width) {\n  lua_Integer f = luaL_checkinteger(L, farg);\n  lua_Integer w = luaL_optinteger(L, farg + 1, 1);\n  luaL_argcheck(L, 0 <= f, farg, \"field cannot be negative\");\n  luaL_argcheck(L, 0 < w, farg + 1, \"width must be positive\");\n  if (f + w > LUA_NBITS)\n    luaL_error(L, \"trying to access non-existent bits\");\n  *width = (int)w;\n  return (int)f;\n}\n\n\nstatic int b_extract (lua_State *L) {\n  int w;\n  lua_Unsigned r = trim(checkunsigned(L, 1));\n  int f = fieldargs(L, 2, &w);\n  r = (r >> f) & mask(w);\n  pushunsigned(L, r);\n  return 1;\n}\n\n\nstatic int b_replace (lua_State *L) {\n  int w;\n  lua_Unsigned r = trim(checkunsigned(L, 1));\n  lua_Unsigned v = trim(checkunsigned(L, 2));\n  int f = fieldargs(L, 3, &w);\n  lua_Unsigned m = mask(w);\n  r = (r & ~(m << f)) | ((v & m) << f);\n  pushunsigned(L, r);\n  return 1;\n}\n\n\nstatic const luaL_Reg bitlib[] = {\n  {\"arshift\", b_arshift},\n  {\"band\", b_and},\n  {\"bnot\", b_not},\n  {\"bor\", b_or},\n  {\"bxor\", b_xor},\n  {\"btest\", b_test},\n  {\"extract\", b_extract},\n  {\"lrotate\", b_lrot},\n  {\"lshift\", b_lshift},\n  {\"replace\", b_replace},\n  {\"rrotate\", b_rrot},\n  {\"rshift\", b_rshift},\n  {NULL, NULL}\n};\n\n\n\nLUAMOD_API int luaopen_bit32 (lua_State *L) {\n  luaL_newlib(L, bitlib);\n  return 1;\n}\n\n\n#else\t\t\t\t\t/* }{ */\n\n\nLUAMOD_API int luaopen_bit32 (lua_State *L) {\n  return luaL_error(L, \"library 'bit32' has been deprecated\");\n}\n\n#endif\t\t\t\t\t/* } */\n"
  },
  {
    "path": "src/lua/lcode.c",
    "content": "/*\n** $Id: lcode.c,v 2.112.1.1 2017/04/19 17:20:42 roberto Exp $\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 <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/* Maximum number of registers in a Lua function (must fit in 8 bits) */\n#define MAXREGS\t\t255\n\n\n#define hasjumps(e)\t((e)->t != (e)->f)\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** 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  Instruction *previous;\n  int l = from + n - 1;  /* last register to set nil */\n  if (fs->pc > fs->lasttarget) {  /* no jumps to current position? */\n    previous = &fs->f->code[fs->pc-1];\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      }\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_sBx(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 (abs(offset) > MAXARG_sBx)\n    luaX_syntaxerror(fs->ls, \"control structure too long\");\n  SETARG_sBx(*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'). If there are jumps to\n** this position (kept in 'jpc'), link them all together so that\n** 'patchlistaux' will fix all them directly to the final destination.\n*/\nint luaK_jump (FuncState *fs) {\n  int jpc = fs->jpc;  /* save list of jumps to here */\n  int j;\n  fs->jpc = NO_JUMP;  /* no more jumps to here */\n  j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP);\n  luaK_concat(fs, &j, jpc);  /* keep them on hold */\n  return j;\n}\n\n\n/*\n** Code a 'return' instruction\n*/\nvoid luaK_ret (FuncState *fs, int first, int nret) {\n  luaK_codeABC(fs, OP_RETURN, 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) {\n  luaK_codeABC(fs, op, A, B, C);\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_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*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** Ensure all pending jumps to current position are fixed (jumping\n** to current position with no values) and reset list of pending\n** jumps\n*/\nstatic void dischargejpc (FuncState *fs) {\n  patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc);\n  fs->jpc = NO_JUMP;\n}\n\n\n/*\n** Add elements in 'list' to list of pending jumps to \"here\"\n** (current position)\n*/\nvoid luaK_patchtohere (FuncState *fs, int list) {\n  luaK_getlabel(fs);  /* mark \"here\" as a jump target */\n  luaK_concat(fs, &fs->jpc, list);\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  if (target == fs->pc)  /* 'target' is current position? */\n    luaK_patchtohere(fs, list);  /* add list to pending jumps */\n  else {\n    lua_assert(target < fs->pc);\n    patchlistaux(fs, list, target, NO_REG, target);\n  }\n}\n\n\n/*\n** Path all jumps in 'list' to close upvalues up to given 'level'\n** (The assertion checks that jumps either were closing nothing\n** or were closing higher levels, from inner blocks.)\n*/\nvoid luaK_patchclose (FuncState *fs, int list, int level) {\n  level++;  /* argument is +1 to reserve 0 as non-op */\n  for (; list != NO_JUMP; list = getjump(fs, list)) {\n    lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP &&\n                (GETARG_A(fs->f->code[list]) == 0 ||\n                 GETARG_A(fs->f->code[list]) >= level));\n    SETARG_A(fs->f->code[list], level);\n  }\n}\n\n\n/*\n** Emit instruction 'i', checking for array sizes and saving also its\n** line information. Return 'i' position.\n*/\nstatic int luaK_code (FuncState *fs, Instruction i) {\n  Proto *f = fs->f;\n  dischargejpc(fs);  /* 'pc' will change */\n  /* put new instruction in code array */\n  luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,\n                  MAX_INT, \"opcodes\");\n  f->code[fs->pc] = i;\n  /* save corresponding line information */\n  luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int,\n                  MAX_INT, \"opcodes\");\n  f->lineinfo[fs->pc] = fs->ls->lastline;\n  return fs->pc++;\n}\n\n\n/*\n** Format and emit an 'iABC' instruction. (Assertions check consistency\n** of parameters versus opcode.)\n*/\nint luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) {\n  lua_assert(getOpMode(o) == iABC);\n  lua_assert(getBMode(o) != OpArgN || b == 0);\n  lua_assert(getCMode(o) != OpArgN || c == 0);\n  lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C);\n  return luaK_code(fs, CREATE_ABC(o, a, b, c));\n}\n\n\n/*\n** Format and emit an 'iABx' instruction.\n*/\nint luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {\n  lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx);\n  lua_assert(getCMode(o) == OpArgN);\n  lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx);\n  return luaK_code(fs, CREATE_ABx(o, a, bc));\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*/\nint 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    if (newstack >= MAXREGS)\n      luaX_syntaxerror(fs->ls,\n        \"function or expression needs too many 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 += 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 (!ISK(reg) && reg >= fs->nactvar) {\n    fs->freereg--;\n    lua_assert(reg == fs->freereg);\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  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** Add constant 'v' to prototype's list of constants (field 'k').\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 addk (FuncState *fs, TValue *key, TValue *v) {\n  lua_State *L = fs->ls->L;\n  Proto *f = fs->f;\n  TValue *idx = luaH_set(L, fs->ls->h, key);  /* index scanner table */\n  int k, oldsize;\n  if (ttisinteger(idx)) {  /* is there an index there? */\n    k = cast_int(ivalue(idx));\n    /* correct value? (warning: must distinguish floats from integers!) */\n    if (k < fs->nk && ttype(&f->k[k]) == ttype(v) &&\n                      luaV_rawequalobj(&f->k[k], v))\n      return k;  /* reuse index */\n  }\n  /* constant not found; create a new entry */\n  oldsize = f->sizek;\n  k = fs->nk;\n  /* numerical value does not need GC barrier;\n     table has no metatable, so it does not need to invalidate cache */\n  setivalue(idx, k);\n  luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, \"constants\");\n  while (oldsize < f->sizek) 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** Add a string to list of constants and return its index.\n*/\nint luaK_stringK (FuncState *fs, TString *s) {\n  TValue o;\n  setsvalue(fs->ls->L, &o, s);\n  return addk(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** Integers use userdata as keys to avoid collision with floats with\n** same value; conversion to 'void*' is used only for hashing, so there\n** are no \"precision\" problems.\n*/\nint luaK_intK (FuncState *fs, lua_Integer n) {\n  TValue k, o;\n  setpvalue(&k, cast(void*, cast(size_t, n)));\n  setivalue(&o, n);\n  return addk(fs, &k, &o);\n}\n\n/*\n** Add a float to list of constants and return its index.\n*/\nstatic int luaK_numberK (FuncState *fs, lua_Number r) {\n  TValue o;\n  setfltvalue(&o, r);\n  return addk(fs, &o, &o);  /* use number itself as key */\n}\n\n\n/*\n** Add a boolean to list of constants and return its index.\n*/\nstatic int boolK (FuncState *fs, int b) {\n  TValue o;\n  setbvalue(&o, b);\n  return addk(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 to represent nil */\n  sethvalue(fs->ls->L, &k, fs->ls->h);\n  return addk(fs, &k, &v);\n}\n\n\n/*\n** Fix an expression to return the number of results 'nresults'.\n** Either 'e' is a multi-ret expression (function call or vararg)\n** or 'nresults' is LUA_MULTRET (as any expression can satisfy that).\n*/\nvoid luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {\n  if (e->k == VCALL) {  /* expression is an open function call? */\n    SETARG_C(getinstruction(fs, e), nresults + 1);\n  }\n  else if (e->k == VVARARG) {\n    Instruction *pc = &getinstruction(fs, e);\n    SETARG_B(*pc, nresults + 1);\n    SETARG_A(*pc, fs->freereg);\n    luaK_reserveregs(fs, 1);\n  }\n  else lua_assert(nresults == LUA_MULTRET);\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 VRELOCABLE (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_B(getinstruction(fs, e), 2);\n    e->k = VRELOCABLE;  /* can relocate its simple result */\n  }\n}\n\n\n/*\n** Ensure that expression 'e' is not a variable.\n*/\nvoid luaK_dischargevars (FuncState *fs, expdesc *e) {\n  switch (e->k) {\n    case VLOCAL: {  /* already in a register */\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 = VRELOCABLE;\n      break;\n    }\n    case VINDEXED: {\n      OpCode op;\n      freereg(fs, e->u.ind.idx);\n      if (e->u.ind.vt == VLOCAL) {  /* is 't' in a register? */\n        freereg(fs, e->u.ind.t);\n        op = OP_GETTABLE;\n      }\n      else {\n        lua_assert(e->u.ind.vt == VUPVAL);\n        op = OP_GETTABUP;  /* 't' is in an upvalue */\n      }\n      e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx);\n      e->k = VRELOCABLE;\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** Ensures expression value is in register 'reg' (and therefore\n** 'e' will become a non-relocatable expression).\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: case VTRUE: {\n      luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);\n      break;\n    }\n    case VK: {\n      luaK_codek(fs, reg, e->u.info);\n      break;\n    }\n    case VKFLT: {\n      luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval));\n      break;\n    }\n    case VKINT: {\n      luaK_codek(fs, reg, luaK_intK(fs, e->u.ival));\n      break;\n    }\n    case VRELOCABLE: {\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** Ensures expression value is in any register.\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, int b, int jump) {\n  luaK_getlabel(fs);  /* those instructions may be jump targets */\n  return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);\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 (including results from its jump\n** 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, 0, 1);\n      p_t = code_loadbool(fs, reg, 1, 0);\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 (including results from its jump\n** lists) 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 (including results from its jump\n** lists) is in some (any) register 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 >= fs->nactvar) {  /* reg. is not a local? */\n      exp2reg(fs, e, e->u.info);  /* put final result in it */\n      return e->u.info;\n    }\n  }\n  luaK_exp2nextreg(fs, e);  /* otherwise, use next available register */\n  return e->u.info;\n}\n\n\n/*\n** Ensures final expression result is either in a register or in an\n** upvalue.\n*/\nvoid luaK_exp2anyregup (FuncState *fs, expdesc *e) {\n  if (e->k != VUPVAL || hasjumps(e))\n    luaK_exp2anyreg(fs, e);\n}\n\n\n/*\n** Ensures final expression result is either in a register or it is\n** a constant.\n*/\nvoid luaK_exp2val (FuncState *fs, expdesc *e) {\n  if (hasjumps(e))\n    luaK_exp2anyreg(fs, e);\n  else\n    luaK_dischargevars(fs, e);\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 R/K index.\n*/\nint luaK_exp2RK (FuncState *fs, expdesc *e) {\n  luaK_exp2val(fs, e);\n  switch (e->k) {  /* move constants to 'k' */\n    case VTRUE: e->u.info = boolK(fs, 1); goto vk;\n    case VFALSE: e->u.info = boolK(fs, 0); goto vk;\n    case VNIL: e->u.info = nilK(fs); goto vk;\n    case VKINT: e->u.info = luaK_intK(fs, e->u.ival); goto vk;\n    case VKFLT: e->u.info = luaK_numberK(fs, e->u.nval); goto vk;\n    case VK:\n     vk:\n      e->k = VK;\n      if (e->u.info <= MAXINDEXRK)  /* constant fits in 'argC'? */\n        return RKASK(e->u.info);\n      else break;\n    default: break;\n  }\n  /* not a constant in the right range: put it in a register */\n  return luaK_exp2anyreg(fs, e);\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.info);  /* 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 VINDEXED: {\n      OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP;\n      int e = luaK_exp2RK(fs, ex);\n      luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e);\n      break;\n    }\n    default: lua_assert(0);  /* invalid var kind to store */\n  }\n  freeexp(fs, ex);\n}\n\n\n/*\n** Emit SELF instruction (convert expression 'e' into 'e:key(e,').\n*/\nvoid luaK_self (FuncState *fs, expdesc *e, expdesc *key) {\n  int ereg;\n  luaK_exp2anyreg(fs, e);\n  ereg = e->u.info;  /* register where 'e' was placed */\n  freeexp(fs, e);\n  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);  /* function and 'self' produced by op_self */\n  luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key));\n  freeexp(fs, key);\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_A(*pc, !(GETARG_A(*pc)));\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 == VRELOCABLE) {\n    Instruction ie = getinstruction(fs, e);\n    if (GET_OPCODE(ie) == OP_NOT) {\n      fs->pc--;  /* remove previous OP_NOT */\n      return condjump(fs, OP_TEST, GETARG_B(ie), 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, 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 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*/\nvoid 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  luaK_dischargevars(fs, 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 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 VRELOCABLE:\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 = VRELOCABLE;\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** Create expression 't[k]'. 't' must have its final result already in a\n** register or upvalue.\n*/\nvoid luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {\n  lua_assert(!hasjumps(t) && (vkisinreg(t->k) || t->k == VUPVAL));\n  t->u.ind.t = t->u.info;  /* register or upvalue index */\n  t->u.ind.idx = luaK_exp2RK(fs, k);  /* R/K index for key */\n  t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL : VLOCAL;\n  t->k = VINDEXED;\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 (tointeger(v1, &i) && tointeger(v2, &i));\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_arith(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** 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 = VRELOCABLE;  /* 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** Because 'luaK_exp2RK' can free registers, its calls must be\n** in \"stack order\" (that is, first on 'e2', which may have more\n** recent registers to be released).\n*/\nvoid codebinexpval (FuncState *fs, OpCode op,\n                           expdesc *e1, expdesc *e2, int line) {\n  int rk2 = luaK_exp2RK(fs, e2);  /* both operands are \"RK\" */\n  int rk1 = luaK_exp2RK(fs, e1);\n  freeexps(fs, e1, e2);\n  e1->u.info = luaK_codeABC(fs, op, 0, rk1, rk2);  /* generate opcode */\n  e1->k = VRELOCABLE;  /* all those operations are relocatable */\n  luaK_fixline(fs, line);\n}\n\n\n/*\n** Emit code for comparisons.\n** 'e1' was already put in R/K form by 'luaK_infix'.\n*/\nstatic void codecomp (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {\n  int rk1 = (e1->k == VK) ? RKASK(e1->u.info)\n                          : check_exp(e1->k == VNONRELOC, e1->u.info);\n  int rk2 = luaK_exp2RK(fs, e2);\n  freeexps(fs, e1, e2);\n  switch (opr) {\n    case OPR_NE: {  /* '(a ~= b)' ==> 'not (a == b)' */\n      e1->u.info = condjump(fs, OP_EQ, 0, rk1, rk2);\n      break;\n    }\n    case OPR_GT: case OPR_GE: {\n      /* '(a > b)' ==> '(b < a)';  '(a >= b)' ==> '(b <= a)' */\n      OpCode op = cast(OpCode, (opr - OPR_NE) + OP_EQ);\n      e1->u.info = condjump(fs, op, 1, rk2, rk1);  /* invert operands */\n      break;\n    }\n    default: {  /* '==', '<', '<=' use their own opcodes */\n      OpCode op = cast(OpCode, (opr - OPR_EQ) + OP_EQ);\n      e1->u.info = condjump(fs, op, 1, rk1, rk2);\n      break;\n    }\n  }\n  e1->k = VJMP;\n}\n\n\n/*\n** Aplly prefix operation 'op' to expression 'e'.\n*/\nvoid luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {\n  static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP};\n  switch (op) {\n    case OPR_MINUS: case OPR_BNOT:  /* use 'ef' as fake 2nd operand */\n      if (constfolding(fs, op + LUA_OPUNM, e, &ef))\n        break;\n      /* FALLTHROUGH */\n    case OPR_LEN:\n      codeunexpval(fs, cast(OpCode, op + OP_UNM), 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  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_exp2RK(fs, v);\n      /* else keep numeral, which may be folded with 2nd operand */\n      break;\n    }\n    default: {\n      luaK_exp2RK(fs, v);\n      break;\n    }\n  }\n}\n\n\n/*\n** Finalize code for binary operation, after reading 2nd operand.\n** For '(a .. b .. c)' (which is '(a .. (b .. c))', because\n** concatenation is right associative), merge second CONCAT into first\n** one.\n*/\nvoid luaK_posfix (FuncState *fs, BinOpr op,\n                  expdesc *e1, expdesc *e2, int line) {\n  switch (op) {\n    case OPR_AND: {\n      lua_assert(e1->t == NO_JUMP);  /* list closed by 'luK_infix' */\n      luaK_dischargevars(fs, e2);\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 'luK_infix' */\n      luaK_dischargevars(fs, e2);\n      luaK_concat(fs, &e2->t, e1->t);\n      *e1 = *e2;\n      break;\n    }\n    case OPR_CONCAT: {\n      luaK_exp2val(fs, e2);\n      if (e2->k == VRELOCABLE &&\n          GET_OPCODE(getinstruction(fs, e2)) == OP_CONCAT) {\n        lua_assert(e1->u.info == GETARG_B(getinstruction(fs, e2))-1);\n        freeexp(fs, e1);\n        SETARG_B(getinstruction(fs, e2), e1->u.info);\n        e1->k = VRELOCABLE; e1->u.info = e2->u.info;\n      }\n      else {\n        luaK_exp2nextreg(fs, e2);  /* operand must be on the 'stack' */\n        codebinexpval(fs, OP_CONCAT, e1, e2, line);\n      }\n      break;\n    }\n    case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:\n    case OPR_IDIV: 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 (!constfolding(fs, op + LUA_OPADD, e1, e2))\n        codebinexpval(fs, cast(OpCode, op + OP_ADD), e1, e2, line);\n      break;\n    }\n    case OPR_EQ: case OPR_LT: case OPR_LE:\n    case OPR_NE: case OPR_GT: case OPR_GE: {\n      codecomp(fs, op, e1, e2);\n      break;\n    }\n    default: lua_assert(0);\n  }\n}\n\n\n/*\n** Change line information associated with current position.\n*/\nvoid luaK_fixline (FuncState *fs, int line) {\n  fs->f->lineinfo[fs->pc - 1] = line;\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  int c =  (nelems - 1)/LFIELDS_PER_FLUSH + 1;\n  int b = (tostore == LUA_MULTRET) ? 0 : tostore;\n  lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH);\n  if (c <= MAXARG_C)\n    luaK_codeABC(fs, OP_SETLIST, base, b, c);\n  else if (c <= MAXARG_Ax) {\n    luaK_codeABC(fs, OP_SETLIST, base, b, 0);\n    codeextraarg(fs, c);\n  }\n  else\n    luaX_syntaxerror(fs->ls, \"constructor too long\");\n  fs->freereg = base + 1;  /* free registers with list values */\n}\n\n"
  },
  {
    "path": "src/lua/lcode.h",
    "content": "/*\n** $Id: lcode.h,v 1.64.1.1 2017/04/19 17:20:42 roberto Exp $\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  OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW,\n  OPR_DIV,\n  OPR_IDIV,\n  OPR_BAND, OPR_BOR, OPR_BXOR,\n  OPR_SHL, OPR_SHR,\n  OPR_CONCAT,\n  OPR_EQ, OPR_LT, OPR_LE,\n  OPR_NE, OPR_GT, OPR_GE,\n  OPR_AND, OPR_OR,\n  OPR_NOBINOPR\n} BinOpr;\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#define luaK_codeAsBx(fs,o,A,sBx)\tluaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx)\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_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);\nLUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C);\nLUAI_FUNC int luaK_codek (FuncState *fs, int reg, int k);\nLUAI_FUNC void luaK_fixline (FuncState *fs, int line);\nLUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);\nLUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);\nLUAI_FUNC void luaK_checkstack (FuncState *fs, int n);\nLUAI_FUNC int luaK_stringK (FuncState *fs, TString *s);\nLUAI_FUNC int luaK_intK (FuncState *fs, lua_Integer n);\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 int luaK_exp2RK (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_goiffalse (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_patchclose (FuncState *fs, int list, int level);\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_setlist (FuncState *fs, int base, int nelems, int tostore);\n\nLUAI_FUNC void codebinexpval(FuncState *fs, OpCode op, expdesc *e1, expdesc *e2, int line);\n\n\n#endif\n"
  },
  {
    "path": "src/lua/lcorolib.c",
    "content": "/*\n** $Id: lcorolib.c,v 1.10.1.1 2017/04/19 17:20:42 roberto Exp $\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\n\nstatic lua_State *getco (lua_State *L) {\n  lua_State *co = lua_tothread(L, 1);\n  luaL_argcheck(L, co, 1, \"thread expected\");\n  return co;\n}\n\n\nstatic int auxresume (lua_State *L, lua_State *co, int narg) {\n  int status;\n  if (!lua_checkstack(co, narg)) {\n    lua_pushliteral(L, \"too many arguments to resume\");\n    return -1;  /* error flag */\n  }\n  if (lua_status(co) == LUA_OK && lua_gettop(co) == 0) {\n    lua_pushliteral(L, \"cannot resume dead coroutine\");\n    return -1;  /* error flag */\n  }\n  lua_xmove(L, co, narg);\n  status = lua_resume(co, L, narg);\n  if (status == LUA_OK || status == LUA_YIELD) {\n    int nres = lua_gettop(co);\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\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 (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 (r < 0) {\n    if (lua_type(L, -1) == LUA_TSTRING) {  /* error object is a string? */\n      luaL_where(L, 1);  /* add extra info */\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\nstatic int luaB_costatus (lua_State *L) {\n  lua_State *co = getco(L);\n  if (L == co) lua_pushliteral(L, \"running\");\n  else {\n    switch (lua_status(co)) {\n      case LUA_YIELD:\n        lua_pushliteral(L, \"suspended\");\n        break;\n      case LUA_OK: {\n        lua_Debug ar;\n        if (lua_getstack(co, 0, &ar) > 0)  /* does it have frames? */\n          lua_pushliteral(L, \"normal\");  /* it is running */\n        else if (lua_gettop(co) == 0)\n            lua_pushliteral(L, \"dead\");\n        else\n          lua_pushliteral(L, \"suspended\");  /* initial state */\n        break;\n      }\n      default:  /* some error occurred */\n        lua_pushliteral(L, \"dead\");\n        break;\n    }\n  }\n  return 1;\n}\n\n\nstatic int luaB_yieldable (lua_State *L) {\n  lua_pushboolean(L, lua_isyieldable(L));\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 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  {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": "src/lua/lctype.c",
    "content": "/*\n** $Id: lctype.c,v 1.12.1.1 2017/04/19 17:20:42 roberto Exp $\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\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  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\t/* 8. */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\t/* 9. */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\t/* a. */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\t/* b. */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\t/* c. */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\t/* d. */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\t/* e. */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\t/* f. */\n  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,\n};\n\n#endif\t\t\t/* } */\n"
  },
  {
    "path": "src/lua/lctype.h",
    "content": "/*\n** $Id: lctype.h,v 1.12.1.1 2013/04/12 18:48:47 roberto Exp $\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** this 'ltolower' only works for alphabetic characters\n*/\n#define ltolower(c)\t((c) | ('A' ^ 'a'))\n\n\n/* two more entries for 0 and -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": "src/lua/ldblib.c",
    "content": "/*\n** $Id: ldblib.c,v 1.151.1.1 2017/04/19 17:20:42 roberto Exp $\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\n\n/*\n** The hook table at registry[&HOOKKEY] maps threads to their current\n** hook function. (We only need the unique address of 'HOOKKEY'.)\n*/\nstatic const int HOOKKEY = 0;\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 != 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_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,\n                    \"nil or table expected\");\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  if (lua_type(L, 1) != LUA_TUSERDATA)\n    lua_pushnil(L);\n  else\n    lua_getuservalue(L, 1);\n  return 1;\n}\n\n\nstatic int db_setuservalue (lua_State *L) {\n  luaL_checktype(L, 1, LUA_TUSERDATA);\n  luaL_checkany(L, 2);\n  lua_settop(L, 2);\n  lua_setuservalue(L, 1);\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, \"flnStu\");\n  checkstack(L, L1, 3);\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      lua_pushnil(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    settabss(L, \"source\", ar.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, 't'))\n    settabsb(L, \"istailcall\", ar.istailcall);\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  lua_Debug ar;\n  const char *name;\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    int level = (int)luaL_checkinteger(L, arg + 1);\n    if (!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      lua_pushnil(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 (!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 int checkupval (lua_State *L, int argf, int argnup) {\n  int nup = (int)luaL_checkinteger(L, argnup);  /* upvalue index */\n  luaL_checktype(L, argf, LUA_TFUNCTION);  /* closure */\n  luaL_argcheck(L, (lua_getupvalue(L, argf, nup) != NULL), argnup,\n                   \"invalid upvalue index\");\n  return nup;\n}\n\n\nstatic int db_upvalueid (lua_State *L) {\n  int n = checkupval(L, 1, 2);\n  lua_pushlightuserdata(L, lua_upvalueid(L, 1, n));\n  return 1;\n}\n\n\nstatic int db_upvaluejoin (lua_State *L) {\n  int n1 = checkupval(L, 1, 2);\n  int n2 = checkupval(L, 3, 4);\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_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_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 (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  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    lua_pushnil(L);\n  else if (hook != hookf)  /* external hook? */\n    lua_pushliteral(L, \"external hook\");\n  else {  /* hook table must exist */\n    lua_rawgetp(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) == 0 ||\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\", lua_tostring(L, -1));\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": "src/lua/ldebug.c",
    "content": "/*\n** $Id: ldebug.c,v 2.121.1.2 2017/07/10 17:21:50 roberto Exp $\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 noLuaClosure(f)\t\t((f) == NULL || (f)->c.tt == LUA_TCCL)\n\n\n/* Active Lua function (given call info) */\n#define ci_func(ci)\t\t(clLvalue((ci)->func))\n\n\nstatic const char *funcnamefromcode (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\nstatic int currentline (CallInfo *ci) {\n  return getfuncline(ci_func(ci)->p, currentpc(ci));\n}\n\n\n/*\n** If function yielded, its 'func' can be in the 'extra' field. The\n** next function restores 'func' to its correct value for debugging\n** purposes. (It exchanges 'func' and 'extra'; so, when called again,\n** after debugging, it also \"re-restores\" ** 'func' to its altered value.\n*/\nstatic void swapextra (lua_State *L) {\n  if (L->status == LUA_YIELD) {\n    CallInfo *ci = L->ci;  /* get function that yielded */\n    StkId temp = ci->func;  /* exchange its 'func' and 'extra' values */\n    ci->func = restorestack(L, ci->extra);\n    ci->extra = savestack(L, temp);\n  }\n}\n\n\n/*\n** This function can be called asynchronously (e.g. during a signal).\n** Fields 'oldpc', 'basehookcount', and 'hookcount' (set by\n** 'resethookcount') are for debug only, and it is no problem if they\n** get arbitrary values (causes at most one wrong hook call). 'hookmask'\n** is an atomic value. We assume that pointers are atomic too (e.g., gcc\n** ensures that for all platforms where it runs). Moreover, 'hook' is\n** always checked 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  if (isLua(L->ci))\n    L->oldpc = L->ci->u.l.savedpc;\n  L->hook = func;\n  L->basehookcount = count;\n  resethookcount(L);\n  L->hookmask = cast_byte(mask);\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 (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  int nparams = clLvalue(ci->func)->p->numparams;\n  if (n >= cast_int(ci->u.l.base - ci->func) - nparams)\n    return NULL;  /* no such vararg */\n  else {\n    *pos = ci->func + nparams + n;\n    return \"(*vararg)\";  /* generic name for any vararg */\n  }\n}\n\n\nstatic const char *findlocal (lua_State *L, CallInfo *ci, int n,\n                              StkId *pos) {\n  const char *name = NULL;\n  StkId base;\n  if (isLua(ci)) {\n    if (n < 0)  /* access to vararg values? */\n      return findvararg(ci, -n, pos);\n    else {\n      base = ci->u.l.base;\n      name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));\n    }\n  }\n  else\n    base = ci->func + 1;\n  if (name == NULL) {  /* no 'standard' name? */\n    StkId limit = (ci == L->ci) ? L->top : ci->next->func;\n    if (limit - base >= n && n > 0)  /* is 'n' inside 'ci' stack? */\n      name = \"(*temporary)\";  /* generic name for any valid slot */\n    else\n      return NULL;  /* no name */\n  }\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  swapextra(L);\n  if (ar == NULL) {  /* information about non-active function? */\n    if (!isLfunction(L->top - 1))  /* not a Lua function? */\n      name = NULL;\n    else  /* consider live variables at function start (parameters) */\n      name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0);\n  }\n  else {  /* active function; get information through 'ar' */\n    StkId pos = NULL;  /* to avoid warnings */\n    name = findlocal(L, ar->i_ci, n, &pos);\n    if (name) {\n      setobj2s(L, L->top, pos);\n      api_incr_top(L);\n    }\n  }\n  swapextra(L);\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  swapextra(L);\n  name = findlocal(L, ar->i_ci, n, &pos);\n  if (name) {\n    setobjs2s(L, pos, L->top - 1);\n    L->top--;  /* pop value */\n  }\n  swapextra(L);\n  lua_unlock(L);\n  return name;\n}\n\n\nstatic void funcinfo (lua_Debug *ar, Closure *cl) {\n  if (noLuaClosure(cl)) {\n    ar->source = \"=[C]\";\n    ar->linedefined = -1;\n    ar->lastlinedefined = -1;\n    ar->what = \"C\";\n  }\n  else {\n    Proto *p = cl->l.p;\n    ar->source = p->source ? getstr(p->source) : \"=?\";\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, LUA_IDSIZE);\n}\n\n\nstatic void collectvalidlines (lua_State *L, Closure *f) {\n  if (noLuaClosure(f)) {\n    setnilvalue(L->top);\n    api_incr_top(L);\n  }\n  else {\n    int i;\n    TValue v;\n    int *lineinfo = f->l.p->lineinfo;\n    Table *t = luaH_new(L);  /* new table to store active lines */\n    sethvalue(L, L->top, t);  /* push it on stack */\n    api_incr_top(L);\n    setbvalue(&v, 1);  /* boolean 'true' to be the value of all indices */\n    for (i = 0; i < f->l.p->sizelineinfo; i++)  /* for all lines with code */\n      luaH_setint(L, t, lineinfo[i], &v);  /* table[line] = true */\n  }\n}\n\n\nstatic const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {\n  if (ci == NULL)  /* no 'ci'? */\n    return NULL;  /* no info */\n  else if (ci->callstatus & CIST_FIN) {  /* is this a finalizer? */\n    *name = \"__gc\";\n    return \"metamethod\";  /* report it as such */\n  }\n  /* calling function is a known Lua function? */\n  else if (!(ci->callstatus & CIST_TAIL) && isLua(ci->previous))\n    return funcnamefromcode(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)) ? currentline(ci) : -1;\n        break;\n      }\n      case 'u': {\n        ar->nups = (f == NULL) ? 0 : f->c.nupvalues;\n        if (noLuaClosure(f)) {\n          ar->isvararg = 1;\n          ar->nparams = 0;\n        }\n        else {\n          ar->isvararg = f->l.p->is_vararg;\n          ar->nparams = f->l.p->numparams;\n        }\n        break;\n      }\n      case 't': {\n        ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0;\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 '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  StkId func;\n  lua_lock(L);\n  swapextra(L);\n  if (*what == '>') {\n    ci = NULL;\n    func = L->top - 1;\n    api_check(L, ttisfunction(func), \"function expected\");\n    what++;  /* skip the '>' */\n    L->top--;  /* pop function */\n  }\n  else {\n    ci = ar->i_ci;\n    func = ci->func;\n    lua_assert(ttisfunction(ci->func));\n  }\n  cl = ttisclosure(func) ? clvalue(func) : NULL;\n  status = auxgetinfo(L, what, ar, cl, ci);\n  if (strchr(what, 'f')) {\n    setobjs2s(L, L->top, func);\n    api_incr_top(L);\n  }\n  swapextra(L);  /* correct before option 'L', which can raise a mem. error */\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\nstatic const char *getobjname (Proto *p, int lastpc, int reg,\n                               const char **name);\n\n\n/*\n** find a \"name\" for the RK value 'c'\n*/\nstatic void kname (Proto *p, int pc, int c, const char **name) {\n  if (ISK(c)) {  /* is 'c' a constant? */\n    TValue *kvalue = &p->k[INDEXK(c)];\n    if (ttisstring(kvalue)) {  /* literal constant? */\n      *name = svalue(kvalue);  /* it is its own name */\n      return;\n    }\n    /* else no reasonable name found */\n  }\n  else {  /* 'c' is a register */\n    const char *what = getobjname(p, pc, c, name); /* search for 'c' */\n    if (what && *what == 'c') {  /* found a constant name? */\n      return;  /* 'name' already filled */\n    }\n    /* else no reasonable name found */\n  }\n  *name = \"?\";  /* no reasonable name found */\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 (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  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    switch (op) {\n      case OP_LOADNIL: {\n        int b = GETARG_B(i);\n        if (a <= reg && reg <= a + b)  /* set registers from 'a' to 'a+b' */\n          setreg = filterpc(pc, jmptarget);\n        break;\n      }\n      case OP_TFORCALL: {\n        if (reg >= a + 2)  /* affect all regs above its base */\n          setreg = filterpc(pc, jmptarget);\n        break;\n      }\n      case OP_CALL:\n      case OP_TAILCALL: {\n        if (reg >= a)  /* affect all registers above base */\n          setreg = filterpc(pc, jmptarget);\n        break;\n      }\n      case OP_JMP: {\n        int b = GETARG_sBx(i);\n        int dest = pc + 1 + b;\n        /* jump is forward and do not skip 'lastpc'? */\n        if (pc < dest && dest <= lastpc) {\n          if (dest > jmptarget)\n            jmptarget = dest;  /* update 'jmptarget' */\n        }\n        break;\n      }\n      default:\n        if (testAMode(op) && reg == a)  /* any instruction that set A */\n          setreg = filterpc(pc, jmptarget);\n        break;\n    }\n  }\n  return setreg;\n}\n\n\nstatic const char *getobjname (Proto *p, int lastpc, int reg,\n                               const char **name) {\n  int pc;\n  *name = luaF_getlocalname(p, reg + 1, lastpc);\n  if (*name)  /* is a local? */\n    return \"local\";\n  /* else try symbolic execution */\n  pc = findsetreg(p, lastpc, 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 getobjname(p, pc, b, name);  /* get name for 'b' */\n        break;\n      }\n      case OP_GETTABUP:\n      case OP_GETTABLE: {\n        int k = GETARG_C(i);  /* key index */\n        int t = GETARG_B(i);  /* table index */\n        const char *vn = (op == OP_GETTABLE)  /* name of indexed variable */\n                         ? luaF_getlocalname(p, t + 1, pc)\n                         : upvalname(p, t);\n        kname(p, pc, k, name);\n        return (vn && strcmp(vn, LUA_ENV) == 0) ? \"global\" : \"field\";\n      }\n      case OP_GETUPVAL: {\n        *name = upvalname(p, GETARG_B(i));\n        return \"upvalue\";\n      }\n      case OP_LOADK:\n      case OP_LOADKX: {\n        int b = (op == OP_LOADK) ? GETARG_Bx(i)\n                                 : GETARG_Ax(p->code[pc + 1]);\n        if (ttisstring(&p->k[b])) {\n          *name = svalue(&p->k[b]);\n          return \"constant\";\n        }\n        break;\n      }\n      case OP_SELF: {\n        int k = GETARG_C(i);  /* key index */\n        kname(p, pc, 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, CallInfo *ci,\n                                     const char **name) {\n  TMS tm = (TMS)0;  /* (initial value avoids warnings) */\n  Proto *p = ci_func(ci)->p;  /* calling function */\n  int pc = currentpc(ci);  /* calling instruction index */\n  Instruction i = p->code[pc];  /* calling instruction */\n  if (ci->callstatus & CIST_HOOKED) {  /* was it called inside a hook? */\n    *name = \"?\";\n    return \"hook\";\n  }\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      tm = TM_INDEX;\n      break;\n    case OP_SETTABUP: case OP_SETTABLE:\n      tm = TM_NEWINDEX;\n      break;\n    case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD:\n    case OP_POW: case OP_DIV: case OP_IDIV: case OP_BAND:\n    case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: {\n      int offset = cast_int(GET_OPCODE(i)) - cast_int(OP_ADD);  /* ORDER OP */\n      tm = cast(TMS, offset + cast_int(TM_ADD));  /* ORDER TM */\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    case OP_LT: tm = TM_LT; break;\n    case OP_LE: tm = TM_LE; break;\n    default:\n      return NULL;  /* cannot find a reasonable name */\n  }\n  *name = getstr(G(L)->tmname[tm]);\n  return \"metamethod\";\n}\n\n/* }====================================================== */\n\n\n\n/*\n** The subtraction of two potentially unrelated pointers is\n** not ISO C, but it should not crash a program; the subsequent\n** checks are ISO C and ensure a correct result.\n*/\nstatic int isinstack (CallInfo *ci, const TValue *o) {\n  ptrdiff_t i = o - ci->u.l.base;\n  return (0 <= i && i < (ci->top - ci->u.l.base) && ci->u.l.base + i == o);\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 == o) {\n      *name = upvalname(c->p, i);\n      return \"upvalue\";\n    }\n  }\n  return NULL;\n}\n\n\nstatic const char *varinfo (lua_State *L, const TValue *o) {\n  const char *name = NULL;  /* to avoid warnings */\n  CallInfo *ci = L->ci;\n  const char *kind = NULL;\n  if (isLua(ci)) {\n    kind = getupvalname(ci, o, &name);  /* check whether 'o' is an upvalue */\n    if (!kind && isinstack(ci, o))  /* no? try a register */\n      kind = getobjname(ci_func(ci)->p, currentpc(ci),\n                        cast_int(o - ci->u.l.base), &name);\n  }\n  return (kind) ? luaO_pushfstring(L, \" (%s '%s')\", kind, name) : \"\";\n}\n\n\nl_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {\n  const char *t = luaT_objtypename(L, o);\n  luaG_runerror(L, \"attempt to %s a %s value%s\", op, t, varinfo(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  lua_Number temp;\n  if (!tonumber(p1, &temp))  /* 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 (!tointeger(p1, &temp))\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\n/* add src:line information to 'msg' */\nconst char *luaG_addinfo (lua_State *L, const char *msg, TString *src,\n                                        int line) {\n  char buff[LUA_IDSIZE];\n  if (src)\n    luaO_chunkid(buff, getstr(src), LUA_IDSIZE);\n  else {  /* no source available; use \"?\" instead */\n    buff[0] = '?'; buff[1] = '\\0';\n  }\n  return luaO_pushfstring(L, \"%s:%d: %s\", buff, line, msg);\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    setobjs2s(L, L->top, L->top - 1);  /* move argument */\n    setobjs2s(L, L->top - 1, errfunc);  /* push function */\n    L->top++;  /* assume EXTRA_STACK */\n    luaD_callnoyield(L, L->top - 2, 1);  /* call it */\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  va_start(argp, fmt);\n  msg = luaO_pushvfstring(L, fmt, argp);  /* format message */\n  va_end(argp);\n  if (isLua(ci))  /* if Lua function, add source:line information */\n    luaG_addinfo(L, msg, ci_func(ci)->p->source, currentline(ci));\n  luaG_errormsg(L);\n}\n\n\nvoid luaG_traceexec (lua_State *L) {\n  CallInfo *ci = L->ci;\n  lu_byte mask = L->hookmask;\n  int counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT));\n  if (counthook)\n    resethookcount(L);  /* reset count */\n  else if (!(mask & LUA_MASKLINE))\n    return;  /* no line hook and count != 0; nothing to be done */\n  if (ci->callstatus & CIST_HOOKYIELD) {  /* called hook last time? */\n    ci->callstatus &= ~CIST_HOOKYIELD;  /* erase mark */\n    return;  /* do not call hook again (VM yielded, so it did not move) */\n  }\n  if (counthook)\n    luaD_hook(L, LUA_HOOKCOUNT, -1);  /* call count hook */\n  if (mask & LUA_MASKLINE) {\n    Proto *p = ci_func(ci)->p;\n    int npc = pcRel(ci->u.l.savedpc, p);\n    int newline = getfuncline(p, npc);\n    if (npc == 0 ||  /* call linehook when enter a new function, */\n        ci->u.l.savedpc <= L->oldpc ||  /* when jump back (loop), or when */\n        newline != getfuncline(p, pcRel(L->oldpc, p)))  /* enter a new line */\n      luaD_hook(L, LUA_HOOKLINE, newline);  /* call line hook */\n  }\n  L->oldpc = ci->u.l.savedpc;\n  if (L->status == LUA_YIELD) {  /* did hook yield? */\n    if (counthook)\n      L->hookcount = 1;  /* undo decrement to zero */\n    ci->u.l.savedpc--;  /* undo increment (resume will increment it again) */\n    ci->callstatus |= CIST_HOOKYIELD;  /* mark that it yielded */\n    ci->func = L->top - 1;  /* protect stack below results */\n    luaD_throw(L, LUA_YIELD);\n  }\n}\n\n"
  },
  {
    "path": "src/lua/ldebug.h",
    "content": "/*\n** $Id: ldebug.h,v 2.14.1.1 2017/04/19 17:20:42 roberto Exp $\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#define getfuncline(f,pc)\t(((f)->lineinfo) ? (f)->lineinfo[pc] : -1)\n\n#define resethookcount(L)\t(L->hookcount = L->basehookcount)\n\n\nLUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o,\n                                                const char *opname);\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_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 void luaG_traceexec (lua_State *L);\n\n\n#endif\n"
  },
  {
    "path": "src/lua/ldo.c",
    "content": "/*\n** $Id: ldo.c,v 2.157.1.1 2017/04/19 17:20:42 roberto Exp $\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** {======================================================\n** Error-recovery functions\n** =======================================================\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 asked to use them, 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#define LUAI_TRY(L,c,a) \\\n\ttry { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }\n#define luai_jmpbuf\t\tint  /* dummy variable */\n\n#elif defined(LUA_USE_POSIX)\t\t\t\t/* }{ */\n\n/* in POSIX, try _longjmp/_setjmp (more efficient) */\n#define LUAI_THROW(L,c)\t\t_longjmp((c)->b, 1)\n#define LUAI_TRY(L,c,a)\t\tif (_setjmp((c)->b) == 0) { a }\n#define luai_jmpbuf\t\tjmp_buf\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,a)\t\tif (setjmp((c)->b) == 0) { a }\n#define luai_jmpbuf\t\tjmp_buf\n\n#endif\t\t\t\t\t\t\t/* } */\n\n#endif\t\t\t\t\t\t\t/* } */\n\n\n\n/* chain list of long jump buffers */\nstruct lua_longjmp {\n  struct lua_longjmp *previous;\n  luai_jmpbuf b;\n  volatile int status;  /* error code */\n};\n\n\nstatic void seterrorobj (lua_State *L, int errcode, StkId oldtop) {\n  switch (errcode) {\n    case LUA_ERRMEM: {  /* memory error? */\n      setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */\n      break;\n    }\n    case LUA_ERRERR: {\n      setsvalue2s(L, oldtop, luaS_newliteral(L, \"error in error handling\"));\n      break;\n    }\n    default: {\n      setobjs2s(L, oldtop, L->top - 1);  /* error message on current top */\n      break;\n    }\n  }\n  L->top = oldtop + 1;\n}\n\n\nl_noret luaD_throw (lua_State *L, int 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    L->status = cast_byte(errcode);  /* mark it as dead */\n    if (g->mainthread->errorJmp) {  /* main thread has a handler? */\n      setobjs2s(L, g->mainthread->top++, L->top - 1);  /* copy error obj. */\n      luaD_throw(g->mainthread, errcode);  /* re-throw in main thread */\n    }\n    else {  /* no handler at all; abort */\n      if (g->panic) {  /* panic function? */\n        seterrorobj(L, errcode, L->top);  /* assume EXTRA_STACK */\n        if (L->ci->top < L->top)\n          L->ci->top = L->top;  /* pushing msg. can break this invariant */\n        lua_unlock(L);\n        g->panic(L);  /* call panic function (last chance to jump out) */\n      }\n      abort();\n    }\n  }\n}\n\n\nint luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {\n  unsigned short oldnCcalls = L->nCcalls;\n  struct 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,\n    (*f)(L, ud);\n  );\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*/\nstatic void correctstack (lua_State *L, TValue *oldstack) {\n  CallInfo *ci;\n  UpVal *up;\n  L->top = (L->top - oldstack) + L->stack;\n  for (up = L->openupval; up != NULL; up = up->u.open.next)\n    up->v = (up->v - oldstack) + L->stack;\n  for (ci = L->ci; ci != NULL; ci = ci->previous) {\n    ci->top = (ci->top - oldstack) + L->stack;\n    ci->func = (ci->func - oldstack) + L->stack;\n    if (isLua(ci))\n      ci->u.l.base = (ci->u.l.base - oldstack) + L->stack;\n  }\n}\n\n\n/* some space for error handling */\n#define ERRORSTACKSIZE\t(LUAI_MAXSTACK + 200)\n\n\nvoid luaD_reallocstack (lua_State *L, int newsize) {\n  TValue *oldstack = L->stack;\n  int lim = L->stacksize;\n  lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);\n  lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);\n  luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue);\n  for (; lim < newsize; lim++)\n    setnilvalue(L->stack + lim); /* erase new segment */\n  L->stacksize = newsize;\n  L->stack_last = L->stack + newsize - EXTRA_STACK;\n  correctstack(L, oldstack);\n}\n\n\nvoid luaD_growstack (lua_State *L, int n) {\n  int size = L->stacksize;\n  if (size > LUAI_MAXSTACK)  /* error after extra size? */\n    luaD_throw(L, LUA_ERRERR);\n  else {\n    int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;\n    int newsize = 2 * size;\n    if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK;\n    if (newsize < needed) newsize = needed;\n    if (newsize > LUAI_MAXSTACK) {  /* stack overflow? */\n      luaD_reallocstack(L, ERRORSTACKSIZE);\n      luaG_runerror(L, \"stack overflow\");\n    }\n    else\n      luaD_reallocstack(L, newsize);\n  }\n}\n\n\nstatic int stackinuse (lua_State *L) {\n  CallInfo *ci;\n  StkId lim = L->top;\n  for (ci = L->ci; ci != NULL; ci = ci->previous) {\n    if (lim < ci->top) lim = ci->top;\n  }\n  lua_assert(lim <= L->stack_last);\n  return cast_int(lim - L->stack) + 1;  /* part of stack in use */\n}\n\n\nvoid luaD_shrinkstack (lua_State *L) {\n  int inuse = stackinuse(L);\n  int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;\n  if (goodsize > LUAI_MAXSTACK)\n    goodsize = LUAI_MAXSTACK;  /* respect stack limit */\n  if (L->stacksize > LUAI_MAXSTACK)  /* had been handling stack overflow? */\n    luaE_freeCI(L);  /* free all CIs (list grew because of an error) */\n  else\n    luaE_shrinkCI(L);  /* shrink list */\n  /* if thread is currently not handling a stack overflow and its\n     good size is smaller than current size, shrink its stack */\n  if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) &&\n      goodsize < L->stacksize)\n    luaD_reallocstack(L, goodsize);\n  else  /* don't change stack */\n    condmovestack(L,{},{});  /* (change only for debugging) */\n}\n\n\nvoid luaD_inctop (lua_State *L) {\n  luaD_checkstack(L, 1);\n  L->top++;\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 triggers this\n** function, can be changed asynchronously by signals.)\n*/\nvoid luaD_hook (lua_State *L, int event, int line) {\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);\n    ptrdiff_t ci_top = savestack(L, ci->top);\n    lua_Debug ar;\n    ar.event = event;\n    ar.currentline = line;\n    ar.i_ci = ci;\n    luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */\n    ci->top = L->top + LUA_MINSTACK;\n    lua_assert(ci->top <= L->stack_last);\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 = restorestack(L, ci_top);\n    L->top = restorestack(L, top);\n    ci->callstatus &= ~CIST_HOOKED;\n  }\n}\n\n\nstatic void callhook (lua_State *L, CallInfo *ci) {\n  int hook = LUA_HOOKCALL;\n  ci->u.l.savedpc++;  /* hooks assume 'pc' is already incremented */\n  if (isLua(ci->previous) &&\n      GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) {\n    ci->callstatus |= CIST_TAIL;\n    hook = LUA_HOOKTAILCALL;\n  }\n  luaD_hook(L, hook, -1);\n  ci->u.l.savedpc--;  /* correct 'pc' */\n}\n\n\nstatic StkId adjust_varargs (lua_State *L, Proto *p, int actual) {\n  int i;\n  int nfixargs = p->numparams;\n  StkId base, fixed;\n  /* move fixed parameters to final position */\n  fixed = L->top - actual;  /* first fixed argument */\n  base = L->top;  /* final position of first argument */\n  for (i = 0; i < nfixargs && i < actual; i++) {\n    setobjs2s(L, L->top++, fixed + i);\n    setnilvalue(fixed + i);  /* erase original copy (for GC) */\n  }\n  for (; i < nfixargs; i++)\n    setnilvalue(L->top++);  /* complete missing arguments */\n  return base;\n}\n\n\n/*\n** Check whether __call metafield of 'func' is a function. If so, put\n** it in stack below original 'func' so that 'luaD_precall' can call\n** it. Raise an error if __call metafield is not a function.\n*/\nstatic void tryfuncTM (lua_State *L, StkId func) {\n  const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);\n  StkId p;\n  if (!ttisfunction(tm))\n    luaG_typeerror(L, func, \"call\");\n  /* Open a hole inside the stack at 'func' */\n  for (p = L->top; p > func; p--)\n    setobjs2s(L, p, p-1);\n  L->top++;  /* slot ensured by caller */\n  setobj2s(L, func, tm);  /* tag method is the new function to be called */\n}\n\n\n/*\n** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.\n** Handle most typical cases (zero results for commands, one result for\n** expressions, multiple results for tail calls/single parameters)\n** separated.\n*/\nstatic int moveresults (lua_State *L, const TValue *firstResult, StkId res,\n                                      int nres, int wanted) {\n  switch (wanted) {  /* handle typical cases separately */\n    case 0: break;  /* nothing to move */\n    case 1: {  /* one result needed */\n      if (nres == 0)   /* no results? */\n        firstResult = luaO_nilobject;  /* adjust with nil */\n      setobjs2s(L, res, firstResult);  /* move it to proper place */\n      break;\n    }\n    case LUA_MULTRET: {\n      int i;\n      for (i = 0; i < nres; i++)  /* move all results to correct place */\n        setobjs2s(L, res + i, firstResult + i);\n      L->top = res + nres;\n      return 0;  /* wanted == LUA_MULTRET */\n    }\n    default: {\n      int i;\n      if (wanted <= nres) {  /* enough results? */\n        for (i = 0; i < wanted; i++)  /* move wanted results to correct place */\n          setobjs2s(L, res + i, firstResult + i);\n      }\n      else {  /* not enough results; use all of them plus nils */\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(res + i);\n      }\n      break;\n    }\n  }\n  L->top = res + wanted;  /* top points after the last result */\n  return 1;\n}\n\n\n/*\n** Finishes a function call: calls hook if necessary, removes CallInfo,\n** moves current number of results to proper place; returns 0 iff call\n** wanted multiple (variable number of) results.\n*/\nint luaD_poscall (lua_State *L, CallInfo *ci, StkId firstResult, int nres) {\n  StkId res;\n  int wanted = ci->nresults;\n  if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) {\n    if (L->hookmask & LUA_MASKRET) {\n      ptrdiff_t fr = savestack(L, firstResult);  /* hook may change stack */\n      luaD_hook(L, LUA_HOOKRET, -1);\n      firstResult = restorestack(L, fr);\n    }\n    L->oldpc = ci->previous->u.l.savedpc;  /* 'oldpc' for caller function */\n  }\n  res = ci->func;  /* res == final position of 1st result */\n  L->ci = ci->previous;  /* back to caller */\n  /* move results to proper place */\n  return moveresults(L, firstResult, res, nres, wanted);\n}\n\n\n\n#define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L)))\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    luaC_checkGC(L),  /* stack grow uses memory */ \\\n    p = restorestack(L, t__))  /* 'pos' part: restore 'p' */\n\n\n/*\n** Prepares a function call: checks the stack, creates a new CallInfo\n** entry, fills in the relevant information, calls hook if needed.\n** If function is a C function, does the call, too. (Otherwise, leave\n** the execution ('luaV_execute') to the caller, to allow stackless\n** calls.) Returns true iff function has been executed (C function).\n*/\nint luaD_precall (lua_State *L, StkId func, int nresults) {\n  lua_CFunction f;\n  CallInfo *ci;\n  switch (ttype(func)) {\n    case LUA_TCCL:  /* C closure */\n      f = clCvalue(func)->f;\n      goto Cfunc;\n    case LUA_TLCF:  /* light C function */\n      f = fvalue(func);\n     Cfunc: {\n      int n;  /* number of returns */\n      checkstackp(L, LUA_MINSTACK, func);  /* ensure minimum stack size */\n      ci = next_ci(L);  /* now 'enter' new function */\n      ci->nresults = nresults;\n      ci->func = func;\n      ci->top = L->top + LUA_MINSTACK;\n      lua_assert(ci->top <= L->stack_last);\n      ci->callstatus = 0;\n      if (L->hookmask & LUA_MASKCALL)\n        luaD_hook(L, LUA_HOOKCALL, -1);\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, L->top - n, n);\n      return 1;\n    }\n    case LUA_TLCL: {  /* Lua function: prepare its call */\n      StkId base;\n      Proto *p = clLvalue(func)->p;\n      int n = cast_int(L->top - func) - 1;  /* number of real arguments */\n      int fsize = p->maxstacksize;  /* frame size */\n      checkstackp(L, fsize, func);\n      if (p->is_vararg)\n        base = adjust_varargs(L, p, n);\n      else {  /* non vararg function */\n        for (; n < p->numparams; n++)\n          setnilvalue(L->top++);  /* complete missing arguments */\n        base = func + 1;\n      }\n      ci = next_ci(L);  /* now 'enter' new function */\n      ci->nresults = nresults;\n      ci->func = func;\n      ci->u.l.base = base;\n      L->top = ci->top = base + fsize;\n      lua_assert(ci->top <= L->stack_last);\n      ci->u.l.savedpc = p->code;  /* starting point */\n      ci->callstatus = CIST_LUA;\n      if (L->hookmask & LUA_MASKCALL)\n        callhook(L, ci);\n      return 0;\n    }\n    default: {  /* not a function */\n      checkstackp(L, 1, func);  /* ensure space for metamethod */\n      tryfuncTM(L, func);  /* try to get '__call' metamethod */\n      return luaD_precall(L, func, nresults);  /* now it must be a function */\n    }\n  }\n}\n\n\n/*\n** Check appropriate error for stack overflow (\"regular\" overflow or\n** overflow while handling stack overflow). If 'nCalls' is larger than\n** LUAI_MAXCCALLS (which means it is handling a \"regular\" overflow) but\n** smaller than 9/8 of LUAI_MAXCCALLS, does not report an error (to\n** allow overflow handling to work)\n*/\nstatic void stackerror (lua_State *L) {\n  if (L->nCcalls == LUAI_MAXCCALLS)\n    luaG_runerror(L, \"C stack overflow\");\n  else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))\n    luaD_throw(L, LUA_ERRERR);  /* error while handing stack error */\n}\n\n\n/*\n** Call a function (C or Lua). The function to be called is at *func.\n** The arguments are on the stack, right after the function.\n** When returns, all the results are on the stack, starting at the original\n** function position.\n*/\nvoid luaD_call (lua_State *L, StkId func, int nResults) {\n  if (++L->nCcalls >= LUAI_MAXCCALLS)\n    stackerror(L);\n  if (!luaD_precall(L, func, nResults))  /* is a Lua function? */\n    luaV_execute(L);  /* call it */\n  L->nCcalls--;\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  L->nny++;\n  luaD_call(L, func, nResults);\n  L->nny--;\n}\n\n\n/*\n** Completes the execution of an interrupted C function, calling its\n** continuation function.\n*/\nstatic void finishCcall (lua_State *L, int status) {\n  CallInfo *ci = L->ci;\n  int n;\n  /* must have a continuation and must be able to call it */\n  lua_assert(ci->u.c.k != NULL && L->nny == 0);\n  /* error status can only happen in a protected call */\n  lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD);\n  if (ci->callstatus & CIST_YPCALL) {  /* was inside a pcall? */\n    ci->callstatus &= ~CIST_YPCALL;  /* continuation is also inside it */\n    L->errfunc = ci->u.c.old_errfunc;  /* with the same error function */\n  }\n  /* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already\n     handled */\n  adjustresults(L, ci->nresults);\n  lua_unlock(L);\n  n = (*ci->u.c.k)(L, status, ci->u.c.ctx);  /* call continuation function */\n  lua_lock(L);\n  api_checknelems(L, n);\n  luaD_poscall(L, ci, L->top - n, n);  /* finish 'luaD_precall' */\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). If the coroutine is\n** recovering from an error, 'ud' points to the error status, which must\n** be passed to the first continuation function (otherwise the default\n** status is LUA_YIELD).\n*/\nstatic void unroll (lua_State *L, void *ud) {\n  if (ud != NULL)  /* error status? */\n    finishCcall(L, *(int *)ud);  /* finish 'lua_pcallk' callee */\n  while (L->ci != &L->base_ci) {  /* something in the stack */\n    if (!isLua(L->ci))  /* C function? */\n      finishCcall(L, LUA_YIELD);  /* complete its execution */\n    else {  /* Lua function */\n      luaV_finishOp(L);  /* finish interrupted instruction */\n      luaV_execute(L);  /* 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** Recovers from an error in a coroutine. Finds a recover point (if\n** there is one) and completes the execution of the interrupted\n** 'luaD_pcall'. If there is no recover point, returns zero.\n*/\nstatic int recover (lua_State *L, int status) {\n  StkId oldtop;\n  CallInfo *ci = findpcall(L);\n  if (ci == NULL) return 0;  /* no recovery point */\n  /* \"finish\" luaD_pcall */\n  oldtop = restorestack(L, ci->extra);\n  luaF_close(L, oldtop);\n  seterrorobj(L, status, oldtop);\n  L->ci = ci;\n  L->allowhook = getoah(ci->callstatus);  /* restore original 'allowhook' */\n  L->nny = 0;  /* should be zero to be yieldable */\n  luaD_shrinkstack(L);\n  L->errfunc = ci->u.c.old_errfunc;\n  return 1;  /* continue running the coroutine */\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  L->top -= narg;  /* remove args from the stack */\n  setsvalue2s(L, L->top, 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 - n;  /* first argument */\n  CallInfo *ci = L->ci;\n  if (L->status == LUA_OK) {  /* starting a coroutine? */\n    if (!luaD_precall(L, firstArg - 1, LUA_MULTRET))  /* Lua function? */\n      luaV_execute(L);  /* call it */\n  }\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    ci->func = restorestack(L, ci->extra);\n    if (isLua(ci))  /* yielded inside a hook? */\n      luaV_execute(L);  /* just continue running Lua code */\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        firstArg = L->top - n;  /* yield results come from continuation */\n      }\n      luaD_poscall(L, ci, firstArg, n);  /* finish 'luaD_precall' */\n    }\n    unroll(L, NULL);  /* run continuation */\n  }\n}\n\n\nLUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {\n  int status;\n  unsigned short oldnny = L->nny;  /* save \"number of non-yieldable\" calls */\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  }\n  else if (L->status != LUA_YIELD)\n    return resume_error(L, \"cannot resume dead coroutine\", nargs);\n  L->nCcalls = (from) ? from->nCcalls + 1 : 1;\n  if (L->nCcalls >= LUAI_MAXCCALLS)\n    return resume_error(L, \"C stack overflow\", nargs);\n  luai_userstateresume(L, nargs);\n  L->nny = 0;  /* allow yields */\n  api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);\n  status = luaD_rawrunprotected(L, resume, &nargs);\n  if (status == -1)  /* error calling 'lua_resume'? */\n    status = LUA_ERRRUN;\n  else {  /* continue running after recoverable errors */\n    while (errorstatus(status) && recover(L, status)) {\n      /* unroll continuation */\n      status = luaD_rawrunprotected(L, unroll, &status);\n    }\n    if (errorstatus(status)) {  /* unrecoverable error? */\n      L->status = cast_byte(status);  /* mark thread as 'dead' */\n      seterrorobj(L, status, L->top);  /* push error message */\n      L->ci->top = L->top;\n    }\n    else lua_assert(status == L->status);  /* normal end or yield */\n  }\n  L->nny = oldnny;  /* restore 'nny' */\n  L->nCcalls--;\n  lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0));\n  lua_unlock(L);\n  return status;\n}\n\n\nLUA_API int lua_isyieldable (lua_State *L) {\n  return (L->nny == 0);\n}\n\n\nLUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,\n                        lua_KFunction k) {\n  CallInfo *ci = L->ci;\n  luai_userstateyield(L, nresults);\n  lua_lock(L);\n  api_checknelems(L, nresults);\n  if (L->nny > 0) {\n    if (L != G(L)->mainthread)\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->extra = savestack(L, ci->func);  /* save current 'func' */\n  if (isLua(ci)) {  /* inside a hook? */\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    ci->func = L->top - nresults - 1;  /* protect stack below results */\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\nint luaD_pcall (lua_State *L, Pfunc func, void *u,\n                ptrdiff_t old_top, ptrdiff_t ef) {\n  int status;\n  CallInfo *old_ci = L->ci;\n  lu_byte old_allowhooks = L->allowhook;\n  unsigned short old_nny = L->nny;\n  ptrdiff_t old_errfunc = L->errfunc;\n  L->errfunc = ef;\n  status = luaD_rawrunprotected(L, func, u);\n  if (status != LUA_OK) {  /* an error occurred? */\n    StkId oldtop = restorestack(L, old_top);\n    luaF_close(L, oldtop);  /* close possible pending closures */\n    seterrorobj(L, status, oldtop);\n    L->ci = old_ci;\n    L->allowhook = old_allowhooks;\n    L->nny = old_nny;\n    luaD_shrinkstack(L);\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 (mode && 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  int c = zgetc(p->z);  /* read first character */\n  if (c == LUA_SIGNATURE[0]) {\n    checkmode(L, p->mode, \"binary\");\n    cl = luaU_undump(L, p->z, p->name);\n  }\n  else {\n    checkmode(L, p->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\nint luaD_protectedparser (lua_State *L, ZIO *z, const char *name,\n                                        const char *mode) {\n  struct SParser p;\n  int status;\n  L->nny++;  /* 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), L->errfunc);\n  luaZ_freebuffer(L, &p.buff);\n  luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);\n  luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);\n  luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);\n  L->nny--;\n  return status;\n}\n\n\n"
  },
  {
    "path": "src/lua/ldo.h",
    "content": "/*\n** $Id: ldo.h,v 2.29.1.1 2017/04/19 17:20:42 roberto Exp $\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 \"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** 'condmovestack' is used in heavy tests to force a stack reallocation\n** at every check.\n*/\n#define luaD_checkstackaux(L,n,pre,pos)  \\\n\tif (L->stack_last - L->top <= (n)) \\\n\t  { pre; luaD_growstack(L, n); pos; } else { 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,p)\t\t((char *)(p) - (char *)L->stack)\n#define restorestack(L,n)\t((TValue *)((char *)L->stack + (n)))\n\n\n/* type of protected functions, to be ran by 'runprotected' */\ntypedef void (*Pfunc) (lua_State *L, void *ud);\n\nLUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,\n                                                  const char *mode);\nLUAI_FUNC void luaD_hook (lua_State *L, int event, int line);\nLUAI_FUNC int 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 int luaD_pcall (lua_State *L, Pfunc func, void *u,\n                                        ptrdiff_t oldtop, ptrdiff_t ef);\nLUAI_FUNC int luaD_poscall (lua_State *L, CallInfo *ci, StkId firstResult,\n                                          int nres);\nLUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize);\nLUAI_FUNC void luaD_growstack (lua_State *L, int n);\nLUAI_FUNC void luaD_shrinkstack (lua_State *L);\nLUAI_FUNC void luaD_inctop (lua_State *L);\n\nLUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode);\nLUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);\n\n#endif\n\n"
  },
  {
    "path": "src/lua/ldump.c",
    "content": "/*\n** $Id: ldump.c,v 2.37.1.1 2017/04/19 17:20:42 roberto Exp $\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 <stddef.h>\n\n#include \"lua.h\"\n\n#include \"lobject.h\"\n#include \"lstate.h\"\n#include \"lundump.h\"\n\n\ntypedef struct {\n  lua_State *L;\n  lua_Writer writer;\n  void *data;\n  int strip;\n  int status;\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(v,n,D)\tDumpBlock(v,(n)*sizeof((v)[0]),D)\n\n#define DumpLiteral(s,D)\tDumpBlock(s, sizeof(s) - sizeof(char), D)\n\n\nstatic void DumpBlock (const void *b, size_t size, DumpState *D) {\n  if (D->status == 0 && size > 0) {\n    lua_unlock(D->L);\n    D->status = (*D->writer)(D->L, b, size, D->data);\n    lua_lock(D->L);\n  }\n}\n\n\n#define DumpVar(x,D)\t\tDumpVector(&x,1,D)\n\n\nstatic void DumpByte (int y, DumpState *D) {\n  lu_byte x = (lu_byte)y;\n  DumpVar(x, D);\n}\n\n\nstatic void DumpInt (int x, DumpState *D) {\n  DumpVar(x, D);\n}\n\n\nstatic void DumpNumber (lua_Number x, DumpState *D) {\n  DumpVar(x, D);\n}\n\n\nstatic void DumpInteger (lua_Integer x, DumpState *D) {\n  DumpVar(x, D);\n}\n\n\nstatic void DumpString (const TString *s, DumpState *D) {\n  if (s == NULL)\n    DumpByte(0, D);\n  else {\n    size_t size = tsslen(s) + 1;  /* include trailing '\\0' */\n    const char *str = getstr(s);\n    if (size < 0xFF)\n      DumpByte(cast_int(size), D);\n    else {\n      DumpByte(0xFF, D);\n      DumpVar(size, D);\n    }\n    DumpVector(str, size - 1, D);  /* no need to save '\\0' */\n  }\n}\n\n\nstatic void DumpCode (const Proto *f, DumpState *D) {\n  DumpInt(f->sizecode, D);\n  DumpVector(f->code, f->sizecode, D);\n}\n\n\nstatic void DumpFunction(const Proto *f, TString *psource, DumpState *D);\n\nstatic void DumpConstants (const Proto *f, DumpState *D) {\n  int i;\n  int n = f->sizek;\n  DumpInt(n, D);\n  for (i = 0; i < n; i++) {\n    const TValue *o = &f->k[i];\n    DumpByte(ttype(o), D);\n    switch (ttype(o)) {\n    case LUA_TNIL:\n      break;\n    case LUA_TBOOLEAN:\n      DumpByte(bvalue(o), D);\n      break;\n    case LUA_TNUMFLT:\n      DumpNumber(fltvalue(o), D);\n      break;\n    case LUA_TNUMINT:\n      DumpInteger(ivalue(o), D);\n      break;\n    case LUA_TSHRSTR:\n    case LUA_TLNGSTR:\n      DumpString(tsvalue(o), D);\n      break;\n    default:\n      lua_assert(0);\n    }\n  }\n}\n\n\nstatic void DumpProtos (const Proto *f, DumpState *D) {\n  int i;\n  int n = f->sizep;\n  DumpInt(n, D);\n  for (i = 0; i < n; i++)\n    DumpFunction(f->p[i], f->source, D);\n}\n\n\nstatic void DumpUpvalues (const Proto *f, DumpState *D) {\n  int i, n = f->sizeupvalues;\n  DumpInt(n, D);\n  for (i = 0; i < n; i++) {\n    DumpByte(f->upvalues[i].instack, D);\n    DumpByte(f->upvalues[i].idx, D);\n  }\n}\n\n\nstatic void DumpDebug (const Proto *f, DumpState *D) {\n  int i, n;\n  n = (D->strip) ? 0 : f->sizelineinfo;\n  DumpInt(n, D);\n  DumpVector(f->lineinfo, n, D);\n  n = (D->strip) ? 0 : f->sizelocvars;\n  DumpInt(n, D);\n  for (i = 0; i < n; i++) {\n    DumpString(f->locvars[i].varname, D);\n    DumpInt(f->locvars[i].startpc, D);\n    DumpInt(f->locvars[i].endpc, D);\n  }\n  n = (D->strip) ? 0 : f->sizeupvalues;\n  DumpInt(n, D);\n  for (i = 0; i < n; i++)\n    DumpString(f->upvalues[i].name, D);\n}\n\n\nstatic void DumpFunction (const Proto *f, TString *psource, DumpState *D) {\n  if (D->strip || f->source == psource)\n    DumpString(NULL, D);  /* no debug info or same source as its parent */\n  else\n    DumpString(f->source, D);\n  DumpInt(f->linedefined, D);\n  DumpInt(f->lastlinedefined, D);\n  DumpByte(f->numparams, D);\n  DumpByte(f->is_vararg, D);\n  DumpByte(f->maxstacksize, D);\n  DumpCode(f, D);\n  DumpConstants(f, D);\n  DumpUpvalues(f, D);\n  DumpProtos(f, D);\n  DumpDebug(f, D);\n}\n\n\nstatic void DumpHeader (DumpState *D) {\n  DumpLiteral(LUA_SIGNATURE, D);\n  DumpByte(LUAC_VERSION, D);\n  DumpByte(LUAC_FORMAT, D);\n  DumpLiteral(LUAC_DATA, D);\n  DumpByte(sizeof(int), D);\n  DumpByte(sizeof(size_t), D);\n  DumpByte(sizeof(Instruction), D);\n  DumpByte(sizeof(lua_Integer), D);\n  DumpByte(sizeof(lua_Number), D);\n  DumpInteger(LUAC_INT, D);\n  DumpNumber(LUAC_NUM, D);\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.L = L;\n  D.writer = w;\n  D.data = data;\n  D.strip = strip;\n  D.status = 0;\n  DumpHeader(&D);\n  DumpByte(f->sizeupvalues, &D);\n  DumpFunction(f, NULL, &D);\n  return D.status;\n}\n\n"
  },
  {
    "path": "src/lua/lfunc.c",
    "content": "/*\n** $Id: lfunc.c,v 2.45.1.1 2017/04/19 17:39:34 roberto Exp $\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 \"lfunc.h\"\n#include \"lgc.h\"\n#include \"lmem.h\"\n#include \"lobject.h\"\n#include \"lstate.h\"\n\n\n\nCClosure *luaF_newCclosure (lua_State *L, int n) {\n  GCObject *o = luaC_newobj(L, LUA_TCCL, sizeCclosure(n));\n  CClosure *c = gco2ccl(o);\n  c->nupvalues = cast_byte(n);\n  return c;\n}\n\n\nLClosure *luaF_newLclosure (lua_State *L, int n) {\n  GCObject *o = luaC_newobj(L, LUA_TLCL, sizeLclosure(n));\n  LClosure *c = gco2lcl(o);\n  c->p = NULL;\n  c->nupvalues = cast_byte(n);\n  while (n--) c->upvals[n] = NULL;\n  return c;\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    UpVal *uv = luaM_new(L, UpVal);\n    uv->refcount = 1;\n    uv->v = &uv->u.value;  /* make it closed */\n    setnilvalue(uv->v);\n    cl->upvals[i] = uv;\n  }\n}\n\n\nUpVal *luaF_findupval (lua_State *L, StkId level) {\n  UpVal **pp = &L->openupval;\n  UpVal *p;\n  UpVal *uv;\n  lua_assert(isintwups(L) || L->openupval == NULL);\n  while (*pp != NULL && (p = *pp)->v >= level) {\n    lua_assert(upisopen(p));\n    if (p->v == level)  /* found a corresponding upvalue? */\n      return p;  /* return it */\n    pp = &p->u.open.next;\n  }\n  /* not found: create a new upvalue */\n  uv = luaM_new(L, UpVal);\n  uv->refcount = 0;\n  uv->u.open.next = *pp;  /* link it to list of open upvalues */\n  uv->u.open.touched = 1;\n  *pp = uv;\n  uv->v = level;  /* current value lives in the stack */\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\nvoid luaF_close (lua_State *L, StkId level) {\n  UpVal *uv;\n  while (L->openupval != NULL && (uv = L->openupval)->v >= level) {\n    lua_assert(upisopen(uv));\n    L->openupval = uv->u.open.next;  /* remove from 'open' list */\n    if (uv->refcount == 0)  /* no references? */\n      luaM_free(L, uv);  /* free upvalue */\n    else {\n      setobj(L, &uv->u.value, uv->v);  /* move value to upvalue slot */\n      uv->v = &uv->u.value;  /* now current value lives here */\n      luaC_upvalbarrier(L, uv);\n    }\n  }\n}\n\n\nProto *luaF_newproto (lua_State *L) {\n  GCObject *o = luaC_newobj(L, LUA_TPROTO, 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->cache = NULL;\n  f->sizecode = 0;\n  f->lineinfo = NULL;\n  f->sizelineinfo = 0;\n  f->upvalues = NULL;\n  f->sizeupvalues = 0;\n  f->numparams = 0;\n  f->is_vararg = 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\nvoid luaF_freeproto (lua_State *L, Proto *f) {\n  luaM_freearray(L, f->code, f->sizecode);\n  luaM_freearray(L, f->p, f->sizep);\n  luaM_freearray(L, f->k, f->sizek);\n  luaM_freearray(L, f->lineinfo, f->sizelineinfo);\n  luaM_freearray(L, f->locvars, f->sizelocvars);\n  luaM_freearray(L, f->upvalues, 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\n"
  },
  {
    "path": "src/lua/lfunc.h",
    "content": "/*\n** $Id: lfunc.h,v 2.15.1.1 2017/04/19 17:39:34 roberto Exp $\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)\t(cast(int, sizeof(CClosure)) + \\\n                         cast(int, sizeof(TValue)*((n)-1)))\n\n#define sizeLclosure(n)\t(cast(int, sizeof(LClosure)) + \\\n                         cast(int, sizeof(TValue *)*((n)-1)))\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/*\n** Upvalues for Lua closures\n*/\nstruct UpVal {\n  TValue *v;  /* points to stack or to its own value */\n  lu_mem refcount;  /* reference counter */\n  union {\n    struct {  /* (when open) */\n      UpVal *next;  /* linked list */\n      int touched;  /* mark to avoid cycles with dead threads */\n    } open;\n    TValue value;  /* the value (when closed) */\n  } u;\n};\n\n#define upisopen(up)\t((up)->v != &(up)->u.value)\n\n\nLUAI_FUNC Proto *luaF_newproto (lua_State *L);\nLUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nelems);\nLUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nelems);\nLUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl);\nLUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);\nLUAI_FUNC void luaF_close (lua_State *L, StkId level);\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);\n\n\n#endif\n"
  },
  {
    "path": "src/lua/lgc.c",
    "content": "/*\n** $Id: lgc.c,v 2.215.1.2 2017/08/31 16:15:27 roberto Exp $\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\n#include <string.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#include \"ltable.h\"\n#include \"ltm.h\"\n\n\n/*\n** internal state for collector while inside the atomic phase. The\n** collector should never be in this state while running regular code.\n*/\n#define GCSinsideatomic\t\t(GCSpause + 1)\n\n/*\n** cost of sweeping one element (the size of a small object divided\n** by some adjust for the sweep speed)\n*/\n#define GCSWEEPCOST\t((sizeof(TString) + 4) / 4)\n\n/* maximum number of elements to sweep in each single step */\n#define GCSWEEPMAX\t(cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))\n\n/* cost of calling one finalizer */\n#define GCFINALIZECOST\tGCSWEEPCOST\n\n\n/*\n** macro to adjust 'stepmul': 'stepmul' is actually used like\n** 'stepmul / STEPMULADJ' (value chosen by tests)\n*/\n#define STEPMULADJ\t\t200\n\n\n/*\n** macro to adjust 'pause': 'pause' is actually used like\n** 'pause / PAUSEADJ' (value chosen by tests)\n*/\n#define PAUSEADJ\t\t100\n\n\n/*\n** 'makewhite' erases all color bits then sets only the current white\n** bit\n*/\n#define maskcolors\t(~(bitmask(BLACKBIT) | WHITEBITS))\n#define makewhite(g,x)\t\\\n (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g)))\n\n#define white2gray(x)\tresetbits(x->marked, WHITEBITS)\n#define black2gray(x)\tresetbit(x->marked, BLACKBIT)\n\n\n#define valiswhite(x)   (iscollectable(x) && iswhite(gcvalue(x)))\n\n#define checkdeadkey(n)\tlua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))\n\n\n#define checkconsistency(obj)  \\\n  lua_longassert(!iscollectable(obj) || righttt(obj))\n\n\n#define markvalue(g,o) { checkconsistency(o); \\\n  if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }\n\n#define markobject(g,t)\t{ if (iswhite(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\nstatic void reallymarkobject (global_State *g, GCObject *o);\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(size_t, sizenode(h)))\n\n\n/*\n** link collectable object 'o' into list pointed by 'p'\n*/\n#define linkgclist(o,p)\t((o)->gclist = (p), (p) = obj2gco(o))\n\n\n/*\n** If key is not marked, mark its entry as dead. This allows key to be\n** collected, but keeps its entry in the table.  A dead node is needed\n** when Lua looks up for a key (it may be part of a chain) and when\n** traversing a weak table (key might be removed from the table during\n** traversal). Other places never manipulate dead keys, because its\n** associated nil value is enough to signal that the entry is logically\n** empty.\n*/\nstatic void removeentry (Node *n) {\n  lua_assert(ttisnil(gval(n)));\n  if (valiswhite(gkey(n)))\n    setdeadvalue(wgkey(n));  /* unused and unmarked 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 TValue *o) {\n  if (!iscollectable(o)) return 0;\n  else if (ttisstring(o)) {\n    markobject(g, tsvalue(o));  /* strings are 'values', so are never weak */\n    return 0;\n  }\n  else return iswhite(gcvalue(o));\n}\n\n\n/*\n** barrier that moves collector forward, that is, mark the white object\n** being pointed by a black object. (If in sweep phase, clear the black\n** object to white [sweep it] to avoid other barrier calls for this\n** same object.)\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));\n  if (keepinvariant(g))  /* must keep invariant? */\n    reallymarkobject(g, v);  /* restore invariant */\n  else {  /* sweep phase */\n    lua_assert(issweepphase(g));\n    makewhite(g, o);  /* mark main obj. 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, Table *t) {\n  global_State *g = G(L);\n  lua_assert(isblack(t) && !isdead(g, t));\n  black2gray(t);  /* make table gray (again) */\n  linkgclist(t, g->grayagain);\n}\n\n\n/*\n** barrier for assignments to closed upvalues. Because upvalues are\n** shared among closures, it is impossible to know the color of all\n** closures pointing to it. So, we assume that the object being assigned\n** must be marked.\n*/\nvoid luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {\n  global_State *g = G(L);\n  GCObject *o = gcvalue(uv->v);\n  lua_assert(!upisopen(uv));  /* ensured by macro luaC_upvalbarrier */\n  if (keepinvariant(g))\n    markobject(g, o);\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  white2gray(o);  /* they will be gray 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 and size) and link\n** it to 'allgc' list.\n*/\nGCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {\n  global_State *g = G(L);\n  GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));\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\n\n/*\n** {======================================================\n** Mark functions\n** =======================================================\n*/\n\n\n/*\n** mark an object. Userdata, strings, and closed upvalues are visited\n** and turned black here. Other objects are marked gray and added\n** to appropriate list to be visited (and turned black) later. (Open\n** upvalues are already linked in 'headuv' list.)\n*/\nstatic void reallymarkobject (global_State *g, GCObject *o) {\n reentry:\n  white2gray(o);\n  switch (o->tt) {\n    case LUA_TSHRSTR: {\n      gray2black(o);\n      g->GCmemtrav += sizelstring(gco2ts(o)->shrlen);\n      break;\n    }\n    case LUA_TLNGSTR: {\n      gray2black(o);\n      g->GCmemtrav += sizelstring(gco2ts(o)->u.lnglen);\n      break;\n    }\n    case LUA_TUSERDATA: {\n      TValue uvalue;\n      markobjectN(g, gco2u(o)->metatable);  /* mark its metatable */\n      gray2black(o);\n      g->GCmemtrav += sizeudata(gco2u(o));\n      getuservalue(g->mainthread, gco2u(o), &uvalue);\n      if (valiswhite(&uvalue)) {  /* markvalue(g, &uvalue); */\n        o = gcvalue(&uvalue);\n        goto reentry;\n      }\n      break;\n    }\n    case LUA_TLCL: {\n      linkgclist(gco2lcl(o), g->gray);\n      break;\n    }\n    case LUA_TCCL: {\n      linkgclist(gco2ccl(o), g->gray);\n      break;\n    }\n    case LUA_TTABLE: {\n      linkgclist(gco2t(o), g->gray);\n      break;\n    }\n    case LUA_TTHREAD: {\n      linkgclist(gco2th(o), g->gray);\n      break;\n    }\n    case LUA_TPROTO: {\n      linkgclist(gco2p(o), g->gray);\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_NUMTAGS; 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** Mark all values stored in marked open upvalues from non-marked threads.\n** (Values from marked threads were already marked when traversing the\n** thread.) Remove from the list threads that no longer have upvalues and\n** not-marked threads.\n*/\nstatic void remarkupvals (global_State *g) {\n  lua_State *thread;\n  lua_State **p = &g->twups;\n  while ((thread = *p) != NULL) {\n    lua_assert(!isblack(thread));  /* threads are never black */\n    if (isgray(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      *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        if (uv->u.open.touched) {\n          markvalue(g, uv->v);  /* remark upvalue's value */\n          uv->u.open.touched = 0;\n        }\n      }\n    }\n  }\n}\n\n\n/*\n** mark root set and reset all gray lists, to start a new collection\n*/\nstatic void restartcollection (global_State *g) {\n  g->gray = g->grayagain = NULL;\n  g->weak = g->allweak = g->ephemeron = NULL;\n  markobject(g, g->mainthread);\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** 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.\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->sizearray > 0);\n  for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */\n    checkdeadkey(n);\n    if (ttisnil(gval(n)))  /* entry is empty? */\n      removeentry(n);  /* remove it */\n    else {\n      lua_assert(!ttisnil(gkey(n)));\n      markvalue(g, gkey(n));  /* mark key */\n      if (!hasclears && iscleared(g, gval(n)))  /* is there 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}\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).\n*/\nstatic int traverseephemeron (global_State *g, Table *h) {\n  int marked = 0;  /* true if an object is marked in this traversal */\n  int hasclears = 0;  /* true if table has white keys */\n  int hasww = 0;  /* true if table has entry \"white-key -> white-value\" */\n  Node *n, *limit = gnodelast(h);\n  unsigned int i;\n  /* traverse array part */\n  for (i = 0; i < h->sizearray; i++) {\n    if (valiswhite(&h->array[i])) {\n      marked = 1;\n      reallymarkobject(g, gcvalue(&h->array[i]));\n    }\n  }\n  /* traverse hash part */\n  for (n = gnode(h, 0); n < limit; n++) {\n    checkdeadkey(n);\n    if (ttisnil(gval(n)))  /* entry is empty? */\n      removeentry(n);  /* remove it */\n    else if (iscleared(g, gkey(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  return marked;\n}\n\n\nstatic void traversestrongtable (global_State *g, Table *h) {\n  Node *n, *limit = gnodelast(h);\n  unsigned int i;\n  for (i = 0; i < h->sizearray; i++)  /* traverse array part */\n    markvalue(g, &h->array[i]);\n  for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */\n    checkdeadkey(n);\n    if (ttisnil(gval(n)))  /* entry is empty? */\n      removeentry(n);  /* remove it */\n    else {\n      lua_assert(!ttisnil(gkey(n)));\n      markvalue(g, gkey(n));  /* mark key */\n      markvalue(g, gval(n));  /* mark value */\n    }\n  }\n}\n\n\nstatic lu_mem traversetable (global_State *g, Table *h) {\n  const char *weakkey, *weakvalue;\n  const TValue *mode = gfasttm(g, h->metatable, TM_MODE);\n  markobjectN(g, h->metatable);\n  if (mode && ttisstring(mode) &&  /* is there a weak mode? */\n      ((weakkey = strchr(svalue(mode), 'k')),\n       (weakvalue = strchr(svalue(mode), 'v')),\n       (weakkey || weakvalue))) {  /* is really weak? */\n    black2gray(h);  /* keep table gray */\n    if (!weakkey)  /* strong keys? */\n      traverseweakvalue(g, h);\n    else if (!weakvalue)  /* strong values? */\n      traverseephemeron(g, h);\n    else  /* all weak */\n      linkgclist(h, g->allweak);  /* nothing to traverse now */\n  }\n  else  /* not weak */\n    traversestrongtable(g, h);\n  return sizeof(Table) + sizeof(TValue) * h->sizearray +\n                         sizeof(Node) * cast(size_t, allocsizenode(h));\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 int traverseproto (global_State *g, Proto *f) {\n  int i;\n  if (f->cache && iswhite(f->cache))\n    f->cache = NULL;  /* allow cache to be collected */\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 sizeof(Proto) + sizeof(Instruction) * f->sizecode +\n                         sizeof(Proto *) * f->sizep +\n                         sizeof(TValue) * f->sizek +\n                         sizeof(int) * f->sizelineinfo +\n                         sizeof(LocVar) * f->sizelocvars +\n                         sizeof(Upvaldesc) * f->sizeupvalues;\n}\n\n\nstatic lu_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 sizeCclosure(cl->nupvalues);\n}\n\n/*\n** open upvalues point to values in a thread, so those values should\n** be marked when the thread is traversed except in the atomic phase\n** (because then the value cannot be changed by the thread and the\n** thread may not be traversed again)\n*/\nstatic lu_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++) {  /* mark its upvalues */\n    UpVal *uv = cl->upvals[i];\n    if (uv != NULL) {\n      if (upisopen(uv) && g->gcstate != GCSinsideatomic)\n        uv->u.open.touched = 1;  /* can be marked in 'remarkupvals' */\n      else\n        markvalue(g, uv->v);\n    }\n  }\n  return sizeLclosure(cl->nupvalues);\n}\n\n\nstatic lu_mem traversethread (global_State *g, lua_State *th) {\n  StkId o = th->stack;\n  if (o == NULL)\n    return 1;  /* stack not completely built yet */\n  lua_assert(g->gcstate == GCSinsideatomic ||\n             th->openupval == NULL || isintwups(th));\n  for (; o < th->top; o++)  /* mark live elements in the stack */\n    markvalue(g, o);\n  if (g->gcstate == GCSinsideatomic) {  /* final traversal? */\n    StkId lim = th->stack + th->stacksize;  /* real end of stack */\n    for (; o < lim; o++)  /* clear not-marked stack slice */\n      setnilvalue(o);\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  else if (g->gckind != KGC_EMERGENCY)\n    luaD_shrinkstack(th); /* do not change stack in emergency cycle */\n  return (sizeof(lua_State) + sizeof(TValue) * th->stacksize +\n          sizeof(CallInfo) * th->nci);\n}\n\n\n/*\n** traverse one gray object, turning it to black (except for threads,\n** which are always gray).\n*/\nstatic void propagatemark (global_State *g) {\n  lu_mem size;\n  GCObject *o = g->gray;\n  lua_assert(isgray(o));\n  gray2black(o);\n  switch (o->tt) {\n    case LUA_TTABLE: {\n      Table *h = gco2t(o);\n      g->gray = h->gclist;  /* remove from 'gray' list */\n      size = traversetable(g, h);\n      break;\n    }\n    case LUA_TLCL: {\n      LClosure *cl = gco2lcl(o);\n      g->gray = cl->gclist;  /* remove from 'gray' list */\n      size = traverseLclosure(g, cl);\n      break;\n    }\n    case LUA_TCCL: {\n      CClosure *cl = gco2ccl(o);\n      g->gray = cl->gclist;  /* remove from 'gray' list */\n      size = traverseCclosure(g, cl);\n      break;\n    }\n    case LUA_TTHREAD: {\n      lua_State *th = gco2th(o);\n      g->gray = th->gclist;  /* remove from 'gray' list */\n      linkgclist(th, g->grayagain);  /* insert into 'grayagain' list */\n      black2gray(o);\n      size = traversethread(g, th);\n      break;\n    }\n    case LUA_TPROTO: {\n      Proto *p = gco2p(o);\n      g->gray = p->gclist;  /* remove from 'gray' list */\n      size = traverseproto(g, p);\n      break;\n    }\n    default: lua_assert(0); return;\n  }\n  g->GCmemtrav += size;\n}\n\n\nstatic void propagateall (global_State *g) {\n  while (g->gray) propagatemark(g);\n}\n\n\nstatic void convergeephemerons (global_State *g) {\n  int changed;\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) {\n      next = gco2t(w)->gclist;\n      if (traverseephemeron(g, gco2t(w))) {  /* traverse marked some value? */\n        propagateall(g);  /* propagate changes */\n        changed = 1;  /* will have to revisit all ephemeron tables */\n      }\n    }\n  } while (changed);\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' up\n** to element 'f'\n*/\nstatic void clearkeys (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    for (n = gnode(h, 0); n < limit; n++) {\n      if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) {\n        setnilvalue(gval(n));  /* remove value ... */\n      }\n      if (ttisnil(gval(n)))  /* is entry empty? */\n        removeentry(n);  /* remove entry from table */\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 clearvalues (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    for (i = 0; i < h->sizearray; i++) {\n      TValue *o = &h->array[i];\n      if (iscleared(g, o))  /* value was collected? */\n        setnilvalue(o);  /* remove value */\n    }\n    for (n = gnode(h, 0); n < limit; n++) {\n      if (!ttisnil(gval(n)) && iscleared(g, gval(n))) {\n        setnilvalue(gval(n));  /* remove value ... */\n        removeentry(n);  /* and remove entry from table */\n      }\n    }\n  }\n}\n\n\nvoid luaC_upvdeccount (lua_State *L, UpVal *uv) {\n  lua_assert(uv->refcount > 0);\n  uv->refcount--;\n  if (uv->refcount == 0 && !upisopen(uv))\n    luaM_free(L, uv);\n}\n\n\nstatic void freeLclosure (lua_State *L, LClosure *cl) {\n  int i;\n  for (i = 0; i < cl->nupvalues; i++) {\n    UpVal *uv = cl->upvals[i];\n    if (uv)\n      luaC_upvdeccount(L, uv);\n  }\n  luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));\n}\n\n\nstatic void freeobj (lua_State *L, GCObject *o) {\n  switch (o->tt) {\n    case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;\n    case LUA_TLCL: {\n      freeLclosure(L, gco2lcl(o));\n      break;\n    }\n    case LUA_TCCL: {\n      luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));\n      break;\n    }\n    case LUA_TTABLE: luaH_free(L, gco2t(o)); break;\n    case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;\n    case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;\n    case LUA_TSHRSTR:\n      luaS_remove(L, gco2ts(o));  /* remove it from hash table */\n      luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen));\n      break;\n    case LUA_TLNGSTR: {\n      luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen));\n      break;\n    }\n    default: lua_assert(0);\n  }\n}\n\n\n#define sweepwholelist(L,p)\tsweeplist(L,p,MAX_LUMEM)\nstatic GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);\n\n\n/*\n** sweep at most 'count' 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, preparing for next\n** collection cycle. Return where to continue the traversal or NULL if\n** list is finished.\n*/\nstatic GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {\n  global_State *g = G(L);\n  int ow = otherwhite(g);\n  int white = luaC_white(g);  /* current white */\n  while (*p != NULL && count-- > 0) {\n    GCObject *curr = *p;\n    int marked = curr->marked;\n    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' */\n      curr->marked = cast_byte((marked & maskcolors) | white);\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->gckind != KGC_EMERGENCY) {\n    l_mem olddebt = g->GCdebt;\n    if (g->strt.nuse < g->strt.size / 4)  /* string table too big? */\n      luaS_resize(L, g->strt.size / 2);  /* shrink it a little */\n    g->GCestimate += g->GCdebt - olddebt;  /* update estimate */\n  }\n}\n\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  return o;\n}\n\n\nstatic void dothecall (lua_State *L, void *ud) {\n  UNUSED(ud);\n  luaD_callnoyield(L, L->top - 2, 0);\n}\n\n\nstatic void GCTM (lua_State *L, int propagateerrors) {\n  global_State *g = G(L);\n  const TValue *tm;\n  TValue v;\n  setgcovalue(L, &v, udata2finalize(g));\n  tm = luaT_gettmbyobj(L, &v, TM_GC);\n  if (tm != NULL && ttisfunction(tm)) {  /* is there a finalizer? */\n    int status;\n    lu_byte oldah = L->allowhook;\n    int running  = g->gcrunning;\n    L->allowhook = 0;  /* stop debug hooks during GC metamethod */\n    g->gcrunning = 0;  /* avoid GC steps */\n    setobj2s(L, L->top, tm);  /* push finalizer... */\n    setobj2s(L, L->top + 1, &v);  /* ... and its argument */\n    L->top += 2;  /* and (next line) call the finalizer */\n    L->ci->callstatus |= CIST_FIN;  /* will run a finalizer */\n    status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);\n    L->ci->callstatus &= ~CIST_FIN;  /* not running a finalizer anymore */\n    L->allowhook = oldah;  /* restore hooks */\n    g->gcrunning = running;  /* restore state */\n    if (status != LUA_OK && propagateerrors) {  /* error while running __gc? */\n      if (status == LUA_ERRRUN) {  /* is there an error object? */\n        const char *msg = (ttisstring(L->top - 1))\n                            ? svalue(L->top - 1)\n                            : \"no message\";\n        luaO_pushfstring(L, \"error in __gc metamethod (%s)\", msg);\n        status = LUA_ERRGCMM;  /* error in __gc metamethod */\n      }\n      luaD_throw(L, status);  /* re-throw error */\n    }\n  }\n}\n\n\n/*\n** call a few (up to 'g->gcfinnum') finalizers\n*/\nstatic int runafewfinalizers (lua_State *L) {\n  global_State *g = G(L);\n  unsigned int i;\n  lua_assert(!g->tobefnz || g->gcfinnum > 0);\n  for (i = 0; g->tobefnz && i < g->gcfinnum; i++)\n    GCTM(L, 1);  /* call one finalizer */\n  g->gcfinnum = (!g->tobefnz) ? 0  /* nothing more to finalize? */\n                    : g->gcfinnum * 2;  /* else call a few more next time */\n  return i;\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, 0);\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*/\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) != NULL) {  /* 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      *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 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    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    /* 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** {======================================================\n** GC control\n** =======================================================\n*/\n\n\n/*\n** Set a reasonable \"time\" to wait before starting a new GC cycle; cycle\n** will start when memory use hits threshold. (Division by 'estimate'\n** should be OK: it cannot be zero (because Lua cannot even start with\n** less than PAUSEADJ bytes).\n*/\nstatic void setpause (global_State *g) {\n  l_mem threshold, debt;\n  l_mem estimate = g->GCestimate / PAUSEADJ;  /* adjust 'estimate' */\n  lua_assert(estimate > 0);\n  threshold = (g->gcpause < MAX_LMEM / estimate)  /* overflow? */\n            ? estimate * g->gcpause  /* no overflow */\n            : MAX_LMEM;  /* overflow; truncate to maximum */\n  debt = gettotalbytes(g) - threshold;\n  luaE_setdebt(g, debt);\n}\n\n\n/*\n** Enter first sweep phase.\n** The call to 'sweeplist' tries to make 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 = sweeplist(L, &g->allgc, 1);\n}\n\n\nvoid luaC_freeallobjects (lua_State *L) {\n  global_State *g = G(L);\n  separatetobefnz(g, 1);  /* separate all objects with finalizers */\n  lua_assert(g->finobj == NULL);\n  callallpendingfinalizers(L);\n  lua_assert(g->tobefnz == NULL);\n  g->currentwhite = WHITEBITS; /* this \"white\" makes all objects look dead */\n  g->gckind = KGC_NORMAL;\n  sweepwholelist(L, &g->finobj);\n  sweepwholelist(L, &g->allgc);\n  sweepwholelist(L, &g->fixedgc);  /* collect fixed objects */\n  lua_assert(g->strt.nuse == 0);\n}\n\n\nstatic l_mem atomic (lua_State *L) {\n  global_State *g = G(L);\n  l_mem work;\n  GCObject *origweak, *origall;\n  GCObject *grayagain = g->grayagain;  /* save original list */\n  lua_assert(g->ephemeron == NULL && g->weak == NULL);\n  lua_assert(!iswhite(g->mainthread));\n  g->gcstate = GCSinsideatomic;\n  g->GCmemtrav = 0;  /* start counting work */\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  /* remark occasional upvalues of (maybe) dead threads */\n  remarkupvals(g);\n  propagateall(g);  /* propagate changes */\n  work = g->GCmemtrav;  /* stop counting (do not recount 'grayagain') */\n  g->gray = grayagain;\n  propagateall(g);  /* traverse 'grayagain' list */\n  g->GCmemtrav = 0;  /* restart counting */\n  convergeephemerons(g);\n  /* at this point, all strongly accessible objects are marked. */\n  /* Clear values from weak tables, before checking finalizers */\n  clearvalues(g, g->weak, NULL);\n  clearvalues(g, g->allweak, NULL);\n  origweak = g->weak; origall = g->allweak;\n  work += g->GCmemtrav;  /* stop counting (objects being finalized) */\n  separatetobefnz(g, 0);  /* separate objects to be finalized */\n  g->gcfinnum = 1;  /* there may be objects to be finalized */\n  markbeingfnz(g);  /* mark objects that will be finalized */\n  propagateall(g);  /* remark, to propagate 'resurrection' */\n  g->GCmemtrav = 0;  /* restart counting */\n  convergeephemerons(g);\n  /* at this point, all resurrected objects are marked. */\n  /* remove dead objects from weak tables */\n  clearkeys(g, g->ephemeron, NULL);  /* clear keys from all ephemeron tables */\n  clearkeys(g, g->allweak, NULL);  /* clear keys from all 'allweak' tables */\n  /* clear values from resurrected weak tables */\n  clearvalues(g, g->weak, origweak);\n  clearvalues(g, g->allweak, origall);\n  luaS_clearcache(g);\n  g->currentwhite = cast_byte(otherwhite(g));  /* flip current white */\n  work += g->GCmemtrav;  /* complete counting */\n  return work;  /* estimate of memory marked by 'atomic' */\n}\n\n\nstatic lu_mem sweepstep (lua_State *L, global_State *g,\n                         int nextstate, GCObject **nextlist) {\n  if (g->sweepgc) {\n    l_mem olddebt = g->GCdebt;\n    g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);\n    g->GCestimate += g->GCdebt - olddebt;  /* update estimate */\n    if (g->sweepgc)  /* is there still something to sweep? */\n      return (GCSWEEPMAX * GCSWEEPCOST);\n  }\n  /* else enter next state */\n  g->gcstate = nextstate;\n  g->sweepgc = nextlist;\n  return 0;\n}\n\n\nstatic lu_mem singlestep (lua_State *L) {\n  global_State *g = G(L);\n  switch (g->gcstate) {\n    case GCSpause: {\n      g->GCmemtrav = g->strt.size * sizeof(GCObject*);\n      restartcollection(g);\n      g->gcstate = GCSpropagate;\n      return g->GCmemtrav;\n    }\n    case GCSpropagate: {\n      g->GCmemtrav = 0;\n      lua_assert(g->gray);\n      propagatemark(g);\n       if (g->gray == NULL)  /* no more gray objects? */\n        g->gcstate = GCSatomic;  /* finish propagate phase */\n      return g->GCmemtrav;  /* memory traversed in this step */\n    }\n    case GCSatomic: {\n      lu_mem work;\n      propagateall(g);  /* make sure gray list is empty */\n      work = atomic(L);  /* work is what was traversed by 'atomic' */\n      entersweep(L);\n      g->GCestimate = gettotalbytes(g);  /* first estimate */;\n      return work;\n    }\n    case GCSswpallgc: {  /* sweep \"regular\" objects */\n      return sweepstep(L, g, GCSswpfinobj, &g->finobj);\n    }\n    case GCSswpfinobj: {  /* sweep objects with finalizers */\n      return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);\n    }\n    case GCSswptobefnz: {  /* sweep objects to be finalized */\n      return sweepstep(L, g, GCSswpend, NULL);\n    }\n    case GCSswpend: {  /* finish sweeps */\n      makewhite(g, g->mainthread);  /* sweep main thread */\n      checkSizes(L, g);\n      g->gcstate = GCScallfin;\n      return 0;\n    }\n    case GCScallfin: {  /* call remaining finalizers */\n      if (g->tobefnz && g->gckind != KGC_EMERGENCY) {\n        int n = runafewfinalizers(L);\n        return (n * GCFINALIZECOST);\n      }\n      else {  /* emergency mode or no more finalizers */\n        g->gcstate = GCSpause;  /* finish collection */\n        return 0;\n      }\n    }\n    default: lua_assert(0); return 0;\n  }\n}\n\n\n/*\n** advances the garbage collector until it reaches a state allowed\n** by 'statemask'\n*/\nvoid luaC_runtilstate (lua_State *L, int statesmask) {\n  global_State *g = G(L);\n  while (!testbit(statesmask, g->gcstate))\n    singlestep(L);\n}\n\n\n/*\n** get GC debt and convert it from Kb to 'work units' (avoid zero debt\n** and overflows)\n*/\nstatic l_mem getdebt (global_State *g) {\n  l_mem debt = g->GCdebt;\n  int stepmul = g->gcstepmul;\n  if (debt <= 0) return 0;  /* minimal debt */\n  else {\n    debt = (debt / STEPMULADJ) + 1;\n    debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;\n    return debt;\n  }\n}\n\n/*\n** performs a basic GC step when collector is running\n*/\nvoid luaC_step (lua_State *L) {\n  global_State *g = G(L);\n  l_mem debt = getdebt(g);  /* GC deficit (be paid now) */\n  if (!g->gcrunning) {  /* not running? */\n    luaE_setdebt(g, -GCSTEPSIZE * 10);  /* avoid being called too often */\n    return;\n  }\n  do {  /* repeat until pause or enough \"credit\" (negative debt) */\n    lu_mem work = singlestep(L);  /* perform one single step */\n    debt -= work;\n  } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);\n  if (g->gcstate == GCSpause)\n    setpause(g);  /* pause until next cycle */\n  else {\n    debt = (debt / g->gcstepmul) * STEPMULADJ;  /* convert 'work units' to Kb */\n    luaE_setdebt(g, debt);\n    runafewfinalizers(L);\n  }\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** 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*/\nvoid luaC_fullgc (lua_State *L, int isemergency) {\n  global_State *g = G(L);\n  lua_assert(g->gckind == KGC_NORMAL);\n  if (isemergency) g->gckind = KGC_EMERGENCY;  /* set flag */\n  if (keepinvariant(g)) {  /* black objects? */\n    entersweep(L); /* sweep everything to turn them back to white */\n  }\n  /* finish any pending sweep phase to start a new cycle */\n  luaC_runtilstate(L, bitmask(GCSpause));\n  luaC_runtilstate(L, ~bitmask(GCSpause));  /* start new collection */\n  luaC_runtilstate(L, bitmask(GCScallfin));  /* run up to finalizers */\n  /* estimate must be correct after a full GC cycle */\n  lua_assert(g->GCestimate == gettotalbytes(g));\n  luaC_runtilstate(L, bitmask(GCSpause));  /* finish collection */\n  g->gckind = KGC_NORMAL;\n  setpause(g);\n}\n\n/* }====================================================== */\n\n\n"
  },
  {
    "path": "src/lua/lgc.h",
    "content": "/*\n** $Id: lgc.h,v 2.91.1.1 2017/04/19 17:39:34 roberto Exp $\n** Garbage Collector\n** See Copyright Notice in lua.h\n*/\n\n#ifndef lgc_h\n#define lgc_h\n\n\n#include \"lobject.h\"\n#include \"lstate.h\"\n\n/*\n** Collectable objects may have one of three colors: white, which\n** means the object is not marked; gray, which means the\n** object is marked, but its references may be not marked; and\n** black, which means that the object and all its references are marked.\n** The main invariant of the garbage collector, while marking objects,\n** is that a black object can never point to a white one. Moreover,\n** any gray object must be in a \"gray list\" (gray, grayagain, weak,\n** allweak, ephemeron) so that it can be visited again before finishing\n** the collection cycle. These lists have no meaning when the invariant\n** is not being enforced (e.g., sweep phase).\n*/\n\n\n\n/* how much to allocate before next GC step */\n#if !defined(GCSTEPSIZE)\n/* ~100 small strings */\n#define GCSTEPSIZE\t(cast_int(100 * sizeof(TString)))\n#endif\n\n\n/*\n** Possible states of the Garbage Collector\n*/\n#define GCSpropagate\t0\n#define GCSatomic\t1\n#define GCSswpallgc\t2\n#define GCSswpfinobj\t3\n#define GCSswptobefnz\t4\n#define GCSswpend\t5\n#define GCScallfin\t6\n#define GCSpause\t7\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\n** phase may break the invariant, as objects turned white may point to\n** still-black objects. The invariant is restored when sweep ends and\n** all objects 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(lu_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/* Layout for bit use in 'marked' field: */\n#define WHITE0BIT\t0  /* object is white (type 0) */\n#define WHITE1BIT\t1  /* object is white (type 1) */\n#define BLACKBIT\t2  /* object is black */\n#define FINALIZEDBIT\t3  /* object has been marked for finalization */\n/* bit 7 is currently used by tests (luaL_checkmemory) */\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) ^ WHITEBITS) & (ow)))\n#define isdead(g,v)\tisdeadm(otherwhite(g), (v)->marked)\n\n#define changewhite(x)\t((x)->marked ^= WHITEBITS)\n#define gray2black(x)\tl_setbit((x)->marked, BLACKBIT)\n\n#define luaC_white(g)\tcast(lu_byte, (g)->currentwhite & WHITEBITS)\n\n\n/*\n** Does one step of collection when debt becomes positive. '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#define luaC_condGC(L,pre,pos) \\\n\t{ if (G(L)->GCdebt > 0) { pre; luaC_step(L); pos;}; \\\n\t  condchangemem(L,pre,pos); }\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_barrier(L,p,v) (  \\\n\t(iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ?  \\\n\tluaC_barrier_(L,obj2gco(p),gcvalue(v)) : cast_void(0))\n\n#define luaC_barrierback(L,p,v) (  \\\n\t(iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \\\n\tluaC_barrierback_(L,p) : cast_void(0))\n\n#define luaC_objbarrier(L,p,o) (  \\\n\t(isblack(p) && iswhite(o)) ? \\\n\tluaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0))\n\n#define luaC_upvalbarrier(L,uv) ( \\\n\t(iscollectable((uv)->v) && !upisopen(uv)) ? \\\n         luaC_upvalbarrier_(L,uv) : 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 statesmask);\nLUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);\nLUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz);\nLUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);\nLUAI_FUNC void luaC_barrierback_ (lua_State *L, Table *o);\nLUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv);\nLUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);\nLUAI_FUNC void luaC_upvdeccount (lua_State *L, UpVal *uv);\n\n\n#endif\n"
  },
  {
    "path": "src/lua/linit.c",
    "content": "/*\n** $Id: linit.c,v 1.39.1.1 2017/04/19 17:20:42 roberto Exp $\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** If you embed Lua in your program and need to open the standard\n** libraries, call luaL_openlibs in your program. If you need a\n** different set of libraries, copy this file to your project and edit\n** it to suit your needs.\n**\n** You can also *preload* libraries, so that a later 'require' can\n** open the library, which is already linked to the application.\n** For that, do the following code:\n**\n**  luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);\n**  lua_pushcfunction(L, luaopen_modname);\n**  lua_setfield(L, -2, modname);\n**  lua_pop(L, 1);  // remove PRELOAD table\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\n\n/*\n** these libs are loaded by lua.c and are readily available to any Lua\n** program\n*/\nstatic const luaL_Reg loadedlibs[] = {\n  {\"_G\", luaopen_base},\n  //{LUA_LOADLIBNAME, luaopen_package},\n  {LUA_COLIBNAME, luaopen_coroutine},\n  {LUA_TABLIBNAME, luaopen_table},\n  //{LUA_IOLIBNAME, luaopen_io},\n  //{LUA_OSLIBNAME, luaopen_os},\n  //{LUA_STRLIBNAME, luaopen_string},\n  //{LUA_MATHLIBNAME, luaopen_math},\n  //{LUA_UTF8LIBNAME, luaopen_utf8},\n  //{LUA_DBLIBNAME, luaopen_debug},\n#if defined(LUA_COMPAT_BITLIB)\n  {LUA_BITLIBNAME, luaopen_bit32},\n#endif\n  {NULL, NULL}\n};\n\n\nLUALIB_API void luaL_openlibs (lua_State *L) {\n  const luaL_Reg *lib;\n  /* \"require\" functions from 'loadedlibs' and set results to global table */\n  for (lib = loadedlibs; lib->func; lib++) {\n    luaL_requiref(L, lib->name, lib->func, 1);\n    lua_pop(L, 1);  /* remove lib */\n  }\n}\n\n"
  },
  {
    "path": "src/lua/liolib.c",
    "content": "/*\n** $Id: liolib.c,v 2.151.1.1 2017/04/19 17:29:57 roberto Exp $\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\n\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 != '+' || (++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#else\t\t\t\t/* }{ */\n\n/* ISO C definitions */\n#define l_popen(L,c,m)  \\\n\t  ((void)((void)c, 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\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)\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#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    lua_pushnil(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 (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_newuserdata(L, sizeof(LStream));\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 standard 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  int res = fclose(p->f);\n  return luaL_fileresult(L, (res == 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 (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  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  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  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  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 (isclosed(p))\n    luaL_error(L, \"standard %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\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_pushinteger(L, n);  /* number of arguments to read */\n  lua_pushboolean(L, toclose);  /* close/not close file when finished */\n  lua_rotate(L, 2, 2);  /* move 'n' and 'toclose' 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\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);\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 (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++] = 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 signal */\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 signal */\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 (lua_stringtonumber(L, rn.buff))  /* is this a valid number? */\n    return 1;  /* ok */\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 = '\\0';\n  luaL_buffinit(L, &b);\n  while (c != EOF && c != '\\n') {  /* repeat until end of line */\n    char *buff = luaL_prepbuffer(&b);  /* preallocate buffer */\n    int 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++] = c;\n    l_unlockfile(f);\n    luaL_addsize(&b, i);\n  }\n  if (!chop && c == '\\n')  /* want a newline and have one? */\n    luaL_addchar(&b, c);  /* 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 success;\n  int n;\n  clearerr(f);\n  if (nargs == 0) {  /* no arguments? */\n    success = read_line(L, f, 1);\n    n = first+1;  /* to return 1 result */\n  }\n  else {  /* 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    lua_pushnil(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\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 nil: 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);\n      lua_pushvalue(L, lua_upvalueindex(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  int status = 1;\n  for (; nargs--; arg++) {\n    if (lua_type(L, arg) == LUA_TNUMBER) {\n      /* optimization: could be done exactly as for strings */\n      int len = lua_isinteger(L, arg)\n                ? fprintf(f, LUA_INTEGER_FMT,\n                             (LUAI_UACINT)lua_tointeger(L, arg))\n                : fprintf(f, LUA_NUMBER_FMT,\n                             (LUAI_UACNUMBER)lua_tonumber(L, arg));\n      status = status && (len > 0);\n    }\n    else {\n      size_t l;\n      const char *s = luaL_checklstring(L, arg, &l);\n      status = status && (fwrite(s, sizeof(char), l, f) == l);\n    }\n  }\n  if (status) return 1;  /* file handle already on stack top */\n  else return luaL_fileresult(L, status, NULL);\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  op = l_fseek(f, offset, mode[op]);\n  if (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 = setvbuf(f, NULL, mode[op], (size_t)sz);\n  return luaL_fileresult(L, res == 0, NULL);\n}\n\n\n\nstatic int io_flush (lua_State *L) {\n  return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);\n}\n\n\nstatic int f_flush (lua_State *L) {\n  return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);\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 flib[] = {\n  {\"close\", f_close},\n  {\"flush\", f_flush},\n  {\"lines\", f_lines},\n  {\"read\", f_read},\n  {\"seek\", f_seek},\n  {\"setvbuf\", f_setvbuf},\n  {\"write\", f_write},\n  {\"__gc\", f_gc},\n  {\"__tostring\", f_tostring},\n  {NULL, NULL}\n};\n\n\nstatic void createmeta (lua_State *L) {\n  luaL_newmetatable(L, LUA_FILEHANDLE);  /* create metatable for file handles */\n  lua_pushvalue(L, -1);  /* push metatable */\n  lua_setfield(L, -2, \"__index\");  /* metatable.__index = metatable */\n  luaL_setfuncs(L, flib, 0);  /* add file methods to new metatable */\n  lua_pop(L, 1);  /* pop new 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  lua_pushnil(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": "src/lua/llex.c",
    "content": "/*\n** $Id: llex.c,v 2.96.1.1 2017/04/19 17:20:42 roberto Exp $\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) (ls->current = zgetc(ls->z))\n\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\", \"goto\", \"if\",\n    \"in\", \"local\", \"nil\", \"not\", \"or\", \"repeat\",\n    \"return\", \"then\", \"true\", \"until\", \"while\",\n    \"//\", \"..\", \"...\", \"==\", \">=\", \"<=\", \"~=\", \"!=\",\n    \"+=\", \"-=\", \"*=\", \"/=\",\n    \"<<\", \">>\", \"::\", \"<eof>\", \"<eol>\"\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;\n    if (luaZ_sizebuffer(b) >= MAX_SIZE/2)\n      lexerror(ls, \"lexical element too long\", 0);\n    newsize = luaZ_sizebuffer(b) * 2;\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    lua_assert(token == cast_uchar(token));\n    return luaO_pushfstring(ls->L, \"'%c'\", 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** creates a new string and anchors it in scanner's table so that\n** it will not be collected until the end of the compilation\n** (by that time it should be anchored somewhere)\n*/\nTString *luaX_newstring (LexState *ls, const char *str, size_t l) {\n  lua_State *L = ls->L;\n  TValue *o;  /* entry for 'str' */\n  TString *ts = luaS_newlstr(L, str, l);  /* create new string */\n  setsvalue2s(L, L->top++, ts);  /* temporarily anchor it in stack */\n  o = luaH_set(L, ls->h, L->top - 1);\n  if (ttisnil(o)) {  /* not in use yet? */\n    /* boolean value does not need GC barrier;\n       table has no metatable, so it does not need to invalidate cache */\n    setbvalue(o, 1);  /* t[string] = true */\n    luaC_checkGC(L);\n  }\n  else {  /* string already present */\n    ts = tsvalue(keyfromval(o));  /* re-use value previously stored */\n  }\n  L->top--;  /* remove string from stack */\n  return ts;\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 >= MAX_INT)\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  ls->envn = luaS_newliteral(L, LUA_ENV);  /* get env name */\n  ls->ignorenewline = 1;\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.\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 part? */\n      check_next2(ls, \"-+\");  /* optional exponent sign */\n    if (lisxdigit(ls->current))\n      save_and_next(ls);\n    else if (ls->current == '.')\n      save_and_next(ls);\n    else break;\n  }\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** skip a sequence '[=*[' or ']=*]'; if sequence is well formed, return\n** its number of '='s; otherwise, return a negative number (-1 iff there\n** are no '='s after initial bracket)\n*/\nstatic int skip_sep (LexState *ls) {\n  int 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 : (-count) - 1;\n}\n\n\nstatic void read_long_string (LexState *ls, SemInfo *seminfo, int 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) + (2 + sep),\n                                     luaZ_bufflen(ls->buff) - 2*(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\nstatic unsigned long readutf8esc (LexState *ls) {\n  unsigned long r;\n  int i = 4;  /* chars to be removed: '\\', 'u', '{', and first digit */\n  save_and_next(ls);  /* skip 'u' */\n  esccheck(ls, ls->current == '{', \"missing '{'\");\n  r = gethexa(ls);  /* must have at least one digit */\n  while ((save_and_next(ls), lisxdigit(ls->current))) {\n    i++;\n    r = (r << 4) + luaO_hexavalue(ls->current);\n    esccheck(ls, r <= 0x10FFFF, \"UTF-8 value too large\");\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        if (ls->ignorenewline)\n          break;\n        return TK_EOL;\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 != '-')\n        {\n          if (check_next1(ls, '=')) return TK_ASSSUB;\n          return '-';\n        }\n        /* else is a comment */\n        next(ls);\n        if (ls->current == '[') {  /* long comment? */\n          int sep = skip_sep(ls);\n          luaZ_resetbuffer(ls->buff);  /* 'skip_sep' may dirty the buffer */\n          if (sep >= 0) {\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        int sep = skip_sep(ls);\n        if (sep >= 0) {\n          read_long_string(ls, seminfo, sep);\n          return TK_STRING;\n        }\n        else if (sep != -1)  /* '[=...' 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 if (check_next1(ls, '=')) return TK_ASSDIV;\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        next(ls);\n        return TK_NE2;\n      }\n      case '+': {\n        next(ls);\n        if (check_next1(ls, '='))\n          return TK_ASSADD;\n        else return '+';\n      }\n      case '*': {\n        next(ls);\n        if (check_next1(ls, '=')) return TK_ASSMUL;\n        else return '*';\n      }\n      case '%': {\n        next(ls);\n        if (check_next1(ls, '=')) return TK_ASSMOD;\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      /* special glyphs */\n      case 0xE2:\n      case 0xF0:\n      {\n\n        static char down_arrow[]  = { 0xe2, 0xac, 0x87, 0xef, 0xb8, 0x8f };\n        static char up_arrow[]    = { 0xe2, 0xac, 0x86, 0xef, 0xb8, 0x8f };\n        static char left_arrow[]  = { 0xe2, 0xac, 0x85, 0xef, 0xb8, 0x8f };\n        static char right_arrow[] = { 0xe2, 0x9e, 0xa1, 0xef, 0xb8, 0x8f };\n        static char x_button[]    = { 0xe2, 0x9d, 0x8e };\n        static char o_button[] = { 0xf0, 0x9f, 0x85, 0xbe, 0xef, 0xb8, 0x8f };\n\n        static size_t lengths[] = { 6, 6, 6, 6, 3, 7 };\n        static const char* keys[] = { down_arrow, up_arrow, left_arrow, right_arrow, x_button, o_button };\n        static const int value[] = { 3, 2, 0, 1,5, 4 };\n\n        int anyValid = 1;\n\n        do\n        {\n          save_and_next(ls);\n\n          anyValid = 0;\n          int i;\n          for (i = 0; i < sizeof(keys) / sizeof(keys[0]); ++i)\n          {\n            if (memcmp(ls->buff->buffer, keys[i], ls->buff->n) == 0)\n            {\n              if (ls->buff->n == lengths[i])\n              {\n                seminfo->i = value[i];\n                return TK_INT;\n              }\n              else\n                anyValid = 1;\n            }\n          }\n        } while (anyValid);\n\n      }\n      case 0x8B:\n      {\n        next(ls);\n        seminfo->i = 0;\n        return TK_INT;\n      }\n      case 0x91:\n      {\n        next(ls);\n        seminfo->i = 1;\n        return TK_INT;\n      }\n      case 0x94:\n      {\n        next(ls);\n        seminfo->i = 2;\n        return TK_INT;\n      }\n      case 0x83:\n      {\n        next(ls);\n        seminfo->i = 3;\n        return TK_INT;\n      }\n      case 0x8e:\n      {\n        next(ls);\n        seminfo->i = 4;\n        return TK_INT;\n      }\n      case 0x97:\n      {\n        next(ls);\n        seminfo->i = 5;\n        return TK_INT;\n      }\n\n      case '?':\n      {\n        //TODO FIXME: print with ? consume the whole line for now, so it's not executed\n        while (!check_next1(ls, '\\n'))\n          next(ls);\n        continue;\n      }\n\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          ts = luaX_newstring(ls, luaZ_buffer(ls->buff),\n                                  luaZ_bufflen(ls->buff));\n          seminfo->ts = ts;\n          if (isreserved(ts))  /* reserved word? */\n            return ts->extra - 1 + FIRST_RESERVED;\n          else {\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"
  },
  {
    "path": "src/lua/llex.h",
    "content": "/*\n** $Id: llex.h,v 1.79.1.1 2017/04/19 17:20:42 roberto Exp $\n** Lexical Analyzer\n** See Copyright Notice in lua.h\n*/\n\n#ifndef llex_h\n#define llex_h\n\n#include \"lobject.h\"\n#include \"lzio.h\"\n\n\n#define FIRST_RESERVED\t257\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_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,\n  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, TK_NE2,\n  TK_ASSADD, TK_ASSSUB, TK_ASSMUL, TK_ASSDIV, TK_ASSMOD,\n  TK_SHL, TK_SHR,\n  TK_DBCOLON, TK_EOS, TK_EOL,\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 lexer plus state of the parser when shared by all\n   functions */\ntypedef struct LexState {\n  int ignorenewline;\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} 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": "src/lua/llimits.h",
    "content": "/*\n** $Id: llimits.h,v 1.141.1.1 2017/04/19 17:20:42 roberto Exp $\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** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count\n** the total memory used by Lua (in bytes). Usually, 'size_t' and\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_UMEM lu_mem;\ntypedef LUAI_MEM l_mem;\n#elif LUAI_BITSINT >= 32\t/* }{ */\ntypedef size_t lu_mem;\ntypedef ptrdiff_t l_mem;\n#else  /* 16-bit ints */\t/* }{ */\ntypedef unsigned long lu_mem;\ntypedef long l_mem;\n#endif\t\t\t\t/* } */\n\n\n/* chars used as small naturals (so that 'char' is reserved for characters) */\ntypedef unsigned char lu_byte;\n\n\n/* maximum value for size_t */\n#define MAX_SIZET\t((size_t)(~(size_t)0))\n\n/* maximum size visible for Lua (must be representable in a lua_Integer */\n#define MAX_SIZE\t(sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \\\n                          : (size_t)(LUA_MAXINTEGER))\n\n\n#define MAX_LUMEM\t((lu_mem)(~(lu_mem)0))\n\n#define MAX_LMEM\t((l_mem)(MAX_LUMEM >> 1))\n\n\n#define MAX_INT\t\tINT_MAX  /* maximum value of an int */\n\n\n/*\n** conversion of pointer to unsigned integer:\n** this is for hashing only; there is no problem if the integer\n** cannot hold the whole pointer value\n*/\n#define point2uint(p)\t((unsigned int)((size_t)(p) & UINT_MAX))\n\n\n\n/* type to ensure maximum alignment */\n#if defined(LUAI_USER_ALIGNMENT_T)\ntypedef LUAI_USER_ALIGNMENT_T L_Umaxalign;\n#else\ntypedef union {\n  lua_Number n;\n  double u;\n  void *s;\n  lua_Integer i;\n  long l;\n} L_Umaxalign;\n#endif\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/* internal assertions for in-house debugging */\n#if defined(lua_assert)\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)\t((c) ? (void)0 : lua_assert(0))\n#else\n#define lua_assert(c)\t\t((void)0)\n#define check_exp(c,e)\t\t(e)\n#define lua_longassert(c)\t((void)0)\n#endif\n\n/*\n** assertion for checking API calls\n*/\n#if !defined(luai_apicheck)\n#define luai_apicheck(l,e)\tlua_assert(e)\n#endif\n\n#define api_check(l,e,msg)\tluai_apicheck(l,(e) && msg)\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_byte(i)\tcast(lu_byte, (i))\n#define cast_num(i)\tcast(lua_Number, (i))\n#define cast_int(i)\tcast(int, (i))\n#define cast_uchar(i)\tcast(unsigned char, (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/*\n** non-return type\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\n\n/*\n** maximum depth for nested C calls and syntactical nested non-terminals\n** in a program. (Value must fit in an unsigned short int.)\n*/\n#if !defined(LUAI_MAXCCALLS)\n#define LUAI_MAXCCALLS\t\t200\n#endif\n\n\n\n/*\n** type for virtual-machine instructions;\n** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)\n*/\n#if LUAI_BITSINT >= 32\ntypedef unsigned int Instruction;\n#else\ntypedef unsigned long Instruction;\n#endif\n\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** 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\t128\n#endif\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 (M == 1\n** makes a direct cache.)\n*/\n#if !defined(STRCACHE_N)\n#define STRCACHE_N\t\t53\n#define STRCACHE_M\t\t2\n#endif\n\n\n/* minimum size for string buffer */\n#if !defined(LUA_MINBUFFER)\n#define LUA_MINBUFFER\t32\n#endif\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** 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\n/*\n** these macros allow user-specific actions on threads when you defined\n** LUAI_EXTRASPACE and need to do something extra when a thread is\n** created/deleted/resumed/yielded.\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#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** 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'; this definition gives NaN when\n** 'b' is huge, but the result should be 'a'. 'fmod' gives the result of\n** 'a - trunc(a/b)*b', and therefore must be corrected when 'trunc(a/b)\n** ~= floor(a/b)'. That happens when the division has a non-integer\n** negative result, which is equivalent to the test below.\n*/\n#if !defined(luai_nummod)\n#define luai_nummod(L,a,b,m)  \\\n  { (m) = l_mathop(fmod)(a,b); if ((m)*(b) < 0) (m) += (b); }\n#endif\n\n/* exponentiation */\n#if !defined(luai_numpow)\n#define luai_numpow(L,a,b)      ((void)L, 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_numisnan(a)        (!luai_numeq((a), (a)))\n#endif\n\n\n\n\n\n/*\n** macro to control inclusion of some hard tests on stack reallocation\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\t{ int sz_ = (L)->stacksize; pre; luaD_reallocstack((L), sz_); pos; }\n#endif\n\n#if !defined(HARDMEMTESTS)\n#define condchangemem(L,pre,pos)\t((void)0)\n#else\n#define condchangemem(L,pre,pos)  \\\n\t{ if (G(L)->gcrunning) { pre; luaC_fullgc(L, 0); pos; } }\n#endif\n\n#endif\n"
  },
  {
    "path": "src/lua/lmathlib.c",
    "content": "/*\n** $Id: lmathlib.c,v 1.119.1.1 2017/04/19 17:20:42 roberto Exp $\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 <stdlib.h>\n#include <math.h>\n\n#include \"lua.h\"\n\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n\n\n#undef PI\n#define PI\t(l_mathop(3.141592653589793238462643383279502884))\n\n\n#if !defined(l_rand)\t\t/* { */\n#if defined(LUA_USE_POSIX)\n#define l_rand()\trandom()\n#define l_srand(x)\tsrandom(x)\n#define L_RANDMAX\t2147483647\t/* (2^31 - 1), following POSIX */\n#else\n#define l_rand()\trand()\n#define l_srand(x)\tsrand(x)\n#define L_RANDMAX\tRAND_MAX\n#endif\n#endif\t\t\t\t/* } */\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\nstatic int math_sin (lua_State *L) {\n  lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1)));\n  return 1;\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\nstatic int math_tan (lua_State *L) {\n  lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1)));\n  return 1;\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\nstatic int math_acos (lua_State *L) {\n  lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1)));\n  return 1;\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 (valid)\n    lua_pushinteger(L, n);\n  else {\n    luaL_checkany(L, 1);\n    lua_pushnil(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 ceil */\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\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); 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\nstatic int math_exp (lua_State *L) {\n  lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1)));\n  return 1;\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\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_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/*\n** This function uses 'double' (instead of 'lua_Number') to ensure that\n** all bits from 'l_rand' can be represented, and that 'RANDMAX + 1.0'\n** will keep full precision (ensuring that 'r' is always less than 1.0.)\n*/\nstatic int math_random (lua_State *L) {\n  lua_Integer low, up;\n  double r = (double)l_rand() * (1.0 / ((double)L_RANDMAX + 1.0));\n  switch (lua_gettop(L)) {  /* check number of arguments */\n    case 0: {  /* no arguments */\n      lua_pushnumber(L, (lua_Number)r);  /* Number between 0 and 1 */\n      return 1;\n    }\n    case 1: {  /* only upper limit */\n      low = 1;\n      up = luaL_checkinteger(L, 1);\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  luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1,\n                   \"interval too large\");\n  r *= (double)(up - low) + 1.0;\n  lua_pushinteger(L, (lua_Integer)r + low);\n  return 1;\n}\n\n\nstatic int math_randomseed (lua_State *L) {\n  l_srand((unsigned int)(lua_Integer)luaL_checknumber(L, 1));\n  (void)l_rand(); /* discard first value to avoid undesirable correlations */\n  return 0;\n}\n\n\nstatic int math_type (lua_State *L) {\n  if (lua_type(L, 1) == LUA_TNUMBER) {\n      if (lua_isinteger(L, 1))\n        lua_pushliteral(L, \"integer\");\n      else\n        lua_pushliteral(L, \"float\");\n  }\n  else {\n    luaL_checkany(L, 1);\n    lua_pushnil(L);\n  }\n  return 1;\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_frexp (lua_State *L) {\n  int e;\n  lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e));\n  lua_pushinteger(L, e);\n  return 2;\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\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  {\"ult\",   math_ult},\n  {\"log\",   math_log},\n  {\"max\",   math_max},\n  {\"min\",   math_min},\n  {\"modf\",   math_modf},\n  {\"rad\",   math_rad},\n  {\"random\",     math_random},\n  {\"randomseed\", math_randomseed},\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  {\"frexp\", math_frexp},\n  {\"ldexp\", math_ldexp},\n  {\"log10\", math_log10},\n#endif\n  /* placeholders */\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  return 1;\n}\n\n"
  },
  {
    "path": "src/lua/lmem.c",
    "content": "/*\n** $Id: lmem.c,v 1.91.1.1 2017/04/19 17:20:42 roberto Exp $\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, NULL, x, s) creates a new block of size 's' (no\n** matter 'x').\n**\n** * frealloc(ud, p, x, 0) frees the block 'p'\n** (in this specific case, frealloc must return NULL);\n** particularly, frealloc(ud, NULL, 0, 0) does nothing\n** (which is equivalent to free(NULL) in ISO C)\n**\n** frealloc returns NULL if it cannot create or reallocate the area\n** (any reallocation to an equal or smaller size cannot fail!)\n*/\n\n\n\n#define MINSIZEARRAY\t4\n\n\nvoid *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,\n                     int limit, const char *what) {\n  void *newblock;\n  int newsize;\n  if (*size >= limit/2) {  /* cannot double it? */\n    if (*size >= limit)  /* cannot grow even a little? */\n      luaG_runerror(L, \"too many %s (limit is %d)\", what, limit);\n    newsize = limit;  /* still have at least one free place */\n  }\n  else {\n    newsize = (*size)*2;\n    if (newsize < MINSIZEARRAY)\n      newsize = MINSIZEARRAY;  /* minimum size */\n  }\n  newblock = luaM_reallocv(L, block, *size, newsize, size_elems);\n  *size = newsize;  /* update only when everything else is OK */\n  return newblock;\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/*\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  size_t realosize = (block) ? osize : 0;\n  lua_assert((realosize == 0) == (block == NULL));\n#if defined(HARDMEMTESTS)\n  if (nsize > realosize && g->gcrunning)\n    luaC_fullgc(L, 1);  /* force a GC whenever possible */\n#endif\n  newblock = (*g->frealloc)(g->ud, block, osize, nsize);\n  if (newblock == NULL && nsize > 0) {\n    lua_assert(nsize > realosize);  /* cannot fail when shrinking a block */\n    if (g->version) {  /* is state fully built? */\n      luaC_fullgc(L, 1);  /* try to free some memory... */\n      newblock = (*g->frealloc)(g->ud, block, osize, nsize);  /* try again */\n    }\n    if (newblock == NULL)\n      luaD_throw(L, LUA_ERRMEM);\n  }\n  lua_assert((nsize == 0) == (newblock == NULL));\n  g->GCdebt = (g->GCdebt + nsize) - realosize;\n  return newblock;\n}\n\n"
  },
  {
    "path": "src/lua/lmem.h",
    "content": "/*\n** $Id: lmem.h,v 1.43.1.1 2017/04/19 17:20:42 roberto Exp $\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/*\n** This macro reallocs a vector 'b' from 'on' to 'n' elements, where\n** each element has size 'e'. In case of arithmetic overflow of the\n** product 'n'*'e', it raises an error (calling 'luaM_toobig'). Because\n** 'e' is always constant, it avoids the runtime division MAX_SIZET/(e).\n**\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_reallocv(L,b,on,n,e) \\\n  (((sizeof(n) >= sizeof(size_t) && cast(size_t, (n)) + 1 > MAX_SIZET/(e)) \\\n      ? luaM_toobig(L) : cast_void(0)) , \\\n   luaM_realloc_(L, (b), (on)*(e), (n)*(e)))\n\n/*\n** Arrays of chars do not need any test\n*/\n#define luaM_reallocvchar(L,b,on,n)  \\\n    cast(char *, luaM_realloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char)))\n\n#define luaM_freemem(L, b, s)\tluaM_realloc_(L, (b), (s), 0)\n#define luaM_free(L, b)\t\tluaM_realloc_(L, (b), sizeof(*(b)), 0)\n#define luaM_freearray(L, b, n)   luaM_realloc_(L, (b), (n)*sizeof(*(b)), 0)\n\n#define luaM_malloc(L,s)\tluaM_realloc_(L, NULL, 0, (s))\n#define luaM_new(L,t)\t\tcast(t *, luaM_malloc(L, sizeof(t)))\n#define luaM_newvector(L,n,t) \\\n\t\tcast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t)))\n\n#define luaM_newobject(L,tag,s)\tluaM_realloc_(L, NULL, tag, (s))\n\n#define luaM_growvector(L,v,nelems,size,t,limit,e) \\\n          if ((nelems)+1 > (size)) \\\n            ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e)))\n\n#define luaM_reallocvector(L, v,oldn,n,t) \\\n   ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, 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_growaux_ (lua_State *L, void *block, int *size,\n                               size_t size_elem, int limit,\n                               const char *what);\n\n#endif\n\n"
  },
  {
    "path": "src/lua/loadlib.c",
    "content": "/*\n** $Id: loadlib.c,v 1.130.1.1 2017/04/19 17:20:42 roberto Exp $\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\n\n/*\n** LUA_IGMARK is a mark to ignore all before it when building the\n** luaopen_ function name.\n*/\n#if !defined (LUA_IGMARK)\n#define LUA_IGMARK\t\t\"-\"\n#endif\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** unique key for table in the registry that keeps handles\n** for all loaded C libraries\n*/\nstatic const int CLIBS = 0;\n\n#define LIB_FAIL\t\"open\"\n\n\n#define setprogdir(L)           ((void)0)\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** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,\n** NetBSD, AIX 4.2, HPUX 11, and  probably most other Unix flavors, at least\n** as an emulation layer on top of native functions.\n** =========================================================================\n*/\n\n#include <dlfcn.h>\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__ (lua_CFunction)(p))\n#else\n#define cast_func(p) ((lua_CFunction)(p))\n#endif\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 (lib == NULL) 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_func(dlsym(lib, sym));\n  if (f == NULL) 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 = (lua_CFunction)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#define AUXMARK         \"\\1\"\t/* auxiliary mark */\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\n*/\nstatic void setpath (lua_State *L, const char *fieldname,\n                                   const char *envname,\n                                   const char *dft) {\n  const char *nver = lua_pushfstring(L, \"%s%s\", envname, LUA_VERSUFFIX);\n  const char *path = getenv(nver);  /* use versioned name */\n  if (path == NULL)  /* no environment variable? */\n    path = getenv(envname);  /* try unversioned name */\n  if (path == NULL || noenv(L))  /* no environment variable? */\n    lua_pushstring(L, dft);  /* use default */\n  else {\n    /* replace \";;\" by \";AUXMARK;\" and then AUXMARK by default path */\n    path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP,\n                              LUA_PATH_SEP AUXMARK LUA_PATH_SEP);\n    luaL_gsub(L, path, AUXMARK, dft);\n    lua_remove(L, -2); /* remove result from 1st 'gsub' */\n  }\n  setprogdir(L);\n  lua_setfield(L, -3, fieldname);  /* package[fieldname] = path value */\n  lua_pop(L, 1);  /* pop versioned variable name */\n}\n\n/* }================================================================== */\n\n\n/*\n** return registry.CLIBS[path]\n*/\nstatic void *checkclib (lua_State *L, const char *path) {\n  void *plib;\n  lua_rawgetp(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** registry.CLIBS[path] = plib        -- for queries\n** registry.CLIBS[#CLIBS + 1] = plib  -- also keep a list of all libraries\n*/\nstatic void addtoclib (lua_State *L, const char *path, void *plib) {\n  lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);\n  lua_pushlightuserdata(L, plib);\n  lua_pushvalue(L, -1);\n  lua_setfield(L, -3, path);  /* CLIBS[path] = plib */\n  lua_rawseti(L, -2, luaL_len(L, -2) + 1);  /* CLIBS[#CLIBS + 1] = plib */\n  lua_pop(L, 1);  /* pop CLIBS table */\n}\n\n\n/*\n** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib\n** handles in list CLIBS\n*/\nstatic int gctm (lua_State *L) {\n  lua_Integer n = luaL_len(L, 1);\n  for (; n >= 1; n--) {  /* for each handle, in reverse order */\n    lua_rawgeti(L, 1, n);  /* get handle CLIBS[n] */\n    lsys_unloadlib(lua_touserdata(L, -1));\n    lua_pop(L, 1);  /* pop handle */\n  }\n  return 0;\n}\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 and 'true' or a function in the stack; in case of\n** errors, return an error code and 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 (stat == 0)  /* no errors? */\n    return 1;  /* return the loaded function */\n  else {  /* error; error message is on stack top */\n    lua_pushnil(L);\n    lua_insert(L, -2);\n    lua_pushstring(L, (stat == ERRLIB) ?  LIB_FAIL : \"init\");\n    return 3;  /* return nil, 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\nstatic const char *pushnexttemplate (lua_State *L, const char *path) {\n  const char *l;\n  while (*path == *LUA_PATH_SEP) path++;  /* skip separators */\n  if (*path == '\\0') return NULL;  /* no more templates */\n  l = strchr(path, *LUA_PATH_SEP);  /* find next separator */\n  if (l == NULL) l = path + strlen(path);\n  lua_pushlstring(L, path, l - path);  /* template */\n  return l;\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 msg;  /* to build error message */\n  luaL_buffinit(L, &msg);\n  if (*sep != '\\0')  /* non-empty separator? */\n    name = luaL_gsub(L, name, sep, dirsep);  /* replace it by 'dirsep' */\n  while ((path = pushnexttemplate(L, path)) != NULL) {\n    const char *filename = luaL_gsub(L, lua_tostring(L, -1),\n                                     LUA_PATH_MARK, name);\n    lua_remove(L, -2);  /* remove path template */\n    if (readable(filename))  /* does file exist and is readable? */\n      return filename;  /* return that file name */\n    lua_pushfstring(L, \"\\n\\tno file '%s'\", filename);\n    lua_remove(L, -2);  /* remove file name */\n    luaL_addvalue(&msg);  /* concatenate error msg. entry */\n  }\n  luaL_pushresult(&msg);  /* 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    lua_pushnil(L);\n    lua_insert(L, -2);\n    return 2;  /* return nil + 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 (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 (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, 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, 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, \"\\n\\tno 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, \"\\n\\tno field package.preload['%s']\", name);\n  return 1;\n}\n\n\nstatic void findloader (lua_State *L, const char *name) {\n  int i;\n  luaL_Buffer msg;  /* to build error message */\n  luaL_buffinit(L, &msg);\n  /* push 'package.searchers' to index 3 in the stack */\n  if (lua_getfield(L, lua_upvalueindex(1), \"searchers\") != LUA_TTABLE)\n    luaL_error(L, \"'package.searchers' must be a table\");\n  /*  iterate over available searchers to find a loader */\n  for (i = 1; ; i++) {\n    if (lua_rawgeti(L, 3, i) == LUA_TNIL) {  /* no more searchers? */\n      lua_pop(L, 1);  /* remove nil */\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    }\n    else\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_pushstring(L, name);  /* pass name as argument to module loader */\n  lua_insert(L, -2);  /* name is 1st argument (before search data) */\n  lua_call(L, 2, 1);  /* run loader to load module */\n  if (!lua_isnil(L, -1))  /* non-nil return? */\n    lua_setfield(L, 2, name);  /* LOADED[name] = returned value */\n  if (lua_getfield(L, 2, name) == LUA_TNIL) {   /* module set no value? */\n    lua_pushboolean(L, 1);  /* use true as result */\n    lua_pushvalue(L, -1);  /* extra copy to be returned */\n    lua_setfield(L, 2, name);  /* LOADED[name] = true */\n  }\n  return 1;\n}\n\n/* }====================================================== */\n\n\n\n/*\n** {======================================================\n** 'module' function\n** =======================================================\n*/\n#if defined(LUA_COMPAT_MODULE)\n\n/*\n** changes the environment variable of calling function\n*/\nstatic void set_env (lua_State *L) {\n  lua_Debug ar;\n  if (lua_getstack(L, 1, &ar) == 0 ||\n      lua_getinfo(L, \"f\", &ar) == 0 ||  /* get calling function */\n      lua_iscfunction(L, -1))\n    luaL_error(L, \"'module' not called from a Lua function\");\n  lua_pushvalue(L, -2);  /* copy new environment table to top */\n  lua_setupvalue(L, -2, 1);\n  lua_pop(L, 1);  /* remove function */\n}\n\n\nstatic void dooptions (lua_State *L, int n) {\n  int i;\n  for (i = 2; i <= n; i++) {\n    if (lua_isfunction(L, i)) {  /* avoid 'calling' extra info. */\n      lua_pushvalue(L, i);  /* get option (a function) */\n      lua_pushvalue(L, -2);  /* module */\n      lua_call(L, 1, 0);\n    }\n  }\n}\n\n\nstatic void modinit (lua_State *L, const char *modname) {\n  const char *dot;\n  lua_pushvalue(L, -1);\n  lua_setfield(L, -2, \"_M\");  /* module._M = module */\n  lua_pushstring(L, modname);\n  lua_setfield(L, -2, \"_NAME\");\n  dot = strrchr(modname, '.');  /* look for last dot in module name */\n  if (dot == NULL) dot = modname;\n  else dot++;\n  /* set _PACKAGE as package name (full module name minus last part) */\n  lua_pushlstring(L, modname, dot - modname);\n  lua_setfield(L, -2, \"_PACKAGE\");\n}\n\n\nstatic int ll_module (lua_State *L) {\n  const char *modname = luaL_checkstring(L, 1);\n  int lastarg = lua_gettop(L);  /* last parameter */\n  luaL_pushmodule(L, modname, 1);  /* get/create module table */\n  /* check whether table already has a _NAME field */\n  if (lua_getfield(L, -1, \"_NAME\") != LUA_TNIL)\n    lua_pop(L, 1);  /* table is an initialized module */\n  else {  /* no; initialize it */\n    lua_pop(L, 1);\n    modinit(L, modname);\n  }\n  lua_pushvalue(L, -1);\n  set_env(L);\n  dooptions(L, lastarg);\n  return 1;\n}\n\n\nstatic int ll_seeall (lua_State *L) {\n  luaL_checktype(L, 1, LUA_TTABLE);\n  if (!lua_getmetatable(L, 1)) {\n    lua_createtable(L, 0, 1); /* create new metatable */\n    lua_pushvalue(L, -1);\n    lua_setmetatable(L, 1);\n  }\n  lua_pushglobaltable(L);\n  lua_setfield(L, -2, \"__index\");  /* mt.__index = _G */\n  return 0;\n}\n\n#endif\n/* }====================================================== */\n\n\n\nstatic const luaL_Reg pk_funcs[] = {\n  {\"loadlib\", ll_loadlib},\n  {\"searchpath\", ll_searchpath},\n#if defined(LUA_COMPAT_MODULE)\n  {\"seeall\", ll_seeall},\n#endif\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#if defined(LUA_COMPAT_MODULE)\n  {\"module\", ll_module},\n#endif\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, searcher_Lua, searcher_C, searcher_Croot, NULL};\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#if defined(LUA_COMPAT_LOADERS)\n  lua_pushvalue(L, -1);  /* make a copy of 'searchers' table */\n  lua_setfield(L, -3, \"loaders\");  /* put it in field 'loaders' */\n#endif\n  lua_setfield(L, -2, \"searchers\");  /* put it in field 'searchers' */\n}\n\n\n/*\n** create table CLIBS to keep track of loaded C libraries,\n** setting a finalizer to close all libraries when closing state.\n*/\nstatic void createclibstable (lua_State *L) {\n  lua_newtable(L);  /* create CLIBS table */\n  lua_createtable(L, 0, 1);  /* create metatable for CLIBS */\n  lua_pushcfunction(L, gctm);\n  lua_setfield(L, -2, \"__gc\");  /* set finalizer for CLIBS table */\n  lua_setmetatable(L, -2);\n  lua_rawsetp(L, LUA_REGISTRYINDEX, &CLIBS);  /* set CLIBS table in registry */\n}\n\n\nLUAMOD_API int luaopen_package (lua_State *L) {\n  createclibstable(L);\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": "src/lua/lobject.c",
    "content": "/*\n** $Id: lobject.c,v 2.113.1.1 2017/04/19 17:29:57 roberto Exp $\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 <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\nLUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT};\n\n\n/*\n** converts an integer to a \"floating point byte\", represented as\n** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if\n** eeeee != 0 and (xxx) otherwise.\n*/\nint luaO_int2fb (unsigned int x) {\n  int e = 0;  /* exponent */\n  if (x < 8) return x;\n  while (x >= (8 << 4)) {  /* coarse steps */\n    x = (x + 0xf) >> 4;  /* x = ceil(x / 16) */\n    e += 4;\n  }\n  while (x >= (8 << 1)) {  /* fine steps */\n    x = (x + 1) >> 1;  /* x = ceil(x / 2) */\n    e++;\n  }\n  return ((e+1) << 3) | (cast_int(x) - 8);\n}\n\n\n/* converts back */\nint luaO_fb2int (int x) {\n  return (x < 8) ? x : ((x & 7) + 8) << ((x >> 3) - 1);\n}\n\n\n/*\n** Computes ceil(log2(x))\n*/\nint luaO_ceillog2 (unsigned int x) {\n  static const lu_byte log_2[256] = {  /* log_2[i] = ceil(log2(i - 1)) */\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 l + log_2[x];\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_div(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_shiftl(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: {\n      lua_Number m;\n      luai_nummod(L, v1, v2, m);\n      return m;\n    }\n    default: lua_assert(0); return 0;\n  }\n}\n\n\nvoid luaO_arith (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 (tointeger(p1, &i1) && tointeger(p2, &i2)) {\n        setivalue(res, intarith(L, op, i1, i2));\n        return;\n      }\n      else break;  /* go to the end */\n    }\n    case LUA_OPDIV: case LUA_OPPOW: {  /* operate only on floats */\n      lua_Number n1; lua_Number n2;\n      if (tonumber(p1, &n1) && tonumber(p2, &n2)) {\n        setfltvalue(res, numarith(L, op, n1, n2));\n        return;\n      }\n      else break;  /* go to the end */\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;\n      }\n      else if (tonumber(p1, &n1) && tonumber(p2, &n2)) {\n        setfltvalue(res, numarith(L, op, n1, n2));\n        return;\n      }\n      else break;  /* go to the end */\n    }\n  }\n  /* could not perform raw operation; try metamethod */\n  lua_assert(L != NULL);  /* should not fail when folding (compile time) */\n  luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));\n}\n\n\nint luaO_hexavalue (int c) {\n  if (lisdigit(c)) return c - '0';\n  else return (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 an 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 = 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(char *, s);  /* nothing is valid yet */\n  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */\n  neg = isneg(&s);  /* check signal */\n  if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X')))  /* check '0x' */\n    return 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 * cast_num(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 0.0;  /* invalid format */\n  *endptr = cast(char *, 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 signal */\n    s++;  /* skip 'p' */\n    neg1 = isneg(&s);  /* signal */\n    if (!lisdigit(cast_uchar(*s)))\n      return 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(char *, s);  /* valid up to here */\n  }\n  if (neg) r = -r;\n  return l_mathop(ldexp)(r, e);\n}\n\n#endif\n/* }====================================================== */\n\nlua_Number lua_strb2number(const char* s, char** endptr)\n{\n  if (s[0] != '0' || (s[1] != 'b' && s[1] != 'B'))\n    return 0.0f;\n\n  s += 2;\n\n  //TODO: additional checks on wrong format\n\n  lua_Number result = 0.0f;\n\n  while (*s == '0') ++s;\n  while (*s == '1' || *s == '0')\n  {\n    result *= 2.0f;\n    result += (*s == '1') ? 1 : 0;\n    ++s;\n  }\n\n  if (*s == '.')\n  {\n    int fractional = 0;\n    int digits = 0;\n    ++s;\n\n    while (*s == '1' || *s == '0')\n    {\n      fractional <<= 1;\n      fractional += (*s == '1') ? 1 : 0;\n      ++s;\n      ++digits;\n\n      float total = 1 << digits;\n      result += fractional / total;\n    }\n  }\n\n  *endptr = cast(char*, s);\n  return result;\n}\n\n/* maximum length of a numeral */\n#if !defined (L_MAXLENNUM)\n#define L_MAXLENNUM\t200\n#endif\n\nstatic const char *l_str2dloc (const char *s, lua_Number *result, int mode) {\n  char *endptr;\n\n  if (mode == 'b')\n    *result = lua_strb2number(s, &endptr);\n  else\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 if no trailing characters */\n}\n\n\n/*\n** Convert string 's' to a Lua number (put in 'result'). Return NULL\n** on fail or the address of the ending '\\0' on success.\n** 'pmode' points to (and 'mode' contains) special things in the string:\n** - 'x'/'X' means an hexadecimal numeral\n** - 'n'/'N' means 'inf' or 'nan' (which should be rejected)\n** - '.' just optimizes the search for the common case (nothing special)\n** This function accepts both the current locale or a dot as the radix\n** mark. If the convertion 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*/\nstatic const char *l_str2d (const char *s, lua_Number *result) {\n  const char *endptr;\n  const char *pmode = strpbrk(s, \".xXnNbB\");\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 (strlen(s) > L_MAXLENNUM || pdot == NULL)\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 if (s[0] == '0' && (s[1] == 'b' || s[1] == 'B')) { /* binary */\n    s += 2;\n    for (; *s == '0' || *s == '1'; s++) {\n      a = a * 2 + (*s == '0' ? 0 : 1);\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 + 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 (e - s) + 1;  /* success; return string size */\n}\n\n\nint luaO_utf8esc (char *buff, unsigned long x) {\n  int n = 1;  /* number of bytes put in buffer (backwards) */\n  lua_assert(x <= 0x10FFFF);\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/* maximum length of the conversion of a number to a string */\n#define MAXNUMBER2STR\t50\n\n\n/*\n** Convert a number object to a string\n*/\nvoid luaO_tostring (lua_State *L, StkId obj) {\n  char buff[MAXNUMBER2STR];\n  size_t len;\n  lua_assert(ttisnumber(obj));\n  if (ttisinteger(obj))\n    len = lua_integer2str(buff, sizeof(buff), ivalue(obj));\n  else {\n    len = lua_number2str(buff, sizeof(buff), fltvalue(obj));\n#if !defined(LUA_COMPAT_FLOATSTRING)\n    if (buff[strspn(buff, \"-0123456789\")] == '\\0') {  /* looks like an int? */\n      buff[len++] = lua_getlocaledecpoint();\n      buff[len++] = '0';  /* adds '.0' to result */\n    }\n#endif\n  }\n  setsvalue2s(L, obj, luaS_newlstr(L, buff, len));\n}\n\n\nstatic void pushstr (lua_State *L, const char *str, size_t l) {\n  setsvalue2s(L, L->top, luaS_newlstr(L, str, l));\n  luaD_inctop(L);\n}\n\n\n/*\n** this function handles only '%d', '%c', '%f', '%p', and '%s'\n   conventional formats, plus Lua-specific '%I' and '%U'\n*/\nconst char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {\n  int n = 0;\n  for (;;) {\n    const char *e = strchr(fmt, '%');\n    if (e == NULL) break;\n    pushstr(L, fmt, e - fmt);\n    switch (*(e+1)) {\n      case 's': {  /* zero-terminated string */\n        const char *s = va_arg(argp, char *);\n        if (s == NULL) s = \"(null)\";\n        pushstr(L, s, strlen(s));\n        break;\n      }\n      case 'c': {  /* an 'int' as a character */\n        char buff = cast(char, va_arg(argp, int));\n        if (lisprint(cast_uchar(buff)))\n          pushstr(L, &buff, 1);\n        else  /* non-printable character; print its code */\n          luaO_pushfstring(L, \"<\\\\%d>\", cast_uchar(buff));\n        break;\n      }\n      case 'd': {  /* an 'int' */\n        setivalue(L->top, va_arg(argp, int));\n        goto top2str;\n      }\n      case 'I': {  /* a 'lua_Integer' */\n        setivalue(L->top, cast(lua_Integer, va_arg(argp, l_uacInt)));\n        goto top2str;\n      }\n      case 'f': {  /* a 'lua_Number' */\n        setfltvalue(L->top, cast_num(va_arg(argp, l_uacNumber)));\n      top2str:  /* convert the top element to a string */\n        luaD_inctop(L);\n        luaO_tostring(L, L->top - 1);\n        break;\n      }\n      case 'p': {  /* a pointer */\n        char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */\n        void *p = va_arg(argp, void *);\n        int l = lua_pointer2str(buff, sizeof(buff), p);\n        pushstr(L, buff, l);\n        break;\n      }\n      case 'U': {  /* an 'int' as a UTF-8 sequence */\n        char buff[UTF8BUFFSZ];\n        int l = luaO_utf8esc(buff, cast(long, va_arg(argp, long)));\n        pushstr(L, buff + UTF8BUFFSZ - l, l);\n        break;\n      }\n      case '%': {\n        pushstr(L, \"%\", 1);\n        break;\n      }\n      default: {\n        luaG_runerror(L, \"invalid option '%%%c' to 'lua_pushfstring'\",\n                         *(e + 1));\n      }\n    }\n    n += 2;\n    fmt = e+2;\n  }\n  luaD_checkstack(L, 1);\n  pushstr(L, fmt, strlen(fmt));\n  if (n > 0) luaV_concat(L, n + 1);\n  return svalue(L->top - 1);\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  return msg;\n}\n\n\n/* number of chars of a literal string without the ending \\0 */\n#define LL(x)\t(sizeof(x)/sizeof(char) - 1)\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 bufflen) {\n  size_t l = strlen(source);\n  if (*source == '=') {  /* 'literal' source */\n    if (l <= bufflen)  /* small enough? */\n      memcpy(out, source + 1, l * 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 (l <= bufflen)  /* small enough? */\n      memcpy(out, source + 1, l * sizeof(char));\n    else {  /* add '...' before rest of name */\n      addstr(out, RETS, LL(RETS));\n      bufflen -= LL(RETS);\n      memcpy(out, source + 1 + l - 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 (l < bufflen && nl == NULL) {  /* small one-line source? */\n      addstr(out, source, l);  /* keep it */\n    }\n    else {\n      if (nl != NULL) l = nl - source;  /* stop at first newline */\n      if (l > bufflen) l = bufflen;\n      addstr(out, source, l);\n      addstr(out, RETS, LL(RETS));\n    }\n    memcpy(out, POS, (LL(POS) + 1) * sizeof(char));\n  }\n}\n\n"
  },
  {
    "path": "src/lua/lobject.h",
    "content": "/*\n** $Id: lobject.h,v 2.117.1.1 2017/04/19 17:39:34 roberto Exp $\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 tags for non-values\n*/\n#define LUA_TPROTO\tLUA_NUMTAGS\t\t/* function prototypes */\n#define LUA_TDEADKEY\t(LUA_NUMTAGS+1)\t\t/* removed keys in tables */\n\n/*\n** number of all possible tags (including LUA_TNONE but excluding DEADKEY)\n*/\n#define LUA_TOTALTAGS\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* value)\n** bits 4-5: variant bits\n** bit 6: whether value is collectable\n*/\n\n\n/*\n** LUA_TFUNCTION variants:\n** 0 - Lua function\n** 1 - light C function\n** 2 - regular C function (closure)\n*/\n\n/* Variant tags for functions */\n#define LUA_TLCL\t(LUA_TFUNCTION | (0 << 4))  /* Lua closure */\n#define LUA_TLCF\t(LUA_TFUNCTION | (1 << 4))  /* light C function */\n#define LUA_TCCL\t(LUA_TFUNCTION | (2 << 4))  /* C closure */\n\n\n/* Variant tags for strings */\n#define LUA_TSHRSTR\t(LUA_TSTRING | (0 << 4))  /* short strings */\n#define LUA_TLNGSTR\t(LUA_TSTRING | (1 << 4))  /* long strings */\n\n\n/* Variant tags for numbers */\n#define LUA_TNUMFLT\t(LUA_TNUMBER | (0 << 4))  /* float numbers */\n#define LUA_TNUMINT\t(LUA_TNUMBER | (1 << 4))  /* integer numbers */\n\n\n/* Bit mark for collectable types */\n#define BIT_ISCOLLECTABLE\t(1 << 6)\n\n/* mark a tag as collectable */\n#define ctb(t)\t\t\t((t) | BIT_ISCOLLECTABLE)\n\n\n/*\n** Common type for all collectable objects\n*/\ntypedef struct GCObject GCObject;\n\n\n/*\n** Common Header for all collectable objects (in macro form, to be\n** included in other objects)\n*/\n#define CommonHeader\tGCObject *next; lu_byte tt; lu_byte marked\n\n\n/*\n** Common type has only the common header\n*/\nstruct GCObject {\n  CommonHeader;\n};\n\n\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/*\n** Union of all Lua values\n*/\ntypedef union Value {\n  GCObject *gc;    /* collectable objects */\n  void *p;         /* light userdata */\n  int b;           /* booleans */\n  lua_CFunction f; /* light C functions */\n  lua_Integer i;   /* integer numbers */\n  lua_Number n;    /* float numbers */\n} Value;\n\n\n#define TValuefields\tValue value_; int tt_\n\n\ntypedef struct lua_TValue {\n  TValuefields;\n} TValue;\n\n\n\n/* macro defining a nil value */\n#define NILCONSTANT\t{NULL}, LUA_TNIL\n\n\n#define val_(o)\t\t((o)->value_)\n\n\n/* raw type tag of a TValue */\n#define rttype(o)\t((o)->tt_)\n\n/* tag with no variants (bits 0-3) */\n#define novariant(x)\t((x) & 0x0F)\n\n/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */\n#define ttype(o)\t(rttype(o) & 0x3F)\n\n/* type tag of a TValue with no variants (bits 0-3) */\n#define ttnov(o)\t(novariant(rttype(o)))\n\n\n/* Macros to test type */\n#define checktag(o,t)\t\t(rttype(o) == (t))\n#define checktype(o,t)\t\t(ttnov(o) == (t))\n#define ttisnumber(o)\t\tchecktype((o), LUA_TNUMBER)\n#define ttisfloat(o)\t\tchecktag((o), LUA_TNUMFLT)\n#define ttisinteger(o)\t\tchecktag((o), LUA_TNUMINT)\n#define ttisnil(o)\t\tchecktag((o), LUA_TNIL)\n#define ttisboolean(o)\t\tchecktag((o), LUA_TBOOLEAN)\n#define ttislightuserdata(o)\tchecktag((o), LUA_TLIGHTUSERDATA)\n#define ttisstring(o)\t\tchecktype((o), LUA_TSTRING)\n#define ttisshrstring(o)\tchecktag((o), ctb(LUA_TSHRSTR))\n#define ttislngstring(o)\tchecktag((o), ctb(LUA_TLNGSTR))\n#define ttistable(o)\t\tchecktag((o), ctb(LUA_TTABLE))\n#define ttisfunction(o)\t\tchecktype(o, LUA_TFUNCTION)\n#define ttisclosure(o)\t\t((rttype(o) & 0x1F) == LUA_TFUNCTION)\n#define ttisCclosure(o)\t\tchecktag((o), ctb(LUA_TCCL))\n#define ttisLclosure(o)\t\tchecktag((o), ctb(LUA_TLCL))\n#define ttislcf(o)\t\tchecktag((o), LUA_TLCF)\n#define ttisfulluserdata(o)\tchecktag((o), ctb(LUA_TUSERDATA))\n#define ttisthread(o)\t\tchecktag((o), ctb(LUA_TTHREAD))\n#define ttisdeadkey(o)\t\tchecktag((o), LUA_TDEADKEY)\n\n\n/* Macros to access values */\n#define ivalue(o)\tcheck_exp(ttisinteger(o), val_(o).i)\n#define fltvalue(o)\tcheck_exp(ttisfloat(o), val_(o).n)\n#define nvalue(o)\tcheck_exp(ttisnumber(o), \\\n\t(ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o)))\n#define gcvalue(o)\tcheck_exp(iscollectable(o), val_(o).gc)\n#define pvalue(o)\tcheck_exp(ttislightuserdata(o), val_(o).p)\n#define tsvalue(o)\tcheck_exp(ttisstring(o), gco2ts(val_(o).gc))\n#define uvalue(o)\tcheck_exp(ttisfulluserdata(o), gco2u(val_(o).gc))\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 clCvalue(o)\tcheck_exp(ttisCclosure(o), gco2ccl(val_(o).gc))\n#define fvalue(o)\tcheck_exp(ttislcf(o), val_(o).f)\n#define hvalue(o)\tcheck_exp(ttistable(o), gco2t(val_(o).gc))\n#define bvalue(o)\tcheck_exp(ttisboolean(o), val_(o).b)\n#define thvalue(o)\tcheck_exp(ttisthread(o), gco2th(val_(o).gc))\n/* a dead value may get the 'gc' field, but cannot access its contents */\n#define deadvalue(o)\tcheck_exp(ttisdeadkey(o), cast(void *, val_(o).gc))\n\n#define l_isfalse(o)\t(ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))\n\n\n#define iscollectable(o)\t(rttype(o) & BIT_ISCOLLECTABLE)\n\n\n/* Macros for internal tests */\n#define righttt(obj)\t\t(ttype(obj) == gcvalue(obj)->tt)\n\n#define checkliveness(L,obj) \\\n\tlua_longassert(!iscollectable(obj) || \\\n\t\t(righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj)))))\n\n\n/* Macros to set values */\n#define settt_(o,t)\t((o)->tt_=(t))\n\n#define setfltvalue(obj,x) \\\n  { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_TNUMFLT); }\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_TNUMINT); }\n\n#define chgivalue(obj,x) \\\n  { TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); }\n\n#define setnilvalue(obj) settt_(obj, LUA_TNIL)\n\n#define setfvalue(obj,x) \\\n  { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); }\n\n#define setpvalue(obj,x) \\\n  { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); }\n\n#define setbvalue(obj,x) \\\n  { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); }\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#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#define setuvalue(L,obj,x) \\\n  { TValue *io = (obj); Udata *x_ = (x); \\\n    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TUSERDATA)); \\\n    checkliveness(L,io); }\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_TTHREAD)); \\\n    checkliveness(L,io); }\n\n#define setclLvalue(L,obj,x) \\\n  { TValue *io = (obj); LClosure *x_ = (x); \\\n    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TLCL)); \\\n    checkliveness(L,io); }\n\n#define setclCvalue(L,obj,x) \\\n  { TValue *io = (obj); CClosure *x_ = (x); \\\n    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TCCL)); \\\n    checkliveness(L,io); }\n\n#define sethvalue(L,obj,x) \\\n  { TValue *io = (obj); Table *x_ = (x); \\\n    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTABLE)); \\\n    checkliveness(L,io); }\n\n#define setdeadvalue(obj)\tsettt_(obj, LUA_TDEADKEY)\n\n\n\n#define setobj(L,obj1,obj2) \\\n\t{ TValue *io1=(obj1); *io1 = *(obj2); \\\n\t  (void)L; checkliveness(L,io1); }\n\n\n/*\n** different types of assignments, according to destination\n*/\n\n/* from stack to (same) stack */\n#define setobjs2s\tsetobj\n/* to stack (not from same stack) */\n#define setobj2s\tsetobj\n#define setsvalue2s\tsetsvalue\n#define sethvalue2s\tsethvalue\n#define setptvalue2s\tsetptvalue\n/* from table to same table */\n#define setobjt2t\tsetobj\n/* to new object */\n#define setobj2n\tsetobj\n#define setsvalue2n\tsetsvalue\n\n/* to table (define it as an expression to be used in macros) */\n#define setobj2t(L,o1,o2)  ((void)L, *(o1)=*(o2), checkliveness(L,(o1)))\n\n\n\n\n/*\n** {======================================================\n** types and prototypes\n** =======================================================\n*/\n\n\ntypedef TValue *StkId;  /* index to stack elements */\n\n\n\n\n/*\n** Header for string value; string bytes follow the end of this structure\n** (aligned according to 'UTString'; see next).\n*/\ntypedef struct TString {\n  CommonHeader;\n  lu_byte extra;  /* reserved words for short strings; \"has hash\" for longs */\n  lu_byte shrlen;  /* length for short strings */\n  unsigned int hash;\n  union {\n    size_t lnglen;  /* length for long strings */\n    struct TString *hnext;  /* linked list for hash table */\n  } u;\n} TString;\n\n\n/*\n** Ensures that address after this type is always fully aligned.\n*/\ntypedef union UTString {\n  L_Umaxalign dummy;  /* ensures maximum alignment for strings */\n  TString tsv;\n} UTString;\n\n\n/*\n** Get the actual string (array of bytes) from a 'TString'.\n** (Access to 'extra' ensures that value is really a 'TString'.)\n*/\n#define getstr(ts)  \\\n  check_exp(sizeof((ts)->extra), cast(char *, (ts)) + sizeof(UTString))\n\n\n/* get the actual string (array of bytes) from a Lua value */\n#define svalue(o)       getstr(tsvalue(o))\n\n/* get string length from 'TString *s' */\n#define tsslen(s)\t((s)->tt == LUA_TSHRSTR ? (s)->shrlen : (s)->u.lnglen)\n\n/* get string length from 'TValue *o' */\n#define vslen(o)\ttsslen(tsvalue(o))\n\n\n/*\n** Header for userdata; memory area follows the end of this structure\n** (aligned according to 'UUdata'; see next).\n*/\ntypedef struct Udata {\n  CommonHeader;\n  lu_byte ttuv_;  /* user value's tag */\n  struct Table *metatable;\n  size_t len;  /* number of bytes */\n  union Value user_;  /* user value */\n} Udata;\n\n\n/*\n** Ensures that address after this type is always fully aligned.\n*/\ntypedef union UUdata {\n  L_Umaxalign dummy;  /* ensures maximum alignment for 'local' udata */\n  Udata uv;\n} UUdata;\n\n\n/*\n**  Get the address of memory block inside 'Udata'.\n** (Access to 'ttuv_' ensures that value is really a 'Udata'.)\n*/\n#define getudatamem(u)  \\\n  check_exp(sizeof((u)->ttuv_), (cast(char*, (u)) + sizeof(UUdata)))\n\n#define setuservalue(L,u,o) \\\n\t{ const TValue *io=(o); Udata *iu = (u); \\\n\t  iu->user_ = io->value_; iu->ttuv_ = rttype(io); \\\n\t  checkliveness(L,io); }\n\n\n#define getuservalue(L,u,o) \\\n\t{ TValue *io=(o); const Udata *iu = (u); \\\n\t  io->value_ = iu->user_; settt_(io, iu->ttuv_); \\\n\t  checkliveness(L,io); }\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} 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** Function Prototypes\n*/\ntypedef struct Proto {\n  CommonHeader;\n  lu_byte numparams;  /* number of fixed parameters */\n  lu_byte is_vararg;\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 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  int *lineinfo;  /* map from opcodes to source lines (debug information) */\n  LocVar *locvars;  /* information about local variables (debug information) */\n  Upvaldesc *upvalues;  /* upvalue information */\n  struct LClosure *cache;  /* last-created closure with this prototype */\n  TString  *source;  /* used for debug information */\n  GCObject *gclist;\n} Proto;\n\n\n\n/*\n** Lua Upvalues\n*/\ntypedef struct UpVal UpVal;\n\n\n/*\n** Closures\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 isLfunction(o)\tttisLclosure(o)\n\n#define getproto(o)\t(clLvalue(o)->p)\n\n\n/*\n** Tables\n*/\n\ntypedef union TKey {\n  struct {\n    TValuefields;\n    int next;  /* for chaining (offset for next node) */\n  } nk;\n  TValue tvk;\n} TKey;\n\n\n/* copy a value into a key without messing up field 'next' */\n#define setnodekey(L,key,obj) \\\n\t{ TKey *k_=(key); const TValue *io_=(obj); \\\n\t  k_->nk.value_ = io_->value_; k_->nk.tt_ = io_->tt_; \\\n\t  (void)L; checkliveness(L,io_); }\n\n\ntypedef struct Node {\n  TValue i_val;\n  TKey i_key;\n} Node;\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 size of 'node' array */\n  unsigned int sizearray;  /* size of 'array' array */\n  TValue *array;  /* array part */\n  Node *node;\n  Node *lastfree;  /* any free position is before this position */\n  struct Table *metatable;\n  GCObject *gclist;\n} Table;\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(int, (s) & ((size)-1)))))\n\n\n#define twoto(x)\t(1<<(x))\n#define sizenode(t)\t(twoto((t)->lsizenode))\n\n\n/*\n** (address of) a fixed nil value\n*/\n#define luaO_nilobject\t\t(&luaO_nilobject_)\n\n\nLUAI_DDEC const TValue luaO_nilobject_;\n\n/* size of buffer for 'luaO_utf8esc' function */\n#define UTF8BUFFSZ\t8\n\nLUAI_FUNC int luaO_int2fb (unsigned int x);\nLUAI_FUNC int luaO_fb2int (int x);\nLUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x);\nLUAI_FUNC int luaO_ceillog2 (unsigned int x);\nLUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1,\n                           const TValue *p2, TValue *res);\nLUAI_FUNC size_t luaO_str2num (const char *s, TValue *o);\nLUAI_FUNC int luaO_hexavalue (int c);\nLUAI_FUNC void luaO_tostring (lua_State *L, StkId 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 len);\n\n\n#endif\n\n"
  },
  {
    "path": "src/lua/lopcodes.c",
    "content": "/*\n** $Id: lopcodes.c,v 1.55.1.1 2017/04/19 17:20:42 roberto Exp $\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 <stddef.h>\n\n#include \"lopcodes.h\"\n\n\n/* ORDER OP */\n\nLUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = {\n  \"MOVE\",\n  \"LOADK\",\n  \"LOADKX\",\n  \"LOADBOOL\",\n  \"LOADNIL\",\n  \"GETUPVAL\",\n  \"GETTABUP\",\n  \"GETTABLE\",\n  \"SETTABUP\",\n  \"SETUPVAL\",\n  \"SETTABLE\",\n  \"NEWTABLE\",\n  \"SELF\",\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  \"UNM\",\n  \"BNOT\",\n  \"NOT\",\n  \"LEN\",\n  \"CONCAT\",\n  \"JMP\",\n  \"EQ\",\n  \"LT\",\n  \"LE\",\n  \"TEST\",\n  \"TESTSET\",\n  \"CALL\",\n  \"TAILCALL\",\n  \"RETURN\",\n  \"FORLOOP\",\n  \"FORPREP\",\n  \"TFORCALL\",\n  \"TFORLOOP\",\n  \"SETLIST\",\n  \"CLOSURE\",\n  \"VARARG\",\n  \"EXTRAARG\",\n  NULL\n};\n\n\n#define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m))\n\nLUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {\n/*       T  A    B       C     mode\t\t   opcode\t*/\n  opmode(0, 1, OpArgR, OpArgN, iABC)\t\t/* OP_MOVE */\n ,opmode(0, 1, OpArgK, OpArgN, iABx)\t\t/* OP_LOADK */\n ,opmode(0, 1, OpArgN, OpArgN, iABx)\t\t/* OP_LOADKX */\n ,opmode(0, 1, OpArgU, OpArgU, iABC)\t\t/* OP_LOADBOOL */\n ,opmode(0, 1, OpArgU, OpArgN, iABC)\t\t/* OP_LOADNIL */\n ,opmode(0, 1, OpArgU, OpArgN, iABC)\t\t/* OP_GETUPVAL */\n ,opmode(0, 1, OpArgU, OpArgK, iABC)\t\t/* OP_GETTABUP */\n ,opmode(0, 1, OpArgR, OpArgK, iABC)\t\t/* OP_GETTABLE */\n ,opmode(0, 0, OpArgK, OpArgK, iABC)\t\t/* OP_SETTABUP */\n ,opmode(0, 0, OpArgU, OpArgN, iABC)\t\t/* OP_SETUPVAL */\n ,opmode(0, 0, OpArgK, OpArgK, iABC)\t\t/* OP_SETTABLE */\n ,opmode(0, 1, OpArgU, OpArgU, iABC)\t\t/* OP_NEWTABLE */\n ,opmode(0, 1, OpArgR, OpArgK, iABC)\t\t/* OP_SELF */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_ADD */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_SUB */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_MUL */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_MOD */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_POW */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_DIV */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_IDIV */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_BAND */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_BOR */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_BXOR */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_SHL */\n ,opmode(0, 1, OpArgK, OpArgK, iABC)\t\t/* OP_SHR */\n ,opmode(0, 1, OpArgR, OpArgN, iABC)\t\t/* OP_UNM */\n ,opmode(0, 1, OpArgR, OpArgN, iABC)\t\t/* OP_BNOT */\n ,opmode(0, 1, OpArgR, OpArgN, iABC)\t\t/* OP_NOT */\n ,opmode(0, 1, OpArgR, OpArgN, iABC)\t\t/* OP_LEN */\n ,opmode(0, 1, OpArgR, OpArgR, iABC)\t\t/* OP_CONCAT */\n ,opmode(0, 0, OpArgR, OpArgN, iAsBx)\t\t/* OP_JMP */\n ,opmode(1, 0, OpArgK, OpArgK, iABC)\t\t/* OP_EQ */\n ,opmode(1, 0, OpArgK, OpArgK, iABC)\t\t/* OP_LT */\n ,opmode(1, 0, OpArgK, OpArgK, iABC)\t\t/* OP_LE */\n ,opmode(1, 0, OpArgN, OpArgU, iABC)\t\t/* OP_TEST */\n ,opmode(1, 1, OpArgR, OpArgU, iABC)\t\t/* OP_TESTSET */\n ,opmode(0, 1, OpArgU, OpArgU, iABC)\t\t/* OP_CALL */\n ,opmode(0, 1, OpArgU, OpArgU, iABC)\t\t/* OP_TAILCALL */\n ,opmode(0, 0, OpArgU, OpArgN, iABC)\t\t/* OP_RETURN */\n ,opmode(0, 1, OpArgR, OpArgN, iAsBx)\t\t/* OP_FORLOOP */\n ,opmode(0, 1, OpArgR, OpArgN, iAsBx)\t\t/* OP_FORPREP */\n ,opmode(0, 0, OpArgN, OpArgU, iABC)\t\t/* OP_TFORCALL */\n ,opmode(0, 1, OpArgR, OpArgN, iAsBx)\t\t/* OP_TFORLOOP */\n ,opmode(0, 0, OpArgU, OpArgU, iABC)\t\t/* OP_SETLIST */\n ,opmode(0, 1, OpArgU, OpArgN, iABx)\t\t/* OP_CLOSURE */\n ,opmode(0, 1, OpArgU, OpArgN, iABC)\t\t/* OP_VARARG */\n ,opmode(0, 0, OpArgU, OpArgU, iAx)\t\t/* OP_EXTRAARG */\n};\n\n"
  },
  {
    "path": "src/lua/lopcodes.h",
    "content": "/*\n** $Id: lopcodes.h,v 1.149.1.1 2017/04/19 17:20:42 roberto Exp $\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\n\n/*===========================================================================\n  We assume that instructions are unsigned numbers.\n  All instructions have an opcode in the first 6 bits.\n  Instructions can have the following fields:\n\t'A' : 8 bits\n\t'B' : 9 bits\n\t'C' : 9 bits\n\t'Ax' : 26 bits ('A', 'B', and 'C' together)\n\t'Bx' : 18 bits ('B' and 'C' together)\n\t'sBx' : signed Bx\n\n  A signed argument is represented in excess K; that is, the number\n  value is the unsigned value minus K. K is exactly the maximum value\n  for that argument (so that -max is represented by 0, and +max is\n  represented by 2*max), which is half the maximum for the corresponding\n  unsigned argument.\n===========================================================================*/\n\n\nenum OpMode {iABC, iABx, iAsBx, iAx};  /* basic instruction format */\n\n\n/*\n** size and position of opcode arguments.\n*/\n#define SIZE_C\t\t9\n#define SIZE_B\t\t9\n#define SIZE_Bx\t\t(SIZE_C + SIZE_B)\n#define SIZE_A\t\t8\n#define SIZE_Ax\t\t(SIZE_C + SIZE_B + SIZE_A)\n\n#define SIZE_OP\t\t6\n\n#define POS_OP\t\t0\n#define POS_A\t\t(POS_OP + SIZE_OP)\n#define POS_C\t\t(POS_A + SIZE_A)\n#define POS_B\t\t(POS_C + SIZE_C)\n#define POS_Bx\t\tPOS_C\n#define POS_Ax\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 LUAI_BITSINT-1 bits (-1 for sign)\n*/\n#if SIZE_Bx < LUAI_BITSINT-1\n#define MAXARG_Bx        ((1<<SIZE_Bx)-1)\n#define MAXARG_sBx        (MAXARG_Bx>>1)         /* 'sBx' is signed */\n#else\n#define MAXARG_Bx        MAX_INT\n#define MAXARG_sBx        MAX_INT\n#endif\n\n#if SIZE_Ax < LUAI_BITSINT-1\n#define MAXARG_Ax\t((1<<SIZE_Ax)-1)\n#else\n#define MAXARG_Ax\tMAX_INT\n#endif\n\n\n#define MAXARG_A        ((1<<SIZE_A)-1)\n#define MAXARG_B        ((1<<SIZE_B)-1)\n#define MAXARG_C        ((1<<SIZE_C)-1)\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(Instruction, o)<<POS_OP)&MASK1(SIZE_OP,POS_OP))))\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(Instruction, 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)\tgetarg(i, POS_B, SIZE_B)\n#define SETARG_B(i,v)\tsetarg(i, v, POS_B, SIZE_B)\n\n#define GETARG_C(i)\tgetarg(i, POS_C, SIZE_C)\n#define SETARG_C(i,v)\tsetarg(i, v, POS_C, SIZE_C)\n\n#define GETARG_Bx(i)\tgetarg(i, POS_Bx, SIZE_Bx)\n#define SETARG_Bx(i,v)\tsetarg(i, v, POS_Bx, SIZE_Bx)\n\n#define GETARG_Ax(i)\tgetarg(i, POS_Ax, SIZE_Ax)\n#define SETARG_Ax(i,v)\tsetarg(i, v, POS_Ax, SIZE_Ax)\n\n#define GETARG_sBx(i)\t(GETARG_Bx(i)-MAXARG_sBx)\n#define SETARG_sBx(i,b)\tSETARG_Bx((i),cast(unsigned int, (b)+MAXARG_sBx))\n\n\n#define CREATE_ABC(o,a,b,c)\t((cast(Instruction, o)<<POS_OP) \\\n\t\t\t| (cast(Instruction, a)<<POS_A) \\\n\t\t\t| (cast(Instruction, b)<<POS_B) \\\n\t\t\t| (cast(Instruction, c)<<POS_C))\n\n#define CREATE_ABx(o,a,bc)\t((cast(Instruction, o)<<POS_OP) \\\n\t\t\t| (cast(Instruction, a)<<POS_A) \\\n\t\t\t| (cast(Instruction, bc)<<POS_Bx))\n\n#define CREATE_Ax(o,a)\t\t((cast(Instruction, o)<<POS_OP) \\\n\t\t\t| (cast(Instruction, a)<<POS_Ax))\n\n\n/*\n** Macros to operate RK indices\n*/\n\n/* this bit 1 means constant (0 means register) */\n#define BITRK\t\t(1 << (SIZE_B - 1))\n\n/* test whether value is a constant */\n#define ISK(x)\t\t((x) & BITRK)\n\n/* gets the index of the constant */\n#define INDEXK(r)\t((int)(r) & ~BITRK)\n\n#if !defined(MAXINDEXRK)  /* (for debugging only) */\n#define MAXINDEXRK\t(BITRK - 1)\n#endif\n\n/* code a constant index as a RK value */\n#define RKASK(x)\t((x) | BITRK)\n\n\n/*\n** invalid register that fits in 8 bits\n*/\n#define NO_REG\t\tMAXARG_A\n\n\n/*\n** R(x) - register\n** Kst(x) - constant (in constant table)\n** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)\n*/\n\n\n/*\n** grep \"ORDER OP\" if you change these enums\n*/\n\ntypedef enum {\n/*----------------------------------------------------------------------\nname\t\targs\tdescription\n------------------------------------------------------------------------*/\nOP_MOVE,/*\tA B\tR(A) := R(B)\t\t\t\t\t*/\nOP_LOADK,/*\tA Bx\tR(A) := Kst(Bx)\t\t\t\t\t*/\nOP_LOADKX,/*\tA \tR(A) := Kst(extra arg)\t\t\t\t*/\nOP_LOADBOOL,/*\tA B C\tR(A) := (Bool)B; if (C) pc++\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*/\n\nOP_GETTABUP,/*\tA B C\tR(A) := UpValue[B][RK(C)]\t\t\t*/\nOP_GETTABLE,/*\tA B C\tR(A) := R(B)[RK(C)]\t\t\t\t*/\n\nOP_SETTABUP,/*\tA B C\tUpValue[A][RK(B)] := RK(C)\t\t\t*/\nOP_SETUPVAL,/*\tA B\tUpValue[B] := R(A)\t\t\t\t*/\nOP_SETTABLE,/*\tA B C\tR(A)[RK(B)] := RK(C)\t\t\t\t*/\n\nOP_NEWTABLE,/*\tA B C\tR(A) := {} (size = B,C)\t\t\t\t*/\n\nOP_SELF,/*\tA B C\tR(A+1) := R(B); R(A) := R(B)[RK(C)]\t\t*/\n\nOP_ADD,/*\tA B C\tR(A) := RK(B) + RK(C)\t\t\t\t*/\nOP_SUB,/*\tA B C\tR(A) := RK(B) - RK(C)\t\t\t\t*/\nOP_MUL,/*\tA B C\tR(A) := RK(B) * RK(C)\t\t\t\t*/\nOP_MOD,/*\tA B C\tR(A) := RK(B) % RK(C)\t\t\t\t*/\nOP_POW,/*\tA B C\tR(A) := RK(B) ^ RK(C)\t\t\t\t*/\nOP_DIV,/*\tA B C\tR(A) := RK(B) / RK(C)\t\t\t\t*/\nOP_IDIV,/*\tA B C\tR(A) := RK(B) // RK(C)\t\t\t\t*/\nOP_BAND,/*\tA B C\tR(A) := RK(B) & RK(C)\t\t\t\t*/\nOP_BOR,/*\tA B C\tR(A) := RK(B) | RK(C)\t\t\t\t*/\nOP_BXOR,/*\tA B C\tR(A) := RK(B) ~ RK(C)\t\t\t\t*/\nOP_SHL,/*\tA B C\tR(A) := RK(B) << RK(C)\t\t\t\t*/\nOP_SHR,/*\tA B C\tR(A) := RK(B) >> RK(C)\t\t\t\t*/\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) := length of R(B)\t\t\t\t*/\n\nOP_CONCAT,/*\tA B C\tR(A) := R(B).. ... ..R(C)\t\t\t*/\n\nOP_JMP,/*\tA sBx\tpc+=sBx; if (A) close all upvalues >= R(A - 1)\t*/\nOP_EQ,/*\tA B C\tif ((RK(B) == RK(C)) ~= A) then pc++\t\t*/\nOP_LT,/*\tA B C\tif ((RK(B) <  RK(C)) ~= A) then pc++\t\t*/\nOP_LE,/*\tA B C\tif ((RK(B) <= RK(C)) ~= A) then pc++\t\t*/\n\nOP_TEST,/*\tA C\tif not (R(A) <=> C) then pc++\t\t\t*/\nOP_TESTSET,/*\tA B C\tif (R(B) <=> C) then R(A) := R(B) else pc++\t*/\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\treturn R(A)(R(A+1), ... ,R(A+B-1))\t\t*/\nOP_RETURN,/*\tA B\treturn R(A), ... ,R(A+B-2)\t(see note)\t*/\n\nOP_FORLOOP,/*\tA sBx\tR(A)+=R(A+2);\n\t\t\tif R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/\nOP_FORPREP,/*\tA sBx\tR(A)-=R(A+2); pc+=sBx\t\t\t\t*/\n\nOP_TFORCALL,/*\tA C\tR(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2));\t*/\nOP_TFORLOOP,/*\tA sBx\tif R(A+1) ~= nil then { R(A)=R(A+1); pc += sBx }*/\n\nOP_SETLIST,/*\tA B C\tR(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B\t*/\n\nOP_CLOSURE,/*\tA Bx\tR(A) := closure(KPROTO[Bx])\t\t\t*/\n\nOP_VARARG,/*\tA B\tR(A), R(A+1), ..., R(A+B-2) = vararg\t\t*/\n\nOP_EXTRAARG/*\tAx\textra (larger) argument for previous opcode\t*/\n} OpCode;\n\n\n#define NUM_OPCODES\t(cast(int, OP_EXTRAARG) + 1)\n\n\n\n/*===========================================================================\n  Notes:\n  (*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then 'top' is\n  set to last_result+1, so next open instruction (OP_CALL, OP_RETURN,\n  OP_SETLIST) may use 'top'.\n\n  (*) In OP_VARARG, if (B == 0) then use actual number of varargs and\n  set top (like in OP_CALL with C == 0).\n\n  (*) In OP_RETURN, if (B == 0) then return up to 'top'.\n\n  (*) In OP_SETLIST, if (B == 0) then B = 'top'; if (C == 0) then next\n  'instruction' is EXTRAARG(real C).\n\n  (*) In OP_LOADKX, the next 'instruction' is always EXTRAARG.\n\n  (*) For comparisons, A specifies what condition the test should accept\n  (true or false).\n\n  (*) All 'skips' (pc++) assume that next instruction is a jump.\n\n===========================================================================*/\n\n\n/*\n** masks for instruction properties. The format is:\n** bits 0-1: op mode\n** bits 2-3: C arg mode\n** bits 4-5: B arg mode\n** bit 6: instruction set register A\n** bit 7: operator is a test (next instruction must be a jump)\n*/\n\nenum OpArgMask {\n  OpArgN,  /* argument is not used */\n  OpArgU,  /* argument is used */\n  OpArgR,  /* argument is a register or a jump offset */\n  OpArgK   /* argument is a constant or register/constant */\n};\n\nLUAI_DDEC const lu_byte luaP_opmodes[NUM_OPCODES];\n\n#define getOpMode(m)\t(cast(enum OpMode, luaP_opmodes[m] & 3))\n#define getBMode(m)\t(cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3))\n#define getCMode(m)\t(cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3))\n#define testAMode(m)\t(luaP_opmodes[m] & (1 << 6))\n#define testTMode(m)\t(luaP_opmodes[m] & (1 << 7))\n\n\nLUAI_DDEC const char *const luaP_opnames[NUM_OPCODES+1];  /* opcode names */\n\n\n/* number of list items to accumulate before a SETLIST instruction */\n#define LFIELDS_PER_FLUSH\t50\n\n\n#endif\n"
  },
  {
    "path": "src/lua/loslib.c",
    "content": "/*\r\n** $Id: loslib.c,v 1.65.1.1 2017/04/19 17:29:57 roberto Exp $\r\n** Standard Operating System library\r\n** See Copyright Notice in lua.h\r\n*/\r\n\r\n#define loslib_c\r\n#define LUA_LIB\r\n\r\n#include \"lprefix.h\"\r\n\r\n\r\n#include <errno.h>\r\n#include <locale.h>\r\n#include <stdlib.h>\r\n#include <string.h>\r\n#include <time.h>\r\n\r\n#include \"lua.h\"\r\n\r\n#include \"lauxlib.h\"\r\n#include \"lualib.h\"\r\n\r\n\r\n/*\r\n** {==================================================================\r\n** List of valid conversion specifiers for the 'strftime' function;\r\n** options are grouped by length; group of length 2 start with '||'.\r\n** ===================================================================\r\n*/\r\n#if !defined(LUA_STRFTIMEOPTIONS)\t/* { */\r\n\r\n/* options for ANSI C 89 (only 1-char options) */\r\n#define L_STRFTIMEC89\t\t\"aAbBcdHIjmMpSUwWxXyYZ%\"\r\n\r\n/* options for ISO C 99 and POSIX */\r\n#define L_STRFTIMEC99 \"aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%\" \\\r\n    \"||\" \"EcECExEXEyEY\" \"OdOeOHOIOmOMOSOuOUOVOwOWOy\"  /* two-char options */\r\n\r\n/* options for Windows */\r\n#define L_STRFTIMEWIN \"aAbBcdHIjmMpSUwWxXyYzZ%\" \\\r\n    \"||\" \"#c#x#d#H#I#j#m#M#S#U#w#W#y#Y\"  /* two-char options */\r\n\r\n#if defined(LUA_USE_WINDOWS)\r\n#define LUA_STRFTIMEOPTIONS\tL_STRFTIMEWIN\r\n#elif defined(LUA_USE_C89)\r\n#define LUA_STRFTIMEOPTIONS\tL_STRFTIMEC89\r\n#else  /* C99 specification */\r\n#define LUA_STRFTIMEOPTIONS\tL_STRFTIMEC99\r\n#endif\r\n\r\n#endif\t\t\t\t\t/* } */\r\n/* }================================================================== */\r\n\r\n\r\n/*\r\n** {==================================================================\r\n** Configuration for time-related stuff\r\n** ===================================================================\r\n*/\r\n\r\n#if !defined(l_time_t)\t\t/* { */\r\n/*\r\n** type to represent time_t in Lua\r\n*/\r\n#define l_timet\t\t\tlua_Integer\r\n#define l_pushtime(L,t)\t\tlua_pushinteger(L,(lua_Integer)(t))\r\n\r\nstatic time_t l_checktime (lua_State *L, int arg) {\r\n  lua_Integer t = luaL_checkinteger(L, arg);\r\n  luaL_argcheck(L, (time_t)t == t, arg, \"time out-of-bounds\");\r\n  return (time_t)t;\r\n}\r\n\r\n#endif\t\t\t\t/* } */\r\n\r\n\r\n#if !defined(l_gmtime)\t\t/* { */\r\n/*\r\n** By default, Lua uses gmtime/localtime, except when POSIX is available,\r\n** where it uses gmtime_r/localtime_r\r\n*/\r\n\r\n#if defined(LUA_USE_POSIX)\t/* { */\r\n\r\n#define l_gmtime(t,r)\t\tgmtime_r(t,r)\r\n#define l_localtime(t,r)\tlocaltime_r(t,r)\r\n\r\n#else\t\t\t\t/* }{ */\r\n\r\n/* ISO C definitions */\r\n#define l_gmtime(t,r)\t\t((void)(r)->tm_sec, gmtime(t))\r\n#define l_localtime(t,r)  \t((void)(r)->tm_sec, localtime(t))\r\n\r\n#endif\t\t\t\t/* } */\r\n\r\n#endif\t\t\t\t/* } */\r\n\r\n/* }================================================================== */\r\n\r\n\r\n/*\r\n** {==================================================================\r\n** Configuration for 'tmpnam':\r\n** By default, Lua uses tmpnam except when POSIX is available, where\r\n** it uses mkstemp.\r\n** ===================================================================\r\n*/\r\n#if !defined(lua_tmpnam)\t/* { */\r\n\r\n#if defined(LUA_USE_POSIX)\t/* { */\r\n\r\n#include <unistd.h>\r\n\r\n#define LUA_TMPNAMBUFSIZE\t32\r\n\r\n#if !defined(LUA_TMPNAMTEMPLATE)\r\n#define LUA_TMPNAMTEMPLATE\t\"/tmp/lua_XXXXXX\"\r\n#endif\r\n\r\n#define lua_tmpnam(b,e) { \\\r\n        strcpy(b, LUA_TMPNAMTEMPLATE); \\\r\n        e = mkstemp(b); \\\r\n        if (e != -1) close(e); \\\r\n        e = (e == -1); }\r\n\r\n#else\t\t\t\t/* }{ */\r\n\r\n/* ISO C definitions */\r\n#define LUA_TMPNAMBUFSIZE\tL_tmpnam\r\n#define lua_tmpnam(b,e)\t\t{ e = (tmpnam(b) == NULL); }\r\n\r\n#endif\t\t\t\t/* } */\r\n\r\n#endif\t\t\t\t/* } */\r\n/* }================================================================== */\r\n\r\n\r\n\r\n\r\nstatic int os_execute (lua_State *L) {\r\n  // commented, not really necessary and was unallowing compilation on some architectures\r\n  /*\r\n  const char *cmd = luaL_optstring(L, 1, NULL);\r\n  int stat = system(cmd);\r\n  if (cmd != NULL)\r\n    return luaL_execresult(L, stat);\r\n  else {\r\n    lua_pushboolean(L, stat);\r\n    return 1;\r\n  }\r\n  */\r\n}\r\n\r\n\r\nstatic int os_remove (lua_State *L) {\r\n  const char *filename = luaL_checkstring(L, 1);\r\n  return luaL_fileresult(L, remove(filename) == 0, filename);\r\n}\r\n\r\n\r\nstatic int os_rename (lua_State *L) {\r\n  const char *fromname = luaL_checkstring(L, 1);\r\n  const char *toname = luaL_checkstring(L, 2);\r\n  return luaL_fileresult(L, rename(fromname, toname) == 0, NULL);\r\n}\r\n\r\n\r\nstatic int os_tmpname (lua_State *L) {\r\n  char buff[LUA_TMPNAMBUFSIZE];\r\n  int err;\r\n  lua_tmpnam(buff, err);\r\n  if (err)\r\n    return luaL_error(L, \"unable to generate a unique filename\");\r\n  lua_pushstring(L, buff);\r\n  return 1;\r\n}\r\n\r\n\r\nstatic int os_getenv (lua_State *L) {\r\n  lua_pushstring(L, getenv(luaL_checkstring(L, 1)));  /* if NULL push nil */\r\n  return 1;\r\n}\r\n\r\n\r\nstatic int os_clock (lua_State *L) {\r\n  lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);\r\n  return 1;\r\n}\r\n\r\n\r\n/*\r\n** {======================================================\r\n** Time/Date operations\r\n** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,\r\n**   wday=%w+1, yday=%j, isdst=? }\r\n** =======================================================\r\n*/\r\n\r\nstatic void setfield (lua_State *L, const char *key, int value) {\r\n  lua_pushinteger(L, value);\r\n  lua_setfield(L, -2, key);\r\n}\r\n\r\nstatic void setboolfield (lua_State *L, const char *key, int value) {\r\n  if (value < 0)  /* undefined? */\r\n    return;  /* does not set field */\r\n  lua_pushboolean(L, value);\r\n  lua_setfield(L, -2, key);\r\n}\r\n\r\n\r\n/*\r\n** Set all fields from structure 'tm' in the table on top of the stack\r\n*/\r\nstatic void setallfields (lua_State *L, struct tm *stm) {\r\n  setfield(L, \"sec\", stm->tm_sec);\r\n  setfield(L, \"min\", stm->tm_min);\r\n  setfield(L, \"hour\", stm->tm_hour);\r\n  setfield(L, \"day\", stm->tm_mday);\r\n  setfield(L, \"month\", stm->tm_mon + 1);\r\n  setfield(L, \"year\", stm->tm_year + 1900);\r\n  setfield(L, \"wday\", stm->tm_wday + 1);\r\n  setfield(L, \"yday\", stm->tm_yday + 1);\r\n  setboolfield(L, \"isdst\", stm->tm_isdst);\r\n}\r\n\r\n\r\nstatic int getboolfield (lua_State *L, const char *key) {\r\n  int res;\r\n  res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);\r\n  lua_pop(L, 1);\r\n  return res;\r\n}\r\n\r\n\r\n/* maximum value for date fields (to avoid arithmetic overflows with 'int') */\r\n#if !defined(L_MAXDATEFIELD)\r\n#define L_MAXDATEFIELD\t(INT_MAX / 2)\r\n#endif\r\n\r\nstatic int getfield (lua_State *L, const char *key, int d, int delta) {\r\n  int isnum;\r\n  int t = lua_getfield(L, -1, key);  /* get field and its type */\r\n  lua_Integer res = lua_tointegerx(L, -1, &isnum);\r\n  if (!isnum) {  /* field is not an integer? */\r\n    if (t != LUA_TNIL)  /* some other value? */\r\n      return luaL_error(L, \"field '%s' is not an integer\", key);\r\n    else if (d < 0)  /* absent field; no default? */\r\n      return luaL_error(L, \"field '%s' missing in date table\", key);\r\n    res = d;\r\n  }\r\n  else {\r\n    if (!(-L_MAXDATEFIELD <= res && res <= L_MAXDATEFIELD))\r\n      return luaL_error(L, \"field '%s' is out-of-bound\", key);\r\n    res -= delta;\r\n  }\r\n  lua_pop(L, 1);\r\n  return (int)res;\r\n}\r\n\r\n\r\nstatic const char *checkoption (lua_State *L, const char *conv,\r\n                                ptrdiff_t convlen, char *buff) {\r\n  const char *option = LUA_STRFTIMEOPTIONS;\r\n  int oplen = 1;  /* length of options being checked */\r\n  for (; *option != '\\0' && oplen <= convlen; option += oplen) {\r\n    if (*option == '|')  /* next block? */\r\n      oplen++;  /* will check options with next length (+1) */\r\n    else if (memcmp(conv, option, oplen) == 0) {  /* match? */\r\n      memcpy(buff, conv, oplen);  /* copy valid option to buffer */\r\n      buff[oplen] = '\\0';\r\n      return conv + oplen;  /* return next item */\r\n    }\r\n  }\r\n  luaL_argerror(L, 1,\r\n    lua_pushfstring(L, \"invalid conversion specifier '%%%s'\", conv));\r\n  return conv;  /* to avoid warnings */\r\n}\r\n\r\n\r\n/* maximum size for an individual 'strftime' item */\r\n#define SIZETIMEFMT\t250\r\n\r\n\r\nstatic int os_date (lua_State *L) {\r\n  size_t slen;\r\n  const char *s = luaL_optlstring(L, 1, \"%c\", &slen);\r\n  time_t t = luaL_opt(L, l_checktime, 2, time(NULL));\r\n  const char *se = s + slen;  /* 's' end */\r\n  struct tm tmr, *stm;\r\n  if (*s == '!') {  /* UTC? */\r\n    stm = l_gmtime(&t, &tmr);\r\n    s++;  /* skip '!' */\r\n  }\r\n  else\r\n    stm = l_localtime(&t, &tmr);\r\n  if (stm == NULL)  /* invalid date? */\r\n    return luaL_error(L,\r\n                 \"time result cannot be represented in this installation\");\r\n  if (strcmp(s, \"*t\") == 0) {\r\n    lua_createtable(L, 0, 9);  /* 9 = number of fields */\r\n    setallfields(L, stm);\r\n  }\r\n  else {\r\n    char cc[4];  /* buffer for individual conversion specifiers */\r\n    luaL_Buffer b;\r\n    cc[0] = '%';\r\n    luaL_buffinit(L, &b);\r\n    while (s < se) {\r\n      if (*s != '%')  /* not a conversion specifier? */\r\n        luaL_addchar(&b, *s++);\r\n      else {\r\n        size_t reslen;\r\n        char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT);\r\n        s++;  /* skip '%' */\r\n        s = checkoption(L, s, se - s, cc + 1);  /* copy specifier to 'cc' */\r\n        reslen = strftime(buff, SIZETIMEFMT, cc, stm);\r\n        luaL_addsize(&b, reslen);\r\n      }\r\n    }\r\n    luaL_pushresult(&b);\r\n  }\r\n  return 1;\r\n}\r\n\r\n\r\nstatic int os_time (lua_State *L) {\r\n  time_t t;\r\n  if (lua_isnoneornil(L, 1))  /* called without args? */\r\n    t = time(NULL);  /* get current time */\r\n  else {\r\n    struct tm ts;\r\n    luaL_checktype(L, 1, LUA_TTABLE);\r\n    lua_settop(L, 1);  /* make sure table is at the top */\r\n    ts.tm_sec = getfield(L, \"sec\", 0, 0);\r\n    ts.tm_min = getfield(L, \"min\", 0, 0);\r\n    ts.tm_hour = getfield(L, \"hour\", 12, 0);\r\n    ts.tm_mday = getfield(L, \"day\", -1, 0);\r\n    ts.tm_mon = getfield(L, \"month\", -1, 1);\r\n    ts.tm_year = getfield(L, \"year\", -1, 1900);\r\n    ts.tm_isdst = getboolfield(L, \"isdst\");\r\n    t = mktime(&ts);\r\n    setallfields(L, &ts);  /* update fields with normalized values */\r\n  }\r\n  if (t != (time_t)(l_timet)t || t == (time_t)(-1))\r\n    return luaL_error(L,\r\n                  \"time result cannot be represented in this installation\");\r\n  l_pushtime(L, t);\r\n  return 1;\r\n}\r\n\r\n\r\nstatic int os_difftime (lua_State *L) {\r\n  time_t t1 = l_checktime(L, 1);\r\n  time_t t2 = l_checktime(L, 2);\r\n  lua_pushnumber(L, (lua_Number)difftime(t1, t2));\r\n  return 1;\r\n}\r\n\r\n/* }====================================================== */\r\n\r\n\r\nstatic int os_setlocale (lua_State *L) {\r\n  static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,\r\n                      LC_NUMERIC, LC_TIME};\r\n  static const char *const catnames[] = {\"all\", \"collate\", \"ctype\", \"monetary\",\r\n     \"numeric\", \"time\", NULL};\r\n  const char *l = luaL_optstring(L, 1, NULL);\r\n  int op = luaL_checkoption(L, 2, \"all\", catnames);\r\n  lua_pushstring(L, setlocale(cat[op], l));\r\n  return 1;\r\n}\r\n\r\n\r\nstatic int os_exit (lua_State *L) {\r\n  int status;\r\n  if (lua_isboolean(L, 1))\r\n    status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);\r\n  else\r\n    status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);\r\n  if (lua_toboolean(L, 2))\r\n    lua_close(L);\r\n  if (L) exit(status);  /* 'if' to avoid warnings for unreachable 'return' */\r\n  return 0;\r\n}\r\n\r\n\r\nstatic const luaL_Reg syslib[] = {\r\n  {\"clock\",     os_clock},\r\n  {\"date\",      os_date},\r\n  {\"difftime\",  os_difftime},\r\n  {\"execute\",   os_execute},\r\n  {\"exit\",      os_exit},\r\n  {\"getenv\",    os_getenv},\r\n  {\"remove\",    os_remove},\r\n  {\"rename\",    os_rename},\r\n  {\"setlocale\", os_setlocale},\r\n  {\"time\",      os_time},\r\n  {\"tmpname\",   os_tmpname},\r\n  {NULL, NULL}\r\n};\r\n\r\n/* }====================================================== */\r\n\r\n\r\n\r\nLUAMOD_API int luaopen_os (lua_State *L) {\r\n  luaL_newlib(L, syslib);\r\n  return 1;\r\n}\r\n\r\n"
  },
  {
    "path": "src/lua/lparser.c",
    "content": "/*\n** $Id: lparser.c,v 2.155.1.2 2017/04/29 18:11:40 roberto Exp $\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 <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 local variables per function (must be smaller\n   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  lu_byte nactvar;  /* # active locals outside the block */\n  lu_byte upval;  /* true if some variable in the block is an upvalue */\n  lu_byte isloop;  /* true if 'block' is a loop */\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\n/* semantic error */\nstatic l_noret semerror (LexState *ls, const char *msg) {\n  ls->t.token = 0;  /* remove \"near <token>\" from final message */\n  luaX_syntaxerror(ls, msg);\n}\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\nstatic void checklimit (FuncState *fs, int v, int l, const char *what) {\n  if (v > l) errorlimit(fs, l, what);\n}\n\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\nstatic void check (LexState *ls, int c) {\n  if (ls->t.token != c)\n    error_expected(ls, c);\n}\n\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\nstatic void check_match (LexState *ls, int what, int who, int where) {\n  if (!testnext(ls, what)) {\n    if (where == ls->linenumber)\n      error_expected(ls, what);\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 (LexState *ls, expdesc *e, TString *s) {\n  init_exp(e, VK, luaK_stringK(ls->fs, s));\n}\n\n\nstatic void checkname (LexState *ls, expdesc *e) {\n  codestring(ls, e, str_checkname(ls));\n}\n\n\nstatic int registerlocalvar (LexState *ls, TString *varname) {\n  FuncState *fs = ls->fs;\n  Proto *f = fs->f;\n  int oldsize = f->sizelocvars;\n  luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,\n                  LocVar, SHRT_MAX, \"local variables\");\n  while (oldsize < f->sizelocvars)\n    f->locvars[oldsize++].varname = NULL;\n  f->locvars[fs->nlocvars].varname = varname;\n  luaC_objbarrier(ls->L, f, varname);\n  return fs->nlocvars++;\n}\n\n\nstatic void new_localvar (LexState *ls, TString *name) {\n  FuncState *fs = ls->fs;\n  Dyndata *dyd = ls->dyd;\n  int reg = registerlocalvar(ls, name);\n  checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,\n                  MAXVARS, \"local variables\");\n  luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,\n                  dyd->actvar.size, Vardesc, MAX_INT, \"local variables\");\n  dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg);\n}\n\n\nstatic void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) {\n  new_localvar(ls, luaX_newstring(ls, name, sz));\n}\n\n#define new_localvarliteral(ls,v) \\\n\tnew_localvarliteral_(ls, \"\" v, (sizeof(v)/sizeof(char))-1)\n\n\nstatic LocVar *getlocvar (FuncState *fs, int i) {\n  int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;\n  lua_assert(idx < fs->nlocvars);\n  return &fs->f->locvars[idx];\n}\n\n\nstatic void adjustlocalvars (LexState *ls, int nvars) {\n  FuncState *fs = ls->fs;\n  fs->nactvar = cast_byte(fs->nactvar + nvars);\n  for (; nvars; nvars--) {\n    getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;\n  }\n}\n\n\nstatic void removevars (FuncState *fs, int tolevel) {\n  fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);\n  while (fs->nactvar > tolevel)\n    getlocvar(fs, --fs->nactvar)->endpc = fs->pc;\n}\n\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 int newupvalue (FuncState *fs, TString *name, expdesc *v) {\n  Proto *f = fs->f;\n  int oldsize = f->sizeupvalues;\n  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  f->upvalues[fs->nups].instack = (v->k == VLOCAL);\n  f->upvalues[fs->nups].idx = cast_byte(v->u.info);\n  f->upvalues[fs->nups].name = name;\n  luaC_objbarrier(fs->ls->L, f, name);\n  return fs->nups++;\n}\n\n\nstatic int searchvar (FuncState *fs, TString *n) {\n  int i;\n  for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {\n    if (eqstr(n, getlocvar(fs, i)->varname))\n      return i;\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}\n\n\n/*\n  Find variable with given name 'n'. If it is an upvalue, add this\n  upvalue into all intermediate functions.\n*/\nstatic void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {\n  if (fs == NULL)  /* no more levels? */\n    init_exp(var, VVOID, 0);  /* default is global */\n  else {\n    int v = searchvar(fs, n);  /* look up locals at current level */\n    if (v >= 0) {  /* found? */\n      init_exp(var, VLOCAL, v);  /* variable is local */\n      if (!base)\n        markupval(fs, v);  /* local will be used as an upval */\n    }\n    else {  /* not found as local at current level; try upvalues */\n      int idx = searchupvalue(fs, n);  /* try existing upvalues */\n      if (idx < 0) {  /* not found? */\n        singlevaraux(fs->prev, n, var, 0);  /* try upper levels */\n        if (var->k == VVOID)  /* not found? */\n          return;  /* it is a global */\n        /* else was LOCAL or UPVAL */\n        idx  = newupvalue(fs, n, var);  /* will be a new upvalue */\n      }\n      init_exp(var, VUPVAL, idx);  /* new or old upvalue */\n    }\n  }\n}\n\n\nstatic void singlevar (LexState *ls, expdesc *var) {\n  TString *varname = str_checkname(ls);\n  FuncState *fs = ls->fs;\n  singlevaraux(fs, varname, var, 1);\n  if (var->k == VVOID) {  /* global name? */\n    expdesc key;\n    singlevaraux(fs, ls->envn, var, 1);  /* get environment variable */\n    lua_assert(var->k != VVOID);  /* this one must exist */\n    codestring(ls, &key, varname);  /* key is variable name */\n    luaK_indexed(fs, var, &key);  /* env[varname] */\n  }\n}\n\n\nstatic void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {\n  FuncState *fs = ls->fs;\n  int extra = nvars - nexps;\n  if (hasmultret(e->k)) {\n    extra++;  /* includes call itself */\n    if (extra < 0) extra = 0;\n    luaK_setreturns(fs, e, extra);  /* last exp. provides the difference */\n    if (extra > 1) luaK_reserveregs(fs, extra-1);\n  }\n  else {\n    if (e->k != VVOID) luaK_exp2nextreg(fs, e);  /* close last expression */\n    if (extra > 0) {\n      int reg = fs->freereg;\n      luaK_reserveregs(fs, extra);\n      luaK_nil(fs, reg, extra);\n    }\n  }\n  if (nexps > nvars)\n    ls->fs->freereg -= nexps - nvars;  /* remove extra values */\n}\n\n\nstatic void enterlevel (LexState *ls) {\n  lua_State *L = ls->L;\n  ++L->nCcalls;\n  checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, \"C levels\");\n}\n\n\n#define leavelevel(ls)\t((ls)->L->nCcalls--)\n\n\nstatic void closegoto (LexState *ls, int g, Labeldesc *label) {\n  int i;\n  FuncState *fs = ls->fs;\n  Labellist *gl = &ls->dyd->gt;\n  Labeldesc *gt = &gl->arr[g];\n  lua_assert(eqstr(gt->name, label->name));\n  if (gt->nactvar < label->nactvar) {\n    TString *vname = getlocvar(fs, gt->nactvar)->varname;\n    const char *msg = luaO_pushfstring(ls->L,\n      \"<goto %s> at line %d jumps into the scope of local '%s'\",\n      getstr(gt->name), gt->line, getstr(vname));\n    semerror(ls, msg);\n  }\n  luaK_patchlist(fs, gt->pc, label->pc);\n  /* remove goto from pending list */\n  for (i = g; i < gl->n - 1; i++)\n    gl->arr[i] = gl->arr[i + 1];\n  gl->n--;\n}\n\n\n/*\n** try to close a goto with existing labels; this solves backward jumps\n*/\nstatic int findlabel (LexState *ls, int g) {\n  int i;\n  BlockCnt *bl = ls->fs->bl;\n  Dyndata *dyd = ls->dyd;\n  Labeldesc *gt = &dyd->gt.arr[g];\n  /* check labels in current block for a match */\n  for (i = bl->firstlabel; i < dyd->label.n; i++) {\n    Labeldesc *lb = &dyd->label.arr[i];\n    if (eqstr(lb->name, gt->name)) {  /* correct label? */\n      if (gt->nactvar > lb->nactvar &&\n          (bl->upval || dyd->label.n > bl->firstlabel))\n        luaK_patchclose(ls->fs, gt->pc, lb->nactvar);\n      closegoto(ls, g, lb);  /* close it */\n      return 1;\n    }\n  }\n  return 0;  /* label not found; cannot close goto */\n}\n\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].pc = pc;\n  l->n = n + 1;\n  return n;\n}\n\n\n/*\n** check whether new label 'lb' matches any pending gotos in current\n** block; solves forward jumps\n*/\nstatic void findgotos (LexState *ls, Labeldesc *lb) {\n  Labellist *gl = &ls->dyd->gt;\n  int i = ls->fs->bl->firstgoto;\n  while (i < gl->n) {\n    if (eqstr(gl->arr[i].name, lb->name))\n      closegoto(ls, i, lb);\n    else\n      i++;\n  }\n}\n\n\n/*\n** export pending gotos to outer level, to check them against\n** outer labels; if the block being exited has upvalues, and\n** the goto exits the scope of any variable (which can be the\n** upvalue), close those variables being exited.\n*/\nstatic void movegotosout (FuncState *fs, BlockCnt *bl) {\n  int i = bl->firstgoto;\n  Labellist *gl = &fs->ls->dyd->gt;\n  /* correct pending gotos to current block and try to close it\n     with visible labels */\n  while (i < gl->n) {\n    Labeldesc *gt = &gl->arr[i];\n    if (gt->nactvar > bl->nactvar) {\n      if (bl->upval)\n        luaK_patchclose(fs, gt->pc, bl->nactvar);\n      gt->nactvar = bl->nactvar;\n    }\n    if (!findlabel(fs->ls, i))\n      i++;  /* move to next one */\n  }\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  bl->previous = fs->bl;\n  fs->bl = bl;\n  lua_assert(fs->freereg == fs->nactvar);\n}\n\n\n/*\n** create a label named 'break' to resolve break statements\n*/\nstatic void breaklabel (LexState *ls) {\n  TString *n = luaS_new(ls->L, \"break\");\n  int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);\n  findgotos(ls, &ls->dyd->label.arr[l]);\n}\n\n/*\n** generates an error for an undefined 'goto'; choose appropriate\n** message when label name is a reserved word (which can only be 'break')\n*/\nstatic l_noret undefgoto (LexState *ls, Labeldesc *gt) {\n  const char *msg = isreserved(gt->name)\n                    ? \"<%s> at line %d not inside a loop\"\n                    : \"no visible label '%s' for <goto> at line %d\";\n  msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);\n  semerror(ls, msg);\n}\n\n\nstatic void leaveblock (FuncState *fs) {\n  BlockCnt *bl = fs->bl;\n  LexState *ls = fs->ls;\n  if (bl->previous && bl->upval) {\n    /* create a 'jump to here' to close upvalues */\n    int j = luaK_jump(fs);\n    luaK_patchclose(fs, j, bl->nactvar);\n    luaK_patchtohere(fs, j);\n  }\n  if (bl->isloop)\n    breaklabel(ls);  /* close pending breaks */\n  fs->bl = bl->previous;\n  removevars(fs, bl->nactvar);\n  lua_assert(bl->nactvar == fs->nactvar);\n  fs->freereg = fs->nactvar;  /* free registers */\n  ls->dyd->label.n = bl->firstlabel;  /* remove local labels */\n  if (bl->previous)  /* inner block? */\n    movegotosout(fs, bl);  /* update pending gotos to outer block */\n  else if (bl->firstgoto < ls->dyd->gt.n)  /* pending gotos in outer block? */\n    undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]);  /* error */\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 must use 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*/\nstatic void codeclosure (LexState *ls, expdesc *v) {\n  FuncState *fs = ls->fs->prev;\n  init_exp(v, VRELOCABLE, 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  Proto *f;\n  fs->prev = ls->fs;  /* linked list of funcstates */\n  fs->ls = ls;\n  ls->fs = fs;\n  fs->pc = 0;\n  fs->lasttarget = 0;\n  fs->jpc = NO_JUMP;\n  fs->freereg = 0;\n  fs->nk = 0;\n  fs->np = 0;\n  fs->nups = 0;\n  fs->nlocvars = 0;\n  fs->nactvar = 0;\n  fs->firstlocal = ls->dyd->actvar.n;\n  fs->bl = NULL;\n  f = fs->f;\n  f->source = ls->source;\n  f->maxstacksize = 2;  /* registers 0/1 are always valid */\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, 0, 0);  /* final return */\n  leaveblock(fs);\n  luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);\n  f->sizecode = fs->pc;\n  luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);\n  f->sizelineinfo = fs->pc;\n  luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);\n  f->sizek = fs->nk;\n  luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);\n  f->sizep = fs->np;\n  luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);\n  f->sizelocvars = fs->nlocvars;\n  luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);\n  f->sizeupvalues = fs->nups;\n  lua_assert(fs->bl == NULL);\n  ls->fs = fs->prev;\n  luaC_checkGC(L);\n}\n\n\n\n/*============================================================*/\n/* GRAMMAR RULES */\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_EOL:\n      return ls->ignorenewline ? 0 : 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  checkname(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\n\nstruct ConsControl {\n  expdesc v;  /* last list item read */\n  expdesc *t;  /* table descriptor */\n  int nh;  /* total number of 'record' elements */\n  int na;  /* total number of array elements */\n  int tostore;  /* number of array elements pending to be stored */\n};\n\n\nstatic void recfield (LexState *ls, struct ConsControl *cc) {\n  /* recfield -> (NAME | '['exp1']') = exp1 */\n  FuncState *fs = ls->fs;\n  int reg = ls->fs->freereg;\n  expdesc key, val;\n  int rkkey;\n  if (ls->t.token == TK_NAME) {\n    checklimit(fs, cc->nh, MAX_INT, \"items in a constructor\");\n    checkname(ls, &key);\n  }\n  else  /* ls->t.token == '[' */\n    yindex(ls, &key);\n  cc->nh++;\n  checknext(ls, '=');\n  rkkey = luaK_exp2RK(fs, &key);\n  expr(ls, &val);\n  luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val));\n  fs->freereg = reg;  /* free registers */\n}\n\n\nstatic void closelistfield (FuncState *fs, struct ConsControl *cc) {\n  if (cc->v.k == VVOID) return;  /* there is no list item */\n  luaK_exp2nextreg(fs, &cc->v);\n  cc->v.k = VVOID;\n  if (cc->tostore == LFIELDS_PER_FLUSH) {\n    luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);  /* flush */\n    cc->tostore = 0;  /* no more items pending */\n  }\n}\n\n\nstatic void lastlistfield (FuncState *fs, struct 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}\n\n\nstatic void listfield (LexState *ls, struct ConsControl *cc) {\n  /* listfield -> exp */\n  expr(ls, &cc->v);\n  checklimit(ls->fs, cc->na, MAX_INT, \"items in a constructor\");\n  cc->na++;\n  cc->tostore++;\n}\n\n\nstatic void field (LexState *ls, struct 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\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_codeABC(fs, OP_NEWTABLE, 0, 0, 0);\n  struct ConsControl cc;\n  cc.na = cc.nh = cc.tostore = 0;\n  cc.t = t;\n  init_exp(t, VRELOCABLE, pc);\n  init_exp(&cc.v, VVOID, 0);  /* no value (yet) */\n  luaK_exp2nextreg(ls->fs, t);  /* fix it at stack top */\n  checknext(ls, '{');\n  do {\n    lua_assert(cc.v.k == VVOID || cc.tostore > 0);\n    if (ls->t.token == '}') break;\n    closelistfield(fs, &cc);\n    field(ls, &cc);\n  } while (testnext(ls, ',') || testnext(ls, ';'));\n  check_match(ls, '}', '{', line);\n  lastlistfield(fs, &cc);\n  SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */\n  SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh));  /* set initial table size */\n}\n\n/* }====================================================================== */\n\n\n\nstatic void parlist (LexState *ls) {\n  /* parlist -> [ param { ',' param } ] */\n  FuncState *fs = ls->fs;\n  Proto *f = fs->f;\n  int nparams = 0;\n  f->is_vararg = 0;\n  if (ls->t.token != ')') {  /* is 'parlist' not empty? */\n    do {\n      switch (ls->t.token) {\n        case TK_NAME: {  /* param -> NAME */\n          new_localvar(ls, str_checkname(ls));\n          nparams++;\n          break;\n        }\n        case TK_DOTS: {  /* param -> '...' */\n          luaX_next(ls);\n          f->is_vararg = 1;  /* declared vararg */\n          break;\n        }\n        default: luaX_syntaxerror(ls, \"<name> or '...' expected\");\n      }\n    } while (!f->is_vararg && testnext(ls, ','));\n  }\n  adjustlocalvars(ls, nparams);\n  f->numparams = cast_byte(fs->nactvar);\n  luaK_reserveregs(fs, fs->nactvar);  /* reserve register for parameters */\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, int line) {\n  FuncState *fs = ls->fs;\n  expdesc args;\n  int base, nparams;\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        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(ls, &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  fs->freereg = base+1;  /* call remove function and arguments and leaves\n                            (unless changed) one result */\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  int line = ls->linenumber;\n  primaryexp(ls, v);\n  for (;;) {\n    switch (ls->t.token) {\n      case '.': {  /* fieldsel */\n        fieldsel(ls, v);\n        break;\n      }\n      case '[': {  /* '[' exp1 ']' */\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        checkname(ls, &key);\n        luaK_self(fs, v, &key);\n        funcargs(ls, v, line);\n        break;\n      }\n      case '(': case TK_STRING: case '{': {  /* funcargs */\n        luaK_exp2nextreg(fs, v);\n        funcargs(ls, v, line);\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(ls, 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, fs->f->is_vararg,\n                      \"cannot use '...' outside a vararg function\");\n      init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));\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_NE2: 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\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) {\n    int line = ls->linenumber;\n    luaX_next(ls);\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);\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  int 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 (lh->v.k == VINDEXED) {  /* assigning to a table? */\n      /* table is the upvalue/local being assigned now? */\n      if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {\n        conflict = 1;\n        lh->v.u.ind.vt = VLOCAL;\n        lh->v.u.ind.t = extra;  /* previous assignment will use safe copy */\n      }\n      /* index is the local being assigned? (index cannot be upvalue) */\n      if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {\n        conflict = 1;\n        lh->v.u.ind.idx = extra;  /* previous assignment will use safe copy */\n      }\n    }\n  }\n  if (conflict) {\n    /* copy upvalue/local value to a temporary (in position 'extra') */\n    OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;\n    luaK_codeABC(fs, op, extra, v->u.info, 0);\n    luaK_reserveregs(fs, 1);\n  }\n}\n\nstatic BinOpr op_for_compound_assign(Token r)\n{\n  switch (r.token) {\n  case TK_ASSADD:\n    return OPR_ADD;\n  case TK_ASSDIV:\n    return OPR_DIV;\n  case TK_ASSMUL:\n    return OPR_MUL;\n  case TK_ASSSUB:\n    return OPR_SUB;\n  case TK_ASSMOD:\n    return OPR_MOD;\n  default:\n    return OPR_NOBINOPR;\n  }\n}\n\n\nstatic void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {\n  expdesc e;\n  check_condition(ls, vkisvar(lh->v.k), \"syntax error\");\n  if (testnext(ls, ',')) {  /* assignment -> ',' suffixedexp assignment */\n    struct LHS_assign nv;\n    nv.prev = lh;\n    suffixedexp(ls, &nv.v); // read next lhs into nv\n    if (nv.v.k != VINDEXED)\n      check_conflict(ls, lh, &nv.v);\n    checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,\n                    \"C levels\");\n    assignment(ls, &nv, nvars+1);\n  }\n  else {  /* assignment -> '=' explist */\n    int nexps;\n\n    if (ls->t.token != '=')\n      luaX_syntaxerror(ls, luaO_pushfstring(ls->L, \"expected assignment operator\"));\n\n    luaX_next(ls);\n\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\n      /*if (op != OPR_NOBINOPR)\n      {\n        expdesc ec = lh->v;\n        luaK_infix(ls->fs, op, &ec);\n        luaK_posfix(ls->fs, op, &ec, &e, ls->linenumber);\n        luaK_storevar(ls->fs, &lh->v, &ec);\n      }\n      else*/\n        luaK_storevar(ls->fs, &lh->v, &e);\n      return;  /* avoid default */\n    }\n  }\n  init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */\n  luaK_storevar(ls->fs, &lh->v, &e);\n}\n\nstatic void compound_assign_op(LexState *ls, expdesc *v) {\n  int line;\n  FuncState *fs = ls->fs;\n  expdesc e = *v, v2;\n  BinOpr op = op_for_compound_assign(ls->t);\n  luaK_reserveregs(fs, fs->freereg - fs->nactvar); /* reserve all registers needed by the lvalue */\n  luaX_next(ls);\n  line = ls->linenumber;\n  enterlevel(ls);\n  luaK_infix(fs, op, &e);\n  expr(ls, &v2);\n  luaK_posfix(fs, op, &e, &v2, line);\n  leavelevel(ls);\n  luaK_exp2nextreg(fs, &e);\n  luaK_setoneret(ls->fs, &e);\n  luaK_storevar(ls->fs, v, &e);\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 pc) {\n  int line = ls->linenumber;\n  TString *label;\n  int g;\n  if (testnext(ls, TK_GOTO))\n    label = str_checkname(ls);\n  else {\n    luaX_next(ls);  /* skip break */\n    label = luaS_new(ls->L, \"break\");\n  }\n  g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);\n  findlabel(ls, g);  /* close it if label already defined */\n}\n\n\n/* check for repeated labels on the same block */\nstatic void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {\n  int i;\n  for (i = fs->bl->firstlabel; i < ll->n; i++) {\n    if (eqstr(label, ll->arr[i].name)) {\n      const char *msg = luaO_pushfstring(fs->ls->L,\n                          \"label '%s' already defined on line %d\",\n                          getstr(label), ll->arr[i].line);\n      semerror(fs->ls, msg);\n    }\n  }\n}\n\n\n/* skip no-op statements */\nstatic void skipnoopstat (LexState *ls) {\n  while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)\n    statement(ls);\n}\n\n\nstatic void labelstat (LexState *ls, TString *label, int line) {\n  /* label -> '::' NAME '::' */\n  FuncState *fs = ls->fs;\n  Labellist *ll = &ls->dyd->label;\n  int l;  /* index of new label being created */\n  checkrepeated(fs, ll, label);  /* check for repeated labels */\n  checknext(ls, TK_DBCOLON);  /* skip double colon */\n  /* create new entry for this label */\n  l = newlabelentry(ls, ll, label, line, luaK_getlabel(fs));\n  skipnoopstat(ls);  /* skip other no-op statements */\n  if (block_follow(ls, 0)) {  /* 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  findgotos(ls, &ll->arr[l]);\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  if (bl2.upval)  /* upvalues? */\n    luaK_patchclose(fs, condexit, bl2.nactvar);\n  leaveblock(fs);  /* finish scope */\n  luaK_patchlist(fs, condexit, repeat_init);  /* close the loop */\n  leaveblock(fs);  /* finish loop */\n}\n\n\nstatic int exp1 (LexState *ls) {\n  expdesc e;\n  int reg;\n  expr(ls, &e);\n  luaK_exp2nextreg(ls->fs, &e);\n  lua_assert(e.k == VNONRELOC);\n  reg = e.u.info;\n  return reg;\n}\n\n\nstatic void forbody (LexState *ls, int base, int line, int nvars, int isnum) {\n  /* forbody -> DO block */\n  BlockCnt bl;\n  FuncState *fs = ls->fs;\n  int prep, endfor;\n  adjustlocalvars(ls, 3);  /* control variables */\n  checknext(ls, TK_DO);\n  prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);\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  luaK_patchtohere(fs, prep);\n  if (isnum)  /* numeric for? */\n    endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);\n  else {  /* generic for */\n    luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);\n    luaK_fixline(fs, line);\n    endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);\n  }\n  luaK_patchlist(fs, endfor, prep + 1);\n  luaK_fixline(fs, line);\n}\n\n\nstatic void fornum (LexState *ls, TString *varname, int line) {\n  /* fornum -> NAME = exp1,exp1[,exp1] forbody */\n  FuncState *fs = ls->fs;\n  int base = fs->freereg;\n  new_localvarliteral(ls, \"(for index)\");\n  new_localvarliteral(ls, \"(for limit)\");\n  new_localvarliteral(ls, \"(for step)\");\n  new_localvar(ls, varname);\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_codek(fs, fs->freereg, luaK_intK(fs, 1));\n    luaK_reserveregs(fs, 1);\n  }\n  forbody(ls, base, line, 1, 1);\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;  /* gen, state, control, plus at least one declared var */\n  int line;\n  int base = fs->freereg;\n  /* create control variables */\n  new_localvarliteral(ls, \"(for generator)\");\n  new_localvarliteral(ls, \"(for state)\");\n  new_localvarliteral(ls, \"(for control)\");\n  /* create declared variables */\n  new_localvar(ls, indexname);\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, 3, explist(ls, &e), &e);\n  luaK_checkstack(fs, 3);  /* extra space to call generator */\n  forbody(ls, base, line, nvars - 3, 0);\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 retstat(LexState* ls);\n\nstatic void inline_if(LexState* ls, expdesc* v)\n{\n  /* IF ( COND ) block [ELSE block]*/\n\n  BlockCnt bl;\n  FuncState* fs = ls->fs;\n  int jf;\n\n  if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {\n    luaK_goiffalse(ls->fs, v);  /* will jump to label if condition is true */\n    enterblock(fs, &bl, 0);  /* must enter block before 'goto' */\n    gotostat(ls, v->t);  /* handle goto/break */\n    while (testnext(ls, ';')) {}  /* skip colons */\n    if (1 || block_follow(ls, 0)) {  /* 'goto' is the entire block? (ALWAYS TRUE WITH INLINE!) */\n      leaveblock(fs);\n      return;  /* and that is it */\n    }\n    else  /* must skip over 'then' part if condition is false */\n      jf = luaK_jump(fs);\n  }\n  else {  /* regular case (not goto/break) */\n    luaK_goiftrue(ls->fs, v);  /* skip over block if condition is false */\n    enterblock(fs, &bl, 0);\n    jf = v->f;\n  }\n\n  ls->ignorenewline = 0;\n  statlist(ls);  /* parse true block */\n\n  leaveblock(fs);\n\n  luaK_patchtohere(fs, jf);\n\n  if (testnext(ls, TK_ELSE))\n  {\n    block(ls);  /* 'else' part */\n  }\n\n  ls->ignorenewline = 1;\n  while (testnext(ls, TK_EOL));\n}\n\nstatic int test_then_block (LexState *ls, int *escapelist) {\n  /* test_then_block -> [IF | ELSEIF] cond THEN block */\n  BlockCnt bl;\n  FuncState *fs = ls->fs;\n  expdesc v;\n  int jf;  /* instruction to skip 'then' code (if condition is false) */\n  luaX_next(ls);  /* skip IF or ELSEIF */\n\n  int maybeInline = ls->t.token == '(';\n\n  expr(ls, &v);  /* read condition */\n\n  /* if we had parenthesis and there is no then, it's an inline */\n  maybeInline = maybeInline && ls->t.token != TK_THEN;\n\n  if (maybeInline) /* surely inline inline, consume ')' */\n  {\n    inline_if(ls, &v);\n    return 1;\n  }\n\n  checknext(ls, TK_THEN);\n  if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {\n    luaK_goiffalse(ls->fs, &v);  /* will jump to label if condition is true */\n    enterblock(fs, &bl, 0);  /* must enter block before 'goto' */\n    gotostat(ls, v.t);  /* handle goto/break */\n    while (testnext(ls, ';')) {}  /* skip colons */\n    if (block_follow(ls, 0)) {  /* 'goto' is the entire block? */\n      leaveblock(fs);\n      return 0;  /* and that is it */\n    }\n    else  /* must skip over 'then' part if condition is false */\n      jf = luaK_jump(fs);\n  }\n  else {  /* regular case (not goto/break) */\n    luaK_goiftrue(ls->fs, &v);  /* skip over block if condition is false */\n    enterblock(fs, &bl, 0);\n    jf = v.f;\n  }\n  statlist(ls);  /* 'then' part */\n  leaveblock(fs);\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, jf);\n  return 0;\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\n  if (test_then_block(ls, &escapelist))  /* IF cond THEN block */\n    return;\n\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  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  getlocvar(fs, b.u.info)->startpc = fs->pc;\n}\n\n\nstatic void localstat (LexState *ls) {\n  /* stat -> LOCAL NAME {',' NAME} ['=' explist] */\n  int nvars = 0;\n  int nexps;\n  expdesc e;\n  do {\n    new_localvar(ls, str_checkname(ls));\n    nvars++;\n  } while (testnext(ls, ','));\n  if (testnext(ls, '='))\n    nexps = explist(ls, &e);\n  else {\n    e.k = VVOID;\n    nexps = 0;\n  }\n  adjust_assign(ls, nvars, nexps, &e);\n  adjustlocalvars(ls, nvars);\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  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\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\n  if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */\n    v.prev = NULL;\n    assignment(ls, &v, 1);\n  }\n  else if (op_for_compound_assign(ls->t) != OPR_NOBINOPR)\n  {\n    v.prev = NULL;\n    compound_assign_op(ls, &v.v);\n  }\n\n  else {  /* stat -> func */\n    check_condition(ls, v.v.k == VCALL, \"syntax error\");\n    SETARG_C(getinstruction(fs, &v.v), 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 first, nret;  /* registers with returned values */\n  if (block_follow(ls, 1) || ls->t.token == ';' || (ls->t.token == TK_EOL && !ls->ignorenewline))\n    first = 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) {  /* tail call? */\n        SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);\n        lua_assert(GETARG_A(getinstruction(fs,&e)) == fs->nactvar);\n      }\n      first = fs->nactvar;\n      nret = LUA_MULTRET;  /* return all values */\n    }\n    else {\n      if (nret == 1)  /* only one single value? */\n        first = luaK_exp2anyreg(fs, &e);\n      else {\n        luaK_exp2nextreg(fs, &e);  /* values must go to the stack */\n        first = fs->nactvar;  /* return all active values */\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_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    case TK_GOTO: {  /* stat -> 'goto' NAME */\n      gotostat(ls, luaK_jump(ls->fs));\n      break;\n    }\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 >= ls->fs->nactvar);\n  ls->fs->freereg = ls->fs->nactvar;  /* free registers */\n  leavelevel(ls);\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  expdesc v;\n  open_func(ls, fs, &bl);\n  fs->f->is_vararg = 1;  /* main function is always declared vararg */\n  init_exp(&v, VLOCAL, 0);  /* create and... */\n  newupvalue(fs, ls->envn, &v);  /* ...set environment upvalue */\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  setclLvalue(L, L->top, cl);  /* anchor it (to avoid being collected) */\n  luaD_inctop(L);\n  lexstate.h = luaH_new(L);  /* create table for scanner */\n  sethvalue(L, L->top, lexstate.h);  /* anchor it */\n  luaD_inctop(L);\n  funcstate.f = cl->p = luaF_newproto(L);\n  funcstate.f->source = luaS_new(L, name);  /* create and anchor TString */\n  lua_assert(iswhite(funcstate.f));  /* do not need barrier here */\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--;  /* remove scanner's table */\n  return cl;  /* closure is on the stack, too */\n}\n"
  },
  {
    "path": "src/lua/lparser.h",
    "content": "/*\n** $Id: lparser.h,v 1.76.1.1 2017/04/19 17:20:42 roberto Exp $\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 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; nval = numerical integer value */\n  VNONRELOC,  /* expression has its value in a fixed register;\n                 info = result register */\n  VLOCAL,  /* local variable; info = local register */\n  VUPVAL,  /* upvalue variable; info = index of upvalue in 'upvalues' */\n  VINDEXED,  /* indexed variable;\n                ind.vt = whether 't' is register or upvalue;\n                ind.t = table register or upvalue;\n                ind.idx = key's R/K index */\n  VJMP,  /* expression is a test/comparison;\n            info = pc of corresponding jump instruction */\n  VRELOCABLE,  /* 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) <= VINDEXED)\n#define vkisinreg(k)\t((k) == VNONRELOC || (k) == VLOCAL)\n\ntypedef struct expdesc {\n  expkind k;\n  union {\n    lua_Integer ival;    /* for VKINT */\n    lua_Number nval;  /* for VKFLT */\n    int info;  /* for generic use */\n    struct {  /* for indexed variables (VINDEXED) */\n      short idx;  /* index (R/K) */\n      lu_byte t;  /* table (register or upvalue) */\n      lu_byte vt;  /* whether 't' is register (VLOCAL) or upvalue (VUPVAL) */\n    } ind;\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/* description of active local variable */\ntypedef struct Vardesc {\n  short idx;  /* variable index in stack */\n} Vardesc;\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  lu_byte nactvar;  /* local level where it appears in current block */\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 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  int pc;  /* next position to code (equivalent to 'ncode') */\n  int lasttarget;   /* 'label' of last 'jump label' */\n  int jpc;  /* list of pending jumps to 'pc' */\n  int nk;  /* number of elements in 'k' */\n  int np;  /* number of elements in 'p' */\n  int firstlocal;  /* index of first local var (in Dyndata array) */\n  short nlocvars;  /* number of elements in 'f->locvars' */\n  lu_byte nactvar;  /* number of active local variables */\n  lu_byte nups;  /* number of upvalues */\n  lu_byte freereg;  /* first free register */\n} FuncState;\n\n\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": "src/lua/lprefix.h",
    "content": "/*\n** $Id: lprefix.h,v 1.2.1.1 2017/04/19 17:20:42 roberto Exp $\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": "src/lua/lstate.c",
    "content": "/*\n** $Id: lstate.c,v 2.133.1.1 2017/04/19 17:39:34 roberto Exp $\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#if !defined(LUAI_GCPAUSE)\n#define LUAI_GCPAUSE\t200  /* 200% */\n#endif\n\n#if !defined(LUAI_GCMUL)\n#define LUAI_GCMUL\t200 /* GC runs 'twice the speed' of memory allocation */\n#endif\n\n\n/*\n** a macro to help the creation of a unique random seed when a state is\n** created; the seed is used to randomize hashes.\n*/\n#if !defined(luai_makeseed)\n#include <time.h>\n#define luai_makeseed()\t\tcast(unsigned int, time(NULL))\n#endif\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** Main thread combines a thread state and the global state\n*/\ntypedef struct LG {\n  LX l;\n  global_State g;\n} LG;\n\n\n\n#define fromstate(L)\t(cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l)))\n\n\n/*\n** Compute an initial seed as random as possible. Rely on Address Space\n** Layout Randomization (if present) to increase randomness..\n*/\n#define addbuff(b,p,e) \\\n  { size_t t = cast(size_t, e); \\\n    memcpy(b + p, &t, sizeof(t)); p += sizeof(t); }\n\nstatic unsigned int makeseed (lua_State *L) {\n  char buff[4 * sizeof(size_t)];\n  unsigned int h = luai_makeseed();\n  int p = 0;\n  addbuff(buff, p, L);  /* heap variable */\n  addbuff(buff, p, &h);  /* local variable */\n  addbuff(buff, p, luaO_nilobject);  /* global variable */\n  addbuff(buff, p, &lua_newstate);  /* public function */\n  lua_assert(p == sizeof(buff));\n  return luaS_hash(buff, p, h);\n}\n\n\n/*\n** set GCdebt to a new value keeping the value (totalbytes + GCdebt)\n** invariant (and avoiding underflows in 'totalbytes')\n*/\nvoid luaE_setdebt (global_State *g, l_mem debt) {\n  l_mem tb = gettotalbytes(g);\n  lua_assert(tb > 0);\n  if (debt < tb - MAX_LMEM)\n    debt = tb - MAX_LMEM;  /* will make 'totalbytes == MAX_LMEM' */\n  g->totalbytes = tb - debt;\n  g->GCdebt = debt;\n}\n\n\nCallInfo *luaE_extendCI (lua_State *L) {\n  CallInfo *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  L->nci++;\n  return ci;\n}\n\n\n/*\n** free all CallInfo structures not in use by a thread\n*/\nvoid luaE_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*/\nvoid luaE_shrinkCI (lua_State *L) {\n  CallInfo *ci = L->ci;\n  CallInfo *next2;  /* next's next */\n  /* while there are two nexts */\n  while (ci->next != NULL && (next2 = ci->next->next) != NULL) {\n    luaM_free(L, ci->next);  /* free next */\n    L->nci--;\n    ci->next = next2;  /* remove 'next' from the list */\n    next2->previous = ci;\n    ci = next2;  /* keep next's next */\n  }\n}\n\n\nstatic void stack_init (lua_State *L1, lua_State *L) {\n  int i; CallInfo *ci;\n  /* initialize stack array */\n  L1->stack = luaM_newvector(L, BASIC_STACK_SIZE, TValue);\n  L1->stacksize = BASIC_STACK_SIZE;\n  for (i = 0; i < BASIC_STACK_SIZE; i++)\n    setnilvalue(L1->stack + i);  /* erase new stack */\n  L1->top = L1->stack;\n  L1->stack_last = L1->stack + L1->stacksize - EXTRA_STACK;\n  /* initialize first ci */\n  ci = &L1->base_ci;\n  ci->next = ci->previous = NULL;\n  ci->callstatus = 0;\n  ci->func = L1->top;\n  setnilvalue(L1->top++);  /* 'function' entry for this 'ci' */\n  ci->top = L1->top + LUA_MINSTACK;\n  L1->ci = ci;\n}\n\n\nstatic void freestack (lua_State *L) {\n  if (L->stack == NULL)\n    return;  /* stack not completely built yet */\n  L->ci = &L->base_ci;  /* free the entire 'ci' list */\n  luaE_freeCI(L);\n  lua_assert(L->nci == 0);\n  luaM_freearray(L, L->stack, L->stacksize);  /* free stack array */\n}\n\n\n/*\n** Create registry table and its predefined values\n*/\nstatic void init_registry (lua_State *L, global_State *g) {\n  TValue temp;\n  /* create registry */\n  Table *registry = luaH_new(L);\n  sethvalue(L, &g->l_registry, registry);\n  luaH_resize(L, registry, LUA_RIDX_LAST, 0);\n  /* registry[LUA_RIDX_MAINTHREAD] = L */\n  setthvalue(L, &temp, L);  /* temp = L */\n  luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &temp);\n  /* registry[LUA_RIDX_GLOBALS] = table of globals */\n  sethvalue(L, &temp, luaH_new(L));  /* temp = new table (global table) */\n  luaH_setint(L, registry, LUA_RIDX_GLOBALS, &temp);\n}\n\n\n/*\n** open parts of the state that may cause memory-allocation errors.\n** ('g->version' != NULL flags that the state was completely build)\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->gcrunning = 1;  /* allow gc */\n  g->version = lua_version(NULL);\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 = NULL;\n  L->ci = NULL;\n  L->nci = 0;\n  L->stacksize = 0;\n  L->twups = L;  /* thread has no upvalues */\n  L->errorJmp = NULL;\n  L->nCcalls = 0;\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->nny = 1;\n  L->status = LUA_OK;\n  L->errfunc = 0;\n}\n\n\nstatic void close_state (lua_State *L) {\n  global_State *g = G(L);\n  luaF_close(L, L->stack);  /* close all upvalues for this thread */\n  luaC_freeallobjects(L);  /* collect all objects */\n  if (g->version)  /* closing a fully built state? */\n    luai_userstateclose(L);\n  luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);\n  freestack(L);\n  lua_assert(gettotalbytes(g) == sizeof(LG));\n  (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0);  /* free main block */\n}\n\n\nLUA_API lua_State *lua_newthread (lua_State *L) {\n  global_State *g = G(L);\n  lua_State *L1;\n  lua_lock(L);\n  luaC_checkGC(L);\n  /* create new thread */\n  L1 = &cast(LX *, luaM_newobject(L, LUA_TTHREAD, sizeof(LX)))->l;\n  L1->marked = luaC_white(g);\n  L1->tt = LUA_TTHREAD;\n  /* link it on list 'allgc' */\n  L1->next = g->allgc;\n  g->allgc = obj2gco(L1);\n  /* anchor it on L stack */\n  setthvalue(L, L->top, 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(g->mainthread),\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_close(L1, L1->stack);  /* close all upvalues for this thread */\n  lua_assert(L1->openupval == NULL);\n  luai_userstatefree(L, L1);\n  freestack(L1);\n  luaM_free(L, l);\n}\n\n\nLUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {\n  int i;\n  lua_State *L;\n  global_State *g;\n  LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG)));\n  if (l == NULL) return NULL;\n  L = &l->l.l;\n  g = &l->g;\n  L->next = NULL;\n  L->tt = LUA_TTHREAD;\n  g->currentwhite = bitmask(WHITE0BIT);\n  L->marked = luaC_white(g);\n  preinit_thread(L, g);\n  g->frealloc = f;\n  g->ud = ud;\n  g->mainthread = L;\n  g->seed = makeseed(L);\n  g->gcrunning = 0;  /* no GC while building state */\n  g->GCestimate = 0;\n  g->strt.size = g->strt.nuse = 0;\n  g->strt.hash = NULL;\n  setnilvalue(&g->l_registry);\n  g->panic = NULL;\n  g->version = NULL;\n  g->gcstate = GCSpause;\n  g->gckind = KGC_NORMAL;\n  g->allgc = g->finobj = g->tobefnz = g->fixedgc = 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->totalbytes = sizeof(LG);\n  g->GCdebt = 0;\n  g->gcfinnum = 0;\n  g->gcpause = LUAI_GCPAUSE;\n  g->gcstepmul = LUAI_GCMUL;\n  for (i=0; i < LUA_NUMTAGS; 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  L = G(L)->mainthread;  /* only the main thread can be closed */\n  lua_lock(L);\n  close_state(L);\n}\n\n\n"
  },
  {
    "path": "src/lua/lstate.h",
    "content": "/*\n** $Id: lstate.h,v 2.133.1.1 2017/04/19 17:39:34 roberto Exp $\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#include \"lobject.h\"\n#include \"ltm.h\"\n#include \"lzio.h\"\n\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** 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:\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** The last three lists are used only during the atomic phase.\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/* extra stack space to handle TM calls and some other extras */\n#define EXTRA_STACK   5\n\n\n#define BASIC_STACK_SIZE        (2*LUA_MINSTACK)\n\n\n/* kinds of Garbage Collection */\n#define KGC_NORMAL\t0\n#define KGC_EMERGENCY\t1\t/* gc was forced by an allocation failure */\n\n\ntypedef struct stringtable {\n  TString **hash;\n  int nuse;  /* number of elements */\n  int size;\n} stringtable;\n\n\n/*\n** Information about a call.\n** When a thread yields, 'func' is adjusted to pretend that the\n** top function has only the yielded values in its stack; in that\n** case, the actual 'func' value is saved in field 'extra'.\n** When a function calls another with a continuation, 'extra' keeps\n** the function index so that, in case of errors, the continuation\n** function can be called with the correct top.\n*/\ntypedef struct CallInfo {\n  StkId func;  /* function index in the stack */\n  StkId\ttop;  /* top for this function */\n  struct CallInfo *previous, *next;  /* dynamic call link */\n  union {\n    struct {  /* only for Lua functions */\n      StkId base;  /* base for this function */\n      const Instruction *savedpc;\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  ptrdiff_t extra;\n  short nresults;  /* expected number of results from this function */\n  unsigned short callstatus;\n} CallInfo;\n\n\n/*\n** Bits in CallInfo status\n*/\n#define CIST_OAH\t(1<<0)\t/* original value of 'allowhook' */\n#define CIST_LUA\t(1<<1)\t/* call is running a Lua function */\n#define CIST_HOOKED\t(1<<2)\t/* call is running a debug hook */\n#define CIST_FRESH\t(1<<3)\t/* call is running on a fresh invocation\n                                   of luaV_execute */\n#define CIST_YPCALL\t(1<<4)\t/* call is a yieldable protected call */\n#define CIST_TAIL\t(1<<5)\t/* call was tail called */\n#define CIST_HOOKYIELD\t(1<<6)\t/* last hook called yielded */\n#define CIST_LEQ\t(1<<7)  /* using __lt for __le */\n#define CIST_FIN\t(1<<8)  /* call is running a finalizer */\n\n#define isLua(ci)\t((ci)->callstatus & CIST_LUA)\n\n/* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */\n#define setoah(st,v)\t((st) = ((st) & ~CIST_OAH) | (v))\n#define getoah(st)\t((st) & CIST_OAH)\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 totalbytes;  /* number of bytes currently allocated - GCdebt */\n  l_mem GCdebt;  /* bytes allocated not yet compensated by the collector */\n  lu_mem GCmemtrav;  /* memory traversed by the GC */\n  lu_mem GCestimate;  /* an estimate of the non-garbage memory in use */\n  stringtable strt;  /* hash table for strings */\n  TValue l_registry;\n  unsigned int seed;  /* randomized seed for hashes */\n  lu_byte currentwhite;\n  lu_byte gcstate;  /* state of garbage collector */\n  lu_byte gckind;  /* kind of GC running */\n  lu_byte gcrunning;  /* true if GC is running */\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  struct lua_State *twups;  /* list of threads with open upvalues */\n  unsigned int gcfinnum;  /* number of finalizers to call in each GC step */\n  int gcpause;  /* size of pause between successive GCs */\n  int gcstepmul;  /* GC 'granularity' */\n  lua_CFunction panic;  /* to be called in unprotected errors */\n  struct lua_State *mainthread;\n  const lua_Number *version;  /* pointer to version number */\n  TString *memerrmsg;  /* memory-error message */\n  TString *tmname[TM_N];  /* array with tag-method names */\n  struct Table *mt[LUA_NUMTAGS];  /* metatables for basic types */\n  TString *strcache[STRCACHE_N][STRCACHE_M];  /* cache for strings in API */\n} global_State;\n\n\n/*\n** 'per thread' state\n*/\nstruct lua_State {\n  CommonHeader;\n  unsigned short nci;  /* number of items in 'ci' list */\n  lu_byte status;\n  StkId top;  /* first free slot in the stack */\n  global_State *l_G;\n  CallInfo *ci;  /* call info for current function */\n  const Instruction *oldpc;  /* last pc traced */\n  StkId stack_last;  /* last free slot in the stack */\n  StkId stack;  /* stack base */\n  UpVal *openupval;  /* list of open upvalues in this stack */\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 calling Lua) */\n  volatile lua_Hook hook;\n  ptrdiff_t errfunc;  /* current error handling function (stack index) */\n  int stacksize;\n  int basehookcount;\n  int hookcount;\n  unsigned short nny;  /* number of non-yieldable calls in stack */\n  unsigned short nCcalls;  /* number of nested C calls */\n  l_signalT hookmask;\n  lu_byte allowhook;\n};\n\n\n#define G(L)\t(L->l_G)\n\n\n/*\n** Union of all collectable objects (only for conversions)\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};\n\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_TUSERDATA, &((cast_u(o))->u))\n#define gco2lcl(o)  check_exp((o)->tt == LUA_TLCL, &((cast_u(o))->cl.l))\n#define gco2ccl(o)  check_exp((o)->tt == LUA_TCCL, &((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_TTABLE, &((cast_u(o))->h))\n#define gco2p(o)  check_exp((o)->tt == LUA_TPROTO, &((cast_u(o))->p))\n#define gco2th(o)  check_exp((o)->tt == LUA_TTHREAD, &((cast_u(o))->th))\n\n\n/* macro to convert a Lua object into a GCObject */\n#define obj2gco(v) \\\n\tcheck_exp(novariant((v)->tt) < LUA_TDEADKEY, (&(cast_u(v)->gc)))\n\n\n/* actual number of total bytes allocated */\n#define gettotalbytes(g)\tcast(lu_mem, (g)->totalbytes + (g)->GCdebt)\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 CallInfo *luaE_extendCI (lua_State *L);\nLUAI_FUNC void luaE_freeCI (lua_State *L);\nLUAI_FUNC void luaE_shrinkCI (lua_State *L);\n\n\n#endif\n\n"
  },
  {
    "path": "src/lua/lstring.c",
    "content": "/*\n** $Id: lstring.c,v 2.56.1.1 2017/04/19 17:20:42 roberto Exp $\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\n\n#define MEMERRMSG       \"not enough memory\"\n\n\n/*\n** Lua will use at most ~(2^LUAI_HASHLIMIT) bytes from a string to\n** compute its hash\n*/\n#if !defined(LUAI_HASHLIMIT)\n#define LUAI_HASHLIMIT\t\t5\n#endif\n\n\n/*\n** equality for long strings\n*/\nint luaS_eqlngstr (TString *a, TString *b) {\n  size_t len = a->u.lnglen;\n  lua_assert(a->tt == LUA_TLNGSTR && b->tt == LUA_TLNGSTR);\n  return (a == b) ||  /* same instance or... */\n    ((len == b->u.lnglen) &&  /* equal length and ... */\n     (memcmp(getstr(a), getstr(b), len) == 0));  /* equal contents */\n}\n\n\nunsigned int luaS_hash (const char *str, size_t l, unsigned int seed) {\n  unsigned int h = seed ^ cast(unsigned int, l);\n  size_t step = (l >> LUAI_HASHLIMIT) + 1;\n  for (; l >= step; l -= step)\n    h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1]));\n  return h;\n}\n\n\nunsigned int luaS_hashlongstr (TString *ts) {\n  lua_assert(ts->tt == LUA_TLNGSTR);\n  if (ts->extra == 0) {  /* no hash? */\n    ts->hash = luaS_hash(getstr(ts), ts->u.lnglen, ts->hash);\n    ts->extra = 1;  /* now it has its hash */\n  }\n  return ts->hash;\n}\n\n\n/*\n** resizes the string table\n*/\nvoid luaS_resize (lua_State *L, int newsize) {\n  int i;\n  stringtable *tb = &G(L)->strt;\n  if (newsize > tb->size) {  /* grow table if needed */\n    luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);\n    for (i = tb->size; i < newsize; i++)\n      tb->hash[i] = NULL;\n  }\n  for (i = 0; i < tb->size; i++) {  /* rehash */\n    TString *p = tb->hash[i];\n    tb->hash[i] = NULL;\n    while (p) {  /* for each node in the list */\n      TString *hnext = p->u.hnext;  /* save next */\n      unsigned int h = lmod(p->hash, newsize);  /* new position */\n      p->u.hnext = tb->hash[h];  /* chain it */\n      tb->hash[h] = p;\n      p = hnext;\n    }\n  }\n  if (newsize < tb->size) {  /* shrink table if needed */\n    /* vanishing slice should be empty */\n    lua_assert(tb->hash[newsize] == NULL && tb->hash[tb->size - 1] == NULL);\n    luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);\n  }\n  tb->size = newsize;\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  luaS_resize(L, MINSTRTABSIZE);  /* initial size of string table */\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\n\n/*\n** creates a new string object\n*/\nstatic TString *createstrobj (lua_State *L, size_t l, int tag, unsigned int h) {\n  TString *ts;\n  GCObject *o;\n  size_t totalsize;  /* total size of TString object */\n  totalsize = sizelstring(l);\n  o = luaC_newobj(L, tag, totalsize);\n  ts = gco2ts(o);\n  ts->hash = h;\n  ts->extra = 0;\n  getstr(ts)[l] = '\\0';  /* ending 0 */\n  return ts;\n}\n\n\nTString *luaS_createlngstrobj (lua_State *L, size_t l) {\n  TString *ts = createstrobj(L, l, LUA_TLNGSTR, G(L)->seed);\n  ts->u.lnglen = l;\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\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  unsigned int h = luaS_hash(str, l, g->seed);\n  TString **list = &g->strt.hash[lmod(h, g->strt.size)];\n  lua_assert(str != NULL);  /* otherwise 'memcmp'/'memcpy' are undefined */\n  for (ts = *list; ts != NULL; ts = ts->u.hnext) {\n    if (l == ts->shrlen &&\n        (memcmp(str, getstr(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  if (g->strt.nuse >= g->strt.size && g->strt.size <= MAX_INT/2) {\n    luaS_resize(L, g->strt.size * 2);\n    list = &g->strt.hash[lmod(h, g->strt.size)];  /* recompute with new size */\n  }\n  ts = createstrobj(L, l, LUA_TSHRSTR, h);\n  memcpy(getstr(ts), str, l * sizeof(char));\n  ts->shrlen = cast_byte(l);\n  ts->u.hnext = *list;\n  *list = ts;\n  g->strt.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 >= (MAX_SIZE - sizeof(TString))/sizeof(char))\n      luaM_toobig(L);\n    ts = luaS_createlngstrobj(L, l);\n    memcpy(getstr(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) {\n  Udata *u;\n  GCObject *o;\n  if (s > MAX_SIZE - sizeof(Udata))\n    luaM_toobig(L);\n  o = luaC_newobj(L, LUA_TUSERDATA, sizeludata(s));\n  u = gco2u(o);\n  u->len = s;\n  u->metatable = NULL;\n  setuservalue(L, u, luaO_nilobject);\n  return u;\n}\n\n"
  },
  {
    "path": "src/lua/lstring.h",
    "content": "/*\n** $Id: lstring.h,v 1.61.1.1 2017/04/19 17:20:42 roberto Exp $\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#define sizelstring(l)  (sizeof(union UTString) + ((l) + 1) * sizeof(char))\n\n#define sizeludata(l)\t(sizeof(union UUdata) + (l))\n#define sizeudata(u)\tsizeludata((u)->len)\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((s)->tt == LUA_TSHRSTR && (s)->extra > 0)\n\n\n/*\n** equality for short strings, which are always internalized\n*/\n#define eqshrstr(a,b)\tcheck_exp((a)->tt == LUA_TSHRSTR, (a) == (b))\n\n\nLUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed);\nLUAI_FUNC unsigned int luaS_hashlongstr (TString *ts);\nLUAI_FUNC int luaS_eqlngstr (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);\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);\n\n\n#endif\n"
  },
  {
    "path": "src/lua/lstrlib.c",
    "content": "/*\n** $Id: lstrlib.c,v 1.254.1.1 2017/04/19 17:29:57 roberto Exp $\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 <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\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\n/* macro to 'unsign' a character */\n#define uchar(c)\t((unsigned char)(c))\n\n\n/*\n** Some sizes are better limited to fit in 'int', but must also fit in\n** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.)\n*/\n#define MAX_SIZET\t((size_t)(~(size_t)0))\n\n#define MAXSIZE  \\\n\t(sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX))\n\n\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/* translate a relative string position: negative means back from end */\nstatic lua_Integer 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\nstatic int str_sub (lua_State *L) {\n  size_t l;\n  const char *s = luaL_checklstring(L, 1, &l);\n  lua_Integer start = posrelat(luaL_checkinteger(L, 2), l);\n  lua_Integer end = posrelat(luaL_optinteger(L, 3, -1), l);\n  if (start < 1) start = 1;\n  if (end > (lua_Integer)l) end = l;\n  if (start <= end)\n    lua_pushlstring(L, s + start - 1, (size_t)(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] = tolower(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] = toupper(uchar(s[i]));\n  luaL_pushresultsize(&b, l);\n  return 1;\n}\n\n\nstatic int str_rep (lua_State *L) {\n  size_t l, lsep;\n  const char *s = luaL_checklstring(L, 1, &l);\n  lua_Integer n = luaL_checkinteger(L, 2);\n  const char *sep = luaL_optlstring(L, 3, \"\", &lsep);\n  if (n <= 0) lua_pushliteral(L, \"\");\n  else if (l + lsep < l || l + lsep > MAXSIZE / n)  /* may overflow? */\n    return luaL_error(L, \"resulting string too large\");\n  else {\n    size_t totallen = (size_t)n * l + (size_t)(n - 1) * 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, l * sizeof(char)); p += l;\n      if (lsep > 0) {  /* empty 'memcpy' is not that cheap */\n        memcpy(p, sep, lsep * sizeof(char));\n        p += lsep;\n      }\n    }\n    memcpy(p, s, l * sizeof(char));  /* last copy (not followed by 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 posi = posrelat(luaL_optinteger(L, 2, 1), l);\n  lua_Integer pose = posrelat(luaL_optinteger(L, 3, posi), l);\n  int n, i;\n  if (posi < 1) posi = 1;\n  if (pose > (lua_Integer)l) pose = l;\n  if (posi > pose) return 0;  /* empty interval; return no values */\n  if (pose - posi >= 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, uchar(s[posi+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, n);\n  for (i=1; i<=n; i++) {\n    lua_Integer c = luaL_checkinteger(L, i);\n    luaL_argcheck(L, uchar(c) == c, i, \"value out of range\");\n    p[i - 1] = uchar(c);\n  }\n  luaL_pushresultsize(&b, n);\n  return 1;\n}\n\n\nstatic int writer (lua_State *L, const void *b, size_t size, void *B) {\n  (void)L;\n  luaL_addlstring((luaL_Buffer *) B, (const char *)b, size);\n  return 0;\n}\n\n\nstatic int str_dump (lua_State *L) {\n  luaL_Buffer b;\n  int strip = lua_toboolean(L, 2);\n  luaL_checktype(L, 1, LUA_TFUNCTION);\n  lua_settop(L, 1);\n  luaL_buffinit(L,&b);\n  if (lua_dump(L, writer, &b, strip) != 0)\n    return luaL_error(L, \"unable to dump given function\");\n  luaL_pushresult(&b);\n  return 1;\n}\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  unsigned char level;  /* total number of captures (finished or unfinished) */\n  struct {\n    const char *init;\n    ptrdiff_t len;\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 < 0 || l >= ms->level || 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 (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 (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, uchar(*p)))\n        return sig;\n    }\n    else if ((*(p+1) == '-') && (p+2 < ec)) {\n      p+=2;\n      if (uchar(*(p-2)) <= c && c <= uchar(*p))\n        return sig;\n    }\n    else if (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 = uchar(*s);\n    switch (*p) {\n      case '.': return 1;  /* matches any char */\n      case L_ESC: return match_class(c, uchar(*(p+1)));\n      case '[': return matchbracketclass(c, p, ep-1);\n      default:  return (uchar(*p) == c);\n    }\n  }\n}\n\n\nstatic const char *matchbalance (MatchState *ms, const char *s,\n                                   const char *p) {\n  if (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 = 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 (ms->matchdepth-- == 0)\n    luaL_error(ms->L, \"pattern too complex\");\n  init: /* using goto's 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 (*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(uchar(previous), p, ep - 1) &&\n               matchbracketclass(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, 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 -= init-s1;\n        s1 = init;\n      }\n    }\n    return NULL;  /* not found */\n  }\n}\n\n\nstatic void push_onecapture (MatchState *ms, int i, const char *s,\n                                                    const char *e) {\n  if (i >= ms->level) {\n    if (i == 0)  /* ms->level == 0, too */\n      lua_pushlstring(ms->L, s, e - s);  /* add whole match */\n    else\n      luaL_error(ms->L, \"invalid capture index %%%d\", i + 1);\n  }\n  else {\n    ptrdiff_t l = ms->capture[i].len;\n    if (l == CAP_UNFINISHED) luaL_error(ms->L, \"unfinished capture\");\n    if (l == CAP_POSITION)\n      lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1);\n    else\n      lua_pushlstring(ms->L, ms->capture[i].init, l);\n  }\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  lua_Integer init = posrelat(luaL_optinteger(L, 3, 1), ls);\n  if (init < 1) init = 1;\n  else if (init > (lua_Integer)ls + 1) {  /* start after string's end? */\n    lua_pushnil(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 - 1, ls - (size_t)init + 1, p, lp);\n    if (s2) {\n      lua_pushinteger(L, (s2 - s) + 1);\n      lua_pushinteger(L, (s2 - s) + lp);\n      return 2;\n    }\n  }\n  else {\n    MatchState ms;\n    const char *s1 = s + init - 1;\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, (s1 - s) + 1);  /* start */\n          lua_pushinteger(L, 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  lua_pushnil(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  GMatchState *gm;\n  lua_settop(L, 2);  /* keep them on closure to avoid being collected */\n  gm = (GMatchState *)lua_newuserdata(L, sizeof(GMatchState));\n  prepstate(&gm->ms, L, s, ls, p, lp);\n  gm->src = s; 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, i;\n  lua_State *L = ms->L;\n  const char *news = lua_tolstring(L, 3, &l);\n  for (i = 0; i < l; i++) {\n    if (news[i] != L_ESC)\n      luaL_addchar(b, news[i]);\n    else {\n      i++;  /* skip ESC */\n      if (!isdigit(uchar(news[i]))) {\n        if (news[i] != L_ESC)\n          luaL_error(L, \"invalid use of '%c' in replacement string\", L_ESC);\n        luaL_addchar(b, news[i]);\n      }\n      else if (news[i] == '0')\n          luaL_addlstring(b, s, e - s);\n      else {\n        push_onecapture(ms, news[i] - '1', s, e);\n        luaL_tolstring(L, -1, NULL);  /* if number, convert it to string */\n        lua_remove(L, -2);  /* remove original value */\n        luaL_addvalue(b);  /* add capture to accumulated result */\n      }\n    }\n  }\n}\n\n\nstatic void 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: {\n      int n;\n      lua_pushvalue(L, 3);\n      n = push_captures(ms, s, e);\n      lua_call(L, n, 1);\n      break;\n    }\n    case LUA_TTABLE: {\n      push_onecapture(ms, 0, s, e);\n      lua_gettable(L, 3);\n      break;\n    }\n    default: {  /* LUA_TNUMBER or LUA_TSTRING */\n      add_s(ms, b, s, e);\n      return;\n    }\n  }\n  if (!lua_toboolean(L, -1)) {  /* nil or false? */\n    lua_pop(L, 1);\n    lua_pushlstring(L, s, e - s);  /* keep original text */\n  }\n  else if (!lua_isstring(L, -1))\n    luaL_error(L, \"invalid replacement value (a %s)\", luaL_typename(L, -1));\n  luaL_addvalue(b);  /* add result to accumulator */\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  lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1);  /* max replacements */\n  int anchor = (*p == '^');\n  lua_Integer n = 0;  /* replacement count */\n  MatchState ms;\n  luaL_Buffer b;\n  luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||\n                   tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,\n                      \"string/function/table expected\");\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      add_value(&ms, &b, src, e, tr);  /* add replacement to buffer */\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  luaL_addlstring(&b, src, ms.src_end-src);\n  luaL_pushresult(&b);\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#include <math.h>\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_mathlim(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, int 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] = (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, int 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    int n = 0;  /* character count */\n    if (m < 0) {  /* is number negative? */\n      buff[n++] = '-';  /* add signal */\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 += l_sprintf(buff + n, sz - n, \"p%+d\", e);  /* add exponent */\n    lua_assert(n < sz);\n    return n;\n  }\n}\n\n\nstatic int lua_number2strx (lua_State *L, char *buff, int 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] = toupper(uchar(buff[i]));\n  }\n  else if (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 of each formatted item. This maximum 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 then rounded to 120 for \"extra\n** expenses\", such as locale-dependent stuff)\n*/\n#define MAX_ITEM        (120 + l_mathlim(MAX_10_EXP))\n\n\n/* valid flags in a format specification */\n#define FLAGS\t\"-+ #0\"\n\n/*\n** maximum size of each format specification (such as \"%-099.99d\")\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(uchar(*s))) {\n      char buff[10];\n      if (!isdigit(uchar(*(s+1))))\n        l_sprintf(buff, sizeof(buff), \"\\\\%d\", (int)uchar(*s));\n      else\n        l_sprintf(buff, sizeof(buff), \"\\\\%03d\", (int)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** Ensures the 'buff' string uses a dot as the radix character.\n*/\nstatic void checkdp (char *buff, int nb) {\n  if (memchr(buff, '.', nb) == NULL) {  /* no dot? */\n    char point = lua_getlocaledecpoint();  /* try locale point */\n    char *ppoint = (char *)memchr(buff, point, nb);\n    if (ppoint) *ppoint = '.';  /* change it to a dot */\n  }\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        lua_Number n = lua_tonumber(L, arg);  /* write as hexa ('%a') */\n        nb = lua_number2strx(L, buff, MAX_ITEM, \"%\" LUA_NUMBER_FRMLEN \"a\", n);\n        checkdp(buff, nb);  /* ensure it uses a dot */\n      }\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 hexa */\n                           : LUA_INTEGER_FMT;  /* else use default format */\n        nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);\n      }\n      luaL_addsize(b, 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 *scanformat (lua_State *L, const char *strfrmt, char *form) {\n  const char *p = strfrmt;\n  while (*p != '\\0' && strchr(FLAGS, *p) != NULL) p++;  /* skip flags */\n  if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))\n    luaL_error(L, \"invalid format (repeated flags)\");\n  if (isdigit(uchar(*p))) p++;  /* skip width */\n  if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */\n  if (*p == '.') {\n    p++;\n    if (isdigit(uchar(*p))) p++;  /* skip precision */\n    if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */\n  }\n  if (isdigit(uchar(*p)))\n    luaL_error(L, \"invalid format (width or precision too long)\");\n  *(form++) = '%';\n  memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char));\n  form += (p - strfrmt) + 1;\n  *form = '\\0';\n  return p;\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  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      char *buff = luaL_prepbuffsize(&b, MAX_ITEM);  /* to put formatted item */\n      int nb = 0;  /* number of bytes in added item */\n      if (++arg > top)\n        luaL_argerror(L, arg, \"no value\");\n      strfrmt = scanformat(L, strfrmt, form);\n      switch (*strfrmt++) {\n        case 'c': {\n          nb = l_sprintf(buff, MAX_ITEM, form, (int)luaL_checkinteger(L, arg));\n          break;\n        }\n        case 'd': case 'i':\n        case 'o': case 'u': case 'x': case 'X': {\n          lua_Integer n = luaL_checkinteger(L, arg);\n          addlenmod(form, LUA_INTEGER_FRMLEN);\n          nb = l_sprintf(buff, MAX_ITEM, form, (LUAI_UACINT)n);\n          break;\n        }\n        case 'a': case 'A':\n          addlenmod(form, LUA_NUMBER_FRMLEN);\n          nb = lua_number2strx(L, buff, MAX_ITEM, form,\n                                  luaL_checknumber(L, arg));\n          break;\n        case 'e': case 'E': case 'f':\n        case 'g': case 'G': {\n          lua_Number n = luaL_checknumber(L, arg);\n          addlenmod(form, LUA_NUMBER_FRMLEN);\n          nb = l_sprintf(buff, MAX_ITEM, form, (LUAI_UACNUMBER)n);\n          break;\n        }\n        case 'q': {\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            if (!strchr(form, '.') && 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, MAX_ITEM, 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 option '%%%c' to 'format'\",\n                               *(strfrmt - 1));\n        }\n      }\n      lua_assert(nb < MAX_ITEM);\n      luaL_addsize(&b, 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/* dummy structure to get native alignment requirements */\nstruct cD {\n  char c;\n  union { double d; void *p; lua_Integer i; lua_Number n; } u;\n};\n\n#define MAXALIGN\t(offsetof(struct cD, u))\n\n\n/*\n** Union for serializing floats\n*/\ntypedef union Ftypes {\n  float f;\n  double d;\n  lua_Number n;\n  char buff[5 * sizeof(lua_Number)];  /* enough for any float type */\n} Ftypes;\n\n\n/*\n** information to pack/unpack stuff\n*/\ntypedef struct Header {\n  lua_State *L;\n  int islittle;\n  int 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/* 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 int getnum (const char **fmt, int df) {\n  if (!digit(**fmt))  /* no number? */\n    return df;  /* return default value */\n  else {\n    int a = 0;\n    do {\n      a = a*10 + (*((*fmt)++) - '0');\n    } while (digit(**fmt) && a <= ((int)MAXSIZE - 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 for integers.\n*/\nstatic int getnumlimit (Header *h, const char **fmt, int df) {\n  int sz = getnum(fmt, df);\n  if (sz > MAXINTSIZE || sz <= 0)\n    return luaL_error(h->L, \"integral size (%d) out of limits [1,%d]\",\n                            sz, MAXINTSIZE);\n  return 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, int *size) {\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 'd': *size = sizeof(double); return Kfloat;\n    case 'n': *size = sizeof(lua_Number); return Kfloat;\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, -1);\n      if (*size == -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 '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break;\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,\n                           const char **fmt, int *psize, int *ntoalign) {\n  KOption opt = getoption(h, fmt, psize);\n  int 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 ((align & (align - 1)) != 0)  /* is 'align' not a power of 2? */\n      luaL_argerror(h->L, 1, \"format asks for alignment not power of 2\");\n    *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);\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, int size, int neg) {\n  char *buff = luaL_prepbuffsize(b, size);\n  int 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 (volatile char *dest, volatile const char *src,\n                            int size, int islittle) {\n  if (islittle == nativeendian.little) {\n    while (size-- != 0)\n      *(dest++) = *(src++);\n  }\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    int size, ntoalign;\n    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);\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, 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, size, 0);\n        break;\n      }\n      case Kfloat: {  /* floating-point options */\n        volatile Ftypes u;\n        char *buff = luaL_prepbuffsize(&b, size);\n        lua_Number n = luaL_checknumber(L, arg);  /* get argument */\n        if (size == sizeof(u.f)) u.f = (float)n;  /* copy it into 'u' */\n        else if (size == sizeof(u.d)) u.d = (double)n;\n        else u.n = n;\n        /* move 'u' to final result, correcting endianness if needed */\n        copywithendian(buff, u.buff, size, 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_t)size, arg,\n                         \"string longer than given size\");\n        luaL_addlstring(&b, s, len);  /* add string */\n        while (len++ < (size_t)size)  /* pad extra space */\n          luaL_addchar(&b, LUAL_PACKPADBYTE);\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 >= (int)sizeof(size_t) ||\n                         len < ((size_t)1 << (size * NB)),\n                         arg, \"string length does not fit in given size\");\n        packint(&b, (lua_Unsigned)len, h.islittle, size, 0);  /* pack length */\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    int size, ntoalign;\n    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);\n    size += ntoalign;  /* total space used by option */\n    luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,\n                     \"format result too large\");\n    totalsize += size;\n    switch (opt) {\n      case Kstring:  /* strings with length count */\n      case Kzstr:    /* zero-terminated string */\n        luaL_argerror(L, 1, \"variable-length format\");\n        /* call never return, but to avoid warnings: *//* FALLTHROUGH */\n      default:  break;\n    }\n  }\n  lua_pushinteger(L, (lua_Integer)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 ((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 = (size_t)posrelat(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    int size, ntoalign;\n    KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);\n    if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld)\n      luaL_argerror(L, 2, \"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, size,\n                                       (opt == Kint));\n        lua_pushinteger(L, res);\n        break;\n      }\n      case Kfloat: {\n        volatile Ftypes u;\n        lua_Number num;\n        copywithendian(u.buff, data + pos, size, h.islittle);\n        if (size == sizeof(u.f)) num = (lua_Number)u.f;\n        else if (size == sizeof(u.d)) num = (lua_Number)u.d;\n        else num = u.n;\n        lua_pushnumber(L, num);\n        break;\n      }\n      case Kchar: {\n        lua_pushlstring(L, data + pos, size);\n        break;\n      }\n      case Kstring: {\n        size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0);\n        luaL_argcheck(L, pos + len + size <= ld, 2, \"data string too short\");\n        lua_pushlstring(L, data + pos + size, len);\n        pos += len;  /* skip string */\n        break;\n      }\n      case Kzstr: {\n        size_t len = (int)strlen(data + pos);\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, 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  lua_createtable(L, 0, 1);  /* table to be metatable for strings */\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": "src/lua/ltable.c",
    "content": "/*\n** $Id: ltable.c,v 2.118.1.4 2018/06/08 16:22:51 roberto Exp $\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\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** Maximum size of array part (MAXASIZE) is 2^MAXABITS. MAXABITS is\n** the largest integer such that MAXASIZE fits in an unsigned int.\n*/\n#define MAXABITS\tcast_int(sizeof(int) * CHAR_BIT - 1)\n#define MAXASIZE\t(1u << MAXABITS)\n\n/*\n** Maximum size of hash part is 2^MAXHBITS. MAXHBITS is the largest\n** integer such that 2^MAXHBITS fits in a signed int. (Note that the\n** maximum number of elements in a table, 2^MAXABITS + 2^MAXHBITS, still\n** fits comfortably in an unsigned int.)\n*/\n#define MAXHBITS\t(MAXABITS - 1)\n\n\n#define hashpow2(t,n)\t\t(gnode(t, lmod((n), sizenode(t))))\n\n#define hashstr(t,str)\t\thashpow2(t, (str)->hash)\n#define hashboolean(t,p)\thashpow2(t, p)\n#define hashint(t,i)\t\thashpow2(t, i)\n\n\n/*\n** for some types, it is better to avoid modulus by power of 2, as\n** they tend to have many 2 factors.\n*/\n#define hashmod(t,n)\t(gnode(t, ((n) % ((sizenode(t)-1)|1))))\n\n\n#define hashpointer(t,p)\thashmod(t, point2uint(p))\n\n\n#define dummynode\t\t(&dummynode_)\n\nstatic const Node dummynode_ = {\n  {NILCONSTANT},  /* value */\n  {{NILCONSTANT, 0}}  /* key */\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 does not has 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 int 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(unsigned int, i) + cast(unsigned int, ni);\n    return cast_int(u <= cast(unsigned int, INT_MAX) ? u : ~u);\n  }\n}\n#endif\n\n\n/*\n** returns the 'main' position of an element in a table (that is, the index\n** of its hash value)\n*/\nstatic Node *mainposition (const Table *t, const TValue *key) {\n  switch (ttype(key)) {\n    case LUA_TNUMINT:\n      return hashint(t, ivalue(key));\n    case LUA_TNUMFLT:\n      return hashmod(t, l_hashfloat(fltvalue(key)));\n    case LUA_TSHRSTR:\n      return hashstr(t, tsvalue(key));\n    case LUA_TLNGSTR:\n      return hashpow2(t, luaS_hashlongstr(tsvalue(key)));\n    case LUA_TBOOLEAN:\n      return hashboolean(t, bvalue(key));\n    case LUA_TLIGHTUSERDATA:\n      return hashpointer(t, pvalue(key));\n    case LUA_TLCF:\n      return hashpointer(t, fvalue(key));\n    default:\n      lua_assert(!ttisdeadkey(key));\n      return hashpointer(t, gcvalue(key));\n  }\n}\n\n\n/*\n** returns the index for 'key' if 'key' is an appropriate key to live in\n** the array part of the table, 0 otherwise.\n*/\nstatic unsigned int arrayindex (const TValue *key) {\n  if (ttisinteger(key)) {\n    lua_Integer k = ivalue(key);\n    if (0 < k && (lua_Unsigned)k <= MAXASIZE)\n      return cast(unsigned int, k);  /* 'key' is an appropriate array index */\n  }\n  return 0;  /* 'key' did not match some condition */\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 int findindex (lua_State *L, Table *t, StkId key) {\n  unsigned int i;\n  if (ttisnil(key)) return 0;  /* first iteration */\n  i = arrayindex(key);\n  if (i != 0 && i <= t->sizearray)  /* is 'key' inside array part? */\n    return i;  /* yes; that's the index */\n  else {\n    int nx;\n    Node *n = mainposition(t, key);\n    for (;;) {  /* check whether 'key' is somewhere in the chain */\n      /* key may be dead already, but it is ok to use it in 'next' */\n      if (luaV_rawequalobj(gkey(n), key) ||\n            (ttisdeadkey(gkey(n)) && iscollectable(key) &&\n             deadvalue(gkey(n)) == gcvalue(key))) {\n        i = cast_int(n - gnode(t, 0));  /* key index in hash table */\n        /* hash elements are numbered after array ones */\n        return (i + 1) + t->sizearray;\n      }\n      nx = gnext(n);\n      if (nx == 0)\n        luaG_runerror(L, \"invalid key to 'next'\");  /* key not found */\n      else n += nx;\n    }\n  }\n}\n\n\nint luaH_next (lua_State *L, Table *t, StkId key) {\n  unsigned int i = findindex(L, t, key);  /* find original element */\n  for (; i < t->sizearray; i++) {  /* try first array part */\n    if (!ttisnil(&t->array[i])) {  /* a non-nil value? */\n      setivalue(key, i + 1);\n      setobj2s(L, key+1, &t->array[i]);\n      return 1;\n    }\n  }\n  for (i -= t->sizearray; cast_int(i) < sizenode(t); i++) {  /* hash part */\n    if (!ttisnil(gval(gnode(t, i)))) {  /* a non-nil value? */\n      setobj2s(L, key, gkey(gnode(t, i)));\n      setobj2s(L, key+1, gval(gnode(t, i)));\n      return 1;\n    }\n  }\n  return 0;  /* no more elements */\n}\n\n\n/*\n** {=============================================================\n** Rehash\n** ==============================================================\n*/\n\n/*\n** Compute the optimal size for the array part of table 't'. 'nums' is a\n** \"count array\" where 'nums[i]' is the number of integers in the table\n** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of\n** integer keys in the table and leaves with the number of keys that\n** will go to the array part; return the optimal size.\n*/\nstatic unsigned int computesizes (unsigned int nums[], unsigned int *pna) {\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  /* loop while keys can fill more than half of total size */\n  for (i = 0, twotoi = 1;\n       twotoi > 0 && *pna > twotoi / 2;\n       i++, twotoi *= 2) {\n    if (nums[i] > 0) {\n      a += nums[i];\n      if (a > twotoi/2) {  /* more than half elements present? */\n        optimal = twotoi;  /* optimal size (till now) */\n        na = a;  /* all elements up to 'optimal' will go to array part */\n      }\n    }\n  }\n  lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);\n  *pna = na;\n  return optimal;\n}\n\n\nstatic int countint (const TValue *key, unsigned int *nums) {\n  unsigned int k = arrayindex(key);\n  if (k != 0) {  /* is 'key' an appropriate array index? */\n    nums[luaO_ceillog2(k)]++;  /* count as such */\n    return 1;\n  }\n  else\n    return 0;\n}\n\n\n/*\n** Count keys in array part of table 't': Fill 'nums[i]' with\n** number of keys that will go into corresponding slice and return\n** total number of non-nil keys.\n*/\nstatic unsigned int numusearray (const Table *t, unsigned int *nums) {\n  int lg;\n  unsigned int ttlg;  /* 2^lg */\n  unsigned int ause = 0;  /* summation of 'nums' */\n  unsigned int i = 1;  /* count to traverse all array keys */\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 > t->sizearray) {\n      lim = t->sizearray;  /* 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 (!ttisnil(&t->array[i-1]))\n        lc++;\n    }\n    nums[lg] += lc;\n    ause += lc;\n  }\n  return ause;\n}\n\n\nstatic int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {\n  int totaluse = 0;  /* total number of elements */\n  int ause = 0;  /* elements added to 'nums' (can go to array part) */\n  int i = sizenode(t);\n  while (i--) {\n    Node *n = &t->node[i];\n    if (!ttisnil(gval(n))) {\n      ause += countint(gkey(n), nums);\n      totaluse++;\n    }\n  }\n  *pna += ause;\n  return totaluse;\n}\n\n\nstatic void setarrayvector (lua_State *L, Table *t, unsigned int size) {\n  unsigned int i;\n  luaM_reallocvector(L, t->array, t->sizearray, size, TValue);\n  for (i=t->sizearray; i<size; i++)\n     setnilvalue(&t->array[i]);\n  t->sizearray = size;\n}\n\n\nstatic void setnodevector (lua_State *L, Table *t, unsigned int size) {\n  if (size == 0) {  /* no elements to hash part? */\n    t->node = cast(Node *, dummynode);  /* use common 'dummynode' */\n    t->lsizenode = 0;\n    t->lastfree = NULL;  /* signal that it is using dummy node */\n  }\n  else {\n    int i;\n    int lsize = luaO_ceillog2(size);\n    if (lsize > MAXHBITS)\n      luaG_runerror(L, \"table overflow\");\n    size = twoto(lsize);\n    t->node = luaM_newvector(L, size, Node);\n    for (i = 0; i < (int)size; i++) {\n      Node *n = gnode(t, i);\n      gnext(n) = 0;\n      setnilvalue(wgkey(n));\n      setnilvalue(gval(n));\n    }\n    t->lsizenode = cast_byte(lsize);\n    t->lastfree = gnode(t, size);  /* all positions are free */\n  }\n}\n\n\ntypedef struct {\n  Table *t;\n  unsigned int nhsize;\n} AuxsetnodeT;\n\n\nstatic void auxsetnode (lua_State *L, void *ud) {\n  AuxsetnodeT *asn = cast(AuxsetnodeT *, ud);\n  setnodevector(L, asn->t, asn->nhsize);\n}\n\n\nvoid luaH_resize (lua_State *L, Table *t, unsigned int nasize,\n                                          unsigned int nhsize) {\n  unsigned int i;\n  int j;\n  AuxsetnodeT asn;\n  unsigned int oldasize = t->sizearray;\n  int oldhsize = allocsizenode(t);\n  Node *nold = t->node;  /* save old hash ... */\n  if (nasize > oldasize)  /* array part must grow? */\n    setarrayvector(L, t, nasize);\n  /* create new hash part with appropriate size */\n  asn.t = t; asn.nhsize = nhsize;\n  if (luaD_rawrunprotected(L, auxsetnode, &asn) != LUA_OK) {  /* mem. error? */\n    setarrayvector(L, t, oldasize);  /* array back to its original size */\n    luaD_throw(L, LUA_ERRMEM);  /* rethrow memory error */\n  }\n  if (nasize < oldasize) {  /* array part must shrink? */\n    t->sizearray = nasize;\n    /* re-insert elements from vanishing slice */\n    for (i=nasize; i<oldasize; i++) {\n      if (!ttisnil(&t->array[i]))\n        luaH_setint(L, t, i + 1, &t->array[i]);\n    }\n    /* shrink array */\n    luaM_reallocvector(L, t->array, oldasize, nasize, TValue);\n  }\n  /* re-insert elements from hash part */\n  for (j = oldhsize - 1; j >= 0; j--) {\n    Node *old = nold + j;\n    if (!ttisnil(gval(old))) {\n      /* doesn't need barrier/invalidate cache, as entry was\n         already present in the table */\n      setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old));\n    }\n  }\n  if (oldhsize > 0)  /* not the dummy node? */\n    luaM_freearray(L, nold, cast(size_t, oldhsize)); /* free old hash */\n}\n\n\nvoid luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {\n  int nsize = allocsizenode(t);\n  luaH_resize(L, t, nasize, nsize);\n}\n\n/*\n** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i\n*/\nstatic void rehash (lua_State *L, Table *t, const TValue *ek) {\n  unsigned int asize;  /* optimal size for array part */\n  unsigned int na;  /* number of keys in the array part */\n  unsigned int nums[MAXABITS + 1];\n  int i;\n  int totaluse;\n  for (i = 0; i <= MAXABITS; i++) nums[i] = 0;  /* reset counts */\n  na = numusearray(t, nums);  /* count keys in array part */\n  totaluse = na;  /* all those keys are integer keys */\n  totaluse += numusehash(t, nums, &na);  /* count keys in hash part */\n  /* count extra key */\n  na += countint(ek, nums);\n  totaluse++;\n  /* compute new size for array part */\n  asize = computesizes(nums, &na);\n  /* resize the table to new computed sizes */\n  luaH_resize(L, t, asize, totaluse - na);\n}\n\n\n\n/*\n** }=============================================================\n*/\n\n\nTable *luaH_new (lua_State *L) {\n  GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table));\n  Table *t = gco2t(o);\n  t->metatable = NULL;\n  t->flags = cast_byte(~0);\n  t->array = NULL;\n  t->sizearray = 0;\n  setnodevector(L, t, 0);\n  return t;\n}\n\n\nvoid luaH_free (lua_State *L, Table *t) {\n  if (!isdummy(t))\n    luaM_freearray(L, t->node, cast(size_t, sizenode(t)));\n  luaM_freearray(L, t->array, t->sizearray);\n  luaM_free(L, t);\n}\n\n\nstatic Node *getfreepos (Table *t) {\n  if (!isdummy(t)) {\n    while (t->lastfree > t->node) {\n      t->lastfree--;\n      if (ttisnil(gkey(t->lastfree)))\n        return t->lastfree;\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 and\n** put new key in its main position; otherwise (colliding node is in its main\n** position), new key goes to an empty position.\n*/\nTValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {\n  Node *mp;\n  TValue aux;\n  if (ttisnil(key)) luaG_runerror(L, \"table index is nil\");\n  else if (ttisfloat(key)) {\n    lua_Integer k;\n    if (luaV_tointeger(key, &k, 0)) {  /* does index fit in an integer? */\n      setivalue(&aux, k);\n      key = &aux;  /* insert it as an integer */\n    }\n    else if (luai_numisnan(fltvalue(key)))\n      luaG_runerror(L, \"table index is NaN\");\n  }\n  mp = mainposition(t, key);\n  if (!ttisnil(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      rehash(L, t, key);  /* grow table */\n      /* whatever called 'newkey' takes care of TM cache */\n      return luaH_set(L, t, key);  /* insert key into grown table */\n    }\n    lua_assert(!isdummy(t));\n    othern = mainposition(t, gkey(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      setnilvalue(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(L, &mp->i_key, key);\n  luaC_barrierback(L, t, key);\n  lua_assert(ttisnil(gval(mp)));\n  return gval(mp);\n}\n\n\n/*\n** search function for integers\n*/\nconst TValue *luaH_getint (Table *t, lua_Integer key) {\n  /* (1 <= key && key <= t->sizearray) */\n  if (l_castS2U(key) - 1 < t->sizearray)\n    return &t->array[key - 1];\n  else {\n    Node *n = hashint(t, key);\n    for (;;) {  /* check whether 'key' is somewhere in the chain */\n      if (ttisinteger(gkey(n)) && ivalue(gkey(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 luaO_nilobject;\n  }\n}\n\n\n/*\n** search function for short strings\n*/\nconst TValue *luaH_getshortstr (Table *t, TString *key) {\n  Node *n = hashstr(t, key);\n  lua_assert(key->tt == LUA_TSHRSTR);\n  for (;;) {  /* check whether 'key' is somewhere in the chain */\n    const TValue *k = gkey(n);\n    if (ttisshrstring(k) && eqshrstr(tsvalue(k), key))\n      return gval(n);  /* that's it */\n    else {\n      int nx = gnext(n);\n      if (nx == 0)\n        return luaO_nilobject;  /* not found */\n      n += nx;\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*/\nstatic const TValue *getgeneric (Table *t, const TValue *key) {\n  Node *n = mainposition(t, key);\n  for (;;) {  /* check whether 'key' is somewhere in the chain */\n    if (luaV_rawequalobj(gkey(n), key))\n      return gval(n);  /* that's it */\n    else {\n      int nx = gnext(n);\n      if (nx == 0)\n        return luaO_nilobject;  /* not found */\n      n += nx;\n    }\n  }\n}\n\n\nconst TValue *luaH_getstr (Table *t, TString *key) {\n  if (key->tt == LUA_TSHRSTR)\n    return luaH_getshortstr(t, key);\n  else {  /* for long strings, use generic case */\n    TValue ko;\n    setsvalue(cast(lua_State *, NULL), &ko, key);\n    return getgeneric(t, &ko);\n  }\n}\n\n\n/*\n** main search function\n*/\nconst TValue *luaH_get (Table *t, const TValue *key) {\n  switch (ttype(key)) {\n    case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key));\n    case LUA_TNUMINT: return luaH_getint(t, ivalue(key));\n    case LUA_TNIL: return luaO_nilobject;\n    case LUA_TNUMFLT: {\n      lua_Integer k;\n      if (luaV_tointeger(key, &k, 0)) /* index is int? */\n        return luaH_getint(t, k);  /* use specialized version */\n      /* else... */\n    }  /* FALLTHROUGH */\n    default:\n      return getgeneric(t, key);\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*/\nTValue *luaH_set (lua_State *L, Table *t, const TValue *key) {\n  const TValue *p = luaH_get(t, key);\n  if (p != luaO_nilobject)\n    return cast(TValue *, p);\n  else return luaH_newkey(L, t, key);\n}\n\n\nvoid luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {\n  const TValue *p = luaH_getint(t, key);\n  TValue *cell;\n  if (p != luaO_nilobject)\n    cell = cast(TValue *, p);\n  else {\n    TValue k;\n    setivalue(&k, key);\n    cell = luaH_newkey(L, t, &k);\n  }\n  setobj2t(L, cell, value);\n}\n\n\nstatic lua_Unsigned unbound_search (Table *t, lua_Unsigned j) {\n  lua_Unsigned i = j;  /* i is zero or a present index */\n  j++;\n  /* find 'i' and 'j' such that i is present and j is not */\n  while (!ttisnil(luaH_getint(t, j))) {\n    i = j;\n    if (j > l_castS2U(LUA_MAXINTEGER) / 2) {  /* overflow? */\n      /* table was built with bad purposes: resort to linear search */\n      i = 1;\n      while (!ttisnil(luaH_getint(t, i))) i++;\n      return i - 1;\n    }\n    j *= 2;\n  }\n  /* now do a binary search between them */\n  while (j - i > 1) {\n    lua_Unsigned m = (i+j)/2;\n    if (ttisnil(luaH_getint(t, m))) j = m;\n    else i = m;\n  }\n  return i;\n}\n\n\n/*\n** Try to find a boundary in table 't'. A 'boundary' is an integer index\n** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).\n*/\nlua_Unsigned luaH_getn (Table *t) {\n  unsigned int j = t->sizearray;\n  if (j > 0 && ttisnil(&t->array[j - 1])) {\n    /* there is a boundary in the array part: (binary) search for it */\n    unsigned int i = 0;\n    while (j - i > 1) {\n      unsigned int m = (i+j)/2;\n      if (ttisnil(&t->array[m - 1])) j = m;\n      else i = m;\n    }\n    return i;\n  }\n  /* else must find a boundary in hash part */\n  else if (isdummy(t))  /* hash part is empty? */\n    return j;  /* that is easy... */\n  else return unbound_search(t, j);\n}\n\n\n\n#if defined(LUA_DEBUG)\n\nNode *luaH_mainposition (const Table *t, const TValue *key) {\n  return mainposition(t, key);\n}\n\nint luaH_isdummy (const Table *t) { return isdummy(t); }\n\n#endif\n"
  },
  {
    "path": "src/lua/ltable.h",
    "content": "/*\n** $Id: ltable.h,v 2.23.1.2 2018/05/24 19:39:05 roberto Exp $\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)->i_key.nk.next)\n\n\n/* 'const' to avoid wrong writings that can mess up field 'next' */\n#define gkey(n)\t\tcast(const TValue*, (&(n)->i_key.tvk))\n\n/*\n** writable version of 'gkey'; allows updates to individual fields,\n** but not to the whole (which has incompatible type)\n*/\n#define wgkey(n)\t\t(&(n)->i_key.nk)\n\n#define invalidateTMcache(t)\t((t)->flags = 0)\n\n\n/* true when 't' is using 'dummynode' as its hash part */\n#define isdummy(t)\t\t((t)->lastfree == NULL)\n\n\n/* allocated size for hash nodes */\n#define allocsizenode(t)\t(isdummy(t) ? 0 : sizenode(t))\n\n\n/* returns the key, given the value of a table entry */\n#define keyfromval(v) \\\n  (gkey(cast(Node *, cast(char *, (v)) - offsetof(Node, i_val))))\n\n\nLUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key);\nLUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key,\n                                                    TValue *value);\nLUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key);\nLUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);\nLUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);\nLUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key);\nLUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);\nLUAI_FUNC Table *luaH_new (lua_State *L);\nLUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize,\n                                                    unsigned int nhsize);\nLUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize);\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 (Table *t);\n\n\n#if defined(LUA_DEBUG)\nLUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key);\nLUAI_FUNC int luaH_isdummy (const Table *t);\n#endif\n\n\n#endif\n"
  },
  {
    "path": "src/lua/ltablib.c",
    "content": "/*\n** $Id: ltablib.c,v 1.93.1.1 2017/04/19 17:20:42 roberto Exp $\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\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\n#if defined(LUA_COMPAT_MAXN)\nstatic int maxn (lua_State *L) {\n  lua_Number max = 0;\n  luaL_checktype(L, 1, LUA_TTABLE);\n  lua_pushnil(L);  /* first key */\n  while (lua_next(L, 1)) {\n    lua_pop(L, 1);  /* remove value */\n    if (lua_type(L, -1) == LUA_TNUMBER) {\n      lua_Number v = lua_tonumber(L, -1);\n      if (v > max) max = v;\n    }\n  }\n  lua_pushnumber(L, max);\n  return 1;\n}\n#endif\n\n\nstatic int tinsert (lua_State *L) {\n  lua_Integer e = aux_getn(L, 1, TAB_RW) + 1;  /* first empty element */\n  lua_Integer pos;  /* where to insert new 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      luaL_argcheck(L, 1 <= pos && pos <= e, 2, \"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    luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, \"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);  /* t[pos] = nil */\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 (!lua_isstring(L, -1))\n    luaL_error(L, \"invalid value (%s) at index %d in table for 'concat'\",\n                  luaL_typename(L, -1), 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 pack (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 unpack (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 = (lua_Unsigned)e - i;  /* number of elements minus 1 (avoid overflows) */\n  if (n >= (unsigned int)INT_MAX  || !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/* type for array indices */\ntypedef unsigned int IdxT;\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)\t\t/* { */\n\n#include <time.h>\n\n/* size of 'e' measured in number of 'unsigned int's */\n#define sof(e)\t\t(sizeof(e) / sizeof(unsigned int))\n\n/*\n** Use 'time' and 'clock' as sources of \"randomness\". Because we don't\n** know the types 'clock_t' and 'time_t', we cannot cast them to\n** anything without risking overflows. A safe way to use their values\n** is to copy them to an array of a known type and use the array values.\n*/\nstatic unsigned int l_randomizePivot (void) {\n  clock_t c = clock();\n  time_t t = time(NULL);\n  unsigned int buff[sof(c) + sof(t)];\n  unsigned int i, rnd = 0;\n  memcpy(buff, &c, sof(c) * sizeof(unsigned int));\n  memcpy(buff + sof(c), &t, sof(t) * sizeof(unsigned int));\n  for (i = 0; i < sof(buff); i++)\n    rnd += buff[i];\n  return rnd;\n}\n\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  lua_seti(L, 1, i);\n  lua_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 (lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) {\n      if (i == up - 1)  /* a[i] < P  but a[up - 1] == P  ?? */\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 */\n    /* next loop: repeat --j while P < a[j] */\n    while (lua_geti(L, 1, --j), sort_comp(L, -3, -1)) {\n      if (j < i)  /* j < i  but  a[j] > P ?? */\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 % (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,\n                                   unsigned int 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    lua_geti(L, 1, lo);\n    lua_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    lua_geti(L, 1, p);\n    lua_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      lua_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    lua_geti(L, 1, p);  /* get middle element (Pivot) */\n    lua_pushvalue(L, -1);  /* push Pivot */\n    lua_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();  /* 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#if defined(LUA_COMPAT_MAXN)\n  {\"maxn\", maxn},\n#endif\n  {\"insert\", tinsert},\n  {\"pack\", pack},\n  {\"unpack\", unpack},\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#if defined(LUA_COMPAT_UNPACK)\n  /* _G.unpack = table.unpack */\n  lua_getfield(L, -1, \"unpack\");\n  lua_setglobal(L, \"unpack\");\n#endif\n  return 1;\n}\n\n"
  },
  {
    "path": "src/lua/ltests.c",
    "content": "/*\n** $Id: ltests.c,v 2.211.1.1 2017/04/19 17:39:34 roberto Exp $\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 \"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\nint islocked = 0;\n\n\n#define obj_at(L,k)\t(L->ci->func + (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_pushstring(L, name);\n  lua_pushinteger(L, val);\n  lua_settable(L, -3);\n}\n\n\nstatic void pushobject (lua_State *L, const TValue *o) {\n  setobj2s(L, L->top, o);\n  api_incr_top(L);\n}\n\n\nstatic int tpanic (lua_State *L) {\n  fprintf(stderr, \"PANIC: unprotected error in call to Lua API (%s)\\n\",\n                   lua_tostring(L, -1));\n  return (exit(EXIT_FAILURE), 0);  /* do not return to Lua */\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 Header {\n  L_Umaxalign a;  /* ensures maximum alignment for Header */\n  struct {\n    size_t size;\n    int type;\n  } d;\n} Header;\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  {0L, 0L, 0L, 0L, {0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L}};\n\n\nstatic void freeblock (Memcontrol *mc, Header *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(char *, block + 1) + size + i) == MARK);\n    mc->objcount[block->d.type]--;\n    fillmem(block, sizeof(Header) + 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  Header *block = cast(Header *, 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_NUMTAGS) ? 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  else if (size > oldsize && mc->total+size-oldsize > mc->memlimit)\n    return NULL;  /* fake a memory allocation error */\n  else {\n    Header *newblock;\n    int i;\n    size_t commonsize = (oldsize < size) ? oldsize : size;\n    size_t realsize = sizeof(Header) + size + MARKSIZE;\n    if (realsize < size) return NULL;  /* arithmetic overflow! */\n    newblock = cast(Header *, malloc(realsize));  /* alloc a new block */\n    if (newblock == NULL) 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(char *, newblock + 1) + commonsize, size - commonsize);\n    /* initialize marks after block */\n    for (i = 0; i < MARKSIZE; i++)\n      *(cast(char *, 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** =======================================================\n*/\n\n\nstatic int testobjref1 (global_State *g, GCObject *f, GCObject *t) {\n  if (isdead(g,t)) return 0;\n  if (!issweepphase(g))\n    return !(isblack(f) && iswhite(t));\n  else return 1;\n}\n\n\nstatic void printobj (global_State *g, GCObject *o) {\n  printf(\"||%s(%p)-%c(%02X)||\",\n           ttypename(novariant(o->tt)), (void *)o,\n           isdead(g,o)?'d':isblack(o)?'b':iswhite(o)?'w':'g', o->marked);\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#define checkobjref(g,f,t)  \\\n\t{ if (t) lua_longassert(testobjref(g,f,obj2gco(t))); }\n\n\nstatic void checkvalref (global_State *g, GCObject *f, const TValue *t) {\n  lua_assert(!iscollectable(t) ||\n    (righttt(t) && testobjref(g, f, gcvalue(t))));\n}\n\n\nstatic void checktable (global_State *g, Table *h) {\n  unsigned int i;\n  Node *n, *limit = gnode(h, sizenode(h));\n  GCObject *hgc = obj2gco(h);\n  checkobjref(g, hgc, h->metatable);\n  for (i = 0; i < h->sizearray; i++)\n    checkvalref(g, hgc, &h->array[i]);\n  for (n = gnode(h, 0); n < limit; n++) {\n    if (!ttisnil(gval(n))) {\n      lua_assert(!ttisnil(gkey(n)));\n      checkvalref(g, hgc, gkey(n));\n      checkvalref(g, hgc, gval(n));\n    }\n  }\n}\n\n\n/*\n** All marks are conditional because a GC may happen while the\n** prototype is still being created\n*/\nstatic void checkproto (global_State *g, Proto *f) {\n  int i;\n  GCObject *fgc = obj2gco(f);\n  checkobjref(g, fgc, f->cache);\n  checkobjref(g, fgc, f->source);\n  for (i=0; i<f->sizek; i++) {\n    if (ttisstring(f->k + i))\n      checkobjref(g, fgc, tsvalue(f->k + i));\n  }\n  for (i=0; i<f->sizeupvalues; i++)\n    checkobjref(g, fgc, f->upvalues[i].name);\n  for (i=0; i<f->sizep; i++)\n    checkobjref(g, fgc, f->p[i]);\n  for (i=0; i<f->sizelocvars; i++)\n    checkobjref(g, fgc, f->locvars[i].varname);\n}\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  checkobjref(g, clgc, cl->p);\n  for (i=0; i<cl->nupvalues; i++) {\n    UpVal *uv = cl->upvals[i];\n    if (uv) {\n      if (!upisopen(uv))  /* only closed upvalues matter to invariant */\n        checkvalref(g, clgc, uv->v);\n      lua_assert(uv->refcount > 0);\n    }\n  }\n}\n\n\nstatic int lua_checkpc (lua_State *L, CallInfo *ci) {\n  if (!isLua(ci)) return 1;\n  else {\n    /* if function yielded (inside a hook), real 'func' is in 'extra' field */\n    StkId f = (L->status != LUA_YIELD || ci != L->ci)\n              ? ci->func\n              : restorestack(L, ci->extra);\n    Proto *p = clLvalue(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 checkstack (global_State *g, lua_State *L1) {\n  StkId o;\n  CallInfo *ci;\n  UpVal *uv;\n  lua_assert(!isdead(g, L1));\n  for (uv = L1->openupval; uv != NULL; uv = uv->u.open.next)\n    lua_assert(upisopen(uv));  /* must be open */\n  for (ci = L1->ci; ci != NULL; ci = ci->previous) {\n    lua_assert(ci->top <= L1->stack_last);\n    lua_assert(lua_checkpc(L1, ci));\n  }\n  if (L1->stack) {  /* complete thread? */\n    for (o = L1->stack; o < L1->stack_last + EXTRA_STACK; o++)\n      checkliveness(L1, o);  /* entire stack must have valid values */\n  }\n  else lua_assert(L1->stacksize == 0);\n}\n\n\nstatic void checkobject (global_State *g, GCObject *o, int maybedead) {\n  if (isdead(g, o))\n    lua_assert(maybedead);\n  else {\n    lua_assert(g->gcstate != GCSpause || iswhite(o));\n    switch (o->tt) {\n      case LUA_TUSERDATA: {\n        TValue uservalue;\n        Table *mt = gco2u(o)->metatable;\n        checkobjref(g, o, mt);\n        getuservalue(g->mainthread, gco2u(o), &uservalue);\n        checkvalref(g, o, &uservalue);\n        break;\n      }\n      case LUA_TTABLE: {\n        checktable(g, gco2t(o));\n        break;\n      }\n      case LUA_TTHREAD: {\n        checkstack(g, gco2th(o));\n        break;\n      }\n      case LUA_TLCL: {\n        checkLclosure(g, gco2lcl(o));\n        break;\n      }\n      case LUA_TCCL: {\n        checkCclosure(g, gco2ccl(o));\n        break;\n      }\n      case LUA_TPROTO: {\n        checkproto(g, gco2p(o));\n        break;\n      }\n      case LUA_TSHRSTR:\n      case LUA_TLNGSTR: {\n        lua_assert(!isgray(o));  /* strings are never gray */\n        break;\n      }\n      default: lua_assert(0);\n    }\n  }\n}\n\n\n#define TESTGRAYBIT\t\t7\n\nstatic void checkgraylist (global_State *g, GCObject *o) {\n  ((void)g);  /* better to keep it available if we need to print an object */\n  while (o) {\n    lua_assert(isgray(o));\n    lua_assert(!testbit(o->marked, TESTGRAYBIT));\n    l_setbit(o->marked, TESTGRAYBIT);\n    switch (o->tt) {\n      case LUA_TTABLE: o = gco2t(o)->gclist; break;\n      case LUA_TLCL: o = gco2lcl(o)->gclist; break;\n      case LUA_TCCL: o = gco2ccl(o)->gclist; break;\n      case LUA_TTHREAD: o = gco2th(o)->gclist; break;\n      case LUA_TPROTO: o = gco2p(o)->gclist; break;\n      default: lua_assert(0);  /* other objects cannot be gray */\n    }\n  }\n}\n\n\n/*\n** mark all objects in gray lists with the TESTGRAYBIT, so that\n** 'checkmemory' can check that all gray objects are in a gray list\n*/\nstatic void markgrays (global_State *g) {\n  if (!keepinvariant(g)) return;\n  checkgraylist(g, g->gray);\n  checkgraylist(g, g->grayagain);\n  checkgraylist(g, g->weak);\n  checkgraylist(g, g->ephemeron);\n  checkgraylist(g, g->allweak);\n}\n\n\nstatic void checkgray (global_State *g, GCObject *o) {\n  for (; o != NULL; o = o->next) {\n    if (isgray(o)) {\n      lua_assert(!keepinvariant(g) || testbit(o->marked, TESTGRAYBIT));\n      resetbit(o->marked, TESTGRAYBIT);\n    }\n    lua_assert(!testbit(o->marked, TESTGRAYBIT));\n  }\n}\n\n\nint lua_checkmemory (lua_State *L) {\n  global_State *g = G(L);\n  GCObject *o;\n  int maybedead;\n  if (keepinvariant(g)) {\n    lua_assert(!iswhite(g->mainthread));\n    lua_assert(!iswhite(gcvalue(&g->l_registry)));\n  }\n  lua_assert(!isdead(g, gcvalue(&g->l_registry)));\n  checkstack(g, g->mainthread);\n  resetbit(g->mainthread->marked, TESTGRAYBIT);\n  lua_assert(g->sweepgc == NULL || issweepphase(g));\n  markgrays(g);\n  /* check 'fixedgc' list */\n  for (o = g->fixedgc; o != NULL; o = o->next) {\n    lua_assert(o->tt == LUA_TSHRSTR && isgray(o));\n  }\n  /* check 'allgc' list */\n  checkgray(g, g->allgc);\n  maybedead = (GCSatomic < g->gcstate && g->gcstate <= GCSswpallgc);\n  for (o = g->allgc; o != NULL; o = o->next) {\n    checkobject(g, o, maybedead);\n    lua_assert(!tofinalize(o));\n  }\n  /* check 'finobj' list */\n  checkgray(g, g->finobj);\n  for (o = g->finobj; o != NULL; o = o->next) {\n    checkobject(g, o, 0);\n    lua_assert(tofinalize(o));\n    lua_assert(o->tt == LUA_TUSERDATA || o->tt == LUA_TTABLE);\n  }\n  /* check 'tobefnz' list */\n  checkgray(g, g->tobefnz);\n  for (o = g->tobefnz; o != NULL; o = o->next) {\n    checkobject(g, o, 0);\n    lua_assert(tofinalize(o));\n    lua_assert(o->tt == LUA_TUSERDATA || o->tt == LUA_TTABLE);\n  }\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  Instruction i = p->code[pc];\n  OpCode o = GET_OPCODE(i);\n  const char *name = luaP_opnames[o];\n  int line = getfuncline(p, pc);\n  sprintf(buff, \"(%4d) %4d - \", line, pc);\n  switch (getOpMode(o)) {\n    case iABC:\n      sprintf(buff+strlen(buff), \"%-12s%4d %4d %4d\", name,\n              GETARG_A(i), GETARG_B(i), GETARG_C(i));\n      break;\n    case iABx:\n      sprintf(buff+strlen(buff), \"%-12s%4d %4d\", name, GETARG_A(i), GETARG_Bx(i));\n      break;\n    case iAsBx:\n      sprintf(buff+strlen(buff), \"%-12s%4d %4d\", name, GETARG_A(i), GETARG_sBx(i));\n      break;\n    case iAx:\n      sprintf(buff+strlen(buff), \"%-12s%4d\", name, GETARG_Ax(i));\n      break;\n  }\n  return buff;\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 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 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\nstatic void printstack (lua_State *L) {\n  int i;\n  int n = lua_gettop(L);\n  for (i = 1; i <= n; i++) {\n    printf(\"%3d: %s\\n\", i, luaL_tolstring(L, i, NULL));\n    lua_pop(L, 1);\n  }\n  printf(\"\\n\");\n}\n\n\nstatic int get_limits (lua_State *L) {\n  lua_createtable(L, 0, 5);\n  setnameval(L, \"BITS_INT\", LUAI_BITSINT);\n  setnameval(L, \"MAXARG_Ax\", MAXARG_Ax);\n  setnameval(L, \"MAXARG_Bx\", MAXARG_Bx);\n  setnameval(L, \"MAXARG_sBx\", MAXARG_sBx);\n  setnameval(L, \"BITS_INT\", LUAI_BITSINT);\n  setnameval(L, \"LFPF\", LFIELDS_PER_FLUSH);\n  setnameval(L, \"NUM_OPCODES\", NUM_OPCODES);\n  return 1;\n}\n\n\nstatic int mem_query (lua_State *L) {\n  if (lua_isnone(L, 1)) {\n    lua_pushinteger(L, l_memcontrol.total);\n    lua_pushinteger(L, l_memcontrol.numblocks);\n    lua_pushinteger(L, 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_NUMTAGS - 1; i >= 0; i--) {\n      if (strcmp(t, ttypename(i)) == 0) {\n        lua_pushinteger(L, l_memcontrol.objcount[i]);\n        return 1;\n      }\n    }\n    return luaL_error(L, \"unkown type '%s'\", t);\n  }\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\" : \"grey\");\n  }\n  return 1;\n}\n\n\nstatic int gc_state (lua_State *L) {\n  static const char *statenames[] = {\"propagate\", \"atomic\", \"sweepallgc\",\n      \"sweepfinobj\", \"sweeptobefnz\", \"sweepend\", \"pause\", \"\"};\n  static const int states[] = {GCSpropagate, GCSatomic, GCSswpallgc,\n      GCSswpfinobj, GCSswptobefnz, GCSswpend, GCSpause, -1};\n  int option = states[luaL_checkoption(L, 1, \"\", statenames)];\n  if (option == -1) {\n    lua_pushstring(L, statenames[G(L)->gcstate]);\n    return 1;\n  }\n  else {\n    global_State *g = G(L);\n    lua_lock(L);\n    if (option < g->gcstate) {  /* must cross 'pause'? */\n      luaC_runtilstate(L, bitmask(GCSpause));  /* run until pause */\n    }\n    luaC_runtilstate(L, bitmask(option));\n    lua_assert(G(L)->gcstate == option);\n    lua_unlock(L);\n    return 0;\n  }\n}\n\n\nstatic int hash_query (lua_State *L) {\n  if (lua_isnone(L, 2)) {\n    luaL_argcheck(L, lua_type(L, 1) == LUA_TSTRING, 1, \"string expected\");\n    lua_pushinteger(L, tsvalue(obj_at(L, 1))->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, luaH_mainposition(t, o) - t->node);\n  }\n  return 1;\n}\n\n\nstatic int stacklevel (lua_State *L) {\n  unsigned long a = 0;\n  lua_pushinteger(L, (L->top - L->stack));\n  lua_pushinteger(L, (L->stack_last - L->stack));\n  lua_pushinteger(L, (unsigned long)&a);\n  return 3;\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  luaL_checktype(L, 1, LUA_TTABLE);\n  t = hvalue(obj_at(L, 1));\n  if (i == -1) {\n    lua_pushinteger(L, t->sizearray);\n    lua_pushinteger(L, allocsizenode(t));\n    lua_pushinteger(L, isdummy(t) ? 0 : t->lastfree - t->node);\n  }\n  else if ((unsigned int)i < t->sizearray) {\n    lua_pushinteger(L, i);\n    pushobject(L, &t->array[i]);\n    lua_pushnil(L);\n  }\n  else if ((i -= t->sizearray) < sizenode(t)) {\n    if (!ttisnil(gval(gnode(t, i))) ||\n        ttisnil(gkey(gnode(t, i))) ||\n        ttisnumber(gkey(gnode(t, i)))) {\n      pushobject(L, gkey(gnode(t, i)));\n    }\n    else\n      lua_pushliteral(L, \"<undef>\");\n    pushobject(L, gval(gnode(t, i)));\n    if (gnext(&t->node[i]) != 0)\n      lua_pushinteger(L, gnext(&t->node[i]));\n    else\n      lua_pushnil(L);\n  }\n  return 3;\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, ts);\n      api_incr_top(L);\n      n++;\n    }\n    return n;\n  }\n  else return 0;\n}\n\n\nstatic int tref (lua_State *L) {\n  int level = lua_gettop(L);\n  luaL_checkany(L, 1);\n  lua_pushvalue(L, 1);\n  lua_pushinteger(L, luaL_ref(L, LUA_REGISTRYINDEX));\n  lua_assert(lua_gettop(L) == level+1);  /* +1 for result */\n  return 1;\n}\n\nstatic int getref (lua_State *L) {\n  int level = lua_gettop(L);\n  lua_rawgeti(L, LUA_REGISTRYINDEX, luaL_checkinteger(L, 1));\n  lua_assert(lua_gettop(L) == level+1);\n  return 1;\n}\n\nstatic int unref (lua_State *L) {\n  int level = lua_gettop(L);\n  luaL_unref(L, LUA_REGISTRYINDEX, cast_int(luaL_checkinteger(L, 1)));\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(size_t, luaL_checkinteger(L, 1));\n  char *p = cast(char *, lua_newuserdata(L, size));\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(void *, cast(size_t, u)));\n  return 1;\n}\n\n\nstatic int udataval (lua_State *L) {\n  lua_pushinteger(L, cast(long, 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(const double *, luaL_checkstring(L, 1)));\n  return 1;\n}\n\n\nstatic int d2s (lua_State *L) {\n  double d = luaL_checknumber(L, 1);\n  lua_pushlstring(L, cast(char *, &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 newstate (lua_State *L) {\n  void *ud;\n  lua_Alloc f = lua_getallocf(L, &ud);\n  lua_State *L1 = lua_newstate(f, ud);\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  static const luaL_Reg libs[] = {\n    {\"_G\", luaopen_base},\n    {\"coroutine\", luaopen_coroutine},\n    {\"debug\", luaopen_debug},\n    {\"io\", luaopen_io},\n    {\"os\", luaopen_os},\n    {\"math\", luaopen_math},\n    {\"string\", luaopen_string},\n    {\"table\", luaopen_table},\n    {NULL, NULL}\n  };\n  lua_State *L1 = getstate(L);\n  int i;\n  luaL_requiref(L1, \"package\", luaopen_package, 0);\n  lua_assert(lua_type(L1, -1) == LUA_TTABLE);\n  /* 'requiref' should not reload module already loaded... */\n  luaL_requiref(L1, \"package\", 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  luaL_getsubtable(L1, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);\n  for (i = 0; libs[i].name; i++) {\n    lua_pushcfunction(L1, libs[i].func);\n    lua_setfield(L1, -2, libs[i].name);\n  }\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 int2fb_aux (lua_State *L) {\n  int b = luaO_int2fb((unsigned int)luaL_checkinteger(L, 1));\n  lua_pushinteger(L, b);\n  lua_pushinteger(L, (unsigned int)luaO_fb2int(b));\n  return 2;\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);  /* create new state */\n  if (L1 == NULL) {  /* error? */\n    lua_pushnil(L);\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\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 == '#') {\n      while (**pc != '\\n' && **pc != '\\0') (*pc)++;\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    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 'G': return luaL_error(L, \"deprecated index 'G'\");\n    case 'U': return lua_upvalueindex(getnum_aux(L, L1, pc));\n    default: (*pc)--; return getnum_aux(L, L1, pc);\n  }\n}\n\n\nstatic void pushcode (lua_State *L, int code) {\n  static const char *const codes[] = {\"OK\", \"YIELD\", \"ERRRUN\",\n                   \"ERRSYNTAX\", \"ERRMEM\", \"ERRGCMM\", \"ERRERR\"};\n  lua_pushstring(L, codes[code]);\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_pushnumber(L1, lua_absindex(L1, getindex));\n    }\n    else if EQ(\"append\") {\n      int t = getindex;\n      int i = 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 = 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(\"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_pushnumber(L1, cast(size_t, func));\n    }\n    else if EQ(\"getfield\") {\n      int t = getindex;\n      lua_getfield(L1, t, getstring);\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      lua_gettable(L1, getindex);\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      const char *s = luaL_checkstring(L1, getnum);\n      luaL_loadstring(L1, s);\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(\"newuserdata\") {\n      lua_newuserdata(L1, getnum);\n    }\n    else if EQ(\"next\") {\n      lua_next(L1, -2);\n    }\n    else if EQ(\"objsize\") {\n      lua_pushinteger(L1, 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(\"print\") {\n      int n = getnum;\n      if (n != 0) {\n        printf(\"%s\\n\", luaL_tolstring(L1, n, NULL));\n        lua_pop(L1, 1);\n      }\n      else printstack(L1);\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      pushcode(L1, 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(\"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(void *, cast(size_t, getnum)));\n    }\n    else if EQ(\"rawsetp\") {\n      int t = getindex;\n      lua_rawsetp(L1, t, cast(void *, cast(size_t, 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      status = lua_resume(lua_tothread(L1, i), L, 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          lua_pushstring(L, lua_tostring(L1, -(n - i)));\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      lua_setfield(L1, t, getstring);\n    }\n    else if EQ(\"setglobal\") {\n      lua_setglobal(L1, getstring);\n    }\n    else if EQ(\"sethook\") {\n      int mask = getnum;\n      int count = getnum;\n      sethookaux(L1, mask, count, getstring);\n    }\n    else if EQ(\"setmetatable\") {\n      lua_setmetatable(L1, getindex);\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(\"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_pushnumber(L1, cast(size_t, lua_topointer(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      lua_longassert((s == NULL && s1 == NULL) || strcmp(s, s1) == 0);\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(\"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 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  pushcode(L, status);\n  lua_setglobal(L, \"status\");\n  lua_pushinteger(L, ctx);\n  lua_setglobal(L, \"ctx\");\n  return runC(L, L, lua_tostring(L, 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;\n  lua_State *co = lua_tothread(L, 1);\n  luaL_argcheck(L, co, 1, \"coroutine expected\");\n  status = lua_resume(co, L, 0);\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/* }====================================================== */\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  {\"gcstate\", gc_state},\n  {\"getref\", getref},\n  {\"hash\", hash_query},\n  {\"int2fb\", int2fb_aux},\n  {\"log2\", log2_aux},\n  {\"limits\", get_limits},\n  {\"listcode\", listcode},\n  {\"listk\", listk},\n  {\"listlocals\", listlocals},\n  {\"loadlib\", loadlib},\n  {\"checkpanic\", checkpanic},\n  {\"newstate\", newstate},\n  {\"newuserdata\", newuserdata},\n  {\"num2int\", num2int},\n  {\"pushuserdata\", pushuserdata},\n  {\"querystr\", string_query},\n  {\"querytab\", table_query},\n  {\"ref\", tref},\n  {\"resume\", coresume},\n  {\"s2d\", s2d},\n  {\"sethook\", sethook},\n  {\"stacklevel\", stacklevel},\n  {\"testC\", testC},\n  {\"makeCfunc\", makeCfunc},\n  {\"totalmem\", mem_query},\n  {\"trick\", settrick},\n  {\"udataval\", udataval},\n  {\"unref\", unref},\n  {\"upvalue\", upvalue},\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_atpanic(L, &tpanic);\n  atexit(checkfinalmem);\n  lua_assert(lua_getallocf(L, &ud) == debug_realloc);\n  lua_assert(ud == cast(void *, &l_memcontrol));\n  lua_setallocf(L, lua_getallocf(L, NULL), ud);\n  luaL_newlib(L, tests_funcs);\n  return 1;\n}\n\n#endif\n\n"
  },
  {
    "path": "src/lua/ltests.h",
    "content": "/*\n** $Id: ltests.h,v 2.50.1.1 2017/04/19 17:20:42 roberto Exp $\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 <stdlib.h>\n\n/* test Lua with no compatibility code */\n#undef LUA_COMPAT_MATHLIB\n#undef LUA_COMPAT_IPAIRS\n#undef LUA_COMPAT_BITLIB\n#undef LUA_COMPAT_APIINTCASTS\n#undef LUA_COMPAT_FLOATSTRING\n#undef LUA_COMPAT_UNPACK\n#undef LUA_COMPAT_LOADERS\n#undef LUA_COMPAT_LOG10\n#undef LUA_COMPAT_LOADSTRING\n#undef LUA_COMPAT_MAXN\n#undef LUA_COMPAT_MODULE\n\n\n#define LUA_DEBUG\n\n\n/* turn on assertions */\n#undef NDEBUG\n#include <assert.h>\n#define lua_assert(c)           assert(c)\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/* memory-allocator control variables */\ntypedef struct Memcontrol {\n  unsigned long numblocks;\n  unsigned long total;\n  unsigned long maxmem;\n  unsigned long memlimit;\n  unsigned long objcount[LUA_NUMTAGS];\n} Memcontrol;\n\nLUA_API Memcontrol l_memcontrol;\n\n\n/*\n** generic variable for debug tricks\n*/\nextern void *l_Trick;\n\n\n\n/*\n** Function to traverse and check all memory used by Lua\n*/\nint lua_checkmemory (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#if defined(lua_c)\n#define luaL_newstate()\t\tlua_newstate(debug_realloc, &l_memcontrol)\n#define luaL_openlibs(L)  \\\n  { (luaL_openlibs)(L); \\\n     luaL_requiref(L, \"T\", luaB_opentests, 1); \\\n     lua_pop(L, 1); }\n#endif\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 MAXINDEXRK\t\t1\n\n\n/* make stack-overflow tests run faster */\n#undef LUAI_MAXSTACK\n#define LUAI_MAXSTACK   50000\n\n\n#undef LUAI_USER_ALIGNMENT_T\n#define LUAI_USER_ALIGNMENT_T   union { char b[sizeof(void*) * 8]; }\n\n\n#define STRCACHE_N\t23\n#define STRCACHE_M\t5\n\n#endif\n\n"
  },
  {
    "path": "src/lua/ltm.c",
    "content": "/*\n** $Id: ltm.c,v 2.38.1.1 2017/04/19 17:39:34 roberto Exp $\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 \"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_TOTALTAGS] = {\n  \"no value\",\n  \"nil\", \"boolean\", udatatypename, \"number\",\n  \"string\", \"table\", \"function\", udatatypename, \"thread\",\n  \"proto\" /* this last case is 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\"\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_getshortstr(events, ename);\n  lua_assert(event <= TM_EQ);\n  if (ttisnil(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 (ttnov(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[ttnov(o)];\n  }\n  return (mt ? luaH_getshortstr(mt, G(L)->tmname[event]) : luaO_nilobject);\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_getshortstr(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(ttnov(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, TValue *p3, int hasres) {\n  ptrdiff_t result = savestack(L, p3);\n  StkId func = L->top;\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 += 3;\n  if (!hasres)  /* no result? 'p3' is third argument */\n    setobj2s(L, L->top++, p3);  /* 3rd argument */\n  /* metamethod may yield only when called from Lua code */\n  if (isLua(L->ci))\n    luaD_call(L, func, hasres);\n  else\n    luaD_callnoyield(L, func, hasres);\n  if (hasres) {  /* if has result, move it to its place */\n    p3 = restorestack(L, result);\n    setobjs2s(L, p3, --L->top);\n  }\n}\n\n\nint luaT_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 (ttisnil(tm))\n    tm = luaT_gettmbyobj(L, p2, event);  /* try second operand */\n  if (ttisnil(tm)) return 0;\n  luaT_callTM(L, tm, p1, p2, res, 1);\n  return 1;\n}\n\n\nvoid luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,\n                    StkId res, TMS event) {\n  if (!luaT_callbinTM(L, p1, p2, res, event)) {\n    switch (event) {\n      case TM_CONCAT:\n        luaG_concaterror(L, p1, p2);\n      /* call never returns, but to avoid warnings: *//* FALLTHROUGH */\n      case TM_BAND: case TM_BOR: case TM_BXOR:\n      case TM_SHL: case TM_SHR: case TM_BNOT: {\n        lua_Number dummy;\n        if (tonumber(p1, &dummy) && tonumber(p2, &dummy))\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\nint luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2,\n                      TMS event) {\n  if (!luaT_callbinTM(L, p1, p2, L->top, event))\n    return -1;  /* no metamethod */\n  else\n    return !l_isfalse(L->top);\n}\n\n"
  },
  {
    "path": "src/lua/ltm.h",
    "content": "/*\n** $Id: ltm.h,v 2.22.1.1 2017/04/19 17:20:42 roberto Exp $\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_N\t\t/* number of elements in the enum */\n} TMS;\n\n\n\n#define gfasttm(g,et,e) ((et) == NULL ? NULL : \\\n  ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e]))\n\n#define fasttm(l,et,e)\tgfasttm(G(l), et, e)\n\n#define ttypename(x)\tluaT_typenames_[(x) + 1]\n\nLUAI_DDEC const char *const luaT_typenames_[LUA_TOTALTAGS];\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, TValue *p3, int hasres);\nLUAI_FUNC int luaT_callbinTM (lua_State *L, const TValue *p1, const TValue *p2,\n                              StkId res, TMS event);\nLUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,\n                              StkId res, TMS event);\nLUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1,\n                                const TValue *p2, TMS event);\n\n\n\n#endif\n"
  },
  {
    "path": "src/lua/lua.h",
    "content": "/*\n** $Id: lua.h,v 1.332.1.2 2018/06/13 16:58:17 roberto Exp $\n** Lua - A Scripting Language\n** Lua.org, PUC-Rio, Brazil (http://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#include \"luaconf.h\"\n\n\n#define LUA_VERSION_MAJOR\t\"5\"\n#define LUA_VERSION_MINOR\t\"3\"\n#define LUA_VERSION_NUM\t\t503\n#define LUA_VERSION_RELEASE\t\"5\"\n\n#define LUA_VERSION\t\"Lua \" LUA_VERSION_MAJOR \".\" LUA_VERSION_MINOR\n#define LUA_RELEASE\tLUA_VERSION \".\" LUA_VERSION_RELEASE\n#define LUA_COPYRIGHT\tLUA_RELEASE \"  Copyright (C) 1994-2018 Lua.org, PUC-Rio\"\n#define LUA_AUTHORS\t\"R. Ierusalimschy, L. H. de Figueiredo, W. Celes\"\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** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty\n** space after that to help overflow detection)\n*/\n#define LUA_REGISTRYINDEX\t(-LUAI_MAXSTACK - 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_ERRGCMM\t5\n#define LUA_ERRERR\t6\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_NUMTAGS\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#define LUA_RIDX_MAINTHREAD\t1\n#define LUA_RIDX_GLOBALS\t2\n#define LUA_RIDX_LAST\t\tLUA_RIDX_GLOBALS\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/*\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);\nLUA_API void       (lua_close) (lua_State *L);\nLUA_API lua_State *(lua_newthread) (lua_State *L);\n\nLUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf);\n\n\nLUA_API const 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 size_t          (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_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\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_newuserdata) (lua_State *L, size_t sz);\nLUA_API int   (lua_getmetatable) (lua_State *L, int objindex);\nLUA_API int  (lua_getuservalue) (lua_State *L, int idx);\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 void  (lua_setuservalue) (lua_State *L, int idx);\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);\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** garbage-collection function and 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_GCSETPAUSE\t\t6\n#define LUA_GCSETSTEPMUL\t7\n#define LUA_GCISRUNNING\t\t9\n\nLUA_API int (lua_gc) (lua_State *L, int what, int data);\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\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\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#define lua_to_or_default(L, w, i, d) lua_gettop(L) >= i ? lua_to ## w(L, i) : d  \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 for unsigned conversions\n** ===============================================================\n*/\n#if defined(LUA_COMPAT_APIINTCASTS)\n\n#define lua_pushunsigned(L,n)\tlua_pushinteger(L, (lua_Integer)(n))\n#define lua_tounsignedx(L,i,is)\t((lua_Unsigned)lua_tointegerx(L,i,is))\n#define lua_tounsigned(L,i)\tlua_tounsignedx(L,(i),NULL)\n\n#endif\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\ntypedef struct lua_Debug lua_Debug;  /* activation record */\n\n\n/* Functions to be called by the debugger in specific events */\ntypedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);\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  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  char istailcall;\t/* (t) */\n  char short_src[LUA_IDSIZE]; /* (S) */\n  /* private part */\n  struct CallInfo *i_ci;  /* active function */\n};\n\n/* }====================================================================== */\n\n\n/******************************************************************************\n* Copyright (C) 1994-2018 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": "src/lua/lua.hpp",
    "content": "extern \"C\"\n{\n  #include <climits>\n  #include \"lua.h\"\n  #include \"lualib.h\"\n  #include \"lauxlib.h\"\n}"
  },
  {
    "path": "src/lua/luaconf.h",
    "content": "/*\n** $Id: luaconf.h,v 1.259.1.1 2017/04/19 17:29:57 roberto Exp $\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** 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 compiling it with 32-bit numbers or\n** restricting it to C89.\n** =====================================================================\n*/\n\n/*\n@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. You\n** can also define LUA_32BITS in the make file, but changing here you\n** ensure that all software connected to Lua will be compiled with the\n** same configuration.\n*/\n/* #define LUA_32BITS */\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#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_USE_READLINE\t/* needs some extra libraries */\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_USE_READLINE\t/* needs an extra library: -lreadline */\n#endif\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\n#endif\n\n\n\n/*\n@@ LUAI_BITSINT defines the (minimum) number of bits in an 'int'.\n*/\n/* avoid undefined shifts */\n#if ((INT_MAX >> 15) >> 15) >= 1\n#define LUAI_BITSINT\t32\n#else\n/* 'int' always must have at least 16 bits */\n#define LUAI_BITSINT\t16\n#endif\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 (if 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#if defined(LUA_32BITS)\t\t/* { */\n/*\n** 32-bit integers and 'float'\n*/\n#if LUAI_BITSINT >= 32  /* 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 defined(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#endif\t\t\t\t/* } */\n\n\n/*\n** default configuration for 64-bit Lua ('long long' and 'double')\n*/\n#if !defined(LUA_INT_TYPE)\n#define LUA_INT_TYPE\tLUA_INT_LONGLONG\n#endif\n\n#if !defined(LUA_FLOAT_TYPE)\n#define LUA_FLOAT_TYPE\tLUA_FLOAT_FLOAT\n#endif\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#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#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#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\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#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#define LUA_CPATH_DEFAULT \\\n\t\tLUA_CDIR\"?.so;\" LUA_CDIR\"loadall.so;\" \"./?.so\"\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(_WIN32)\n#define LUA_DIRSEP\t\"\\\\\"\n#else\n#define LUA_DIRSEP\t\"/\"\n#endif\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/* more often than not the libs go together with the core */\n#define LUALIB_API\tLUA_API\n#define LUAMOD_API\tLUALIB_API\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** that are not to be exported to outside modules (LUAI_DDEF for\n** definitions and LUAI_DDEC for declarations).\n** CHANGE them if you need to mark them in some special way. Elf/gcc\n** (versions 3.2 and later) mark them as \"hidden\" to optimize access\n** when Lua is compiled as a shared library. Not all elf targets support\n** this attribute. Unfortunately, gcc does not offer a way to check\n** whether the target offers that support, and those without support\n** give a warning about it. To avoid these warnings, change to the\n** default definition.\n*/\n#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \\\n    defined(__ELF__)\t\t/* { */\n#define LUAI_FUNC\t__attribute__((visibility(\"hidden\"))) extern\n#else\t\t\t\t/* }{ */\n#define LUAI_FUNC\textern\n#endif\t\t\t\t/* } */\n\n#define LUAI_DDEC\tLUAI_FUNC\n#define LUAI_DDEF\t/* empty */\n\n/* }================================================================== */\n\n\n/*\n** {==================================================================\n** Compatibility with previous versions\n** ===================================================================\n*/\n\n/*\n@@ LUA_COMPAT_5_2 controls other macros for compatibility with Lua 5.2.\n@@ LUA_COMPAT_5_1 controls other macros for compatibility with Lua 5.1.\n** You can define it to get all options, or change specific options\n** to fit your specific needs.\n*/\n#if defined(LUA_COMPAT_5_2)\t/* { */\n\n/*\n@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated\n** functions in the mathematical library.\n*/\n#define LUA_COMPAT_MATHLIB\n\n/*\n@@ LUA_COMPAT_BITLIB controls the presence of library 'bit32'.\n*/\n#define LUA_COMPAT_BITLIB\n\n/*\n@@ LUA_COMPAT_IPAIRS controls the effectiveness of the __ipairs metamethod.\n*/\n#define LUA_COMPAT_IPAIRS\n\n/*\n@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for\n** manipulating other integer types (lua_pushunsigned, lua_tounsigned,\n** luaL_checkint, luaL_checklong, etc.)\n*/\n#define LUA_COMPAT_APIINTCASTS\n\n#endif\t\t\t\t/* } */\n\n\n#if defined(LUA_COMPAT_5_1)\t/* { */\n\n/* Incompatibilities from 5.2 -> 5.3 */\n#define LUA_COMPAT_MATHLIB\n#define LUA_COMPAT_APIINTCASTS\n\n/*\n@@ LUA_COMPAT_UNPACK controls the presence of global 'unpack'.\n** You can replace it with 'table.unpack'.\n*/\n#define LUA_COMPAT_UNPACK\n\n/*\n@@ LUA_COMPAT_LOADERS controls the presence of table 'package.loaders'.\n** You can replace it with 'package.searchers'.\n*/\n#define LUA_COMPAT_LOADERS\n\n/*\n@@ macro 'lua_cpcall' emulates deprecated function lua_cpcall.\n** You can call your C function directly (with light C functions).\n*/\n#define lua_cpcall(L,f,u)  \\\n\t(lua_pushcfunction(L, (f)), \\\n\t lua_pushlightuserdata(L,(u)), \\\n\t lua_pcall(L,1,0,0))\n\n\n/*\n@@ LUA_COMPAT_LOG10 defines the function 'log10' in the math library.\n** You can rewrite 'log10(x)' as 'log(x, 10)'.\n*/\n#define LUA_COMPAT_LOG10\n\n/*\n@@ LUA_COMPAT_LOADSTRING defines the function 'loadstring' in the base\n** library. You can rewrite 'loadstring(s)' as 'load(s)'.\n*/\n#define LUA_COMPAT_LOADSTRING\n\n/*\n@@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library.\n*/\n#define LUA_COMPAT_MAXN\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*/\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@@ LUA_COMPAT_MODULE controls compatibility with previous\n** module functions 'module' (Lua) and 'luaL_register' (C).\n*/\n#define LUA_COMPAT_MODULE\n\n#endif\t\t\t\t/* } */\n\n\n/*\n@@ LUA_COMPAT_FLOATSTRING makes Lua format integral floats without a\n@@ a float mark ('.0').\n** This macro is not on by default even in compatibility mode,\n** because this is not really an incompatibility.\n*/\n/* #define LUA_COMPAT_FLOATSTRING */\n\n/* }================================================================== */\n\n\n\n/*\n** {==================================================================\n** Configuration for Numbers.\n** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_*\n** satisfy your needs.\n** ===================================================================\n*/\n\n/*\n@@ LUA_NUMBER is the floating-point type used by Lua.\n@@ LUAI_UACNUMBER is the result of a 'default argument promotion'\n@@ over a floating number.\n@@ l_mathlim(x) corrects limit name '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.\n@@ lua_number2str converts a float to a string.\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 numeric string to a number.\n*/\n\n\n/* The following definitions are good for most cases here */\n\n#define l_floor(x)\t\t(l_mathop(floor)(x))\n\n#define lua_number2str(s,sz,n)  \\\n\tl_sprintf((s), sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)(n))\n\n/*\n@@ lua_numbertointeger converts a float number to an integer, or\n** returns 0 if float is not within the range of a lua_Integer.\n** (The range comparisons are tricky because of rounding. The tests\n** here assume a two-complement representation, where MININTEGER always\n** has an exact representation as a float; MAXINTEGER may not have one,\n** and therefore its conversion to float 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/* 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_mathlim(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\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_mathlim(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\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_mathlim(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\"%.14g\"\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_INTEGER is the integer type used by Lua.\n**\n@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER.\n**\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_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#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#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#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#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 an hexadecimal numeric string 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 an hexadecimal numeric string.\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 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\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#if defined(LUA_USE_APICHECK)\n#include <assert.h>\n#define luai_apicheck(l,e)\tassert(e)\n#endif\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). You probably do not want/need to change them.\n** =====================================================================\n*/\n\n/*\n@@ LUAI_MAXSTACK limits the size of the Lua stack.\n** CHANGE it if you need a different limit. This limit is arbitrary;\n** its only purpose is to stop Lua from consuming unlimited stack\n** space (and to reserve some numbers for pseudo-indices).\n*/\n#if LUAI_BITSINT >= 32\n#define LUAI_MAXSTACK\t\t1000000\n#else\n#define LUAI_MAXSTACK\t\t15000\n#endif\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 buffer size used by the lauxlib buffer system.\n** CHANGE it if it uses too much C-stack space. (For long double,\n** 'string.format(\"%.99f\", -1e4932)' needs 5034 bytes, so a\n** smaller buffer would force a memory allocation for each call to\n** 'string.format'.)\n*/\n#if LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE\n#define LUAL_BUFFERSIZE\t\t8192\n#else\n#define LUAL_BUFFERSIZE   ((int)(0x80 * sizeof(void*) * sizeof(lua_Integer)))\n#endif\n\n/* }================================================================== */\n\n\n/*\n@@ LUA_QL describes how error messages quote program elements.\n** Lua does not use these macros anymore; they are here for\n** compatibility only.\n*/\n#define LUA_QL(x)\t\"'\" x \"'\"\n#define LUA_QS\t\tLUA_QL(\"%s\")\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\n\n#endif\n\n"
  },
  {
    "path": "src/lua/lualib.h",
    "content": "/*\n** $Id: lualib.h,v 1.45.1.1 2017/04/19 17:20:42 roberto Exp $\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\nLUAMOD_API int (luaopen_base) (lua_State *L);\n\n#define LUA_COLIBNAME\t\"coroutine\"\nLUAMOD_API int (luaopen_coroutine) (lua_State *L);\n\n#define LUA_TABLIBNAME\t\"table\"\nLUAMOD_API int (luaopen_table) (lua_State *L);\n\n#define LUA_IOLIBNAME\t\"io\"\nLUAMOD_API int (luaopen_io) (lua_State *L);\n\n#define LUA_OSLIBNAME\t\"os\"\nLUAMOD_API int (luaopen_os) (lua_State *L);\n\n#define LUA_STRLIBNAME\t\"string\"\nLUAMOD_API int (luaopen_string) (lua_State *L);\n\n#define LUA_UTF8LIBNAME\t\"utf8\"\nLUAMOD_API int (luaopen_utf8) (lua_State *L);\n\n#define LUA_BITLIBNAME\t\"bit32\"\nLUAMOD_API int (luaopen_bit32) (lua_State *L);\n\n#define LUA_MATHLIBNAME\t\"math\"\nLUAMOD_API int (luaopen_math) (lua_State *L);\n\n#define LUA_DBLIBNAME\t\"debug\"\nLUAMOD_API int (luaopen_debug) (lua_State *L);\n\n#define LUA_LOADLIBNAME\t\"package\"\nLUAMOD_API int (luaopen_package) (lua_State *L);\n\n\n/* open all previous libraries */\nLUALIB_API void (luaL_openlibs) (lua_State *L);\n\n\n\n#if !defined(lua_assert)\n#define lua_assert(x)\t((void)0)\n#endif\n\n\n#endif\n"
  },
  {
    "path": "src/lua/lundump.c",
    "content": "/*\n** $Id: lundump.c,v 2.44.1.1 2017/04/19 17:20:42 roberto Exp $\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 <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 \"lundump.h\"\n#include \"lzio.h\"\n\n\n#if !defined(luai_verifycode)\n#define luai_verifycode(L,b,f)  /* empty */\n#endif\n\n\ntypedef struct {\n  lua_State *L;\n  ZIO *Z;\n  const char *name;\n} LoadState;\n\n\nstatic l_noret error(LoadState *S, const char *why) {\n  luaO_pushfstring(S->L, \"%s: %s precompiled chunk\", 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,(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\");\n}\n\n\n#define LoadVar(S,x)\t\tLoadVector(S,&x,1)\n\n\nstatic lu_byte LoadByte (LoadState *S) {\n  lu_byte x;\n  LoadVar(S, x);\n  return x;\n}\n\n\nstatic int LoadInt (LoadState *S) {\n  int x;\n  LoadVar(S, x);\n  return x;\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_Integer x;\n  LoadVar(S, x);\n  return x;\n}\n\n\nstatic TString *LoadString (LoadState *S) {\n  size_t size = LoadByte(S);\n  if (size == 0xFF)\n    LoadVar(S, size);\n  if (size == 0)\n    return NULL;\n  else if (--size <= LUAI_MAXSHORTLEN) {  /* short string? */\n    char buff[LUAI_MAXSHORTLEN];\n    LoadVector(S, buff, size);\n    return luaS_newlstr(S->L, buff, size);\n  }\n  else {  /* long string */\n    TString *ts = luaS_createlngstrobj(S->L, size);\n    LoadVector(S, getstr(ts), size);  /* load directly in final place */\n    return ts;\n  }\n}\n\n\nstatic void LoadCode (LoadState *S, Proto *f) {\n  int n = LoadInt(S);\n  f->code = luaM_newvector(S->L, n, Instruction);\n  f->sizecode = n;\n  LoadVector(S, f->code, n);\n}\n\n\nstatic void LoadFunction(LoadState *S, Proto *f, TString *psource);\n\n\nstatic void LoadConstants (LoadState *S, Proto *f) {\n  int i;\n  int n = LoadInt(S);\n  f->k = luaM_newvector(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_TNIL:\n      setnilvalue(o);\n      break;\n    case LUA_TBOOLEAN:\n      setbvalue(o, LoadByte(S));\n      break;\n    case LUA_TNUMFLT:\n      setfltvalue(o, LoadNumber(S));\n      break;\n    case LUA_TNUMINT:\n      setivalue(o, LoadInteger(S));\n      break;\n    case LUA_TSHRSTR:\n    case LUA_TLNGSTR:\n      setsvalue2n(S->L, o, LoadString(S));\n      break;\n    default:\n      lua_assert(0);\n    }\n  }\n}\n\n\nstatic void LoadProtos (LoadState *S, Proto *f) {\n  int i;\n  int n = LoadInt(S);\n  f->p = luaM_newvector(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    LoadFunction(S, f->p[i], f->source);\n  }\n}\n\n\nstatic void LoadUpvalues (LoadState *S, Proto *f) {\n  int i, n;\n  n = LoadInt(S);\n  f->upvalues = luaM_newvector(S->L, n, Upvaldesc);\n  f->sizeupvalues = n;\n  for (i = 0; i < n; i++)\n    f->upvalues[i].name = NULL;\n  for (i = 0; i < n; i++) {\n    f->upvalues[i].instack = LoadByte(S);\n    f->upvalues[i].idx = LoadByte(S);\n  }\n}\n\n\nstatic void LoadDebug (LoadState *S, Proto *f) {\n  int i, n;\n  n = LoadInt(S);\n  f->lineinfo = luaM_newvector(S->L, n, int);\n  f->sizelineinfo = n;\n  LoadVector(S, f->lineinfo, n);\n  n = LoadInt(S);\n  f->locvars = luaM_newvector(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    f->locvars[i].varname = LoadString(S);\n    f->locvars[i].startpc = LoadInt(S);\n    f->locvars[i].endpc = LoadInt(S);\n  }\n  n = LoadInt(S);\n  for (i = 0; i < n; i++)\n    f->upvalues[i].name = LoadString(S);\n}\n\n\nstatic void LoadFunction (LoadState *S, Proto *f, TString *psource) {\n  f->source = LoadString(S);\n  if (f->source == NULL)  /* no source in dump? */\n    f->source = psource;  /* reuse parent's source */\n  f->linedefined = LoadInt(S);\n  f->lastlinedefined = LoadInt(S);\n  f->numparams = LoadByte(S);\n  f->is_vararg = LoadByte(S);\n  f->maxstacksize = LoadByte(S);\n  LoadCode(S, f);\n  LoadConstants(S, f);\n  LoadUpvalues(S, f);\n  LoadProtos(S, f);\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 void fchecksize (LoadState *S, size_t size, const char *tname) {\n  if (LoadByte(S) != size)\n    error(S, luaO_pushfstring(S->L, \"%s size mismatch in\", tname));\n}\n\n\n#define checksize(S,t)\tfchecksize(S,sizeof(t),#t)\n\nstatic void checkHeader (LoadState *S) {\n  checkliteral(S, LUA_SIGNATURE + 1, \"not a\");  /* 1st char already checked */\n  if (LoadByte(S) != LUAC_VERSION)\n    error(S, \"version mismatch in\");\n  if (LoadByte(S) != LUAC_FORMAT)\n    error(S, \"format mismatch in\");\n  checkliteral(S, LUAC_DATA, \"corrupted\");\n  checksize(S, int);\n  checksize(S, size_t);\n  checksize(S, Instruction);\n  checksize(S, lua_Integer);\n  checksize(S, lua_Number);\n  if (LoadInteger(S) != LUAC_INT)\n    error(S, \"endianness mismatch in\");\n  if (LoadNumber(S) != LUAC_NUM)\n    error(S, \"float format mismatch in\");\n}\n\n\n/*\n** load precompiled chunk\n*/\nLClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) {\n  LoadState S;\n  LClosure *cl;\n  if (*name == '@' || *name == '=')\n    S.name = name + 1;\n  else if (*name == LUA_SIGNATURE[0])\n    S.name = \"binary string\";\n  else\n    S.name = name;\n  S.L = L;\n  S.Z = Z;\n  checkHeader(&S);\n  cl = luaF_newLclosure(L, LoadByte(&S));\n  setclLvalue(L, L->top, cl);\n  luaD_inctop(L);\n  cl->p = luaF_newproto(L);\n  LoadFunction(&S, cl->p, NULL);\n  lua_assert(cl->nupvalues == cl->p->sizeupvalues);\n  luai_verifycode(L, buff, cl->p);\n  return cl;\n}\n\n"
  },
  {
    "path": "src/lua/lundump.h",
    "content": "/*\n** $Id: lundump.h,v 1.45.1.1 2017/04/19 17:20:42 roberto Exp $\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 \"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\t0x5678\n#define LUAC_NUM\tcast_num(370.5)\n\n#define MYINT(s)\t(s[0]-'0')\n#define LUAC_VERSION\t(MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR))\n#define LUAC_FORMAT\t0\t/* this is the official format */\n\n/* load one chunk; from lundump.c */\nLUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, const char* name);\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": "src/lua/lutf8lib.c",
    "content": "/*\n** $Id: lutf8lib.c,v 1.16.1.1 2017/04/19 17:29:57 roberto Exp $\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 <assert.h>\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\n#define MAXUNICODE\t0x10FFFF\n\n#define iscont(p)\t((*(p) & 0xC0) == 0x80)\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 invalid.\n*/\nstatic const char *utf8_decode (const char *o, int *val) {\n  static const unsigned int limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFF};\n  const unsigned char *s = (const unsigned char *)o;\n  unsigned int c = s[0];\n  unsigned int 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 > MAXUNICODE || res <= limits[count])\n      return NULL;  /* invalid byte sequence */\n    s += count;  /* skip continuation bytes read */\n  }\n  if (val) *val = res;\n  return (const char *)s + 1;  /* +1 to include first byte */\n}\n\n\n/*\n** utf8len(s [, i [, j]]) --> number of characters that start in the\n** range [i,j], or nil + current position if 's' is not well formed in\n** that interval\n*/\nstatic int utflen (lua_State *L) {\n  int n = 0;\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 posj = u_posrelat(luaL_optinteger(L, 3, -1), len);\n  luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,\n                   \"initial position out of string\");\n  luaL_argcheck(L, --posj < (lua_Integer)len, 3,\n                   \"final position out of string\");\n  while (posi <= posj) {\n    const char *s1 = utf8_decode(s + posi, NULL);\n    if (s1 == NULL) {  /* conversion error? */\n      lua_pushnil(L);  /* return nil ... */\n      lua_pushinteger(L, posi + 1);  /* ... and current position */\n      return 2;\n    }\n    posi = s1 - s;\n    n++;\n  }\n  lua_pushinteger(L, n);\n  return 1;\n}\n\n\n/*\n** codepoint(s, [i, [j]])  -> returns codepoints for all characters\n** 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 n;\n  const char *se;\n  luaL_argcheck(L, posi >= 1, 2, \"out of range\");\n  luaL_argcheck(L, pose <= (lua_Integer)len, 3, \"out of range\");\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;\n  luaL_checkstack(L, n, \"string slice too long\");\n  n = 0;\n  se = s + pose;\n  for (s += posi - 1; s < se;) {\n    int code;\n    s = utf8_decode(s, &code);\n    if (s == NULL)\n      return luaL_error(L, \"invalid UTF-8 code\");\n    lua_pushinteger(L, code);\n    n++;\n  }\n  return n;\n}\n\n\nstatic void pushutfchar (lua_State *L, int arg) {\n  lua_Integer code = luaL_checkinteger(L, arg);\n  luaL_argcheck(L, 0 <= code && code <= MAXUNICODE, 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])  -> index where n-th character counting from\n**   position 'i' starts; 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 : 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 range\");\n  if (n == 0) {\n    /* find beginning of current byte sequence */\n    while (posi > 0 && iscont(s + posi)) posi--;\n  }\n  else {\n    if (iscont(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 && iscont(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 (iscont(s + posi));  /* (cannot pass final '\\0') */\n         n--;\n       }\n     }\n  }\n  if (n == 0)  /* did it find given character? */\n    lua_pushinteger(L, posi + 1);\n  else  /* no such character */\n    lua_pushnil(L);\n  return 1;\n}\n\n\nstatic int iter_aux (lua_State *L) {\n  size_t len;\n  const char *s = luaL_checklstring(L, 1, &len);\n  lua_Integer n = lua_tointeger(L, 2) - 1;\n  if (n < 0)  /* first iteration? */\n    n = 0;  /* start from here */\n  else if (n < (lua_Integer)len) {\n    n++;  /* skip current byte */\n    while (iscont(s + n)) n++;  /* and its continuations */\n  }\n  if (n >= (lua_Integer)len)\n    return 0;  /* no more codepoints */\n  else {\n    int code;\n    const char *next = utf8_decode(s + n, &code);\n    if (next == NULL || iscont(next))\n      return luaL_error(L, \"invalid UTF-8 code\");\n    lua_pushinteger(L, n + 1);\n    lua_pushinteger(L, code);\n    return 2;\n  }\n}\n\n\nstatic int iter_codes (lua_State *L) {\n  luaL_checkstring(L, 1);\n  lua_pushcfunction(L, iter_aux);\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-\\xF4][\\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": "src/lua/lvm.c",
    "content": "/*\n** $Id: lvm.c,v 2.268.1.1 2017/04/19 17:39:34 roberto Exp $\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 \"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/* limit for table tag-method chains (to avoid loops) */\n#define MAXTAGLOOP\t2000\n\n\n\n/*\n** 'l_intfitsf' checks whether a given integer can be converted to a\n** float without rounding. Used in comparisons. Left undefined if\n** all integers fit in a float precisely.\n*/\n#if !defined(l_intfitsf)\n\n/* number of bits in the mantissa of a float */\n#define NBM\t\t(l_mathlim(MANT_DIG))\n\n/*\n** Check whether some integers may not fit in a float, that is, 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(integer) == 32.)\n*/\n#if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \\\n\t>> (NBM - (3 * (NBM / 4))))  >  0\n\n#define l_intfitsf(i)  \\\n  (-((lua_Integer)1 << NBM) <= (i) && (i) <= ((lua_Integer)1 << NBM))\n\n#endif\n\n#endif\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 (cvt2num(obj) &&  /* string convertible to number? */\n            luaO_str2num(svalue(obj), &v) == vslen(obj) + 1) {\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 value to an integer, rounding according to 'mode':\n** mode == 0: accepts only integral values\n** mode == 1: takes the floor of the number\n** mode == 2: takes the ceil of the number\n*/\nint luaV_tointeger (const TValue *obj, lua_Integer *p, int mode) {\n  TValue v;\n again:\n  if (ttisfloat(obj)) {\n    lua_Number n = fltvalue(obj);\n    lua_Number f = l_floor(n);\n    if (n != f) {  /* not an integral value? */\n      if (mode == 0) return 0;  /* fails if mode demands integral value */\n      else if (mode > 1)  /* needs ceil? */\n        f += 1;  /* convert floor to ceil (remember: n != f) */\n    }\n    return lua_numbertointeger(f, p);\n  }\n  else if (ttisinteger(obj)) {\n    *p = ivalue(obj);\n    return 1;\n  }\n  else if (cvt2num(obj) &&\n            luaO_str2num(svalue(obj), &v) == vslen(obj) + 1) {\n    obj = &v;\n    goto again;  /* convert result from 'luaO_str2num' to an integer */\n  }\n  return 0;  /* conversion failed */\n}\n\n\n/*\n** Try to convert a 'for' limit to an integer, preserving the\n** semantics of the loop.\n** (The following explanation assumes a non-negative step; it is valid\n** for negative steps mutatis mutandis.)\n** If the limit can be converted to an integer, rounding down, that is\n** it.\n** Otherwise, check whether the limit can be converted to a number.  If\n** the number is too large, it is OK to set the limit as LUA_MAXINTEGER,\n** which means no limit.  If the number is too negative, the loop\n** should not run, because any initial integer value is larger than the\n** limit. So, it sets the limit to LUA_MININTEGER. 'stopnow' corrects\n** the extreme case when the initial value is LUA_MININTEGER, in which\n** case the LUA_MININTEGER limit would still run the loop once.\n*/\nstatic int forlimit (const TValue *obj, lua_Integer *p, lua_Integer step,\n                     int *stopnow) {\n  *stopnow = 0;  /* usually, let loops run */\n  if (!luaV_tointeger(obj, p, (step < 0 ? 2 : 1))) {  /* not fit in integer? */\n    lua_Number n;  /* try to convert to float */\n    if (!tonumber(obj, &n)) /* cannot convert to float? */\n      return 0;  /* not a number */\n    if (luai_numlt(0, n)) {  /* if true, float is larger than max integer */\n      *p = LUA_MAXINTEGER;\n      if (step < 0) *stopnow = 1;\n    }\n    else {  /* float is smaller than min integer */\n      *p = LUA_MININTEGER;\n      if (step >= 0) *stopnow = 1;\n    }\n  }\n  return 1;\n}\n\n\n/*\n** Finish the table access 'val = t[key]'.\n** if 'slot' is NULL, 't' is not a table; otherwise, 'slot' points to\n** t[k] entry (which must be nil).\n*/\nvoid luaV_finishget (lua_State *L, const TValue *t, TValue *key, StkId val,\n                      const TValue *slot) {\n  int loop;  /* counter to avoid infinite loops */\n  const TValue *tm;  /* metamethod */\n  for (loop = 0; loop < MAXTAGLOOP; loop++) {\n    if (slot == NULL) {  /* 't' is not a table? */\n      lua_assert(!ttistable(t));\n      tm = luaT_gettmbyobj(L, t, TM_INDEX);\n      if (ttisnil(tm))\n        luaG_typeerror(L, t, \"index\");  /* no metamethod */\n      /* else will try the metamethod */\n    }\n    else {  /* 't' is a table */\n      lua_assert(ttisnil(slot));\n      tm = fasttm(L, hvalue(t)->metatable, TM_INDEX);  /* table's metamethod */\n      if (tm == NULL) {  /* no metamethod? */\n        setnilvalue(val);  /* result is nil */\n        return;\n      }\n      /* else will try the metamethod */\n    }\n    if (ttisfunction(tm)) {  /* is metamethod a function? */\n      luaT_callTM(L, tm, t, key, val, 1);  /* call it */\n      return;\n    }\n    t = tm;  /* else try to access 'tm[key]' */\n    if (luaV_fastget(L,t,key,slot,luaH_get)) {  /* fast track? */\n      setobj2s(L, val, slot);  /* done */\n      return;\n    }\n    /* else repeat (tail call 'luaV_finishget') */\n  }\n  luaG_runerror(L, \"'__index' chain too long; possible loop\");\n}\n\n\n/*\n** Finish a table assignment 't[key] = val'.\n** If 'slot' is NULL, 't' is not a table.  Otherwise, 'slot' points\n** to the entry 't[key]', or to 'luaO_nilobject' if there is no such\n** entry.  (The value at 'slot' must be nil, otherwise 'luaV_fastset'\n** would have done the job.)\n*/\nvoid luaV_finishset (lua_State *L, const TValue *t, TValue *key,\n                     StkId val, const TValue *slot) {\n  int loop;  /* counter to avoid infinite loops */\n  for (loop = 0; loop < MAXTAGLOOP; loop++) {\n    const TValue *tm;  /* '__newindex' metamethod */\n    if (slot != NULL) {  /* is 't' a table? */\n      Table *h = hvalue(t);  /* save 't' table */\n      lua_assert(ttisnil(slot));  /* old value must be nil */\n      tm = fasttm(L, h->metatable, TM_NEWINDEX);  /* get metamethod */\n      if (tm == NULL) {  /* no metamethod? */\n        if (slot == luaO_nilobject)  /* no previous entry? */\n          slot = luaH_newkey(L, h, key);  /* create one */\n        /* no metamethod and (now) there is an entry with given key */\n        setobj2t(L, cast(TValue *, slot), val);  /* set its new value */\n        invalidateTMcache(h);\n        luaC_barrierback(L, h, val);\n        return;\n      }\n      /* else will try the metamethod */\n    }\n    else {  /* not a table; check metamethod */\n      if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))\n        luaG_typeerror(L, t, \"index\");\n    }\n    /* try the metamethod */\n    if (ttisfunction(tm)) {\n      luaT_callTM(L, tm, t, key, val, 0);\n      return;\n    }\n    t = tm;  /* else repeat assignment over 'tm' */\n    if (luaV_fastset(L, t, key, slot, luaH_get, val))\n      return;  /* done */\n    /* else loop */\n  }\n  luaG_runerror(L, \"'__newindex' chain too long; possible loop\");\n}\n\n\n/*\n** Compare two strings 'ls' x 'rs', returning an integer smaller-equal-\n** -larger than zero if 'ls' is smaller-equal-larger than 'rs'.\n** The code is a little tricky because it allows '\\0' in the strings\n** and it uses 'strcoll' (to respect locales) for each segments\n** of the strings.\n*/\nstatic int l_strcmp (const TString *ls, const TString *rs) {\n  const char *l = getstr(ls);\n  size_t ll = tsslen(ls);\n  const char *r = getstr(rs);\n  size_t lr = tsslen(rs);\n  for (;;) {  /* for each segment */\n    int temp = strcoll(l, r);\n    if (temp != 0)  /* not equal? */\n      return temp;  /* done */\n    else {  /* strings are equal up to a '\\0' */\n      size_t len = strlen(l);  /* index of first '\\0' in both strings */\n      if (len == lr)  /* 'rs' is finished? */\n        return (len == ll) ? 0 : 1;  /* check 'ls' */\n      else if (len == ll)  /* 'ls' is finished? */\n        return -1;  /* 'ls' is smaller than 'rs' ('rs' is not finished) */\n      /* both strings longer than 'len'; go on comparing after the '\\0' */\n      len++;\n      l += len; ll -= len; r += len; lr -= len;\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, if 'f' is outside the range for integers, result\n** is trivial. Otherwise, compare them as integers. (When 'i' has no\n** float representation, either 'f' is \"far away\" from 'i' or 'f' has\n** no precision left for a fractional part; either way, how 'f' is\n** truncated is irrelevant.) When 'f' is NaN, comparisons must result\n** in false.\n*/\nstatic int LTintfloat (lua_Integer i, lua_Number f) {\n#if defined(l_intfitsf)\n  if (!l_intfitsf(i)) {\n    if (f >= -cast_num(LUA_MININTEGER))  /* -minint == maxint + 1 */\n      return 1;  /* f >= maxint + 1 > i */\n    else if (f > cast_num(LUA_MININTEGER))  /* minint < f <= maxint ? */\n      return (i < cast(lua_Integer, f));  /* compare them as integers */\n    else  /* f <= minint <= i (or 'f' is NaN)  -->  not(i < f) */\n      return 0;\n  }\n#endif\n  return luai_numlt(cast_num(i), f);  /* compare them as floats */\n}\n\n\n/*\n** Check whether integer 'i' is less than or equal to float 'f'.\n** See comments on previous function.\n*/\nstatic int LEintfloat (lua_Integer i, lua_Number f) {\n#if defined(l_intfitsf)\n  if (!l_intfitsf(i)) {\n    if (f >= -cast_num(LUA_MININTEGER))  /* -minint == maxint + 1 */\n      return 1;  /* f >= maxint + 1 > i */\n    else if (f >= cast_num(LUA_MININTEGER))  /* minint <= f <= maxint ? */\n      return (i <= cast(lua_Integer, f));  /* compare them as integers */\n    else  /* f < minint <= i (or 'f' is NaN)  -->  not(i <= f) */\n      return 0;\n  }\n#endif\n  return luai_numle(cast_num(i), f);  /* compare them as floats */\n}\n\n\n/*\n** Return 'l < r', for numbers.\n*/\nstatic int LTnum (const TValue *l, const TValue *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 if (luai_numisnan(lf))  /* 'r' is int and 'l' is float */\n      return 0;  /* NaN < i is always false */\n    else  /* without NaN, (l < r)  <-->  not(r <= l) */\n      return !LEintfloat(ivalue(r), lf);  /* not (r <= l) ? */\n  }\n}\n\n\n/*\n** Return 'l <= r', for numbers.\n*/\nstatic int LEnum (const TValue *l, const TValue *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 if (luai_numisnan(lf))  /* 'r' is int and 'l' is float */\n      return 0;  /*  NaN <= i is always false */\n    else  /* without NaN, (l <= r)  <-->  not(r < l) */\n      return !LTintfloat(ivalue(r), lf);  /* not (r < l) ? */\n  }\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  int res;\n  if (ttisnumber(l) && ttisnumber(r))  /* both operands are numbers? */\n    return LTnum(l, r);\n  else if (ttisstring(l) && ttisstring(r))  /* both are strings? */\n    return l_strcmp(tsvalue(l), tsvalue(r)) < 0;\n  else if ((res = luaT_callorderTM(L, l, r, TM_LT)) < 0)  /* no metamethod? */\n    luaG_ordererror(L, l, r);  /* error */\n  return res;\n}\n\n\n/*\n** Main operation less than or equal to; return 'l <= r'. If it needs\n** a metamethod and there is no '__le', try '__lt', based on\n** l <= r iff !(r < l) (assuming a total order). If the metamethod\n** yields during this substitution, the continuation has to know\n** about it (to negate the result of r<l); bit CIST_LEQ in the call\n** status keeps that information.\n*/\nint luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {\n  int res;\n  if (ttisnumber(l) && ttisnumber(r))  /* both operands are numbers? */\n    return LEnum(l, r);\n  else if (ttisstring(l) && ttisstring(r))  /* both are strings? */\n    return l_strcmp(tsvalue(l), tsvalue(r)) <= 0;\n  else if ((res = luaT_callorderTM(L, l, r, TM_LE)) >= 0)  /* try 'le' */\n    return res;\n  else {  /* try 'lt': */\n    L->ci->callstatus |= CIST_LEQ;  /* mark it is doing 'lt' for 'le' */\n    res = luaT_callorderTM(L, r, l, TM_LT);\n    L->ci->callstatus ^= CIST_LEQ;  /* clear mark */\n    if (res < 0)\n      luaG_ordererror(L, l, r);\n    return !res;  /* result is negated */\n  }\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 variant? */\n    if (ttnov(t1) != ttnov(t2) || ttnov(t1) != LUA_TNUMBER)\n      return 0;  /* only numbers can be equal with different variants */\n    else {  /* two numbers with different variants */\n      lua_Integer i1, i2;  /* compare them as integers */\n      return (tointeger(t1, &i1) && tointeger(t2, &i2) && i1 == i2);\n    }\n  }\n  /* values have same type and same variant */\n  switch (ttype(t1)) {\n    case LUA_TNIL: return 1;\n    case LUA_TNUMINT: return (ivalue(t1) == ivalue(t2));\n    case LUA_TNUMFLT: return luai_numeq(fltvalue(t1), fltvalue(t2));\n    case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2);  /* true must be 1 !! */\n    case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);\n    case LUA_TLCF: return fvalue(t1) == fvalue(t2);\n    case LUA_TSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2));\n    case LUA_TLNGSTR: return luaS_eqlngstr(tsvalue(t1), tsvalue(t2));\n    case LUA_TUSERDATA: {\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_TTABLE: {\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    default:\n      return gcvalue(t1) == gcvalue(t2);\n  }\n  if (tm == NULL)  /* no TM? */\n    return 0;  /* objects are different */\n  luaT_callTM(L, tm, t1, t2, L->top, 1);  /* call TM */\n  return !l_isfalse(L->top);\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#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    size_t l = vslen(top - n);  /* length of string being copied */\n    memcpy(buff + tl, svalue(top - n), 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 - total' up to 'L->top - 1'.\n*/\nvoid luaV_concat (lua_State *L, int total) {\n  lua_assert(total >= 2);\n  do {\n    StkId top = L->top;\n    int n = 2;  /* number of elements handled in this pass (at least 2) */\n    if (!(ttisstring(top-2) || cvt2str(top-2)) || !tostring(L, top-1))\n      luaT_trybinTM(L, top-2, top-1, top-2, TM_CONCAT);\n    else if (isemptystr(top - 1))  /* second operand is empty? */\n      cast_void(tostring(L, top - 2));  /* result is first operand */\n    else if (isemptystr(top - 2)) {  /* first operand is an empty string? */\n      setobjs2s(L, top - 2, top - 1);  /* result is second op. */\n    }\n    else {\n      /* at least two non-empty string values; get as many as possible */\n      size_t tl = vslen(top - 1);\n      TString *ts;\n      /* collect total length and number of strings */\n      for (n = 1; n < total && tostring(L, top - n - 1); n++) {\n        size_t l = vslen(top - n - 1);\n        if (l >= (MAX_SIZE/sizeof(char)) - tl)\n          luaG_runerror(L, \"string length overflow\");\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, getstr(ts));\n      }\n      setsvalue2s(L, top - n, ts);  /* create result */\n    }\n    total -= n-1;  /* got 'n' strings to create 1 new */\n    L->top -= 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 (ttype(rb)) {\n    case LUA_TTABLE: {\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(ra, luaH_getn(h));  /* else primitive len */\n      return;\n    }\n    case LUA_TSHRSTR: {\n      setivalue(ra, tsvalue(rb)->shrlen);\n      return;\n    }\n    case LUA_TLNGSTR: {\n      setivalue(ra, tsvalue(rb)->u.lnglen);\n      return;\n    }\n    default: {  /* try metamethod */\n      tm = luaT_gettmbyobj(L, rb, TM_LEN);\n      if (ttisnil(tm))  /* no metamethod? */\n        luaG_typeerror(L, rb, \"get length of\");\n      break;\n    }\n  }\n  luaT_callTM(L, tm, rb, rb, ra, 1);\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_div (lua_State *L, lua_Integer m, lua_Integer n) {\n  if (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_div.)\n*/\nlua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) {\n  if (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 && (m ^ 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/* number of bits in an integer */\n#define NBITS\tcast_int(sizeof(lua_Integer) * CHAR_BIT)\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** check whether cached closure in prototype 'p' may be reused, that is,\n** whether there is a cached closure with the same upvalues needed by\n** new closure to be created.\n*/\nstatic LClosure *getcached (Proto *p, UpVal **encup, StkId base) {\n  LClosure *c = p->cache;\n  if (c != NULL) {  /* is there a cached closure? */\n    int nup = p->sizeupvalues;\n    Upvaldesc *uv = p->upvalues;\n    int i;\n    for (i = 0; i < nup; i++) {  /* check whether it has right upvalues */\n      TValue *v = uv[i].instack ? base + uv[i].idx : encup[uv[i].idx]->v;\n      if (c->upvals[i]->v != v)\n        return NULL;  /* wrong upvalue; cannot reuse closure */\n    }\n  }\n  return c;  /* return cached closure (or NULL if no cached closure) */\n}\n\n\n/*\n** create a new Lua closure, push it in the stack, and initialize\n** its upvalues. Note that the closure is not cached if prototype is\n** already black (which means that 'cache' was already cleared by the\n** GC).\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  setclLvalue(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    ncl->upvals[i]->refcount++;\n    /* new closure is white, so we do not need a barrier here */\n  }\n  if (!isblack(p))  /* cache will not break GC invariant? */\n    p->cache = ncl;  /* save it on cache for reuse */\n}\n\n\n/*\n** finish execution of an opcode interrupted by an yield\n*/\nvoid luaV_finishOp (lua_State *L) {\n  CallInfo *ci = L->ci;\n  StkId base = ci->u.l.base;\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_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_IDIV:\n    case OP_BAND: case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR:\n    case OP_MOD: case OP_POW:\n    case OP_UNM: case OP_BNOT: case OP_LEN:\n    case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: {\n      setobjs2s(L, base + GETARG_A(inst), --L->top);\n      break;\n    }\n    case OP_LE: case OP_LT: case OP_EQ: {\n      int res = !l_isfalse(L->top - 1);\n      L->top--;\n      if (ci->callstatus & CIST_LEQ) {  /* \"<=\" using \"<\" instead? */\n        lua_assert(op == OP_LE);\n        ci->callstatus ^= CIST_LEQ;  /* clear mark */\n        res = !res;  /* negate result */\n      }\n      lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP);\n      if (res != GETARG_A(inst))  /* condition failed? */\n        ci->u.l.savedpc++;  /* skip jump instruction */\n      break;\n    }\n    case OP_CONCAT: {\n      StkId top = L->top - 1;  /* top when 'luaT_trybinTM' was called */\n      int b = GETARG_B(inst);      /* first element to concatenate */\n      int total = cast_int(top - 1 - (base + b));  /* yet to concatenate */\n      setobj2s(L, top - 2, top);  /* put TM result in proper position */\n      if (total > 1) {  /* are there elements to concat? */\n        L->top = top - 1;  /* top is one after last element (at top-2) */\n        luaV_concat(L, total);  /* concat them (may yield again) */\n      }\n      /* move final result to final position */\n      setobj2s(L, ci->u.l.base + GETARG_A(inst), L->top - 1);\n      L->top = ci->top;  /* restore top */\n      break;\n    }\n    case OP_TFORCALL: {\n      lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_TFORLOOP);\n      L->top = ci->top;  /* correct top */\n      break;\n    }\n    case OP_CALL: {\n      if (GETARG_C(inst) - 1 >= 0)  /* nresults >= 0? */\n        L->top = ci->top;  /* adjust results */\n      break;\n    }\n    case OP_TAILCALL: case OP_SETTABUP: case OP_SETTABLE:\n      break;\n    default: lua_assert(0);\n  }\n}\n\n\n\n\n/*\n** {==================================================================\n** Function 'luaV_execute': main interpreter loop\n** ===================================================================\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 RB(i)\tcheck_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))\n#define RC(i)\tcheck_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i))\n#define RKB(i)\tcheck_exp(getBMode(GET_OPCODE(i)) == OpArgK, \\\n\tISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i))\n#define RKC(i)\tcheck_exp(getCMode(GET_OPCODE(i)) == OpArgK, \\\n\tISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i))\n\n\n/* execute a jump instruction */\n#define dojump(ci,i,e) \\\n  { int a = GETARG_A(i); \\\n    if (a != 0) luaF_close(L, ci->u.l.base + a - 1); \\\n    ci->u.l.savedpc += GETARG_sBx(i) + e; }\n\n/* for test instructions, execute the jump instruction that follows it */\n#define donextjump(ci)\t{ i = *ci->u.l.savedpc; dojump(ci, i, 1); }\n\n\n#define Protect(x)\t{ {x;}; base = ci->u.l.base; }\n\n#define checkGC(L,c)  \\\n\t{ luaC_condGC(L, L->top = (c),  /* limit of live values */ \\\n                         Protect(L->top = ci->top));  /* restore top */ \\\n           luai_threadyield(L); }\n\n\n/* fetch an instruction and prepare its execution */\n#define vmfetch()\t{ \\\n  i = *(ci->u.l.savedpc++); \\\n  if (L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) \\\n    Protect(luaG_traceexec(L)); \\\n  ra = RA(i); /* WARNING: any stack reallocation invalidates 'ra' */ \\\n  lua_assert(base == ci->u.l.base); \\\n  lua_assert(base <= L->top && L->top < L->stack + L->stacksize); \\\n}\n\n#define vmdispatch(o)\tswitch(o)\n#define vmcase(l)\tcase l:\n#define vmbreak\t\tbreak\n\n\n/*\n** copy of 'luaV_gettable', but protecting the call to potential\n** metamethod (which can reallocate the stack)\n*/\n#define gettableProtected(L,t,k,v)  { const TValue *slot; \\\n  if (luaV_fastget(L,t,k,slot,luaH_get)) { setobj2s(L, v, slot); } \\\n  else Protect(luaV_finishget(L,t,k,v,slot)); }\n\n\n/* same for 'luaV_settable' */\n#define settableProtected(L,t,k,v) { const TValue *slot; \\\n  if (!luaV_fastset(L,t,k,slot,luaH_get,v)) \\\n    Protect(luaV_finishset(L,t,k,v,slot)); }\n\n\n\nvoid luaV_execute (lua_State *L) {\n  CallInfo *ci = L->ci;\n  LClosure *cl;\n  TValue *k;\n  StkId base;\n  ci->callstatus |= CIST_FRESH;  /* fresh invocation of 'luaV_execute\" */\n newframe:  /* reentry point when frame changes (call/return) */\n  lua_assert(ci == L->ci);\n  cl = clLvalue(ci->func);  /* local reference to function's closure */\n  k = cl->p->k;  /* local reference to function's constant table */\n  base = ci->u.l.base;  /* local copy of function's base */\n  /* main loop of interpreter */\n  for (;;) {\n    Instruction i;\n    StkId ra;\n    vmfetch();\n    vmdispatch (GET_OPCODE(i)) {\n      vmcase(OP_MOVE) {\n        setobjs2s(L, ra, RB(i));\n        vmbreak;\n      }\n      vmcase(OP_LOADK) {\n        TValue *rb = k + GETARG_Bx(i);\n        setobj2s(L, ra, rb);\n        vmbreak;\n      }\n      vmcase(OP_LOADKX) {\n        TValue *rb;\n        lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);\n        rb = k + GETARG_Ax(*ci->u.l.savedpc++);\n        setobj2s(L, ra, rb);\n        vmbreak;\n      }\n      vmcase(OP_LOADBOOL) {\n        setbvalue(ra, GETARG_B(i));\n        if (GETARG_C(i)) ci->u.l.savedpc++;  /* skip next instruction (if C) */\n        vmbreak;\n      }\n      vmcase(OP_LOADNIL) {\n        int b = GETARG_B(i);\n        do {\n          setnilvalue(ra++);\n        } while (b--);\n        vmbreak;\n      }\n      vmcase(OP_GETUPVAL) {\n        int b = GETARG_B(i);\n        setobj2s(L, ra, cl->upvals[b]->v);\n        vmbreak;\n      }\n      vmcase(OP_GETTABUP) {\n        TValue *upval = cl->upvals[GETARG_B(i)]->v;\n        TValue *rc = RKC(i);\n        gettableProtected(L, upval, rc, ra);\n        vmbreak;\n      }\n      vmcase(OP_GETTABLE) {\n        StkId rb = RB(i);\n        TValue *rc = RKC(i);\n        gettableProtected(L, rb, rc, ra);\n        vmbreak;\n      }\n      vmcase(OP_SETTABUP) {\n        TValue *upval = cl->upvals[GETARG_A(i)]->v;\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        settableProtected(L, upval, rb, rc);\n        vmbreak;\n      }\n      vmcase(OP_SETUPVAL) {\n        UpVal *uv = cl->upvals[GETARG_B(i)];\n        setobj(L, uv->v, ra);\n        luaC_upvalbarrier(L, uv);\n        vmbreak;\n      }\n      vmcase(OP_SETTABLE) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        settableProtected(L, ra, rb, rc);\n        vmbreak;\n      }\n      vmcase(OP_NEWTABLE) {\n        int b = GETARG_B(i);\n        int c = GETARG_C(i);\n        Table *t = luaH_new(L);\n        sethvalue(L, ra, t);\n        if (b != 0 || c != 0)\n          luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));\n        checkGC(L, ra + 1);\n        vmbreak;\n      }\n      vmcase(OP_SELF) {\n        const TValue *aux;\n        StkId rb = RB(i);\n        TValue *rc = RKC(i);\n        TString *key = tsvalue(rc);  /* key must be a string */\n        setobjs2s(L, ra + 1, rb);\n        if (luaV_fastget(L, rb, key, aux, luaH_getstr)) {\n          setobj2s(L, ra, aux);\n        }\n        else Protect(luaV_finishget(L, rb, rc, ra, aux));\n        vmbreak;\n      }\n      vmcase(OP_ADD) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Number nb; lua_Number nc;\n        if (ttisinteger(rb) && ttisinteger(rc)) {\n          lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);\n          setivalue(ra, intop(+, ib, ic));\n        }\n        else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {\n          setfltvalue(ra, luai_numadd(L, nb, nc));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_ADD)); }\n        vmbreak;\n      }\n      vmcase(OP_SUB) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Number nb; lua_Number nc;\n        if (ttisinteger(rb) && ttisinteger(rc)) {\n          lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);\n          setivalue(ra, intop(-, ib, ic));\n        }\n        else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {\n          setfltvalue(ra, luai_numsub(L, nb, nc));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SUB)); }\n        vmbreak;\n      }\n      vmcase(OP_MUL) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Number nb; lua_Number nc;\n        if (ttisinteger(rb) && ttisinteger(rc)) {\n          lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);\n          setivalue(ra, intop(*, ib, ic));\n        }\n        else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {\n          setfltvalue(ra, luai_nummul(L, nb, nc));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MUL)); }\n        vmbreak;\n      }\n      vmcase(OP_DIV) {  /* float division (always with floats) */\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Number nb; lua_Number nc;\n        if (tonumber(rb, &nb) && tonumber(rc, &nc)) {\n          setfltvalue(ra, luai_numdiv(L, nb, nc));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_DIV)); }\n        vmbreak;\n      }\n      vmcase(OP_BAND) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Integer ib; lua_Integer ic;\n        if (tointeger(rb, &ib) && tointeger(rc, &ic)) {\n          setivalue(ra, intop(&, ib, ic));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BAND)); }\n        vmbreak;\n      }\n      vmcase(OP_BOR) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Integer ib; lua_Integer ic;\n        if (tointeger(rb, &ib) && tointeger(rc, &ic)) {\n          setivalue(ra, intop(|, ib, ic));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BOR)); }\n        vmbreak;\n      }\n      vmcase(OP_BXOR) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Integer ib; lua_Integer ic;\n        if (tointeger(rb, &ib) && tointeger(rc, &ic)) {\n          setivalue(ra, intop(^, ib, ic));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BXOR)); }\n        vmbreak;\n      }\n      vmcase(OP_SHL) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Integer ib; lua_Integer ic;\n        if (tointeger(rb, &ib) && tointeger(rc, &ic)) {\n          setivalue(ra, luaV_shiftl(ib, ic));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHL)); }\n        vmbreak;\n      }\n      vmcase(OP_SHR) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Integer ib; lua_Integer ic;\n        if (tointeger(rb, &ib) && tointeger(rc, &ic)) {\n          setivalue(ra, luaV_shiftl(ib, -ic));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHR)); }\n        vmbreak;\n      }\n      vmcase(OP_MOD) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Number nb; lua_Number nc;\n        if (ttisinteger(rb) && ttisinteger(rc)) {\n          lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);\n          setivalue(ra, luaV_mod(L, ib, ic));\n        }\n        else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {\n          lua_Number m;\n          luai_nummod(L, nb, nc, m);\n          setfltvalue(ra, m);\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MOD)); }\n        vmbreak;\n      }\n      vmcase(OP_IDIV) {  /* floor division */\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Number nb; lua_Number nc;\n        if (ttisinteger(rb) && ttisinteger(rc)) {\n          lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);\n          setivalue(ra, luaV_div(L, ib, ic));\n        }\n        else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {\n          setfltvalue(ra, luai_numidiv(L, nb, nc));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_IDIV)); }\n        vmbreak;\n      }\n      vmcase(OP_POW) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        lua_Number nb; lua_Number nc;\n        if (tonumber(rb, &nb) && tonumber(rc, &nc)) {\n          setfltvalue(ra, luai_numpow(L, nb, nc));\n        }\n        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_POW)); }\n        vmbreak;\n      }\n      vmcase(OP_UNM) {\n        TValue *rb = RB(i);\n        lua_Number nb;\n        if (ttisinteger(rb)) {\n          lua_Integer ib = ivalue(rb);\n          setivalue(ra, intop(-, 0, ib));\n        }\n        else if (tonumber(rb, &nb)) {\n          setfltvalue(ra, luai_numunm(L, nb));\n        }\n        else {\n          Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));\n        }\n        vmbreak;\n      }\n      vmcase(OP_BNOT) {\n        TValue *rb = RB(i);\n        lua_Integer ib;\n        if (tointeger(rb, &ib)) {\n          setivalue(ra, intop(^, ~l_castS2U(0), ib));\n        }\n        else {\n          Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));\n        }\n        vmbreak;\n      }\n      vmcase(OP_NOT) {\n        TValue *rb = RB(i);\n        int res = l_isfalse(rb);  /* next assignment may change this value */\n        setbvalue(ra, res);\n        vmbreak;\n      }\n      vmcase(OP_LEN) {\n        Protect(luaV_objlen(L, ra, RB(i)));\n        vmbreak;\n      }\n      vmcase(OP_CONCAT) {\n        int b = GETARG_B(i);\n        int c = GETARG_C(i);\n        StkId rb;\n        L->top = base + c + 1;  /* mark the end of concat operands */\n        Protect(luaV_concat(L, c - b + 1));\n        ra = RA(i);  /* 'luaV_concat' may invoke TMs and move the stack */\n        rb = base + b;\n        setobjs2s(L, ra, rb);\n        checkGC(L, (ra >= rb ? ra + 1 : rb));\n        L->top = ci->top;  /* restore top */\n        vmbreak;\n      }\n      vmcase(OP_JMP) {\n        dojump(ci, i, 0);\n        vmbreak;\n      }\n      vmcase(OP_EQ) {\n        TValue *rb = RKB(i);\n        TValue *rc = RKC(i);\n        Protect(\n          if (luaV_equalobj(L, rb, rc) != GETARG_A(i))\n            ci->u.l.savedpc++;\n          else\n            donextjump(ci);\n        )\n        vmbreak;\n      }\n      vmcase(OP_LT) {\n        Protect(\n          if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i))\n            ci->u.l.savedpc++;\n          else\n            donextjump(ci);\n        )\n        vmbreak;\n      }\n      vmcase(OP_LE) {\n        Protect(\n          if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i))\n            ci->u.l.savedpc++;\n          else\n            donextjump(ci);\n        )\n        vmbreak;\n      }\n      vmcase(OP_TEST) {\n        if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra))\n            ci->u.l.savedpc++;\n          else\n          donextjump(ci);\n        vmbreak;\n      }\n      vmcase(OP_TESTSET) {\n        TValue *rb = RB(i);\n        if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb))\n          ci->u.l.savedpc++;\n        else {\n          setobjs2s(L, ra, rb);\n          donextjump(ci);\n        }\n        vmbreak;\n      }\n      vmcase(OP_CALL) {\n        int b = GETARG_B(i);\n        int nresults = GETARG_C(i) - 1;\n        if (b != 0) L->top = ra+b;  /* else previous instruction set top */\n        if (luaD_precall(L, ra, nresults)) {  /* C function? */\n          if (nresults >= 0)\n            L->top = ci->top;  /* adjust results */\n          Protect((void)0);  /* update 'base' */\n        }\n        else {  /* Lua function */\n          ci = L->ci;\n          goto newframe;  /* restart luaV_execute over new Lua function */\n        }\n        vmbreak;\n      }\n      vmcase(OP_TAILCALL) {\n        int b = GETARG_B(i);\n        if (b != 0) L->top = ra+b;  /* else previous instruction set top */\n        lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);\n        if (luaD_precall(L, ra, LUA_MULTRET)) {  /* C function? */\n          Protect((void)0);  /* update 'base' */\n        }\n        else {\n          /* tail call: put called frame (n) in place of caller one (o) */\n          CallInfo *nci = L->ci;  /* called frame */\n          CallInfo *oci = nci->previous;  /* caller frame */\n          StkId nfunc = nci->func;  /* called function */\n          StkId ofunc = oci->func;  /* caller function */\n          /* last stack slot filled by 'precall' */\n          StkId lim = nci->u.l.base + getproto(nfunc)->numparams;\n          int aux;\n          /* close all upvalues from previous call */\n          if (cl->p->sizep > 0) luaF_close(L, oci->u.l.base);\n          /* move new frame into old one */\n          for (aux = 0; nfunc + aux < lim; aux++)\n            setobjs2s(L, ofunc + aux, nfunc + aux);\n          oci->u.l.base = ofunc + (nci->u.l.base - nfunc);  /* correct base */\n          oci->top = L->top = ofunc + (L->top - nfunc);  /* correct top */\n          oci->u.l.savedpc = nci->u.l.savedpc;\n          oci->callstatus |= CIST_TAIL;  /* function was tail called */\n          ci = L->ci = oci;  /* remove new frame */\n          lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize);\n          goto newframe;  /* restart luaV_execute over new Lua function */\n        }\n        vmbreak;\n      }\n      vmcase(OP_RETURN) {\n        int b = GETARG_B(i);\n        if (cl->p->sizep > 0) luaF_close(L, base);\n        b = luaD_poscall(L, ci, ra, (b != 0 ? b - 1 : cast_int(L->top - ra)));\n        if (ci->callstatus & CIST_FRESH)  /* local 'ci' still from callee */\n          return;  /* external invocation: return */\n        else {  /* invocation via reentry: continue execution */\n          ci = L->ci;\n          if (b) L->top = ci->top;\n          lua_assert(isLua(ci));\n          lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL);\n          goto newframe;  /* restart luaV_execute over new Lua function */\n        }\n      }\n      vmcase(OP_FORLOOP) {\n        if (ttisinteger(ra)) {  /* integer loop? */\n          lua_Integer step = ivalue(ra + 2);\n          lua_Integer idx = intop(+, ivalue(ra), step); /* increment index */\n          lua_Integer limit = ivalue(ra + 1);\n          if ((0 < step) ? (idx <= limit) : (limit <= idx)) {\n            ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */\n            chgivalue(ra, idx);  /* update internal index... */\n            setivalue(ra + 3, idx);  /* ...and external index */\n          }\n        }\n        else {  /* floating loop */\n          lua_Number step = fltvalue(ra + 2);\n          lua_Number idx = luai_numadd(L, fltvalue(ra), step); /* inc. index */\n          lua_Number limit = fltvalue(ra + 1);\n          if (luai_numlt(0, step) ? luai_numle(idx, limit)\n                                  : luai_numle(limit, idx)) {\n            ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */\n            chgfltvalue(ra, idx);  /* update internal index... */\n            setfltvalue(ra + 3, idx);  /* ...and external index */\n          }\n        }\n        vmbreak;\n      }\n      vmcase(OP_FORPREP) {\n        TValue *init = ra;\n        TValue *plimit = ra + 1;\n        TValue *pstep = ra + 2;\n        lua_Integer ilimit;\n        int stopnow;\n        if (ttisinteger(init) && ttisinteger(pstep) &&\n            forlimit(plimit, &ilimit, ivalue(pstep), &stopnow)) {\n          /* all values are integer */\n          lua_Integer initv = (stopnow ? 0 : ivalue(init));\n          setivalue(plimit, ilimit);\n          setivalue(init, intop(-, initv, ivalue(pstep)));\n        }\n        else {  /* try making all values floats */\n          lua_Number ninit; lua_Number nlimit; lua_Number nstep;\n          if (!tonumber(plimit, &nlimit))\n            luaG_runerror(L, \"'for' limit must be a number\");\n          setfltvalue(plimit, nlimit);\n          if (!tonumber(pstep, &nstep))\n            luaG_runerror(L, \"'for' step must be a number\");\n          setfltvalue(pstep, nstep);\n          if (!tonumber(init, &ninit))\n            luaG_runerror(L, \"'for' initial value must be a number\");\n          setfltvalue(init, luai_numsub(L, ninit, nstep));\n        }\n        ci->u.l.savedpc += GETARG_sBx(i);\n        vmbreak;\n      }\n      vmcase(OP_TFORCALL) {\n        StkId cb = ra + 3;  /* call base */\n        setobjs2s(L, cb+2, ra+2);\n        setobjs2s(L, cb+1, ra+1);\n        setobjs2s(L, cb, ra);\n        L->top = cb + 3;  /* func. + 2 args (state and index) */\n        Protect(luaD_call(L, cb, GETARG_C(i)));\n        L->top = ci->top;\n        i = *(ci->u.l.savedpc++);  /* go to next instruction */\n        ra = RA(i);\n        lua_assert(GET_OPCODE(i) == OP_TFORLOOP);\n        goto l_tforloop;\n      }\n      vmcase(OP_TFORLOOP) {\n        l_tforloop:\n        if (!ttisnil(ra + 1)) {  /* continue loop? */\n          setobjs2s(L, ra, ra + 1);  /* save control variable */\n           ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */\n        }\n        vmbreak;\n      }\n      vmcase(OP_SETLIST) {\n        int n = GETARG_B(i);\n        int c = GETARG_C(i);\n        unsigned int last;\n        Table *h;\n        if (n == 0) n = cast_int(L->top - ra) - 1;\n        if (c == 0) {\n          lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);\n          c = GETARG_Ax(*ci->u.l.savedpc++);\n        }\n        h = hvalue(ra);\n        last = ((c-1)*LFIELDS_PER_FLUSH) + n;\n        if (last > h->sizearray)  /* needs more space? */\n          luaH_resizearray(L, h, last);  /* preallocate it at once */\n        for (; n > 0; n--) {\n          TValue *val = ra+n;\n          luaH_setint(L, h, last--, val);\n          luaC_barrierback(L, h, val);\n        }\n        L->top = ci->top;  /* correct top (in case of previous open call) */\n        vmbreak;\n      }\n      vmcase(OP_CLOSURE) {\n        Proto *p = cl->p->p[GETARG_Bx(i)];\n        LClosure *ncl = getcached(p, cl->upvals, base);  /* cached closure */\n        if (ncl == NULL)  /* no match? */\n          pushclosure(L, p, cl->upvals, base, ra);  /* create a new one */\n        else\n          setclLvalue(L, ra, ncl);  /* push cashed closure */\n        checkGC(L, ra + 1);\n        vmbreak;\n      }\n      vmcase(OP_VARARG) {\n        int b = GETARG_B(i) - 1;  /* required results */\n        int j;\n        int n = cast_int(base - ci->func) - cl->p->numparams - 1;\n        if (n < 0)  /* less arguments than parameters? */\n          n = 0;  /* no vararg arguments */\n        if (b < 0) {  /* B == 0? */\n          b = n;  /* get all var. arguments */\n          Protect(luaD_checkstack(L, n));\n          ra = RA(i);  /* previous call may change the stack */\n          L->top = ra + n;\n        }\n        for (j = 0; j < b && j < n; j++)\n          setobjs2s(L, ra + j, base - n + j);\n        for (; j < b; j++)  /* complete required results with nil */\n          setnilvalue(ra + j);\n        vmbreak;\n      }\n      vmcase(OP_EXTRAARG) {\n        lua_assert(0);\n        vmbreak;\n      }\n    }\n  }\n}\n\n/* }================================================================== */\n\n"
  },
  {
    "path": "src/lua/lvm.h",
    "content": "/*\n** $Id: lvm.h,v 2.41.1.1 2017/04/19 17:20:42 roberto Exp $\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\t0\n#endif\n\n\n#define tonumber(o,n) \\\n\t(ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n))\n\n#define tointeger(o,i) \\\n    (ttisinteger(o) ? (*(i) = ivalue(o), 1) : luaV_tointeger(o,i,LUA_FLOORN2I))\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': if 't' is a table and 't[k]' is not nil,\n** return 1 with 'slot' pointing to 't[k]' (final result).  Otherwise,\n** return 0 (meaning it will have to check metamethod) with 'slot'\n** pointing to a nil 't[k]' (if 't' is a table) or NULL (otherwise).\n** 'f' is the raw get function to use.\n*/\n#define luaV_fastget(L,t,k,slot,f) \\\n  (!ttistable(t)  \\\n   ? (slot = NULL, 0)  /* not a table; 'slot' is NULL and result is 0 */  \\\n   : (slot = f(hvalue(t), k),  /* else, do raw access */  \\\n      !ttisnil(slot)))  /* result not nil? */\n\n/*\n** standard implementation for 'gettable'\n*/\n#define luaV_gettable(L,t,k,v) { const TValue *slot; \\\n  if (luaV_fastget(L,t,k,slot,luaH_get)) { setobj2s(L, v, slot); } \\\n  else luaV_finishget(L,t,k,v,slot); }\n\n\n/*\n** Fast track for set table. If 't' is a table and 't[k]' is not nil,\n** call GC barrier, do a raw 't[k]=v', and return true; otherwise,\n** return false with 'slot' equal to NULL (if 't' is not a table) or\n** 'nil'. (This is needed by 'luaV_finishget'.) Note that, if the macro\n** returns true, there is no need to 'invalidateTMcache', because the\n** call is not creating a new entry.\n*/\n#define luaV_fastset(L,t,k,slot,f,v) \\\n  (!ttistable(t) \\\n   ? (slot = NULL, 0) \\\n   : (slot = f(hvalue(t), k), \\\n     ttisnil(slot) ? 0 \\\n     : (luaC_barrierback(L, hvalue(t), v), \\\n        setobj2t(L, cast(TValue *,slot), v), \\\n        1)))\n\n\n#define luaV_settable(L,t,k,v) { const TValue *slot; \\\n  if (!luaV_fastset(L,t,k,slot,luaH_get,v)) \\\n    luaV_finishset(L,t,k,v,slot); }\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, int mode);\nLUAI_FUNC void luaV_finishget (lua_State *L, const TValue *t, TValue *key,\n                               StkId val, const TValue *slot);\nLUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key,\n                               StkId val, const TValue *slot);\nLUAI_FUNC void luaV_finishOp (lua_State *L);\nLUAI_FUNC void luaV_execute (lua_State *L);\nLUAI_FUNC void luaV_concat (lua_State *L, int total);\nLUAI_FUNC lua_Integer luaV_div (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_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": "src/lua/lzio.c",
    "content": "/*\n** $Id: lzio.c,v 1.37.1.1 2017/04/19 17:20:42 roberto Exp $\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 \"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 --- */\nsize_t luaZ_read (ZIO *z, void *b, size_t n) {\n  while (n) {\n    size_t m;\n    if (z->n == 0) {  /* no bytes in buffer? */\n      if (luaZ_fill(z) == EOZ)  /* try to read more */\n        return n;  /* no more input; return number of missing bytes */\n      else {\n        z->n++;  /* luaZ_fill consumed first byte; put it back */\n        z->p--;\n      }\n    }\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"
  },
  {
    "path": "src/lua/lzio.h",
    "content": "/*\n** $Id: lzio.h,v 1.31.1.1 2017/04/19 17:20:42 roberto Exp $\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 -= (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\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": "src/main.cpp",
    "content": "#include \"views/view_manager.h\"\r\n#include \"views/main_view.h\"\r\n\r\n/*\r\n* D-PAD Left - SDLK_LEFT\r\n* D-PAD Right - SDLK_RIGHT\r\n* D-PAD Up - SDLK_UP\r\n* D-PAD Down - SDLK_DOWN\r\n* Y button - SDLK_SPACE\r\n* X button - SDLK_LSHIFT\r\n* A button - SDLK_LCTRL\r\n* B button - SDLK_LALT\r\n* START button - SDLK_RETURN\r\n* SELECT button - SDLK_ESC\r\n* L shoulder - SDLK_TAB\r\n* R shoulder - SDLK_BACKSPACE\r\n* Power slider in up position - SDLK_POWER (not encouraged to map in game, as it's used by the pwswd daemon)\r\n* Power slider in down position - SDLK_PAUSE\r\n*/\r\n\r\n#if defined(SDL12)\r\n  extern \"C\" { FILE __iob_func[3] = { *stdin,*stdout,*stderr }; }\r\n#endif\r\n\r\n#if TEST_MODE\r\nextern int testMain(int argc, char* argv[]);\r\n#endif\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n#if TEST_MODE\r\n  return testMain(argc, argv);\r\n#endif\r\n\r\n  ui::ViewManager ui;\r\n\r\n  if (!ui.init())\r\n    return -1;\r\n  \r\n  if (!ui.loadData())\r\n  {\r\n    LOGD(\"Error while loading and initializing data.\\n\");\r\n    ui.deinit();\r\n    return -1;\r\n  }\r\n\r\n  if (argc == 2)\r\n    ui.gameView()->loadCartridge(argv[1]);\r\n  \r\n  ui.loop();\r\n  ui.deinit();\r\n\r\n  return 0;\r\n}\r\n"
  },
  {
    "path": "src/test/catch.hpp",
    "content": "/*\n *  Catch v2.11.0\n *  Generated: 2019-11-15 15:01:56.628356\n *  ----------------------------------------------------------\n *  This file has been merged from multiple headers. Please don't edit it directly\n *  Copyright (c) 2019 Two Blue Cubes Ltd. All rights reserved.\n *\n *  Distributed under the Boost Software License, Version 1.0. (See accompanying\n *  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED\n#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED\n// start catch.hpp\n\n\n#define CATCH_VERSION_MAJOR 2\n#define CATCH_VERSION_MINOR 11\n#define CATCH_VERSION_PATCH 0\n\n#ifdef __clang__\n#    pragma clang system_header\n#elif defined __GNUC__\n#    pragma GCC system_header\n#endif\n\n// start catch_suppress_warnings.h\n\n#ifdef __clang__\n#   ifdef __ICC // icpc defines the __clang__ macro\n#       pragma warning(push)\n#       pragma warning(disable: 161 1682)\n#   else // __ICC\n#       pragma clang diagnostic push\n#       pragma clang diagnostic ignored \"-Wpadded\"\n#       pragma clang diagnostic ignored \"-Wswitch-enum\"\n#       pragma clang diagnostic ignored \"-Wcovered-switch-default\"\n#    endif\n#elif defined __GNUC__\n     // Because REQUIREs trigger GCC's -Wparentheses, and because still\n     // supported version of g++ have only buggy support for _Pragmas,\n     // Wparentheses have to be suppressed globally.\n#    pragma GCC diagnostic ignored \"-Wparentheses\" // See #674 for details\n\n#    pragma GCC diagnostic push\n#    pragma GCC diagnostic ignored \"-Wunused-variable\"\n#    pragma GCC diagnostic ignored \"-Wpadded\"\n#endif\n// end catch_suppress_warnings.h\n#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)\n#  define CATCH_IMPL\n#  define CATCH_CONFIG_ALL_PARTS\n#endif\n\n// In the impl file, we want to have access to all parts of the headers\n// Can also be used to sanely support PCHs\n#if defined(CATCH_CONFIG_ALL_PARTS)\n#  define CATCH_CONFIG_EXTERNAL_INTERFACES\n#  if defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#    undef CATCH_CONFIG_DISABLE_MATCHERS\n#  endif\n#  if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)\n#    define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER\n#  endif\n#endif\n\n#if !defined(CATCH_CONFIG_IMPL_ONLY)\n// start catch_platform.h\n\n#ifdef __APPLE__\n# include <TargetConditionals.h>\n# if TARGET_OS_OSX == 1\n#  define CATCH_PLATFORM_MAC\n# elif TARGET_OS_IPHONE == 1\n#  define CATCH_PLATFORM_IPHONE\n# endif\n\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n#  define CATCH_PLATFORM_LINUX\n\n#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)\n#  define CATCH_PLATFORM_WINDOWS\n#endif\n\n// end catch_platform.h\n\n#ifdef CATCH_IMPL\n#  ifndef CLARA_CONFIG_MAIN\n#    define CLARA_CONFIG_MAIN_NOT_DEFINED\n#    define CLARA_CONFIG_MAIN\n#  endif\n#endif\n\n// start catch_user_interfaces.h\n\nnamespace Catch {\n    unsigned int rngSeed();\n}\n\n// end catch_user_interfaces.h\n// start catch_tag_alias_autoregistrar.h\n\n// start catch_common.h\n\n// start catch_compiler_capabilities.h\n\n// Detect a number of compiler features - by compiler\n// The following features are defined:\n//\n// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?\n// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?\n// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?\n// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?\n// ****************\n// Note to maintainers: if new toggles are added please document them\n// in configuration.md, too\n// ****************\n\n// In general each macro has a _NO_<feature name> form\n// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.\n// Many features, at point of detection, define an _INTERNAL_ macro, so they\n// can be combined, en-mass, with the _NO_ forms later.\n\n#ifdef __cplusplus\n\n#  if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)\n#    define CATCH_CPP14_OR_GREATER\n#  endif\n\n#  if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)\n#    define CATCH_CPP17_OR_GREATER\n#  endif\n\n#endif\n\n#if defined(CATCH_CPP17_OR_GREATER)\n#  define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS\n#endif\n\n// We have to avoid both ICC and Clang, because they try to mask themselves\n// as gcc, and we want only GCC in this block\n#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC)\n#    define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( \"GCC diagnostic push\" )\n#    define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION  _Pragma( \"GCC diagnostic pop\" )\n#endif\n\n#if defined(__clang__)\n\n#    define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( \"clang diagnostic push\" )\n#    define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION  _Pragma( \"clang diagnostic pop\" )\n\n#    define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n         _Pragma( \"clang diagnostic ignored \\\"-Wexit-time-destructors\\\"\" ) \\\n         _Pragma( \"clang diagnostic ignored \\\"-Wglobal-constructors\\\"\")\n\n#    define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \\\n         _Pragma( \"clang diagnostic ignored \\\"-Wparentheses\\\"\" )\n\n#    define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \\\n         _Pragma( \"clang diagnostic ignored \\\"-Wunused-variable\\\"\" )\n\n#    define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \\\n         _Pragma( \"clang diagnostic ignored \\\"-Wgnu-zero-variadic-macro-arguments\\\"\" )\n\n#    define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \\\n         _Pragma( \"clang diagnostic ignored \\\"-Wunused-template\\\"\" )\n\n#endif // __clang__\n\n////////////////////////////////////////////////////////////////////////////////\n// Assume that non-Windows platforms support posix signals by default\n#if !defined(CATCH_PLATFORM_WINDOWS)\n    #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n// We know some environments not to support full POSIX signals\n#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)\n    #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS\n#endif\n\n#ifdef __OS400__\n#       define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS\n#       define CATCH_CONFIG_COLOUR_NONE\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n// Android somehow still does not support std::to_string\n#if defined(__ANDROID__)\n#    define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING\n#    define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n// Not all Windows environments support SEH properly\n#if defined(__MINGW32__)\n#    define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n// PS4\n#if defined(__ORBIS__)\n#    define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n// Cygwin\n#ifdef __CYGWIN__\n\n// Required for some versions of Cygwin to declare gettimeofday\n// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin\n#   define _BSD_SOURCE\n// some versions of cygwin (most) do not support std::to_string. Use the libstd check.\n// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813\n# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \\\n           && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))\n\n#    define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING\n\n# endif\n#endif // __CYGWIN__\n\n////////////////////////////////////////////////////////////////////////////////\n// Visual C++\n#if defined(_MSC_VER)\n\n#  define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )\n#  define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION  __pragma( warning(pop) )\n\n#  if _MSC_VER >= 1900 // Visual Studio 2015 or newer\n#    define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS\n#  endif\n\n// Universal Windows platform does not support SEH\n// Or console colours (or console at all...)\n#  if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)\n#    define CATCH_CONFIG_COLOUR_NONE\n#  else\n#    define CATCH_INTERNAL_CONFIG_WINDOWS_SEH\n#  endif\n\n// MSVC traditional preprocessor needs some workaround for __VA_ARGS__\n// _MSVC_TRADITIONAL == 0 means new conformant preprocessor\n// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor\n#  if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)\n#    define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n#  endif\n#endif // _MSC_VER\n\n#if defined(_REENTRANT) || defined(_MSC_VER)\n// Enable async processing, as -pthread is specified or no additional linking is required\n# define CATCH_INTERNAL_CONFIG_USE_ASYNC\n#endif // _MSC_VER\n\n////////////////////////////////////////////////////////////////////////////////\n// Check if we are compiled with -fno-exceptions or equivalent\n#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)\n#  define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n// DJGPP\n#ifdef __DJGPP__\n#  define CATCH_INTERNAL_CONFIG_NO_WCHAR\n#endif // __DJGPP__\n\n////////////////////////////////////////////////////////////////////////////////\n// Embarcadero C++Build\n#if defined(__BORLANDC__)\n    #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n\n// Use of __COUNTER__ is suppressed during code analysis in\n// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly\n// handled by it.\n// Otherwise all supported compilers support COUNTER macro,\n// but user still might want to turn it off\n#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )\n    #define CATCH_INTERNAL_CONFIG_COUNTER\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n\n// RTX is a special version of Windows that is real time.\n// This means that it is detected as Windows, but does not provide\n// the same set of capabilities as real Windows does.\n#if defined(UNDER_RTSS) || defined(RTX64_BUILD)\n    #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH\n    #define CATCH_INTERNAL_CONFIG_NO_ASYNC\n    #define CATCH_CONFIG_COLOUR_NONE\n#endif\n\n#if defined(__UCLIBC__)\n#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER\n#endif\n\n// Various stdlib support checks that require __has_include\n#if defined(__has_include)\n  // Check if string_view is available and usable\n  #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)\n  #    define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW\n  #endif\n\n  // Check if optional is available and usable\n  #  if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)\n  #    define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL\n  #  endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)\n\n  // Check if byte is available and usable\n  #  if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)\n  #    define CATCH_INTERNAL_CONFIG_CPP17_BYTE\n  #  endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)\n\n  // Check if variant is available and usable\n  #  if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)\n  #    if defined(__clang__) && (__clang_major__ < 8)\n         // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852\n         // fix should be in clang 8, workaround in libstdc++ 8.2\n  #      include <ciso646>\n  #      if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)\n  #        define CATCH_CONFIG_NO_CPP17_VARIANT\n  #      else\n  #        define CATCH_INTERNAL_CONFIG_CPP17_VARIANT\n  #      endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)\n  #    else\n  #      define CATCH_INTERNAL_CONFIG_CPP17_VARIANT\n  #    endif // defined(__clang__) && (__clang_major__ < 8)\n  #  endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)\n#endif // defined(__has_include)\n\n#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)\n#   define CATCH_CONFIG_COUNTER\n#endif\n#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)\n#   define CATCH_CONFIG_WINDOWS_SEH\n#endif\n// This is set by default, because we assume that unix compilers are posix-signal-compatible by default.\n#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)\n#   define CATCH_CONFIG_POSIX_SIGNALS\n#endif\n// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.\n#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)\n#   define CATCH_CONFIG_WCHAR\n#endif\n\n#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)\n#    define CATCH_CONFIG_CPP11_TO_STRING\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)\n#  define CATCH_CONFIG_CPP17_OPTIONAL\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)\n#  define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)\n#  define CATCH_CONFIG_CPP17_STRING_VIEW\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)\n#  define CATCH_CONFIG_CPP17_VARIANT\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)\n#  define CATCH_CONFIG_CPP17_BYTE\n#endif\n\n#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)\n#  define CATCH_INTERNAL_CONFIG_NEW_CAPTURE\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)\n#  define CATCH_CONFIG_NEW_CAPTURE\n#endif\n\n#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)\n#  define CATCH_CONFIG_DISABLE_EXCEPTIONS\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)\n#  define CATCH_CONFIG_POLYFILL_ISNAN\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC)  && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)\n#  define CATCH_CONFIG_USE_ASYNC\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)\n#  define CATCH_CONFIG_ANDROID_LOGWRITE\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)\n#  define CATCH_CONFIG_GLOBAL_NEXTAFTER\n#endif\n\n// Even if we do not think the compiler has that warning, we still have\n// to provide a macro that can be used by the code.\n#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)\n#   define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION\n#endif\n#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)\n#   define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION\n#endif\n#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)\n#   define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS\n#endif\n#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)\n#   define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS\n#endif\n#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)\n#   define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS\n#endif\n#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)\n#   define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS\n#endif\n\n#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)\n#   undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS\n#elif defined(__clang__) && (__clang_major__ < 5)\n#   undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS\n#endif\n\n#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)\n#   define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS\n#endif\n\n#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)\n#define CATCH_TRY if ((true))\n#define CATCH_CATCH_ALL if ((false))\n#define CATCH_CATCH_ANON(type) if ((false))\n#else\n#define CATCH_TRY try\n#define CATCH_CATCH_ALL catch (...)\n#define CATCH_CATCH_ANON(type) catch (type)\n#endif\n\n#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)\n#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n#endif\n\n// end catch_compiler_capabilities.h\n#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line\n#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )\n#ifdef CATCH_CONFIG_COUNTER\n#  define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )\n#else\n#  define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )\n#endif\n\n#include <iosfwd>\n#include <string>\n#include <cstdint>\n\n// We need a dummy global operator<< so we can bring it into Catch namespace later\nstruct Catch_global_namespace_dummy {};\nstd::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);\n\nnamespace Catch {\n\n    struct CaseSensitive { enum Choice {\n        Yes,\n        No\n    }; };\n\n    class NonCopyable {\n        NonCopyable( NonCopyable const& )              = delete;\n        NonCopyable( NonCopyable && )                  = delete;\n        NonCopyable& operator = ( NonCopyable const& ) = delete;\n        NonCopyable& operator = ( NonCopyable && )     = delete;\n\n    protected:\n        NonCopyable();\n        virtual ~NonCopyable();\n    };\n\n    struct SourceLineInfo {\n\n        SourceLineInfo() = delete;\n        SourceLineInfo( char const* _file, std::size_t _line ) noexcept\n        :   file( _file ),\n            line( _line )\n        {}\n\n        SourceLineInfo( SourceLineInfo const& other )            = default;\n        SourceLineInfo& operator = ( SourceLineInfo const& )     = default;\n        SourceLineInfo( SourceLineInfo&& )              noexcept = default;\n        SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;\n\n        bool empty() const noexcept { return file[0] == '\\0'; }\n        bool operator == ( SourceLineInfo const& other ) const noexcept;\n        bool operator < ( SourceLineInfo const& other ) const noexcept;\n\n        char const* file;\n        std::size_t line;\n    };\n\n    std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );\n\n    // Bring in operator<< from global namespace into Catch namespace\n    // This is necessary because the overload of operator<< above makes\n    // lookup stop at namespace Catch\n    using ::operator<<;\n\n    // Use this in variadic streaming macros to allow\n    //    >> +StreamEndStop\n    // as well as\n    //    >> stuff +StreamEndStop\n    struct StreamEndStop {\n        std::string operator+() const;\n    };\n    template<typename T>\n    T const& operator + ( T const& value, StreamEndStop ) {\n        return value;\n    }\n}\n\n#define CATCH_INTERNAL_LINEINFO \\\n    ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )\n\n// end catch_common.h\nnamespace Catch {\n\n    struct RegistrarForTagAliases {\n        RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );\n    };\n\n} // end namespace Catch\n\n#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \\\n    CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n    CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n    namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \\\n    CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION\n\n// end catch_tag_alias_autoregistrar.h\n// start catch_test_registry.h\n\n// start catch_interfaces_testcase.h\n\n#include <vector>\n\nnamespace Catch {\n\n    class TestSpec;\n\n    struct ITestInvoker {\n        virtual void invoke () const = 0;\n        virtual ~ITestInvoker();\n    };\n\n    class TestCase;\n    struct IConfig;\n\n    struct ITestCaseRegistry {\n        virtual ~ITestCaseRegistry();\n        virtual std::vector<TestCase> const& getAllTests() const = 0;\n        virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;\n    };\n\n    bool isThrowSafe( TestCase const& testCase, IConfig const& config );\n    bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );\n    std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );\n    std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );\n\n}\n\n// end catch_interfaces_testcase.h\n// start catch_stringref.h\n\n#include <cstddef>\n#include <string>\n#include <iosfwd>\n#include <cassert>\n\nnamespace Catch {\n\n    /// A non-owning string class (similar to the forthcoming std::string_view)\n    /// Note that, because a StringRef may be a substring of another string,\n    /// it may not be null terminated.\n    class StringRef {\n    public:\n        using size_type = std::size_t;\n        using const_iterator = const char*;\n\n    private:\n        static constexpr char const* const s_empty = \"\";\n\n        char const* m_start = s_empty;\n        size_type m_size = 0;\n\n    public: // construction\n        constexpr StringRef() noexcept = default;\n\n        StringRef( char const* rawChars ) noexcept;\n\n        constexpr StringRef( char const* rawChars, size_type size ) noexcept\n        :   m_start( rawChars ),\n            m_size( size )\n        {}\n\n        StringRef( std::string const& stdString ) noexcept\n        :   m_start( stdString.c_str() ),\n            m_size( stdString.size() )\n        {}\n\n        explicit operator std::string() const {\n            return std::string(m_start, m_size);\n        }\n\n    public: // operators\n        auto operator == ( StringRef const& other ) const noexcept -> bool;\n        auto operator != (StringRef const& other) const noexcept -> bool {\n            return !(*this == other);\n        }\n\n        auto operator[] ( size_type index ) const noexcept -> char {\n            assert(index < m_size);\n            return m_start[index];\n        }\n\n    public: // named queries\n        constexpr auto empty() const noexcept -> bool {\n            return m_size == 0;\n        }\n        constexpr auto size() const noexcept -> size_type {\n            return m_size;\n        }\n\n        // Returns the current start pointer. If the StringRef is not\n        // null-terminated, throws std::domain_exception\n        auto c_str() const -> char const*;\n\n    public: // substrings and searches\n        // Returns a substring of [start, start + length).\n        // If start + length > size(), then the substring is [start, size()).\n        // If start > size(), then the substring is empty.\n        auto substr( size_type start, size_type length ) const noexcept -> StringRef;\n\n        // Returns the current start pointer. May not be null-terminated.\n        auto data() const noexcept -> char const*;\n\n        constexpr auto isNullTerminated() const noexcept -> bool {\n            return m_start[m_size] == '\\0';\n        }\n\n    public: // iterators\n        constexpr const_iterator begin() const { return m_start; }\n        constexpr const_iterator end() const { return m_start + m_size; }\n    };\n\n    auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;\n    auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;\n\n    constexpr auto operator \"\" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {\n        return StringRef( rawChars, size );\n    }\n} // namespace Catch\n\nconstexpr auto operator \"\" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {\n    return Catch::StringRef( rawChars, size );\n}\n\n// end catch_stringref.h\n// start catch_preprocessor.hpp\n\n\n#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__\n#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))\n#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))\n#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))\n#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))\n#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))\n\n#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__\n// MSVC needs more evaluations\n#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))\n#define CATCH_RECURSE(...)  CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))\n#else\n#define CATCH_RECURSE(...)  CATCH_RECURSION_LEVEL5(__VA_ARGS__)\n#endif\n\n#define CATCH_REC_END(...)\n#define CATCH_REC_OUT\n\n#define CATCH_EMPTY()\n#define CATCH_DEFER(id) id CATCH_EMPTY()\n\n#define CATCH_REC_GET_END2() 0, CATCH_REC_END\n#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2\n#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1\n#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT\n#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)\n#define CATCH_REC_NEXT(test, next)  CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)\n\n#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )\n#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )\n#define CATCH_REC_LIST2(f, x, peek, ...)   f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )\n\n#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )\n#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )\n#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...)   f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )\n\n// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,\n// and passes userdata as the first parameter to each invocation,\n// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)\n#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))\n\n#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))\n\n#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)\n#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__\n#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__\n#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF\n#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__\n#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))\n#else\n// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF\n#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)\n#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__\n#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)\n#endif\n\n#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__\n#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)\n\n#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())\n#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))\n#else\n#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))\n#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))\n#endif\n\n#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\\\n    CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)\n\n#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)\n#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)\n#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)\n#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)\n#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)\n#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)\n#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _4, _5, _6)\n#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)\n#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)\n#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)\n#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)\n\n#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N\n\n#define INTERNAL_CATCH_TYPE_GEN\\\n    template<typename...> struct TypeList {};\\\n    template<typename...Ts>\\\n    constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\\\n    template<template<typename...> class...> struct TemplateTypeList{};\\\n    template<template<typename...> class...Cs>\\\n    constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\\\n    template<typename...>\\\n    struct append;\\\n    template<typename...>\\\n    struct rewrap;\\\n    template<template<typename...> class, typename...>\\\n    struct create;\\\n    template<template<typename...> class, typename>\\\n    struct convert;\\\n    \\\n    template<typename T> \\\n    struct append<T> { using type = T; };\\\n    template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\\\n    struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\\\n    template< template<typename...> class L1, typename...E1, typename...Rest>\\\n    struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\\\n    \\\n    template< template<typename...> class Container, template<typename...> class List, typename...elems>\\\n    struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\\\n    template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\\\n    struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\\\n    \\\n    template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\\\n    struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\\\n    template<template <typename...> class Final, template <typename...> class List, typename...Ts>\\\n    struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };\n\n#define INTERNAL_CATCH_NTTP_1(signature, ...)\\\n    template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\\\n    template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\\\n    constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \\\n    template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\\\n    template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\\\n    constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \\\n    \\\n    template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\\\n    struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\\\n    template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\\\n    struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\\\n    template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\\\n    struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };\n\n#define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)\n#define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\\\n    template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\\\n    static void TestName()\n#define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\\\n    template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\\\n    static void TestName()\n\n#define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)\n#define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\\\n    template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\\\n    static void TestName()\n#define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\\\n    template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\\\n    static void TestName()\n\n#define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\\\n    template<typename Type>\\\n    void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\\\n    {\\\n        Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\\\n    }\n\n#define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\\\n    template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\\\n    void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\\\n    {\\\n        Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\\\n    }\n\n#define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\\\n    template<typename Type>\\\n    void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\\\n    {\\\n        Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\\\n    }\n\n#define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\\\n    template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\\\n    void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\\\n    {\\\n        Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\\\n    }\n\n#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)\n#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\\\n    template<typename TestType> \\\n    struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \\\n        void test();\\\n    }\n\n#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\\\n    template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \\\n    struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \\\n        void test();\\\n    }\n\n#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)\n#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\\\n    template<typename TestType> \\\n    void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()\n#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\\\n    template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \\\n    void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n#define INTERNAL_CATCH_NTTP_0\n#define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)\n#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)\n#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)\n#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)\n#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)\n#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)\n#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)\n#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)\n#else\n#define INTERNAL_CATCH_NTTP_0(signature)\n#define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))\n#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))\n#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))\n#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))\n#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))\n#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))\n#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \"dummy\", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))\n#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))\n#endif\n\n// end catch_preprocessor.hpp\n// start catch_meta.hpp\n\n\n#include <type_traits>\n\nnamespace Catch {\n    template<typename T>\n    struct always_false : std::false_type {};\n\n    template <typename> struct true_given : std::true_type {};\n    struct is_callable_tester {\n        template <typename Fun, typename... Args>\n        true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);\n        template <typename...>\n        std::false_type static test(...);\n    };\n\n    template <typename T>\n    struct is_callable;\n\n    template <typename Fun, typename... Args>\n    struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};\n\n#if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703\n    // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is\n    // replaced with std::invoke_result here. Also *_t format is preferred over\n    // typename *::type format.\n    template <typename Func, typename U>\n    using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;\n#else\n    template <typename Func, typename U>\n    using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U)>::type>::type>::type;\n#endif\n\n} // namespace Catch\n\nnamespace mpl_{\n    struct na;\n}\n\n// end catch_meta.hpp\nnamespace Catch {\n\ntemplate<typename C>\nclass TestInvokerAsMethod : public ITestInvoker {\n    void (C::*m_testAsMethod)();\npublic:\n    TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}\n\n    void invoke() const override {\n        C obj;\n        (obj.*m_testAsMethod)();\n    }\n};\n\nauto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;\n\ntemplate<typename C>\nauto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {\n    return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );\n}\n\nstruct NameAndTags {\n    NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;\n    StringRef name;\n    StringRef tags;\n};\n\nstruct AutoReg : NonCopyable {\n    AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;\n    ~AutoReg();\n};\n\n} // end namespace Catch\n\n#if defined(CATCH_CONFIG_DISABLE)\n    #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \\\n        static void TestName()\n    #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \\\n        namespace{                        \\\n            struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \\\n                void test();              \\\n            };                            \\\n        }                                 \\\n        void TestName::test()\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... )  \\\n        INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... )    \\\n        namespace{                                                                                  \\\n            namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                      \\\n            INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\\\n        }                                                                                           \\\n        }                                                                                           \\\n        INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\n\n    #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n        #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \\\n            INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )\n    #else\n        #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \\\n            INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )\n    #endif\n\n    #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n        #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \\\n            INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )\n    #else\n        #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \\\n            INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )\n    #endif\n\n    #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n        #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \\\n            INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )\n    #else\n        #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \\\n            INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )\n    #endif\n\n    #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n        #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \\\n            INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )\n    #else\n        #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \\\n            INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )\n    #endif\n#endif\n\n    ///////////////////////////////////////////////////////////////////////////////\n    #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \\\n        static void TestName(); \\\n        CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n        CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n        namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \\\n        CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \\\n        static void TestName()\n    #define INTERNAL_CATCH_TESTCASE( ... ) \\\n        INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )\n\n    ///////////////////////////////////////////////////////////////////////////////\n    #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \\\n        CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n        CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n        namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, \"&\" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \\\n        CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION\n\n    ///////////////////////////////////////////////////////////////////////////////\n    #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\\\n        CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n        CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n        namespace{ \\\n            struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \\\n                void test(); \\\n            }; \\\n            Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \\\n        } \\\n        CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \\\n        void TestName::test()\n    #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \\\n        INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )\n\n    ///////////////////////////////////////////////////////////////////////////////\n    #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \\\n        CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n        CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n        Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \\\n        CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION\n\n    ///////////////////////////////////////////////////////////////////////////////\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\\\n        CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n        CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n        CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \\\n        CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \\\n        INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\\\n        namespace {\\\n        namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\\\n            INTERNAL_CATCH_TYPE_GEN\\\n            INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\\\n            INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\\\n            template<typename...Types> \\\n            struct TestName{\\\n                TestName(){\\\n                    int index = 0;                                    \\\n                    constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\\\n                    using expander = int[];\\\n                    (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name \" - \" + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \\\n                }\\\n            };\\\n            static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\\\n            TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\\\n            return 0;\\\n        }();\\\n        }\\\n        }\\\n        CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \\\n        INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \\\n        INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )\n#else\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \\\n        INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )\n#endif\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \\\n        INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )\n#else\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \\\n        INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )\n#endif\n\n    #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \\\n        CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                      \\\n        CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                      \\\n        CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS                \\\n        CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS              \\\n        template<typename TestType> static void TestFuncName();       \\\n        namespace {\\\n        namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                     \\\n            INTERNAL_CATCH_TYPE_GEN                                                  \\\n            INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))         \\\n            template<typename... Types>                               \\\n            struct TestName {                                         \\\n                void reg_tests() {                                          \\\n                    int index = 0;                                    \\\n                    using expander = int[];                           \\\n                    constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\\\n                    constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\\\n                    constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\\\n                    (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name \" - \" + std::string(tmpl_types[index / num_types]) + \"<\" + std::string(types_list[index % num_types]) + \">\", Tags } ), index++, 0)... };/* NOLINT */\\\n                }                                                     \\\n            };                                                        \\\n            static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \\\n                using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \\\n                TestInit t;                                           \\\n                t.reg_tests();                                        \\\n                return 0;                                             \\\n            }();                                                      \\\n        }                                                             \\\n        }                                                             \\\n        CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                       \\\n        template<typename TestType>                                   \\\n        static void TestFuncName()\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n    #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\\\n        INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__)\n#else\n    #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\\\n        INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) )\n#endif\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n    #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\\\n        INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__)\n#else\n    #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\\\n        INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )\n#endif\n\n    #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\\\n        CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n        CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n        CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \\\n        template<typename TestType> static void TestFunc();       \\\n        namespace {\\\n        namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\\\n        INTERNAL_CATCH_TYPE_GEN\\\n        template<typename... Types>                               \\\n        struct TestName {                                         \\\n            void reg_tests() {                                          \\\n                int index = 0;                                    \\\n                using expander = int[];                           \\\n                (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name \" - \" + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + \" - \" + std::to_string(index), Tags } ), index++, 0)... };/* NOLINT */\\\n            }                                                     \\\n        };\\\n        static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \\\n                using TestInit = typename convert<TestName, TmplList>::type; \\\n                TestInit t;                                           \\\n                t.reg_tests();                                        \\\n                return 0;                                             \\\n            }();                                                      \\\n        }}\\\n        CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                       \\\n        template<typename TestType>                                   \\\n        static void TestFunc()\n\n    #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \\\n        INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList )\n\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \\\n        CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n        CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n        CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \\\n        CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \\\n        namespace {\\\n        namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \\\n            INTERNAL_CATCH_TYPE_GEN\\\n            INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\\\n            INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\\\n            INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\\\n            template<typename...Types> \\\n            struct TestNameClass{\\\n                TestNameClass(){\\\n                    int index = 0;                                    \\\n                    constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\\\n                    using expander = int[];\\\n                    (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name \" - \" + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \\\n                }\\\n            };\\\n            static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\\\n                TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\\\n                return 0;\\\n        }();\\\n        }\\\n        }\\\n        CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \\\n        INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \\\n        INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )\n#else\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \\\n        INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )\n#endif\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \\\n        INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )\n#else\n    #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \\\n        INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )\n#endif\n\n    #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\\\n        CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n        CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n        CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \\\n        CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \\\n        template<typename TestType> \\\n            struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \\\n                void test();\\\n            };\\\n        namespace {\\\n        namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\\\n            INTERNAL_CATCH_TYPE_GEN                  \\\n            INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\\\n            template<typename...Types>\\\n            struct TestNameClass{\\\n                void reg_tests(){\\\n                    int index = 0;\\\n                    using expander = int[];\\\n                    constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\\\n                    constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\\\n                    constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\\\n                    (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name \" - \" + std::string(tmpl_types[index / num_types]) + \"<\" + std::string(types_list[index % num_types]) + \">\", Tags } ), index++, 0)... };/* NOLINT */ \\\n                }\\\n            };\\\n            static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\\\n                using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\\\n                TestInit t;\\\n                t.reg_tests();\\\n                return 0;\\\n            }(); \\\n        }\\\n        }\\\n        CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \\\n        template<typename TestType> \\\n        void TestName<TestType>::test()\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n    #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\\\n        INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )\n#else\n    #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\\\n        INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )\n#endif\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n    #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\\\n        INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )\n#else\n    #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\\\n        INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )\n#endif\n\n    #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \\\n        CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n        CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n        CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \\\n        template<typename TestType> \\\n        struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \\\n            void test();\\\n        };\\\n        namespace {\\\n        namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \\\n            INTERNAL_CATCH_TYPE_GEN\\\n            template<typename...Types>\\\n            struct TestNameClass{\\\n                void reg_tests(){\\\n                    int index = 0;\\\n                    using expander = int[];\\\n                    (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name \" - \" + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + \" - \" + std::to_string(index), Tags } ), index++, 0)... };/* NOLINT */ \\\n                }\\\n            };\\\n            static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\\\n                using TestInit = typename convert<TestNameClass, TmplList>::type;\\\n                TestInit t;\\\n                t.reg_tests();\\\n                return 0;\\\n            }(); \\\n        }}\\\n        CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \\\n        template<typename TestType> \\\n        void TestName<TestType>::test()\n\n#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \\\n        INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList )\n\n// end catch_test_registry.h\n// start catch_capture.hpp\n\n// start catch_assertionhandler.h\n\n// start catch_assertioninfo.h\n\n// start catch_result_type.h\n\nnamespace Catch {\n\n    // ResultWas::OfType enum\n    struct ResultWas { enum OfType {\n        Unknown = -1,\n        Ok = 0,\n        Info = 1,\n        Warning = 2,\n\n        FailureBit = 0x10,\n\n        ExpressionFailed = FailureBit | 1,\n        ExplicitFailure = FailureBit | 2,\n\n        Exception = 0x100 | FailureBit,\n\n        ThrewException = Exception | 1,\n        DidntThrowException = Exception | 2,\n\n        FatalErrorCondition = 0x200 | FailureBit\n\n    }; };\n\n    bool isOk( ResultWas::OfType resultType );\n    bool isJustInfo( int flags );\n\n    // ResultDisposition::Flags enum\n    struct ResultDisposition { enum Flags {\n        Normal = 0x01,\n\n        ContinueOnFailure = 0x02,   // Failures fail test, but execution continues\n        FalseTest = 0x04,           // Prefix expression with !\n        SuppressFail = 0x08         // Failures are reported but do not fail the test\n    }; };\n\n    ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );\n\n    bool shouldContinueOnFailure( int flags );\n    inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }\n    bool shouldSuppressFailure( int flags );\n\n} // end namespace Catch\n\n// end catch_result_type.h\nnamespace Catch {\n\n    struct AssertionInfo\n    {\n        StringRef macroName;\n        SourceLineInfo lineInfo;\n        StringRef capturedExpression;\n        ResultDisposition::Flags resultDisposition;\n\n        // We want to delete this constructor but a compiler bug in 4.8 means\n        // the struct is then treated as non-aggregate\n        //AssertionInfo() = delete;\n    };\n\n} // end namespace Catch\n\n// end catch_assertioninfo.h\n// start catch_decomposer.h\n\n// start catch_tostring.h\n\n#include <vector>\n#include <cstddef>\n#include <type_traits>\n#include <string>\n// start catch_stream.h\n\n#include <iosfwd>\n#include <cstddef>\n#include <ostream>\n\nnamespace Catch {\n\n    std::ostream& cout();\n    std::ostream& cerr();\n    std::ostream& clog();\n\n    class StringRef;\n\n    struct IStream {\n        virtual ~IStream();\n        virtual std::ostream& stream() const = 0;\n    };\n\n    auto makeStream( StringRef const &filename ) -> IStream const*;\n\n    class ReusableStringStream : NonCopyable {\n        std::size_t m_index;\n        std::ostream* m_oss;\n    public:\n        ReusableStringStream();\n        ~ReusableStringStream();\n\n        auto str() const -> std::string;\n\n        template<typename T>\n        auto operator << ( T const& value ) -> ReusableStringStream& {\n            *m_oss << value;\n            return *this;\n        }\n        auto get() -> std::ostream& { return *m_oss; }\n    };\n}\n\n// end catch_stream.h\n// start catch_interfaces_enum_values_registry.h\n\n#include <vector>\n\nnamespace Catch {\n\n    namespace Detail {\n        struct EnumInfo {\n            StringRef m_name;\n            std::vector<std::pair<int, StringRef>> m_values;\n\n            ~EnumInfo();\n\n            StringRef lookup( int value ) const;\n        };\n    } // namespace Detail\n\n    struct IMutableEnumValuesRegistry {\n        virtual ~IMutableEnumValuesRegistry();\n\n        virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;\n\n        template<typename E>\n        Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {\n            static_assert(sizeof(int) >= sizeof(E), \"Cannot serialize enum to int\");\n            std::vector<int> intValues;\n            intValues.reserve( values.size() );\n            for( auto enumValue : values )\n                intValues.push_back( static_cast<int>( enumValue ) );\n            return registerEnum( enumName, allEnums, intValues );\n        }\n    };\n\n} // Catch\n\n// end catch_interfaces_enum_values_registry.h\n\n#ifdef CATCH_CONFIG_CPP17_STRING_VIEW\n#include <string_view>\n#endif\n\n#ifdef __OBJC__\n// start catch_objc_arc.hpp\n\n#import <Foundation/Foundation.h>\n\n#ifdef __has_feature\n#define CATCH_ARC_ENABLED __has_feature(objc_arc)\n#else\n#define CATCH_ARC_ENABLED 0\n#endif\n\nvoid arcSafeRelease( NSObject* obj );\nid performOptionalSelector( id obj, SEL sel );\n\n#if !CATCH_ARC_ENABLED\ninline void arcSafeRelease( NSObject* obj ) {\n    [obj release];\n}\ninline id performOptionalSelector( id obj, SEL sel ) {\n    if( [obj respondsToSelector: sel] )\n        return [obj performSelector: sel];\n    return nil;\n}\n#define CATCH_UNSAFE_UNRETAINED\n#define CATCH_ARC_STRONG\n#else\ninline void arcSafeRelease( NSObject* ){}\ninline id performOptionalSelector( id obj, SEL sel ) {\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Warc-performSelector-leaks\"\n#endif\n    if( [obj respondsToSelector: sel] )\n        return [obj performSelector: sel];\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n    return nil;\n}\n#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained\n#define CATCH_ARC_STRONG __strong\n#endif\n\n// end catch_objc_arc.hpp\n#endif\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless\n#endif\n\nnamespace Catch {\n    namespace Detail {\n\n        extern const std::string unprintableString;\n\n        std::string rawMemoryToString( const void *object, std::size_t size );\n\n        template<typename T>\n        std::string rawMemoryToString( const T& object ) {\n          return rawMemoryToString( &object, sizeof(object) );\n        }\n\n        template<typename T>\n        class IsStreamInsertable {\n            template<typename Stream, typename U>\n            static auto test(int)\n                -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());\n\n            template<typename, typename>\n            static auto test(...)->std::false_type;\n\n        public:\n            static const bool value = decltype(test<std::ostream, const T&>(0))::value;\n        };\n\n        template<typename E>\n        std::string convertUnknownEnumToString( E e );\n\n        template<typename T>\n        typename std::enable_if<\n            !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,\n        std::string>::type convertUnstreamable( T const& ) {\n            return Detail::unprintableString;\n        }\n        template<typename T>\n        typename std::enable_if<\n            !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,\n         std::string>::type convertUnstreamable(T const& ex) {\n            return ex.what();\n        }\n\n        template<typename T>\n        typename std::enable_if<\n            std::is_enum<T>::value\n        , std::string>::type convertUnstreamable( T const& value ) {\n            return convertUnknownEnumToString( value );\n        }\n\n#if defined(_MANAGED)\n        //! Convert a CLR string to a utf8 std::string\n        template<typename T>\n        std::string clrReferenceToString( T^ ref ) {\n            if (ref == nullptr)\n                return std::string(\"null\");\n            auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());\n            cli::pin_ptr<System::Byte> p = &bytes[0];\n            return std::string(reinterpret_cast<char const *>(p), bytes->Length);\n        }\n#endif\n\n    } // namespace Detail\n\n    // If we decide for C++14, change these to enable_if_ts\n    template <typename T, typename = void>\n    struct StringMaker {\n        template <typename Fake = T>\n        static\n        typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type\n            convert(const Fake& value) {\n                ReusableStringStream rss;\n                // NB: call using the function-like syntax to avoid ambiguity with\n                // user-defined templated operator<< under clang.\n                rss.operator<<(value);\n                return rss.str();\n        }\n\n        template <typename Fake = T>\n        static\n        typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type\n            convert( const Fake& value ) {\n#if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)\n            return Detail::convertUnstreamable(value);\n#else\n            return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);\n#endif\n        }\n    };\n\n    namespace Detail {\n\n        // This function dispatches all stringification requests inside of Catch.\n        // Should be preferably called fully qualified, like ::Catch::Detail::stringify\n        template <typename T>\n        std::string stringify(const T& e) {\n            return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);\n        }\n\n        template<typename E>\n        std::string convertUnknownEnumToString( E e ) {\n            return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));\n        }\n\n#if defined(_MANAGED)\n        template <typename T>\n        std::string stringify( T^ e ) {\n            return ::Catch::StringMaker<T^>::convert(e);\n        }\n#endif\n\n    } // namespace Detail\n\n    // Some predefined specializations\n\n    template<>\n    struct StringMaker<std::string> {\n        static std::string convert(const std::string& str);\n    };\n\n#ifdef CATCH_CONFIG_CPP17_STRING_VIEW\n    template<>\n    struct StringMaker<std::string_view> {\n        static std::string convert(std::string_view str);\n    };\n#endif\n\n    template<>\n    struct StringMaker<char const *> {\n        static std::string convert(char const * str);\n    };\n    template<>\n    struct StringMaker<char *> {\n        static std::string convert(char * str);\n    };\n\n#ifdef CATCH_CONFIG_WCHAR\n    template<>\n    struct StringMaker<std::wstring> {\n        static std::string convert(const std::wstring& wstr);\n    };\n\n# ifdef CATCH_CONFIG_CPP17_STRING_VIEW\n    template<>\n    struct StringMaker<std::wstring_view> {\n        static std::string convert(std::wstring_view str);\n    };\n# endif\n\n    template<>\n    struct StringMaker<wchar_t const *> {\n        static std::string convert(wchar_t const * str);\n    };\n    template<>\n    struct StringMaker<wchar_t *> {\n        static std::string convert(wchar_t * str);\n    };\n#endif\n\n    // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,\n    //      while keeping string semantics?\n    template<int SZ>\n    struct StringMaker<char[SZ]> {\n        static std::string convert(char const* str) {\n            return ::Catch::Detail::stringify(std::string{ str });\n        }\n    };\n    template<int SZ>\n    struct StringMaker<signed char[SZ]> {\n        static std::string convert(signed char const* str) {\n            return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });\n        }\n    };\n    template<int SZ>\n    struct StringMaker<unsigned char[SZ]> {\n        static std::string convert(unsigned char const* str) {\n            return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });\n        }\n    };\n\n#if defined(CATCH_CONFIG_CPP17_BYTE)\n    template<>\n    struct StringMaker<std::byte> {\n        static std::string convert(std::byte value);\n    };\n#endif // defined(CATCH_CONFIG_CPP17_BYTE)\n    template<>\n    struct StringMaker<int> {\n        static std::string convert(int value);\n    };\n    template<>\n    struct StringMaker<long> {\n        static std::string convert(long value);\n    };\n    template<>\n    struct StringMaker<long long> {\n        static std::string convert(long long value);\n    };\n    template<>\n    struct StringMaker<unsigned int> {\n        static std::string convert(unsigned int value);\n    };\n    template<>\n    struct StringMaker<unsigned long> {\n        static std::string convert(unsigned long value);\n    };\n    template<>\n    struct StringMaker<unsigned long long> {\n        static std::string convert(unsigned long long value);\n    };\n\n    template<>\n    struct StringMaker<bool> {\n        static std::string convert(bool b);\n    };\n\n    template<>\n    struct StringMaker<char> {\n        static std::string convert(char c);\n    };\n    template<>\n    struct StringMaker<signed char> {\n        static std::string convert(signed char c);\n    };\n    template<>\n    struct StringMaker<unsigned char> {\n        static std::string convert(unsigned char c);\n    };\n\n    template<>\n    struct StringMaker<std::nullptr_t> {\n        static std::string convert(std::nullptr_t);\n    };\n\n    template<>\n    struct StringMaker<float> {\n        static std::string convert(float value);\n        static int precision;\n    };\n\n    template<>\n    struct StringMaker<double> {\n        static std::string convert(double value);\n        static int precision;\n    };\n\n    template <typename T>\n    struct StringMaker<T*> {\n        template <typename U>\n        static std::string convert(U* p) {\n            if (p) {\n                return ::Catch::Detail::rawMemoryToString(p);\n            } else {\n                return \"nullptr\";\n            }\n        }\n    };\n\n    template <typename R, typename C>\n    struct StringMaker<R C::*> {\n        static std::string convert(R C::* p) {\n            if (p) {\n                return ::Catch::Detail::rawMemoryToString(p);\n            } else {\n                return \"nullptr\";\n            }\n        }\n    };\n\n#if defined(_MANAGED)\n    template <typename T>\n    struct StringMaker<T^> {\n        static std::string convert( T^ ref ) {\n            return ::Catch::Detail::clrReferenceToString(ref);\n        }\n    };\n#endif\n\n    namespace Detail {\n        template<typename InputIterator>\n        std::string rangeToString(InputIterator first, InputIterator last) {\n            ReusableStringStream rss;\n            rss << \"{ \";\n            if (first != last) {\n                rss << ::Catch::Detail::stringify(*first);\n                for (++first; first != last; ++first)\n                    rss << \", \" << ::Catch::Detail::stringify(*first);\n            }\n            rss << \" }\";\n            return rss.str();\n        }\n    }\n\n#ifdef __OBJC__\n    template<>\n    struct StringMaker<NSString*> {\n        static std::string convert(NSString * nsstring) {\n            if (!nsstring)\n                return \"nil\";\n            return std::string(\"@\") + [nsstring UTF8String];\n        }\n    };\n    template<>\n    struct StringMaker<NSObject*> {\n        static std::string convert(NSObject* nsObject) {\n            return ::Catch::Detail::stringify([nsObject description]);\n        }\n\n    };\n    namespace Detail {\n        inline std::string stringify( NSString* nsstring ) {\n            return StringMaker<NSString*>::convert( nsstring );\n        }\n\n    } // namespace Detail\n#endif // __OBJC__\n\n} // namespace Catch\n\n//////////////////////////////////////////////////////\n// Separate std-lib types stringification, so it can be selectively enabled\n// This means that we do not bring in\n\n#if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)\n#  define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER\n#  define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER\n#  define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER\n#  define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER\n#  define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER\n#endif\n\n// Separate std::pair specialization\n#if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)\n#include <utility>\nnamespace Catch {\n    template<typename T1, typename T2>\n    struct StringMaker<std::pair<T1, T2> > {\n        static std::string convert(const std::pair<T1, T2>& pair) {\n            ReusableStringStream rss;\n            rss << \"{ \"\n                << ::Catch::Detail::stringify(pair.first)\n                << \", \"\n                << ::Catch::Detail::stringify(pair.second)\n                << \" }\";\n            return rss.str();\n        }\n    };\n}\n#endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER\n\n#if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)\n#include <optional>\nnamespace Catch {\n    template<typename T>\n    struct StringMaker<std::optional<T> > {\n        static std::string convert(const std::optional<T>& optional) {\n            ReusableStringStream rss;\n            if (optional.has_value()) {\n                rss << ::Catch::Detail::stringify(*optional);\n            } else {\n                rss << \"{ }\";\n            }\n            return rss.str();\n        }\n    };\n}\n#endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER\n\n// Separate std::tuple specialization\n#if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)\n#include <tuple>\nnamespace Catch {\n    namespace Detail {\n        template<\n            typename Tuple,\n            std::size_t N = 0,\n            bool = (N < std::tuple_size<Tuple>::value)\n            >\n            struct TupleElementPrinter {\n            static void print(const Tuple& tuple, std::ostream& os) {\n                os << (N ? \", \" : \" \")\n                    << ::Catch::Detail::stringify(std::get<N>(tuple));\n                TupleElementPrinter<Tuple, N + 1>::print(tuple, os);\n            }\n        };\n\n        template<\n            typename Tuple,\n            std::size_t N\n        >\n            struct TupleElementPrinter<Tuple, N, false> {\n            static void print(const Tuple&, std::ostream&) {}\n        };\n\n    }\n\n    template<typename ...Types>\n    struct StringMaker<std::tuple<Types...>> {\n        static std::string convert(const std::tuple<Types...>& tuple) {\n            ReusableStringStream rss;\n            rss << '{';\n            Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());\n            rss << \" }\";\n            return rss.str();\n        }\n    };\n}\n#endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER\n\n#if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)\n#include <variant>\nnamespace Catch {\n    template<>\n    struct StringMaker<std::monostate> {\n        static std::string convert(const std::monostate&) {\n            return \"{ }\";\n        }\n    };\n\n    template<typename... Elements>\n    struct StringMaker<std::variant<Elements...>> {\n        static std::string convert(const std::variant<Elements...>& variant) {\n            if (variant.valueless_by_exception()) {\n                return \"{valueless variant}\";\n            } else {\n                return std::visit(\n                    [](const auto& value) {\n                        return ::Catch::Detail::stringify(value);\n                    },\n                    variant\n                );\n            }\n        }\n    };\n}\n#endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER\n\nnamespace Catch {\n    struct not_this_one {}; // Tag type for detecting which begin/ end are being selected\n\n    // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace\n    using std::begin;\n    using std::end;\n\n    not_this_one begin( ... );\n    not_this_one end( ... );\n\n    template <typename T>\n    struct is_range {\n        static const bool value =\n            !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&\n            !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;\n    };\n\n#if defined(_MANAGED) // Managed types are never ranges\n    template <typename T>\n    struct is_range<T^> {\n        static const bool value = false;\n    };\n#endif\n\n    template<typename Range>\n    std::string rangeToString( Range const& range ) {\n        return ::Catch::Detail::rangeToString( begin( range ), end( range ) );\n    }\n\n    // Handle vector<bool> specially\n    template<typename Allocator>\n    std::string rangeToString( std::vector<bool, Allocator> const& v ) {\n        ReusableStringStream rss;\n        rss << \"{ \";\n        bool first = true;\n        for( bool b : v ) {\n            if( first )\n                first = false;\n            else\n                rss << \", \";\n            rss << ::Catch::Detail::stringify( b );\n        }\n        rss << \" }\";\n        return rss.str();\n    }\n\n    template<typename R>\n    struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {\n        static std::string convert( R const& range ) {\n            return rangeToString( range );\n        }\n    };\n\n    template <typename T, int SZ>\n    struct StringMaker<T[SZ]> {\n        static std::string convert(T const(&arr)[SZ]) {\n            return rangeToString(arr);\n        }\n    };\n\n} // namespace Catch\n\n// Separate std::chrono::duration specialization\n#if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)\n#include <ctime>\n#include <ratio>\n#include <chrono>\n\nnamespace Catch {\n\ntemplate <class Ratio>\nstruct ratio_string {\n    static std::string symbol();\n};\n\ntemplate <class Ratio>\nstd::string ratio_string<Ratio>::symbol() {\n    Catch::ReusableStringStream rss;\n    rss << '[' << Ratio::num << '/'\n        << Ratio::den << ']';\n    return rss.str();\n}\ntemplate <>\nstruct ratio_string<std::atto> {\n    static std::string symbol();\n};\ntemplate <>\nstruct ratio_string<std::femto> {\n    static std::string symbol();\n};\ntemplate <>\nstruct ratio_string<std::pico> {\n    static std::string symbol();\n};\ntemplate <>\nstruct ratio_string<std::nano> {\n    static std::string symbol();\n};\ntemplate <>\nstruct ratio_string<std::micro> {\n    static std::string symbol();\n};\ntemplate <>\nstruct ratio_string<std::milli> {\n    static std::string symbol();\n};\n\n    ////////////\n    // std::chrono::duration specializations\n    template<typename Value, typename Ratio>\n    struct StringMaker<std::chrono::duration<Value, Ratio>> {\n        static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {\n            ReusableStringStream rss;\n            rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';\n            return rss.str();\n        }\n    };\n    template<typename Value>\n    struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {\n        static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {\n            ReusableStringStream rss;\n            rss << duration.count() << \" s\";\n            return rss.str();\n        }\n    };\n    template<typename Value>\n    struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {\n        static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {\n            ReusableStringStream rss;\n            rss << duration.count() << \" m\";\n            return rss.str();\n        }\n    };\n    template<typename Value>\n    struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {\n        static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {\n            ReusableStringStream rss;\n            rss << duration.count() << \" h\";\n            return rss.str();\n        }\n    };\n\n    ////////////\n    // std::chrono::time_point specialization\n    // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>\n    template<typename Clock, typename Duration>\n    struct StringMaker<std::chrono::time_point<Clock, Duration>> {\n        static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {\n            return ::Catch::Detail::stringify(time_point.time_since_epoch()) + \" since epoch\";\n        }\n    };\n    // std::chrono::time_point<system_clock> specialization\n    template<typename Duration>\n    struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {\n        static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {\n            auto converted = std::chrono::system_clock::to_time_t(time_point);\n\n#ifdef _MSC_VER\n            std::tm timeInfo = {};\n            gmtime_s(&timeInfo, &converted);\n#else\n            std::tm* timeInfo = std::gmtime(&converted);\n#endif\n\n            auto const timeStampSize = sizeof(\"2017-01-16T17:06:45Z\");\n            char timeStamp[timeStampSize];\n            const char * const fmt = \"%Y-%m-%dT%H:%M:%SZ\";\n\n#ifdef _MSC_VER\n            std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);\n#else\n            std::strftime(timeStamp, timeStampSize, fmt, timeInfo);\n#endif\n            return std::string(timeStamp);\n        }\n    };\n}\n#endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER\n\n#define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \\\nnamespace Catch { \\\n    template<> struct StringMaker<enumName> { \\\n        static std::string convert( enumName value ) { \\\n            static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \\\n            return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \\\n        } \\\n    }; \\\n}\n\n#define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n// end catch_tostring.h\n#include <iosfwd>\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4389) // '==' : signed/unsigned mismatch\n#pragma warning(disable:4018) // more \"signed/unsigned mismatch\"\n#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)\n#pragma warning(disable:4180) // qualifier applied to function type has no meaning\n#pragma warning(disable:4800) // Forcing result to true or false\n#endif\n\nnamespace Catch {\n\n    struct ITransientExpression {\n        auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }\n        auto getResult() const -> bool { return m_result; }\n        virtual void streamReconstructedExpression( std::ostream &os ) const = 0;\n\n        ITransientExpression( bool isBinaryExpression, bool result )\n        :   m_isBinaryExpression( isBinaryExpression ),\n            m_result( result )\n        {}\n\n        // We don't actually need a virtual destructor, but many static analysers\n        // complain if it's not here :-(\n        virtual ~ITransientExpression();\n\n        bool m_isBinaryExpression;\n        bool m_result;\n\n    };\n\n    void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );\n\n    template<typename LhsT, typename RhsT>\n    class BinaryExpr  : public ITransientExpression {\n        LhsT m_lhs;\n        StringRef m_op;\n        RhsT m_rhs;\n\n        void streamReconstructedExpression( std::ostream &os ) const override {\n            formatReconstructedExpression\n                    ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );\n        }\n\n    public:\n        BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )\n        :   ITransientExpression{ true, comparisonResult },\n            m_lhs( lhs ),\n            m_op( op ),\n            m_rhs( rhs )\n        {}\n\n        template<typename T>\n        auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {\n            static_assert(always_false<T>::value,\n            \"chained comparisons are not supported inside assertions, \"\n            \"wrap the expression inside parentheses, or decompose it\");\n        }\n\n        template<typename T>\n        auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {\n            static_assert(always_false<T>::value,\n            \"chained comparisons are not supported inside assertions, \"\n            \"wrap the expression inside parentheses, or decompose it\");\n        }\n\n        template<typename T>\n        auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {\n            static_assert(always_false<T>::value,\n            \"chained comparisons are not supported inside assertions, \"\n            \"wrap the expression inside parentheses, or decompose it\");\n        }\n\n        template<typename T>\n        auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {\n            static_assert(always_false<T>::value,\n            \"chained comparisons are not supported inside assertions, \"\n            \"wrap the expression inside parentheses, or decompose it\");\n        }\n\n        template<typename T>\n        auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {\n            static_assert(always_false<T>::value,\n            \"chained comparisons are not supported inside assertions, \"\n            \"wrap the expression inside parentheses, or decompose it\");\n        }\n\n        template<typename T>\n        auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {\n            static_assert(always_false<T>::value,\n            \"chained comparisons are not supported inside assertions, \"\n            \"wrap the expression inside parentheses, or decompose it\");\n        }\n\n        template<typename T>\n        auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {\n            static_assert(always_false<T>::value,\n            \"chained comparisons are not supported inside assertions, \"\n            \"wrap the expression inside parentheses, or decompose it\");\n        }\n\n        template<typename T>\n        auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {\n            static_assert(always_false<T>::value,\n            \"chained comparisons are not supported inside assertions, \"\n            \"wrap the expression inside parentheses, or decompose it\");\n        }\n    };\n\n    template<typename LhsT>\n    class UnaryExpr : public ITransientExpression {\n        LhsT m_lhs;\n\n        void streamReconstructedExpression( std::ostream &os ) const override {\n            os << Catch::Detail::stringify( m_lhs );\n        }\n\n    public:\n        explicit UnaryExpr( LhsT lhs )\n        :   ITransientExpression{ false, static_cast<bool>(lhs) },\n            m_lhs( lhs )\n        {}\n    };\n\n    // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)\n    template<typename LhsT, typename RhsT>\n    auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }\n    template<typename T>\n    auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }\n    template<typename T>\n    auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }\n    template<typename T>\n    auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }\n    template<typename T>\n    auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }\n\n    template<typename LhsT, typename RhsT>\n    auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }\n    template<typename T>\n    auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }\n    template<typename T>\n    auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }\n    template<typename T>\n    auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }\n    template<typename T>\n    auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }\n\n    template<typename LhsT>\n    class ExprLhs {\n        LhsT m_lhs;\n    public:\n        explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}\n\n        template<typename RhsT>\n        auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {\n            return { compareEqual( m_lhs, rhs ), m_lhs, \"==\", rhs };\n        }\n        auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {\n            return { m_lhs == rhs, m_lhs, \"==\", rhs };\n        }\n\n        template<typename RhsT>\n        auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {\n            return { compareNotEqual( m_lhs, rhs ), m_lhs, \"!=\", rhs };\n        }\n        auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {\n            return { m_lhs != rhs, m_lhs, \"!=\", rhs };\n        }\n\n        template<typename RhsT>\n        auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {\n            return { static_cast<bool>(m_lhs > rhs), m_lhs, \">\", rhs };\n        }\n        template<typename RhsT>\n        auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {\n            return { static_cast<bool>(m_lhs < rhs), m_lhs, \"<\", rhs };\n        }\n        template<typename RhsT>\n        auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {\n            return { static_cast<bool>(m_lhs >= rhs), m_lhs, \">=\", rhs };\n        }\n        template<typename RhsT>\n        auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {\n            return { static_cast<bool>(m_lhs <= rhs), m_lhs, \"<=\", rhs };\n        }\n\n        template<typename RhsT>\n        auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {\n            static_assert(always_false<RhsT>::value,\n            \"operator&& is not supported inside assertions, \"\n            \"wrap the expression inside parentheses, or decompose it\");\n        }\n\n        template<typename RhsT>\n        auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {\n            static_assert(always_false<RhsT>::value,\n            \"operator|| is not supported inside assertions, \"\n            \"wrap the expression inside parentheses, or decompose it\");\n        }\n\n        auto makeUnaryExpr() const -> UnaryExpr<LhsT> {\n            return UnaryExpr<LhsT>{ m_lhs };\n        }\n    };\n\n    void handleExpression( ITransientExpression const& expr );\n\n    template<typename T>\n    void handleExpression( ExprLhs<T> const& expr ) {\n        handleExpression( expr.makeUnaryExpr() );\n    }\n\n    struct Decomposer {\n        template<typename T>\n        auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {\n            return ExprLhs<T const&>{ lhs };\n        }\n\n        auto operator <=( bool value ) -> ExprLhs<bool> {\n            return ExprLhs<bool>{ value };\n        }\n    };\n\n} // end namespace Catch\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n// end catch_decomposer.h\n// start catch_interfaces_capture.h\n\n#include <string>\n#include <chrono>\n\nnamespace Catch {\n\n    class AssertionResult;\n    struct AssertionInfo;\n    struct SectionInfo;\n    struct SectionEndInfo;\n    struct MessageInfo;\n    struct MessageBuilder;\n    struct Counts;\n    struct AssertionReaction;\n    struct SourceLineInfo;\n\n    struct ITransientExpression;\n    struct IGeneratorTracker;\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n    struct BenchmarkInfo;\n    template <typename Duration = std::chrono::duration<double, std::nano>>\n    struct BenchmarkStats;\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n    struct IResultCapture {\n\n        virtual ~IResultCapture();\n\n        virtual bool sectionStarted(    SectionInfo const& sectionInfo,\n                                        Counts& assertions ) = 0;\n        virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;\n        virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;\n\n        virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n        virtual void benchmarkPreparing( std::string const& name ) = 0;\n        virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;\n        virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;\n        virtual void benchmarkFailed( std::string const& error ) = 0;\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n        virtual void pushScopedMessage( MessageInfo const& message ) = 0;\n        virtual void popScopedMessage( MessageInfo const& message ) = 0;\n\n        virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;\n\n        virtual void handleFatalErrorCondition( StringRef message ) = 0;\n\n        virtual void handleExpr\n                (   AssertionInfo const& info,\n                    ITransientExpression const& expr,\n                    AssertionReaction& reaction ) = 0;\n        virtual void handleMessage\n                (   AssertionInfo const& info,\n                    ResultWas::OfType resultType,\n                    StringRef const& message,\n                    AssertionReaction& reaction ) = 0;\n        virtual void handleUnexpectedExceptionNotThrown\n                (   AssertionInfo const& info,\n                    AssertionReaction& reaction ) = 0;\n        virtual void handleUnexpectedInflightException\n                (   AssertionInfo const& info,\n                    std::string const& message,\n                    AssertionReaction& reaction ) = 0;\n        virtual void handleIncomplete\n                (   AssertionInfo const& info ) = 0;\n        virtual void handleNonExpr\n                (   AssertionInfo const &info,\n                    ResultWas::OfType resultType,\n                    AssertionReaction &reaction ) = 0;\n\n        virtual bool lastAssertionPassed() = 0;\n        virtual void assertionPassed() = 0;\n\n        // Deprecated, do not use:\n        virtual std::string getCurrentTestName() const = 0;\n        virtual const AssertionResult* getLastResult() const = 0;\n        virtual void exceptionEarlyReported() = 0;\n    };\n\n    IResultCapture& getResultCapture();\n}\n\n// end catch_interfaces_capture.h\nnamespace Catch {\n\n    struct TestFailureException{};\n    struct AssertionResultData;\n    struct IResultCapture;\n    class RunContext;\n\n    class LazyExpression {\n        friend class AssertionHandler;\n        friend struct AssertionStats;\n        friend class RunContext;\n\n        ITransientExpression const* m_transientExpression = nullptr;\n        bool m_isNegated;\n    public:\n        LazyExpression( bool isNegated );\n        LazyExpression( LazyExpression const& other );\n        LazyExpression& operator = ( LazyExpression const& ) = delete;\n\n        explicit operator bool() const;\n\n        friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;\n    };\n\n    struct AssertionReaction {\n        bool shouldDebugBreak = false;\n        bool shouldThrow = false;\n    };\n\n    class AssertionHandler {\n        AssertionInfo m_assertionInfo;\n        AssertionReaction m_reaction;\n        bool m_completed = false;\n        IResultCapture& m_resultCapture;\n\n    public:\n        AssertionHandler\n            (   StringRef const& macroName,\n                SourceLineInfo const& lineInfo,\n                StringRef capturedExpression,\n                ResultDisposition::Flags resultDisposition );\n        ~AssertionHandler() {\n            if ( !m_completed ) {\n                m_resultCapture.handleIncomplete( m_assertionInfo );\n            }\n        }\n\n        template<typename T>\n        void handleExpr( ExprLhs<T> const& expr ) {\n            handleExpr( expr.makeUnaryExpr() );\n        }\n        void handleExpr( ITransientExpression const& expr );\n\n        void handleMessage(ResultWas::OfType resultType, StringRef const& message);\n\n        void handleExceptionThrownAsExpected();\n        void handleUnexpectedExceptionNotThrown();\n        void handleExceptionNotThrownAsExpected();\n        void handleThrowingCallSkipped();\n        void handleUnexpectedInflightException();\n\n        void complete();\n        void setCompleted();\n\n        // query\n        auto allowThrows() const -> bool;\n    };\n\n    void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );\n\n} // namespace Catch\n\n// end catch_assertionhandler.h\n// start catch_message.h\n\n#include <string>\n#include <vector>\n\nnamespace Catch {\n\n    struct MessageInfo {\n        MessageInfo(    StringRef const& _macroName,\n                        SourceLineInfo const& _lineInfo,\n                        ResultWas::OfType _type );\n\n        StringRef macroName;\n        std::string message;\n        SourceLineInfo lineInfo;\n        ResultWas::OfType type;\n        unsigned int sequence;\n\n        bool operator == ( MessageInfo const& other ) const;\n        bool operator < ( MessageInfo const& other ) const;\n    private:\n        static unsigned int globalCount;\n    };\n\n    struct MessageStream {\n\n        template<typename T>\n        MessageStream& operator << ( T const& value ) {\n            m_stream << value;\n            return *this;\n        }\n\n        ReusableStringStream m_stream;\n    };\n\n    struct MessageBuilder : MessageStream {\n        MessageBuilder( StringRef const& macroName,\n                        SourceLineInfo const& lineInfo,\n                        ResultWas::OfType type );\n\n        template<typename T>\n        MessageBuilder& operator << ( T const& value ) {\n            m_stream << value;\n            return *this;\n        }\n\n        MessageInfo m_info;\n    };\n\n    class ScopedMessage {\n    public:\n        explicit ScopedMessage( MessageBuilder const& builder );\n        ScopedMessage( ScopedMessage& duplicate ) = delete;\n        ScopedMessage( ScopedMessage&& old );\n        ~ScopedMessage();\n\n        MessageInfo m_info;\n        bool m_moved;\n    };\n\n    class Capturer {\n        std::vector<MessageInfo> m_messages;\n        IResultCapture& m_resultCapture = getResultCapture();\n        size_t m_captured = 0;\n    public:\n        Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );\n        ~Capturer();\n\n        void captureValue( size_t index, std::string const& value );\n\n        template<typename T>\n        void captureValues( size_t index, T const& value ) {\n            captureValue( index, Catch::Detail::stringify( value ) );\n        }\n\n        template<typename T, typename... Ts>\n        void captureValues( size_t index, T const& value, Ts const&... values ) {\n            captureValue( index, Catch::Detail::stringify(value) );\n            captureValues( index+1, values... );\n        }\n    };\n\n} // end namespace Catch\n\n// end catch_message.h\n#if !defined(CATCH_CONFIG_DISABLE)\n\n#if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)\n  #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__\n#else\n  #define CATCH_INTERNAL_STRINGIFY(...) \"Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION\"\n#endif\n\n#if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)\n\n///////////////////////////////////////////////////////////////////////////////\n// Another way to speed-up compilation is to omit local try-catch for REQUIRE*\n// macros.\n#define INTERNAL_CATCH_TRY\n#define INTERNAL_CATCH_CATCH( capturer )\n\n#else // CATCH_CONFIG_FAST_COMPILE\n\n#define INTERNAL_CATCH_TRY try\n#define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }\n\n#endif\n\n#define INTERNAL_CATCH_REACT( handler ) handler.complete();\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \\\n    do { \\\n        Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \\\n        INTERNAL_CATCH_TRY { \\\n            CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n            CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \\\n            catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \\\n            CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \\\n        } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \\\n        INTERNAL_CATCH_REACT( catchAssertionHandler ) \\\n    } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look\n    // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \\\n    INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \\\n    if( Catch::getResultCapture().lastAssertionPassed() )\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \\\n    INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \\\n    if( !Catch::getResultCapture().lastAssertionPassed() )\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \\\n    do { \\\n        Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \\\n        try { \\\n            static_cast<void>(__VA_ARGS__); \\\n            catchAssertionHandler.handleExceptionNotThrownAsExpected(); \\\n        } \\\n        catch( ... ) { \\\n            catchAssertionHandler.handleUnexpectedInflightException(); \\\n        } \\\n        INTERNAL_CATCH_REACT( catchAssertionHandler ) \\\n    } while( false )\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \\\n    do { \\\n        Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \\\n        if( catchAssertionHandler.allowThrows() ) \\\n            try { \\\n                static_cast<void>(__VA_ARGS__); \\\n                catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \\\n            } \\\n            catch( ... ) { \\\n                catchAssertionHandler.handleExceptionThrownAsExpected(); \\\n            } \\\n        else \\\n            catchAssertionHandler.handleThrowingCallSkipped(); \\\n        INTERNAL_CATCH_REACT( catchAssertionHandler ) \\\n    } while( false )\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \\\n    do { \\\n        Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) \", \" CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \\\n        if( catchAssertionHandler.allowThrows() ) \\\n            try { \\\n                static_cast<void>(expr); \\\n                catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \\\n            } \\\n            catch( exceptionType const& ) { \\\n                catchAssertionHandler.handleExceptionThrownAsExpected(); \\\n            } \\\n            catch( ... ) { \\\n                catchAssertionHandler.handleUnexpectedInflightException(); \\\n            } \\\n        else \\\n            catchAssertionHandler.handleThrowingCallSkipped(); \\\n        INTERNAL_CATCH_REACT( catchAssertionHandler ) \\\n    } while( false )\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \\\n    do { \\\n        Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \\\n        catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \\\n        INTERNAL_CATCH_REACT( catchAssertionHandler ) \\\n    } while( false )\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \\\n    auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \\\n    varName.captureValues( 0, __VA_ARGS__ )\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_INFO( macroName, log ) \\\n    Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \\\n    Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )\n\n///////////////////////////////////////////////////////////////////////////////\n// Although this is matcher-based, it can be used with just a string\n#define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \\\n    do { \\\n        Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) \", \" CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \\\n        if( catchAssertionHandler.allowThrows() ) \\\n            try { \\\n                static_cast<void>(__VA_ARGS__); \\\n                catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \\\n            } \\\n            catch( ... ) { \\\n                Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \\\n            } \\\n        else \\\n            catchAssertionHandler.handleThrowingCallSkipped(); \\\n        INTERNAL_CATCH_REACT( catchAssertionHandler ) \\\n    } while( false )\n\n#endif // CATCH_CONFIG_DISABLE\n\n// end catch_capture.hpp\n// start catch_section.h\n\n// start catch_section_info.h\n\n// start catch_totals.h\n\n#include <cstddef>\n\nnamespace Catch {\n\n    struct Counts {\n        Counts operator - ( Counts const& other ) const;\n        Counts& operator += ( Counts const& other );\n\n        std::size_t total() const;\n        bool allPassed() const;\n        bool allOk() const;\n\n        std::size_t passed = 0;\n        std::size_t failed = 0;\n        std::size_t failedButOk = 0;\n    };\n\n    struct Totals {\n\n        Totals operator - ( Totals const& other ) const;\n        Totals& operator += ( Totals const& other );\n\n        Totals delta( Totals const& prevTotals ) const;\n\n        int error = 0;\n        Counts assertions;\n        Counts testCases;\n    };\n}\n\n// end catch_totals.h\n#include <string>\n\nnamespace Catch {\n\n    struct SectionInfo {\n        SectionInfo\n            (   SourceLineInfo const& _lineInfo,\n                std::string const& _name );\n\n        // Deprecated\n        SectionInfo\n            (   SourceLineInfo const& _lineInfo,\n                std::string const& _name,\n                std::string const& ) : SectionInfo( _lineInfo, _name ) {}\n\n        std::string name;\n        std::string description; // !Deprecated: this will always be empty\n        SourceLineInfo lineInfo;\n    };\n\n    struct SectionEndInfo {\n        SectionInfo sectionInfo;\n        Counts prevAssertions;\n        double durationInSeconds;\n    };\n\n} // end namespace Catch\n\n// end catch_section_info.h\n// start catch_timer.h\n\n#include <cstdint>\n\nnamespace Catch {\n\n    auto getCurrentNanosecondsSinceEpoch() -> uint64_t;\n    auto getEstimatedClockResolution() -> uint64_t;\n\n    class Timer {\n        uint64_t m_nanoseconds = 0;\n    public:\n        void start();\n        auto getElapsedNanoseconds() const -> uint64_t;\n        auto getElapsedMicroseconds() const -> uint64_t;\n        auto getElapsedMilliseconds() const -> unsigned int;\n        auto getElapsedSeconds() const -> double;\n    };\n\n} // namespace Catch\n\n// end catch_timer.h\n#include <string>\n\nnamespace Catch {\n\n    class Section : NonCopyable {\n    public:\n        Section( SectionInfo const& info );\n        ~Section();\n\n        // This indicates whether the section should be executed or not\n        explicit operator bool() const;\n\n    private:\n        SectionInfo m_info;\n\n        std::string m_name;\n        Counts m_assertions;\n        bool m_sectionIncluded;\n        Timer m_timer;\n    };\n\n} // end namespace Catch\n\n#define INTERNAL_CATCH_SECTION( ... ) \\\n    CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n    CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \\\n    if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \\\n    CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION\n\n#define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \\\n    CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n    CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \\\n    if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \\\n    CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION\n\n// end catch_section.h\n// start catch_interfaces_exception.h\n\n// start catch_interfaces_registry_hub.h\n\n#include <string>\n#include <memory>\n\nnamespace Catch {\n\n    class TestCase;\n    struct ITestCaseRegistry;\n    struct IExceptionTranslatorRegistry;\n    struct IExceptionTranslator;\n    struct IReporterRegistry;\n    struct IReporterFactory;\n    struct ITagAliasRegistry;\n    struct IMutableEnumValuesRegistry;\n\n    class StartupExceptionRegistry;\n\n    using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;\n\n    struct IRegistryHub {\n        virtual ~IRegistryHub();\n\n        virtual IReporterRegistry const& getReporterRegistry() const = 0;\n        virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;\n        virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;\n        virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;\n\n        virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;\n    };\n\n    struct IMutableRegistryHub {\n        virtual ~IMutableRegistryHub();\n        virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;\n        virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;\n        virtual void registerTest( TestCase const& testInfo ) = 0;\n        virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;\n        virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;\n        virtual void registerStartupException() noexcept = 0;\n        virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;\n    };\n\n    IRegistryHub const& getRegistryHub();\n    IMutableRegistryHub& getMutableRegistryHub();\n    void cleanUp();\n    std::string translateActiveException();\n\n}\n\n// end catch_interfaces_registry_hub.h\n#if defined(CATCH_CONFIG_DISABLE)\n    #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \\\n        static std::string translatorName( signature )\n#endif\n\n#include <exception>\n#include <string>\n#include <vector>\n\nnamespace Catch {\n    using exceptionTranslateFunction = std::string(*)();\n\n    struct IExceptionTranslator;\n    using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;\n\n    struct IExceptionTranslator {\n        virtual ~IExceptionTranslator();\n        virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;\n    };\n\n    struct IExceptionTranslatorRegistry {\n        virtual ~IExceptionTranslatorRegistry();\n\n        virtual std::string translateActiveException() const = 0;\n    };\n\n    class ExceptionTranslatorRegistrar {\n        template<typename T>\n        class ExceptionTranslator : public IExceptionTranslator {\n        public:\n\n            ExceptionTranslator( std::string(*translateFunction)( T& ) )\n            : m_translateFunction( translateFunction )\n            {}\n\n            std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {\n                try {\n                    if( it == itEnd )\n                        std::rethrow_exception(std::current_exception());\n                    else\n                        return (*it)->translate( it+1, itEnd );\n                }\n                catch( T& ex ) {\n                    return m_translateFunction( ex );\n                }\n            }\n\n        protected:\n            std::string(*m_translateFunction)( T& );\n        };\n\n    public:\n        template<typename T>\n        ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {\n            getMutableRegistryHub().registerTranslator\n                ( new ExceptionTranslator<T>( translateFunction ) );\n        }\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \\\n    static std::string translatorName( signature ); \\\n    CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \\\n    CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \\\n    namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \\\n    CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \\\n    static std::string translatorName( signature )\n\n#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )\n\n// end catch_interfaces_exception.h\n// start catch_approx.h\n\n#include <type_traits>\n\nnamespace Catch {\nnamespace Detail {\n\n    class Approx {\n    private:\n        bool equalityComparisonImpl(double other) const;\n        // Validates the new margin (margin >= 0)\n        // out-of-line to avoid including stdexcept in the header\n        void setMargin(double margin);\n        // Validates the new epsilon (0 < epsilon < 1)\n        // out-of-line to avoid including stdexcept in the header\n        void setEpsilon(double epsilon);\n\n    public:\n        explicit Approx ( double value );\n\n        static Approx custom();\n\n        Approx operator-() const;\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        Approx operator()( T const& value ) {\n            Approx approx( static_cast<double>(value) );\n            approx.m_epsilon = m_epsilon;\n            approx.m_margin = m_margin;\n            approx.m_scale = m_scale;\n            return approx;\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        explicit Approx( T const& value ): Approx(static_cast<double>(value))\n        {}\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        friend bool operator == ( const T& lhs, Approx const& rhs ) {\n            auto lhs_v = static_cast<double>(lhs);\n            return rhs.equalityComparisonImpl(lhs_v);\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        friend bool operator == ( Approx const& lhs, const T& rhs ) {\n            return operator==( rhs, lhs );\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        friend bool operator != ( T const& lhs, Approx const& rhs ) {\n            return !operator==( lhs, rhs );\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        friend bool operator != ( Approx const& lhs, T const& rhs ) {\n            return !operator==( rhs, lhs );\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        friend bool operator <= ( T const& lhs, Approx const& rhs ) {\n            return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        friend bool operator <= ( Approx const& lhs, T const& rhs ) {\n            return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        friend bool operator >= ( T const& lhs, Approx const& rhs ) {\n            return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        friend bool operator >= ( Approx const& lhs, T const& rhs ) {\n            return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        Approx& epsilon( T const& newEpsilon ) {\n            double epsilonAsDouble = static_cast<double>(newEpsilon);\n            setEpsilon(epsilonAsDouble);\n            return *this;\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        Approx& margin( T const& newMargin ) {\n            double marginAsDouble = static_cast<double>(newMargin);\n            setMargin(marginAsDouble);\n            return *this;\n        }\n\n        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n        Approx& scale( T const& newScale ) {\n            m_scale = static_cast<double>(newScale);\n            return *this;\n        }\n\n        std::string toString() const;\n\n    private:\n        double m_epsilon;\n        double m_margin;\n        double m_scale;\n        double m_value;\n    };\n} // end namespace Detail\n\nnamespace literals {\n    Detail::Approx operator \"\" _a(long double val);\n    Detail::Approx operator \"\" _a(unsigned long long val);\n} // end namespace literals\n\ntemplate<>\nstruct StringMaker<Catch::Detail::Approx> {\n    static std::string convert(Catch::Detail::Approx const& value);\n};\n\n} // end namespace Catch\n\n// end catch_approx.h\n// start catch_string_manip.h\n\n#include <string>\n#include <iosfwd>\n#include <vector>\n\nnamespace Catch {\n\n    bool startsWith( std::string const& s, std::string const& prefix );\n    bool startsWith( std::string const& s, char prefix );\n    bool endsWith( std::string const& s, std::string const& suffix );\n    bool endsWith( std::string const& s, char suffix );\n    bool contains( std::string const& s, std::string const& infix );\n    void toLowerInPlace( std::string& s );\n    std::string toLower( std::string const& s );\n    //! Returns a new string without whitespace at the start/end\n    std::string trim( std::string const& str );\n    //! Returns a substring of the original ref without whitespace. Beware lifetimes!\n    StringRef trim(StringRef ref);\n\n    // !!! Be aware, returns refs into original string - make sure original string outlives them\n    std::vector<StringRef> splitStringRef( StringRef str, char delimiter );\n    bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );\n\n    struct pluralise {\n        pluralise( std::size_t count, std::string const& label );\n\n        friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );\n\n        std::size_t m_count;\n        std::string m_label;\n    };\n}\n\n// end catch_string_manip.h\n#ifndef CATCH_CONFIG_DISABLE_MATCHERS\n// start catch_capture_matchers.h\n\n// start catch_matchers.h\n\n#include <string>\n#include <vector>\n\nnamespace Catch {\nnamespace Matchers {\n    namespace Impl {\n\n        template<typename ArgT> struct MatchAllOf;\n        template<typename ArgT> struct MatchAnyOf;\n        template<typename ArgT> struct MatchNotOf;\n\n        class MatcherUntypedBase {\n        public:\n            MatcherUntypedBase() = default;\n            MatcherUntypedBase ( MatcherUntypedBase const& ) = default;\n            MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;\n            std::string toString() const;\n\n        protected:\n            virtual ~MatcherUntypedBase();\n            virtual std::string describe() const = 0;\n            mutable std::string m_cachedToString;\n        };\n\n#ifdef __clang__\n#    pragma clang diagnostic push\n#    pragma clang diagnostic ignored \"-Wnon-virtual-dtor\"\n#endif\n\n        template<typename ObjectT>\n        struct MatcherMethod {\n            virtual bool match( ObjectT const& arg ) const = 0;\n        };\n\n#if defined(__OBJC__)\n        // Hack to fix Catch GH issue #1661. Could use id for generic Object support.\n        // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation\n        template<>\n        struct MatcherMethod<NSString*> {\n            virtual bool match( NSString* arg ) const = 0;\n        };\n#endif\n\n#ifdef __clang__\n#    pragma clang diagnostic pop\n#endif\n\n        template<typename T>\n        struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {\n\n            MatchAllOf<T> operator && ( MatcherBase const& other ) const;\n            MatchAnyOf<T> operator || ( MatcherBase const& other ) const;\n            MatchNotOf<T> operator ! () const;\n        };\n\n        template<typename ArgT>\n        struct MatchAllOf : MatcherBase<ArgT> {\n            bool match( ArgT const& arg ) const override {\n                for( auto matcher : m_matchers ) {\n                    if (!matcher->match(arg))\n                        return false;\n                }\n                return true;\n            }\n            std::string describe() const override {\n                std::string description;\n                description.reserve( 4 + m_matchers.size()*32 );\n                description += \"( \";\n                bool first = true;\n                for( auto matcher : m_matchers ) {\n                    if( first )\n                        first = false;\n                    else\n                        description += \" and \";\n                    description += matcher->toString();\n                }\n                description += \" )\";\n                return description;\n            }\n\n            MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {\n                m_matchers.push_back( &other );\n                return *this;\n            }\n\n            std::vector<MatcherBase<ArgT> const*> m_matchers;\n        };\n        template<typename ArgT>\n        struct MatchAnyOf : MatcherBase<ArgT> {\n\n            bool match( ArgT const& arg ) const override {\n                for( auto matcher : m_matchers ) {\n                    if (matcher->match(arg))\n                        return true;\n                }\n                return false;\n            }\n            std::string describe() const override {\n                std::string description;\n                description.reserve( 4 + m_matchers.size()*32 );\n                description += \"( \";\n                bool first = true;\n                for( auto matcher : m_matchers ) {\n                    if( first )\n                        first = false;\n                    else\n                        description += \" or \";\n                    description += matcher->toString();\n                }\n                description += \" )\";\n                return description;\n            }\n\n            MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {\n                m_matchers.push_back( &other );\n                return *this;\n            }\n\n            std::vector<MatcherBase<ArgT> const*> m_matchers;\n        };\n\n        template<typename ArgT>\n        struct MatchNotOf : MatcherBase<ArgT> {\n\n            MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}\n\n            bool match( ArgT const& arg ) const override {\n                return !m_underlyingMatcher.match( arg );\n            }\n\n            std::string describe() const override {\n                return \"not \" + m_underlyingMatcher.toString();\n            }\n            MatcherBase<ArgT> const& m_underlyingMatcher;\n        };\n\n        template<typename T>\n        MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {\n            return MatchAllOf<T>() && *this && other;\n        }\n        template<typename T>\n        MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {\n            return MatchAnyOf<T>() || *this || other;\n        }\n        template<typename T>\n        MatchNotOf<T> MatcherBase<T>::operator ! () const {\n            return MatchNotOf<T>( *this );\n        }\n\n    } // namespace Impl\n\n} // namespace Matchers\n\nusing namespace Matchers;\nusing Matchers::Impl::MatcherBase;\n\n} // namespace Catch\n\n// end catch_matchers.h\n// start catch_matchers_exception.hpp\n\nnamespace Catch {\nnamespace Matchers {\nnamespace Exception {\n\nclass ExceptionMessageMatcher : public MatcherBase<std::exception> {\n    std::string m_message;\npublic:\n\n    ExceptionMessageMatcher(std::string const& message):\n        m_message(message)\n    {}\n\n    bool match(std::exception const& ex) const override;\n\n    std::string describe() const override;\n};\n\n} // namespace Exception\n\nException::ExceptionMessageMatcher Message(std::string const& message);\n\n} // namespace Matchers\n} // namespace Catch\n\n// end catch_matchers_exception.hpp\n// start catch_matchers_floating.h\n\nnamespace Catch {\nnamespace Matchers {\n\n    namespace Floating {\n\n        enum class FloatingPointKind : uint8_t;\n\n        struct WithinAbsMatcher : MatcherBase<double> {\n            WithinAbsMatcher(double target, double margin);\n            bool match(double const& matchee) const override;\n            std::string describe() const override;\n        private:\n            double m_target;\n            double m_margin;\n        };\n\n        struct WithinUlpsMatcher : MatcherBase<double> {\n            WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);\n            bool match(double const& matchee) const override;\n            std::string describe() const override;\n        private:\n            double m_target;\n            uint64_t m_ulps;\n            FloatingPointKind m_type;\n        };\n\n        // Given IEEE-754 format for floats and doubles, we can assume\n        // that float -> double promotion is lossless. Given this, we can\n        // assume that if we do the standard relative comparison of\n        // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get\n        // the same result if we do this for floats, as if we do this for\n        // doubles that were promoted from floats.\n        struct WithinRelMatcher : MatcherBase<double> {\n            WithinRelMatcher(double target, double epsilon);\n            bool match(double const& matchee) const override;\n            std::string describe() const override;\n        private:\n            double m_target;\n            double m_epsilon;\n        };\n\n    } // namespace Floating\n\n    // The following functions create the actual matcher objects.\n    // This allows the types to be inferred\n    Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);\n    Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);\n    Floating::WithinAbsMatcher WithinAbs(double target, double margin);\n    Floating::WithinRelMatcher WithinRel(double target, double eps);\n    // defaults epsilon to 100*numeric_limits<double>::epsilon()\n    Floating::WithinRelMatcher WithinRel(double target);\n    Floating::WithinRelMatcher WithinRel(float target, float eps);\n    // defaults epsilon to 100*numeric_limits<float>::epsilon()\n    Floating::WithinRelMatcher WithinRel(float target);\n\n} // namespace Matchers\n} // namespace Catch\n\n// end catch_matchers_floating.h\n// start catch_matchers_generic.hpp\n\n#include <functional>\n#include <string>\n\nnamespace Catch {\nnamespace Matchers {\nnamespace Generic {\n\nnamespace Detail {\n    std::string finalizeDescription(const std::string& desc);\n}\n\ntemplate <typename T>\nclass PredicateMatcher : public MatcherBase<T> {\n    std::function<bool(T const&)> m_predicate;\n    std::string m_description;\npublic:\n\n    PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)\n        :m_predicate(std::move(elem)),\n        m_description(Detail::finalizeDescription(descr))\n    {}\n\n    bool match( T const& item ) const override {\n        return m_predicate(item);\n    }\n\n    std::string describe() const override {\n        return m_description;\n    }\n};\n\n} // namespace Generic\n\n    // The following functions create the actual matcher objects.\n    // The user has to explicitly specify type to the function, because\n    // inferring std::function<bool(T const&)> is hard (but possible) and\n    // requires a lot of TMP.\n    template<typename T>\n    Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = \"\") {\n        return Generic::PredicateMatcher<T>(predicate, description);\n    }\n\n} // namespace Matchers\n} // namespace Catch\n\n// end catch_matchers_generic.hpp\n// start catch_matchers_string.h\n\n#include <string>\n\nnamespace Catch {\nnamespace Matchers {\n\n    namespace StdString {\n\n        struct CasedString\n        {\n            CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );\n            std::string adjustString( std::string const& str ) const;\n            std::string caseSensitivitySuffix() const;\n\n            CaseSensitive::Choice m_caseSensitivity;\n            std::string m_str;\n        };\n\n        struct StringMatcherBase : MatcherBase<std::string> {\n            StringMatcherBase( std::string const& operation, CasedString const& comparator );\n            std::string describe() const override;\n\n            CasedString m_comparator;\n            std::string m_operation;\n        };\n\n        struct EqualsMatcher : StringMatcherBase {\n            EqualsMatcher( CasedString const& comparator );\n            bool match( std::string const& source ) const override;\n        };\n        struct ContainsMatcher : StringMatcherBase {\n            ContainsMatcher( CasedString const& comparator );\n            bool match( std::string const& source ) const override;\n        };\n        struct StartsWithMatcher : StringMatcherBase {\n            StartsWithMatcher( CasedString const& comparator );\n            bool match( std::string const& source ) const override;\n        };\n        struct EndsWithMatcher : StringMatcherBase {\n            EndsWithMatcher( CasedString const& comparator );\n            bool match( std::string const& source ) const override;\n        };\n\n        struct RegexMatcher : MatcherBase<std::string> {\n            RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );\n            bool match( std::string const& matchee ) const override;\n            std::string describe() const override;\n\n        private:\n            std::string m_regex;\n            CaseSensitive::Choice m_caseSensitivity;\n        };\n\n    } // namespace StdString\n\n    // The following functions create the actual matcher objects.\n    // This allows the types to be inferred\n\n    StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );\n    StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );\n    StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );\n    StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );\n    StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );\n\n} // namespace Matchers\n} // namespace Catch\n\n// end catch_matchers_string.h\n// start catch_matchers_vector.h\n\n#include <algorithm>\n\nnamespace Catch {\nnamespace Matchers {\n\n    namespace Vector {\n        template<typename T>\n        struct ContainsElementMatcher : MatcherBase<std::vector<T>> {\n\n            ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}\n\n            bool match(std::vector<T> const &v) const override {\n                for (auto const& el : v) {\n                    if (el == m_comparator) {\n                        return true;\n                    }\n                }\n                return false;\n            }\n\n            std::string describe() const override {\n                return \"Contains: \" + ::Catch::Detail::stringify( m_comparator );\n            }\n\n            T const& m_comparator;\n        };\n\n        template<typename T>\n        struct ContainsMatcher : MatcherBase<std::vector<T>> {\n\n            ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}\n\n            bool match(std::vector<T> const &v) const override {\n                // !TBD: see note in EqualsMatcher\n                if (m_comparator.size() > v.size())\n                    return false;\n                for (auto const& comparator : m_comparator) {\n                    auto present = false;\n                    for (const auto& el : v) {\n                        if (el == comparator) {\n                            present = true;\n                            break;\n                        }\n                    }\n                    if (!present) {\n                        return false;\n                    }\n                }\n                return true;\n            }\n            std::string describe() const override {\n                return \"Contains: \" + ::Catch::Detail::stringify( m_comparator );\n            }\n\n            std::vector<T> const& m_comparator;\n        };\n\n        template<typename T>\n        struct EqualsMatcher : MatcherBase<std::vector<T>> {\n\n            EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}\n\n            bool match(std::vector<T> const &v) const override {\n                // !TBD: This currently works if all elements can be compared using !=\n                // - a more general approach would be via a compare template that defaults\n                // to using !=. but could be specialised for, e.g. std::vector<T> etc\n                // - then just call that directly\n                if (m_comparator.size() != v.size())\n                    return false;\n                for (std::size_t i = 0; i < v.size(); ++i)\n                    if (m_comparator[i] != v[i])\n                        return false;\n                return true;\n            }\n            std::string describe() const override {\n                return \"Equals: \" + ::Catch::Detail::stringify( m_comparator );\n            }\n            std::vector<T> const& m_comparator;\n        };\n\n        template<typename T>\n        struct ApproxMatcher : MatcherBase<std::vector<T>> {\n\n            ApproxMatcher(std::vector<T> const& comparator) : m_comparator( comparator ) {}\n\n            bool match(std::vector<T> const &v) const override {\n                if (m_comparator.size() != v.size())\n                    return false;\n                for (std::size_t i = 0; i < v.size(); ++i)\n                    if (m_comparator[i] != approx(v[i]))\n                        return false;\n                return true;\n            }\n            std::string describe() const override {\n                return \"is approx: \" + ::Catch::Detail::stringify( m_comparator );\n            }\n            template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n            ApproxMatcher& epsilon( T const& newEpsilon ) {\n                approx.epsilon(newEpsilon);\n                return *this;\n            }\n            template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n            ApproxMatcher& margin( T const& newMargin ) {\n                approx.margin(newMargin);\n                return *this;\n            }\n            template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n            ApproxMatcher& scale( T const& newScale ) {\n                approx.scale(newScale);\n                return *this;\n            }\n\n            std::vector<T> const& m_comparator;\n            mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();\n        };\n\n        template<typename T>\n        struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {\n            UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}\n            bool match(std::vector<T> const& vec) const override {\n                // Note: This is a reimplementation of std::is_permutation,\n                //       because I don't want to include <algorithm> inside the common path\n                if (m_target.size() != vec.size()) {\n                    return false;\n                }\n                return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());\n            }\n\n            std::string describe() const override {\n                return \"UnorderedEquals: \" + ::Catch::Detail::stringify(m_target);\n            }\n        private:\n            std::vector<T> const& m_target;\n        };\n\n    } // namespace Vector\n\n    // The following functions create the actual matcher objects.\n    // This allows the types to be inferred\n\n    template<typename T>\n    Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {\n        return Vector::ContainsMatcher<T>( comparator );\n    }\n\n    template<typename T>\n    Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {\n        return Vector::ContainsElementMatcher<T>( comparator );\n    }\n\n    template<typename T>\n    Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {\n        return Vector::EqualsMatcher<T>( comparator );\n    }\n\n    template<typename T>\n    Vector::ApproxMatcher<T> Approx( std::vector<T> const& comparator ) {\n        return Vector::ApproxMatcher<T>( comparator );\n    }\n\n    template<typename T>\n    Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {\n        return Vector::UnorderedEqualsMatcher<T>(target);\n    }\n\n} // namespace Matchers\n} // namespace Catch\n\n// end catch_matchers_vector.h\nnamespace Catch {\n\n    template<typename ArgT, typename MatcherT>\n    class MatchExpr : public ITransientExpression {\n        ArgT const& m_arg;\n        MatcherT m_matcher;\n        StringRef m_matcherString;\n    public:\n        MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )\n        :   ITransientExpression{ true, matcher.match( arg ) },\n            m_arg( arg ),\n            m_matcher( matcher ),\n            m_matcherString( matcherString )\n        {}\n\n        void streamReconstructedExpression( std::ostream &os ) const override {\n            auto matcherAsString = m_matcher.toString();\n            os << Catch::Detail::stringify( m_arg ) << ' ';\n            if( matcherAsString == Detail::unprintableString )\n                os << m_matcherString;\n            else\n                os << matcherAsString;\n        }\n    };\n\n    using StringMatcher = Matchers::Impl::MatcherBase<std::string>;\n\n    void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString  );\n\n    template<typename ArgT, typename MatcherT>\n    auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString  ) -> MatchExpr<ArgT, MatcherT> {\n        return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );\n    }\n\n} // namespace Catch\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \\\n    do { \\\n        Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) \", \" CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \\\n        INTERNAL_CATCH_TRY { \\\n            catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \\\n        } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \\\n        INTERNAL_CATCH_REACT( catchAssertionHandler ) \\\n    } while( false )\n\n///////////////////////////////////////////////////////////////////////////////\n#define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \\\n    do { \\\n        Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) \", \" CATCH_INTERNAL_STRINGIFY(exceptionType) \", \" CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \\\n        if( catchAssertionHandler.allowThrows() ) \\\n            try { \\\n                static_cast<void>(__VA_ARGS__ ); \\\n                catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \\\n            } \\\n            catch( exceptionType const& ex ) { \\\n                catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \\\n            } \\\n            catch( ... ) { \\\n                catchAssertionHandler.handleUnexpectedInflightException(); \\\n            } \\\n        else \\\n            catchAssertionHandler.handleThrowingCallSkipped(); \\\n        INTERNAL_CATCH_REACT( catchAssertionHandler ) \\\n    } while( false )\n\n// end catch_capture_matchers.h\n#endif\n// start catch_generators.hpp\n\n// start catch_interfaces_generatortracker.h\n\n\n#include <memory>\n\nnamespace Catch {\n\n    namespace Generators {\n        class GeneratorUntypedBase {\n        public:\n            GeneratorUntypedBase() = default;\n            virtual ~GeneratorUntypedBase();\n            // Attempts to move the generator to the next element\n             //\n             // Returns true iff the move succeeded (and a valid element\n             // can be retrieved).\n            virtual bool next() = 0;\n        };\n        using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;\n\n    } // namespace Generators\n\n    struct IGeneratorTracker {\n        virtual ~IGeneratorTracker();\n        virtual auto hasGenerator() const -> bool = 0;\n        virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;\n        virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;\n    };\n\n} // namespace Catch\n\n// end catch_interfaces_generatortracker.h\n// start catch_enforce.h\n\n#include <exception>\n\nnamespace Catch {\n#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)\n    template <typename Ex>\n    [[noreturn]]\n    void throw_exception(Ex const& e) {\n        throw e;\n    }\n#else // ^^ Exceptions are enabled //  Exceptions are disabled vv\n    [[noreturn]]\n    void throw_exception(std::exception const& e);\n#endif\n\n    [[noreturn]]\n    void throw_logic_error(std::string const& msg);\n    [[noreturn]]\n    void throw_domain_error(std::string const& msg);\n    [[noreturn]]\n    void throw_runtime_error(std::string const& msg);\n\n} // namespace Catch;\n\n#define CATCH_MAKE_MSG(...) \\\n    (Catch::ReusableStringStream() << __VA_ARGS__).str()\n\n#define CATCH_INTERNAL_ERROR(...) \\\n    Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << \": Internal Catch2 error: \" << __VA_ARGS__))\n\n#define CATCH_ERROR(...) \\\n    Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))\n\n#define CATCH_RUNTIME_ERROR(...) \\\n    Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))\n\n#define CATCH_ENFORCE( condition, ... ) \\\n    do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)\n\n// end catch_enforce.h\n#include <memory>\n#include <vector>\n#include <cassert>\n\n#include <utility>\n#include <exception>\n\nnamespace Catch {\n\nclass GeneratorException : public std::exception {\n    const char* const m_msg = \"\";\n\npublic:\n    GeneratorException(const char* msg):\n        m_msg(msg)\n    {}\n\n    const char* what() const noexcept override final;\n};\n\nnamespace Generators {\n\n    // !TBD move this into its own location?\n    namespace pf{\n        template<typename T, typename... Args>\n        std::unique_ptr<T> make_unique( Args&&... args ) {\n            return std::unique_ptr<T>(new T(std::forward<Args>(args)...));\n        }\n    }\n\n    template<typename T>\n    struct IGenerator : GeneratorUntypedBase {\n        virtual ~IGenerator() = default;\n\n        // Returns the current element of the generator\n        //\n        // \\Precondition The generator is either freshly constructed,\n        // or the last call to `next()` returned true\n        virtual T const& get() const = 0;\n        using type = T;\n    };\n\n    template<typename T>\n    class SingleValueGenerator final : public IGenerator<T> {\n        T m_value;\n    public:\n        SingleValueGenerator(T const& value) : m_value( value ) {}\n        SingleValueGenerator(T&& value) : m_value(std::move(value)) {}\n\n        T const& get() const override {\n            return m_value;\n        }\n        bool next() override {\n            return false;\n        }\n    };\n\n    template<typename T>\n    class FixedValuesGenerator final : public IGenerator<T> {\n        static_assert(!std::is_same<T, bool>::value,\n            \"FixedValuesGenerator does not support bools because of std::vector<bool>\"\n            \"specialization, use SingleValue Generator instead.\");\n        std::vector<T> m_values;\n        size_t m_idx = 0;\n    public:\n        FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}\n\n        T const& get() const override {\n            return m_values[m_idx];\n        }\n        bool next() override {\n            ++m_idx;\n            return m_idx < m_values.size();\n        }\n    };\n\n    template <typename T>\n    class GeneratorWrapper final {\n        std::unique_ptr<IGenerator<T>> m_generator;\n    public:\n        GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):\n            m_generator(std::move(generator))\n        {}\n        T const& get() const {\n            return m_generator->get();\n        }\n        bool next() {\n            return m_generator->next();\n        }\n    };\n\n    template <typename T>\n    GeneratorWrapper<T> value(T&& value) {\n        return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));\n    }\n    template <typename T>\n    GeneratorWrapper<T> values(std::initializer_list<T> values) {\n        return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));\n    }\n\n    template<typename T>\n    class Generators : public IGenerator<T> {\n        std::vector<GeneratorWrapper<T>> m_generators;\n        size_t m_current = 0;\n\n        void populate(GeneratorWrapper<T>&& generator) {\n            m_generators.emplace_back(std::move(generator));\n        }\n        void populate(T&& val) {\n            m_generators.emplace_back(value(std::move(val)));\n        }\n        template<typename U>\n        void populate(U&& val) {\n            populate(T(std::move(val)));\n        }\n        template<typename U, typename... Gs>\n        void populate(U&& valueOrGenerator, Gs... moreGenerators) {\n            populate(std::forward<U>(valueOrGenerator));\n            populate(std::forward<Gs>(moreGenerators)...);\n        }\n\n    public:\n        template <typename... Gs>\n        Generators(Gs... moreGenerators) {\n            m_generators.reserve(sizeof...(Gs));\n            populate(std::forward<Gs>(moreGenerators)...);\n        }\n\n        T const& get() const override {\n            return m_generators[m_current].get();\n        }\n\n        bool next() override {\n            if (m_current >= m_generators.size()) {\n                return false;\n            }\n            const bool current_status = m_generators[m_current].next();\n            if (!current_status) {\n                ++m_current;\n            }\n            return m_current < m_generators.size();\n        }\n    };\n\n    template<typename... Ts>\n    GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {\n        return values<std::tuple<Ts...>>( tuples );\n    }\n\n    // Tag type to signal that a generator sequence should convert arguments to a specific type\n    template <typename T>\n    struct as {};\n\n    template<typename T, typename... Gs>\n    auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {\n        return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);\n    }\n    template<typename T>\n    auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {\n        return Generators<T>(std::move(generator));\n    }\n    template<typename T, typename... Gs>\n    auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {\n        return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );\n    }\n    template<typename T, typename U, typename... Gs>\n    auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {\n        return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );\n    }\n\n    auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;\n\n    template<typename L>\n    // Note: The type after -> is weird, because VS2015 cannot parse\n    //       the expression used in the typedef inside, when it is in\n    //       return type. Yeah.\n    auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {\n        using UnderlyingType = typename decltype(generatorExpression())::type;\n\n        IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );\n        if (!tracker.hasGenerator()) {\n            tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));\n        }\n\n        auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );\n        return generator.get();\n    }\n\n} // namespace Generators\n} // namespace Catch\n\n#define GENERATE( ... ) \\\n    Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )\n#define GENERATE_COPY( ... ) \\\n    Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )\n#define GENERATE_REF( ... ) \\\n    Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )\n\n// end catch_generators.hpp\n// start catch_generators_generic.hpp\n\nnamespace Catch {\nnamespace Generators {\n\n    template <typename T>\n    class TakeGenerator : public IGenerator<T> {\n        GeneratorWrapper<T> m_generator;\n        size_t m_returned = 0;\n        size_t m_target;\n    public:\n        TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):\n            m_generator(std::move(generator)),\n            m_target(target)\n        {\n            assert(target != 0 && \"Empty generators are not allowed\");\n        }\n        T const& get() const override {\n            return m_generator.get();\n        }\n        bool next() override {\n            ++m_returned;\n            if (m_returned >= m_target) {\n                return false;\n            }\n\n            const auto success = m_generator.next();\n            // If the underlying generator does not contain enough values\n            // then we cut short as well\n            if (!success) {\n                m_returned = m_target;\n            }\n            return success;\n        }\n    };\n\n    template <typename T>\n    GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {\n        return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));\n    }\n\n    template <typename T, typename Predicate>\n    class FilterGenerator : public IGenerator<T> {\n        GeneratorWrapper<T> m_generator;\n        Predicate m_predicate;\n    public:\n        template <typename P = Predicate>\n        FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):\n            m_generator(std::move(generator)),\n            m_predicate(std::forward<P>(pred))\n        {\n            if (!m_predicate(m_generator.get())) {\n                // It might happen that there are no values that pass the\n                // filter. In that case we throw an exception.\n                auto has_initial_value = next();\n                if (!has_initial_value) {\n                    Catch::throw_exception(GeneratorException(\"No valid value found in filtered generator\"));\n                }\n            }\n        }\n\n        T const& get() const override {\n            return m_generator.get();\n        }\n\n        bool next() override {\n            bool success = m_generator.next();\n            if (!success) {\n                return false;\n            }\n            while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);\n            return success;\n        }\n    };\n\n    template <typename T, typename Predicate>\n    GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {\n        return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));\n    }\n\n    template <typename T>\n    class RepeatGenerator : public IGenerator<T> {\n        static_assert(!std::is_same<T, bool>::value,\n            \"RepeatGenerator currently does not support bools\"\n            \"because of std::vector<bool> specialization\");\n        GeneratorWrapper<T> m_generator;\n        mutable std::vector<T> m_returned;\n        size_t m_target_repeats;\n        size_t m_current_repeat = 0;\n        size_t m_repeat_index = 0;\n    public:\n        RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):\n            m_generator(std::move(generator)),\n            m_target_repeats(repeats)\n        {\n            assert(m_target_repeats > 0 && \"Repeat generator must repeat at least once\");\n        }\n\n        T const& get() const override {\n            if (m_current_repeat == 0) {\n                m_returned.push_back(m_generator.get());\n                return m_returned.back();\n            }\n            return m_returned[m_repeat_index];\n        }\n\n        bool next() override {\n            // There are 2 basic cases:\n            // 1) We are still reading the generator\n            // 2) We are reading our own cache\n\n            // In the first case, we need to poke the underlying generator.\n            // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache\n            if (m_current_repeat == 0) {\n                const auto success = m_generator.next();\n                if (!success) {\n                    ++m_current_repeat;\n                }\n                return m_current_repeat < m_target_repeats;\n            }\n\n            // In the second case, we need to move indices forward and check that we haven't run up against the end\n            ++m_repeat_index;\n            if (m_repeat_index == m_returned.size()) {\n                m_repeat_index = 0;\n                ++m_current_repeat;\n            }\n            return m_current_repeat < m_target_repeats;\n        }\n    };\n\n    template <typename T>\n    GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {\n        return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));\n    }\n\n    template <typename T, typename U, typename Func>\n    class MapGenerator : public IGenerator<T> {\n        // TBD: provide static assert for mapping function, for friendly error message\n        GeneratorWrapper<U> m_generator;\n        Func m_function;\n        // To avoid returning dangling reference, we have to save the values\n        T m_cache;\n    public:\n        template <typename F2 = Func>\n        MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :\n            m_generator(std::move(generator)),\n            m_function(std::forward<F2>(function)),\n            m_cache(m_function(m_generator.get()))\n        {}\n\n        T const& get() const override {\n            return m_cache;\n        }\n        bool next() override {\n            const auto success = m_generator.next();\n            if (success) {\n                m_cache = m_function(m_generator.get());\n            }\n            return success;\n        }\n    };\n\n    template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>\n    GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {\n        return GeneratorWrapper<T>(\n            pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))\n        );\n    }\n\n    template <typename T, typename U, typename Func>\n    GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {\n        return GeneratorWrapper<T>(\n            pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))\n        );\n    }\n\n    template <typename T>\n    class ChunkGenerator final : public IGenerator<std::vector<T>> {\n        std::vector<T> m_chunk;\n        size_t m_chunk_size;\n        GeneratorWrapper<T> m_generator;\n        bool m_used_up = false;\n    public:\n        ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :\n            m_chunk_size(size), m_generator(std::move(generator))\n        {\n            m_chunk.reserve(m_chunk_size);\n            if (m_chunk_size != 0) {\n                m_chunk.push_back(m_generator.get());\n                for (size_t i = 1; i < m_chunk_size; ++i) {\n                    if (!m_generator.next()) {\n                        Catch::throw_exception(GeneratorException(\"Not enough values to initialize the first chunk\"));\n                    }\n                    m_chunk.push_back(m_generator.get());\n                }\n            }\n        }\n        std::vector<T> const& get() const override {\n            return m_chunk;\n        }\n        bool next() override {\n            m_chunk.clear();\n            for (size_t idx = 0; idx < m_chunk_size; ++idx) {\n                if (!m_generator.next()) {\n                    return false;\n                }\n                m_chunk.push_back(m_generator.get());\n            }\n            return true;\n        }\n    };\n\n    template <typename T>\n    GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {\n        return GeneratorWrapper<std::vector<T>>(\n            pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))\n        );\n    }\n\n} // namespace Generators\n} // namespace Catch\n\n// end catch_generators_generic.hpp\n// start catch_generators_specific.hpp\n\n// start catch_context.h\n\n#include <memory>\n\nnamespace Catch {\n\n    struct IResultCapture;\n    struct IRunner;\n    struct IConfig;\n    struct IMutableContext;\n\n    using IConfigPtr = std::shared_ptr<IConfig const>;\n\n    struct IContext\n    {\n        virtual ~IContext();\n\n        virtual IResultCapture* getResultCapture() = 0;\n        virtual IRunner* getRunner() = 0;\n        virtual IConfigPtr const& getConfig() const = 0;\n    };\n\n    struct IMutableContext : IContext\n    {\n        virtual ~IMutableContext();\n        virtual void setResultCapture( IResultCapture* resultCapture ) = 0;\n        virtual void setRunner( IRunner* runner ) = 0;\n        virtual void setConfig( IConfigPtr const& config ) = 0;\n\n    private:\n        static IMutableContext *currentContext;\n        friend IMutableContext& getCurrentMutableContext();\n        friend void cleanUpContext();\n        static void createContext();\n    };\n\n    inline IMutableContext& getCurrentMutableContext()\n    {\n        if( !IMutableContext::currentContext )\n            IMutableContext::createContext();\n        // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)\n        return *IMutableContext::currentContext;\n    }\n\n    inline IContext& getCurrentContext()\n    {\n        return getCurrentMutableContext();\n    }\n\n    void cleanUpContext();\n\n    class SimplePcg32;\n    SimplePcg32& rng();\n}\n\n// end catch_context.h\n// start catch_interfaces_config.h\n\n// start catch_option.hpp\n\nnamespace Catch {\n\n    // An optional type\n    template<typename T>\n    class Option {\n    public:\n        Option() : nullableValue( nullptr ) {}\n        Option( T const& _value )\n        : nullableValue( new( storage ) T( _value ) )\n        {}\n        Option( Option const& _other )\n        : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )\n        {}\n\n        ~Option() {\n            reset();\n        }\n\n        Option& operator= ( Option const& _other ) {\n            if( &_other != this ) {\n                reset();\n                if( _other )\n                    nullableValue = new( storage ) T( *_other );\n            }\n            return *this;\n        }\n        Option& operator = ( T const& _value ) {\n            reset();\n            nullableValue = new( storage ) T( _value );\n            return *this;\n        }\n\n        void reset() {\n            if( nullableValue )\n                nullableValue->~T();\n            nullableValue = nullptr;\n        }\n\n        T& operator*() { return *nullableValue; }\n        T const& operator*() const { return *nullableValue; }\n        T* operator->() { return nullableValue; }\n        const T* operator->() const { return nullableValue; }\n\n        T valueOr( T const& defaultValue ) const {\n            return nullableValue ? *nullableValue : defaultValue;\n        }\n\n        bool some() const { return nullableValue != nullptr; }\n        bool none() const { return nullableValue == nullptr; }\n\n        bool operator !() const { return nullableValue == nullptr; }\n        explicit operator bool() const {\n            return some();\n        }\n\n    private:\n        T *nullableValue;\n        alignas(alignof(T)) char storage[sizeof(T)];\n    };\n\n} // end namespace Catch\n\n// end catch_option.hpp\n#include <iosfwd>\n#include <string>\n#include <vector>\n#include <memory>\n\nnamespace Catch {\n\n    enum class Verbosity {\n        Quiet = 0,\n        Normal,\n        High\n    };\n\n    struct WarnAbout { enum What {\n        Nothing = 0x00,\n        NoAssertions = 0x01,\n        NoTests = 0x02\n    }; };\n\n    struct ShowDurations { enum OrNot {\n        DefaultForReporter,\n        Always,\n        Never\n    }; };\n    struct RunTests { enum InWhatOrder {\n        InDeclarationOrder,\n        InLexicographicalOrder,\n        InRandomOrder\n    }; };\n    struct UseColour { enum YesOrNo {\n        Auto,\n        Yes,\n        No\n    }; };\n    struct WaitForKeypress { enum When {\n        Never,\n        BeforeStart = 1,\n        BeforeExit = 2,\n        BeforeStartAndExit = BeforeStart | BeforeExit\n    }; };\n\n    class TestSpec;\n\n    struct IConfig : NonCopyable {\n\n        virtual ~IConfig();\n\n        virtual bool allowThrows() const = 0;\n        virtual std::ostream& stream() const = 0;\n        virtual std::string name() const = 0;\n        virtual bool includeSuccessfulResults() const = 0;\n        virtual bool shouldDebugBreak() const = 0;\n        virtual bool warnAboutMissingAssertions() const = 0;\n        virtual bool warnAboutNoTests() const = 0;\n        virtual int abortAfter() const = 0;\n        virtual bool showInvisibles() const = 0;\n        virtual ShowDurations::OrNot showDurations() const = 0;\n        virtual TestSpec const& testSpec() const = 0;\n        virtual bool hasTestFilters() const = 0;\n        virtual std::vector<std::string> const& getTestsOrTags() const = 0;\n        virtual RunTests::InWhatOrder runOrder() const = 0;\n        virtual unsigned int rngSeed() const = 0;\n        virtual UseColour::YesOrNo useColour() const = 0;\n        virtual std::vector<std::string> const& getSectionsToRun() const = 0;\n        virtual Verbosity verbosity() const = 0;\n\n        virtual bool benchmarkNoAnalysis() const = 0;\n        virtual int benchmarkSamples() const = 0;\n        virtual double benchmarkConfidenceInterval() const = 0;\n        virtual unsigned int benchmarkResamples() const = 0;\n    };\n\n    using IConfigPtr = std::shared_ptr<IConfig const>;\n}\n\n// end catch_interfaces_config.h\n// start catch_random_number_generator.h\n\n#include <cstdint>\n\nnamespace Catch {\n\n    // This is a simple implementation of C++11 Uniform Random Number\n    // Generator. It does not provide all operators, because Catch2\n    // does not use it, but it should behave as expected inside stdlib's\n    // distributions.\n    // The implementation is based on the PCG family (http://pcg-random.org)\n    class SimplePcg32 {\n        using state_type = std::uint64_t;\n    public:\n        using result_type = std::uint32_t;\n        static constexpr result_type (min)() {\n            return 0;\n        }\n        static constexpr result_type (max)() {\n            return static_cast<result_type>(-1);\n        }\n\n        // Provide some default initial state for the default constructor\n        SimplePcg32():SimplePcg32(0xed743cc4U) {}\n\n        explicit SimplePcg32(result_type seed_);\n\n        void seed(result_type seed_);\n        void discard(uint64_t skip);\n\n        result_type operator()();\n\n    private:\n        friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);\n        friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);\n\n        // In theory we also need operator<< and operator>>\n        // In practice we do not use them, so we will skip them for now\n\n        std::uint64_t m_state;\n        // This part of the state determines which \"stream\" of the numbers\n        // is chosen -- we take it as a constant for Catch2, so we only\n        // need to deal with seeding the main state.\n        // Picked by reading 8 bytes from `/dev/random` :-)\n        static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;\n    };\n\n} // end namespace Catch\n\n// end catch_random_number_generator.h\n#include <random>\n\nnamespace Catch {\nnamespace Generators {\n\ntemplate <typename Float>\nclass RandomFloatingGenerator final : public IGenerator<Float> {\n    Catch::SimplePcg32& m_rng;\n    std::uniform_real_distribution<Float> m_dist;\n    Float m_current_number;\npublic:\n\n    RandomFloatingGenerator(Float a, Float b):\n        m_rng(rng()),\n        m_dist(a, b) {\n        static_cast<void>(next());\n    }\n\n    Float const& get() const override {\n        return m_current_number;\n    }\n    bool next() override {\n        m_current_number = m_dist(m_rng);\n        return true;\n    }\n};\n\ntemplate <typename Integer>\nclass RandomIntegerGenerator final : public IGenerator<Integer> {\n    Catch::SimplePcg32& m_rng;\n    std::uniform_int_distribution<Integer> m_dist;\n    Integer m_current_number;\npublic:\n\n    RandomIntegerGenerator(Integer a, Integer b):\n        m_rng(rng()),\n        m_dist(a, b) {\n        static_cast<void>(next());\n    }\n\n    Integer const& get() const override {\n        return m_current_number;\n    }\n    bool next() override {\n        m_current_number = m_dist(m_rng);\n        return true;\n    }\n};\n\n// TODO: Ideally this would be also constrained against the various char types,\n//       but I don't expect users to run into that in practice.\ntemplate <typename T>\ntypename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,\nGeneratorWrapper<T>>::type\nrandom(T a, T b) {\n    return GeneratorWrapper<T>(\n        pf::make_unique<RandomIntegerGenerator<T>>(a, b)\n    );\n}\n\ntemplate <typename T>\ntypename std::enable_if<std::is_floating_point<T>::value,\nGeneratorWrapper<T>>::type\nrandom(T a, T b) {\n    return GeneratorWrapper<T>(\n        pf::make_unique<RandomFloatingGenerator<T>>(a, b)\n    );\n}\n\ntemplate <typename T>\nclass RangeGenerator final : public IGenerator<T> {\n    T m_current;\n    T m_end;\n    T m_step;\n    bool m_positive;\n\npublic:\n    RangeGenerator(T const& start, T const& end, T const& step):\n        m_current(start),\n        m_end(end),\n        m_step(step),\n        m_positive(m_step > T(0))\n    {\n        assert(m_current != m_end && \"Range start and end cannot be equal\");\n        assert(m_step != T(0) && \"Step size cannot be zero\");\n        assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && \"Step moves away from end\");\n    }\n\n    RangeGenerator(T const& start, T const& end):\n        RangeGenerator(start, end, (start < end) ? T(1) : T(-1))\n    {}\n\n    T const& get() const override {\n        return m_current;\n    }\n\n    bool next() override {\n        m_current += m_step;\n        return (m_positive) ? (m_current < m_end) : (m_current > m_end);\n    }\n};\n\ntemplate <typename T>\nGeneratorWrapper<T> range(T const& start, T const& end, T const& step) {\n    static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, \"Type must be numeric\");\n    return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));\n}\n\ntemplate <typename T>\nGeneratorWrapper<T> range(T const& start, T const& end) {\n    static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, \"Type must be an integer\");\n    return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));\n}\n\ntemplate <typename T>\nclass IteratorGenerator final : public IGenerator<T> {\n    static_assert(!std::is_same<T, bool>::value,\n        \"IteratorGenerator currently does not support bools\"\n        \"because of std::vector<bool> specialization\");\n\n    std::vector<T> m_elems;\n    size_t m_current = 0;\npublic:\n    template <typename InputIterator, typename InputSentinel>\n    IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {\n        if (m_elems.empty()) {\n            Catch::throw_exception(GeneratorException(\"IteratorGenerator received no valid values\"));\n        }\n    }\n\n    T const& get() const override {\n        return m_elems[m_current];\n    }\n\n    bool next() override {\n        ++m_current;\n        return m_current != m_elems.size();\n    }\n};\n\ntemplate <typename InputIterator,\n          typename InputSentinel,\n          typename ResultType = typename std::iterator_traits<InputIterator>::value_type>\nGeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {\n    return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));\n}\n\ntemplate <typename Container,\n          typename ResultType = typename Container::value_type>\nGeneratorWrapper<ResultType> from_range(Container const& cnt) {\n    return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));\n}\n\n} // namespace Generators\n} // namespace Catch\n\n// end catch_generators_specific.hpp\n\n// These files are included here so the single_include script doesn't put them\n// in the conditionally compiled sections\n// start catch_test_case_info.h\n\n#include <string>\n#include <vector>\n#include <memory>\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wpadded\"\n#endif\n\nnamespace Catch {\n\n    struct ITestInvoker;\n\n    struct TestCaseInfo {\n        enum SpecialProperties{\n            None = 0,\n            IsHidden = 1 << 1,\n            ShouldFail = 1 << 2,\n            MayFail = 1 << 3,\n            Throws = 1 << 4,\n            NonPortable = 1 << 5,\n            Benchmark = 1 << 6\n        };\n\n        TestCaseInfo(   std::string const& _name,\n                        std::string const& _className,\n                        std::string const& _description,\n                        std::vector<std::string> const& _tags,\n                        SourceLineInfo const& _lineInfo );\n\n        friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );\n\n        bool isHidden() const;\n        bool throws() const;\n        bool okToFail() const;\n        bool expectedToFail() const;\n\n        std::string tagsAsString() const;\n\n        std::string name;\n        std::string className;\n        std::string description;\n        std::vector<std::string> tags;\n        std::vector<std::string> lcaseTags;\n        SourceLineInfo lineInfo;\n        SpecialProperties properties;\n    };\n\n    class TestCase : public TestCaseInfo {\n    public:\n\n        TestCase( ITestInvoker* testCase, TestCaseInfo&& info );\n\n        TestCase withName( std::string const& _newName ) const;\n\n        void invoke() const;\n\n        TestCaseInfo const& getTestCaseInfo() const;\n\n        bool operator == ( TestCase const& other ) const;\n        bool operator < ( TestCase const& other ) const;\n\n    private:\n        std::shared_ptr<ITestInvoker> test;\n    };\n\n    TestCase makeTestCase(  ITestInvoker* testCase,\n                            std::string const& className,\n                            NameAndTags const& nameAndTags,\n                            SourceLineInfo const& lineInfo );\n}\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n// end catch_test_case_info.h\n// start catch_interfaces_runner.h\n\nnamespace Catch {\n\n    struct IRunner {\n        virtual ~IRunner();\n        virtual bool aborting() const = 0;\n    };\n}\n\n// end catch_interfaces_runner.h\n\n#ifdef __OBJC__\n// start catch_objc.hpp\n\n#import <objc/runtime.h>\n\n#include <string>\n\n// NB. Any general catch headers included here must be included\n// in catch.hpp first to make sure they are included by the single\n// header for non obj-usage\n\n///////////////////////////////////////////////////////////////////////////////\n// This protocol is really only here for (self) documenting purposes, since\n// all its methods are optional.\n@protocol OcFixture\n\n@optional\n\n-(void) setUp;\n-(void) tearDown;\n\n@end\n\nnamespace Catch {\n\n    class OcMethod : public ITestInvoker {\n\n    public:\n        OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}\n\n        virtual void invoke() const {\n            id obj = [[m_cls alloc] init];\n\n            performOptionalSelector( obj, @selector(setUp)  );\n            performOptionalSelector( obj, m_sel );\n            performOptionalSelector( obj, @selector(tearDown)  );\n\n            arcSafeRelease( obj );\n        }\n    private:\n        virtual ~OcMethod() {}\n\n        Class m_cls;\n        SEL m_sel;\n    };\n\n    namespace Detail{\n\n        inline std::string getAnnotation(   Class cls,\n                                            std::string const& annotationName,\n                                            std::string const& testCaseName ) {\n            NSString* selStr = [[NSString alloc] initWithFormat:@\"Catch_%s_%s\", annotationName.c_str(), testCaseName.c_str()];\n            SEL sel = NSSelectorFromString( selStr );\n            arcSafeRelease( selStr );\n            id value = performOptionalSelector( cls, sel );\n            if( value )\n                return [(NSString*)value UTF8String];\n            return \"\";\n        }\n    }\n\n    inline std::size_t registerTestMethods() {\n        std::size_t noTestMethods = 0;\n        int noClasses = objc_getClassList( nullptr, 0 );\n\n        Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);\n        objc_getClassList( classes, noClasses );\n\n        for( int c = 0; c < noClasses; c++ ) {\n            Class cls = classes[c];\n            {\n                u_int count;\n                Method* methods = class_copyMethodList( cls, &count );\n                for( u_int m = 0; m < count ; m++ ) {\n                    SEL selector = method_getName(methods[m]);\n                    std::string methodName = sel_getName(selector);\n                    if( startsWith( methodName, \"Catch_TestCase_\" ) ) {\n                        std::string testCaseName = methodName.substr( 15 );\n                        std::string name = Detail::getAnnotation( cls, \"Name\", testCaseName );\n                        std::string desc = Detail::getAnnotation( cls, \"Description\", testCaseName );\n                        const char* className = class_getName( cls );\n\n                        getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo(\"\",0) ) );\n                        noTestMethods++;\n                    }\n                }\n                free(methods);\n            }\n        }\n        return noTestMethods;\n    }\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n\n    namespace Matchers {\n        namespace Impl {\n        namespace NSStringMatchers {\n\n            struct StringHolder : MatcherBase<NSString*>{\n                StringHolder( NSString* substr ) : m_substr( [substr copy] ){}\n                StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}\n                StringHolder() {\n                    arcSafeRelease( m_substr );\n                }\n\n                bool match( NSString* str ) const override {\n                    return false;\n                }\n\n                NSString* CATCH_ARC_STRONG m_substr;\n            };\n\n            struct Equals : StringHolder {\n                Equals( NSString* substr ) : StringHolder( substr ){}\n\n                bool match( NSString* str ) const override {\n                    return  (str != nil || m_substr == nil ) &&\n                            [str isEqualToString:m_substr];\n                }\n\n                std::string describe() const override {\n                    return \"equals string: \" + Catch::Detail::stringify( m_substr );\n                }\n            };\n\n            struct Contains : StringHolder {\n                Contains( NSString* substr ) : StringHolder( substr ){}\n\n                bool match( NSString* str ) const override {\n                    return  (str != nil || m_substr == nil ) &&\n                            [str rangeOfString:m_substr].location != NSNotFound;\n                }\n\n                std::string describe() const override {\n                    return \"contains string: \" + Catch::Detail::stringify( m_substr );\n                }\n            };\n\n            struct StartsWith : StringHolder {\n                StartsWith( NSString* substr ) : StringHolder( substr ){}\n\n                bool match( NSString* str ) const override {\n                    return  (str != nil || m_substr == nil ) &&\n                            [str rangeOfString:m_substr].location == 0;\n                }\n\n                std::string describe() const override {\n                    return \"starts with: \" + Catch::Detail::stringify( m_substr );\n                }\n            };\n            struct EndsWith : StringHolder {\n                EndsWith( NSString* substr ) : StringHolder( substr ){}\n\n                bool match( NSString* str ) const override {\n                    return  (str != nil || m_substr == nil ) &&\n                            [str rangeOfString:m_substr].location == [str length] - [m_substr length];\n                }\n\n                std::string describe() const override {\n                    return \"ends with: \" + Catch::Detail::stringify( m_substr );\n                }\n            };\n\n        } // namespace NSStringMatchers\n        } // namespace Impl\n\n        inline Impl::NSStringMatchers::Equals\n            Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }\n\n        inline Impl::NSStringMatchers::Contains\n            Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }\n\n        inline Impl::NSStringMatchers::StartsWith\n            StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }\n\n        inline Impl::NSStringMatchers::EndsWith\n            EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }\n\n    } // namespace Matchers\n\n    using namespace Matchers;\n\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n\n} // namespace Catch\n\n///////////////////////////////////////////////////////////////////////////////\n#define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix\n#define OC_TEST_CASE2( name, desc, uniqueSuffix ) \\\n+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \\\n{ \\\nreturn @ name; \\\n} \\\n+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \\\n{ \\\nreturn @ desc; \\\n} \\\n-(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )\n\n#define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )\n\n// end catch_objc.hpp\n#endif\n\n// Benchmarking needs the externally-facing parts of reporters to work\n#if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n// start catch_external_interfaces.h\n\n// start catch_reporter_bases.hpp\n\n// start catch_interfaces_reporter.h\n\n// start catch_config.hpp\n\n// start catch_test_spec_parser.h\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wpadded\"\n#endif\n\n// start catch_test_spec.h\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wpadded\"\n#endif\n\n// start catch_wildcard_pattern.h\n\nnamespace Catch\n{\n    class WildcardPattern {\n        enum WildcardPosition {\n            NoWildcard = 0,\n            WildcardAtStart = 1,\n            WildcardAtEnd = 2,\n            WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd\n        };\n\n    public:\n\n        WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );\n        virtual ~WildcardPattern() = default;\n        virtual bool matches( std::string const& str ) const;\n\n    private:\n        std::string normaliseString( std::string const& str ) const;\n        CaseSensitive::Choice m_caseSensitivity;\n        WildcardPosition m_wildcard = NoWildcard;\n        std::string m_pattern;\n    };\n}\n\n// end catch_wildcard_pattern.h\n#include <string>\n#include <vector>\n#include <memory>\n\nnamespace Catch {\n\n    struct IConfig;\n\n    class TestSpec {\n        class Pattern {\n        public:\n            explicit Pattern( std::string const& name );\n            virtual ~Pattern();\n            virtual bool matches( TestCaseInfo const& testCase ) const = 0;\n            std::string const& name() const;\n        private:\n            std::string const m_name;\n        };\n        using PatternPtr = std::shared_ptr<Pattern>;\n\n        class NamePattern : public Pattern {\n        public:\n            explicit NamePattern( std::string const& name, std::string const& filterString );\n            bool matches( TestCaseInfo const& testCase ) const override;\n        private:\n            WildcardPattern m_wildcardPattern;\n        };\n\n        class TagPattern : public Pattern {\n        public:\n            explicit TagPattern( std::string const& tag, std::string const& filterString );\n            bool matches( TestCaseInfo const& testCase ) const override;\n        private:\n            std::string m_tag;\n        };\n\n        class ExcludedPattern : public Pattern {\n        public:\n            explicit ExcludedPattern( PatternPtr const& underlyingPattern );\n            bool matches( TestCaseInfo const& testCase ) const override;\n        private:\n            PatternPtr m_underlyingPattern;\n        };\n\n        struct Filter {\n            std::vector<PatternPtr> m_patterns;\n\n            bool matches( TestCaseInfo const& testCase ) const;\n            std::string name() const;\n        };\n\n    public:\n        struct FilterMatch {\n            std::string name;\n            std::vector<TestCase const*> tests;\n        };\n        using Matches = std::vector<FilterMatch>;\n        using vectorStrings = std::vector<std::string>;\n\n        bool hasFilters() const;\n        bool matches( TestCaseInfo const& testCase ) const;\n        Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;\n        const vectorStrings & getInvalidArgs() const;\n\n    private:\n        std::vector<Filter> m_filters;\n        std::vector<std::string> m_invalidArgs;\n        friend class TestSpecParser;\n    };\n}\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n// end catch_test_spec.h\n// start catch_interfaces_tag_alias_registry.h\n\n#include <string>\n\nnamespace Catch {\n\n    struct TagAlias;\n\n    struct ITagAliasRegistry {\n        virtual ~ITagAliasRegistry();\n        // Nullptr if not present\n        virtual TagAlias const* find( std::string const& alias ) const = 0;\n        virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;\n\n        static ITagAliasRegistry const& get();\n    };\n\n} // end namespace Catch\n\n// end catch_interfaces_tag_alias_registry.h\nnamespace Catch {\n\n    class TestSpecParser {\n        enum Mode{ None, Name, QuotedName, Tag, EscapedName };\n        Mode m_mode = None;\n        Mode lastMode = None;\n        bool m_exclusion = false;\n        std::size_t m_pos = 0;\n        std::size_t m_realPatternPos = 0;\n        std::string m_arg;\n        std::string m_substring;\n        std::string m_patternName;\n        std::vector<std::size_t> m_escapeChars;\n        TestSpec::Filter m_currentFilter;\n        TestSpec m_testSpec;\n        ITagAliasRegistry const* m_tagAliases = nullptr;\n\n    public:\n        TestSpecParser( ITagAliasRegistry const& tagAliases );\n\n        TestSpecParser& parse( std::string const& arg );\n        TestSpec testSpec();\n\n    private:\n        bool visitChar( char c );\n        void startNewMode( Mode mode );\n        bool processNoneChar( char c );\n        void processNameChar( char c );\n        bool processOtherChar( char c );\n        void endMode();\n        void escape();\n        bool isControlChar( char c ) const;\n        void saveLastMode();\n        void revertBackToLastMode();\n        void addFilter();\n        bool separate();\n\n        // Handles common preprocessing of the pattern for name/tag patterns\n        std::string preprocessPattern();\n        // Adds the current pattern as a test name\n        void addNamePattern();\n        // Adds the current pattern as a tag\n        void addTagPattern();\n\n        inline void addCharToPattern(char c) {\n            m_substring += c;\n            m_patternName += c;\n            m_realPatternPos++;\n        }\n\n    };\n    TestSpec parseTestSpec( std::string const& arg );\n\n} // namespace Catch\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n// end catch_test_spec_parser.h\n// Libstdc++ doesn't like incomplete classes for unique_ptr\n\n#include <memory>\n#include <vector>\n#include <string>\n\n#ifndef CATCH_CONFIG_CONSOLE_WIDTH\n#define CATCH_CONFIG_CONSOLE_WIDTH 80\n#endif\n\nnamespace Catch {\n\n    struct IStream;\n\n    struct ConfigData {\n        bool listTests = false;\n        bool listTags = false;\n        bool listReporters = false;\n        bool listTestNamesOnly = false;\n\n        bool showSuccessfulTests = false;\n        bool shouldDebugBreak = false;\n        bool noThrow = false;\n        bool showHelp = false;\n        bool showInvisibles = false;\n        bool filenamesAsTags = false;\n        bool libIdentify = false;\n\n        int abortAfter = -1;\n        unsigned int rngSeed = 0;\n\n        bool benchmarkNoAnalysis = false;\n        unsigned int benchmarkSamples = 100;\n        double benchmarkConfidenceInterval = 0.95;\n        unsigned int benchmarkResamples = 100000;\n\n        Verbosity verbosity = Verbosity::Normal;\n        WarnAbout::What warnings = WarnAbout::Nothing;\n        ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;\n        RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;\n        UseColour::YesOrNo useColour = UseColour::Auto;\n        WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;\n\n        std::string outputFilename;\n        std::string name;\n        std::string processName;\n#ifndef CATCH_CONFIG_DEFAULT_REPORTER\n#define CATCH_CONFIG_DEFAULT_REPORTER \"console\"\n#endif\n        std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;\n#undef CATCH_CONFIG_DEFAULT_REPORTER\n\n        std::vector<std::string> testsOrTags;\n        std::vector<std::string> sectionsToRun;\n    };\n\n    class Config : public IConfig {\n    public:\n\n        Config() = default;\n        Config( ConfigData const& data );\n        virtual ~Config() = default;\n\n        std::string const& getFilename() const;\n\n        bool listTests() const;\n        bool listTestNamesOnly() const;\n        bool listTags() const;\n        bool listReporters() const;\n\n        std::string getProcessName() const;\n        std::string const& getReporterName() const;\n\n        std::vector<std::string> const& getTestsOrTags() const override;\n        std::vector<std::string> const& getSectionsToRun() const override;\n\n        TestSpec const& testSpec() const override;\n        bool hasTestFilters() const override;\n\n        bool showHelp() const;\n\n        // IConfig interface\n        bool allowThrows() const override;\n        std::ostream& stream() const override;\n        std::string name() const override;\n        bool includeSuccessfulResults() const override;\n        bool warnAboutMissingAssertions() const override;\n        bool warnAboutNoTests() const override;\n        ShowDurations::OrNot showDurations() const override;\n        RunTests::InWhatOrder runOrder() const override;\n        unsigned int rngSeed() const override;\n        UseColour::YesOrNo useColour() const override;\n        bool shouldDebugBreak() const override;\n        int abortAfter() const override;\n        bool showInvisibles() const override;\n        Verbosity verbosity() const override;\n        bool benchmarkNoAnalysis() const override;\n        int benchmarkSamples() const override;\n        double benchmarkConfidenceInterval() const override;\n        unsigned int benchmarkResamples() const override;\n\n    private:\n\n        IStream const* openStream();\n        ConfigData m_data;\n\n        std::unique_ptr<IStream const> m_stream;\n        TestSpec m_testSpec;\n        bool m_hasTestFilters = false;\n    };\n\n} // end namespace Catch\n\n// end catch_config.hpp\n// start catch_assertionresult.h\n\n#include <string>\n\nnamespace Catch {\n\n    struct AssertionResultData\n    {\n        AssertionResultData() = delete;\n\n        AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );\n\n        std::string message;\n        mutable std::string reconstructedExpression;\n        LazyExpression lazyExpression;\n        ResultWas::OfType resultType;\n\n        std::string reconstructExpression() const;\n    };\n\n    class AssertionResult {\n    public:\n        AssertionResult() = delete;\n        AssertionResult( AssertionInfo const& info, AssertionResultData const& data );\n\n        bool isOk() const;\n        bool succeeded() const;\n        ResultWas::OfType getResultType() const;\n        bool hasExpression() const;\n        bool hasMessage() const;\n        std::string getExpression() const;\n        std::string getExpressionInMacro() const;\n        bool hasExpandedExpression() const;\n        std::string getExpandedExpression() const;\n        std::string getMessage() const;\n        SourceLineInfo getSourceInfo() const;\n        StringRef getTestMacroName() const;\n\n    //protected:\n        AssertionInfo m_info;\n        AssertionResultData m_resultData;\n    };\n\n} // end namespace Catch\n\n// end catch_assertionresult.h\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n// start catch_estimate.hpp\n\n // Statistics estimates\n\n\nnamespace Catch {\n    namespace Benchmark {\n        template <typename Duration>\n        struct Estimate {\n            Duration point;\n            Duration lower_bound;\n            Duration upper_bound;\n            double confidence_interval;\n\n            template <typename Duration2>\n            operator Estimate<Duration2>() const {\n                return { point, lower_bound, upper_bound, confidence_interval };\n            }\n        };\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_estimate.hpp\n// start catch_outlier_classification.hpp\n\n// Outlier information\n\nnamespace Catch {\n    namespace Benchmark {\n        struct OutlierClassification {\n            int samples_seen = 0;\n            int low_severe = 0;     // more than 3 times IQR below Q1\n            int low_mild = 0;       // 1.5 to 3 times IQR below Q1\n            int high_mild = 0;      // 1.5 to 3 times IQR above Q3\n            int high_severe = 0;    // more than 3 times IQR above Q3\n\n            int total() const {\n                return low_severe + low_mild + high_mild + high_severe;\n            }\n        };\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_outlier_classification.hpp\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n#include <string>\n#include <iosfwd>\n#include <map>\n#include <set>\n#include <memory>\n#include <algorithm>\n\nnamespace Catch {\n\n    struct ReporterConfig {\n        explicit ReporterConfig( IConfigPtr const& _fullConfig );\n\n        ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );\n\n        std::ostream& stream() const;\n        IConfigPtr fullConfig() const;\n\n    private:\n        std::ostream* m_stream;\n        IConfigPtr m_fullConfig;\n    };\n\n    struct ReporterPreferences {\n        bool shouldRedirectStdOut = false;\n        bool shouldReportAllAssertions = false;\n    };\n\n    template<typename T>\n    struct LazyStat : Option<T> {\n        LazyStat& operator=( T const& _value ) {\n            Option<T>::operator=( _value );\n            used = false;\n            return *this;\n        }\n        void reset() {\n            Option<T>::reset();\n            used = false;\n        }\n        bool used = false;\n    };\n\n    struct TestRunInfo {\n        TestRunInfo( std::string const& _name );\n        std::string name;\n    };\n    struct GroupInfo {\n        GroupInfo(  std::string const& _name,\n                    std::size_t _groupIndex,\n                    std::size_t _groupsCount );\n\n        std::string name;\n        std::size_t groupIndex;\n        std::size_t groupsCounts;\n    };\n\n    struct AssertionStats {\n        AssertionStats( AssertionResult const& _assertionResult,\n                        std::vector<MessageInfo> const& _infoMessages,\n                        Totals const& _totals );\n\n        AssertionStats( AssertionStats const& )              = default;\n        AssertionStats( AssertionStats && )                  = default;\n        AssertionStats& operator = ( AssertionStats const& ) = delete;\n        AssertionStats& operator = ( AssertionStats && )     = delete;\n        virtual ~AssertionStats();\n\n        AssertionResult assertionResult;\n        std::vector<MessageInfo> infoMessages;\n        Totals totals;\n    };\n\n    struct SectionStats {\n        SectionStats(   SectionInfo const& _sectionInfo,\n                        Counts const& _assertions,\n                        double _durationInSeconds,\n                        bool _missingAssertions );\n        SectionStats( SectionStats const& )              = default;\n        SectionStats( SectionStats && )                  = default;\n        SectionStats& operator = ( SectionStats const& ) = default;\n        SectionStats& operator = ( SectionStats && )     = default;\n        virtual ~SectionStats();\n\n        SectionInfo sectionInfo;\n        Counts assertions;\n        double durationInSeconds;\n        bool missingAssertions;\n    };\n\n    struct TestCaseStats {\n        TestCaseStats(  TestCaseInfo const& _testInfo,\n                        Totals const& _totals,\n                        std::string const& _stdOut,\n                        std::string const& _stdErr,\n                        bool _aborting );\n\n        TestCaseStats( TestCaseStats const& )              = default;\n        TestCaseStats( TestCaseStats && )                  = default;\n        TestCaseStats& operator = ( TestCaseStats const& ) = default;\n        TestCaseStats& operator = ( TestCaseStats && )     = default;\n        virtual ~TestCaseStats();\n\n        TestCaseInfo testInfo;\n        Totals totals;\n        std::string stdOut;\n        std::string stdErr;\n        bool aborting;\n    };\n\n    struct TestGroupStats {\n        TestGroupStats( GroupInfo const& _groupInfo,\n                        Totals const& _totals,\n                        bool _aborting );\n        TestGroupStats( GroupInfo const& _groupInfo );\n\n        TestGroupStats( TestGroupStats const& )              = default;\n        TestGroupStats( TestGroupStats && )                  = default;\n        TestGroupStats& operator = ( TestGroupStats const& ) = default;\n        TestGroupStats& operator = ( TestGroupStats && )     = default;\n        virtual ~TestGroupStats();\n\n        GroupInfo groupInfo;\n        Totals totals;\n        bool aborting;\n    };\n\n    struct TestRunStats {\n        TestRunStats(   TestRunInfo const& _runInfo,\n                        Totals const& _totals,\n                        bool _aborting );\n\n        TestRunStats( TestRunStats const& )              = default;\n        TestRunStats( TestRunStats && )                  = default;\n        TestRunStats& operator = ( TestRunStats const& ) = default;\n        TestRunStats& operator = ( TestRunStats && )     = default;\n        virtual ~TestRunStats();\n\n        TestRunInfo runInfo;\n        Totals totals;\n        bool aborting;\n    };\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n    struct BenchmarkInfo {\n        std::string name;\n        double estimatedDuration;\n        int iterations;\n        int samples;\n        unsigned int resamples;\n        double clockResolution;\n        double clockCost;\n    };\n\n    template <class Duration>\n    struct BenchmarkStats {\n        BenchmarkInfo info;\n\n        std::vector<Duration> samples;\n        Benchmark::Estimate<Duration> mean;\n        Benchmark::Estimate<Duration> standardDeviation;\n        Benchmark::OutlierClassification outliers;\n        double outlierVariance;\n\n        template <typename Duration2>\n        operator BenchmarkStats<Duration2>() const {\n            std::vector<Duration2> samples2;\n            samples2.reserve(samples.size());\n            std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });\n            return {\n                info,\n                std::move(samples2),\n                mean,\n                standardDeviation,\n                outliers,\n                outlierVariance,\n            };\n        }\n    };\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n    struct IStreamingReporter {\n        virtual ~IStreamingReporter() = default;\n\n        // Implementing class must also provide the following static methods:\n        // static std::string getDescription();\n        // static std::set<Verbosity> getSupportedVerbosities()\n\n        virtual ReporterPreferences getPreferences() const = 0;\n\n        virtual void noMatchingTestCases( std::string const& spec ) = 0;\n\n        virtual void reportInvalidArguments(std::string const&) {}\n\n        virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;\n        virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;\n\n        virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;\n        virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n        virtual void benchmarkPreparing( std::string const& ) {}\n        virtual void benchmarkStarting( BenchmarkInfo const& ) {}\n        virtual void benchmarkEnded( BenchmarkStats<> const& ) {}\n        virtual void benchmarkFailed( std::string const& ) {}\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n        virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;\n\n        // The return value indicates if the messages buffer should be cleared:\n        virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;\n\n        virtual void sectionEnded( SectionStats const& sectionStats ) = 0;\n        virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;\n        virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;\n        virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;\n\n        virtual void skipTest( TestCaseInfo const& testInfo ) = 0;\n\n        // Default empty implementation provided\n        virtual void fatalErrorEncountered( StringRef name );\n\n        virtual bool isMulti() const;\n    };\n    using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;\n\n    struct IReporterFactory {\n        virtual ~IReporterFactory();\n        virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;\n        virtual std::string getDescription() const = 0;\n    };\n    using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;\n\n    struct IReporterRegistry {\n        using FactoryMap = std::map<std::string, IReporterFactoryPtr>;\n        using Listeners = std::vector<IReporterFactoryPtr>;\n\n        virtual ~IReporterRegistry();\n        virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;\n        virtual FactoryMap const& getFactories() const = 0;\n        virtual Listeners const& getListeners() const = 0;\n    };\n\n} // end namespace Catch\n\n// end catch_interfaces_reporter.h\n#include <algorithm>\n#include <cstring>\n#include <cfloat>\n#include <cstdio>\n#include <cassert>\n#include <memory>\n#include <ostream>\n\nnamespace Catch {\n    void prepareExpandedExpression(AssertionResult& result);\n\n    // Returns double formatted as %.3f (format expected on output)\n    std::string getFormattedDuration( double duration );\n\n    std::string serializeFilters( std::vector<std::string> const& container );\n\n    template<typename DerivedT>\n    struct StreamingReporterBase : IStreamingReporter {\n\n        StreamingReporterBase( ReporterConfig const& _config )\n        :   m_config( _config.fullConfig() ),\n            stream( _config.stream() )\n        {\n            m_reporterPrefs.shouldRedirectStdOut = false;\n            if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )\n                CATCH_ERROR( \"Verbosity level not supported by this reporter\" );\n        }\n\n        ReporterPreferences getPreferences() const override {\n            return m_reporterPrefs;\n        }\n\n        static std::set<Verbosity> getSupportedVerbosities() {\n            return { Verbosity::Normal };\n        }\n\n        ~StreamingReporterBase() override = default;\n\n        void noMatchingTestCases(std::string const&) override {}\n\n        void reportInvalidArguments(std::string const&) override {}\n\n        void testRunStarting(TestRunInfo const& _testRunInfo) override {\n            currentTestRunInfo = _testRunInfo;\n        }\n\n        void testGroupStarting(GroupInfo const& _groupInfo) override {\n            currentGroupInfo = _groupInfo;\n        }\n\n        void testCaseStarting(TestCaseInfo const& _testInfo) override  {\n            currentTestCaseInfo = _testInfo;\n        }\n        void sectionStarting(SectionInfo const& _sectionInfo) override {\n            m_sectionStack.push_back(_sectionInfo);\n        }\n\n        void sectionEnded(SectionStats const& /* _sectionStats */) override {\n            m_sectionStack.pop_back();\n        }\n        void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {\n            currentTestCaseInfo.reset();\n        }\n        void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {\n            currentGroupInfo.reset();\n        }\n        void testRunEnded(TestRunStats const& /* _testRunStats */) override {\n            currentTestCaseInfo.reset();\n            currentGroupInfo.reset();\n            currentTestRunInfo.reset();\n        }\n\n        void skipTest(TestCaseInfo const&) override {\n            // Don't do anything with this by default.\n            // It can optionally be overridden in the derived class.\n        }\n\n        IConfigPtr m_config;\n        std::ostream& stream;\n\n        LazyStat<TestRunInfo> currentTestRunInfo;\n        LazyStat<GroupInfo> currentGroupInfo;\n        LazyStat<TestCaseInfo> currentTestCaseInfo;\n\n        std::vector<SectionInfo> m_sectionStack;\n        ReporterPreferences m_reporterPrefs;\n    };\n\n    template<typename DerivedT>\n    struct CumulativeReporterBase : IStreamingReporter {\n        template<typename T, typename ChildNodeT>\n        struct Node {\n            explicit Node( T const& _value ) : value( _value ) {}\n            virtual ~Node() {}\n\n            using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;\n            T value;\n            ChildNodes children;\n        };\n        struct SectionNode {\n            explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}\n            virtual ~SectionNode() = default;\n\n            bool operator == (SectionNode const& other) const {\n                return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;\n            }\n            bool operator == (std::shared_ptr<SectionNode> const& other) const {\n                return operator==(*other);\n            }\n\n            SectionStats stats;\n            using ChildSections = std::vector<std::shared_ptr<SectionNode>>;\n            using Assertions = std::vector<AssertionStats>;\n            ChildSections childSections;\n            Assertions assertions;\n            std::string stdOut;\n            std::string stdErr;\n        };\n\n        struct BySectionInfo {\n            BySectionInfo( SectionInfo const& other ) : m_other( other ) {}\n            BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}\n            bool operator() (std::shared_ptr<SectionNode> const& node) const {\n                return ((node->stats.sectionInfo.name == m_other.name) &&\n                        (node->stats.sectionInfo.lineInfo == m_other.lineInfo));\n            }\n            void operator=(BySectionInfo const&) = delete;\n\n        private:\n            SectionInfo const& m_other;\n        };\n\n        using TestCaseNode = Node<TestCaseStats, SectionNode>;\n        using TestGroupNode = Node<TestGroupStats, TestCaseNode>;\n        using TestRunNode = Node<TestRunStats, TestGroupNode>;\n\n        CumulativeReporterBase( ReporterConfig const& _config )\n        :   m_config( _config.fullConfig() ),\n            stream( _config.stream() )\n        {\n            m_reporterPrefs.shouldRedirectStdOut = false;\n            if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )\n                CATCH_ERROR( \"Verbosity level not supported by this reporter\" );\n        }\n        ~CumulativeReporterBase() override = default;\n\n        ReporterPreferences getPreferences() const override {\n            return m_reporterPrefs;\n        }\n\n        static std::set<Verbosity> getSupportedVerbosities() {\n            return { Verbosity::Normal };\n        }\n\n        void testRunStarting( TestRunInfo const& ) override {}\n        void testGroupStarting( GroupInfo const& ) override {}\n\n        void testCaseStarting( TestCaseInfo const& ) override {}\n\n        void sectionStarting( SectionInfo const& sectionInfo ) override {\n            SectionStats incompleteStats( sectionInfo, Counts(), 0, false );\n            std::shared_ptr<SectionNode> node;\n            if( m_sectionStack.empty() ) {\n                if( !m_rootSection )\n                    m_rootSection = std::make_shared<SectionNode>( incompleteStats );\n                node = m_rootSection;\n            }\n            else {\n                SectionNode& parentNode = *m_sectionStack.back();\n                auto it =\n                    std::find_if(   parentNode.childSections.begin(),\n                                    parentNode.childSections.end(),\n                                    BySectionInfo( sectionInfo ) );\n                if( it == parentNode.childSections.end() ) {\n                    node = std::make_shared<SectionNode>( incompleteStats );\n                    parentNode.childSections.push_back( node );\n                }\n                else\n                    node = *it;\n            }\n            m_sectionStack.push_back( node );\n            m_deepestSection = std::move(node);\n        }\n\n        void assertionStarting(AssertionInfo const&) override {}\n\n        bool assertionEnded(AssertionStats const& assertionStats) override {\n            assert(!m_sectionStack.empty());\n            // AssertionResult holds a pointer to a temporary DecomposedExpression,\n            // which getExpandedExpression() calls to build the expression string.\n            // Our section stack copy of the assertionResult will likely outlive the\n            // temporary, so it must be expanded or discarded now to avoid calling\n            // a destroyed object later.\n            prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );\n            SectionNode& sectionNode = *m_sectionStack.back();\n            sectionNode.assertions.push_back(assertionStats);\n            return true;\n        }\n        void sectionEnded(SectionStats const& sectionStats) override {\n            assert(!m_sectionStack.empty());\n            SectionNode& node = *m_sectionStack.back();\n            node.stats = sectionStats;\n            m_sectionStack.pop_back();\n        }\n        void testCaseEnded(TestCaseStats const& testCaseStats) override {\n            auto node = std::make_shared<TestCaseNode>(testCaseStats);\n            assert(m_sectionStack.size() == 0);\n            node->children.push_back(m_rootSection);\n            m_testCases.push_back(node);\n            m_rootSection.reset();\n\n            assert(m_deepestSection);\n            m_deepestSection->stdOut = testCaseStats.stdOut;\n            m_deepestSection->stdErr = testCaseStats.stdErr;\n        }\n        void testGroupEnded(TestGroupStats const& testGroupStats) override {\n            auto node = std::make_shared<TestGroupNode>(testGroupStats);\n            node->children.swap(m_testCases);\n            m_testGroups.push_back(node);\n        }\n        void testRunEnded(TestRunStats const& testRunStats) override {\n            auto node = std::make_shared<TestRunNode>(testRunStats);\n            node->children.swap(m_testGroups);\n            m_testRuns.push_back(node);\n            testRunEndedCumulative();\n        }\n        virtual void testRunEndedCumulative() = 0;\n\n        void skipTest(TestCaseInfo const&) override {}\n\n        IConfigPtr m_config;\n        std::ostream& stream;\n        std::vector<AssertionStats> m_assertions;\n        std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;\n        std::vector<std::shared_ptr<TestCaseNode>> m_testCases;\n        std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;\n\n        std::vector<std::shared_ptr<TestRunNode>> m_testRuns;\n\n        std::shared_ptr<SectionNode> m_rootSection;\n        std::shared_ptr<SectionNode> m_deepestSection;\n        std::vector<std::shared_ptr<SectionNode>> m_sectionStack;\n        ReporterPreferences m_reporterPrefs;\n    };\n\n    template<char C>\n    char const* getLineOfChars() {\n        static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};\n        if( !*line ) {\n            std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );\n            line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;\n        }\n        return line;\n    }\n\n    struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {\n        TestEventListenerBase( ReporterConfig const& _config );\n\n        static std::set<Verbosity> getSupportedVerbosities();\n\n        void assertionStarting(AssertionInfo const&) override;\n        bool assertionEnded(AssertionStats const&) override;\n    };\n\n} // end namespace Catch\n\n// end catch_reporter_bases.hpp\n// start catch_console_colour.h\n\nnamespace Catch {\n\n    struct Colour {\n        enum Code {\n            None = 0,\n\n            White,\n            Red,\n            Green,\n            Blue,\n            Cyan,\n            Yellow,\n            Grey,\n\n            Bright = 0x10,\n\n            BrightRed = Bright | Red,\n            BrightGreen = Bright | Green,\n            LightGrey = Bright | Grey,\n            BrightWhite = Bright | White,\n            BrightYellow = Bright | Yellow,\n\n            // By intention\n            FileName = LightGrey,\n            Warning = BrightYellow,\n            ResultError = BrightRed,\n            ResultSuccess = BrightGreen,\n            ResultExpectedFailure = Warning,\n\n            Error = BrightRed,\n            Success = Green,\n\n            OriginalExpression = Cyan,\n            ReconstructedExpression = BrightYellow,\n\n            SecondaryText = LightGrey,\n            Headers = White\n        };\n\n        // Use constructed object for RAII guard\n        Colour( Code _colourCode );\n        Colour( Colour&& other ) noexcept;\n        Colour& operator=( Colour&& other ) noexcept;\n        ~Colour();\n\n        // Use static method for one-shot changes\n        static void use( Code _colourCode );\n\n    private:\n        bool m_moved = false;\n    };\n\n    std::ostream& operator << ( std::ostream& os, Colour const& );\n\n} // end namespace Catch\n\n// end catch_console_colour.h\n// start catch_reporter_registrars.hpp\n\n\nnamespace Catch {\n\n    template<typename T>\n    class ReporterRegistrar {\n\n        class ReporterFactory : public IReporterFactory {\n\n            IStreamingReporterPtr create( ReporterConfig const& config ) const override {\n                return std::unique_ptr<T>( new T( config ) );\n            }\n\n            std::string getDescription() const override {\n                return T::getDescription();\n            }\n        };\n\n    public:\n\n        explicit ReporterRegistrar( std::string const& name ) {\n            getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );\n        }\n    };\n\n    template<typename T>\n    class ListenerRegistrar {\n\n        class ListenerFactory : public IReporterFactory {\n\n            IStreamingReporterPtr create( ReporterConfig const& config ) const override {\n                return std::unique_ptr<T>( new T( config ) );\n            }\n            std::string getDescription() const override {\n                return std::string();\n            }\n        };\n\n    public:\n\n        ListenerRegistrar() {\n            getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );\n        }\n    };\n}\n\n#if !defined(CATCH_CONFIG_DISABLE)\n\n#define CATCH_REGISTER_REPORTER( name, reporterType ) \\\n    CATCH_INTERNAL_START_WARNINGS_SUPPRESSION         \\\n    CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS          \\\n    namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \\\n    CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION\n\n#define CATCH_REGISTER_LISTENER( listenerType ) \\\n    CATCH_INTERNAL_START_WARNINGS_SUPPRESSION   \\\n    CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS    \\\n    namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \\\n    CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION\n#else // CATCH_CONFIG_DISABLE\n\n#define CATCH_REGISTER_REPORTER(name, reporterType)\n#define CATCH_REGISTER_LISTENER(listenerType)\n\n#endif // CATCH_CONFIG_DISABLE\n\n// end catch_reporter_registrars.hpp\n// Allow users to base their work off existing reporters\n// start catch_reporter_compact.h\n\nnamespace Catch {\n\n    struct CompactReporter : StreamingReporterBase<CompactReporter> {\n\n        using StreamingReporterBase::StreamingReporterBase;\n\n        ~CompactReporter() override;\n\n        static std::string getDescription();\n\n        ReporterPreferences getPreferences() const override;\n\n        void noMatchingTestCases(std::string const& spec) override;\n\n        void assertionStarting(AssertionInfo const&) override;\n\n        bool assertionEnded(AssertionStats const& _assertionStats) override;\n\n        void sectionEnded(SectionStats const& _sectionStats) override;\n\n        void testRunEnded(TestRunStats const& _testRunStats) override;\n\n    };\n\n} // end namespace Catch\n\n// end catch_reporter_compact.h\n// start catch_reporter_console.h\n\n#if defined(_MSC_VER)\n#pragma warning(push)\n#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch\n                              // Note that 4062 (not all labels are handled\n                              // and default is missing) is enabled\n#endif\n\nnamespace Catch {\n    // Fwd decls\n    struct SummaryColumn;\n    class TablePrinter;\n\n    struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {\n        std::unique_ptr<TablePrinter> m_tablePrinter;\n\n        ConsoleReporter(ReporterConfig const& config);\n        ~ConsoleReporter() override;\n        static std::string getDescription();\n\n        void noMatchingTestCases(std::string const& spec) override;\n\n        void reportInvalidArguments(std::string const&arg) override;\n\n        void assertionStarting(AssertionInfo const&) override;\n\n        bool assertionEnded(AssertionStats const& _assertionStats) override;\n\n        void sectionStarting(SectionInfo const& _sectionInfo) override;\n        void sectionEnded(SectionStats const& _sectionStats) override;\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n        void benchmarkPreparing(std::string const& name) override;\n        void benchmarkStarting(BenchmarkInfo const& info) override;\n        void benchmarkEnded(BenchmarkStats<> const& stats) override;\n        void benchmarkFailed(std::string const& error) override;\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n        void testCaseEnded(TestCaseStats const& _testCaseStats) override;\n        void testGroupEnded(TestGroupStats const& _testGroupStats) override;\n        void testRunEnded(TestRunStats const& _testRunStats) override;\n        void testRunStarting(TestRunInfo const& _testRunInfo) override;\n    private:\n\n        void lazyPrint();\n\n        void lazyPrintWithoutClosingBenchmarkTable();\n        void lazyPrintRunInfo();\n        void lazyPrintGroupInfo();\n        void printTestCaseAndSectionHeader();\n\n        void printClosedHeader(std::string const& _name);\n        void printOpenHeader(std::string const& _name);\n\n        // if string has a : in first line will set indent to follow it on\n        // subsequent lines\n        void printHeaderString(std::string const& _string, std::size_t indent = 0);\n\n        void printTotals(Totals const& totals);\n        void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);\n\n        void printTotalsDivider(Totals const& totals);\n        void printSummaryDivider();\n        void printTestFilters();\n\n    private:\n        bool m_headerPrinted = false;\n    };\n\n} // end namespace Catch\n\n#if defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n\n// end catch_reporter_console.h\n// start catch_reporter_junit.h\n\n// start catch_xmlwriter.h\n\n#include <vector>\n\nnamespace Catch {\n    enum class XmlFormatting {\n        None = 0x00,\n        Indent = 0x01,\n        Newline = 0x02,\n    };\n\n    XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);\n    XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);\n\n    class XmlEncode {\n    public:\n        enum ForWhat { ForTextNodes, ForAttributes };\n\n        XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );\n\n        void encodeTo( std::ostream& os ) const;\n\n        friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );\n\n    private:\n        std::string m_str;\n        ForWhat m_forWhat;\n    };\n\n    class XmlWriter {\n    public:\n\n        class ScopedElement {\n        public:\n            ScopedElement( XmlWriter* writer, XmlFormatting fmt );\n\n            ScopedElement( ScopedElement&& other ) noexcept;\n            ScopedElement& operator=( ScopedElement&& other ) noexcept;\n\n            ~ScopedElement();\n\n            ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );\n\n            template<typename T>\n            ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {\n                m_writer->writeAttribute( name, attribute );\n                return *this;\n            }\n\n        private:\n            mutable XmlWriter* m_writer = nullptr;\n            XmlFormatting m_fmt;\n        };\n\n        XmlWriter( std::ostream& os = Catch::cout() );\n        ~XmlWriter();\n\n        XmlWriter( XmlWriter const& ) = delete;\n        XmlWriter& operator=( XmlWriter const& ) = delete;\n\n        XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);\n\n        ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);\n\n        XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);\n\n        XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );\n\n        XmlWriter& writeAttribute( std::string const& name, bool attribute );\n\n        template<typename T>\n        XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {\n            ReusableStringStream rss;\n            rss << attribute;\n            return writeAttribute( name, rss.str() );\n        }\n\n        XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);\n\n        XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);\n\n        void writeStylesheetRef( std::string const& url );\n\n        XmlWriter& writeBlankLine();\n\n        void ensureTagClosed();\n\n    private:\n\n        void applyFormatting(XmlFormatting fmt);\n\n        void writeDeclaration();\n\n        void newlineIfNecessary();\n\n        bool m_tagIsOpen = false;\n        bool m_needsNewline = false;\n        std::vector<std::string> m_tags;\n        std::string m_indent;\n        std::ostream& m_os;\n    };\n\n}\n\n// end catch_xmlwriter.h\nnamespace Catch {\n\n    class JunitReporter : public CumulativeReporterBase<JunitReporter> {\n    public:\n        JunitReporter(ReporterConfig const& _config);\n\n        ~JunitReporter() override;\n\n        static std::string getDescription();\n\n        void noMatchingTestCases(std::string const& /*spec*/) override;\n\n        void testRunStarting(TestRunInfo const& runInfo) override;\n\n        void testGroupStarting(GroupInfo const& groupInfo) override;\n\n        void testCaseStarting(TestCaseInfo const& testCaseInfo) override;\n        bool assertionEnded(AssertionStats const& assertionStats) override;\n\n        void testCaseEnded(TestCaseStats const& testCaseStats) override;\n\n        void testGroupEnded(TestGroupStats const& testGroupStats) override;\n\n        void testRunEndedCumulative() override;\n\n        void writeGroup(TestGroupNode const& groupNode, double suiteTime);\n\n        void writeTestCase(TestCaseNode const& testCaseNode);\n\n        void writeSection(std::string const& className,\n                          std::string const& rootName,\n                          SectionNode const& sectionNode);\n\n        void writeAssertions(SectionNode const& sectionNode);\n        void writeAssertion(AssertionStats const& stats);\n\n        XmlWriter xml;\n        Timer suiteTimer;\n        std::string stdOutForSuite;\n        std::string stdErrForSuite;\n        unsigned int unexpectedExceptions = 0;\n        bool m_okToFail = false;\n    };\n\n} // end namespace Catch\n\n// end catch_reporter_junit.h\n// start catch_reporter_xml.h\n\nnamespace Catch {\n    class XmlReporter : public StreamingReporterBase<XmlReporter> {\n    public:\n        XmlReporter(ReporterConfig const& _config);\n\n        ~XmlReporter() override;\n\n        static std::string getDescription();\n\n        virtual std::string getStylesheetRef() const;\n\n        void writeSourceInfo(SourceLineInfo const& sourceInfo);\n\n    public: // StreamingReporterBase\n\n        void noMatchingTestCases(std::string const& s) override;\n\n        void testRunStarting(TestRunInfo const& testInfo) override;\n\n        void testGroupStarting(GroupInfo const& groupInfo) override;\n\n        void testCaseStarting(TestCaseInfo const& testInfo) override;\n\n        void sectionStarting(SectionInfo const& sectionInfo) override;\n\n        void assertionStarting(AssertionInfo const&) override;\n\n        bool assertionEnded(AssertionStats const& assertionStats) override;\n\n        void sectionEnded(SectionStats const& sectionStats) override;\n\n        void testCaseEnded(TestCaseStats const& testCaseStats) override;\n\n        void testGroupEnded(TestGroupStats const& testGroupStats) override;\n\n        void testRunEnded(TestRunStats const& testRunStats) override;\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n        void benchmarkPreparing(std::string const& name) override;\n        void benchmarkStarting(BenchmarkInfo const&) override;\n        void benchmarkEnded(BenchmarkStats<> const&) override;\n        void benchmarkFailed(std::string const&) override;\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n    private:\n        Timer m_testCaseTimer;\n        XmlWriter m_xml;\n        int m_sectionDepth = 0;\n    };\n\n} // end namespace Catch\n\n// end catch_reporter_xml.h\n\n// end catch_external_interfaces.h\n#endif\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n// start catch_benchmarking_all.hpp\n\n// A proxy header that includes all of the benchmarking headers to allow\n// concise include of the benchmarking features. You should prefer the\n// individual includes in standard use.\n\n// start catch_benchmark.hpp\n\n // Benchmark\n\n// start catch_chronometer.hpp\n\n// User-facing chronometer\n\n\n// start catch_clock.hpp\n\n// Clocks\n\n\n#include <chrono>\n#include <ratio>\n\nnamespace Catch {\n    namespace Benchmark {\n        template <typename Clock>\n        using ClockDuration = typename Clock::duration;\n        template <typename Clock>\n        using FloatDuration = std::chrono::duration<double, typename Clock::period>;\n\n        template <typename Clock>\n        using TimePoint = typename Clock::time_point;\n\n        using default_clock = std::chrono::steady_clock;\n\n        template <typename Clock>\n        struct now {\n            TimePoint<Clock> operator()() const {\n                return Clock::now();\n            }\n        };\n\n        using fp_seconds = std::chrono::duration<double, std::ratio<1>>;\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_clock.hpp\n// start catch_optimizer.hpp\n\n // Hinting the optimizer\n\n\n#if defined(_MSC_VER)\n#   include <atomic> // atomic_thread_fence\n#endif\n\nnamespace Catch {\n    namespace Benchmark {\n#if defined(__GNUC__) || defined(__clang__)\n        template <typename T>\n        inline void keep_memory(T* p) {\n            asm volatile(\"\" : : \"g\"(p) : \"memory\");\n        }\n        inline void keep_memory() {\n            asm volatile(\"\" : : : \"memory\");\n        }\n\n        namespace Detail {\n            inline void optimizer_barrier() { keep_memory(); }\n        } // namespace Detail\n#elif defined(_MSC_VER)\n\n#pragma optimize(\"\", off)\n        template <typename T>\n        inline void keep_memory(T* p) {\n            // thanks @milleniumbug\n            *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);\n        }\n        // TODO equivalent keep_memory()\n#pragma optimize(\"\", on)\n\n        namespace Detail {\n            inline void optimizer_barrier() {\n                std::atomic_thread_fence(std::memory_order_seq_cst);\n            }\n        } // namespace Detail\n\n#endif\n\n        template <typename T>\n        inline void deoptimize_value(T&& x) {\n            keep_memory(&x);\n        }\n\n        template <typename Fn, typename... Args>\n        inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {\n            deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));\n        }\n\n        template <typename Fn, typename... Args>\n        inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {\n            std::forward<Fn>(fn) (std::forward<Args...>(args...));\n        }\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_optimizer.hpp\n// start catch_complete_invoke.hpp\n\n// Invoke with a special case for void\n\n\n#include <type_traits>\n#include <utility>\n\nnamespace Catch {\n    namespace Benchmark {\n        namespace Detail {\n            template <typename T>\n            struct CompleteType { using type = T; };\n            template <>\n            struct CompleteType<void> { struct type {}; };\n\n            template <typename T>\n            using CompleteType_t = typename CompleteType<T>::type;\n\n            template <typename Result>\n            struct CompleteInvoker {\n                template <typename Fun, typename... Args>\n                static Result invoke(Fun&& fun, Args&&... args) {\n                    return std::forward<Fun>(fun)(std::forward<Args>(args)...);\n                }\n            };\n            template <>\n            struct CompleteInvoker<void> {\n                template <typename Fun, typename... Args>\n                static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {\n                    std::forward<Fun>(fun)(std::forward<Args>(args)...);\n                    return {};\n                }\n            };\n            template <typename Sig>\n            using ResultOf_t = typename std::result_of<Sig>::type;\n\n            // invoke and not return void :(\n            template <typename Fun, typename... Args>\n            CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&... args) {\n                return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);\n            }\n\n            const std::string benchmarkErrorMsg = \"a benchmark failed to run successfully\";\n        } // namespace Detail\n\n        template <typename Fun>\n        Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {\n            CATCH_TRY{\n                return Detail::complete_invoke(std::forward<Fun>(fun));\n            } CATCH_CATCH_ALL{\n                getResultCapture().benchmarkFailed(translateActiveException());\n                CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);\n            }\n        }\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_complete_invoke.hpp\nnamespace Catch {\n    namespace Benchmark {\n        namespace Detail {\n            struct ChronometerConcept {\n                virtual void start() = 0;\n                virtual void finish() = 0;\n                virtual ~ChronometerConcept() = default;\n            };\n            template <typename Clock>\n            struct ChronometerModel final : public ChronometerConcept {\n                void start() override { started = Clock::now(); }\n                void finish() override { finished = Clock::now(); }\n\n                ClockDuration<Clock> elapsed() const { return finished - started; }\n\n                TimePoint<Clock> started;\n                TimePoint<Clock> finished;\n            };\n        } // namespace Detail\n\n        struct Chronometer {\n        public:\n            template <typename Fun>\n            void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }\n\n            int runs() const { return k; }\n\n            Chronometer(Detail::ChronometerConcept& meter, int k)\n                : impl(&meter)\n                , k(k) {}\n\n        private:\n            template <typename Fun>\n            void measure(Fun&& fun, std::false_type) {\n                measure([&fun](int) { return fun(); }, std::true_type());\n            }\n\n            template <typename Fun>\n            void measure(Fun&& fun, std::true_type) {\n                Detail::optimizer_barrier();\n                impl->start();\n                for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);\n                impl->finish();\n                Detail::optimizer_barrier();\n            }\n\n            Detail::ChronometerConcept* impl;\n            int k;\n        };\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_chronometer.hpp\n// start catch_environment.hpp\n\n// Environment information\n\n\nnamespace Catch {\n    namespace Benchmark {\n        template <typename Duration>\n        struct EnvironmentEstimate {\n            Duration mean;\n            OutlierClassification outliers;\n\n            template <typename Duration2>\n            operator EnvironmentEstimate<Duration2>() const {\n                return { mean, outliers };\n            }\n        };\n        template <typename Clock>\n        struct Environment {\n            using clock_type = Clock;\n            EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;\n            EnvironmentEstimate<FloatDuration<Clock>> clock_cost;\n        };\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_environment.hpp\n// start catch_execution_plan.hpp\n\n // Execution plan\n\n\n// start catch_benchmark_function.hpp\n\n // Dumb std::function implementation for consistent call overhead\n\n\n#include <cassert>\n#include <type_traits>\n#include <utility>\n#include <memory>\n\nnamespace Catch {\n    namespace Benchmark {\n        namespace Detail {\n            template <typename T>\n            using Decay = typename std::decay<T>::type;\n            template <typename T, typename U>\n            struct is_related\n                : std::is_same<Decay<T>, Decay<U>> {};\n\n            /// We need to reinvent std::function because every piece of code that might add overhead\n            /// in a measurement context needs to have consistent performance characteristics so that we\n            /// can account for it in the measurement.\n            /// Implementations of std::function with optimizations that aren't always applicable, like\n            /// small buffer optimizations, are not uncommon.\n            /// This is effectively an implementation of std::function without any such optimizations;\n            /// it may be slow, but it is consistently slow.\n            struct BenchmarkFunction {\n            private:\n                struct callable {\n                    virtual void call(Chronometer meter) const = 0;\n                    virtual callable* clone() const = 0;\n                    virtual ~callable() = default;\n                };\n                template <typename Fun>\n                struct model : public callable {\n                    model(Fun&& fun) : fun(std::move(fun)) {}\n                    model(Fun const& fun) : fun(fun) {}\n\n                    model<Fun>* clone() const override { return new model<Fun>(*this); }\n\n                    void call(Chronometer meter) const override {\n                        call(meter, is_callable<Fun(Chronometer)>());\n                    }\n                    void call(Chronometer meter, std::true_type) const {\n                        fun(meter);\n                    }\n                    void call(Chronometer meter, std::false_type) const {\n                        meter.measure(fun);\n                    }\n\n                    Fun fun;\n                };\n\n                struct do_nothing { void operator()() const {} };\n\n                template <typename T>\n                BenchmarkFunction(model<T>* c) : f(c) {}\n\n            public:\n                BenchmarkFunction()\n                    : f(new model<do_nothing>{ {} }) {}\n\n                template <typename Fun,\n                    typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>\n                    BenchmarkFunction(Fun&& fun)\n                    : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}\n\n                BenchmarkFunction(BenchmarkFunction&& that)\n                    : f(std::move(that.f)) {}\n\n                BenchmarkFunction(BenchmarkFunction const& that)\n                    : f(that.f->clone()) {}\n\n                BenchmarkFunction& operator=(BenchmarkFunction&& that) {\n                    f = std::move(that.f);\n                    return *this;\n                }\n\n                BenchmarkFunction& operator=(BenchmarkFunction const& that) {\n                    f.reset(that.f->clone());\n                    return *this;\n                }\n\n                void operator()(Chronometer meter) const { f->call(meter); }\n\n            private:\n                std::unique_ptr<callable> f;\n            };\n        } // namespace Detail\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_benchmark_function.hpp\n// start catch_repeat.hpp\n\n// repeat algorithm\n\n\n#include <type_traits>\n#include <utility>\n\nnamespace Catch {\n    namespace Benchmark {\n        namespace Detail {\n            template <typename Fun>\n            struct repeater {\n                void operator()(int k) const {\n                    for (int i = 0; i < k; ++i) {\n                        fun();\n                    }\n                }\n                Fun fun;\n            };\n            template <typename Fun>\n            repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {\n                return { std::forward<Fun>(fun) };\n            }\n        } // namespace Detail\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_repeat.hpp\n// start catch_run_for_at_least.hpp\n\n// Run a function for a minimum amount of time\n\n\n// start catch_measure.hpp\n\n// Measure\n\n\n// start catch_timing.hpp\n\n// Timing\n\n\n#include <tuple>\n#include <type_traits>\n\nnamespace Catch {\n    namespace Benchmark {\n        template <typename Duration, typename Result>\n        struct Timing {\n            Duration elapsed;\n            Result result;\n            int iterations;\n        };\n        template <typename Clock, typename Sig>\n        using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_timing.hpp\n#include <utility>\n\nnamespace Catch {\n    namespace Benchmark {\n        namespace Detail {\n            template <typename Clock, typename Fun, typename... Args>\n            TimingOf<Clock, Fun(Args...)> measure(Fun&& fun, Args&&... args) {\n                auto start = Clock::now();\n                auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);\n                auto end = Clock::now();\n                auto delta = end - start;\n                return { delta, std::forward<decltype(r)>(r), 1 };\n            }\n        } // namespace Detail\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_measure.hpp\n#include <utility>\n#include <type_traits>\n\nnamespace Catch {\n    namespace Benchmark {\n        namespace Detail {\n            template <typename Clock, typename Fun>\n            TimingOf<Clock, Fun(int)> measure_one(Fun&& fun, int iters, std::false_type) {\n                return Detail::measure<Clock>(fun, iters);\n            }\n            template <typename Clock, typename Fun>\n            TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun, int iters, std::true_type) {\n                Detail::ChronometerModel<Clock> meter;\n                auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));\n\n                return { meter.elapsed(), std::move(result), iters };\n            }\n\n            template <typename Clock, typename Fun>\n            using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;\n\n            struct optimized_away_error : std::exception {\n                const char* what() const noexcept override {\n                    return \"could not measure benchmark, maybe it was optimized away\";\n                }\n            };\n\n            template <typename Clock, typename Fun>\n            TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {\n                auto iters = seed;\n                while (iters < (1 << 30)) {\n                    auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());\n\n                    if (Timing.elapsed >= how_long) {\n                        return { Timing.elapsed, std::move(Timing.result), iters };\n                    }\n                    iters *= 2;\n                }\n                throw optimized_away_error{};\n            }\n        } // namespace Detail\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_run_for_at_least.hpp\n#include <algorithm>\n\nnamespace Catch {\n    namespace Benchmark {\n        template <typename Duration>\n        struct ExecutionPlan {\n            int iterations_per_sample;\n            Duration estimated_duration;\n            Detail::BenchmarkFunction benchmark;\n            Duration warmup_time;\n            int warmup_iterations;\n\n            template <typename Duration2>\n            operator ExecutionPlan<Duration2>() const {\n                return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };\n            }\n\n            template <typename Clock>\n            std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {\n                // warmup a bit\n                Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));\n\n                std::vector<FloatDuration<Clock>> times;\n                times.reserve(cfg.benchmarkSamples());\n                std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {\n                    Detail::ChronometerModel<Clock> model;\n                    this->benchmark(Chronometer(model, iterations_per_sample));\n                    auto sample_time = model.elapsed() - env.clock_cost.mean;\n                    if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();\n                    return sample_time / iterations_per_sample;\n                });\n                return times;\n            }\n        };\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_execution_plan.hpp\n// start catch_estimate_clock.hpp\n\n // Environment measurement\n\n\n// start catch_stats.hpp\n\n// Statistical analysis tools\n\n\n#include <algorithm>\n#include <functional>\n#include <vector>\n#include <numeric>\n#include <tuple>\n#include <cmath>\n#include <utility>\n#include <cstddef>\n\nnamespace Catch {\n    namespace Benchmark {\n        namespace Detail {\n            using sample = std::vector<double>;\n\n            double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);\n\n            template <typename Iterator>\n            OutlierClassification classify_outliers(Iterator first, Iterator last) {\n                std::vector<double> copy(first, last);\n\n                auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());\n                auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());\n                auto iqr = q3 - q1;\n                auto los = q1 - (iqr * 3.);\n                auto lom = q1 - (iqr * 1.5);\n                auto him = q3 + (iqr * 1.5);\n                auto his = q3 + (iqr * 3.);\n\n                OutlierClassification o;\n                for (; first != last; ++first) {\n                    auto&& t = *first;\n                    if (t < los) ++o.low_severe;\n                    else if (t < lom) ++o.low_mild;\n                    else if (t > his) ++o.high_severe;\n                    else if (t > him) ++o.high_mild;\n                    ++o.samples_seen;\n                }\n                return o;\n            }\n\n            template <typename Iterator>\n            double mean(Iterator first, Iterator last) {\n                auto count = last - first;\n                double sum = std::accumulate(first, last, 0.);\n                return sum / count;\n            }\n\n            template <typename URng, typename Iterator, typename Estimator>\n            sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {\n                auto n = last - first;\n                std::uniform_int_distribution<decltype(n)> dist(0, n - 1);\n\n                sample out;\n                out.reserve(resamples);\n                std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {\n                    std::vector<double> resampled;\n                    resampled.reserve(n);\n                    std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });\n                    return estimator(resampled.begin(), resampled.end());\n                });\n                std::sort(out.begin(), out.end());\n                return out;\n            }\n\n            template <typename Estimator, typename Iterator>\n            sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {\n                auto n = last - first;\n                auto second = std::next(first);\n                sample results;\n                results.reserve(n);\n\n                for (auto it = first; it != last; ++it) {\n                    std::iter_swap(it, first);\n                    results.push_back(estimator(second, last));\n                }\n\n                return results;\n            }\n\n            inline double normal_cdf(double x) {\n                return std::erfc(-x / std::sqrt(2.0)) / 2.0;\n            }\n\n            double erfc_inv(double x);\n\n            double normal_quantile(double p);\n\n            template <typename Iterator, typename Estimator>\n            Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {\n                auto n_samples = last - first;\n\n                double point = estimator(first, last);\n                // Degenerate case with a single sample\n                if (n_samples == 1) return { point, point, point, confidence_level };\n\n                sample jack = jackknife(estimator, first, last);\n                double jack_mean = mean(jack.begin(), jack.end());\n                double sum_squares, sum_cubes;\n                std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {\n                    auto d = jack_mean - x;\n                    auto d2 = d * d;\n                    auto d3 = d2 * d;\n                    return { sqcb.first + d2, sqcb.second + d3 };\n                });\n\n                double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));\n                int n = static_cast<int>(resample.size());\n                double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;\n                // degenerate case with uniform samples\n                if (prob_n == 0) return { point, point, point, confidence_level };\n\n                double bias = normal_quantile(prob_n);\n                double z1 = normal_quantile((1. - confidence_level) / 2.);\n\n                auto cumn = [n](double x) -> int {\n                    return std::lround(normal_cdf(x) * n); };\n                auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };\n                double b1 = bias + z1;\n                double b2 = bias - z1;\n                double a1 = a(b1);\n                double a2 = a(b2);\n                auto lo = std::max(cumn(a1), 0);\n                auto hi = std::min(cumn(a2), n - 1);\n\n                return { point, resample[lo], resample[hi], confidence_level };\n            }\n\n            double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);\n\n            struct bootstrap_analysis {\n                Estimate<double> mean;\n                Estimate<double> standard_deviation;\n                double outlier_variance;\n            };\n\n            bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);\n        } // namespace Detail\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_stats.hpp\n#include <algorithm>\n#include <iterator>\n#include <tuple>\n#include <vector>\n#include <cmath>\n\nnamespace Catch {\n    namespace Benchmark {\n        namespace Detail {\n            template <typename Clock>\n            std::vector<double> resolution(int k) {\n                std::vector<TimePoint<Clock>> times;\n                times.reserve(k + 1);\n                std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});\n\n                std::vector<double> deltas;\n                deltas.reserve(k);\n                std::transform(std::next(times.begin()), times.end(), times.begin(),\n                    std::back_inserter(deltas),\n                    [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });\n\n                return deltas;\n            }\n\n            const auto warmup_iterations = 10000;\n            const auto warmup_time = std::chrono::milliseconds(100);\n            const auto minimum_ticks = 1000;\n            const auto warmup_seed = 10000;\n            const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);\n            const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);\n            const auto clock_cost_estimation_tick_limit = 100000;\n            const auto clock_cost_estimation_time = std::chrono::milliseconds(10);\n            const auto clock_cost_estimation_iterations = 10000;\n\n            template <typename Clock>\n            int warmup() {\n                return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)\n                    .iterations;\n            }\n            template <typename Clock>\n            EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {\n                auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)\n                    .result;\n                return {\n                    FloatDuration<Clock>(mean(r.begin(), r.end())),\n                    classify_outliers(r.begin(), r.end()),\n                };\n            }\n            template <typename Clock>\n            EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {\n                auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));\n                auto time_clock = [](int k) {\n                    return Detail::measure<Clock>([k] {\n                        for (int i = 0; i < k; ++i) {\n                            volatile auto ignored = Clock::now();\n                            (void)ignored;\n                        }\n                    }).elapsed;\n                };\n                time_clock(1);\n                int iters = clock_cost_estimation_iterations;\n                auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);\n                std::vector<double> times;\n                int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));\n                times.reserve(nsamples);\n                std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {\n                    return static_cast<double>((time_clock(r.iterations) / r.iterations).count());\n                });\n                return {\n                    FloatDuration<Clock>(mean(times.begin(), times.end())),\n                    classify_outliers(times.begin(), times.end()),\n                };\n            }\n\n            template <typename Clock>\n            Environment<FloatDuration<Clock>> measure_environment() {\n                static Environment<FloatDuration<Clock>>* env = nullptr;\n                if (env) {\n                    return *env;\n                }\n\n                auto iters = Detail::warmup<Clock>();\n                auto resolution = Detail::estimate_clock_resolution<Clock>(iters);\n                auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);\n\n                env = new Environment<FloatDuration<Clock>>{ resolution, cost };\n                return *env;\n            }\n        } // namespace Detail\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_estimate_clock.hpp\n// start catch_analyse.hpp\n\n // Run and analyse one benchmark\n\n\n// start catch_sample_analysis.hpp\n\n// Benchmark results\n\n\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <iterator>\n\nnamespace Catch {\n    namespace Benchmark {\n        template <typename Duration>\n        struct SampleAnalysis {\n            std::vector<Duration> samples;\n            Estimate<Duration> mean;\n            Estimate<Duration> standard_deviation;\n            OutlierClassification outliers;\n            double outlier_variance;\n\n            template <typename Duration2>\n            operator SampleAnalysis<Duration2>() const {\n                std::vector<Duration2> samples2;\n                samples2.reserve(samples.size());\n                std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });\n                return {\n                    std::move(samples2),\n                    mean,\n                    standard_deviation,\n                    outliers,\n                    outlier_variance,\n                };\n            }\n        };\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_sample_analysis.hpp\n#include <algorithm>\n#include <iterator>\n#include <vector>\n\nnamespace Catch {\n    namespace Benchmark {\n        namespace Detail {\n            template <typename Duration, typename Iterator>\n            SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {\n                if (!cfg.benchmarkNoAnalysis()) {\n                    std::vector<double> samples;\n                    samples.reserve(last - first);\n                    std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });\n\n                    auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());\n                    auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());\n\n                    auto wrap_estimate = [](Estimate<double> e) {\n                        return Estimate<Duration> {\n                            Duration(e.point),\n                                Duration(e.lower_bound),\n                                Duration(e.upper_bound),\n                                e.confidence_interval,\n                        };\n                    };\n                    std::vector<Duration> samples2;\n                    samples2.reserve(samples.size());\n                    std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });\n                    return {\n                        std::move(samples2),\n                        wrap_estimate(analysis.mean),\n                        wrap_estimate(analysis.standard_deviation),\n                        outliers,\n                        analysis.outlier_variance,\n                    };\n                } else {\n                    std::vector<Duration> samples;\n                    samples.reserve(last - first);\n\n                    Duration mean = Duration(0);\n                    int i = 0;\n                    for (auto it = first; it < last; ++it, ++i) {\n                        samples.push_back(Duration(*it));\n                        mean += Duration(*it);\n                    }\n                    mean /= i;\n\n                    return {\n                        std::move(samples),\n                        Estimate<Duration>{mean, mean, mean, 0.0},\n                        Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},\n                        OutlierClassification{},\n                        0.0\n                    };\n                }\n            }\n        } // namespace Detail\n    } // namespace Benchmark\n} // namespace Catch\n\n// end catch_analyse.hpp\n#include <algorithm>\n#include <functional>\n#include <string>\n#include <vector>\n#include <cmath>\n\nnamespace Catch {\n    namespace Benchmark {\n        struct Benchmark {\n            Benchmark(std::string &&name)\n                : name(std::move(name)) {}\n\n            template <class FUN>\n            Benchmark(std::string &&name, FUN &&func)\n                : fun(std::move(func)), name(std::move(name)) {}\n\n            template <typename Clock>\n            ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {\n                auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;\n                auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(Detail::warmup_time));\n                auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);\n                int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));\n                return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(Detail::warmup_time), Detail::warmup_iterations };\n            }\n\n            template <typename Clock = default_clock>\n            void run() {\n                IConfigPtr cfg = getCurrentContext().getConfig();\n\n                auto env = Detail::measure_environment<Clock>();\n\n                getResultCapture().benchmarkPreparing(name);\n                CATCH_TRY{\n                    auto plan = user_code([&] {\n                        return prepare<Clock>(*cfg, env);\n                    });\n\n                    BenchmarkInfo info {\n                        name,\n                        plan.estimated_duration.count(),\n                        plan.iterations_per_sample,\n                        cfg->benchmarkSamples(),\n                        cfg->benchmarkResamples(),\n                        env.clock_resolution.mean.count(),\n                        env.clock_cost.mean.count()\n                    };\n\n                    getResultCapture().benchmarkStarting(info);\n\n                    auto samples = user_code([&] {\n                        return plan.template run<Clock>(*cfg, env);\n                    });\n\n                    auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());\n                    BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };\n                    getResultCapture().benchmarkEnded(stats);\n\n                } CATCH_CATCH_ALL{\n                    if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.\n                        std::rethrow_exception(std::current_exception());\n                }\n            }\n\n            // sets lambda to be used in fun *and* executes benchmark!\n            template <typename Fun,\n                typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>\n                Benchmark & operator=(Fun func) {\n                fun = Detail::BenchmarkFunction(func);\n                run();\n                return *this;\n            }\n\n            explicit operator bool() {\n                return true;\n            }\n\n        private:\n            Detail::BenchmarkFunction fun;\n            std::string name;\n        };\n    }\n} // namespace Catch\n\n#define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1\n#define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2\n\n#define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\\\n    if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \\\n        BenchmarkName = [&](int benchmarkIndex)\n\n#define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\\\n    if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \\\n        BenchmarkName = [&]\n\n// end catch_benchmark.hpp\n// start catch_constructor.hpp\n\n// Constructor and destructor helpers\n\n\n#include <type_traits>\n\nnamespace Catch {\n    namespace Detail {\n        template <typename T, bool Destruct>\n        struct ObjectStorage\n        {\n            using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;\n\n            ObjectStorage() : data() {}\n\n            ObjectStorage(const ObjectStorage& other)\n            {\n                new(&data) T(other.stored_object());\n            }\n\n            ObjectStorage(ObjectStorage&& other)\n            {\n                new(&data) T(std::move(other.stored_object()));\n            }\n\n            ~ObjectStorage() { destruct_on_exit<T>(); }\n\n            template <typename... Args>\n            void construct(Args&&... args)\n            {\n                new (&data) T(std::forward<Args>(args)...);\n            }\n\n            template <bool AllowManualDestruction = !Destruct>\n            typename std::enable_if<AllowManualDestruction>::type destruct()\n            {\n                stored_object().~T();\n            }\n\n        private:\n            // If this is a constructor benchmark, destruct the underlying object\n            template <typename U>\n            void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }\n            // Otherwise, don't\n            template <typename U>\n            void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }\n\n            T& stored_object()\n            {\n                return *static_cast<T*>(static_cast<void*>(&data));\n            }\n\n            TStorage data;\n        };\n    }\n\n    template <typename T>\n    using storage_for = Detail::ObjectStorage<T, true>;\n\n    template <typename T>\n    using destructable_object = Detail::ObjectStorage<T, false>;\n}\n\n// end catch_constructor.hpp\n// end catch_benchmarking_all.hpp\n#endif\n\n#endif // ! CATCH_CONFIG_IMPL_ONLY\n\n#ifdef CATCH_IMPL\n// start catch_impl.hpp\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wweak-vtables\"\n#endif\n\n// Keep these here for external reporters\n// start catch_test_case_tracker.h\n\n#include <string>\n#include <vector>\n#include <memory>\n\nnamespace Catch {\nnamespace TestCaseTracking {\n\n    struct NameAndLocation {\n        std::string name;\n        SourceLineInfo location;\n\n        NameAndLocation( std::string const& _name, SourceLineInfo const& _location );\n    };\n\n    struct ITracker;\n\n    using ITrackerPtr = std::shared_ptr<ITracker>;\n\n    struct ITracker {\n        virtual ~ITracker();\n\n        // static queries\n        virtual NameAndLocation const& nameAndLocation() const = 0;\n\n        // dynamic queries\n        virtual bool isComplete() const = 0; // Successfully completed or failed\n        virtual bool isSuccessfullyCompleted() const = 0;\n        virtual bool isOpen() const = 0; // Started but not complete\n        virtual bool hasChildren() const = 0;\n\n        virtual ITracker& parent() = 0;\n\n        // actions\n        virtual void close() = 0; // Successfully complete\n        virtual void fail() = 0;\n        virtual void markAsNeedingAnotherRun() = 0;\n\n        virtual void addChild( ITrackerPtr const& child ) = 0;\n        virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;\n        virtual void openChild() = 0;\n\n        // Debug/ checking\n        virtual bool isSectionTracker() const = 0;\n        virtual bool isGeneratorTracker() const = 0;\n    };\n\n    class TrackerContext {\n\n        enum RunState {\n            NotStarted,\n            Executing,\n            CompletedCycle\n        };\n\n        ITrackerPtr m_rootTracker;\n        ITracker* m_currentTracker = nullptr;\n        RunState m_runState = NotStarted;\n\n    public:\n\n        ITracker& startRun();\n        void endRun();\n\n        void startCycle();\n        void completeCycle();\n\n        bool completedCycle() const;\n        ITracker& currentTracker();\n        void setCurrentTracker( ITracker* tracker );\n    };\n\n    class TrackerBase : public ITracker {\n    protected:\n        enum CycleState {\n            NotStarted,\n            Executing,\n            ExecutingChildren,\n            NeedsAnotherRun,\n            CompletedSuccessfully,\n            Failed\n        };\n\n        using Children = std::vector<ITrackerPtr>;\n        NameAndLocation m_nameAndLocation;\n        TrackerContext& m_ctx;\n        ITracker* m_parent;\n        Children m_children;\n        CycleState m_runState = NotStarted;\n\n    public:\n        TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );\n\n        NameAndLocation const& nameAndLocation() const override;\n        bool isComplete() const override;\n        bool isSuccessfullyCompleted() const override;\n        bool isOpen() const override;\n        bool hasChildren() const override;\n\n        void addChild( ITrackerPtr const& child ) override;\n\n        ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;\n        ITracker& parent() override;\n\n        void openChild() override;\n\n        bool isSectionTracker() const override;\n        bool isGeneratorTracker() const override;\n\n        void open();\n\n        void close() override;\n        void fail() override;\n        void markAsNeedingAnotherRun() override;\n\n    private:\n        void moveToParent();\n        void moveToThis();\n    };\n\n    class SectionTracker : public TrackerBase {\n        std::vector<std::string> m_filters;\n        std::string m_trimmed_name;\n    public:\n        SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );\n\n        bool isSectionTracker() const override;\n\n        bool isComplete() const override;\n\n        static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );\n\n        void tryOpen();\n\n        void addInitialFilters( std::vector<std::string> const& filters );\n        void addNextFilters( std::vector<std::string> const& filters );\n    };\n\n} // namespace TestCaseTracking\n\nusing TestCaseTracking::ITracker;\nusing TestCaseTracking::TrackerContext;\nusing TestCaseTracking::SectionTracker;\n\n} // namespace Catch\n\n// end catch_test_case_tracker.h\n\n// start catch_leak_detector.h\n\nnamespace Catch {\n\n    struct LeakDetector {\n        LeakDetector();\n        ~LeakDetector();\n    };\n\n}\n// end catch_leak_detector.h\n// Cpp files will be included in the single-header file here\n// start catch_stats.cpp\n\n// Statistical analysis tools\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n\n#include <cassert>\n#include <random>\n\n#if defined(CATCH_CONFIG_USE_ASYNC)\n#include <future>\n#endif\n\nnamespace {\n    double erf_inv(double x) {\n        // Code accompanying the article \"Approximating the erfinv function\" in GPU Computing Gems, Volume 2\n        double w, p;\n\n        w = -log((1.0 - x) * (1.0 + x));\n\n        if (w < 6.250000) {\n            w = w - 3.125000;\n            p = -3.6444120640178196996e-21;\n            p = -1.685059138182016589e-19 + p * w;\n            p = 1.2858480715256400167e-18 + p * w;\n            p = 1.115787767802518096e-17 + p * w;\n            p = -1.333171662854620906e-16 + p * w;\n            p = 2.0972767875968561637e-17 + p * w;\n            p = 6.6376381343583238325e-15 + p * w;\n            p = -4.0545662729752068639e-14 + p * w;\n            p = -8.1519341976054721522e-14 + p * w;\n            p = 2.6335093153082322977e-12 + p * w;\n            p = -1.2975133253453532498e-11 + p * w;\n            p = -5.4154120542946279317e-11 + p * w;\n            p = 1.051212273321532285e-09 + p * w;\n            p = -4.1126339803469836976e-09 + p * w;\n            p = -2.9070369957882005086e-08 + p * w;\n            p = 4.2347877827932403518e-07 + p * w;\n            p = -1.3654692000834678645e-06 + p * w;\n            p = -1.3882523362786468719e-05 + p * w;\n            p = 0.0001867342080340571352 + p * w;\n            p = -0.00074070253416626697512 + p * w;\n            p = -0.0060336708714301490533 + p * w;\n            p = 0.24015818242558961693 + p * w;\n            p = 1.6536545626831027356 + p * w;\n        } else if (w < 16.000000) {\n            w = sqrt(w) - 3.250000;\n            p = 2.2137376921775787049e-09;\n            p = 9.0756561938885390979e-08 + p * w;\n            p = -2.7517406297064545428e-07 + p * w;\n            p = 1.8239629214389227755e-08 + p * w;\n            p = 1.5027403968909827627e-06 + p * w;\n            p = -4.013867526981545969e-06 + p * w;\n            p = 2.9234449089955446044e-06 + p * w;\n            p = 1.2475304481671778723e-05 + p * w;\n            p = -4.7318229009055733981e-05 + p * w;\n            p = 6.8284851459573175448e-05 + p * w;\n            p = 2.4031110387097893999e-05 + p * w;\n            p = -0.0003550375203628474796 + p * w;\n            p = 0.00095328937973738049703 + p * w;\n            p = -0.0016882755560235047313 + p * w;\n            p = 0.0024914420961078508066 + p * w;\n            p = -0.0037512085075692412107 + p * w;\n            p = 0.005370914553590063617 + p * w;\n            p = 1.0052589676941592334 + p * w;\n            p = 3.0838856104922207635 + p * w;\n        } else {\n            w = sqrt(w) - 5.000000;\n            p = -2.7109920616438573243e-11;\n            p = -2.5556418169965252055e-10 + p * w;\n            p = 1.5076572693500548083e-09 + p * w;\n            p = -3.7894654401267369937e-09 + p * w;\n            p = 7.6157012080783393804e-09 + p * w;\n            p = -1.4960026627149240478e-08 + p * w;\n            p = 2.9147953450901080826e-08 + p * w;\n            p = -6.7711997758452339498e-08 + p * w;\n            p = 2.2900482228026654717e-07 + p * w;\n            p = -9.9298272942317002539e-07 + p * w;\n            p = 4.5260625972231537039e-06 + p * w;\n            p = -1.9681778105531670567e-05 + p * w;\n            p = 7.5995277030017761139e-05 + p * w;\n            p = -0.00021503011930044477347 + p * w;\n            p = -0.00013871931833623122026 + p * w;\n            p = 1.0103004648645343977 + p * w;\n            p = 4.8499064014085844221 + p * w;\n        }\n        return p * x;\n    }\n\n    double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {\n        auto m = Catch::Benchmark::Detail::mean(first, last);\n        double variance = std::accumulate(first, last, 0., [m](double a, double b) {\n            double diff = b - m;\n            return a + diff * diff;\n            }) / (last - first);\n            return std::sqrt(variance);\n    }\n\n}\n\nnamespace Catch {\n    namespace Benchmark {\n        namespace Detail {\n\n            double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {\n                auto count = last - first;\n                double idx = (count - 1) * k / static_cast<double>(q);\n                int j = static_cast<int>(idx);\n                double g = idx - j;\n                std::nth_element(first, first + j, last);\n                auto xj = first[j];\n                if (g == 0) return xj;\n\n                auto xj1 = *std::min_element(first + (j + 1), last);\n                return xj + g * (xj1 - xj);\n            }\n\n            double erfc_inv(double x) {\n                return erf_inv(1.0 - x);\n            }\n\n            double normal_quantile(double p) {\n                static const double ROOT_TWO = std::sqrt(2.0);\n\n                double result = 0.0;\n                assert(p >= 0 && p <= 1);\n                if (p < 0 || p > 1) {\n                    return result;\n                }\n\n                result = -erfc_inv(2.0 * p);\n                // result *= normal distribution standard deviation (1.0) * sqrt(2)\n                result *= /*sd * */ ROOT_TWO;\n                // result += normal disttribution mean (0)\n                return result;\n            }\n\n            double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {\n                double sb = stddev.point;\n                double mn = mean.point / n;\n                double mg_min = mn / 2.;\n                double sg = std::min(mg_min / 4., sb / std::sqrt(n));\n                double sg2 = sg * sg;\n                double sb2 = sb * sb;\n\n                auto c_max = [n, mn, sb2, sg2](double x) -> double {\n                    double k = mn - x;\n                    double d = k * k;\n                    double nd = n * d;\n                    double k0 = -n * nd;\n                    double k1 = sb2 - n * sg2 + nd;\n                    double det = k1 * k1 - 4 * sg2 * k0;\n                    return (int)(-2. * k0 / (k1 + std::sqrt(det)));\n                };\n\n                auto var_out = [n, sb2, sg2](double c) {\n                    double nc = n - c;\n                    return (nc / n) * (sb2 - nc * sg2);\n                };\n\n                return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;\n            }\n\n            bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {\n                CATCH_INTERNAL_START_WARNINGS_SUPPRESSION\n                CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS\n                static std::random_device entropy;\n                CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION\n\n                auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++\n\n                auto mean = &Detail::mean<std::vector<double>::iterator>;\n                auto stddev = &standard_deviation;\n\n#if defined(CATCH_CONFIG_USE_ASYNC)\n                auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {\n                    auto seed = entropy();\n                    return std::async(std::launch::async, [=] {\n                        std::mt19937 rng(seed);\n                        auto resampled = resample(rng, n_resamples, first, last, f);\n                        return bootstrap(confidence_level, first, last, resampled, f);\n                    });\n                };\n\n                auto mean_future = Estimate(mean);\n                auto stddev_future = Estimate(stddev);\n\n                auto mean_estimate = mean_future.get();\n                auto stddev_estimate = stddev_future.get();\n#else\n                auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {\n                    auto seed = entropy();\n                    std::mt19937 rng(seed);\n                    auto resampled = resample(rng, n_resamples, first, last, f);\n                    return bootstrap(confidence_level, first, last, resampled, f);\n                };\n\n                auto mean_estimate = Estimate(mean);\n                auto stddev_estimate = Estimate(stddev);\n#endif // CATCH_USE_ASYNC\n\n                double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);\n\n                return { mean_estimate, stddev_estimate, outlier_variance };\n            }\n        } // namespace Detail\n    } // namespace Benchmark\n} // namespace Catch\n\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n// end catch_stats.cpp\n// start catch_approx.cpp\n\n#include <cmath>\n#include <limits>\n\nnamespace {\n\n// Performs equivalent check of std::fabs(lhs - rhs) <= margin\n// But without the subtraction to allow for INFINITY in comparison\nbool marginComparison(double lhs, double rhs, double margin) {\n    return (lhs + margin >= rhs) && (rhs + margin >= lhs);\n}\n\n}\n\nnamespace Catch {\nnamespace Detail {\n\n    Approx::Approx ( double value )\n    :   m_epsilon( std::numeric_limits<float>::epsilon()*100 ),\n        m_margin( 0.0 ),\n        m_scale( 0.0 ),\n        m_value( value )\n    {}\n\n    Approx Approx::custom() {\n        return Approx( 0 );\n    }\n\n    Approx Approx::operator-() const {\n        auto temp(*this);\n        temp.m_value = -temp.m_value;\n        return temp;\n    }\n\n    std::string Approx::toString() const {\n        ReusableStringStream rss;\n        rss << \"Approx( \" << ::Catch::Detail::stringify( m_value ) << \" )\";\n        return rss.str();\n    }\n\n    bool Approx::equalityComparisonImpl(const double other) const {\n        // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value\n        // Thanks to Richard Harris for his help refining the scaled margin value\n        return marginComparison(m_value, other, m_margin)\n            || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));\n    }\n\n    void Approx::setMargin(double newMargin) {\n        CATCH_ENFORCE(newMargin >= 0,\n            \"Invalid Approx::margin: \" << newMargin << '.'\n            << \" Approx::Margin has to be non-negative.\");\n        m_margin = newMargin;\n    }\n\n    void Approx::setEpsilon(double newEpsilon) {\n        CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,\n            \"Invalid Approx::epsilon: \" << newEpsilon << '.'\n            << \" Approx::epsilon has to be in [0, 1]\");\n        m_epsilon = newEpsilon;\n    }\n\n} // end namespace Detail\n\nnamespace literals {\n    Detail::Approx operator \"\" _a(long double val) {\n        return Detail::Approx(val);\n    }\n    Detail::Approx operator \"\" _a(unsigned long long val) {\n        return Detail::Approx(val);\n    }\n} // end namespace literals\n\nstd::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {\n    return value.toString();\n}\n\n} // end namespace Catch\n// end catch_approx.cpp\n// start catch_assertionhandler.cpp\n\n// start catch_debugger.h\n\nnamespace Catch {\n    bool isDebuggerActive();\n}\n\n#ifdef CATCH_PLATFORM_MAC\n\n    #define CATCH_TRAP() __asm__(\"int $3\\n\" : : ) /* NOLINT */\n\n#elif defined(CATCH_PLATFORM_LINUX)\n    // If we can use inline assembler, do it because this allows us to break\n    // directly at the location of the failing check instead of breaking inside\n    // raise() called from it, i.e. one stack frame below.\n    #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))\n        #define CATCH_TRAP() asm volatile (\"int $3\") /* NOLINT */\n    #else // Fall back to the generic way.\n        #include <signal.h>\n\n        #define CATCH_TRAP() raise(SIGTRAP)\n    #endif\n#elif defined(_MSC_VER)\n    #define CATCH_TRAP() __debugbreak()\n#elif defined(__MINGW32__)\n    extern \"C\" __declspec(dllimport) void __stdcall DebugBreak();\n    #define CATCH_TRAP() DebugBreak()\n#endif\n\n#ifdef CATCH_TRAP\n    #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()\n#else\n    #define CATCH_BREAK_INTO_DEBUGGER() []{}()\n#endif\n\n// end catch_debugger.h\n// start catch_run_context.h\n\n// start catch_fatal_condition.h\n\n// start catch_windows_h_proxy.h\n\n\n#if defined(CATCH_PLATFORM_WINDOWS)\n\n#if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)\n#  define CATCH_DEFINED_NOMINMAX\n#  define NOMINMAX\n#endif\n#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)\n#  define CATCH_DEFINED_WIN32_LEAN_AND_MEAN\n#  define WIN32_LEAN_AND_MEAN\n#endif\n\n#ifdef __AFXDLL\n#include <AfxWin.h>\n#else\n#include <windows.h>\n#endif\n\n#ifdef CATCH_DEFINED_NOMINMAX\n#  undef NOMINMAX\n#endif\n#ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN\n#  undef WIN32_LEAN_AND_MEAN\n#endif\n\n#endif // defined(CATCH_PLATFORM_WINDOWS)\n\n// end catch_windows_h_proxy.h\n#if defined( CATCH_CONFIG_WINDOWS_SEH )\n\nnamespace Catch {\n\n    struct FatalConditionHandler {\n\n        static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);\n        FatalConditionHandler();\n        static void reset();\n        ~FatalConditionHandler();\n\n    private:\n        static bool isSet;\n        static ULONG guaranteeSize;\n        static PVOID exceptionHandlerHandle;\n    };\n\n} // namespace Catch\n\n#elif defined ( CATCH_CONFIG_POSIX_SIGNALS )\n\n#include <signal.h>\n\nnamespace Catch {\n\n    struct FatalConditionHandler {\n\n        static bool isSet;\n        static struct sigaction oldSigActions[];\n        static stack_t oldSigStack;\n        static char altStackMem[];\n\n        static void handleSignal( int sig );\n\n        FatalConditionHandler();\n        ~FatalConditionHandler();\n        static void reset();\n    };\n\n} // namespace Catch\n\n#else\n\nnamespace Catch {\n    struct FatalConditionHandler {\n        void reset();\n    };\n}\n\n#endif\n\n// end catch_fatal_condition.h\n#include <string>\n\nnamespace Catch {\n\n    struct IMutableContext;\n\n    ///////////////////////////////////////////////////////////////////////////\n\n    class RunContext : public IResultCapture, public IRunner {\n\n    public:\n        RunContext( RunContext const& ) = delete;\n        RunContext& operator =( RunContext const& ) = delete;\n\n        explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );\n\n        ~RunContext() override;\n\n        void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );\n        void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );\n\n        Totals runTest(TestCase const& testCase);\n\n        IConfigPtr config() const;\n        IStreamingReporter& reporter() const;\n\n    public: // IResultCapture\n\n        // Assertion handlers\n        void handleExpr\n                (   AssertionInfo const& info,\n                    ITransientExpression const& expr,\n                    AssertionReaction& reaction ) override;\n        void handleMessage\n                (   AssertionInfo const& info,\n                    ResultWas::OfType resultType,\n                    StringRef const& message,\n                    AssertionReaction& reaction ) override;\n        void handleUnexpectedExceptionNotThrown\n                (   AssertionInfo const& info,\n                    AssertionReaction& reaction ) override;\n        void handleUnexpectedInflightException\n                (   AssertionInfo const& info,\n                    std::string const& message,\n                    AssertionReaction& reaction ) override;\n        void handleIncomplete\n                (   AssertionInfo const& info ) override;\n        void handleNonExpr\n                (   AssertionInfo const &info,\n                    ResultWas::OfType resultType,\n                    AssertionReaction &reaction ) override;\n\n        bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;\n\n        void sectionEnded( SectionEndInfo const& endInfo ) override;\n        void sectionEndedEarly( SectionEndInfo const& endInfo ) override;\n\n        auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n        void benchmarkPreparing( std::string const& name ) override;\n        void benchmarkStarting( BenchmarkInfo const& info ) override;\n        void benchmarkEnded( BenchmarkStats<> const& stats ) override;\n        void benchmarkFailed( std::string const& error ) override;\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n        void pushScopedMessage( MessageInfo const& message ) override;\n        void popScopedMessage( MessageInfo const& message ) override;\n\n        void emplaceUnscopedMessage( MessageBuilder const& builder ) override;\n\n        std::string getCurrentTestName() const override;\n\n        const AssertionResult* getLastResult() const override;\n\n        void exceptionEarlyReported() override;\n\n        void handleFatalErrorCondition( StringRef message ) override;\n\n        bool lastAssertionPassed() override;\n\n        void assertionPassed() override;\n\n    public:\n        // !TBD We need to do this another way!\n        bool aborting() const final;\n\n    private:\n\n        void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );\n        void invokeActiveTestCase();\n\n        void resetAssertionInfo();\n        bool testForMissingAssertions( Counts& assertions );\n\n        void assertionEnded( AssertionResult const& result );\n        void reportExpr\n                (   AssertionInfo const &info,\n                    ResultWas::OfType resultType,\n                    ITransientExpression const *expr,\n                    bool negated );\n\n        void populateReaction( AssertionReaction& reaction );\n\n    private:\n\n        void handleUnfinishedSections();\n\n        TestRunInfo m_runInfo;\n        IMutableContext& m_context;\n        TestCase const* m_activeTestCase = nullptr;\n        ITracker* m_testCaseTracker = nullptr;\n        Option<AssertionResult> m_lastResult;\n\n        IConfigPtr m_config;\n        Totals m_totals;\n        IStreamingReporterPtr m_reporter;\n        std::vector<MessageInfo> m_messages;\n        std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */\n        AssertionInfo m_lastAssertionInfo;\n        std::vector<SectionEndInfo> m_unfinishedSections;\n        std::vector<ITracker*> m_activeSections;\n        TrackerContext m_trackerContext;\n        bool m_lastAssertionPassed = false;\n        bool m_shouldReportUnexpected = true;\n        bool m_includeSuccessfulResults;\n    };\n\n    void seedRng(IConfig const& config);\n    unsigned int rngSeed();\n} // end namespace Catch\n\n// end catch_run_context.h\nnamespace Catch {\n\n    namespace {\n        auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {\n            expr.streamReconstructedExpression( os );\n            return os;\n        }\n    }\n\n    LazyExpression::LazyExpression( bool isNegated )\n    :   m_isNegated( isNegated )\n    {}\n\n    LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}\n\n    LazyExpression::operator bool() const {\n        return m_transientExpression != nullptr;\n    }\n\n    auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {\n        if( lazyExpr.m_isNegated )\n            os << \"!\";\n\n        if( lazyExpr ) {\n            if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )\n                os << \"(\" << *lazyExpr.m_transientExpression << \")\";\n            else\n                os << *lazyExpr.m_transientExpression;\n        }\n        else {\n            os << \"{** error - unchecked empty expression requested **}\";\n        }\n        return os;\n    }\n\n    AssertionHandler::AssertionHandler\n        (   StringRef const& macroName,\n            SourceLineInfo const& lineInfo,\n            StringRef capturedExpression,\n            ResultDisposition::Flags resultDisposition )\n    :   m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },\n        m_resultCapture( getResultCapture() )\n    {}\n\n    void AssertionHandler::handleExpr( ITransientExpression const& expr ) {\n        m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );\n    }\n    void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {\n        m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );\n    }\n\n    auto AssertionHandler::allowThrows() const -> bool {\n        return getCurrentContext().getConfig()->allowThrows();\n    }\n\n    void AssertionHandler::complete() {\n        setCompleted();\n        if( m_reaction.shouldDebugBreak ) {\n\n            // If you find your debugger stopping you here then go one level up on the\n            // call-stack for the code that caused it (typically a failed assertion)\n\n            // (To go back to the test and change execution, jump over the throw, next)\n            CATCH_BREAK_INTO_DEBUGGER();\n        }\n        if (m_reaction.shouldThrow) {\n#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)\n            throw Catch::TestFailureException();\n#else\n            CATCH_ERROR( \"Test failure requires aborting test!\" );\n#endif\n        }\n    }\n    void AssertionHandler::setCompleted() {\n        m_completed = true;\n    }\n\n    void AssertionHandler::handleUnexpectedInflightException() {\n        m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );\n    }\n\n    void AssertionHandler::handleExceptionThrownAsExpected() {\n        m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);\n    }\n    void AssertionHandler::handleExceptionNotThrownAsExpected() {\n        m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);\n    }\n\n    void AssertionHandler::handleUnexpectedExceptionNotThrown() {\n        m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );\n    }\n\n    void AssertionHandler::handleThrowingCallSkipped() {\n        m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);\n    }\n\n    // This is the overload that takes a string and infers the Equals matcher from it\n    // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp\n    void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString  ) {\n        handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );\n    }\n\n} // namespace Catch\n// end catch_assertionhandler.cpp\n// start catch_assertionresult.cpp\n\nnamespace Catch {\n    AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):\n        lazyExpression(_lazyExpression),\n        resultType(_resultType) {}\n\n    std::string AssertionResultData::reconstructExpression() const {\n\n        if( reconstructedExpression.empty() ) {\n            if( lazyExpression ) {\n                ReusableStringStream rss;\n                rss << lazyExpression;\n                reconstructedExpression = rss.str();\n            }\n        }\n        return reconstructedExpression;\n    }\n\n    AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )\n    :   m_info( info ),\n        m_resultData( data )\n    {}\n\n    // Result was a success\n    bool AssertionResult::succeeded() const {\n        return Catch::isOk( m_resultData.resultType );\n    }\n\n    // Result was a success, or failure is suppressed\n    bool AssertionResult::isOk() const {\n        return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );\n    }\n\n    ResultWas::OfType AssertionResult::getResultType() const {\n        return m_resultData.resultType;\n    }\n\n    bool AssertionResult::hasExpression() const {\n        return !m_info.capturedExpression.empty();\n    }\n\n    bool AssertionResult::hasMessage() const {\n        return !m_resultData.message.empty();\n    }\n\n    std::string AssertionResult::getExpression() const {\n        // Possibly overallocating by 3 characters should be basically free\n        std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);\n        if (isFalseTest(m_info.resultDisposition)) {\n            expr += \"!(\";\n        }\n        expr += m_info.capturedExpression;\n        if (isFalseTest(m_info.resultDisposition)) {\n            expr += ')';\n        }\n        return expr;\n    }\n\n    std::string AssertionResult::getExpressionInMacro() const {\n        std::string expr;\n        if( m_info.macroName.empty() )\n            expr = static_cast<std::string>(m_info.capturedExpression);\n        else {\n            expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );\n            expr += m_info.macroName;\n            expr += \"( \";\n            expr += m_info.capturedExpression;\n            expr += \" )\";\n        }\n        return expr;\n    }\n\n    bool AssertionResult::hasExpandedExpression() const {\n        return hasExpression() && getExpandedExpression() != getExpression();\n    }\n\n    std::string AssertionResult::getExpandedExpression() const {\n        std::string expr = m_resultData.reconstructExpression();\n        return expr.empty()\n                ? getExpression()\n                : expr;\n    }\n\n    std::string AssertionResult::getMessage() const {\n        return m_resultData.message;\n    }\n    SourceLineInfo AssertionResult::getSourceInfo() const {\n        return m_info.lineInfo;\n    }\n\n    StringRef AssertionResult::getTestMacroName() const {\n        return m_info.macroName;\n    }\n\n} // end namespace Catch\n// end catch_assertionresult.cpp\n// start catch_capture_matchers.cpp\n\nnamespace Catch {\n\n    using StringMatcher = Matchers::Impl::MatcherBase<std::string>;\n\n    // This is the general overload that takes a any string matcher\n    // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers\n    // the Equals matcher (so the header does not mention matchers)\n    void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString  ) {\n        std::string exceptionMessage = Catch::translateActiveException();\n        MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );\n        handler.handleExpr( expr );\n    }\n\n} // namespace Catch\n// end catch_capture_matchers.cpp\n// start catch_commandline.cpp\n\n// start catch_commandline.h\n\n// start catch_clara.h\n\n// Use Catch's value for console width (store Clara's off to the side, if present)\n#ifdef CLARA_CONFIG_CONSOLE_WIDTH\n#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH\n#undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH\n#endif\n#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wweak-vtables\"\n#pragma clang diagnostic ignored \"-Wexit-time-destructors\"\n#pragma clang diagnostic ignored \"-Wshadow\"\n#endif\n\n// start clara.hpp\n// Copyright 2017 Two Blue Cubes Ltd. All rights reserved.\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// See https://github.com/philsquared/Clara for more details\n\n// Clara v1.1.5\n\n\n#ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH\n#define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80\n#endif\n\n#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH\n#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH\n#endif\n\n#ifndef CLARA_CONFIG_OPTIONAL_TYPE\n#ifdef __has_include\n#if __has_include(<optional>) && __cplusplus >= 201703L\n#include <optional>\n#define CLARA_CONFIG_OPTIONAL_TYPE std::optional\n#endif\n#endif\n#endif\n\n// ----------- #included from clara_textflow.hpp -----------\n\n// TextFlowCpp\n//\n// A single-header library for wrapping and laying out basic text, by Phil Nash\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// This project is hosted at https://github.com/philsquared/textflowcpp\n\n\n#include <cassert>\n#include <ostream>\n#include <sstream>\n#include <vector>\n\n#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH\n#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80\n#endif\n\nnamespace Catch {\nnamespace clara {\nnamespace TextFlow {\n\ninline auto isWhitespace(char c) -> bool {\n\tstatic std::string chars = \" \\t\\n\\r\";\n\treturn chars.find(c) != std::string::npos;\n}\ninline auto isBreakableBefore(char c) -> bool {\n\tstatic std::string chars = \"[({<|\";\n\treturn chars.find(c) != std::string::npos;\n}\ninline auto isBreakableAfter(char c) -> bool {\n\tstatic std::string chars = \"])}>.,:;*+-=&/\\\\\";\n\treturn chars.find(c) != std::string::npos;\n}\n\nclass Columns;\n\nclass Column {\n\tstd::vector<std::string> m_strings;\n\tsize_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;\n\tsize_t m_indent = 0;\n\tsize_t m_initialIndent = std::string::npos;\n\npublic:\n\tclass iterator {\n\t\tfriend Column;\n\n\t\tColumn const& m_column;\n\t\tsize_t m_stringIndex = 0;\n\t\tsize_t m_pos = 0;\n\n\t\tsize_t m_len = 0;\n\t\tsize_t m_end = 0;\n\t\tbool m_suffix = false;\n\n\t\titerator(Column const& column, size_t stringIndex)\n\t\t\t: m_column(column),\n\t\t\tm_stringIndex(stringIndex) {}\n\n\t\tauto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }\n\n\t\tauto isBoundary(size_t at) const -> bool {\n\t\t\tassert(at > 0);\n\t\t\tassert(at <= line().size());\n\n\t\t\treturn at == line().size() ||\n\t\t\t\t(isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||\n\t\t\t\tisBreakableBefore(line()[at]) ||\n\t\t\t\tisBreakableAfter(line()[at - 1]);\n\t\t}\n\n\t\tvoid calcLength() {\n\t\t\tassert(m_stringIndex < m_column.m_strings.size());\n\n\t\t\tm_suffix = false;\n\t\t\tauto width = m_column.m_width - indent();\n\t\t\tm_end = m_pos;\n\t\t\tif (line()[m_pos] == '\\n') {\n\t\t\t\t++m_end;\n\t\t\t}\n\t\t\twhile (m_end < line().size() && line()[m_end] != '\\n')\n\t\t\t\t++m_end;\n\n\t\t\tif (m_end < m_pos + width) {\n\t\t\t\tm_len = m_end - m_pos;\n\t\t\t} else {\n\t\t\t\tsize_t len = width;\n\t\t\t\twhile (len > 0 && !isBoundary(m_pos + len))\n\t\t\t\t\t--len;\n\t\t\t\twhile (len > 0 && isWhitespace(line()[m_pos + len - 1]))\n\t\t\t\t\t--len;\n\n\t\t\t\tif (len > 0) {\n\t\t\t\t\tm_len = len;\n\t\t\t\t} else {\n\t\t\t\t\tm_suffix = true;\n\t\t\t\t\tm_len = width - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tauto indent() const -> size_t {\n\t\t\tauto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;\n\t\t\treturn initial == std::string::npos ? m_column.m_indent : initial;\n\t\t}\n\n\t\tauto addIndentAndSuffix(std::string const &plain) const -> std::string {\n\t\t\treturn std::string(indent(), ' ') + (m_suffix ? plain + \"-\" : plain);\n\t\t}\n\n\tpublic:\n\t\tusing difference_type = std::ptrdiff_t;\n\t\tusing value_type = std::string;\n\t\tusing pointer = value_type * ;\n\t\tusing reference = value_type & ;\n\t\tusing iterator_category = std::forward_iterator_tag;\n\n\t\texplicit iterator(Column const& column) : m_column(column) {\n\t\t\tassert(m_column.m_width > m_column.m_indent);\n\t\t\tassert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);\n\t\t\tcalcLength();\n\t\t\tif (m_len == 0)\n\t\t\t\tm_stringIndex++; // Empty string\n\t\t}\n\n\t\tauto operator *() const -> std::string {\n\t\t\tassert(m_stringIndex < m_column.m_strings.size());\n\t\t\tassert(m_pos <= m_end);\n\t\t\treturn addIndentAndSuffix(line().substr(m_pos, m_len));\n\t\t}\n\n\t\tauto operator ++() -> iterator& {\n\t\t\tm_pos += m_len;\n\t\t\tif (m_pos < line().size() && line()[m_pos] == '\\n')\n\t\t\t\tm_pos += 1;\n\t\t\telse\n\t\t\t\twhile (m_pos < line().size() && isWhitespace(line()[m_pos]))\n\t\t\t\t\t++m_pos;\n\n\t\t\tif (m_pos == line().size()) {\n\t\t\t\tm_pos = 0;\n\t\t\t\t++m_stringIndex;\n\t\t\t}\n\t\t\tif (m_stringIndex < m_column.m_strings.size())\n\t\t\t\tcalcLength();\n\t\t\treturn *this;\n\t\t}\n\t\tauto operator ++(int) -> iterator {\n\t\t\titerator prev(*this);\n\t\t\toperator++();\n\t\t\treturn prev;\n\t\t}\n\n\t\tauto operator ==(iterator const& other) const -> bool {\n\t\t\treturn\n\t\t\t\tm_pos == other.m_pos &&\n\t\t\t\tm_stringIndex == other.m_stringIndex &&\n\t\t\t\t&m_column == &other.m_column;\n\t\t}\n\t\tauto operator !=(iterator const& other) const -> bool {\n\t\t\treturn !operator==(other);\n\t\t}\n\t};\n\tusing const_iterator = iterator;\n\n\texplicit Column(std::string const& text) { m_strings.push_back(text); }\n\n\tauto width(size_t newWidth) -> Column& {\n\t\tassert(newWidth > 0);\n\t\tm_width = newWidth;\n\t\treturn *this;\n\t}\n\tauto indent(size_t newIndent) -> Column& {\n\t\tm_indent = newIndent;\n\t\treturn *this;\n\t}\n\tauto initialIndent(size_t newIndent) -> Column& {\n\t\tm_initialIndent = newIndent;\n\t\treturn *this;\n\t}\n\n\tauto width() const -> size_t { return m_width; }\n\tauto begin() const -> iterator { return iterator(*this); }\n\tauto end() const -> iterator { return { *this, m_strings.size() }; }\n\n\tinline friend std::ostream& operator << (std::ostream& os, Column const& col) {\n\t\tbool first = true;\n\t\tfor (auto line : col) {\n\t\t\tif (first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tos << \"\\n\";\n\t\t\tos << line;\n\t\t}\n\t\treturn os;\n\t}\n\n\tauto operator + (Column const& other)->Columns;\n\n\tauto toString() const -> std::string {\n\t\tstd::ostringstream oss;\n\t\toss << *this;\n\t\treturn oss.str();\n\t}\n};\n\nclass Spacer : public Column {\n\npublic:\n\texplicit Spacer(size_t spaceWidth) : Column(\"\") {\n\t\twidth(spaceWidth);\n\t}\n};\n\nclass Columns {\n\tstd::vector<Column> m_columns;\n\npublic:\n\n\tclass iterator {\n\t\tfriend Columns;\n\t\tstruct EndTag {};\n\n\t\tstd::vector<Column> const& m_columns;\n\t\tstd::vector<Column::iterator> m_iterators;\n\t\tsize_t m_activeIterators;\n\n\t\titerator(Columns const& columns, EndTag)\n\t\t\t: m_columns(columns.m_columns),\n\t\t\tm_activeIterators(0) {\n\t\t\tm_iterators.reserve(m_columns.size());\n\n\t\t\tfor (auto const& col : m_columns)\n\t\t\t\tm_iterators.push_back(col.end());\n\t\t}\n\n\tpublic:\n\t\tusing difference_type = std::ptrdiff_t;\n\t\tusing value_type = std::string;\n\t\tusing pointer = value_type * ;\n\t\tusing reference = value_type & ;\n\t\tusing iterator_category = std::forward_iterator_tag;\n\n\t\texplicit iterator(Columns const& columns)\n\t\t\t: m_columns(columns.m_columns),\n\t\t\tm_activeIterators(m_columns.size()) {\n\t\t\tm_iterators.reserve(m_columns.size());\n\n\t\t\tfor (auto const& col : m_columns)\n\t\t\t\tm_iterators.push_back(col.begin());\n\t\t}\n\n\t\tauto operator ==(iterator const& other) const -> bool {\n\t\t\treturn m_iterators == other.m_iterators;\n\t\t}\n\t\tauto operator !=(iterator const& other) const -> bool {\n\t\t\treturn m_iterators != other.m_iterators;\n\t\t}\n\t\tauto operator *() const -> std::string {\n\t\t\tstd::string row, padding;\n\n\t\t\tfor (size_t i = 0; i < m_columns.size(); ++i) {\n\t\t\t\tauto width = m_columns[i].width();\n\t\t\t\tif (m_iterators[i] != m_columns[i].end()) {\n\t\t\t\t\tstd::string col = *m_iterators[i];\n\t\t\t\t\trow += padding + col;\n\t\t\t\t\tif (col.size() < width)\n\t\t\t\t\t\tpadding = std::string(width - col.size(), ' ');\n\t\t\t\t\telse\n\t\t\t\t\t\tpadding = \"\";\n\t\t\t\t} else {\n\t\t\t\t\tpadding += std::string(width, ' ');\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn row;\n\t\t}\n\t\tauto operator ++() -> iterator& {\n\t\t\tfor (size_t i = 0; i < m_columns.size(); ++i) {\n\t\t\t\tif (m_iterators[i] != m_columns[i].end())\n\t\t\t\t\t++m_iterators[i];\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t\tauto operator ++(int) -> iterator {\n\t\t\titerator prev(*this);\n\t\t\toperator++();\n\t\t\treturn prev;\n\t\t}\n\t};\n\tusing const_iterator = iterator;\n\n\tauto begin() const -> iterator { return iterator(*this); }\n\tauto end() const -> iterator { return { *this, iterator::EndTag() }; }\n\n\tauto operator += (Column const& col) -> Columns& {\n\t\tm_columns.push_back(col);\n\t\treturn *this;\n\t}\n\tauto operator + (Column const& col) -> Columns {\n\t\tColumns combined = *this;\n\t\tcombined += col;\n\t\treturn combined;\n\t}\n\n\tinline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {\n\n\t\tbool first = true;\n\t\tfor (auto line : cols) {\n\t\t\tif (first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tos << \"\\n\";\n\t\t\tos << line;\n\t\t}\n\t\treturn os;\n\t}\n\n\tauto toString() const -> std::string {\n\t\tstd::ostringstream oss;\n\t\toss << *this;\n\t\treturn oss.str();\n\t}\n};\n\ninline auto Column::operator + (Column const& other) -> Columns {\n\tColumns cols;\n\tcols += *this;\n\tcols += other;\n\treturn cols;\n}\n}\n\n}\n}\n\n// ----------- end of #include from clara_textflow.hpp -----------\n// ........... back in clara.hpp\n\n#include <cctype>\n#include <string>\n#include <memory>\n#include <set>\n#include <algorithm>\n\n#if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )\n#define CATCH_PLATFORM_WINDOWS\n#endif\n\nnamespace Catch { namespace clara {\nnamespace detail {\n\n    // Traits for extracting arg and return type of lambdas (for single argument lambdas)\n    template<typename L>\n    struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};\n\n    template<typename ClassT, typename ReturnT, typename... Args>\n    struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {\n        static const bool isValid = false;\n    };\n\n    template<typename ClassT, typename ReturnT, typename ArgT>\n    struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {\n        static const bool isValid = true;\n        using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;\n        using ReturnType = ReturnT;\n    };\n\n    class TokenStream;\n\n    // Transport for raw args (copied from main args, or supplied via init list for testing)\n    class Args {\n        friend TokenStream;\n        std::string m_exeName;\n        std::vector<std::string> m_args;\n\n    public:\n        Args( int argc, char const* const* argv )\n            : m_exeName(argv[0]),\n              m_args(argv + 1, argv + argc) {}\n\n        Args( std::initializer_list<std::string> args )\n        :   m_exeName( *args.begin() ),\n            m_args( args.begin()+1, args.end() )\n        {}\n\n        auto exeName() const -> std::string {\n            return m_exeName;\n        }\n    };\n\n    // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string\n    // may encode an option + its argument if the : or = form is used\n    enum class TokenType {\n        Option, Argument\n    };\n    struct Token {\n        TokenType type;\n        std::string token;\n    };\n\n    inline auto isOptPrefix( char c ) -> bool {\n        return c == '-'\n#ifdef CATCH_PLATFORM_WINDOWS\n            || c == '/'\n#endif\n        ;\n    }\n\n    // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled\n    class TokenStream {\n        using Iterator = std::vector<std::string>::const_iterator;\n        Iterator it;\n        Iterator itEnd;\n        std::vector<Token> m_tokenBuffer;\n\n        void loadBuffer() {\n            m_tokenBuffer.resize( 0 );\n\n            // Skip any empty strings\n            while( it != itEnd && it->empty() )\n                ++it;\n\n            if( it != itEnd ) {\n                auto const &next = *it;\n                if( isOptPrefix( next[0] ) ) {\n                    auto delimiterPos = next.find_first_of( \" :=\" );\n                    if( delimiterPos != std::string::npos ) {\n                        m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );\n                        m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );\n                    } else {\n                        if( next[1] != '-' && next.size() > 2 ) {\n                            std::string opt = \"- \";\n                            for( size_t i = 1; i < next.size(); ++i ) {\n                                opt[1] = next[i];\n                                m_tokenBuffer.push_back( { TokenType::Option, opt } );\n                            }\n                        } else {\n                            m_tokenBuffer.push_back( { TokenType::Option, next } );\n                        }\n                    }\n                } else {\n                    m_tokenBuffer.push_back( { TokenType::Argument, next } );\n                }\n            }\n        }\n\n    public:\n        explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}\n\n        TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {\n            loadBuffer();\n        }\n\n        explicit operator bool() const {\n            return !m_tokenBuffer.empty() || it != itEnd;\n        }\n\n        auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }\n\n        auto operator*() const -> Token {\n            assert( !m_tokenBuffer.empty() );\n            return m_tokenBuffer.front();\n        }\n\n        auto operator->() const -> Token const * {\n            assert( !m_tokenBuffer.empty() );\n            return &m_tokenBuffer.front();\n        }\n\n        auto operator++() -> TokenStream & {\n            if( m_tokenBuffer.size() >= 2 ) {\n                m_tokenBuffer.erase( m_tokenBuffer.begin() );\n            } else {\n                if( it != itEnd )\n                    ++it;\n                loadBuffer();\n            }\n            return *this;\n        }\n    };\n\n    class ResultBase {\n    public:\n        enum Type {\n            Ok, LogicError, RuntimeError\n        };\n\n    protected:\n        ResultBase( Type type ) : m_type( type ) {}\n        virtual ~ResultBase() = default;\n\n        virtual void enforceOk() const = 0;\n\n        Type m_type;\n    };\n\n    template<typename T>\n    class ResultValueBase : public ResultBase {\n    public:\n        auto value() const -> T const & {\n            enforceOk();\n            return m_value;\n        }\n\n    protected:\n        ResultValueBase( Type type ) : ResultBase( type ) {}\n\n        ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {\n            if( m_type == ResultBase::Ok )\n                new( &m_value ) T( other.m_value );\n        }\n\n        ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {\n            new( &m_value ) T( value );\n        }\n\n        auto operator=( ResultValueBase const &other ) -> ResultValueBase & {\n            if( m_type == ResultBase::Ok )\n                m_value.~T();\n            ResultBase::operator=(other);\n            if( m_type == ResultBase::Ok )\n                new( &m_value ) T( other.m_value );\n            return *this;\n        }\n\n        ~ResultValueBase() override {\n            if( m_type == Ok )\n                m_value.~T();\n        }\n\n        union {\n            T m_value;\n        };\n    };\n\n    template<>\n    class ResultValueBase<void> : public ResultBase {\n    protected:\n        using ResultBase::ResultBase;\n    };\n\n    template<typename T = void>\n    class BasicResult : public ResultValueBase<T> {\n    public:\n        template<typename U>\n        explicit BasicResult( BasicResult<U> const &other )\n        :   ResultValueBase<T>( other.type() ),\n            m_errorMessage( other.errorMessage() )\n        {\n            assert( type() != ResultBase::Ok );\n        }\n\n        template<typename U>\n        static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }\n        static auto ok() -> BasicResult { return { ResultBase::Ok }; }\n        static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }\n        static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }\n\n        explicit operator bool() const { return m_type == ResultBase::Ok; }\n        auto type() const -> ResultBase::Type { return m_type; }\n        auto errorMessage() const -> std::string { return m_errorMessage; }\n\n    protected:\n        void enforceOk() const override {\n\n            // Errors shouldn't reach this point, but if they do\n            // the actual error message will be in m_errorMessage\n            assert( m_type != ResultBase::LogicError );\n            assert( m_type != ResultBase::RuntimeError );\n            if( m_type != ResultBase::Ok )\n                std::abort();\n        }\n\n        std::string m_errorMessage; // Only populated if resultType is an error\n\n        BasicResult( ResultBase::Type type, std::string const &message )\n        :   ResultValueBase<T>(type),\n            m_errorMessage(message)\n        {\n            assert( m_type != ResultBase::Ok );\n        }\n\n        using ResultValueBase<T>::ResultValueBase;\n        using ResultBase::m_type;\n    };\n\n    enum class ParseResultType {\n        Matched, NoMatch, ShortCircuitAll, ShortCircuitSame\n    };\n\n    class ParseState {\n    public:\n\n        ParseState( ParseResultType type, TokenStream const &remainingTokens )\n        : m_type(type),\n          m_remainingTokens( remainingTokens )\n        {}\n\n        auto type() const -> ParseResultType { return m_type; }\n        auto remainingTokens() const -> TokenStream { return m_remainingTokens; }\n\n    private:\n        ParseResultType m_type;\n        TokenStream m_remainingTokens;\n    };\n\n    using Result = BasicResult<void>;\n    using ParserResult = BasicResult<ParseResultType>;\n    using InternalParseResult = BasicResult<ParseState>;\n\n    struct HelpColumns {\n        std::string left;\n        std::string right;\n    };\n\n    template<typename T>\n    inline auto convertInto( std::string const &source, T& target ) -> ParserResult {\n        std::stringstream ss;\n        ss << source;\n        ss >> target;\n        if( ss.fail() )\n            return ParserResult::runtimeError( \"Unable to convert '\" + source + \"' to destination type\" );\n        else\n            return ParserResult::ok( ParseResultType::Matched );\n    }\n    inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {\n        target = source;\n        return ParserResult::ok( ParseResultType::Matched );\n    }\n    inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {\n        std::string srcLC = source;\n        std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );\n        if (srcLC == \"y\" || srcLC == \"1\" || srcLC == \"true\" || srcLC == \"yes\" || srcLC == \"on\")\n            target = true;\n        else if (srcLC == \"n\" || srcLC == \"0\" || srcLC == \"false\" || srcLC == \"no\" || srcLC == \"off\")\n            target = false;\n        else\n            return ParserResult::runtimeError( \"Expected a boolean value but did not recognise: '\" + source + \"'\" );\n        return ParserResult::ok( ParseResultType::Matched );\n    }\n#ifdef CLARA_CONFIG_OPTIONAL_TYPE\n    template<typename T>\n    inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {\n        T temp;\n        auto result = convertInto( source, temp );\n        if( result )\n            target = std::move(temp);\n        return result;\n    }\n#endif // CLARA_CONFIG_OPTIONAL_TYPE\n\n    struct NonCopyable {\n        NonCopyable() = default;\n        NonCopyable( NonCopyable const & ) = delete;\n        NonCopyable( NonCopyable && ) = delete;\n        NonCopyable &operator=( NonCopyable const & ) = delete;\n        NonCopyable &operator=( NonCopyable && ) = delete;\n    };\n\n    struct BoundRef : NonCopyable {\n        virtual ~BoundRef() = default;\n        virtual auto isContainer() const -> bool { return false; }\n        virtual auto isFlag() const -> bool { return false; }\n    };\n    struct BoundValueRefBase : BoundRef {\n        virtual auto setValue( std::string const &arg ) -> ParserResult = 0;\n    };\n    struct BoundFlagRefBase : BoundRef {\n        virtual auto setFlag( bool flag ) -> ParserResult = 0;\n        virtual auto isFlag() const -> bool { return true; }\n    };\n\n    template<typename T>\n    struct BoundValueRef : BoundValueRefBase {\n        T &m_ref;\n\n        explicit BoundValueRef( T &ref ) : m_ref( ref ) {}\n\n        auto setValue( std::string const &arg ) -> ParserResult override {\n            return convertInto( arg, m_ref );\n        }\n    };\n\n    template<typename T>\n    struct BoundValueRef<std::vector<T>> : BoundValueRefBase {\n        std::vector<T> &m_ref;\n\n        explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}\n\n        auto isContainer() const -> bool override { return true; }\n\n        auto setValue( std::string const &arg ) -> ParserResult override {\n            T temp;\n            auto result = convertInto( arg, temp );\n            if( result )\n                m_ref.push_back( temp );\n            return result;\n        }\n    };\n\n    struct BoundFlagRef : BoundFlagRefBase {\n        bool &m_ref;\n\n        explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}\n\n        auto setFlag( bool flag ) -> ParserResult override {\n            m_ref = flag;\n            return ParserResult::ok( ParseResultType::Matched );\n        }\n    };\n\n    template<typename ReturnType>\n    struct LambdaInvoker {\n        static_assert( std::is_same<ReturnType, ParserResult>::value, \"Lambda must return void or clara::ParserResult\" );\n\n        template<typename L, typename ArgType>\n        static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {\n            return lambda( arg );\n        }\n    };\n\n    template<>\n    struct LambdaInvoker<void> {\n        template<typename L, typename ArgType>\n        static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {\n            lambda( arg );\n            return ParserResult::ok( ParseResultType::Matched );\n        }\n    };\n\n    template<typename ArgType, typename L>\n    inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {\n        ArgType temp{};\n        auto result = convertInto( arg, temp );\n        return !result\n           ? result\n           : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );\n    }\n\n    template<typename L>\n    struct BoundLambda : BoundValueRefBase {\n        L m_lambda;\n\n        static_assert( UnaryLambdaTraits<L>::isValid, \"Supplied lambda must take exactly one argument\" );\n        explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}\n\n        auto setValue( std::string const &arg ) -> ParserResult override {\n            return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );\n        }\n    };\n\n    template<typename L>\n    struct BoundFlagLambda : BoundFlagRefBase {\n        L m_lambda;\n\n        static_assert( UnaryLambdaTraits<L>::isValid, \"Supplied lambda must take exactly one argument\" );\n        static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, \"flags must be boolean\" );\n\n        explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}\n\n        auto setFlag( bool flag ) -> ParserResult override {\n            return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );\n        }\n    };\n\n    enum class Optionality { Optional, Required };\n\n    struct Parser;\n\n    class ParserBase {\n    public:\n        virtual ~ParserBase() = default;\n        virtual auto validate() const -> Result { return Result::ok(); }\n        virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult  = 0;\n        virtual auto cardinality() const -> size_t { return 1; }\n\n        auto parse( Args const &args ) const -> InternalParseResult {\n            return parse( args.exeName(), TokenStream( args ) );\n        }\n    };\n\n    template<typename DerivedT>\n    class ComposableParserImpl : public ParserBase {\n    public:\n        template<typename T>\n        auto operator|( T const &other ) const -> Parser;\n\n\t\ttemplate<typename T>\n        auto operator+( T const &other ) const -> Parser;\n    };\n\n    // Common code and state for Args and Opts\n    template<typename DerivedT>\n    class ParserRefImpl : public ComposableParserImpl<DerivedT> {\n    protected:\n        Optionality m_optionality = Optionality::Optional;\n        std::shared_ptr<BoundRef> m_ref;\n        std::string m_hint;\n        std::string m_description;\n\n        explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}\n\n    public:\n        template<typename T>\n        ParserRefImpl( T &ref, std::string const &hint )\n        :   m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),\n            m_hint( hint )\n        {}\n\n        template<typename LambdaT>\n        ParserRefImpl( LambdaT const &ref, std::string const &hint )\n        :   m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),\n            m_hint(hint)\n        {}\n\n        auto operator()( std::string const &description ) -> DerivedT & {\n            m_description = description;\n            return static_cast<DerivedT &>( *this );\n        }\n\n        auto optional() -> DerivedT & {\n            m_optionality = Optionality::Optional;\n            return static_cast<DerivedT &>( *this );\n        };\n\n        auto required() -> DerivedT & {\n            m_optionality = Optionality::Required;\n            return static_cast<DerivedT &>( *this );\n        };\n\n        auto isOptional() const -> bool {\n            return m_optionality == Optionality::Optional;\n        }\n\n        auto cardinality() const -> size_t override {\n            if( m_ref->isContainer() )\n                return 0;\n            else\n                return 1;\n        }\n\n        auto hint() const -> std::string { return m_hint; }\n    };\n\n    class ExeName : public ComposableParserImpl<ExeName> {\n        std::shared_ptr<std::string> m_name;\n        std::shared_ptr<BoundValueRefBase> m_ref;\n\n        template<typename LambdaT>\n        static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {\n            return std::make_shared<BoundLambda<LambdaT>>( lambda) ;\n        }\n\n    public:\n        ExeName() : m_name( std::make_shared<std::string>( \"<executable>\" ) ) {}\n\n        explicit ExeName( std::string &ref ) : ExeName() {\n            m_ref = std::make_shared<BoundValueRef<std::string>>( ref );\n        }\n\n        template<typename LambdaT>\n        explicit ExeName( LambdaT const& lambda ) : ExeName() {\n            m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );\n        }\n\n        // The exe name is not parsed out of the normal tokens, but is handled specially\n        auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {\n            return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );\n        }\n\n        auto name() const -> std::string { return *m_name; }\n        auto set( std::string const& newName ) -> ParserResult {\n\n            auto lastSlash = newName.find_last_of( \"\\\\/\" );\n            auto filename = ( lastSlash == std::string::npos )\n                    ? newName\n                    : newName.substr( lastSlash+1 );\n\n            *m_name = filename;\n            if( m_ref )\n                return m_ref->setValue( filename );\n            else\n                return ParserResult::ok( ParseResultType::Matched );\n        }\n    };\n\n    class Arg : public ParserRefImpl<Arg> {\n    public:\n        using ParserRefImpl::ParserRefImpl;\n\n        auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {\n            auto validationResult = validate();\n            if( !validationResult )\n                return InternalParseResult( validationResult );\n\n            auto remainingTokens = tokens;\n            auto const &token = *remainingTokens;\n            if( token.type != TokenType::Argument )\n                return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );\n\n            assert( !m_ref->isFlag() );\n            auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );\n\n            auto result = valueRef->setValue( remainingTokens->token );\n            if( !result )\n                return InternalParseResult( result );\n            else\n                return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );\n        }\n    };\n\n    inline auto normaliseOpt( std::string const &optName ) -> std::string {\n#ifdef CATCH_PLATFORM_WINDOWS\n        if( optName[0] == '/' )\n            return \"-\" + optName.substr( 1 );\n        else\n#endif\n            return optName;\n    }\n\n    class Opt : public ParserRefImpl<Opt> {\n    protected:\n        std::vector<std::string> m_optNames;\n\n    public:\n        template<typename LambdaT>\n        explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}\n\n        explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}\n\n        template<typename LambdaT>\n        Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}\n\n        template<typename T>\n        Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}\n\n        auto operator[]( std::string const &optName ) -> Opt & {\n            m_optNames.push_back( optName );\n            return *this;\n        }\n\n        auto getHelpColumns() const -> std::vector<HelpColumns> {\n            std::ostringstream oss;\n            bool first = true;\n            for( auto const &opt : m_optNames ) {\n                if (first)\n                    first = false;\n                else\n                    oss << \", \";\n                oss << opt;\n            }\n            if( !m_hint.empty() )\n                oss << \" <\" << m_hint << \">\";\n            return { { oss.str(), m_description } };\n        }\n\n        auto isMatch( std::string const &optToken ) const -> bool {\n            auto normalisedToken = normaliseOpt( optToken );\n            for( auto const &name : m_optNames ) {\n                if( normaliseOpt( name ) == normalisedToken )\n                    return true;\n            }\n            return false;\n        }\n\n        using ParserBase::parse;\n\n        auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {\n            auto validationResult = validate();\n            if( !validationResult )\n                return InternalParseResult( validationResult );\n\n            auto remainingTokens = tokens;\n            if( remainingTokens && remainingTokens->type == TokenType::Option ) {\n                auto const &token = *remainingTokens;\n                if( isMatch(token.token ) ) {\n                    if( m_ref->isFlag() ) {\n                        auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );\n                        auto result = flagRef->setFlag( true );\n                        if( !result )\n                            return InternalParseResult( result );\n                        if( result.value() == ParseResultType::ShortCircuitAll )\n                            return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );\n                    } else {\n                        auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );\n                        ++remainingTokens;\n                        if( !remainingTokens )\n                            return InternalParseResult::runtimeError( \"Expected argument following \" + token.token );\n                        auto const &argToken = *remainingTokens;\n                        if( argToken.type != TokenType::Argument )\n                            return InternalParseResult::runtimeError( \"Expected argument following \" + token.token );\n                        auto result = valueRef->setValue( argToken.token );\n                        if( !result )\n                            return InternalParseResult( result );\n                        if( result.value() == ParseResultType::ShortCircuitAll )\n                            return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );\n                    }\n                    return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );\n                }\n            }\n            return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );\n        }\n\n        auto validate() const -> Result override {\n            if( m_optNames.empty() )\n                return Result::logicError( \"No options supplied to Opt\" );\n            for( auto const &name : m_optNames ) {\n                if( name.empty() )\n                    return Result::logicError( \"Option name cannot be empty\" );\n#ifdef CATCH_PLATFORM_WINDOWS\n                if( name[0] != '-' && name[0] != '/' )\n                    return Result::logicError( \"Option name must begin with '-' or '/'\" );\n#else\n                if( name[0] != '-' )\n                    return Result::logicError( \"Option name must begin with '-'\" );\n#endif\n            }\n            return ParserRefImpl::validate();\n        }\n    };\n\n    struct Help : Opt {\n        Help( bool &showHelpFlag )\n        :   Opt([&]( bool flag ) {\n                showHelpFlag = flag;\n                return ParserResult::ok( ParseResultType::ShortCircuitAll );\n            })\n        {\n            static_cast<Opt &>( *this )\n                    (\"display usage information\")\n                    [\"-?\"][\"-h\"][\"--help\"]\n                    .optional();\n        }\n    };\n\n    struct Parser : ParserBase {\n\n        mutable ExeName m_exeName;\n        std::vector<Opt> m_options;\n        std::vector<Arg> m_args;\n\n        auto operator|=( ExeName const &exeName ) -> Parser & {\n            m_exeName = exeName;\n            return *this;\n        }\n\n        auto operator|=( Arg const &arg ) -> Parser & {\n            m_args.push_back(arg);\n            return *this;\n        }\n\n        auto operator|=( Opt const &opt ) -> Parser & {\n            m_options.push_back(opt);\n            return *this;\n        }\n\n        auto operator|=( Parser const &other ) -> Parser & {\n            m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());\n            m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());\n            return *this;\n        }\n\n        template<typename T>\n        auto operator|( T const &other ) const -> Parser {\n            return Parser( *this ) |= other;\n        }\n\n        // Forward deprecated interface with '+' instead of '|'\n        template<typename T>\n        auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }\n        template<typename T>\n        auto operator+( T const &other ) const -> Parser { return operator|( other ); }\n\n        auto getHelpColumns() const -> std::vector<HelpColumns> {\n            std::vector<HelpColumns> cols;\n            for (auto const &o : m_options) {\n                auto childCols = o.getHelpColumns();\n                cols.insert( cols.end(), childCols.begin(), childCols.end() );\n            }\n            return cols;\n        }\n\n        void writeToStream( std::ostream &os ) const {\n            if (!m_exeName.name().empty()) {\n                os << \"usage:\\n\" << \"  \" << m_exeName.name() << \" \";\n                bool required = true, first = true;\n                for( auto const &arg : m_args ) {\n                    if (first)\n                        first = false;\n                    else\n                        os << \" \";\n                    if( arg.isOptional() && required ) {\n                        os << \"[\";\n                        required = false;\n                    }\n                    os << \"<\" << arg.hint() << \">\";\n                    if( arg.cardinality() == 0 )\n                        os << \" ... \";\n                }\n                if( !required )\n                    os << \"]\";\n                if( !m_options.empty() )\n                    os << \" options\";\n                os << \"\\n\\nwhere options are:\" << std::endl;\n            }\n\n            auto rows = getHelpColumns();\n            size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;\n            size_t optWidth = 0;\n            for( auto const &cols : rows )\n                optWidth = (std::max)(optWidth, cols.left.size() + 2);\n\n            optWidth = (std::min)(optWidth, consoleWidth/2);\n\n            for( auto const &cols : rows ) {\n                auto row =\n                        TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +\n                        TextFlow::Spacer(4) +\n                        TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );\n                os << row << std::endl;\n            }\n        }\n\n        friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {\n            parser.writeToStream( os );\n            return os;\n        }\n\n        auto validate() const -> Result override {\n            for( auto const &opt : m_options ) {\n                auto result = opt.validate();\n                if( !result )\n                    return result;\n            }\n            for( auto const &arg : m_args ) {\n                auto result = arg.validate();\n                if( !result )\n                    return result;\n            }\n            return Result::ok();\n        }\n\n        using ParserBase::parse;\n\n        auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {\n\n            struct ParserInfo {\n                ParserBase const* parser = nullptr;\n                size_t count = 0;\n            };\n            const size_t totalParsers = m_options.size() + m_args.size();\n            assert( totalParsers < 512 );\n            // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do\n            ParserInfo parseInfos[512];\n\n            {\n                size_t i = 0;\n                for (auto const &opt : m_options) parseInfos[i++].parser = &opt;\n                for (auto const &arg : m_args) parseInfos[i++].parser = &arg;\n            }\n\n            m_exeName.set( exeName );\n\n            auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );\n            while( result.value().remainingTokens() ) {\n                bool tokenParsed = false;\n\n                for( size_t i = 0; i < totalParsers; ++i ) {\n                    auto&  parseInfo = parseInfos[i];\n                    if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {\n                        result = parseInfo.parser->parse(exeName, result.value().remainingTokens());\n                        if (!result)\n                            return result;\n                        if (result.value().type() != ParseResultType::NoMatch) {\n                            tokenParsed = true;\n                            ++parseInfo.count;\n                            break;\n                        }\n                    }\n                }\n\n                if( result.value().type() == ParseResultType::ShortCircuitAll )\n                    return result;\n                if( !tokenParsed )\n                    return InternalParseResult::runtimeError( \"Unrecognised token: \" + result.value().remainingTokens()->token );\n            }\n            // !TBD Check missing required options\n            return result;\n        }\n    };\n\n    template<typename DerivedT>\n    template<typename T>\n    auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {\n        return Parser() | static_cast<DerivedT const &>( *this ) | other;\n    }\n} // namespace detail\n\n// A Combined parser\nusing detail::Parser;\n\n// A parser for options\nusing detail::Opt;\n\n// A parser for arguments\nusing detail::Arg;\n\n// Wrapper for argc, argv from main()\nusing detail::Args;\n\n// Specifies the name of the executable\nusing detail::ExeName;\n\n// Convenience wrapper for option parser that specifies the help option\nusing detail::Help;\n\n// enum of result types from a parse\nusing detail::ParseResultType;\n\n// Result type for parser operation\nusing detail::ParserResult;\n\n}} // namespace Catch::clara\n\n// end clara.hpp\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n// Restore Clara's value for console width, if present\n#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH\n#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH\n#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH\n#endif\n\n// end catch_clara.h\nnamespace Catch {\n\n    clara::Parser makeCommandLineParser( ConfigData& config );\n\n} // end namespace Catch\n\n// end catch_commandline.h\n#include <fstream>\n#include <ctime>\n\nnamespace Catch {\n\n    clara::Parser makeCommandLineParser( ConfigData& config ) {\n\n        using namespace clara;\n\n        auto const setWarning = [&]( std::string const& warning ) {\n                auto warningSet = [&]() {\n                    if( warning == \"NoAssertions\" )\n                        return WarnAbout::NoAssertions;\n\n                    if ( warning == \"NoTests\" )\n                        return WarnAbout::NoTests;\n\n                    return WarnAbout::Nothing;\n                }();\n\n                if (warningSet == WarnAbout::Nothing)\n                    return ParserResult::runtimeError( \"Unrecognised warning: '\" + warning + \"'\" );\n                config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );\n                return ParserResult::ok( ParseResultType::Matched );\n            };\n        auto const loadTestNamesFromFile = [&]( std::string const& filename ) {\n                std::ifstream f( filename.c_str() );\n                if( !f.is_open() )\n                    return ParserResult::runtimeError( \"Unable to load input file: '\" + filename + \"'\" );\n\n                std::string line;\n                while( std::getline( f, line ) ) {\n                    line = trim(line);\n                    if( !line.empty() && !startsWith( line, '#' ) ) {\n                        if( !startsWith( line, '\"' ) )\n                            line = '\"' + line + '\"';\n                        config.testsOrTags.push_back( line );\n                        config.testsOrTags.push_back( \",\" );\n\n                    }\n                }\n                //Remove comma in the end\n                if(!config.testsOrTags.empty())\n                    config.testsOrTags.erase( config.testsOrTags.end()-1 );\n\n                return ParserResult::ok( ParseResultType::Matched );\n            };\n        auto const setTestOrder = [&]( std::string const& order ) {\n                if( startsWith( \"declared\", order ) )\n                    config.runOrder = RunTests::InDeclarationOrder;\n                else if( startsWith( \"lexical\", order ) )\n                    config.runOrder = RunTests::InLexicographicalOrder;\n                else if( startsWith( \"random\", order ) )\n                    config.runOrder = RunTests::InRandomOrder;\n                else\n                    return clara::ParserResult::runtimeError( \"Unrecognised ordering: '\" + order + \"'\" );\n                return ParserResult::ok( ParseResultType::Matched );\n            };\n        auto const setRngSeed = [&]( std::string const& seed ) {\n                if( seed != \"time\" )\n                    return clara::detail::convertInto( seed, config.rngSeed );\n                config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );\n                return ParserResult::ok( ParseResultType::Matched );\n            };\n        auto const setColourUsage = [&]( std::string const& useColour ) {\n                    auto mode = toLower( useColour );\n\n                    if( mode == \"yes\" )\n                        config.useColour = UseColour::Yes;\n                    else if( mode == \"no\" )\n                        config.useColour = UseColour::No;\n                    else if( mode == \"auto\" )\n                        config.useColour = UseColour::Auto;\n                    else\n                        return ParserResult::runtimeError( \"colour mode must be one of: auto, yes or no. '\" + useColour + \"' not recognised\" );\n                return ParserResult::ok( ParseResultType::Matched );\n            };\n        auto const setWaitForKeypress = [&]( std::string const& keypress ) {\n                auto keypressLc = toLower( keypress );\n                if( keypressLc == \"start\" )\n                    config.waitForKeypress = WaitForKeypress::BeforeStart;\n                else if( keypressLc == \"exit\" )\n                    config.waitForKeypress = WaitForKeypress::BeforeExit;\n                else if( keypressLc == \"both\" )\n                    config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;\n                else\n                    return ParserResult::runtimeError( \"keypress argument must be one of: start, exit or both. '\" + keypress + \"' not recognised\" );\n            return ParserResult::ok( ParseResultType::Matched );\n            };\n        auto const setVerbosity = [&]( std::string const& verbosity ) {\n            auto lcVerbosity = toLower( verbosity );\n            if( lcVerbosity == \"quiet\" )\n                config.verbosity = Verbosity::Quiet;\n            else if( lcVerbosity == \"normal\" )\n                config.verbosity = Verbosity::Normal;\n            else if( lcVerbosity == \"high\" )\n                config.verbosity = Verbosity::High;\n            else\n                return ParserResult::runtimeError( \"Unrecognised verbosity, '\" + verbosity + \"'\" );\n            return ParserResult::ok( ParseResultType::Matched );\n        };\n        auto const setReporter = [&]( std::string const& reporter ) {\n            IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();\n\n            auto lcReporter = toLower( reporter );\n            auto result = factories.find( lcReporter );\n\n            if( factories.end() != result )\n                config.reporterName = lcReporter;\n            else\n                return ParserResult::runtimeError( \"Unrecognized reporter, '\" + reporter + \"'. Check available with --list-reporters\" );\n            return ParserResult::ok( ParseResultType::Matched );\n        };\n\n        auto cli\n            = ExeName( config.processName )\n            | Help( config.showHelp )\n            | Opt( config.listTests )\n                [\"-l\"][\"--list-tests\"]\n                ( \"list all/matching test cases\" )\n            | Opt( config.listTags )\n                [\"-t\"][\"--list-tags\"]\n                ( \"list all/matching tags\" )\n            | Opt( config.showSuccessfulTests )\n                [\"-s\"][\"--success\"]\n                ( \"include successful tests in output\" )\n            | Opt( config.shouldDebugBreak )\n                [\"-b\"][\"--break\"]\n                ( \"break into debugger on failure\" )\n            | Opt( config.noThrow )\n                [\"-e\"][\"--nothrow\"]\n                ( \"skip exception tests\" )\n            | Opt( config.showInvisibles )\n                [\"-i\"][\"--invisibles\"]\n                ( \"show invisibles (tabs, newlines)\" )\n            | Opt( config.outputFilename, \"filename\" )\n                [\"-o\"][\"--out\"]\n                ( \"output filename\" )\n            | Opt( setReporter, \"name\" )\n                [\"-r\"][\"--reporter\"]\n                ( \"reporter to use (defaults to console)\" )\n            | Opt( config.name, \"name\" )\n                [\"-n\"][\"--name\"]\n                ( \"suite name\" )\n            | Opt( [&]( bool ){ config.abortAfter = 1; } )\n                [\"-a\"][\"--abort\"]\n                ( \"abort at first failure\" )\n            | Opt( [&]( int x ){ config.abortAfter = x; }, \"no. failures\" )\n                [\"-x\"][\"--abortx\"]\n                ( \"abort after x failures\" )\n            | Opt( setWarning, \"warning name\" )\n                [\"-w\"][\"--warn\"]\n                ( \"enable warnings\" )\n            | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, \"yes|no\" )\n                [\"-d\"][\"--durations\"]\n                ( \"show test durations\" )\n            | Opt( loadTestNamesFromFile, \"filename\" )\n                [\"-f\"][\"--input-file\"]\n                ( \"load test names to run from a file\" )\n            | Opt( config.filenamesAsTags )\n                [\"-#\"][\"--filenames-as-tags\"]\n                ( \"adds a tag for the filename\" )\n            | Opt( config.sectionsToRun, \"section name\" )\n                [\"-c\"][\"--section\"]\n                ( \"specify section to run\" )\n            | Opt( setVerbosity, \"quiet|normal|high\" )\n                [\"-v\"][\"--verbosity\"]\n                ( \"set output verbosity\" )\n            | Opt( config.listTestNamesOnly )\n                [\"--list-test-names-only\"]\n                ( \"list all/matching test cases names only\" )\n            | Opt( config.listReporters )\n                [\"--list-reporters\"]\n                ( \"list all reporters\" )\n            | Opt( setTestOrder, \"decl|lex|rand\" )\n                [\"--order\"]\n                ( \"test case order (defaults to decl)\" )\n            | Opt( setRngSeed, \"'time'|number\" )\n                [\"--rng-seed\"]\n                ( \"set a specific seed for random numbers\" )\n            | Opt( setColourUsage, \"yes|no\" )\n                [\"--use-colour\"]\n                ( \"should output be colourised\" )\n            | Opt( config.libIdentify )\n                [\"--libidentify\"]\n                ( \"report name and version according to libidentify standard\" )\n            | Opt( setWaitForKeypress, \"start|exit|both\" )\n                [\"--wait-for-keypress\"]\n                ( \"waits for a keypress before exiting\" )\n            | Opt( config.benchmarkSamples, \"samples\" )\n                [\"--benchmark-samples\"]\n                ( \"number of samples to collect (default: 100)\" )\n            | Opt( config.benchmarkResamples, \"resamples\" )\n                [\"--benchmark-resamples\"]\n                ( \"number of resamples for the bootstrap (default: 100000)\" )\n            | Opt( config.benchmarkConfidenceInterval, \"confidence interval\" )\n                [\"--benchmark-confidence-interval\"]\n                ( \"confidence interval for the bootstrap (between 0 and 1, default: 0.95)\" )\n            | Opt( config.benchmarkNoAnalysis )\n                [\"--benchmark-no-analysis\"]\n                ( \"perform only measurements; do not perform any analysis\" )\n\t\t\t| Arg( config.testsOrTags, \"test name|pattern|tags\" )\n                ( \"which test or tests to use\" );\n\n        return cli;\n    }\n\n} // end namespace Catch\n// end catch_commandline.cpp\n// start catch_common.cpp\n\n#include <cstring>\n#include <ostream>\n\nnamespace Catch {\n\n    bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {\n        return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);\n    }\n    bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {\n        // We can assume that the same file will usually have the same pointer.\n        // Thus, if the pointers are the same, there is no point in calling the strcmp\n        return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));\n    }\n\n    std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {\n#ifndef __GNUG__\n        os << info.file << '(' << info.line << ')';\n#else\n        os << info.file << ':' << info.line;\n#endif\n        return os;\n    }\n\n    std::string StreamEndStop::operator+() const {\n        return std::string();\n    }\n\n    NonCopyable::NonCopyable() = default;\n    NonCopyable::~NonCopyable() = default;\n\n}\n// end catch_common.cpp\n// start catch_config.cpp\n\nnamespace Catch {\n\n    Config::Config( ConfigData const& data )\n    :   m_data( data ),\n        m_stream( openStream() )\n    {\n        // We need to trim filter specs to avoid trouble with superfluous\n        // whitespace (esp. important for bdd macros, as those are manually\n        // aligned with whitespace).\n\n        for (auto& elem : m_data.testsOrTags) {\n            elem = trim(elem);\n        }\n        for (auto& elem : m_data.sectionsToRun) {\n            elem = trim(elem);\n        }\n\n        TestSpecParser parser(ITagAliasRegistry::get());\n        if (!m_data.testsOrTags.empty()) {\n            m_hasTestFilters = true;\n            for (auto const& testOrTags : m_data.testsOrTags) {\n                parser.parse(testOrTags);\n            }\n        }\n        m_testSpec = parser.testSpec();\n    }\n\n    std::string const& Config::getFilename() const {\n        return m_data.outputFilename ;\n    }\n\n    bool Config::listTests() const          { return m_data.listTests; }\n    bool Config::listTestNamesOnly() const  { return m_data.listTestNamesOnly; }\n    bool Config::listTags() const           { return m_data.listTags; }\n    bool Config::listReporters() const      { return m_data.listReporters; }\n\n    std::string Config::getProcessName() const { return m_data.processName; }\n    std::string const& Config::getReporterName() const { return m_data.reporterName; }\n\n    std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }\n    std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }\n\n    TestSpec const& Config::testSpec() const { return m_testSpec; }\n    bool Config::hasTestFilters() const { return m_hasTestFilters; }\n\n    bool Config::showHelp() const { return m_data.showHelp; }\n\n    // IConfig interface\n    bool Config::allowThrows() const                   { return !m_data.noThrow; }\n    std::ostream& Config::stream() const               { return m_stream->stream(); }\n    std::string Config::name() const                   { return m_data.name.empty() ? m_data.processName : m_data.name; }\n    bool Config::includeSuccessfulResults() const      { return m_data.showSuccessfulTests; }\n    bool Config::warnAboutMissingAssertions() const    { return !!(m_data.warnings & WarnAbout::NoAssertions); }\n    bool Config::warnAboutNoTests() const              { return !!(m_data.warnings & WarnAbout::NoTests); }\n    ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }\n    RunTests::InWhatOrder Config::runOrder() const     { return m_data.runOrder; }\n    unsigned int Config::rngSeed() const               { return m_data.rngSeed; }\n    UseColour::YesOrNo Config::useColour() const       { return m_data.useColour; }\n    bool Config::shouldDebugBreak() const              { return m_data.shouldDebugBreak; }\n    int Config::abortAfter() const                     { return m_data.abortAfter; }\n    bool Config::showInvisibles() const                { return m_data.showInvisibles; }\n    Verbosity Config::verbosity() const                { return m_data.verbosity; }\n\n    bool Config::benchmarkNoAnalysis() const           { return m_data.benchmarkNoAnalysis; }\n    int Config::benchmarkSamples() const               { return m_data.benchmarkSamples; }\n    double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }\n    unsigned int Config::benchmarkResamples() const    { return m_data.benchmarkResamples; }\n\n    IStream const* Config::openStream() {\n        return Catch::makeStream(m_data.outputFilename);\n    }\n\n} // end namespace Catch\n// end catch_config.cpp\n// start catch_console_colour.cpp\n\n#if defined(__clang__)\n#    pragma clang diagnostic push\n#    pragma clang diagnostic ignored \"-Wexit-time-destructors\"\n#endif\n\n// start catch_errno_guard.h\n\nnamespace Catch {\n\n    class ErrnoGuard {\n    public:\n        ErrnoGuard();\n        ~ErrnoGuard();\n    private:\n        int m_oldErrno;\n    };\n\n}\n\n// end catch_errno_guard.h\n#include <sstream>\n\nnamespace Catch {\n    namespace {\n\n        struct IColourImpl {\n            virtual ~IColourImpl() = default;\n            virtual void use( Colour::Code _colourCode ) = 0;\n        };\n\n        struct NoColourImpl : IColourImpl {\n            void use( Colour::Code ) {}\n\n            static IColourImpl* instance() {\n                static NoColourImpl s_instance;\n                return &s_instance;\n            }\n        };\n\n    } // anon namespace\n} // namespace Catch\n\n#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )\n#   ifdef CATCH_PLATFORM_WINDOWS\n#       define CATCH_CONFIG_COLOUR_WINDOWS\n#   else\n#       define CATCH_CONFIG_COLOUR_ANSI\n#   endif\n#endif\n\n#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////\n\nnamespace Catch {\nnamespace {\n\n    class Win32ColourImpl : public IColourImpl {\n    public:\n        Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )\n        {\n            CONSOLE_SCREEN_BUFFER_INFO csbiInfo;\n            GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );\n            originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );\n            originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );\n        }\n\n        void use( Colour::Code _colourCode ) override {\n            switch( _colourCode ) {\n                case Colour::None:      return setTextAttribute( originalForegroundAttributes );\n                case Colour::White:     return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );\n                case Colour::Red:       return setTextAttribute( FOREGROUND_RED );\n                case Colour::Green:     return setTextAttribute( FOREGROUND_GREEN );\n                case Colour::Blue:      return setTextAttribute( FOREGROUND_BLUE );\n                case Colour::Cyan:      return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );\n                case Colour::Yellow:    return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );\n                case Colour::Grey:      return setTextAttribute( 0 );\n\n                case Colour::LightGrey:     return setTextAttribute( FOREGROUND_INTENSITY );\n                case Colour::BrightRed:     return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );\n                case Colour::BrightGreen:   return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );\n                case Colour::BrightWhite:   return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );\n                case Colour::BrightYellow:  return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );\n\n                case Colour::Bright: CATCH_INTERNAL_ERROR( \"not a colour\" );\n\n                default:\n                    CATCH_ERROR( \"Unknown colour requested\" );\n            }\n        }\n\n    private:\n        void setTextAttribute( WORD _textAttribute ) {\n            SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );\n        }\n        HANDLE stdoutHandle;\n        WORD originalForegroundAttributes;\n        WORD originalBackgroundAttributes;\n    };\n\n    IColourImpl* platformColourInstance() {\n        static Win32ColourImpl s_instance;\n\n        IConfigPtr config = getCurrentContext().getConfig();\n        UseColour::YesOrNo colourMode = config\n            ? config->useColour()\n            : UseColour::Auto;\n        if( colourMode == UseColour::Auto )\n            colourMode = UseColour::Yes;\n        return colourMode == UseColour::Yes\n            ? &s_instance\n            : NoColourImpl::instance();\n    }\n\n} // end anon namespace\n} // end namespace Catch\n\n#elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////\n\n#include <unistd.h>\n\nnamespace Catch {\nnamespace {\n\n    // use POSIX/ ANSI console terminal codes\n    // Thanks to Adam Strzelecki for original contribution\n    // (http://github.com/nanoant)\n    // https://github.com/philsquared/Catch/pull/131\n    class PosixColourImpl : public IColourImpl {\n    public:\n        void use( Colour::Code _colourCode ) override {\n            switch( _colourCode ) {\n                case Colour::None:\n                case Colour::White:     return setColour( \"[0m\" );\n                case Colour::Red:       return setColour( \"[0;31m\" );\n                case Colour::Green:     return setColour( \"[0;32m\" );\n                case Colour::Blue:      return setColour( \"[0;34m\" );\n                case Colour::Cyan:      return setColour( \"[0;36m\" );\n                case Colour::Yellow:    return setColour( \"[0;33m\" );\n                case Colour::Grey:      return setColour( \"[1;30m\" );\n\n                case Colour::LightGrey:     return setColour( \"[0;37m\" );\n                case Colour::BrightRed:     return setColour( \"[1;31m\" );\n                case Colour::BrightGreen:   return setColour( \"[1;32m\" );\n                case Colour::BrightWhite:   return setColour( \"[1;37m\" );\n                case Colour::BrightYellow:  return setColour( \"[1;33m\" );\n\n                case Colour::Bright: CATCH_INTERNAL_ERROR( \"not a colour\" );\n                default: CATCH_INTERNAL_ERROR( \"Unknown colour requested\" );\n            }\n        }\n        static IColourImpl* instance() {\n            static PosixColourImpl s_instance;\n            return &s_instance;\n        }\n\n    private:\n        void setColour( const char* _escapeCode ) {\n            getCurrentContext().getConfig()->stream()\n                << '\\033' << _escapeCode;\n        }\n    };\n\n    bool useColourOnPlatform() {\n        return\n#ifdef CATCH_PLATFORM_MAC\n            !isDebuggerActive() &&\n#endif\n#if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))\n            isatty(STDOUT_FILENO)\n#else\n            false\n#endif\n            ;\n    }\n    IColourImpl* platformColourInstance() {\n        ErrnoGuard guard;\n        IConfigPtr config = getCurrentContext().getConfig();\n        UseColour::YesOrNo colourMode = config\n            ? config->useColour()\n            : UseColour::Auto;\n        if( colourMode == UseColour::Auto )\n            colourMode = useColourOnPlatform()\n                ? UseColour::Yes\n                : UseColour::No;\n        return colourMode == UseColour::Yes\n            ? PosixColourImpl::instance()\n            : NoColourImpl::instance();\n    }\n\n} // end anon namespace\n} // end namespace Catch\n\n#else  // not Windows or ANSI ///////////////////////////////////////////////\n\nnamespace Catch {\n\n    static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }\n\n} // end namespace Catch\n\n#endif // Windows/ ANSI/ None\n\nnamespace Catch {\n\n    Colour::Colour( Code _colourCode ) { use( _colourCode ); }\n    Colour::Colour( Colour&& rhs ) noexcept {\n        m_moved = rhs.m_moved;\n        rhs.m_moved = true;\n    }\n    Colour& Colour::operator=( Colour&& rhs ) noexcept {\n        m_moved = rhs.m_moved;\n        rhs.m_moved  = true;\n        return *this;\n    }\n\n    Colour::~Colour(){ if( !m_moved ) use( None ); }\n\n    void Colour::use( Code _colourCode ) {\n        static IColourImpl* impl = platformColourInstance();\n        // Strictly speaking, this cannot possibly happen.\n        // However, under some conditions it does happen (see #1626),\n        // and this change is small enough that we can let practicality\n        // triumph over purity in this case.\n        if (impl != NULL) {\n            impl->use( _colourCode );\n        }\n    }\n\n    std::ostream& operator << ( std::ostream& os, Colour const& ) {\n        return os;\n    }\n\n} // end namespace Catch\n\n#if defined(__clang__)\n#    pragma clang diagnostic pop\n#endif\n\n// end catch_console_colour.cpp\n// start catch_context.cpp\n\nnamespace Catch {\n\n    class Context : public IMutableContext, NonCopyable {\n\n    public: // IContext\n        IResultCapture* getResultCapture() override {\n            return m_resultCapture;\n        }\n        IRunner* getRunner() override {\n            return m_runner;\n        }\n\n        IConfigPtr const& getConfig() const override {\n            return m_config;\n        }\n\n        ~Context() override;\n\n    public: // IMutableContext\n        void setResultCapture( IResultCapture* resultCapture ) override {\n            m_resultCapture = resultCapture;\n        }\n        void setRunner( IRunner* runner ) override {\n            m_runner = runner;\n        }\n        void setConfig( IConfigPtr const& config ) override {\n            m_config = config;\n        }\n\n        friend IMutableContext& getCurrentMutableContext();\n\n    private:\n        IConfigPtr m_config;\n        IRunner* m_runner = nullptr;\n        IResultCapture* m_resultCapture = nullptr;\n    };\n\n    IMutableContext *IMutableContext::currentContext = nullptr;\n\n    void IMutableContext::createContext()\n    {\n        currentContext = new Context();\n    }\n\n    void cleanUpContext() {\n        delete IMutableContext::currentContext;\n        IMutableContext::currentContext = nullptr;\n    }\n    IContext::~IContext() = default;\n    IMutableContext::~IMutableContext() = default;\n    Context::~Context() = default;\n\n    SimplePcg32& rng() {\n        static SimplePcg32 s_rng;\n        return s_rng;\n    }\n\n}\n// end catch_context.cpp\n// start catch_debug_console.cpp\n\n// start catch_debug_console.h\n\n#include <string>\n\nnamespace Catch {\n    void writeToDebugConsole( std::string const& text );\n}\n\n// end catch_debug_console.h\n#if defined(CATCH_CONFIG_ANDROID_LOGWRITE)\n#include <android/log.h>\n\n    namespace Catch {\n        void writeToDebugConsole( std::string const& text ) {\n            __android_log_write( ANDROID_LOG_DEBUG, \"Catch\", text.c_str() );\n        }\n    }\n\n#elif defined(CATCH_PLATFORM_WINDOWS)\n\n    namespace Catch {\n        void writeToDebugConsole( std::string const& text ) {\n            ::OutputDebugStringA( text.c_str() );\n        }\n    }\n\n#else\n\n    namespace Catch {\n        void writeToDebugConsole( std::string const& text ) {\n            // !TBD: Need a version for Mac/ XCode and other IDEs\n            Catch::cout() << text;\n        }\n    }\n\n#endif // Platform\n// end catch_debug_console.cpp\n// start catch_debugger.cpp\n\n#ifdef CATCH_PLATFORM_MAC\n\n#  include <assert.h>\n#  include <stdbool.h>\n#  include <sys/types.h>\n#  include <unistd.h>\n#  include <cstddef>\n#  include <ostream>\n\n#ifdef __apple_build_version__\n    // These headers will only compile with AppleClang (XCode)\n    // For other compilers (Clang, GCC, ... ) we need to exclude them\n#  include <sys/sysctl.h>\n#endif\n\n    namespace Catch {\n        #ifdef __apple_build_version__\n        // The following function is taken directly from the following technical note:\n        // https://developer.apple.com/library/archive/qa/qa1361/_index.html\n\n        // Returns true if the current process is being debugged (either\n        // running under the debugger or has a debugger attached post facto).\n        bool isDebuggerActive(){\n            int                 mib[4];\n            struct kinfo_proc   info;\n            std::size_t         size;\n\n            // Initialize the flags so that, if sysctl fails for some bizarre\n            // reason, we get a predictable result.\n\n            info.kp_proc.p_flag = 0;\n\n            // Initialize mib, which tells sysctl the info we want, in this case\n            // we're looking for information about a specific process ID.\n\n            mib[0] = CTL_KERN;\n            mib[1] = KERN_PROC;\n            mib[2] = KERN_PROC_PID;\n            mib[3] = getpid();\n\n            // Call sysctl.\n\n            size = sizeof(info);\n            if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {\n                Catch::cerr() << \"\\n** Call to sysctl failed - unable to determine if debugger is active **\\n\" << std::endl;\n                return false;\n            }\n\n            // We're being debugged if the P_TRACED flag is set.\n\n            return ( (info.kp_proc.p_flag & P_TRACED) != 0 );\n        }\n        #else\n        bool isDebuggerActive() {\n            // We need to find another way to determine this for non-appleclang compilers on macOS\n            return false;\n        }\n        #endif\n    } // namespace Catch\n\n#elif defined(CATCH_PLATFORM_LINUX)\n    #include <fstream>\n    #include <string>\n\n    namespace Catch{\n        // The standard POSIX way of detecting a debugger is to attempt to\n        // ptrace() the process, but this needs to be done from a child and not\n        // this process itself to still allow attaching to this process later\n        // if wanted, so is rather heavy. Under Linux we have the PID of the\n        // \"debugger\" (which doesn't need to be gdb, of course, it could also\n        // be strace, for example) in /proc/$PID/status, so just get it from\n        // there instead.\n        bool isDebuggerActive(){\n            // Libstdc++ has a bug, where std::ifstream sets errno to 0\n            // This way our users can properly assert over errno values\n            ErrnoGuard guard;\n            std::ifstream in(\"/proc/self/status\");\n            for( std::string line; std::getline(in, line); ) {\n                static const int PREFIX_LEN = 11;\n                if( line.compare(0, PREFIX_LEN, \"TracerPid:\\t\") == 0 ) {\n                    // We're traced if the PID is not 0 and no other PID starts\n                    // with 0 digit, so it's enough to check for just a single\n                    // character.\n                    return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';\n                }\n            }\n\n            return false;\n        }\n    } // namespace Catch\n#elif defined(_MSC_VER)\n    extern \"C\" __declspec(dllimport) int __stdcall IsDebuggerPresent();\n    namespace Catch {\n        bool isDebuggerActive() {\n            return IsDebuggerPresent() != 0;\n        }\n    }\n#elif defined(__MINGW32__)\n    extern \"C\" __declspec(dllimport) int __stdcall IsDebuggerPresent();\n    namespace Catch {\n        bool isDebuggerActive() {\n            return IsDebuggerPresent() != 0;\n        }\n    }\n#else\n    namespace Catch {\n       bool isDebuggerActive() { return false; }\n    }\n#endif // Platform\n// end catch_debugger.cpp\n// start catch_decomposer.cpp\n\nnamespace Catch {\n\n    ITransientExpression::~ITransientExpression() = default;\n\n    void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {\n        if( lhs.size() + rhs.size() < 40 &&\n                lhs.find('\\n') == std::string::npos &&\n                rhs.find('\\n') == std::string::npos )\n            os << lhs << \" \" << op << \" \" << rhs;\n        else\n            os << lhs << \"\\n\" << op << \"\\n\" << rhs;\n    }\n}\n// end catch_decomposer.cpp\n// start catch_enforce.cpp\n\n#include <stdexcept>\n\nnamespace Catch {\n#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)\n    [[noreturn]]\n    void throw_exception(std::exception const& e) {\n        Catch::cerr() << \"Catch will terminate because it needed to throw an exception.\\n\"\n                      << \"The message was: \" << e.what() << '\\n';\n        std::terminate();\n    }\n#endif\n\n    [[noreturn]]\n    void throw_logic_error(std::string const& msg) {\n        throw_exception(std::logic_error(msg));\n    }\n\n    [[noreturn]]\n    void throw_domain_error(std::string const& msg) {\n        throw_exception(std::domain_error(msg));\n    }\n\n    [[noreturn]]\n    void throw_runtime_error(std::string const& msg) {\n        throw_exception(std::runtime_error(msg));\n    }\n\n} // namespace Catch;\n// end catch_enforce.cpp\n// start catch_enum_values_registry.cpp\n// start catch_enum_values_registry.h\n\n#include <vector>\n#include <memory>\n\nnamespace Catch {\n\n    namespace Detail {\n\n        std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );\n\n        class EnumValuesRegistry : public IMutableEnumValuesRegistry {\n\n            std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;\n\n            EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;\n        };\n\n        std::vector<StringRef> parseEnums( StringRef enums );\n\n    } // Detail\n\n} // Catch\n\n// end catch_enum_values_registry.h\n\n#include <map>\n#include <cassert>\n\nnamespace Catch {\n\n    IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}\n\n    namespace Detail {\n\n        namespace {\n            // Extracts the actual name part of an enum instance\n            // In other words, it returns the Blue part of Bikeshed::Colour::Blue\n            StringRef extractInstanceName(StringRef enumInstance) {\n                // Find last occurence of \":\"\n                size_t name_start = enumInstance.size();\n                while (name_start > 0 && enumInstance[name_start - 1] != ':') {\n                    --name_start;\n                }\n                return enumInstance.substr(name_start, enumInstance.size() - name_start);\n            }\n        }\n\n        std::vector<StringRef> parseEnums( StringRef enums ) {\n            auto enumValues = splitStringRef( enums, ',' );\n            std::vector<StringRef> parsed;\n            parsed.reserve( enumValues.size() );\n            for( auto const& enumValue : enumValues ) {\n                parsed.push_back(trim(extractInstanceName(enumValue)));\n            }\n            return parsed;\n        }\n\n        EnumInfo::~EnumInfo() {}\n\n        StringRef EnumInfo::lookup( int value ) const {\n            for( auto const& valueToName : m_values ) {\n                if( valueToName.first == value )\n                    return valueToName.second;\n            }\n            return \"{** unexpected enum value **}\"_sr;\n        }\n\n        std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {\n            std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );\n            enumInfo->m_name = enumName;\n            enumInfo->m_values.reserve( values.size() );\n\n            const auto valueNames = Catch::Detail::parseEnums( allValueNames );\n            assert( valueNames.size() == values.size() );\n            std::size_t i = 0;\n            for( auto value : values )\n                enumInfo->m_values.push_back({ value, valueNames[i++] });\n\n            return enumInfo;\n        }\n\n        EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {\n            m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));\n            return *m_enumInfos.back();\n        }\n\n    } // Detail\n} // Catch\n\n// end catch_enum_values_registry.cpp\n// start catch_errno_guard.cpp\n\n#include <cerrno>\n\nnamespace Catch {\n        ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}\n        ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }\n}\n// end catch_errno_guard.cpp\n// start catch_exception_translator_registry.cpp\n\n// start catch_exception_translator_registry.h\n\n#include <vector>\n#include <string>\n#include <memory>\n\nnamespace Catch {\n\n    class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {\n    public:\n        ~ExceptionTranslatorRegistry();\n        virtual void registerTranslator( const IExceptionTranslator* translator );\n        std::string translateActiveException() const override;\n        std::string tryTranslators() const;\n\n    private:\n        std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;\n    };\n}\n\n// end catch_exception_translator_registry.h\n#ifdef __OBJC__\n#import \"Foundation/Foundation.h\"\n#endif\n\nnamespace Catch {\n\n    ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {\n    }\n\n    void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {\n        m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );\n    }\n\n#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)\n    std::string ExceptionTranslatorRegistry::translateActiveException() const {\n        try {\n#ifdef __OBJC__\n            // In Objective-C try objective-c exceptions first\n            @try {\n                return tryTranslators();\n            }\n            @catch (NSException *exception) {\n                return Catch::Detail::stringify( [exception description] );\n            }\n#else\n            // Compiling a mixed mode project with MSVC means that CLR\n            // exceptions will be caught in (...) as well. However, these\n            // do not fill-in std::current_exception and thus lead to crash\n            // when attempting rethrow.\n            // /EHa switch also causes structured exceptions to be caught\n            // here, but they fill-in current_exception properly, so\n            // at worst the output should be a little weird, instead of\n            // causing a crash.\n            if (std::current_exception() == nullptr) {\n                return \"Non C++ exception. Possibly a CLR exception.\";\n            }\n            return tryTranslators();\n#endif\n        }\n        catch( TestFailureException& ) {\n            std::rethrow_exception(std::current_exception());\n        }\n        catch( std::exception& ex ) {\n            return ex.what();\n        }\n        catch( std::string& msg ) {\n            return msg;\n        }\n        catch( const char* msg ) {\n            return msg;\n        }\n        catch(...) {\n            return \"Unknown exception\";\n        }\n    }\n\n    std::string ExceptionTranslatorRegistry::tryTranslators() const {\n        if (m_translators.empty()) {\n            std::rethrow_exception(std::current_exception());\n        } else {\n            return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());\n        }\n    }\n\n#else // ^^ Exceptions are enabled // Exceptions are disabled vv\n    std::string ExceptionTranslatorRegistry::translateActiveException() const {\n        CATCH_INTERNAL_ERROR(\"Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!\");\n    }\n\n    std::string ExceptionTranslatorRegistry::tryTranslators() const {\n        CATCH_INTERNAL_ERROR(\"Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!\");\n    }\n#endif\n\n}\n// end catch_exception_translator_registry.cpp\n// start catch_fatal_condition.cpp\n\n#if defined(__GNUC__)\n#    pragma GCC diagnostic push\n#    pragma GCC diagnostic ignored \"-Wmissing-field-initializers\"\n#endif\n\n#if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )\n\nnamespace {\n    // Report the error condition\n    void reportFatal( char const * const message ) {\n        Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );\n    }\n}\n\n#endif // signals/SEH handling\n\n#if defined( CATCH_CONFIG_WINDOWS_SEH )\n\nnamespace Catch {\n    struct SignalDefs { DWORD id; const char* name; };\n\n    // There is no 1-1 mapping between signals and windows exceptions.\n    // Windows can easily distinguish between SO and SigSegV,\n    // but SigInt, SigTerm, etc are handled differently.\n    static SignalDefs signalDefs[] = {\n        { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION),  \"SIGILL - Illegal instruction signal\" },\n        { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), \"SIGSEGV - Stack overflow\" },\n        { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), \"SIGSEGV - Segmentation violation signal\" },\n        { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), \"Divide by zero error\" },\n    };\n\n    LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {\n        for (auto const& def : signalDefs) {\n            if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {\n                reportFatal(def.name);\n            }\n        }\n        // If its not an exception we care about, pass it along.\n        // This stops us from eating debugger breaks etc.\n        return EXCEPTION_CONTINUE_SEARCH;\n    }\n\n    FatalConditionHandler::FatalConditionHandler() {\n        isSet = true;\n        // 32k seems enough for Catch to handle stack overflow,\n        // but the value was found experimentally, so there is no strong guarantee\n        guaranteeSize = 32 * 1024;\n        exceptionHandlerHandle = nullptr;\n        // Register as first handler in current chain\n        exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);\n        // Pass in guarantee size to be filled\n        SetThreadStackGuarantee(&guaranteeSize);\n    }\n\n    void FatalConditionHandler::reset() {\n        if (isSet) {\n            RemoveVectoredExceptionHandler(exceptionHandlerHandle);\n            SetThreadStackGuarantee(&guaranteeSize);\n            exceptionHandlerHandle = nullptr;\n            isSet = false;\n        }\n    }\n\n    FatalConditionHandler::~FatalConditionHandler() {\n        reset();\n    }\n\nbool FatalConditionHandler::isSet = false;\nULONG FatalConditionHandler::guaranteeSize = 0;\nPVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;\n\n} // namespace Catch\n\n#elif defined( CATCH_CONFIG_POSIX_SIGNALS )\n\nnamespace Catch {\n\n    struct SignalDefs {\n        int id;\n        const char* name;\n    };\n\n    // 32kb for the alternate stack seems to be sufficient. However, this value\n    // is experimentally determined, so that's not guaranteed.\n    static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;\n\n    static SignalDefs signalDefs[] = {\n        { SIGINT,  \"SIGINT - Terminal interrupt signal\" },\n        { SIGILL,  \"SIGILL - Illegal instruction signal\" },\n        { SIGFPE,  \"SIGFPE - Floating point error signal\" },\n        { SIGSEGV, \"SIGSEGV - Segmentation violation signal\" },\n        { SIGTERM, \"SIGTERM - Termination request signal\" },\n        { SIGABRT, \"SIGABRT - Abort (abnormal termination) signal\" }\n    };\n\n    void FatalConditionHandler::handleSignal( int sig ) {\n        char const * name = \"<unknown signal>\";\n        for (auto const& def : signalDefs) {\n            if (sig == def.id) {\n                name = def.name;\n                break;\n            }\n        }\n        reset();\n        reportFatal(name);\n        raise( sig );\n    }\n\n    FatalConditionHandler::FatalConditionHandler() {\n        isSet = true;\n        stack_t sigStack;\n        sigStack.ss_sp = altStackMem;\n        sigStack.ss_size = sigStackSize;\n        sigStack.ss_flags = 0;\n        sigaltstack(&sigStack, &oldSigStack);\n        struct sigaction sa = { };\n\n        sa.sa_handler = handleSignal;\n        sa.sa_flags = SA_ONSTACK;\n        for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {\n            sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);\n        }\n    }\n\n    FatalConditionHandler::~FatalConditionHandler() {\n        reset();\n    }\n\n    void FatalConditionHandler::reset() {\n        if( isSet ) {\n            // Set signals back to previous values -- hopefully nobody overwrote them in the meantime\n            for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {\n                sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);\n            }\n            // Return the old stack\n            sigaltstack(&oldSigStack, nullptr);\n            isSet = false;\n        }\n    }\n\n    bool FatalConditionHandler::isSet = false;\n    struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};\n    stack_t FatalConditionHandler::oldSigStack = {};\n    char FatalConditionHandler::altStackMem[sigStackSize] = {};\n\n} // namespace Catch\n\n#else\n\nnamespace Catch {\n    void FatalConditionHandler::reset() {}\n}\n\n#endif // signals/SEH handling\n\n#if defined(__GNUC__)\n#    pragma GCC diagnostic pop\n#endif\n// end catch_fatal_condition.cpp\n// start catch_generators.cpp\n\n#include <limits>\n#include <set>\n\nnamespace Catch {\n\nIGeneratorTracker::~IGeneratorTracker() {}\n\nconst char* GeneratorException::what() const noexcept {\n    return m_msg;\n}\n\nnamespace Generators {\n\n    GeneratorUntypedBase::~GeneratorUntypedBase() {}\n\n    auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {\n        return getResultCapture().acquireGeneratorTracker( lineInfo );\n    }\n\n} // namespace Generators\n} // namespace Catch\n// end catch_generators.cpp\n// start catch_interfaces_capture.cpp\n\nnamespace Catch {\n    IResultCapture::~IResultCapture() = default;\n}\n// end catch_interfaces_capture.cpp\n// start catch_interfaces_config.cpp\n\nnamespace Catch {\n    IConfig::~IConfig() = default;\n}\n// end catch_interfaces_config.cpp\n// start catch_interfaces_exception.cpp\n\nnamespace Catch {\n    IExceptionTranslator::~IExceptionTranslator() = default;\n    IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;\n}\n// end catch_interfaces_exception.cpp\n// start catch_interfaces_registry_hub.cpp\n\nnamespace Catch {\n    IRegistryHub::~IRegistryHub() = default;\n    IMutableRegistryHub::~IMutableRegistryHub() = default;\n}\n// end catch_interfaces_registry_hub.cpp\n// start catch_interfaces_reporter.cpp\n\n// start catch_reporter_listening.h\n\nnamespace Catch {\n\n    class ListeningReporter : public IStreamingReporter {\n        using Reporters = std::vector<IStreamingReporterPtr>;\n        Reporters m_listeners;\n        IStreamingReporterPtr m_reporter = nullptr;\n        ReporterPreferences m_preferences;\n\n    public:\n        ListeningReporter();\n\n        void addListener( IStreamingReporterPtr&& listener );\n        void addReporter( IStreamingReporterPtr&& reporter );\n\n    public: // IStreamingReporter\n\n        ReporterPreferences getPreferences() const override;\n\n        void noMatchingTestCases( std::string const& spec ) override;\n\n        void reportInvalidArguments(std::string const&arg) override;\n\n        static std::set<Verbosity> getSupportedVerbosities();\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n        void benchmarkPreparing(std::string const& name) override;\n        void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;\n        void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;\n        void benchmarkFailed(std::string const&) override;\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n        void testRunStarting( TestRunInfo const& testRunInfo ) override;\n        void testGroupStarting( GroupInfo const& groupInfo ) override;\n        void testCaseStarting( TestCaseInfo const& testInfo ) override;\n        void sectionStarting( SectionInfo const& sectionInfo ) override;\n        void assertionStarting( AssertionInfo const& assertionInfo ) override;\n\n        // The return value indicates if the messages buffer should be cleared:\n        bool assertionEnded( AssertionStats const& assertionStats ) override;\n        void sectionEnded( SectionStats const& sectionStats ) override;\n        void testCaseEnded( TestCaseStats const& testCaseStats ) override;\n        void testGroupEnded( TestGroupStats const& testGroupStats ) override;\n        void testRunEnded( TestRunStats const& testRunStats ) override;\n\n        void skipTest( TestCaseInfo const& testInfo ) override;\n        bool isMulti() const override;\n\n    };\n\n} // end namespace Catch\n\n// end catch_reporter_listening.h\nnamespace Catch {\n\n    ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )\n    :   m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}\n\n    ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )\n    :   m_stream( &_stream ), m_fullConfig( _fullConfig ) {}\n\n    std::ostream& ReporterConfig::stream() const { return *m_stream; }\n    IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }\n\n    TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}\n\n    GroupInfo::GroupInfo(  std::string const& _name,\n                           std::size_t _groupIndex,\n                           std::size_t _groupsCount )\n    :   name( _name ),\n        groupIndex( _groupIndex ),\n        groupsCounts( _groupsCount )\n    {}\n\n     AssertionStats::AssertionStats( AssertionResult const& _assertionResult,\n                                     std::vector<MessageInfo> const& _infoMessages,\n                                     Totals const& _totals )\n    :   assertionResult( _assertionResult ),\n        infoMessages( _infoMessages ),\n        totals( _totals )\n    {\n        assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;\n\n        if( assertionResult.hasMessage() ) {\n            // Copy message into messages list.\n            // !TBD This should have been done earlier, somewhere\n            MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );\n            builder << assertionResult.getMessage();\n            builder.m_info.message = builder.m_stream.str();\n\n            infoMessages.push_back( builder.m_info );\n        }\n    }\n\n     AssertionStats::~AssertionStats() = default;\n\n    SectionStats::SectionStats(  SectionInfo const& _sectionInfo,\n                                 Counts const& _assertions,\n                                 double _durationInSeconds,\n                                 bool _missingAssertions )\n    :   sectionInfo( _sectionInfo ),\n        assertions( _assertions ),\n        durationInSeconds( _durationInSeconds ),\n        missingAssertions( _missingAssertions )\n    {}\n\n    SectionStats::~SectionStats() = default;\n\n    TestCaseStats::TestCaseStats(  TestCaseInfo const& _testInfo,\n                                   Totals const& _totals,\n                                   std::string const& _stdOut,\n                                   std::string const& _stdErr,\n                                   bool _aborting )\n    : testInfo( _testInfo ),\n        totals( _totals ),\n        stdOut( _stdOut ),\n        stdErr( _stdErr ),\n        aborting( _aborting )\n    {}\n\n    TestCaseStats::~TestCaseStats() = default;\n\n    TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,\n                                    Totals const& _totals,\n                                    bool _aborting )\n    :   groupInfo( _groupInfo ),\n        totals( _totals ),\n        aborting( _aborting )\n    {}\n\n    TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )\n    :   groupInfo( _groupInfo ),\n        aborting( false )\n    {}\n\n    TestGroupStats::~TestGroupStats() = default;\n\n    TestRunStats::TestRunStats(   TestRunInfo const& _runInfo,\n                    Totals const& _totals,\n                    bool _aborting )\n    :   runInfo( _runInfo ),\n        totals( _totals ),\n        aborting( _aborting )\n    {}\n\n    TestRunStats::~TestRunStats() = default;\n\n    void IStreamingReporter::fatalErrorEncountered( StringRef ) {}\n    bool IStreamingReporter::isMulti() const { return false; }\n\n    IReporterFactory::~IReporterFactory() = default;\n    IReporterRegistry::~IReporterRegistry() = default;\n\n} // end namespace Catch\n// end catch_interfaces_reporter.cpp\n// start catch_interfaces_runner.cpp\n\nnamespace Catch {\n    IRunner::~IRunner() = default;\n}\n// end catch_interfaces_runner.cpp\n// start catch_interfaces_testcase.cpp\n\nnamespace Catch {\n    ITestInvoker::~ITestInvoker() = default;\n    ITestCaseRegistry::~ITestCaseRegistry() = default;\n}\n// end catch_interfaces_testcase.cpp\n// start catch_leak_detector.cpp\n\n#ifdef CATCH_CONFIG_WINDOWS_CRTDBG\n#include <crtdbg.h>\n\nnamespace Catch {\n\n    LeakDetector::LeakDetector() {\n        int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);\n        flag |= _CRTDBG_LEAK_CHECK_DF;\n        flag |= _CRTDBG_ALLOC_MEM_DF;\n        _CrtSetDbgFlag(flag);\n        _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);\n        _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n        // Change this to leaking allocation's number to break there\n        _CrtSetBreakAlloc(-1);\n    }\n}\n\n#else\n\n    Catch::LeakDetector::LeakDetector() {}\n\n#endif\n\nCatch::LeakDetector::~LeakDetector() {\n    Catch::cleanUp();\n}\n// end catch_leak_detector.cpp\n// start catch_list.cpp\n\n// start catch_list.h\n\n#include <set>\n\nnamespace Catch {\n\n    std::size_t listTests( Config const& config );\n\n    std::size_t listTestsNamesOnly( Config const& config );\n\n    struct TagInfo {\n        void add( std::string const& spelling );\n        std::string all() const;\n\n        std::set<std::string> spellings;\n        std::size_t count = 0;\n    };\n\n    std::size_t listTags( Config const& config );\n\n    std::size_t listReporters();\n\n    Option<std::size_t> list( std::shared_ptr<Config> const& config );\n\n} // end namespace Catch\n\n// end catch_list.h\n// start catch_text.h\n\nnamespace Catch {\n    using namespace clara::TextFlow;\n}\n\n// end catch_text.h\n#include <limits>\n#include <algorithm>\n#include <iomanip>\n\nnamespace Catch {\n\n    std::size_t listTests( Config const& config ) {\n        TestSpec testSpec = config.testSpec();\n        if( config.hasTestFilters() )\n            Catch::cout() << \"Matching test cases:\\n\";\n        else {\n            Catch::cout() << \"All available test cases:\\n\";\n        }\n\n        auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );\n        for( auto const& testCaseInfo : matchedTestCases ) {\n            Colour::Code colour = testCaseInfo.isHidden()\n                ? Colour::SecondaryText\n                : Colour::None;\n            Colour colourGuard( colour );\n\n            Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << \"\\n\";\n            if( config.verbosity() >= Verbosity::High ) {\n                Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;\n                std::string description = testCaseInfo.description;\n                if( description.empty() )\n                    description = \"(NO DESCRIPTION)\";\n                Catch::cout() << Column( description ).indent(4) << std::endl;\n            }\n            if( !testCaseInfo.tags.empty() )\n                Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << \"\\n\";\n        }\n\n        if( !config.hasTestFilters() )\n            Catch::cout() << pluralise( matchedTestCases.size(), \"test case\" ) << '\\n' << std::endl;\n        else\n            Catch::cout() << pluralise( matchedTestCases.size(), \"matching test case\" ) << '\\n' << std::endl;\n        return matchedTestCases.size();\n    }\n\n    std::size_t listTestsNamesOnly( Config const& config ) {\n        TestSpec testSpec = config.testSpec();\n        std::size_t matchedTests = 0;\n        std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );\n        for( auto const& testCaseInfo : matchedTestCases ) {\n            matchedTests++;\n            if( startsWith( testCaseInfo.name, '#' ) )\n               Catch::cout() << '\"' << testCaseInfo.name << '\"';\n            else\n               Catch::cout() << testCaseInfo.name;\n            if ( config.verbosity() >= Verbosity::High )\n                Catch::cout() << \"\\t@\" << testCaseInfo.lineInfo;\n            Catch::cout() << std::endl;\n        }\n        return matchedTests;\n    }\n\n    void TagInfo::add( std::string const& spelling ) {\n        ++count;\n        spellings.insert( spelling );\n    }\n\n    std::string TagInfo::all() const {\n        size_t size = 0;\n        for (auto const& spelling : spellings) {\n            // Add 2 for the brackes\n            size += spelling.size() + 2;\n        }\n\n        std::string out; out.reserve(size);\n        for (auto const& spelling : spellings) {\n            out += '[';\n            out += spelling;\n            out += ']';\n        }\n        return out;\n    }\n\n    std::size_t listTags( Config const& config ) {\n        TestSpec testSpec = config.testSpec();\n        if( config.hasTestFilters() )\n            Catch::cout() << \"Tags for matching test cases:\\n\";\n        else {\n            Catch::cout() << \"All available tags:\\n\";\n        }\n\n        std::map<std::string, TagInfo> tagCounts;\n\n        std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );\n        for( auto const& testCase : matchedTestCases ) {\n            for( auto const& tagName : testCase.getTestCaseInfo().tags ) {\n                std::string lcaseTagName = toLower( tagName );\n                auto countIt = tagCounts.find( lcaseTagName );\n                if( countIt == tagCounts.end() )\n                    countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;\n                countIt->second.add( tagName );\n            }\n        }\n\n        for( auto const& tagCount : tagCounts ) {\n            ReusableStringStream rss;\n            rss << \"  \" << std::setw(2) << tagCount.second.count << \"  \";\n            auto str = rss.str();\n            auto wrapper = Column( tagCount.second.all() )\n                                                    .initialIndent( 0 )\n                                                    .indent( str.size() )\n                                                    .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );\n            Catch::cout() << str << wrapper << '\\n';\n        }\n        Catch::cout() << pluralise( tagCounts.size(), \"tag\" ) << '\\n' << std::endl;\n        return tagCounts.size();\n    }\n\n    std::size_t listReporters() {\n        Catch::cout() << \"Available reporters:\\n\";\n        IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();\n        std::size_t maxNameLen = 0;\n        for( auto const& factoryKvp : factories )\n            maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );\n\n        for( auto const& factoryKvp : factories ) {\n            Catch::cout()\n                    << Column( factoryKvp.first + \":\" )\n                            .indent(2)\n                            .width( 5+maxNameLen )\n                    +  Column( factoryKvp.second->getDescription() )\n                            .initialIndent(0)\n                            .indent(2)\n                            .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )\n                    << \"\\n\";\n        }\n        Catch::cout() << std::endl;\n        return factories.size();\n    }\n\n    Option<std::size_t> list( std::shared_ptr<Config> const& config ) {\n        Option<std::size_t> listedCount;\n        getCurrentMutableContext().setConfig( config );\n        if( config->listTests() )\n            listedCount = listedCount.valueOr(0) + listTests( *config );\n        if( config->listTestNamesOnly() )\n            listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );\n        if( config->listTags() )\n            listedCount = listedCount.valueOr(0) + listTags( *config );\n        if( config->listReporters() )\n            listedCount = listedCount.valueOr(0) + listReporters();\n        return listedCount;\n    }\n\n} // end namespace Catch\n// end catch_list.cpp\n// start catch_matchers.cpp\n\nnamespace Catch {\nnamespace Matchers {\n    namespace Impl {\n\n        std::string MatcherUntypedBase::toString() const {\n            if( m_cachedToString.empty() )\n                m_cachedToString = describe();\n            return m_cachedToString;\n        }\n\n        MatcherUntypedBase::~MatcherUntypedBase() = default;\n\n    } // namespace Impl\n} // namespace Matchers\n\nusing namespace Matchers;\nusing Matchers::Impl::MatcherBase;\n\n} // namespace Catch\n// end catch_matchers.cpp\n// start catch_matchers_exception.cpp\n\nnamespace Catch {\nnamespace Matchers {\nnamespace Exception {\n\nbool ExceptionMessageMatcher::match(std::exception const& ex) const {\n    return ex.what() == m_message;\n}\n\nstd::string ExceptionMessageMatcher::describe() const {\n    return \"exception message matches \\\"\" + m_message + \"\\\"\";\n}\n\n}\nException::ExceptionMessageMatcher Message(std::string const& message) {\n    return Exception::ExceptionMessageMatcher(message);\n}\n\n// namespace Exception\n} // namespace Matchers\n} // namespace Catch\n// end catch_matchers_exception.cpp\n// start catch_matchers_floating.cpp\n\n// start catch_polyfills.hpp\n\nnamespace Catch {\n    bool isnan(float f);\n    bool isnan(double d);\n}\n\n// end catch_polyfills.hpp\n// start catch_to_string.hpp\n\n#include <string>\n\nnamespace Catch {\n    template <typename T>\n    std::string to_string(T const& t) {\n#if defined(CATCH_CONFIG_CPP11_TO_STRING)\n        return std::to_string(t);\n#else\n        ReusableStringStream rss;\n        rss << t;\n        return rss.str();\n#endif\n    }\n} // end namespace Catch\n\n// end catch_to_string.hpp\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <cstdint>\n#include <cstring>\n#include <sstream>\n#include <type_traits>\n#include <iomanip>\n#include <limits>\n\nnamespace Catch {\nnamespace {\n\n    int32_t convert(float f) {\n        static_assert(sizeof(float) == sizeof(int32_t), \"Important ULP matcher assumption violated\");\n        int32_t i;\n        std::memcpy(&i, &f, sizeof(f));\n        return i;\n    }\n\n    int64_t convert(double d) {\n        static_assert(sizeof(double) == sizeof(int64_t), \"Important ULP matcher assumption violated\");\n        int64_t i;\n        std::memcpy(&i, &d, sizeof(d));\n        return i;\n    }\n\n    template <typename FP>\n    bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {\n        // Comparison with NaN should always be false.\n        // This way we can rule it out before getting into the ugly details\n        if (Catch::isnan(lhs) || Catch::isnan(rhs)) {\n            return false;\n        }\n\n        auto lc = convert(lhs);\n        auto rc = convert(rhs);\n\n        if ((lc < 0) != (rc < 0)) {\n            // Potentially we can have +0 and -0\n            return lhs == rhs;\n        }\n\n        auto ulpDiff = std::abs(lc - rc);\n        return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;\n    }\n\n} //end anonymous namespace\n\n#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)\n\n#if defined(__clang__)\n#pragma clang diagnostic push\n// The long double overload is currently unused\n#pragma clang diagnostic ignored \"-Wunused-function\"\n#endif\n\n    float nextafter(float x, float y) {\n        return ::nextafterf(x, y);\n    }\n\n    double nextafter(double x, double y) {\n        return ::nextafter(x, y);\n    }\n\n    long double nextafter(long double x, long double y) {\n        return ::nextafterl(x, y);\n    }\n\n#if defined(__clang__)\n#pragma clang diagnostic pop\n#endif\n\n#endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^\n\nnamespace {\n\ntemplate <typename FP>\nFP step(FP start, FP direction, uint64_t steps) {\n    for (uint64_t i = 0; i < steps; ++i) {\n#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)\n        start = Catch::nextafter(start, direction);\n#else\n        start = std::nextafter(start, direction);\n#endif\n    }\n    return start;\n}\n\n// Performs equivalent check of std::fabs(lhs - rhs) <= margin\n// But without the subtraction to allow for INFINITY in comparison\nbool marginComparison(double lhs, double rhs, double margin) {\n    return (lhs + margin >= rhs) && (rhs + margin >= lhs);\n}\n\ntemplate <typename FloatingPoint>\nvoid write(std::ostream& out, FloatingPoint num) {\n    out << std::scientific\n        << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)\n        << num;\n}\n\n} // end anonymous namespace\n\nnamespace Matchers {\nnamespace Floating {\n\n    enum class FloatingPointKind : uint8_t {\n        Float,\n        Double\n    };\n\n    WithinAbsMatcher::WithinAbsMatcher(double target, double margin)\n        :m_target{ target }, m_margin{ margin } {\n        CATCH_ENFORCE(margin >= 0, \"Invalid margin: \" << margin << '.'\n            << \" Margin has to be non-negative.\");\n    }\n\n    // Performs equivalent check of std::fabs(lhs - rhs) <= margin\n    // But without the subtraction to allow for INFINITY in comparison\n    bool WithinAbsMatcher::match(double const& matchee) const {\n        return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);\n    }\n\n    std::string WithinAbsMatcher::describe() const {\n        return \"is within \" + ::Catch::Detail::stringify(m_margin) + \" of \" + ::Catch::Detail::stringify(m_target);\n    }\n\n    WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)\n        :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {\n        CATCH_ENFORCE(m_type == FloatingPointKind::Double\n                   || m_ulps < (std::numeric_limits<uint32_t>::max)(),\n            \"Provided ULP is impossibly large for a float comparison.\");\n    }\n\n#if defined(__clang__)\n#pragma clang diagnostic push\n// Clang <3.5 reports on the default branch in the switch below\n#pragma clang diagnostic ignored \"-Wunreachable-code\"\n#endif\n\n    bool WithinUlpsMatcher::match(double const& matchee) const {\n        switch (m_type) {\n        case FloatingPointKind::Float:\n            return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);\n        case FloatingPointKind::Double:\n            return almostEqualUlps<double>(matchee, m_target, m_ulps);\n        default:\n            CATCH_INTERNAL_ERROR( \"Unknown FloatingPointKind value\" );\n        }\n    }\n\n#if defined(__clang__)\n#pragma clang diagnostic pop\n#endif\n\n    std::string WithinUlpsMatcher::describe() const {\n        std::stringstream ret;\n\n        ret << \"is within \" << m_ulps << \" ULPs of \";\n\n        if (m_type == FloatingPointKind::Float) {\n            write(ret, static_cast<float>(m_target));\n            ret << 'f';\n        } else {\n            write(ret, m_target);\n        }\n\n        ret << \" ([\";\n        if (m_type == FloatingPointKind::Double) {\n            write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));\n            ret << \", \";\n            write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));\n        } else {\n            // We have to cast INFINITY to float because of MinGW, see #1782\n            write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));\n            ret << \", \";\n            write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));\n        }\n        ret << \"])\";\n\n        return ret.str();\n    }\n\n    WithinRelMatcher::WithinRelMatcher(double target, double epsilon):\n        m_target(target),\n        m_epsilon(epsilon){\n        CATCH_ENFORCE(m_epsilon >= 0., \"Relative comparison with epsilon <  0 does not make sense.\");\n        CATCH_ENFORCE(m_epsilon  < 1., \"Relative comparison with epsilon >= 1 does not make sense.\");\n    }\n\n    bool WithinRelMatcher::match(double const& matchee) const {\n        const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));\n        return marginComparison(matchee, m_target,\n                                std::isinf(relMargin)? 0 : relMargin);\n    }\n\n    std::string WithinRelMatcher::describe() const {\n        Catch::ReusableStringStream sstr;\n        sstr << \"and \" << m_target << \" are within \" << m_epsilon * 100. << \"% of each other\";\n        return sstr.str();\n    }\n\n}// namespace Floating\n\nFloating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {\n    return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);\n}\n\nFloating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {\n    return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);\n}\n\nFloating::WithinAbsMatcher WithinAbs(double target, double margin) {\n    return Floating::WithinAbsMatcher(target, margin);\n}\n\nFloating::WithinRelMatcher WithinRel(double target, double eps) {\n    return Floating::WithinRelMatcher(target, eps);\n}\n\nFloating::WithinRelMatcher WithinRel(double target) {\n    return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);\n}\n\nFloating::WithinRelMatcher WithinRel(float target, float eps) {\n    return Floating::WithinRelMatcher(target, eps);\n}\n\nFloating::WithinRelMatcher WithinRel(float target) {\n    return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);\n}\n\n} // namespace Matchers\n} // namespace Catch\n\n// end catch_matchers_floating.cpp\n// start catch_matchers_generic.cpp\n\nstd::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {\n    if (desc.empty()) {\n        return \"matches undescribed predicate\";\n    } else {\n        return \"matches predicate: \\\"\" + desc + '\"';\n    }\n}\n// end catch_matchers_generic.cpp\n// start catch_matchers_string.cpp\n\n#include <regex>\n\nnamespace Catch {\nnamespace Matchers {\n\n    namespace StdString {\n\n        CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )\n        :   m_caseSensitivity( caseSensitivity ),\n            m_str( adjustString( str ) )\n        {}\n        std::string CasedString::adjustString( std::string const& str ) const {\n            return m_caseSensitivity == CaseSensitive::No\n                   ? toLower( str )\n                   : str;\n        }\n        std::string CasedString::caseSensitivitySuffix() const {\n            return m_caseSensitivity == CaseSensitive::No\n                   ? \" (case insensitive)\"\n                   : std::string();\n        }\n\n        StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )\n        : m_comparator( comparator ),\n          m_operation( operation ) {\n        }\n\n        std::string StringMatcherBase::describe() const {\n            std::string description;\n            description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +\n                                        m_comparator.caseSensitivitySuffix().size());\n            description += m_operation;\n            description += \": \\\"\";\n            description += m_comparator.m_str;\n            description += \"\\\"\";\n            description += m_comparator.caseSensitivitySuffix();\n            return description;\n        }\n\n        EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( \"equals\", comparator ) {}\n\n        bool EqualsMatcher::match( std::string const& source ) const {\n            return m_comparator.adjustString( source ) == m_comparator.m_str;\n        }\n\n        ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( \"contains\", comparator ) {}\n\n        bool ContainsMatcher::match( std::string const& source ) const {\n            return contains( m_comparator.adjustString( source ), m_comparator.m_str );\n        }\n\n        StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( \"starts with\", comparator ) {}\n\n        bool StartsWithMatcher::match( std::string const& source ) const {\n            return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );\n        }\n\n        EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( \"ends with\", comparator ) {}\n\n        bool EndsWithMatcher::match( std::string const& source ) const {\n            return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );\n        }\n\n        RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}\n\n        bool RegexMatcher::match(std::string const& matchee) const {\n            auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway\n            if (m_caseSensitivity == CaseSensitive::Choice::No) {\n                flags |= std::regex::icase;\n            }\n            auto reg = std::regex(m_regex, flags);\n            return std::regex_match(matchee, reg);\n        }\n\n        std::string RegexMatcher::describe() const {\n            return \"matches \" + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? \" case sensitively\" : \" case insensitively\");\n        }\n\n    } // namespace StdString\n\n    StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {\n        return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );\n    }\n    StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {\n        return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );\n    }\n    StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {\n        return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );\n    }\n    StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {\n        return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );\n    }\n\n    StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {\n        return StdString::RegexMatcher(regex, caseSensitivity);\n    }\n\n} // namespace Matchers\n} // namespace Catch\n// end catch_matchers_string.cpp\n// start catch_message.cpp\n\n// start catch_uncaught_exceptions.h\n\nnamespace Catch {\n    bool uncaught_exceptions();\n} // end namespace Catch\n\n// end catch_uncaught_exceptions.h\n#include <cassert>\n#include <stack>\n\nnamespace Catch {\n\n    MessageInfo::MessageInfo(   StringRef const& _macroName,\n                                SourceLineInfo const& _lineInfo,\n                                ResultWas::OfType _type )\n    :   macroName( _macroName ),\n        lineInfo( _lineInfo ),\n        type( _type ),\n        sequence( ++globalCount )\n    {}\n\n    bool MessageInfo::operator==( MessageInfo const& other ) const {\n        return sequence == other.sequence;\n    }\n\n    bool MessageInfo::operator<( MessageInfo const& other ) const {\n        return sequence < other.sequence;\n    }\n\n    // This may need protecting if threading support is added\n    unsigned int MessageInfo::globalCount = 0;\n\n    ////////////////////////////////////////////////////////////////////////////\n\n    Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,\n                                           SourceLineInfo const& lineInfo,\n                                           ResultWas::OfType type )\n        :m_info(macroName, lineInfo, type) {}\n\n    ////////////////////////////////////////////////////////////////////////////\n\n    ScopedMessage::ScopedMessage( MessageBuilder const& builder )\n    : m_info( builder.m_info ), m_moved()\n    {\n        m_info.message = builder.m_stream.str();\n        getResultCapture().pushScopedMessage( m_info );\n    }\n\n    ScopedMessage::ScopedMessage( ScopedMessage&& old )\n    : m_info( old.m_info ), m_moved()\n    {\n        old.m_moved = true;\n    }\n\n    ScopedMessage::~ScopedMessage() {\n        if ( !uncaught_exceptions() && !m_moved ){\n            getResultCapture().popScopedMessage(m_info);\n        }\n    }\n\n    Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {\n        auto trimmed = [&] (size_t start, size_t end) {\n            while (names[start] == ',' || isspace(names[start])) {\n                ++start;\n            }\n            while (names[end] == ',' || isspace(names[end])) {\n                --end;\n            }\n            return names.substr(start, end - start + 1);\n        };\n        auto skipq = [&] (size_t start, char quote) {\n            for (auto i = start + 1; i < names.size() ; ++i) {\n                if (names[i] == quote)\n                    return i;\n                if (names[i] == '\\\\')\n                    ++i;\n            }\n            CATCH_INTERNAL_ERROR(\"CAPTURE parsing encountered unmatched quote\");\n        };\n\n        size_t start = 0;\n        std::stack<char> openings;\n        for (size_t pos = 0; pos < names.size(); ++pos) {\n            char c = names[pos];\n            switch (c) {\n            case '[':\n            case '{':\n            case '(':\n            // It is basically impossible to disambiguate between\n            // comparison and start of template args in this context\n//            case '<':\n                openings.push(c);\n                break;\n            case ']':\n            case '}':\n            case ')':\n//           case '>':\n                openings.pop();\n                break;\n            case '\"':\n            case '\\'':\n                pos = skipq(pos, c);\n                break;\n            case ',':\n                if (start != pos && openings.size() == 0) {\n                    m_messages.emplace_back(macroName, lineInfo, resultType);\n                    m_messages.back().message = static_cast<std::string>(trimmed(start, pos));\n                    m_messages.back().message += \" := \";\n                    start = pos;\n                }\n            }\n        }\n        assert(openings.size() == 0 && \"Mismatched openings\");\n        m_messages.emplace_back(macroName, lineInfo, resultType);\n        m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));\n        m_messages.back().message += \" := \";\n    }\n    Capturer::~Capturer() {\n        if ( !uncaught_exceptions() ){\n            assert( m_captured == m_messages.size() );\n            for( size_t i = 0; i < m_captured; ++i  )\n                m_resultCapture.popScopedMessage( m_messages[i] );\n        }\n    }\n\n    void Capturer::captureValue( size_t index, std::string const& value ) {\n        assert( index < m_messages.size() );\n        m_messages[index].message += value;\n        m_resultCapture.pushScopedMessage( m_messages[index] );\n        m_captured++;\n    }\n\n} // end namespace Catch\n// end catch_message.cpp\n// start catch_output_redirect.cpp\n\n// start catch_output_redirect.h\n#ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H\n#define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H\n\n#include <cstdio>\n#include <iosfwd>\n#include <string>\n\nnamespace Catch {\n\n    class RedirectedStream {\n        std::ostream& m_originalStream;\n        std::ostream& m_redirectionStream;\n        std::streambuf* m_prevBuf;\n\n    public:\n        RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );\n        ~RedirectedStream();\n    };\n\n    class RedirectedStdOut {\n        ReusableStringStream m_rss;\n        RedirectedStream m_cout;\n    public:\n        RedirectedStdOut();\n        auto str() const -> std::string;\n    };\n\n    // StdErr has two constituent streams in C++, std::cerr and std::clog\n    // This means that we need to redirect 2 streams into 1 to keep proper\n    // order of writes\n    class RedirectedStdErr {\n        ReusableStringStream m_rss;\n        RedirectedStream m_cerr;\n        RedirectedStream m_clog;\n    public:\n        RedirectedStdErr();\n        auto str() const -> std::string;\n    };\n\n    class RedirectedStreams {\n    public:\n        RedirectedStreams(RedirectedStreams const&) = delete;\n        RedirectedStreams& operator=(RedirectedStreams const&) = delete;\n        RedirectedStreams(RedirectedStreams&&) = delete;\n        RedirectedStreams& operator=(RedirectedStreams&&) = delete;\n\n        RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);\n        ~RedirectedStreams();\n    private:\n        std::string& m_redirectedCout;\n        std::string& m_redirectedCerr;\n        RedirectedStdOut m_redirectedStdOut;\n        RedirectedStdErr m_redirectedStdErr;\n    };\n\n#if defined(CATCH_CONFIG_NEW_CAPTURE)\n\n    // Windows's implementation of std::tmpfile is terrible (it tries\n    // to create a file inside system folder, thus requiring elevated\n    // privileges for the binary), so we have to use tmpnam(_s) and\n    // create the file ourselves there.\n    class TempFile {\n    public:\n        TempFile(TempFile const&) = delete;\n        TempFile& operator=(TempFile const&) = delete;\n        TempFile(TempFile&&) = delete;\n        TempFile& operator=(TempFile&&) = delete;\n\n        TempFile();\n        ~TempFile();\n\n        std::FILE* getFile();\n        std::string getContents();\n\n    private:\n        std::FILE* m_file = nullptr;\n    #if defined(_MSC_VER)\n        char m_buffer[L_tmpnam] = { 0 };\n    #endif\n    };\n\n    class OutputRedirect {\n    public:\n        OutputRedirect(OutputRedirect const&) = delete;\n        OutputRedirect& operator=(OutputRedirect const&) = delete;\n        OutputRedirect(OutputRedirect&&) = delete;\n        OutputRedirect& operator=(OutputRedirect&&) = delete;\n\n        OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);\n        ~OutputRedirect();\n\n    private:\n        int m_originalStdout = -1;\n        int m_originalStderr = -1;\n        TempFile m_stdoutFile;\n        TempFile m_stderrFile;\n        std::string& m_stdoutDest;\n        std::string& m_stderrDest;\n    };\n\n#endif\n\n} // end namespace Catch\n\n#endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H\n// end catch_output_redirect.h\n#include <cstdio>\n#include <cstring>\n#include <fstream>\n#include <sstream>\n#include <stdexcept>\n\n#if defined(CATCH_CONFIG_NEW_CAPTURE)\n    #if defined(_MSC_VER)\n    #include <io.h>      //_dup and _dup2\n    #define dup _dup\n    #define dup2 _dup2\n    #define fileno _fileno\n    #else\n    #include <unistd.h>  // dup and dup2\n    #endif\n#endif\n\nnamespace Catch {\n\n    RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )\n    :   m_originalStream( originalStream ),\n        m_redirectionStream( redirectionStream ),\n        m_prevBuf( m_originalStream.rdbuf() )\n    {\n        m_originalStream.rdbuf( m_redirectionStream.rdbuf() );\n    }\n\n    RedirectedStream::~RedirectedStream() {\n        m_originalStream.rdbuf( m_prevBuf );\n    }\n\n    RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}\n    auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }\n\n    RedirectedStdErr::RedirectedStdErr()\n    :   m_cerr( Catch::cerr(), m_rss.get() ),\n        m_clog( Catch::clog(), m_rss.get() )\n    {}\n    auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }\n\n    RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)\n    :   m_redirectedCout(redirectedCout),\n        m_redirectedCerr(redirectedCerr)\n    {}\n\n    RedirectedStreams::~RedirectedStreams() {\n        m_redirectedCout += m_redirectedStdOut.str();\n        m_redirectedCerr += m_redirectedStdErr.str();\n    }\n\n#if defined(CATCH_CONFIG_NEW_CAPTURE)\n\n#if defined(_MSC_VER)\n    TempFile::TempFile() {\n        if (tmpnam_s(m_buffer)) {\n            CATCH_RUNTIME_ERROR(\"Could not get a temp filename\");\n        }\n        if (fopen_s(&m_file, m_buffer, \"w\")) {\n            char buffer[100];\n            if (strerror_s(buffer, errno)) {\n                CATCH_RUNTIME_ERROR(\"Could not translate errno to a string\");\n            }\n            CATCH_RUNTIME_ERROR(\"Could not open the temp file: '\" << m_buffer << \"' because: \" << buffer);\n        }\n    }\n#else\n    TempFile::TempFile() {\n        m_file = std::tmpfile();\n        if (!m_file) {\n            CATCH_RUNTIME_ERROR(\"Could not create a temp file.\");\n        }\n    }\n\n#endif\n\n    TempFile::~TempFile() {\n         // TBD: What to do about errors here?\n         std::fclose(m_file);\n         // We manually create the file on Windows only, on Linux\n         // it will be autodeleted\n#if defined(_MSC_VER)\n         std::remove(m_buffer);\n#endif\n    }\n\n    FILE* TempFile::getFile() {\n        return m_file;\n    }\n\n    std::string TempFile::getContents() {\n        std::stringstream sstr;\n        char buffer[100] = {};\n        std::rewind(m_file);\n        while (std::fgets(buffer, sizeof(buffer), m_file)) {\n            sstr << buffer;\n        }\n        return sstr.str();\n    }\n\n    OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :\n        m_originalStdout(dup(1)),\n        m_originalStderr(dup(2)),\n        m_stdoutDest(stdout_dest),\n        m_stderrDest(stderr_dest) {\n        dup2(fileno(m_stdoutFile.getFile()), 1);\n        dup2(fileno(m_stderrFile.getFile()), 2);\n    }\n\n    OutputRedirect::~OutputRedirect() {\n        Catch::cout() << std::flush;\n        fflush(stdout);\n        // Since we support overriding these streams, we flush cerr\n        // even though std::cerr is unbuffered\n        Catch::cerr() << std::flush;\n        Catch::clog() << std::flush;\n        fflush(stderr);\n\n        dup2(m_originalStdout, 1);\n        dup2(m_originalStderr, 2);\n\n        m_stdoutDest += m_stdoutFile.getContents();\n        m_stderrDest += m_stderrFile.getContents();\n    }\n\n#endif // CATCH_CONFIG_NEW_CAPTURE\n\n} // namespace Catch\n\n#if defined(CATCH_CONFIG_NEW_CAPTURE)\n    #if defined(_MSC_VER)\n    #undef dup\n    #undef dup2\n    #undef fileno\n    #endif\n#endif\n// end catch_output_redirect.cpp\n// start catch_polyfills.cpp\n\n#include <cmath>\n\nnamespace Catch {\n\n#if !defined(CATCH_CONFIG_POLYFILL_ISNAN)\n    bool isnan(float f) {\n        return std::isnan(f);\n    }\n    bool isnan(double d) {\n        return std::isnan(d);\n    }\n#else\n    // For now we only use this for embarcadero\n    bool isnan(float f) {\n        return std::_isnan(f);\n    }\n    bool isnan(double d) {\n        return std::_isnan(d);\n    }\n#endif\n\n} // end namespace Catch\n// end catch_polyfills.cpp\n// start catch_random_number_generator.cpp\n\nnamespace Catch {\n\nnamespace {\n\n#if defined(_MSC_VER)\n#pragma warning(push)\n#pragma warning(disable:4146) // we negate uint32 during the rotate\n#endif\n        // Safe rotr implementation thanks to John Regehr\n        uint32_t rotate_right(uint32_t val, uint32_t count) {\n            const uint32_t mask = 31;\n            count &= mask;\n            return (val >> count) | (val << (-count & mask));\n        }\n\n#if defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n\n}\n\n    SimplePcg32::SimplePcg32(result_type seed_) {\n        seed(seed_);\n    }\n\n    void SimplePcg32::seed(result_type seed_) {\n        m_state = 0;\n        (*this)();\n        m_state += seed_;\n        (*this)();\n    }\n\n    void SimplePcg32::discard(uint64_t skip) {\n        // We could implement this to run in O(log n) steps, but this\n        // should suffice for our use case.\n        for (uint64_t s = 0; s < skip; ++s) {\n            static_cast<void>((*this)());\n        }\n    }\n\n    SimplePcg32::result_type SimplePcg32::operator()() {\n        // prepare the output value\n        const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);\n        const auto output = rotate_right(xorshifted, m_state >> 59u);\n\n        // advance state\n        m_state = m_state * 6364136223846793005ULL + s_inc;\n\n        return output;\n    }\n\n    bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {\n        return lhs.m_state == rhs.m_state;\n    }\n\n    bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {\n        return lhs.m_state != rhs.m_state;\n    }\n}\n// end catch_random_number_generator.cpp\n// start catch_registry_hub.cpp\n\n// start catch_test_case_registry_impl.h\n\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <ios>\n\nnamespace Catch {\n\n    class TestCase;\n    struct IConfig;\n\n    std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );\n\n    bool isThrowSafe( TestCase const& testCase, IConfig const& config );\n    bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );\n\n    void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );\n\n    std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );\n    std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );\n\n    class TestRegistry : public ITestCaseRegistry {\n    public:\n        virtual ~TestRegistry() = default;\n\n        virtual void registerTest( TestCase const& testCase );\n\n        std::vector<TestCase> const& getAllTests() const override;\n        std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;\n\n    private:\n        std::vector<TestCase> m_functions;\n        mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;\n        mutable std::vector<TestCase> m_sortedFunctions;\n        std::size_t m_unnamedCount = 0;\n        std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised\n    };\n\n    ///////////////////////////////////////////////////////////////////////////\n\n    class TestInvokerAsFunction : public ITestInvoker {\n        void(*m_testAsFunction)();\n    public:\n        TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;\n\n        void invoke() const override;\n    };\n\n    std::string extractClassName( StringRef const& classOrQualifiedMethodName );\n\n    ///////////////////////////////////////////////////////////////////////////\n\n} // end namespace Catch\n\n// end catch_test_case_registry_impl.h\n// start catch_reporter_registry.h\n\n#include <map>\n\nnamespace Catch {\n\n    class ReporterRegistry : public IReporterRegistry {\n\n    public:\n\n        ~ReporterRegistry() override;\n\n        IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;\n\n        void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );\n        void registerListener( IReporterFactoryPtr const& factory );\n\n        FactoryMap const& getFactories() const override;\n        Listeners const& getListeners() const override;\n\n    private:\n        FactoryMap m_factories;\n        Listeners m_listeners;\n    };\n}\n\n// end catch_reporter_registry.h\n// start catch_tag_alias_registry.h\n\n// start catch_tag_alias.h\n\n#include <string>\n\nnamespace Catch {\n\n    struct TagAlias {\n        TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);\n\n        std::string tag;\n        SourceLineInfo lineInfo;\n    };\n\n} // end namespace Catch\n\n// end catch_tag_alias.h\n#include <map>\n\nnamespace Catch {\n\n    class TagAliasRegistry : public ITagAliasRegistry {\n    public:\n        ~TagAliasRegistry() override;\n        TagAlias const* find( std::string const& alias ) const override;\n        std::string expandAliases( std::string const& unexpandedTestSpec ) const override;\n        void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );\n\n    private:\n        std::map<std::string, TagAlias> m_registry;\n    };\n\n} // end namespace Catch\n\n// end catch_tag_alias_registry.h\n// start catch_startup_exception_registry.h\n\n#include <vector>\n#include <exception>\n\nnamespace Catch {\n\n    class StartupExceptionRegistry {\n    public:\n        void add(std::exception_ptr const& exception) noexcept;\n        std::vector<std::exception_ptr> const& getExceptions() const noexcept;\n    private:\n        std::vector<std::exception_ptr> m_exceptions;\n    };\n\n} // end namespace Catch\n\n// end catch_startup_exception_registry.h\n// start catch_singletons.hpp\n\nnamespace Catch {\n\n    struct ISingleton {\n        virtual ~ISingleton();\n    };\n\n    void addSingleton( ISingleton* singleton );\n    void cleanupSingletons();\n\n    template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>\n    class Singleton : SingletonImplT, public ISingleton {\n\n        static auto getInternal() -> Singleton* {\n            static Singleton* s_instance = nullptr;\n            if( !s_instance ) {\n                s_instance = new Singleton;\n                addSingleton( s_instance );\n            }\n            return s_instance;\n        }\n\n    public:\n        static auto get() -> InterfaceT const& {\n            return *getInternal();\n        }\n        static auto getMutable() -> MutableInterfaceT& {\n            return *getInternal();\n        }\n    };\n\n} // namespace Catch\n\n// end catch_singletons.hpp\nnamespace Catch {\n\n    namespace {\n\n        class RegistryHub : public IRegistryHub, public IMutableRegistryHub,\n                            private NonCopyable {\n\n        public: // IRegistryHub\n            RegistryHub() = default;\n            IReporterRegistry const& getReporterRegistry() const override {\n                return m_reporterRegistry;\n            }\n            ITestCaseRegistry const& getTestCaseRegistry() const override {\n                return m_testCaseRegistry;\n            }\n            IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {\n                return m_exceptionTranslatorRegistry;\n            }\n            ITagAliasRegistry const& getTagAliasRegistry() const override {\n                return m_tagAliasRegistry;\n            }\n            StartupExceptionRegistry const& getStartupExceptionRegistry() const override {\n                return m_exceptionRegistry;\n            }\n\n        public: // IMutableRegistryHub\n            void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {\n                m_reporterRegistry.registerReporter( name, factory );\n            }\n            void registerListener( IReporterFactoryPtr const& factory ) override {\n                m_reporterRegistry.registerListener( factory );\n            }\n            void registerTest( TestCase const& testInfo ) override {\n                m_testCaseRegistry.registerTest( testInfo );\n            }\n            void registerTranslator( const IExceptionTranslator* translator ) override {\n                m_exceptionTranslatorRegistry.registerTranslator( translator );\n            }\n            void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {\n                m_tagAliasRegistry.add( alias, tag, lineInfo );\n            }\n            void registerStartupException() noexcept override {\n                m_exceptionRegistry.add(std::current_exception());\n            }\n            IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {\n                return m_enumValuesRegistry;\n            }\n\n        private:\n            TestRegistry m_testCaseRegistry;\n            ReporterRegistry m_reporterRegistry;\n            ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;\n            TagAliasRegistry m_tagAliasRegistry;\n            StartupExceptionRegistry m_exceptionRegistry;\n            Detail::EnumValuesRegistry m_enumValuesRegistry;\n        };\n    }\n\n    using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;\n\n    IRegistryHub const& getRegistryHub() {\n        return RegistryHubSingleton::get();\n    }\n    IMutableRegistryHub& getMutableRegistryHub() {\n        return RegistryHubSingleton::getMutable();\n    }\n    void cleanUp() {\n        cleanupSingletons();\n        cleanUpContext();\n    }\n    std::string translateActiveException() {\n        return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();\n    }\n\n} // end namespace Catch\n// end catch_registry_hub.cpp\n// start catch_reporter_registry.cpp\n\nnamespace Catch {\n\n    ReporterRegistry::~ReporterRegistry() = default;\n\n    IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {\n        auto it =  m_factories.find( name );\n        if( it == m_factories.end() )\n            return nullptr;\n        return it->second->create( ReporterConfig( config ) );\n    }\n\n    void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {\n        m_factories.emplace(name, factory);\n    }\n    void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {\n        m_listeners.push_back( factory );\n    }\n\n    IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {\n        return m_factories;\n    }\n    IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {\n        return m_listeners;\n    }\n\n}\n// end catch_reporter_registry.cpp\n// start catch_result_type.cpp\n\nnamespace Catch {\n\n    bool isOk( ResultWas::OfType resultType ) {\n        return ( resultType & ResultWas::FailureBit ) == 0;\n    }\n    bool isJustInfo( int flags ) {\n        return flags == ResultWas::Info;\n    }\n\n    ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {\n        return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );\n    }\n\n    bool shouldContinueOnFailure( int flags )    { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }\n    bool shouldSuppressFailure( int flags )      { return ( flags & ResultDisposition::SuppressFail ) != 0; }\n\n} // end namespace Catch\n// end catch_result_type.cpp\n// start catch_run_context.cpp\n\n#include <cassert>\n#include <algorithm>\n#include <sstream>\n\nnamespace Catch {\n\n    namespace Generators {\n        struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {\n            GeneratorBasePtr m_generator;\n\n            GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )\n            :   TrackerBase( nameAndLocation, ctx, parent )\n            {}\n            ~GeneratorTracker();\n\n            static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {\n                std::shared_ptr<GeneratorTracker> tracker;\n\n                ITracker& currentTracker = ctx.currentTracker();\n                if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {\n                    assert( childTracker );\n                    assert( childTracker->isGeneratorTracker() );\n                    tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );\n                }\n                else {\n                    tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );\n                    currentTracker.addChild( tracker );\n                }\n\n                if( !ctx.completedCycle() && !tracker->isComplete() ) {\n                    tracker->open();\n                }\n\n                return *tracker;\n            }\n\n            // TrackerBase interface\n            bool isGeneratorTracker() const override { return true; }\n            auto hasGenerator() const -> bool override {\n                return !!m_generator;\n            }\n            void close() override {\n                TrackerBase::close();\n                // Generator interface only finds out if it has another item on atual move\n                if (m_runState == CompletedSuccessfully && m_generator->next()) {\n                    m_children.clear();\n                    m_runState = Executing;\n                }\n            }\n\n            // IGeneratorTracker interface\n            auto getGenerator() const -> GeneratorBasePtr const& override {\n                return m_generator;\n            }\n            void setGenerator( GeneratorBasePtr&& generator ) override {\n                m_generator = std::move( generator );\n            }\n        };\n        GeneratorTracker::~GeneratorTracker() {}\n    }\n\n    RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)\n    :   m_runInfo(_config->name()),\n        m_context(getCurrentMutableContext()),\n        m_config(_config),\n        m_reporter(std::move(reporter)),\n        m_lastAssertionInfo{ StringRef(), SourceLineInfo(\"\",0), StringRef(), ResultDisposition::Normal },\n        m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )\n    {\n        m_context.setRunner(this);\n        m_context.setConfig(m_config);\n        m_context.setResultCapture(this);\n        m_reporter->testRunStarting(m_runInfo);\n    }\n\n    RunContext::~RunContext() {\n        m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));\n    }\n\n    void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {\n        m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));\n    }\n\n    void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {\n        m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));\n    }\n\n    Totals RunContext::runTest(TestCase const& testCase) {\n        Totals prevTotals = m_totals;\n\n        std::string redirectedCout;\n        std::string redirectedCerr;\n\n        auto const& testInfo = testCase.getTestCaseInfo();\n\n        m_reporter->testCaseStarting(testInfo);\n\n        m_activeTestCase = &testCase;\n\n        ITracker& rootTracker = m_trackerContext.startRun();\n        assert(rootTracker.isSectionTracker());\n        static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());\n        do {\n            m_trackerContext.startCycle();\n            m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));\n            runCurrentTest(redirectedCout, redirectedCerr);\n        } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());\n\n        Totals deltaTotals = m_totals.delta(prevTotals);\n        if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {\n            deltaTotals.assertions.failed++;\n            deltaTotals.testCases.passed--;\n            deltaTotals.testCases.failed++;\n        }\n        m_totals.testCases += deltaTotals.testCases;\n        m_reporter->testCaseEnded(TestCaseStats(testInfo,\n                                  deltaTotals,\n                                  redirectedCout,\n                                  redirectedCerr,\n                                  aborting()));\n\n        m_activeTestCase = nullptr;\n        m_testCaseTracker = nullptr;\n\n        return deltaTotals;\n    }\n\n    IConfigPtr RunContext::config() const {\n        return m_config;\n    }\n\n    IStreamingReporter& RunContext::reporter() const {\n        return *m_reporter;\n    }\n\n    void RunContext::assertionEnded(AssertionResult const & result) {\n        if (result.getResultType() == ResultWas::Ok) {\n            m_totals.assertions.passed++;\n            m_lastAssertionPassed = true;\n        } else if (!result.isOk()) {\n            m_lastAssertionPassed = false;\n            if( m_activeTestCase->getTestCaseInfo().okToFail() )\n                m_totals.assertions.failedButOk++;\n            else\n                m_totals.assertions.failed++;\n        }\n        else {\n            m_lastAssertionPassed = true;\n        }\n\n        // We have no use for the return value (whether messages should be cleared), because messages were made scoped\n        // and should be let to clear themselves out.\n        static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));\n\n        if (result.getResultType() != ResultWas::Warning)\n            m_messageScopes.clear();\n\n        // Reset working state\n        resetAssertionInfo();\n        m_lastResult = result;\n    }\n    void RunContext::resetAssertionInfo() {\n        m_lastAssertionInfo.macroName = StringRef();\n        m_lastAssertionInfo.capturedExpression = \"{Unknown expression after the reported line}\"_sr;\n    }\n\n    bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {\n        ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));\n        if (!sectionTracker.isOpen())\n            return false;\n        m_activeSections.push_back(&sectionTracker);\n\n        m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;\n\n        m_reporter->sectionStarting(sectionInfo);\n\n        assertions = m_totals.assertions;\n\n        return true;\n    }\n    auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {\n        using namespace Generators;\n        GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( \"generator\", lineInfo ) );\n        assert( tracker.isOpen() );\n        m_lastAssertionInfo.lineInfo = lineInfo;\n        return tracker;\n    }\n\n    bool RunContext::testForMissingAssertions(Counts& assertions) {\n        if (assertions.total() != 0)\n            return false;\n        if (!m_config->warnAboutMissingAssertions())\n            return false;\n        if (m_trackerContext.currentTracker().hasChildren())\n            return false;\n        m_totals.assertions.failed++;\n        assertions.failed++;\n        return true;\n    }\n\n    void RunContext::sectionEnded(SectionEndInfo const & endInfo) {\n        Counts assertions = m_totals.assertions - endInfo.prevAssertions;\n        bool missingAssertions = testForMissingAssertions(assertions);\n\n        if (!m_activeSections.empty()) {\n            m_activeSections.back()->close();\n            m_activeSections.pop_back();\n        }\n\n        m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));\n        m_messages.clear();\n        m_messageScopes.clear();\n    }\n\n    void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {\n        if (m_unfinishedSections.empty())\n            m_activeSections.back()->fail();\n        else\n            m_activeSections.back()->close();\n        m_activeSections.pop_back();\n\n        m_unfinishedSections.push_back(endInfo);\n    }\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n    void RunContext::benchmarkPreparing(std::string const& name) {\n\t\tm_reporter->benchmarkPreparing(name);\n\t}\n    void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {\n        m_reporter->benchmarkStarting( info );\n    }\n    void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {\n        m_reporter->benchmarkEnded( stats );\n    }\n\tvoid RunContext::benchmarkFailed(std::string const & error) {\n\t\tm_reporter->benchmarkFailed(error);\n\t}\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n    void RunContext::pushScopedMessage(MessageInfo const & message) {\n        m_messages.push_back(message);\n    }\n\n    void RunContext::popScopedMessage(MessageInfo const & message) {\n        m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());\n    }\n\n    void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {\n        m_messageScopes.emplace_back( builder );\n    }\n\n    std::string RunContext::getCurrentTestName() const {\n        return m_activeTestCase\n            ? m_activeTestCase->getTestCaseInfo().name\n            : std::string();\n    }\n\n    const AssertionResult * RunContext::getLastResult() const {\n        return &(*m_lastResult);\n    }\n\n    void RunContext::exceptionEarlyReported() {\n        m_shouldReportUnexpected = false;\n    }\n\n    void RunContext::handleFatalErrorCondition( StringRef message ) {\n        // First notify reporter that bad things happened\n        m_reporter->fatalErrorEncountered(message);\n\n        // Don't rebuild the result -- the stringification itself can cause more fatal errors\n        // Instead, fake a result data.\n        AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );\n        tempResult.message = static_cast<std::string>(message);\n        AssertionResult result(m_lastAssertionInfo, tempResult);\n\n        assertionEnded(result);\n\n        handleUnfinishedSections();\n\n        // Recreate section for test case (as we will lose the one that was in scope)\n        auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();\n        SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);\n\n        Counts assertions;\n        assertions.failed = 1;\n        SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);\n        m_reporter->sectionEnded(testCaseSectionStats);\n\n        auto const& testInfo = m_activeTestCase->getTestCaseInfo();\n\n        Totals deltaTotals;\n        deltaTotals.testCases.failed = 1;\n        deltaTotals.assertions.failed = 1;\n        m_reporter->testCaseEnded(TestCaseStats(testInfo,\n                                  deltaTotals,\n                                  std::string(),\n                                  std::string(),\n                                  false));\n        m_totals.testCases.failed++;\n        testGroupEnded(std::string(), m_totals, 1, 1);\n        m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));\n    }\n\n    bool RunContext::lastAssertionPassed() {\n         return m_lastAssertionPassed;\n    }\n\n    void RunContext::assertionPassed() {\n        m_lastAssertionPassed = true;\n        ++m_totals.assertions.passed;\n        resetAssertionInfo();\n        m_messageScopes.clear();\n    }\n\n    bool RunContext::aborting() const {\n        return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());\n    }\n\n    void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {\n        auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();\n        SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);\n        m_reporter->sectionStarting(testCaseSection);\n        Counts prevAssertions = m_totals.assertions;\n        double duration = 0;\n        m_shouldReportUnexpected = true;\n        m_lastAssertionInfo = { \"TEST_CASE\"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };\n\n        seedRng(*m_config);\n\n        Timer timer;\n        CATCH_TRY {\n            if (m_reporter->getPreferences().shouldRedirectStdOut) {\n#if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)\n                RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);\n\n                timer.start();\n                invokeActiveTestCase();\n#else\n                OutputRedirect r(redirectedCout, redirectedCerr);\n                timer.start();\n                invokeActiveTestCase();\n#endif\n            } else {\n                timer.start();\n                invokeActiveTestCase();\n            }\n            duration = timer.getElapsedSeconds();\n        } CATCH_CATCH_ANON (TestFailureException&) {\n            // This just means the test was aborted due to failure\n        } CATCH_CATCH_ALL {\n            // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions\n            // are reported without translation at the point of origin.\n            if( m_shouldReportUnexpected ) {\n                AssertionReaction dummyReaction;\n                handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );\n            }\n        }\n        Counts assertions = m_totals.assertions - prevAssertions;\n        bool missingAssertions = testForMissingAssertions(assertions);\n\n        m_testCaseTracker->close();\n        handleUnfinishedSections();\n        m_messages.clear();\n        m_messageScopes.clear();\n\n        SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);\n        m_reporter->sectionEnded(testCaseSectionStats);\n    }\n\n    void RunContext::invokeActiveTestCase() {\n        FatalConditionHandler fatalConditionHandler; // Handle signals\n        m_activeTestCase->invoke();\n        fatalConditionHandler.reset();\n    }\n\n    void RunContext::handleUnfinishedSections() {\n        // If sections ended prematurely due to an exception we stored their\n        // infos here so we can tear them down outside the unwind process.\n        for (auto it = m_unfinishedSections.rbegin(),\n             itEnd = m_unfinishedSections.rend();\n             it != itEnd;\n             ++it)\n            sectionEnded(*it);\n        m_unfinishedSections.clear();\n    }\n\n    void RunContext::handleExpr(\n        AssertionInfo const& info,\n        ITransientExpression const& expr,\n        AssertionReaction& reaction\n    ) {\n        m_reporter->assertionStarting( info );\n\n        bool negated = isFalseTest( info.resultDisposition );\n        bool result = expr.getResult() != negated;\n\n        if( result ) {\n            if (!m_includeSuccessfulResults) {\n                assertionPassed();\n            }\n            else {\n                reportExpr(info, ResultWas::Ok, &expr, negated);\n            }\n        }\n        else {\n            reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );\n            populateReaction( reaction );\n        }\n    }\n    void RunContext::reportExpr(\n            AssertionInfo const &info,\n            ResultWas::OfType resultType,\n            ITransientExpression const *expr,\n            bool negated ) {\n\n        m_lastAssertionInfo = info;\n        AssertionResultData data( resultType, LazyExpression( negated ) );\n\n        AssertionResult assertionResult{ info, data };\n        assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;\n\n        assertionEnded( assertionResult );\n    }\n\n    void RunContext::handleMessage(\n            AssertionInfo const& info,\n            ResultWas::OfType resultType,\n            StringRef const& message,\n            AssertionReaction& reaction\n    ) {\n        m_reporter->assertionStarting( info );\n\n        m_lastAssertionInfo = info;\n\n        AssertionResultData data( resultType, LazyExpression( false ) );\n        data.message = static_cast<std::string>(message);\n        AssertionResult assertionResult{ m_lastAssertionInfo, data };\n        assertionEnded( assertionResult );\n        if( !assertionResult.isOk() )\n            populateReaction( reaction );\n    }\n    void RunContext::handleUnexpectedExceptionNotThrown(\n            AssertionInfo const& info,\n            AssertionReaction& reaction\n    ) {\n        handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);\n    }\n\n    void RunContext::handleUnexpectedInflightException(\n            AssertionInfo const& info,\n            std::string const& message,\n            AssertionReaction& reaction\n    ) {\n        m_lastAssertionInfo = info;\n\n        AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );\n        data.message = message;\n        AssertionResult assertionResult{ info, data };\n        assertionEnded( assertionResult );\n        populateReaction( reaction );\n    }\n\n    void RunContext::populateReaction( AssertionReaction& reaction ) {\n        reaction.shouldDebugBreak = m_config->shouldDebugBreak();\n        reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);\n    }\n\n    void RunContext::handleIncomplete(\n            AssertionInfo const& info\n    ) {\n        m_lastAssertionInfo = info;\n\n        AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );\n        data.message = \"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE\";\n        AssertionResult assertionResult{ info, data };\n        assertionEnded( assertionResult );\n    }\n    void RunContext::handleNonExpr(\n            AssertionInfo const &info,\n            ResultWas::OfType resultType,\n            AssertionReaction &reaction\n    ) {\n        m_lastAssertionInfo = info;\n\n        AssertionResultData data( resultType, LazyExpression( false ) );\n        AssertionResult assertionResult{ info, data };\n        assertionEnded( assertionResult );\n\n        if( !assertionResult.isOk() )\n            populateReaction( reaction );\n    }\n\n    IResultCapture& getResultCapture() {\n        if (auto* capture = getCurrentContext().getResultCapture())\n            return *capture;\n        else\n            CATCH_INTERNAL_ERROR(\"No result capture instance\");\n    }\n\n    void seedRng(IConfig const& config) {\n        if (config.rngSeed() != 0) {\n            std::srand(config.rngSeed());\n            rng().seed(config.rngSeed());\n        }\n    }\n\n    unsigned int rngSeed() {\n        return getCurrentContext().getConfig()->rngSeed();\n    }\n\n}\n// end catch_run_context.cpp\n// start catch_section.cpp\n\nnamespace Catch {\n\n    Section::Section( SectionInfo const& info )\n    :   m_info( info ),\n        m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )\n    {\n        m_timer.start();\n    }\n\n    Section::~Section() {\n        if( m_sectionIncluded ) {\n            SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };\n            if( uncaught_exceptions() )\n                getResultCapture().sectionEndedEarly( endInfo );\n            else\n                getResultCapture().sectionEnded( endInfo );\n        }\n    }\n\n    // This indicates whether the section should be executed or not\n    Section::operator bool() const {\n        return m_sectionIncluded;\n    }\n\n} // end namespace Catch\n// end catch_section.cpp\n// start catch_section_info.cpp\n\nnamespace Catch {\n\n    SectionInfo::SectionInfo\n        (   SourceLineInfo const& _lineInfo,\n            std::string const& _name )\n    :   name( _name ),\n        lineInfo( _lineInfo )\n    {}\n\n} // end namespace Catch\n// end catch_section_info.cpp\n// start catch_session.cpp\n\n// start catch_session.h\n\n#include <memory>\n\nnamespace Catch {\n\n    class Session : NonCopyable {\n    public:\n\n        Session();\n        ~Session() override;\n\n        void showHelp() const;\n        void libIdentify();\n\n        int applyCommandLine( int argc, char const * const * argv );\n    #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)\n        int applyCommandLine( int argc, wchar_t const * const * argv );\n    #endif\n\n        void useConfigData( ConfigData const& configData );\n\n        template<typename CharT>\n        int run(int argc, CharT const * const argv[]) {\n            if (m_startupExceptions)\n                return 1;\n            int returnCode = applyCommandLine(argc, argv);\n            if (returnCode == 0)\n                returnCode = run();\n            return returnCode;\n        }\n\n        int run();\n\n        clara::Parser const& cli() const;\n        void cli( clara::Parser const& newParser );\n        ConfigData& configData();\n        Config& config();\n    private:\n        int runInternal();\n\n        clara::Parser m_cli;\n        ConfigData m_configData;\n        std::shared_ptr<Config> m_config;\n        bool m_startupExceptions = false;\n    };\n\n} // end namespace Catch\n\n// end catch_session.h\n// start catch_version.h\n\n#include <iosfwd>\n\nnamespace Catch {\n\n    // Versioning information\n    struct Version {\n        Version( Version const& ) = delete;\n        Version& operator=( Version const& ) = delete;\n        Version(    unsigned int _majorVersion,\n                    unsigned int _minorVersion,\n                    unsigned int _patchNumber,\n                    char const * const _branchName,\n                    unsigned int _buildNumber );\n\n        unsigned int const majorVersion;\n        unsigned int const minorVersion;\n        unsigned int const patchNumber;\n\n        // buildNumber is only used if branchName is not null\n        char const * const branchName;\n        unsigned int const buildNumber;\n\n        friend std::ostream& operator << ( std::ostream& os, Version const& version );\n    };\n\n    Version const& libraryVersion();\n}\n\n// end catch_version.h\n#include <cstdlib>\n#include <iomanip>\n#include <set>\n#include <iterator>\n\nnamespace Catch {\n\n    namespace {\n        const int MaxExitCode = 255;\n\n        IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {\n            auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);\n            CATCH_ENFORCE(reporter, \"No reporter registered with name: '\" << reporterName << \"'\");\n\n            return reporter;\n        }\n\n        IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {\n            if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {\n                return createReporter(config->getReporterName(), config);\n            }\n\n            // On older platforms, returning std::unique_ptr<ListeningReporter>\n            // when the return type is std::unique_ptr<IStreamingReporter>\n            // doesn't compile without a std::move call. However, this causes\n            // a warning on newer platforms. Thus, we have to work around\n            // it a bit and downcast the pointer manually.\n            auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);\n            auto& multi = static_cast<ListeningReporter&>(*ret);\n            auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();\n            for (auto const& listener : listeners) {\n                multi.addListener(listener->create(Catch::ReporterConfig(config)));\n            }\n            multi.addReporter(createReporter(config->getReporterName(), config));\n            return ret;\n        }\n\n        class TestGroup {\n        public:\n            explicit TestGroup(std::shared_ptr<Config> const& config)\n            : m_config{config}\n            , m_context{config, makeReporter(config)}\n            {\n                auto const& allTestCases = getAllTestCasesSorted(*m_config);\n                m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);\n                auto const& invalidArgs = m_config->testSpec().getInvalidArgs();\n\n                if (m_matches.empty() && invalidArgs.empty()) {\n                    for (auto const& test : allTestCases)\n                        if (!test.isHidden())\n                            m_tests.emplace(&test);\n                } else {\n                    for (auto const& match : m_matches)\n                        m_tests.insert(match.tests.begin(), match.tests.end());\n                }\n            }\n\n            Totals execute() {\n                auto const& invalidArgs = m_config->testSpec().getInvalidArgs();\n                Totals totals;\n                m_context.testGroupStarting(m_config->name(), 1, 1);\n                for (auto const& testCase : m_tests) {\n                    if (!m_context.aborting())\n                        totals += m_context.runTest(*testCase);\n                    else\n                        m_context.reporter().skipTest(*testCase);\n                }\n\n                for (auto const& match : m_matches) {\n                    if (match.tests.empty()) {\n                        m_context.reporter().noMatchingTestCases(match.name);\n                        totals.error = -1;\n                    }\n                }\n\n                if (!invalidArgs.empty()) {\n                    for (auto const& invalidArg: invalidArgs)\n                         m_context.reporter().reportInvalidArguments(invalidArg);\n                }\n\n                m_context.testGroupEnded(m_config->name(), totals, 1, 1);\n                return totals;\n            }\n\n        private:\n            using Tests = std::set<TestCase const*>;\n\n            std::shared_ptr<Config> m_config;\n            RunContext m_context;\n            Tests m_tests;\n            TestSpec::Matches m_matches;\n        };\n\n        void applyFilenamesAsTags(Catch::IConfig const& config) {\n            auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));\n            for (auto& testCase : tests) {\n                auto tags = testCase.tags;\n\n                std::string filename = testCase.lineInfo.file;\n                auto lastSlash = filename.find_last_of(\"\\\\/\");\n                if (lastSlash != std::string::npos) {\n                    filename.erase(0, lastSlash);\n                    filename[0] = '#';\n                }\n\n                auto lastDot = filename.find_last_of('.');\n                if (lastDot != std::string::npos) {\n                    filename.erase(lastDot);\n                }\n\n                tags.push_back(std::move(filename));\n                setTags(testCase, tags);\n            }\n        }\n\n    } // anon namespace\n\n    Session::Session() {\n        static bool alreadyInstantiated = false;\n        if( alreadyInstantiated ) {\n            CATCH_TRY { CATCH_INTERNAL_ERROR( \"Only one instance of Catch::Session can ever be used\" ); }\n            CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }\n        }\n\n        // There cannot be exceptions at startup in no-exception mode.\n#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)\n        const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();\n        if ( !exceptions.empty() ) {\n            config();\n            getCurrentMutableContext().setConfig(m_config);\n\n            m_startupExceptions = true;\n            Colour colourGuard( Colour::Red );\n            Catch::cerr() << \"Errors occurred during startup!\" << '\\n';\n            // iterate over all exceptions and notify user\n            for ( const auto& ex_ptr : exceptions ) {\n                try {\n                    std::rethrow_exception(ex_ptr);\n                } catch ( std::exception const& ex ) {\n                    Catch::cerr() << Column( ex.what() ).indent(2) << '\\n';\n                }\n            }\n        }\n#endif\n\n        alreadyInstantiated = true;\n        m_cli = makeCommandLineParser( m_configData );\n    }\n    Session::~Session() {\n        Catch::cleanUp();\n    }\n\n    void Session::showHelp() const {\n        Catch::cout()\n                << \"\\nCatch v\" << libraryVersion() << \"\\n\"\n                << m_cli << std::endl\n                << \"For more detailed usage please see the project docs\\n\" << std::endl;\n    }\n    void Session::libIdentify() {\n        Catch::cout()\n                << std::left << std::setw(16) << \"description: \" << \"A Catch2 test executable\\n\"\n                << std::left << std::setw(16) << \"category: \" << \"testframework\\n\"\n                << std::left << std::setw(16) << \"framework: \" << \"Catch Test\\n\"\n                << std::left << std::setw(16) << \"version: \" << libraryVersion() << std::endl;\n    }\n\n    int Session::applyCommandLine( int argc, char const * const * argv ) {\n        if( m_startupExceptions )\n            return 1;\n\n        auto result = m_cli.parse( clara::Args( argc, argv ) );\n        if( !result ) {\n            config();\n            getCurrentMutableContext().setConfig(m_config);\n            Catch::cerr()\n                << Colour( Colour::Red )\n                << \"\\nError(s) in input:\\n\"\n                << Column( result.errorMessage() ).indent( 2 )\n                << \"\\n\\n\";\n            Catch::cerr() << \"Run with -? for usage\\n\" << std::endl;\n            return MaxExitCode;\n        }\n\n        if( m_configData.showHelp )\n            showHelp();\n        if( m_configData.libIdentify )\n            libIdentify();\n        m_config.reset();\n        return 0;\n    }\n\n#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)\n    int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {\n\n        char **utf8Argv = new char *[ argc ];\n\n        for ( int i = 0; i < argc; ++i ) {\n            int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );\n\n            utf8Argv[ i ] = new char[ bufSize ];\n\n            WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );\n        }\n\n        int returnCode = applyCommandLine( argc, utf8Argv );\n\n        for ( int i = 0; i < argc; ++i )\n            delete [] utf8Argv[ i ];\n\n        delete [] utf8Argv;\n\n        return returnCode;\n    }\n#endif\n\n    void Session::useConfigData( ConfigData const& configData ) {\n        m_configData = configData;\n        m_config.reset();\n    }\n\n    int Session::run() {\n        if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {\n            Catch::cout() << \"...waiting for enter/ return before starting\" << std::endl;\n            static_cast<void>(std::getchar());\n        }\n        int exitCode = runInternal();\n        if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {\n            Catch::cout() << \"...waiting for enter/ return before exiting, with code: \" << exitCode << std::endl;\n            static_cast<void>(std::getchar());\n        }\n        return exitCode;\n    }\n\n    clara::Parser const& Session::cli() const {\n        return m_cli;\n    }\n    void Session::cli( clara::Parser const& newParser ) {\n        m_cli = newParser;\n    }\n    ConfigData& Session::configData() {\n        return m_configData;\n    }\n    Config& Session::config() {\n        if( !m_config )\n            m_config = std::make_shared<Config>( m_configData );\n        return *m_config;\n    }\n\n    int Session::runInternal() {\n        if( m_startupExceptions )\n            return 1;\n\n        if (m_configData.showHelp || m_configData.libIdentify) {\n            return 0;\n        }\n\n        CATCH_TRY {\n            config(); // Force config to be constructed\n\n            seedRng( *m_config );\n\n            if( m_configData.filenamesAsTags )\n                applyFilenamesAsTags( *m_config );\n\n            // Handle list request\n            if( Option<std::size_t> listed = list( m_config ) )\n                return static_cast<int>( *listed );\n\n            TestGroup tests { m_config };\n            auto const totals = tests.execute();\n\n            if( m_config->warnAboutNoTests() && totals.error == -1 )\n                return 2;\n\n            // Note that on unices only the lower 8 bits are usually used, clamping\n            // the return value to 255 prevents false negative when some multiple\n            // of 256 tests has failed\n            return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));\n        }\n#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)\n        catch( std::exception& ex ) {\n            Catch::cerr() << ex.what() << std::endl;\n            return MaxExitCode;\n        }\n#endif\n    }\n\n} // end namespace Catch\n// end catch_session.cpp\n// start catch_singletons.cpp\n\n#include <vector>\n\nnamespace Catch {\n\n    namespace {\n        static auto getSingletons() -> std::vector<ISingleton*>*& {\n            static std::vector<ISingleton*>* g_singletons = nullptr;\n            if( !g_singletons )\n                g_singletons = new std::vector<ISingleton*>();\n            return g_singletons;\n        }\n    }\n\n    ISingleton::~ISingleton() {}\n\n    void addSingleton(ISingleton* singleton ) {\n        getSingletons()->push_back( singleton );\n    }\n    void cleanupSingletons() {\n        auto& singletons = getSingletons();\n        for( auto singleton : *singletons )\n            delete singleton;\n        delete singletons;\n        singletons = nullptr;\n    }\n\n} // namespace Catch\n// end catch_singletons.cpp\n// start catch_startup_exception_registry.cpp\n\nnamespace Catch {\nvoid StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {\n        CATCH_TRY {\n            m_exceptions.push_back(exception);\n        } CATCH_CATCH_ALL {\n            // If we run out of memory during start-up there's really not a lot more we can do about it\n            std::terminate();\n        }\n    }\n\n    std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {\n        return m_exceptions;\n    }\n\n} // end namespace Catch\n// end catch_startup_exception_registry.cpp\n// start catch_stream.cpp\n\n#include <cstdio>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <memory>\n\nnamespace Catch {\n\n    Catch::IStream::~IStream() = default;\n\n    namespace Detail { namespace {\n        template<typename WriterF, std::size_t bufferSize=256>\n        class StreamBufImpl : public std::streambuf {\n            char data[bufferSize];\n            WriterF m_writer;\n\n        public:\n            StreamBufImpl() {\n                setp( data, data + sizeof(data) );\n            }\n\n            ~StreamBufImpl() noexcept {\n                StreamBufImpl::sync();\n            }\n\n        private:\n            int overflow( int c ) override {\n                sync();\n\n                if( c != EOF ) {\n                    if( pbase() == epptr() )\n                        m_writer( std::string( 1, static_cast<char>( c ) ) );\n                    else\n                        sputc( static_cast<char>( c ) );\n                }\n                return 0;\n            }\n\n            int sync() override {\n                if( pbase() != pptr() ) {\n                    m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );\n                    setp( pbase(), epptr() );\n                }\n                return 0;\n            }\n        };\n\n        ///////////////////////////////////////////////////////////////////////////\n\n        struct OutputDebugWriter {\n\n            void operator()( std::string const&str ) {\n                writeToDebugConsole( str );\n            }\n        };\n\n        ///////////////////////////////////////////////////////////////////////////\n\n        class FileStream : public IStream {\n            mutable std::ofstream m_ofs;\n        public:\n            FileStream( StringRef filename ) {\n                m_ofs.open( filename.c_str() );\n                CATCH_ENFORCE( !m_ofs.fail(), \"Unable to open file: '\" << filename << \"'\" );\n            }\n            ~FileStream() override = default;\n        public: // IStream\n            std::ostream& stream() const override {\n                return m_ofs;\n            }\n        };\n\n        ///////////////////////////////////////////////////////////////////////////\n\n        class CoutStream : public IStream {\n            mutable std::ostream m_os;\n        public:\n            // Store the streambuf from cout up-front because\n            // cout may get redirected when running tests\n            CoutStream() : m_os( Catch::cout().rdbuf() ) {}\n            ~CoutStream() override = default;\n\n        public: // IStream\n            std::ostream& stream() const override { return m_os; }\n        };\n\n        ///////////////////////////////////////////////////////////////////////////\n\n        class DebugOutStream : public IStream {\n            std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;\n            mutable std::ostream m_os;\n        public:\n            DebugOutStream()\n            :   m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),\n                m_os( m_streamBuf.get() )\n            {}\n\n            ~DebugOutStream() override = default;\n\n        public: // IStream\n            std::ostream& stream() const override { return m_os; }\n        };\n\n    }} // namespace anon::detail\n\n    ///////////////////////////////////////////////////////////////////////////\n\n    auto makeStream( StringRef const &filename ) -> IStream const* {\n        if( filename.empty() )\n            return new Detail::CoutStream();\n        else if( filename[0] == '%' ) {\n            if( filename == \"%debug\" )\n                return new Detail::DebugOutStream();\n            else\n                CATCH_ERROR( \"Unrecognised stream: '\" << filename << \"'\" );\n        }\n        else\n            return new Detail::FileStream( filename );\n    }\n\n    // This class encapsulates the idea of a pool of ostringstreams that can be reused.\n    struct StringStreams {\n        std::vector<std::unique_ptr<std::ostringstream>> m_streams;\n        std::vector<std::size_t> m_unused;\n        std::ostringstream m_referenceStream; // Used for copy state/ flags from\n\n        auto add() -> std::size_t {\n            if( m_unused.empty() ) {\n                m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );\n                return m_streams.size()-1;\n            }\n            else {\n                auto index = m_unused.back();\n                m_unused.pop_back();\n                return index;\n            }\n        }\n\n        void release( std::size_t index ) {\n            m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state\n            m_unused.push_back(index);\n        }\n    };\n\n    ReusableStringStream::ReusableStringStream()\n    :   m_index( Singleton<StringStreams>::getMutable().add() ),\n        m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )\n    {}\n\n    ReusableStringStream::~ReusableStringStream() {\n        static_cast<std::ostringstream*>( m_oss )->str(\"\");\n        m_oss->clear();\n        Singleton<StringStreams>::getMutable().release( m_index );\n    }\n\n    auto ReusableStringStream::str() const -> std::string {\n        return static_cast<std::ostringstream*>( m_oss )->str();\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n\n#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions\n    std::ostream& cout() { return std::cout; }\n    std::ostream& cerr() { return std::cerr; }\n    std::ostream& clog() { return std::clog; }\n#endif\n}\n// end catch_stream.cpp\n// start catch_string_manip.cpp\n\n#include <algorithm>\n#include <ostream>\n#include <cstring>\n#include <cctype>\n#include <vector>\n\nnamespace Catch {\n\n    namespace {\n        char toLowerCh(char c) {\n            return static_cast<char>( std::tolower( c ) );\n        }\n    }\n\n    bool startsWith( std::string const& s, std::string const& prefix ) {\n        return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());\n    }\n    bool startsWith( std::string const& s, char prefix ) {\n        return !s.empty() && s[0] == prefix;\n    }\n    bool endsWith( std::string const& s, std::string const& suffix ) {\n        return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());\n    }\n    bool endsWith( std::string const& s, char suffix ) {\n        return !s.empty() && s[s.size()-1] == suffix;\n    }\n    bool contains( std::string const& s, std::string const& infix ) {\n        return s.find( infix ) != std::string::npos;\n    }\n    void toLowerInPlace( std::string& s ) {\n        std::transform( s.begin(), s.end(), s.begin(), toLowerCh );\n    }\n    std::string toLower( std::string const& s ) {\n        std::string lc = s;\n        toLowerInPlace( lc );\n        return lc;\n    }\n    std::string trim( std::string const& str ) {\n        static char const* whitespaceChars = \"\\n\\r\\t \";\n        std::string::size_type start = str.find_first_not_of( whitespaceChars );\n        std::string::size_type end = str.find_last_not_of( whitespaceChars );\n\n        return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();\n    }\n\n    StringRef trim(StringRef ref) {\n        const auto is_ws = [](char c) {\n            return c == ' ' || c == '\\t' || c == '\\n' || c == '\\r';\n        };\n        size_t real_begin = 0;\n        while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }\n        size_t real_end = ref.size();\n        while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }\n\n        return ref.substr(real_begin, real_end - real_begin);\n    }\n\n    bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {\n        bool replaced = false;\n        std::size_t i = str.find( replaceThis );\n        while( i != std::string::npos ) {\n            replaced = true;\n            str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );\n            if( i < str.size()-withThis.size() )\n                i = str.find( replaceThis, i+withThis.size() );\n            else\n                i = std::string::npos;\n        }\n        return replaced;\n    }\n\n    std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {\n        std::vector<StringRef> subStrings;\n        std::size_t start = 0;\n        for(std::size_t pos = 0; pos < str.size(); ++pos ) {\n            if( str[pos] == delimiter ) {\n                if( pos - start > 1 )\n                    subStrings.push_back( str.substr( start, pos-start ) );\n                start = pos+1;\n            }\n        }\n        if( start < str.size() )\n            subStrings.push_back( str.substr( start, str.size()-start ) );\n        return subStrings;\n    }\n\n    pluralise::pluralise( std::size_t count, std::string const& label )\n    :   m_count( count ),\n        m_label( label )\n    {}\n\n    std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {\n        os << pluraliser.m_count << ' ' << pluraliser.m_label;\n        if( pluraliser.m_count != 1 )\n            os << 's';\n        return os;\n    }\n\n}\n// end catch_string_manip.cpp\n// start catch_stringref.cpp\n\n#include <algorithm>\n#include <ostream>\n#include <cstring>\n#include <cstdint>\n\nnamespace Catch {\n    StringRef::StringRef( char const* rawChars ) noexcept\n    : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )\n    {}\n\n    auto StringRef::c_str() const -> char const* {\n        CATCH_ENFORCE(isNullTerminated(), \"Called StringRef::c_str() on a non-null-terminated instance\");\n        return m_start;\n    }\n    auto StringRef::data() const noexcept -> char const* {\n        return m_start;\n    }\n\n    auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {\n        if (start < m_size) {\n            return StringRef(m_start + start, (std::min)(m_size - start, size));\n        } else {\n            return StringRef();\n        }\n    }\n    auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {\n        return m_size == other.m_size\n            && (std::memcmp( m_start, other.m_start, m_size ) == 0);\n    }\n\n    auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {\n        return os.write(str.data(), str.size());\n    }\n\n    auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {\n        lhs.append(rhs.data(), rhs.size());\n        return lhs;\n    }\n\n} // namespace Catch\n// end catch_stringref.cpp\n// start catch_tag_alias.cpp\n\nnamespace Catch {\n    TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}\n}\n// end catch_tag_alias.cpp\n// start catch_tag_alias_autoregistrar.cpp\n\nnamespace Catch {\n\n    RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {\n        CATCH_TRY {\n            getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);\n        } CATCH_CATCH_ALL {\n            // Do not throw when constructing global objects, instead register the exception to be processed later\n            getMutableRegistryHub().registerStartupException();\n        }\n    }\n\n}\n// end catch_tag_alias_autoregistrar.cpp\n// start catch_tag_alias_registry.cpp\n\n#include <sstream>\n\nnamespace Catch {\n\n    TagAliasRegistry::~TagAliasRegistry() {}\n\n    TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {\n        auto it = m_registry.find( alias );\n        if( it != m_registry.end() )\n            return &(it->second);\n        else\n            return nullptr;\n    }\n\n    std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {\n        std::string expandedTestSpec = unexpandedTestSpec;\n        for( auto const& registryKvp : m_registry ) {\n            std::size_t pos = expandedTestSpec.find( registryKvp.first );\n            if( pos != std::string::npos ) {\n                expandedTestSpec =  expandedTestSpec.substr( 0, pos ) +\n                                    registryKvp.second.tag +\n                                    expandedTestSpec.substr( pos + registryKvp.first.size() );\n            }\n        }\n        return expandedTestSpec;\n    }\n\n    void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {\n        CATCH_ENFORCE( startsWith(alias, \"[@\") && endsWith(alias, ']'),\n                      \"error: tag alias, '\" << alias << \"' is not of the form [@alias name].\\n\" << lineInfo );\n\n        CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,\n                      \"error: tag alias, '\" << alias << \"' already registered.\\n\"\n                      << \"\\tFirst seen at: \" << find(alias)->lineInfo << \"\\n\"\n                      << \"\\tRedefined at: \" << lineInfo );\n    }\n\n    ITagAliasRegistry::~ITagAliasRegistry() {}\n\n    ITagAliasRegistry const& ITagAliasRegistry::get() {\n        return getRegistryHub().getTagAliasRegistry();\n    }\n\n} // end namespace Catch\n// end catch_tag_alias_registry.cpp\n// start catch_test_case_info.cpp\n\n#include <cctype>\n#include <exception>\n#include <algorithm>\n#include <sstream>\n\nnamespace Catch {\n\n    namespace {\n        TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {\n            if( startsWith( tag, '.' ) ||\n                tag == \"!hide\" )\n                return TestCaseInfo::IsHidden;\n            else if( tag == \"!throws\" )\n                return TestCaseInfo::Throws;\n            else if( tag == \"!shouldfail\" )\n                return TestCaseInfo::ShouldFail;\n            else if( tag == \"!mayfail\" )\n                return TestCaseInfo::MayFail;\n            else if( tag == \"!nonportable\" )\n                return TestCaseInfo::NonPortable;\n            else if( tag == \"!benchmark\" )\n                return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );\n            else\n                return TestCaseInfo::None;\n        }\n        bool isReservedTag( std::string const& tag ) {\n            return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );\n        }\n        void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {\n            CATCH_ENFORCE( !isReservedTag(tag),\n                          \"Tag name: [\" << tag << \"] is not allowed.\\n\"\n                          << \"Tag names starting with non alphanumeric characters are reserved\\n\"\n                          << _lineInfo );\n        }\n    }\n\n    TestCase makeTestCase(  ITestInvoker* _testCase,\n                            std::string const& _className,\n                            NameAndTags const& nameAndTags,\n                            SourceLineInfo const& _lineInfo )\n    {\n        bool isHidden = false;\n\n        // Parse out tags\n        std::vector<std::string> tags;\n        std::string desc, tag;\n        bool inTag = false;\n        for (char c : nameAndTags.tags) {\n            if( !inTag ) {\n                if( c == '[' )\n                    inTag = true;\n                else\n                    desc += c;\n            }\n            else {\n                if( c == ']' ) {\n                    TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );\n                    if( ( prop & TestCaseInfo::IsHidden ) != 0 )\n                        isHidden = true;\n                    else if( prop == TestCaseInfo::None )\n                        enforceNotReservedTag( tag, _lineInfo );\n\n                    // Merged hide tags like `[.approvals]` should be added as\n                    // `[.][approvals]`. The `[.]` is added at later point, so\n                    // we only strip the prefix\n                    if (startsWith(tag, '.') && tag.size() > 1) {\n                        tag.erase(0, 1);\n                    }\n                    tags.push_back( tag );\n                    tag.clear();\n                    inTag = false;\n                }\n                else\n                    tag += c;\n            }\n        }\n        if( isHidden ) {\n            tags.push_back( \".\" );\n        }\n\n        TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );\n        return TestCase( _testCase, std::move(info) );\n    }\n\n    void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {\n        std::sort(begin(tags), end(tags));\n        tags.erase(std::unique(begin(tags), end(tags)), end(tags));\n        testCaseInfo.lcaseTags.clear();\n\n        for( auto const& tag : tags ) {\n            std::string lcaseTag = toLower( tag );\n            testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );\n            testCaseInfo.lcaseTags.push_back( lcaseTag );\n        }\n        testCaseInfo.tags = std::move(tags);\n    }\n\n    TestCaseInfo::TestCaseInfo( std::string const& _name,\n                                std::string const& _className,\n                                std::string const& _description,\n                                std::vector<std::string> const& _tags,\n                                SourceLineInfo const& _lineInfo )\n    :   name( _name ),\n        className( _className ),\n        description( _description ),\n        lineInfo( _lineInfo ),\n        properties( None )\n    {\n        setTags( *this, _tags );\n    }\n\n    bool TestCaseInfo::isHidden() const {\n        return ( properties & IsHidden ) != 0;\n    }\n    bool TestCaseInfo::throws() const {\n        return ( properties & Throws ) != 0;\n    }\n    bool TestCaseInfo::okToFail() const {\n        return ( properties & (ShouldFail | MayFail ) ) != 0;\n    }\n    bool TestCaseInfo::expectedToFail() const {\n        return ( properties & (ShouldFail ) ) != 0;\n    }\n\n    std::string TestCaseInfo::tagsAsString() const {\n        std::string ret;\n        // '[' and ']' per tag\n        std::size_t full_size = 2 * tags.size();\n        for (const auto& tag : tags) {\n            full_size += tag.size();\n        }\n        ret.reserve(full_size);\n        for (const auto& tag : tags) {\n            ret.push_back('[');\n            ret.append(tag);\n            ret.push_back(']');\n        }\n\n        return ret;\n    }\n\n    TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}\n\n    TestCase TestCase::withName( std::string const& _newName ) const {\n        TestCase other( *this );\n        other.name = _newName;\n        return other;\n    }\n\n    void TestCase::invoke() const {\n        test->invoke();\n    }\n\n    bool TestCase::operator == ( TestCase const& other ) const {\n        return  test.get() == other.test.get() &&\n                name == other.name &&\n                className == other.className;\n    }\n\n    bool TestCase::operator < ( TestCase const& other ) const {\n        return name < other.name;\n    }\n\n    TestCaseInfo const& TestCase::getTestCaseInfo() const\n    {\n        return *this;\n    }\n\n} // end namespace Catch\n// end catch_test_case_info.cpp\n// start catch_test_case_registry_impl.cpp\n\n#include <sstream>\n\nnamespace Catch {\n\n    std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {\n\n        std::vector<TestCase> sorted = unsortedTestCases;\n\n        switch( config.runOrder() ) {\n            case RunTests::InLexicographicalOrder:\n                std::sort( sorted.begin(), sorted.end() );\n                break;\n            case RunTests::InRandomOrder:\n                seedRng( config );\n                std::shuffle( sorted.begin(), sorted.end(), rng() );\n                break;\n            case RunTests::InDeclarationOrder:\n                // already in declaration order\n                break;\n        }\n        return sorted;\n    }\n\n    bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {\n        return !testCase.throws() || config.allowThrows();\n    }\n\n    bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {\n        return testSpec.matches( testCase ) && isThrowSafe( testCase, config );\n    }\n\n    void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {\n        std::set<TestCase> seenFunctions;\n        for( auto const& function : functions ) {\n            auto prev = seenFunctions.insert( function );\n            CATCH_ENFORCE( prev.second,\n                    \"error: TEST_CASE( \\\"\" << function.name << \"\\\" ) already defined.\\n\"\n                    << \"\\tFirst seen at \" << prev.first->getTestCaseInfo().lineInfo << \"\\n\"\n                    << \"\\tRedefined at \" << function.getTestCaseInfo().lineInfo );\n        }\n    }\n\n    std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {\n        std::vector<TestCase> filtered;\n        filtered.reserve( testCases.size() );\n        for (auto const& testCase : testCases) {\n            if ((!testSpec.hasFilters() && !testCase.isHidden()) ||\n                (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {\n                filtered.push_back(testCase);\n            }\n        }\n        return filtered;\n    }\n    std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {\n        return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );\n    }\n\n    void TestRegistry::registerTest( TestCase const& testCase ) {\n        std::string name = testCase.getTestCaseInfo().name;\n        if( name.empty() ) {\n            ReusableStringStream rss;\n            rss << \"Anonymous test case \" << ++m_unnamedCount;\n            return registerTest( testCase.withName( rss.str() ) );\n        }\n        m_functions.push_back( testCase );\n    }\n\n    std::vector<TestCase> const& TestRegistry::getAllTests() const {\n        return m_functions;\n    }\n    std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {\n        if( m_sortedFunctions.empty() )\n            enforceNoDuplicateTestCases( m_functions );\n\n        if(  m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {\n            m_sortedFunctions = sortTests( config, m_functions );\n            m_currentSortOrder = config.runOrder();\n        }\n        return m_sortedFunctions;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}\n\n    void TestInvokerAsFunction::invoke() const {\n        m_testAsFunction();\n    }\n\n    std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {\n        std::string className(classOrQualifiedMethodName);\n        if( startsWith( className, '&' ) )\n        {\n            std::size_t lastColons = className.rfind( \"::\" );\n            std::size_t penultimateColons = className.rfind( \"::\", lastColons-1 );\n            if( penultimateColons == std::string::npos )\n                penultimateColons = 1;\n            className = className.substr( penultimateColons, lastColons-penultimateColons );\n        }\n        return className;\n    }\n\n} // end namespace Catch\n// end catch_test_case_registry_impl.cpp\n// start catch_test_case_tracker.cpp\n\n#include <algorithm>\n#include <cassert>\n#include <stdexcept>\n#include <memory>\n#include <sstream>\n\n#if defined(__clang__)\n#    pragma clang diagnostic push\n#    pragma clang diagnostic ignored \"-Wexit-time-destructors\"\n#endif\n\nnamespace Catch {\nnamespace TestCaseTracking {\n\n    NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )\n    :   name( _name ),\n        location( _location )\n    {}\n\n    ITracker::~ITracker() = default;\n\n    ITracker& TrackerContext::startRun() {\n        m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( \"{root}\", CATCH_INTERNAL_LINEINFO ), *this, nullptr );\n        m_currentTracker = nullptr;\n        m_runState = Executing;\n        return *m_rootTracker;\n    }\n\n    void TrackerContext::endRun() {\n        m_rootTracker.reset();\n        m_currentTracker = nullptr;\n        m_runState = NotStarted;\n    }\n\n    void TrackerContext::startCycle() {\n        m_currentTracker = m_rootTracker.get();\n        m_runState = Executing;\n    }\n    void TrackerContext::completeCycle() {\n        m_runState = CompletedCycle;\n    }\n\n    bool TrackerContext::completedCycle() const {\n        return m_runState == CompletedCycle;\n    }\n    ITracker& TrackerContext::currentTracker() {\n        return *m_currentTracker;\n    }\n    void TrackerContext::setCurrentTracker( ITracker* tracker ) {\n        m_currentTracker = tracker;\n    }\n\n    TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )\n    :   m_nameAndLocation( nameAndLocation ),\n        m_ctx( ctx ),\n        m_parent( parent )\n    {}\n\n    NameAndLocation const& TrackerBase::nameAndLocation() const {\n        return m_nameAndLocation;\n    }\n    bool TrackerBase::isComplete() const {\n        return m_runState == CompletedSuccessfully || m_runState == Failed;\n    }\n    bool TrackerBase::isSuccessfullyCompleted() const {\n        return m_runState == CompletedSuccessfully;\n    }\n    bool TrackerBase::isOpen() const {\n        return m_runState != NotStarted && !isComplete();\n    }\n    bool TrackerBase::hasChildren() const {\n        return !m_children.empty();\n    }\n\n    void TrackerBase::addChild( ITrackerPtr const& child ) {\n        m_children.push_back( child );\n    }\n\n    ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {\n        auto it = std::find_if( m_children.begin(), m_children.end(),\n            [&nameAndLocation]( ITrackerPtr const& tracker ){\n                return\n                    tracker->nameAndLocation().location == nameAndLocation.location &&\n                    tracker->nameAndLocation().name == nameAndLocation.name;\n            } );\n        return( it != m_children.end() )\n            ? *it\n            : nullptr;\n    }\n    ITracker& TrackerBase::parent() {\n        assert( m_parent ); // Should always be non-null except for root\n        return *m_parent;\n    }\n\n    void TrackerBase::openChild() {\n        if( m_runState != ExecutingChildren ) {\n            m_runState = ExecutingChildren;\n            if( m_parent )\n                m_parent->openChild();\n        }\n    }\n\n    bool TrackerBase::isSectionTracker() const { return false; }\n    bool TrackerBase::isGeneratorTracker() const { return false; }\n\n    void TrackerBase::open() {\n        m_runState = Executing;\n        moveToThis();\n        if( m_parent )\n            m_parent->openChild();\n    }\n\n    void TrackerBase::close() {\n\n        // Close any still open children (e.g. generators)\n        while( &m_ctx.currentTracker() != this )\n            m_ctx.currentTracker().close();\n\n        switch( m_runState ) {\n            case NeedsAnotherRun:\n                break;\n\n            case Executing:\n                m_runState = CompletedSuccessfully;\n                break;\n            case ExecutingChildren:\n                if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )\n                    m_runState = CompletedSuccessfully;\n                break;\n\n            case NotStarted:\n            case CompletedSuccessfully:\n            case Failed:\n                CATCH_INTERNAL_ERROR( \"Illogical state: \" << m_runState );\n\n            default:\n                CATCH_INTERNAL_ERROR( \"Unknown state: \" << m_runState );\n        }\n        moveToParent();\n        m_ctx.completeCycle();\n    }\n    void TrackerBase::fail() {\n        m_runState = Failed;\n        if( m_parent )\n            m_parent->markAsNeedingAnotherRun();\n        moveToParent();\n        m_ctx.completeCycle();\n    }\n    void TrackerBase::markAsNeedingAnotherRun() {\n        m_runState = NeedsAnotherRun;\n    }\n\n    void TrackerBase::moveToParent() {\n        assert( m_parent );\n        m_ctx.setCurrentTracker( m_parent );\n    }\n    void TrackerBase::moveToThis() {\n        m_ctx.setCurrentTracker( this );\n    }\n\n    SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )\n    :   TrackerBase( nameAndLocation, ctx, parent ),\n        m_trimmed_name(trim(nameAndLocation.name))\n    {\n        if( parent ) {\n            while( !parent->isSectionTracker() )\n                parent = &parent->parent();\n\n            SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );\n            addNextFilters( parentSection.m_filters );\n        }\n    }\n\n    bool SectionTracker::isComplete() const {\n        bool complete = true;\n\n        if ((m_filters.empty() || m_filters[0] == \"\")\n            || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {\n            complete = TrackerBase::isComplete();\n        }\n        return complete;\n    }\n\n    bool SectionTracker::isSectionTracker() const { return true; }\n\n    SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {\n        std::shared_ptr<SectionTracker> section;\n\n        ITracker& currentTracker = ctx.currentTracker();\n        if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {\n            assert( childTracker );\n            assert( childTracker->isSectionTracker() );\n            section = std::static_pointer_cast<SectionTracker>( childTracker );\n        }\n        else {\n            section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );\n            currentTracker.addChild( section );\n        }\n        if( !ctx.completedCycle() )\n            section->tryOpen();\n        return *section;\n    }\n\n    void SectionTracker::tryOpen() {\n        if( !isComplete() )\n            open();\n    }\n\n    void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {\n        if( !filters.empty() ) {\n            m_filters.reserve( m_filters.size() + filters.size() + 2 );\n            m_filters.push_back(\"\"); // Root - should never be consulted\n            m_filters.push_back(\"\"); // Test Case - not a section filter\n            m_filters.insert( m_filters.end(), filters.begin(), filters.end() );\n        }\n    }\n    void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {\n        if( filters.size() > 1 )\n            m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );\n    }\n\n} // namespace TestCaseTracking\n\nusing TestCaseTracking::ITracker;\nusing TestCaseTracking::TrackerContext;\nusing TestCaseTracking::SectionTracker;\n\n} // namespace Catch\n\n#if defined(__clang__)\n#    pragma clang diagnostic pop\n#endif\n// end catch_test_case_tracker.cpp\n// start catch_test_registry.cpp\n\nnamespace Catch {\n\n    auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {\n        return new(std::nothrow) TestInvokerAsFunction( testAsFunction );\n    }\n\n    NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}\n\n    AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {\n        CATCH_TRY {\n            getMutableRegistryHub()\n                    .registerTest(\n                        makeTestCase(\n                            invoker,\n                            extractClassName( classOrMethod ),\n                            nameAndTags,\n                            lineInfo));\n        } CATCH_CATCH_ALL {\n            // Do not throw when constructing global objects, instead register the exception to be processed later\n            getMutableRegistryHub().registerStartupException();\n        }\n    }\n\n    AutoReg::~AutoReg() = default;\n}\n// end catch_test_registry.cpp\n// start catch_test_spec.cpp\n\n#include <algorithm>\n#include <string>\n#include <vector>\n#include <memory>\n\nnamespace Catch {\n\n    TestSpec::Pattern::Pattern( std::string const& name )\n    : m_name( name )\n    {}\n\n    TestSpec::Pattern::~Pattern() = default;\n\n    std::string const& TestSpec::Pattern::name() const {\n        return m_name;\n    }\n\n    TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )\n    : Pattern( filterString )\n    , m_wildcardPattern( toLower( name ), CaseSensitive::No )\n    {}\n\n    bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {\n        return m_wildcardPattern.matches( testCase.name );\n    }\n\n    TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )\n    : Pattern( filterString )\n    , m_tag( toLower( tag ) )\n    {}\n\n    bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {\n        return std::find(begin(testCase.lcaseTags),\n                         end(testCase.lcaseTags),\n                         m_tag) != end(testCase.lcaseTags);\n    }\n\n    TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )\n    : Pattern( underlyingPattern->name() )\n    , m_underlyingPattern( underlyingPattern )\n    {}\n\n    bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {\n        return !m_underlyingPattern->matches( testCase );\n    }\n\n    bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {\n        return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );\n    }\n\n    std::string TestSpec::Filter::name() const {\n        std::string name;\n        for( auto const& p : m_patterns )\n            name += p->name();\n        return name;\n    }\n\n    bool TestSpec::hasFilters() const {\n        return !m_filters.empty();\n    }\n\n    bool TestSpec::matches( TestCaseInfo const& testCase ) const {\n        return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );\n    }\n\n    TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const\n    {\n        Matches matches( m_filters.size() );\n        std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){\n            std::vector<TestCase const*> currentMatches;\n            for( auto const& test : testCases )\n                if( isThrowSafe( test, config ) && filter.matches( test ) )\n                    currentMatches.emplace_back( &test );\n            return FilterMatch{ filter.name(), currentMatches };\n        } );\n        return matches;\n    }\n\n    const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{\n        return  (m_invalidArgs);\n    }\n\n}\n// end catch_test_spec.cpp\n// start catch_test_spec_parser.cpp\n\nnamespace Catch {\n\n    TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}\n\n    TestSpecParser& TestSpecParser::parse( std::string const& arg ) {\n        m_mode = None;\n        m_exclusion = false;\n        m_arg = m_tagAliases->expandAliases( arg );\n        m_escapeChars.clear();\n        m_substring.reserve(m_arg.size());\n        m_patternName.reserve(m_arg.size());\n        m_realPatternPos = 0;\n\n        for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )\n          //if visitChar fails\n           if( !visitChar( m_arg[m_pos] ) ){\n               m_testSpec.m_invalidArgs.push_back(arg);\n               break;\n           }\n        endMode();\n        return *this;\n    }\n    TestSpec TestSpecParser::testSpec() {\n        addFilter();\n        return m_testSpec;\n    }\n    bool TestSpecParser::visitChar( char c ) {\n        if( (m_mode != EscapedName) && (c == '\\\\') ) {\n            escape();\n            addCharToPattern(c);\n            return true;\n        }else if((m_mode != EscapedName) && (c == ',') )  {\n            return separate();\n        }\n\n        switch( m_mode ) {\n        case None:\n            if( processNoneChar( c ) )\n                return true;\n            break;\n        case Name:\n            processNameChar( c );\n            break;\n        case EscapedName:\n            endMode();\n            addCharToPattern(c);\n            return true;\n        default:\n        case Tag:\n        case QuotedName:\n            if( processOtherChar( c ) )\n                return true;\n            break;\n        }\n\n        m_substring += c;\n        if( !isControlChar( c ) ) {\n            m_patternName += c;\n            m_realPatternPos++;\n        }\n        return true;\n    }\n    // Two of the processing methods return true to signal the caller to return\n    // without adding the given character to the current pattern strings\n    bool TestSpecParser::processNoneChar( char c ) {\n        switch( c ) {\n        case ' ':\n            return true;\n        case '~':\n            m_exclusion = true;\n            return false;\n        case '[':\n            startNewMode( Tag );\n            return false;\n        case '\"':\n            startNewMode( QuotedName );\n            return false;\n        default:\n            startNewMode( Name );\n            return false;\n        }\n    }\n    void TestSpecParser::processNameChar( char c ) {\n        if( c == '[' ) {\n            if( m_substring == \"exclude:\" )\n                m_exclusion = true;\n            else\n                endMode();\n            startNewMode( Tag );\n        }\n    }\n    bool TestSpecParser::processOtherChar( char c ) {\n        if( !isControlChar( c ) )\n            return false;\n        m_substring += c;\n        endMode();\n        return true;\n    }\n    void TestSpecParser::startNewMode( Mode mode ) {\n        m_mode = mode;\n    }\n    void TestSpecParser::endMode() {\n        switch( m_mode ) {\n        case Name:\n        case QuotedName:\n            return addNamePattern();\n        case Tag:\n            return addTagPattern();\n        case EscapedName:\n            revertBackToLastMode();\n            return;\n        case None:\n        default:\n            return startNewMode( None );\n        }\n    }\n    void TestSpecParser::escape() {\n        saveLastMode();\n        m_mode = EscapedName;\n        m_escapeChars.push_back(m_realPatternPos);\n    }\n    bool TestSpecParser::isControlChar( char c ) const {\n        switch( m_mode ) {\n            default:\n                return false;\n            case None:\n                return c == '~';\n            case Name:\n                return c == '[';\n            case EscapedName:\n                return true;\n            case QuotedName:\n                return c == '\"';\n            case Tag:\n                return c == '[' || c == ']';\n        }\n    }\n\n    void TestSpecParser::addFilter() {\n        if( !m_currentFilter.m_patterns.empty() ) {\n            m_testSpec.m_filters.push_back( m_currentFilter );\n            m_currentFilter = TestSpec::Filter();\n        }\n    }\n\n    void TestSpecParser::saveLastMode() {\n      lastMode = m_mode;\n    }\n\n    void TestSpecParser::revertBackToLastMode() {\n      m_mode = lastMode;\n    }\n\n    bool TestSpecParser::separate() {\n      if( (m_mode==QuotedName) || (m_mode==Tag) ){\n         //invalid argument, signal failure to previous scope.\n         m_mode = None;\n         m_pos = m_arg.size();\n         m_substring.clear();\n         m_patternName.clear();\n         return false;\n      }\n      endMode();\n      addFilter();\n      return true; //success\n    }\n\n    std::string TestSpecParser::preprocessPattern() {\n        std::string token = m_patternName;\n        for (std::size_t i = 0; i < m_escapeChars.size(); ++i)\n            token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);\n        m_escapeChars.clear();\n        if (startsWith(token, \"exclude:\")) {\n            m_exclusion = true;\n            token = token.substr(8);\n        }\n\n        m_patternName.clear();\n\n        return token;\n    }\n\n    void TestSpecParser::addNamePattern() {\n        auto token = preprocessPattern();\n\n        if (!token.empty()) {\n            TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);\n            if (m_exclusion)\n                pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);\n            m_currentFilter.m_patterns.push_back(pattern);\n        }\n        m_substring.clear();\n        m_exclusion = false;\n        m_mode = None;\n    }\n\n    void TestSpecParser::addTagPattern() {\n        auto token = preprocessPattern();\n\n        if (!token.empty()) {\n            // If the tag pattern is the \"hide and tag\" shorthand (e.g. [.foo])\n            // we have to create a separate hide tag and shorten the real one\n            if (token.size() > 1 && token[0] == '.') {\n                token.erase(token.begin());\n                TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(\".\", m_substring);\n                if (m_exclusion) {\n                    pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);\n                }\n                m_currentFilter.m_patterns.push_back(pattern);\n            }\n\n            TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);\n\n            if (m_exclusion) {\n                pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);\n            }\n            m_currentFilter.m_patterns.push_back(pattern);\n        }\n        m_substring.clear();\n        m_exclusion = false;\n        m_mode = None;\n    }\n\n    TestSpec parseTestSpec( std::string const& arg ) {\n        return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();\n    }\n\n} // namespace Catch\n// end catch_test_spec_parser.cpp\n// start catch_timer.cpp\n\n#include <chrono>\n\nstatic const uint64_t nanosecondsInSecond = 1000000000;\n\nnamespace Catch {\n\n    auto getCurrentNanosecondsSinceEpoch() -> uint64_t {\n        return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();\n    }\n\n    namespace {\n        auto estimateClockResolution() -> uint64_t {\n            uint64_t sum = 0;\n            static const uint64_t iterations = 1000000;\n\n            auto startTime = getCurrentNanosecondsSinceEpoch();\n\n            for( std::size_t i = 0; i < iterations; ++i ) {\n\n                uint64_t ticks;\n                uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();\n                do {\n                    ticks = getCurrentNanosecondsSinceEpoch();\n                } while( ticks == baseTicks );\n\n                auto delta = ticks - baseTicks;\n                sum += delta;\n\n                // If we have been calibrating for over 3 seconds -- the clock\n                // is terrible and we should move on.\n                // TBD: How to signal that the measured resolution is probably wrong?\n                if (ticks > startTime + 3 * nanosecondsInSecond) {\n                    return sum / ( i + 1u );\n                }\n            }\n\n            // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers\n            // - and potentially do more iterations if there's a high variance.\n            return sum/iterations;\n        }\n    }\n    auto getEstimatedClockResolution() -> uint64_t {\n        static auto s_resolution = estimateClockResolution();\n        return s_resolution;\n    }\n\n    void Timer::start() {\n       m_nanoseconds = getCurrentNanosecondsSinceEpoch();\n    }\n    auto Timer::getElapsedNanoseconds() const -> uint64_t {\n        return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;\n    }\n    auto Timer::getElapsedMicroseconds() const -> uint64_t {\n        return getElapsedNanoseconds()/1000;\n    }\n    auto Timer::getElapsedMilliseconds() const -> unsigned int {\n        return static_cast<unsigned int>(getElapsedMicroseconds()/1000);\n    }\n    auto Timer::getElapsedSeconds() const -> double {\n        return getElapsedMicroseconds()/1000000.0;\n    }\n\n} // namespace Catch\n// end catch_timer.cpp\n// start catch_tostring.cpp\n\n#if defined(__clang__)\n#    pragma clang diagnostic push\n#    pragma clang diagnostic ignored \"-Wexit-time-destructors\"\n#    pragma clang diagnostic ignored \"-Wglobal-constructors\"\n#endif\n\n// Enable specific decls locally\n#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)\n#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER\n#endif\n\n#include <cmath>\n#include <iomanip>\n\nnamespace Catch {\n\nnamespace Detail {\n\n    const std::string unprintableString = \"{?}\";\n\n    namespace {\n        const int hexThreshold = 255;\n\n        struct Endianness {\n            enum Arch { Big, Little };\n\n            static Arch which() {\n                int one = 1;\n                // If the lowest byte we read is non-zero, we can assume\n                // that little endian format is used.\n                auto value = *reinterpret_cast<char*>(&one);\n                return value ? Little : Big;\n            }\n        };\n    }\n\n    std::string rawMemoryToString( const void *object, std::size_t size ) {\n        // Reverse order for little endian architectures\n        int i = 0, end = static_cast<int>( size ), inc = 1;\n        if( Endianness::which() == Endianness::Little ) {\n            i = end-1;\n            end = inc = -1;\n        }\n\n        unsigned char const *bytes = static_cast<unsigned char const *>(object);\n        ReusableStringStream rss;\n        rss << \"0x\" << std::setfill('0') << std::hex;\n        for( ; i != end; i += inc )\n             rss << std::setw(2) << static_cast<unsigned>(bytes[i]);\n       return rss.str();\n    }\n}\n\ntemplate<typename T>\nstd::string fpToString( T value, int precision ) {\n    if (Catch::isnan(value)) {\n        return \"nan\";\n    }\n\n    ReusableStringStream rss;\n    rss << std::setprecision( precision )\n        << std::fixed\n        << value;\n    std::string d = rss.str();\n    std::size_t i = d.find_last_not_of( '0' );\n    if( i != std::string::npos && i != d.size()-1 ) {\n        if( d[i] == '.' )\n            i++;\n        d = d.substr( 0, i+1 );\n    }\n    return d;\n}\n\n//// ======================================================= ////\n//\n//   Out-of-line defs for full specialization of StringMaker\n//\n//// ======================================================= ////\n\nstd::string StringMaker<std::string>::convert(const std::string& str) {\n    if (!getCurrentContext().getConfig()->showInvisibles()) {\n        return '\"' + str + '\"';\n    }\n\n    std::string s(\"\\\"\");\n    for (char c : str) {\n        switch (c) {\n        case '\\n':\n            s.append(\"\\\\n\");\n            break;\n        case '\\t':\n            s.append(\"\\\\t\");\n            break;\n        default:\n            s.push_back(c);\n            break;\n        }\n    }\n    s.append(\"\\\"\");\n    return s;\n}\n\n#ifdef CATCH_CONFIG_CPP17_STRING_VIEW\nstd::string StringMaker<std::string_view>::convert(std::string_view str) {\n    return ::Catch::Detail::stringify(std::string{ str });\n}\n#endif\n\nstd::string StringMaker<char const*>::convert(char const* str) {\n    if (str) {\n        return ::Catch::Detail::stringify(std::string{ str });\n    } else {\n        return{ \"{null string}\" };\n    }\n}\nstd::string StringMaker<char*>::convert(char* str) {\n    if (str) {\n        return ::Catch::Detail::stringify(std::string{ str });\n    } else {\n        return{ \"{null string}\" };\n    }\n}\n\n#ifdef CATCH_CONFIG_WCHAR\nstd::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {\n    std::string s;\n    s.reserve(wstr.size());\n    for (auto c : wstr) {\n        s += (c <= 0xff) ? static_cast<char>(c) : '?';\n    }\n    return ::Catch::Detail::stringify(s);\n}\n\n# ifdef CATCH_CONFIG_CPP17_STRING_VIEW\nstd::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {\n    return StringMaker<std::wstring>::convert(std::wstring(str));\n}\n# endif\n\nstd::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {\n    if (str) {\n        return ::Catch::Detail::stringify(std::wstring{ str });\n    } else {\n        return{ \"{null string}\" };\n    }\n}\nstd::string StringMaker<wchar_t *>::convert(wchar_t * str) {\n    if (str) {\n        return ::Catch::Detail::stringify(std::wstring{ str });\n    } else {\n        return{ \"{null string}\" };\n    }\n}\n#endif\n\n#if defined(CATCH_CONFIG_CPP17_BYTE)\n#include <cstddef>\nstd::string StringMaker<std::byte>::convert(std::byte value) {\n    return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));\n}\n#endif // defined(CATCH_CONFIG_CPP17_BYTE)\n\nstd::string StringMaker<int>::convert(int value) {\n    return ::Catch::Detail::stringify(static_cast<long long>(value));\n}\nstd::string StringMaker<long>::convert(long value) {\n    return ::Catch::Detail::stringify(static_cast<long long>(value));\n}\nstd::string StringMaker<long long>::convert(long long value) {\n    ReusableStringStream rss;\n    rss << value;\n    if (value > Detail::hexThreshold) {\n        rss << \" (0x\" << std::hex << value << ')';\n    }\n    return rss.str();\n}\n\nstd::string StringMaker<unsigned int>::convert(unsigned int value) {\n    return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));\n}\nstd::string StringMaker<unsigned long>::convert(unsigned long value) {\n    return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));\n}\nstd::string StringMaker<unsigned long long>::convert(unsigned long long value) {\n    ReusableStringStream rss;\n    rss << value;\n    if (value > Detail::hexThreshold) {\n        rss << \" (0x\" << std::hex << value << ')';\n    }\n    return rss.str();\n}\n\nstd::string StringMaker<bool>::convert(bool b) {\n    return b ? \"true\" : \"false\";\n}\n\nstd::string StringMaker<signed char>::convert(signed char value) {\n    if (value == '\\r') {\n        return \"'\\\\r'\";\n    } else if (value == '\\f') {\n        return \"'\\\\f'\";\n    } else if (value == '\\n') {\n        return \"'\\\\n'\";\n    } else if (value == '\\t') {\n        return \"'\\\\t'\";\n    } else if ('\\0' <= value && value < ' ') {\n        return ::Catch::Detail::stringify(static_cast<unsigned int>(value));\n    } else {\n        char chstr[] = \"' '\";\n        chstr[1] = value;\n        return chstr;\n    }\n}\nstd::string StringMaker<char>::convert(char c) {\n    return ::Catch::Detail::stringify(static_cast<signed char>(c));\n}\nstd::string StringMaker<unsigned char>::convert(unsigned char c) {\n    return ::Catch::Detail::stringify(static_cast<char>(c));\n}\n\nstd::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {\n    return \"nullptr\";\n}\n\nint StringMaker<float>::precision = 5;\n\nstd::string StringMaker<float>::convert(float value) {\n    return fpToString(value, precision) + 'f';\n}\n\nint StringMaker<double>::precision = 10;\n\nstd::string StringMaker<double>::convert(double value) {\n    return fpToString(value, precision);\n}\n\nstd::string ratio_string<std::atto>::symbol() { return \"a\"; }\nstd::string ratio_string<std::femto>::symbol() { return \"f\"; }\nstd::string ratio_string<std::pico>::symbol() { return \"p\"; }\nstd::string ratio_string<std::nano>::symbol() { return \"n\"; }\nstd::string ratio_string<std::micro>::symbol() { return \"u\"; }\nstd::string ratio_string<std::milli>::symbol() { return \"m\"; }\n\n} // end namespace Catch\n\n#if defined(__clang__)\n#    pragma clang diagnostic pop\n#endif\n\n// end catch_tostring.cpp\n// start catch_totals.cpp\n\nnamespace Catch {\n\n    Counts Counts::operator - ( Counts const& other ) const {\n        Counts diff;\n        diff.passed = passed - other.passed;\n        diff.failed = failed - other.failed;\n        diff.failedButOk = failedButOk - other.failedButOk;\n        return diff;\n    }\n\n    Counts& Counts::operator += ( Counts const& other ) {\n        passed += other.passed;\n        failed += other.failed;\n        failedButOk += other.failedButOk;\n        return *this;\n    }\n\n    std::size_t Counts::total() const {\n        return passed + failed + failedButOk;\n    }\n    bool Counts::allPassed() const {\n        return failed == 0 && failedButOk == 0;\n    }\n    bool Counts::allOk() const {\n        return failed == 0;\n    }\n\n    Totals Totals::operator - ( Totals const& other ) const {\n        Totals diff;\n        diff.assertions = assertions - other.assertions;\n        diff.testCases = testCases - other.testCases;\n        return diff;\n    }\n\n    Totals& Totals::operator += ( Totals const& other ) {\n        assertions += other.assertions;\n        testCases += other.testCases;\n        return *this;\n    }\n\n    Totals Totals::delta( Totals const& prevTotals ) const {\n        Totals diff = *this - prevTotals;\n        if( diff.assertions.failed > 0 )\n            ++diff.testCases.failed;\n        else if( diff.assertions.failedButOk > 0 )\n            ++diff.testCases.failedButOk;\n        else\n            ++diff.testCases.passed;\n        return diff;\n    }\n\n}\n// end catch_totals.cpp\n// start catch_uncaught_exceptions.cpp\n\n#include <exception>\n\nnamespace Catch {\n    bool uncaught_exceptions() {\n#if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)\n        return std::uncaught_exceptions() > 0;\n#else\n        return std::uncaught_exception();\n#endif\n  }\n} // end namespace Catch\n// end catch_uncaught_exceptions.cpp\n// start catch_version.cpp\n\n#include <ostream>\n\nnamespace Catch {\n\n    Version::Version\n        (   unsigned int _majorVersion,\n            unsigned int _minorVersion,\n            unsigned int _patchNumber,\n            char const * const _branchName,\n            unsigned int _buildNumber )\n    :   majorVersion( _majorVersion ),\n        minorVersion( _minorVersion ),\n        patchNumber( _patchNumber ),\n        branchName( _branchName ),\n        buildNumber( _buildNumber )\n    {}\n\n    std::ostream& operator << ( std::ostream& os, Version const& version ) {\n        os  << version.majorVersion << '.'\n            << version.minorVersion << '.'\n            << version.patchNumber;\n        // branchName is never null -> 0th char is \\0 if it is empty\n        if (version.branchName[0]) {\n            os << '-' << version.branchName\n               << '.' << version.buildNumber;\n        }\n        return os;\n    }\n\n    Version const& libraryVersion() {\n        static Version version( 2, 11, 0, \"\", 0 );\n        return version;\n    }\n\n}\n// end catch_version.cpp\n// start catch_wildcard_pattern.cpp\n\nnamespace Catch {\n\n    WildcardPattern::WildcardPattern( std::string const& pattern,\n                                      CaseSensitive::Choice caseSensitivity )\n    :   m_caseSensitivity( caseSensitivity ),\n        m_pattern( normaliseString( pattern ) )\n    {\n        if( startsWith( m_pattern, '*' ) ) {\n            m_pattern = m_pattern.substr( 1 );\n            m_wildcard = WildcardAtStart;\n        }\n        if( endsWith( m_pattern, '*' ) ) {\n            m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );\n            m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );\n        }\n    }\n\n    bool WildcardPattern::matches( std::string const& str ) const {\n        switch( m_wildcard ) {\n            case NoWildcard:\n                return m_pattern == normaliseString( str );\n            case WildcardAtStart:\n                return endsWith( normaliseString( str ), m_pattern );\n            case WildcardAtEnd:\n                return startsWith( normaliseString( str ), m_pattern );\n            case WildcardAtBothEnds:\n                return contains( normaliseString( str ), m_pattern );\n            default:\n                CATCH_INTERNAL_ERROR( \"Unknown enum\" );\n        }\n    }\n\n    std::string WildcardPattern::normaliseString( std::string const& str ) const {\n        return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );\n    }\n}\n// end catch_wildcard_pattern.cpp\n// start catch_xmlwriter.cpp\n\n#include <iomanip>\n#include <type_traits>\n\nusing uchar = unsigned char;\n\nnamespace Catch {\n\nnamespace {\n\n    size_t trailingBytes(unsigned char c) {\n        if ((c & 0xE0) == 0xC0) {\n            return 2;\n        }\n        if ((c & 0xF0) == 0xE0) {\n            return 3;\n        }\n        if ((c & 0xF8) == 0xF0) {\n            return 4;\n        }\n        CATCH_INTERNAL_ERROR(\"Invalid multibyte utf-8 start byte encountered\");\n    }\n\n    uint32_t headerValue(unsigned char c) {\n        if ((c & 0xE0) == 0xC0) {\n            return c & 0x1F;\n        }\n        if ((c & 0xF0) == 0xE0) {\n            return c & 0x0F;\n        }\n        if ((c & 0xF8) == 0xF0) {\n            return c & 0x07;\n        }\n        CATCH_INTERNAL_ERROR(\"Invalid multibyte utf-8 start byte encountered\");\n    }\n\n    void hexEscapeChar(std::ostream& os, unsigned char c) {\n        std::ios_base::fmtflags f(os.flags());\n        os << \"\\\\x\"\n            << std::uppercase << std::hex << std::setfill('0') << std::setw(2)\n            << static_cast<int>(c);\n        os.flags(f);\n    }\n\n    bool shouldNewline(XmlFormatting fmt) {\n        return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));\n    }\n\n    bool shouldIndent(XmlFormatting fmt) {\n        return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));\n    }\n\n} // anonymous namespace\n\n    XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {\n        return static_cast<XmlFormatting>(\n            static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |\n            static_cast<std::underlying_type<XmlFormatting>::type>(rhs)\n        );\n    }\n\n    XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {\n        return static_cast<XmlFormatting>(\n            static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &\n            static_cast<std::underlying_type<XmlFormatting>::type>(rhs)\n        );\n    }\n\n    XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )\n    :   m_str( str ),\n        m_forWhat( forWhat )\n    {}\n\n    void XmlEncode::encodeTo( std::ostream& os ) const {\n        // Apostrophe escaping not necessary if we always use \" to write attributes\n        // (see: http://www.w3.org/TR/xml/#syntax)\n\n        for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {\n            uchar c = m_str[idx];\n            switch (c) {\n            case '<':   os << \"&lt;\"; break;\n            case '&':   os << \"&amp;\"; break;\n\n            case '>':\n                // See: http://www.w3.org/TR/xml/#syntax\n                if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')\n                    os << \"&gt;\";\n                else\n                    os << c;\n                break;\n\n            case '\\\"':\n                if (m_forWhat == ForAttributes)\n                    os << \"&quot;\";\n                else\n                    os << c;\n                break;\n\n            default:\n                // Check for control characters and invalid utf-8\n\n                // Escape control characters in standard ascii\n                // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0\n                if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {\n                    hexEscapeChar(os, c);\n                    break;\n                }\n\n                // Plain ASCII: Write it to stream\n                if (c < 0x7F) {\n                    os << c;\n                    break;\n                }\n\n                // UTF-8 territory\n                // Check if the encoding is valid and if it is not, hex escape bytes.\n                // Important: We do not check the exact decoded values for validity, only the encoding format\n                // First check that this bytes is a valid lead byte:\n                // This means that it is not encoded as 1111 1XXX\n                // Or as 10XX XXXX\n                if (c <  0xC0 ||\n                    c >= 0xF8) {\n                    hexEscapeChar(os, c);\n                    break;\n                }\n\n                auto encBytes = trailingBytes(c);\n                // Are there enough bytes left to avoid accessing out-of-bounds memory?\n                if (idx + encBytes - 1 >= m_str.size()) {\n                    hexEscapeChar(os, c);\n                    break;\n                }\n                // The header is valid, check data\n                // The next encBytes bytes must together be a valid utf-8\n                // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)\n                bool valid = true;\n                uint32_t value = headerValue(c);\n                for (std::size_t n = 1; n < encBytes; ++n) {\n                    uchar nc = m_str[idx + n];\n                    valid &= ((nc & 0xC0) == 0x80);\n                    value = (value << 6) | (nc & 0x3F);\n                }\n\n                if (\n                    // Wrong bit pattern of following bytes\n                    (!valid) ||\n                    // Overlong encodings\n                    (value < 0x80) ||\n                    (0x80 <= value && value < 0x800   && encBytes > 2) ||\n                    (0x800 < value && value < 0x10000 && encBytes > 3) ||\n                    // Encoded value out of range\n                    (value >= 0x110000)\n                    ) {\n                    hexEscapeChar(os, c);\n                    break;\n                }\n\n                // If we got here, this is in fact a valid(ish) utf-8 sequence\n                for (std::size_t n = 0; n < encBytes; ++n) {\n                    os << m_str[idx + n];\n                }\n                idx += encBytes - 1;\n                break;\n            }\n        }\n    }\n\n    std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {\n        xmlEncode.encodeTo( os );\n        return os;\n    }\n\n    XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )\n    :   m_writer( writer ),\n        m_fmt(fmt)\n    {}\n\n    XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept\n    :   m_writer( other.m_writer ),\n        m_fmt(other.m_fmt)\n    {\n        other.m_writer = nullptr;\n        other.m_fmt = XmlFormatting::None;\n    }\n    XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {\n        if ( m_writer ) {\n            m_writer->endElement();\n        }\n        m_writer = other.m_writer;\n        other.m_writer = nullptr;\n        m_fmt = other.m_fmt;\n        other.m_fmt = XmlFormatting::None;\n        return *this;\n    }\n\n    XmlWriter::ScopedElement::~ScopedElement() {\n        if (m_writer) {\n            m_writer->endElement(m_fmt);\n        }\n    }\n\n    XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {\n        m_writer->writeText( text, fmt );\n        return *this;\n    }\n\n    XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )\n    {\n        writeDeclaration();\n    }\n\n    XmlWriter::~XmlWriter() {\n        while (!m_tags.empty()) {\n            endElement();\n        }\n        newlineIfNecessary();\n    }\n\n    XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {\n        ensureTagClosed();\n        newlineIfNecessary();\n        if (shouldIndent(fmt)) {\n            m_os << m_indent;\n            m_indent += \"  \";\n        }\n        m_os << '<' << name;\n        m_tags.push_back( name );\n        m_tagIsOpen = true;\n        applyFormatting(fmt);\n        return *this;\n    }\n\n    XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {\n        ScopedElement scoped( this, fmt );\n        startElement( name, fmt );\n        return scoped;\n    }\n\n    XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {\n        m_indent = m_indent.substr(0, m_indent.size() - 2);\n\n        if( m_tagIsOpen ) {\n            m_os << \"/>\";\n            m_tagIsOpen = false;\n        } else {\n            newlineIfNecessary();\n            if (shouldIndent(fmt)) {\n                m_os << m_indent;\n            }\n            m_os << \"</\" << m_tags.back() << \">\";\n        }\n        m_os << std::flush;\n        applyFormatting(fmt);\n        m_tags.pop_back();\n        return *this;\n    }\n\n    XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {\n        if( !name.empty() && !attribute.empty() )\n            m_os << ' ' << name << \"=\\\"\" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '\"';\n        return *this;\n    }\n\n    XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {\n        m_os << ' ' << name << \"=\\\"\" << ( attribute ? \"true\" : \"false\" ) << '\"';\n        return *this;\n    }\n\n    XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {\n        if( !text.empty() ){\n            bool tagWasOpen = m_tagIsOpen;\n            ensureTagClosed();\n            if (tagWasOpen && shouldIndent(fmt)) {\n                m_os << m_indent;\n            }\n            m_os << XmlEncode( text );\n            applyFormatting(fmt);\n        }\n        return *this;\n    }\n\n    XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {\n        ensureTagClosed();\n        if (shouldIndent(fmt)) {\n            m_os << m_indent;\n        }\n        m_os << \"<!--\" << text << \"-->\";\n        applyFormatting(fmt);\n        return *this;\n    }\n\n    void XmlWriter::writeStylesheetRef( std::string const& url ) {\n        m_os << \"<?xml-stylesheet type=\\\"text/xsl\\\" href=\\\"\" << url << \"\\\"?>\\n\";\n    }\n\n    XmlWriter& XmlWriter::writeBlankLine() {\n        ensureTagClosed();\n        m_os << '\\n';\n        return *this;\n    }\n\n    void XmlWriter::ensureTagClosed() {\n        if( m_tagIsOpen ) {\n            m_os << '>' << std::flush;\n            newlineIfNecessary();\n            m_tagIsOpen = false;\n        }\n    }\n\n    void XmlWriter::applyFormatting(XmlFormatting fmt) {\n        m_needsNewline = shouldNewline(fmt);\n    }\n\n    void XmlWriter::writeDeclaration() {\n        m_os << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\";\n    }\n\n    void XmlWriter::newlineIfNecessary() {\n        if( m_needsNewline ) {\n            m_os << std::endl;\n            m_needsNewline = false;\n        }\n    }\n}\n// end catch_xmlwriter.cpp\n// start catch_reporter_bases.cpp\n\n#include <cstring>\n#include <cfloat>\n#include <cstdio>\n#include <cassert>\n#include <memory>\n\nnamespace Catch {\n    void prepareExpandedExpression(AssertionResult& result) {\n        result.getExpandedExpression();\n    }\n\n    // Because formatting using c++ streams is stateful, drop down to C is required\n    // Alternatively we could use stringstream, but its performance is... not good.\n    std::string getFormattedDuration( double duration ) {\n        // Max exponent + 1 is required to represent the whole part\n        // + 1 for decimal point\n        // + 3 for the 3 decimal places\n        // + 1 for null terminator\n        const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;\n        char buffer[maxDoubleSize];\n\n        // Save previous errno, to prevent sprintf from overwriting it\n        ErrnoGuard guard;\n#ifdef _MSC_VER\n        sprintf_s(buffer, \"%.3f\", duration);\n#else\n        std::sprintf(buffer, \"%.3f\", duration);\n#endif\n        return std::string(buffer);\n    }\n\n    std::string serializeFilters( std::vector<std::string> const& container ) {\n        ReusableStringStream oss;\n        bool first = true;\n        for (auto&& filter : container)\n        {\n            if (!first)\n                oss << ' ';\n            else\n                first = false;\n\n            oss << filter;\n        }\n        return oss.str();\n    }\n\n    TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)\n        :StreamingReporterBase(_config) {}\n\n    std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {\n        return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };\n    }\n\n    void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}\n\n    bool TestEventListenerBase::assertionEnded(AssertionStats const &) {\n        return false;\n    }\n\n} // end namespace Catch\n// end catch_reporter_bases.cpp\n// start catch_reporter_compact.cpp\n\nnamespace {\n\n#ifdef CATCH_PLATFORM_MAC\n    const char* failedString() { return \"FAILED\"; }\n    const char* passedString() { return \"PASSED\"; }\n#else\n    const char* failedString() { return \"failed\"; }\n    const char* passedString() { return \"passed\"; }\n#endif\n\n    // Colour::LightGrey\n    Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }\n\n    std::string bothOrAll( std::size_t count ) {\n        return count == 1 ? std::string() :\n               count == 2 ? \"both \" : \"all \" ;\n    }\n\n} // anon namespace\n\nnamespace Catch {\nnamespace {\n// Colour, message variants:\n// - white: No tests ran.\n// -   red: Failed [both/all] N test cases, failed [both/all] M assertions.\n// - white: Passed [both/all] N test cases (no assertions).\n// -   red: Failed N tests cases, failed M assertions.\n// - green: Passed [both/all] N tests cases with M assertions.\nvoid printTotals(std::ostream& out, const Totals& totals) {\n    if (totals.testCases.total() == 0) {\n        out << \"No tests ran.\";\n    } else if (totals.testCases.failed == totals.testCases.total()) {\n        Colour colour(Colour::ResultError);\n        const std::string qualify_assertions_failed =\n            totals.assertions.failed == totals.assertions.total() ?\n            bothOrAll(totals.assertions.failed) : std::string();\n        out <<\n            \"Failed \" << bothOrAll(totals.testCases.failed)\n            << pluralise(totals.testCases.failed, \"test case\") << \", \"\n            \"failed \" << qualify_assertions_failed <<\n            pluralise(totals.assertions.failed, \"assertion\") << '.';\n    } else if (totals.assertions.total() == 0) {\n        out <<\n            \"Passed \" << bothOrAll(totals.testCases.total())\n            << pluralise(totals.testCases.total(), \"test case\")\n            << \" (no assertions).\";\n    } else if (totals.assertions.failed) {\n        Colour colour(Colour::ResultError);\n        out <<\n            \"Failed \" << pluralise(totals.testCases.failed, \"test case\") << \", \"\n            \"failed \" << pluralise(totals.assertions.failed, \"assertion\") << '.';\n    } else {\n        Colour colour(Colour::ResultSuccess);\n        out <<\n            \"Passed \" << bothOrAll(totals.testCases.passed)\n            << pluralise(totals.testCases.passed, \"test case\") <<\n            \" with \" << pluralise(totals.assertions.passed, \"assertion\") << '.';\n    }\n}\n\n// Implementation of CompactReporter formatting\nclass AssertionPrinter {\npublic:\n    AssertionPrinter& operator= (AssertionPrinter const&) = delete;\n    AssertionPrinter(AssertionPrinter const&) = delete;\n    AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)\n        : stream(_stream)\n        , result(_stats.assertionResult)\n        , messages(_stats.infoMessages)\n        , itMessage(_stats.infoMessages.begin())\n        , printInfoMessages(_printInfoMessages) {}\n\n    void print() {\n        printSourceInfo();\n\n        itMessage = messages.begin();\n\n        switch (result.getResultType()) {\n        case ResultWas::Ok:\n            printResultType(Colour::ResultSuccess, passedString());\n            printOriginalExpression();\n            printReconstructedExpression();\n            if (!result.hasExpression())\n                printRemainingMessages(Colour::None);\n            else\n                printRemainingMessages();\n            break;\n        case ResultWas::ExpressionFailed:\n            if (result.isOk())\n                printResultType(Colour::ResultSuccess, failedString() + std::string(\" - but was ok\"));\n            else\n                printResultType(Colour::Error, failedString());\n            printOriginalExpression();\n            printReconstructedExpression();\n            printRemainingMessages();\n            break;\n        case ResultWas::ThrewException:\n            printResultType(Colour::Error, failedString());\n            printIssue(\"unexpected exception with message:\");\n            printMessage();\n            printExpressionWas();\n            printRemainingMessages();\n            break;\n        case ResultWas::FatalErrorCondition:\n            printResultType(Colour::Error, failedString());\n            printIssue(\"fatal error condition with message:\");\n            printMessage();\n            printExpressionWas();\n            printRemainingMessages();\n            break;\n        case ResultWas::DidntThrowException:\n            printResultType(Colour::Error, failedString());\n            printIssue(\"expected exception, got none\");\n            printExpressionWas();\n            printRemainingMessages();\n            break;\n        case ResultWas::Info:\n            printResultType(Colour::None, \"info\");\n            printMessage();\n            printRemainingMessages();\n            break;\n        case ResultWas::Warning:\n            printResultType(Colour::None, \"warning\");\n            printMessage();\n            printRemainingMessages();\n            break;\n        case ResultWas::ExplicitFailure:\n            printResultType(Colour::Error, failedString());\n            printIssue(\"explicitly\");\n            printRemainingMessages(Colour::None);\n            break;\n            // These cases are here to prevent compiler warnings\n        case ResultWas::Unknown:\n        case ResultWas::FailureBit:\n        case ResultWas::Exception:\n            printResultType(Colour::Error, \"** internal error **\");\n            break;\n        }\n    }\n\nprivate:\n    void printSourceInfo() const {\n        Colour colourGuard(Colour::FileName);\n        stream << result.getSourceInfo() << ':';\n    }\n\n    void printResultType(Colour::Code colour, std::string const& passOrFail) const {\n        if (!passOrFail.empty()) {\n            {\n                Colour colourGuard(colour);\n                stream << ' ' << passOrFail;\n            }\n            stream << ':';\n        }\n    }\n\n    void printIssue(std::string const& issue) const {\n        stream << ' ' << issue;\n    }\n\n    void printExpressionWas() {\n        if (result.hasExpression()) {\n            stream << ';';\n            {\n                Colour colour(dimColour());\n                stream << \" expression was:\";\n            }\n            printOriginalExpression();\n        }\n    }\n\n    void printOriginalExpression() const {\n        if (result.hasExpression()) {\n            stream << ' ' << result.getExpression();\n        }\n    }\n\n    void printReconstructedExpression() const {\n        if (result.hasExpandedExpression()) {\n            {\n                Colour colour(dimColour());\n                stream << \" for: \";\n            }\n            stream << result.getExpandedExpression();\n        }\n    }\n\n    void printMessage() {\n        if (itMessage != messages.end()) {\n            stream << \" '\" << itMessage->message << '\\'';\n            ++itMessage;\n        }\n    }\n\n    void printRemainingMessages(Colour::Code colour = dimColour()) {\n        if (itMessage == messages.end())\n            return;\n\n        const auto itEnd = messages.cend();\n        const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));\n\n        {\n            Colour colourGuard(colour);\n            stream << \" with \" << pluralise(N, \"message\") << ':';\n        }\n\n        while (itMessage != itEnd) {\n            // If this assertion is a warning ignore any INFO messages\n            if (printInfoMessages || itMessage->type != ResultWas::Info) {\n                printMessage();\n                if (itMessage != itEnd) {\n                    Colour colourGuard(dimColour());\n                    stream << \" and\";\n                }\n                continue;\n            }\n            ++itMessage;\n        }\n    }\n\nprivate:\n    std::ostream& stream;\n    AssertionResult const& result;\n    std::vector<MessageInfo> messages;\n    std::vector<MessageInfo>::const_iterator itMessage;\n    bool printInfoMessages;\n};\n\n} // anon namespace\n\n        std::string CompactReporter::getDescription() {\n            return \"Reports test results on a single line, suitable for IDEs\";\n        }\n\n        ReporterPreferences CompactReporter::getPreferences() const {\n            return m_reporterPrefs;\n        }\n\n        void CompactReporter::noMatchingTestCases( std::string const& spec ) {\n            stream << \"No test cases matched '\" << spec << '\\'' << std::endl;\n        }\n\n        void CompactReporter::assertionStarting( AssertionInfo const& ) {}\n\n        bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {\n            AssertionResult const& result = _assertionStats.assertionResult;\n\n            bool printInfoMessages = true;\n\n            // Drop out if result was successful and we're not printing those\n            if( !m_config->includeSuccessfulResults() && result.isOk() ) {\n                if( result.getResultType() != ResultWas::Warning )\n                    return false;\n                printInfoMessages = false;\n            }\n\n            AssertionPrinter printer( stream, _assertionStats, printInfoMessages );\n            printer.print();\n\n            stream << std::endl;\n            return true;\n        }\n\n        void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {\n            if (m_config->showDurations() == ShowDurations::Always) {\n                stream << getFormattedDuration(_sectionStats.durationInSeconds) << \" s: \" << _sectionStats.sectionInfo.name << std::endl;\n            }\n        }\n\n        void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {\n            printTotals( stream, _testRunStats.totals );\n            stream << '\\n' << std::endl;\n            StreamingReporterBase::testRunEnded( _testRunStats );\n        }\n\n        CompactReporter::~CompactReporter() {}\n\n    CATCH_REGISTER_REPORTER( \"compact\", CompactReporter )\n\n} // end namespace Catch\n// end catch_reporter_compact.cpp\n// start catch_reporter_console.cpp\n\n#include <cfloat>\n#include <cstdio>\n\n#if defined(_MSC_VER)\n#pragma warning(push)\n#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch\n // Note that 4062 (not all labels are handled and default is missing) is enabled\n#endif\n\n#if defined(__clang__)\n#  pragma clang diagnostic push\n// For simplicity, benchmarking-only helpers are always enabled\n#  pragma clang diagnostic ignored \"-Wunused-function\"\n#endif\n\nnamespace Catch {\n\nnamespace {\n\n// Formatter impl for ConsoleReporter\nclass ConsoleAssertionPrinter {\npublic:\n    ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;\n    ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;\n    ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)\n        : stream(_stream),\n        stats(_stats),\n        result(_stats.assertionResult),\n        colour(Colour::None),\n        message(result.getMessage()),\n        messages(_stats.infoMessages),\n        printInfoMessages(_printInfoMessages) {\n        switch (result.getResultType()) {\n        case ResultWas::Ok:\n            colour = Colour::Success;\n            passOrFail = \"PASSED\";\n            //if( result.hasMessage() )\n            if (_stats.infoMessages.size() == 1)\n                messageLabel = \"with message\";\n            if (_stats.infoMessages.size() > 1)\n                messageLabel = \"with messages\";\n            break;\n        case ResultWas::ExpressionFailed:\n            if (result.isOk()) {\n                colour = Colour::Success;\n                passOrFail = \"FAILED - but was ok\";\n            } else {\n                colour = Colour::Error;\n                passOrFail = \"FAILED\";\n            }\n            if (_stats.infoMessages.size() == 1)\n                messageLabel = \"with message\";\n            if (_stats.infoMessages.size() > 1)\n                messageLabel = \"with messages\";\n            break;\n        case ResultWas::ThrewException:\n            colour = Colour::Error;\n            passOrFail = \"FAILED\";\n            messageLabel = \"due to unexpected exception with \";\n            if (_stats.infoMessages.size() == 1)\n                messageLabel += \"message\";\n            if (_stats.infoMessages.size() > 1)\n                messageLabel += \"messages\";\n            break;\n        case ResultWas::FatalErrorCondition:\n            colour = Colour::Error;\n            passOrFail = \"FAILED\";\n            messageLabel = \"due to a fatal error condition\";\n            break;\n        case ResultWas::DidntThrowException:\n            colour = Colour::Error;\n            passOrFail = \"FAILED\";\n            messageLabel = \"because no exception was thrown where one was expected\";\n            break;\n        case ResultWas::Info:\n            messageLabel = \"info\";\n            break;\n        case ResultWas::Warning:\n            messageLabel = \"warning\";\n            break;\n        case ResultWas::ExplicitFailure:\n            passOrFail = \"FAILED\";\n            colour = Colour::Error;\n            if (_stats.infoMessages.size() == 1)\n                messageLabel = \"explicitly with message\";\n            if (_stats.infoMessages.size() > 1)\n                messageLabel = \"explicitly with messages\";\n            break;\n            // These cases are here to prevent compiler warnings\n        case ResultWas::Unknown:\n        case ResultWas::FailureBit:\n        case ResultWas::Exception:\n            passOrFail = \"** internal error **\";\n            colour = Colour::Error;\n            break;\n        }\n    }\n\n    void print() const {\n        printSourceInfo();\n        if (stats.totals.assertions.total() > 0) {\n            printResultType();\n            printOriginalExpression();\n            printReconstructedExpression();\n        } else {\n            stream << '\\n';\n        }\n        printMessage();\n    }\n\nprivate:\n    void printResultType() const {\n        if (!passOrFail.empty()) {\n            Colour colourGuard(colour);\n            stream << passOrFail << \":\\n\";\n        }\n    }\n    void printOriginalExpression() const {\n        if (result.hasExpression()) {\n            Colour colourGuard(Colour::OriginalExpression);\n            stream << \"  \";\n            stream << result.getExpressionInMacro();\n            stream << '\\n';\n        }\n    }\n    void printReconstructedExpression() const {\n        if (result.hasExpandedExpression()) {\n            stream << \"with expansion:\\n\";\n            Colour colourGuard(Colour::ReconstructedExpression);\n            stream << Column(result.getExpandedExpression()).indent(2) << '\\n';\n        }\n    }\n    void printMessage() const {\n        if (!messageLabel.empty())\n            stream << messageLabel << ':' << '\\n';\n        for (auto const& msg : messages) {\n            // If this assertion is a warning ignore any INFO messages\n            if (printInfoMessages || msg.type != ResultWas::Info)\n                stream << Column(msg.message).indent(2) << '\\n';\n        }\n    }\n    void printSourceInfo() const {\n        Colour colourGuard(Colour::FileName);\n        stream << result.getSourceInfo() << \": \";\n    }\n\n    std::ostream& stream;\n    AssertionStats const& stats;\n    AssertionResult const& result;\n    Colour::Code colour;\n    std::string passOrFail;\n    std::string messageLabel;\n    std::string message;\n    std::vector<MessageInfo> messages;\n    bool printInfoMessages;\n};\n\nstd::size_t makeRatio(std::size_t number, std::size_t total) {\n    std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;\n    return (ratio == 0 && number > 0) ? 1 : ratio;\n}\n\nstd::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {\n    if (i > j && i > k)\n        return i;\n    else if (j > k)\n        return j;\n    else\n        return k;\n}\n\nstruct ColumnInfo {\n    enum Justification { Left, Right };\n    std::string name;\n    int width;\n    Justification justification;\n};\nstruct ColumnBreak {};\nstruct RowBreak {};\n\nclass Duration {\n    enum class Unit {\n        Auto,\n        Nanoseconds,\n        Microseconds,\n        Milliseconds,\n        Seconds,\n        Minutes\n    };\n    static const uint64_t s_nanosecondsInAMicrosecond = 1000;\n    static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;\n    static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;\n    static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;\n\n    uint64_t m_inNanoseconds;\n    Unit m_units;\n\npublic:\n\texplicit Duration(double inNanoseconds, Unit units = Unit::Auto)\n        : Duration(static_cast<uint64_t>(inNanoseconds), units) {\n    }\n\n    explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)\n        : m_inNanoseconds(inNanoseconds),\n        m_units(units) {\n        if (m_units == Unit::Auto) {\n            if (m_inNanoseconds < s_nanosecondsInAMicrosecond)\n                m_units = Unit::Nanoseconds;\n            else if (m_inNanoseconds < s_nanosecondsInAMillisecond)\n                m_units = Unit::Microseconds;\n            else if (m_inNanoseconds < s_nanosecondsInASecond)\n                m_units = Unit::Milliseconds;\n            else if (m_inNanoseconds < s_nanosecondsInAMinute)\n                m_units = Unit::Seconds;\n            else\n                m_units = Unit::Minutes;\n        }\n\n    }\n\n    auto value() const -> double {\n        switch (m_units) {\n        case Unit::Microseconds:\n            return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);\n        case Unit::Milliseconds:\n            return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);\n        case Unit::Seconds:\n            return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);\n        case Unit::Minutes:\n            return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);\n        default:\n            return static_cast<double>(m_inNanoseconds);\n        }\n    }\n    auto unitsAsString() const -> std::string {\n        switch (m_units) {\n        case Unit::Nanoseconds:\n            return \"ns\";\n        case Unit::Microseconds:\n            return \"us\";\n        case Unit::Milliseconds:\n            return \"ms\";\n        case Unit::Seconds:\n            return \"s\";\n        case Unit::Minutes:\n            return \"m\";\n        default:\n            return \"** internal error **\";\n        }\n\n    }\n    friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {\n        return os << duration.value() << ' ' << duration.unitsAsString();\n    }\n};\n} // end anon namespace\n\nclass TablePrinter {\n    std::ostream& m_os;\n    std::vector<ColumnInfo> m_columnInfos;\n    std::ostringstream m_oss;\n    int m_currentColumn = -1;\n    bool m_isOpen = false;\n\npublic:\n    TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )\n    :   m_os( os ),\n        m_columnInfos( std::move( columnInfos ) ) {}\n\n    auto columnInfos() const -> std::vector<ColumnInfo> const& {\n        return m_columnInfos;\n    }\n\n    void open() {\n        if (!m_isOpen) {\n            m_isOpen = true;\n            *this << RowBreak();\n\n\t\t\tColumns headerCols;\n\t\t\tSpacer spacer(2);\n\t\t\tfor (auto const& info : m_columnInfos) {\n\t\t\t\theaderCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));\n\t\t\t\theaderCols += spacer;\n\t\t\t}\n\t\t\tm_os << headerCols << '\\n';\n\n            m_os << Catch::getLineOfChars<'-'>() << '\\n';\n        }\n    }\n    void close() {\n        if (m_isOpen) {\n            *this << RowBreak();\n            m_os << std::endl;\n            m_isOpen = false;\n        }\n    }\n\n    template<typename T>\n    friend TablePrinter& operator << (TablePrinter& tp, T const& value) {\n        tp.m_oss << value;\n        return tp;\n    }\n\n    friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {\n        auto colStr = tp.m_oss.str();\n        const auto strSize = colStr.size();\n        tp.m_oss.str(\"\");\n        tp.open();\n        if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {\n            tp.m_currentColumn = -1;\n            tp.m_os << '\\n';\n        }\n        tp.m_currentColumn++;\n\n        auto colInfo = tp.m_columnInfos[tp.m_currentColumn];\n        auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))\n            ? std::string(colInfo.width - (strSize + 1), ' ')\n            : std::string();\n        if (colInfo.justification == ColumnInfo::Left)\n            tp.m_os << colStr << padding << ' ';\n        else\n            tp.m_os << padding << colStr << ' ';\n        return tp;\n    }\n\n    friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {\n        if (tp.m_currentColumn > 0) {\n            tp.m_os << '\\n';\n            tp.m_currentColumn = -1;\n        }\n        return tp;\n    }\n};\n\nConsoleReporter::ConsoleReporter(ReporterConfig const& config)\n    : StreamingReporterBase(config),\n    m_tablePrinter(new TablePrinter(config.stream(),\n        [&config]() -> std::vector<ColumnInfo> {\n        if (config.fullConfig()->benchmarkNoAnalysis())\n        {\n            return{\n                { \"benchmark name\", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },\n                { \"     samples\", 14, ColumnInfo::Right },\n                { \"  iterations\", 14, ColumnInfo::Right },\n                { \"        mean\", 14, ColumnInfo::Right }\n            };\n        }\n        else\n        {\n            return{\n                { \"benchmark name\", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },\n                { \"samples      mean       std dev\", 14, ColumnInfo::Right },\n                { \"iterations   low mean   low std dev\", 14, ColumnInfo::Right },\n                { \"estimated    high mean  high std dev\", 14, ColumnInfo::Right }\n            };\n        }\n    }())) {}\nConsoleReporter::~ConsoleReporter() = default;\n\nstd::string ConsoleReporter::getDescription() {\n    return \"Reports test results as plain lines of text\";\n}\n\nvoid ConsoleReporter::noMatchingTestCases(std::string const& spec) {\n    stream << \"No test cases matched '\" << spec << '\\'' << std::endl;\n}\n\nvoid ConsoleReporter::reportInvalidArguments(std::string const&arg){\n    stream << \"Invalid Filter: \" << arg << std::endl;\n}\n\nvoid ConsoleReporter::assertionStarting(AssertionInfo const&) {}\n\nbool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {\n    AssertionResult const& result = _assertionStats.assertionResult;\n\n    bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();\n\n    // Drop out if result was successful but we're not printing them.\n    if (!includeResults && result.getResultType() != ResultWas::Warning)\n        return false;\n\n    lazyPrint();\n\n    ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);\n    printer.print();\n    stream << std::endl;\n    return true;\n}\n\nvoid ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {\n    m_tablePrinter->close();\n    m_headerPrinted = false;\n    StreamingReporterBase::sectionStarting(_sectionInfo);\n}\nvoid ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {\n    m_tablePrinter->close();\n    if (_sectionStats.missingAssertions) {\n        lazyPrint();\n        Colour colour(Colour::ResultError);\n        if (m_sectionStack.size() > 1)\n            stream << \"\\nNo assertions in section\";\n        else\n            stream << \"\\nNo assertions in test case\";\n        stream << \" '\" << _sectionStats.sectionInfo.name << \"'\\n\" << std::endl;\n    }\n    if (m_config->showDurations() == ShowDurations::Always) {\n        stream << getFormattedDuration(_sectionStats.durationInSeconds) << \" s: \" << _sectionStats.sectionInfo.name << std::endl;\n    }\n    if (m_headerPrinted) {\n        m_headerPrinted = false;\n    }\n    StreamingReporterBase::sectionEnded(_sectionStats);\n}\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\nvoid ConsoleReporter::benchmarkPreparing(std::string const& name) {\n\tlazyPrintWithoutClosingBenchmarkTable();\n\n\tauto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));\n\n\tbool firstLine = true;\n\tfor (auto line : nameCol) {\n\t\tif (!firstLine)\n\t\t\t(*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();\n\t\telse\n\t\t\tfirstLine = false;\n\n\t\t(*m_tablePrinter) << line << ColumnBreak();\n\t}\n}\n\nvoid ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {\n    (*m_tablePrinter) << info.samples << ColumnBreak()\n        << info.iterations << ColumnBreak();\n    if (!m_config->benchmarkNoAnalysis())\n        (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();\n}\nvoid ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {\n    if (m_config->benchmarkNoAnalysis())\n    {\n        (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();\n    }\n    else\n    {\n        (*m_tablePrinter) << ColumnBreak()\n            << Duration(stats.mean.point.count()) << ColumnBreak()\n            << Duration(stats.mean.lower_bound.count()) << ColumnBreak()\n            << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()\n            << Duration(stats.standardDeviation.point.count()) << ColumnBreak()\n            << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()\n            << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();\n    }\n}\n\nvoid ConsoleReporter::benchmarkFailed(std::string const& error) {\n\tColour colour(Colour::Red);\n    (*m_tablePrinter)\n        << \"Benchmark failed (\" << error << ')'\n        << ColumnBreak() << RowBreak();\n}\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\nvoid ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {\n    m_tablePrinter->close();\n    StreamingReporterBase::testCaseEnded(_testCaseStats);\n    m_headerPrinted = false;\n}\nvoid ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {\n    if (currentGroupInfo.used) {\n        printSummaryDivider();\n        stream << \"Summary for group '\" << _testGroupStats.groupInfo.name << \"':\\n\";\n        printTotals(_testGroupStats.totals);\n        stream << '\\n' << std::endl;\n    }\n    StreamingReporterBase::testGroupEnded(_testGroupStats);\n}\nvoid ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {\n    printTotalsDivider(_testRunStats.totals);\n    printTotals(_testRunStats.totals);\n    stream << std::endl;\n    StreamingReporterBase::testRunEnded(_testRunStats);\n}\nvoid ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {\n    StreamingReporterBase::testRunStarting(_testInfo);\n    printTestFilters();\n}\n\nvoid ConsoleReporter::lazyPrint() {\n\n    m_tablePrinter->close();\n    lazyPrintWithoutClosingBenchmarkTable();\n}\n\nvoid ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {\n\n    if (!currentTestRunInfo.used)\n        lazyPrintRunInfo();\n    if (!currentGroupInfo.used)\n        lazyPrintGroupInfo();\n\n    if (!m_headerPrinted) {\n        printTestCaseAndSectionHeader();\n        m_headerPrinted = true;\n    }\n}\nvoid ConsoleReporter::lazyPrintRunInfo() {\n    stream << '\\n' << getLineOfChars<'~'>() << '\\n';\n    Colour colour(Colour::SecondaryText);\n    stream << currentTestRunInfo->name\n        << \" is a Catch v\" << libraryVersion() << \" host application.\\n\"\n        << \"Run with -? for options\\n\\n\";\n\n    if (m_config->rngSeed() != 0)\n        stream << \"Randomness seeded to: \" << m_config->rngSeed() << \"\\n\\n\";\n\n    currentTestRunInfo.used = true;\n}\nvoid ConsoleReporter::lazyPrintGroupInfo() {\n    if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {\n        printClosedHeader(\"Group: \" + currentGroupInfo->name);\n        currentGroupInfo.used = true;\n    }\n}\nvoid ConsoleReporter::printTestCaseAndSectionHeader() {\n    assert(!m_sectionStack.empty());\n    printOpenHeader(currentTestCaseInfo->name);\n\n    if (m_sectionStack.size() > 1) {\n        Colour colourGuard(Colour::Headers);\n\n        auto\n            it = m_sectionStack.begin() + 1, // Skip first section (test case)\n            itEnd = m_sectionStack.end();\n        for (; it != itEnd; ++it)\n            printHeaderString(it->name, 2);\n    }\n\n    SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;\n\n    stream << getLineOfChars<'-'>() << '\\n';\n    Colour colourGuard(Colour::FileName);\n    stream << lineInfo << '\\n';\n    stream << getLineOfChars<'.'>() << '\\n' << std::endl;\n}\n\nvoid ConsoleReporter::printClosedHeader(std::string const& _name) {\n    printOpenHeader(_name);\n    stream << getLineOfChars<'.'>() << '\\n';\n}\nvoid ConsoleReporter::printOpenHeader(std::string const& _name) {\n    stream << getLineOfChars<'-'>() << '\\n';\n    {\n        Colour colourGuard(Colour::Headers);\n        printHeaderString(_name);\n    }\n}\n\n// if string has a : in first line will set indent to follow it on\n// subsequent lines\nvoid ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {\n    std::size_t i = _string.find(\": \");\n    if (i != std::string::npos)\n        i += 2;\n    else\n        i = 0;\n    stream << Column(_string).indent(indent + i).initialIndent(indent) << '\\n';\n}\n\nstruct SummaryColumn {\n\n    SummaryColumn( std::string _label, Colour::Code _colour )\n    :   label( std::move( _label ) ),\n        colour( _colour ) {}\n    SummaryColumn addRow( std::size_t count ) {\n        ReusableStringStream rss;\n        rss << count;\n        std::string row = rss.str();\n        for (auto& oldRow : rows) {\n            while (oldRow.size() < row.size())\n                oldRow = ' ' + oldRow;\n            while (oldRow.size() > row.size())\n                row = ' ' + row;\n        }\n        rows.push_back(row);\n        return *this;\n    }\n\n    std::string label;\n    Colour::Code colour;\n    std::vector<std::string> rows;\n\n};\n\nvoid ConsoleReporter::printTotals( Totals const& totals ) {\n    if (totals.testCases.total() == 0) {\n        stream << Colour(Colour::Warning) << \"No tests ran\\n\";\n    } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {\n        stream << Colour(Colour::ResultSuccess) << \"All tests passed\";\n        stream << \" (\"\n            << pluralise(totals.assertions.passed, \"assertion\") << \" in \"\n            << pluralise(totals.testCases.passed, \"test case\") << ')'\n            << '\\n';\n    } else {\n\n        std::vector<SummaryColumn> columns;\n        columns.push_back(SummaryColumn(\"\", Colour::None)\n                          .addRow(totals.testCases.total())\n                          .addRow(totals.assertions.total()));\n        columns.push_back(SummaryColumn(\"passed\", Colour::Success)\n                          .addRow(totals.testCases.passed)\n                          .addRow(totals.assertions.passed));\n        columns.push_back(SummaryColumn(\"failed\", Colour::ResultError)\n                          .addRow(totals.testCases.failed)\n                          .addRow(totals.assertions.failed));\n        columns.push_back(SummaryColumn(\"failed as expected\", Colour::ResultExpectedFailure)\n                          .addRow(totals.testCases.failedButOk)\n                          .addRow(totals.assertions.failedButOk));\n\n        printSummaryRow(\"test cases\", columns, 0);\n        printSummaryRow(\"assertions\", columns, 1);\n    }\n}\nvoid ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {\n    for (auto col : cols) {\n        std::string value = col.rows[row];\n        if (col.label.empty()) {\n            stream << label << \": \";\n            if (value != \"0\")\n                stream << value;\n            else\n                stream << Colour(Colour::Warning) << \"- none -\";\n        } else if (value != \"0\") {\n            stream << Colour(Colour::LightGrey) << \" | \";\n            stream << Colour(col.colour)\n                << value << ' ' << col.label;\n        }\n    }\n    stream << '\\n';\n}\n\nvoid ConsoleReporter::printTotalsDivider(Totals const& totals) {\n    if (totals.testCases.total() > 0) {\n        std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());\n        std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());\n        std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());\n        while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)\n            findMax(failedRatio, failedButOkRatio, passedRatio)++;\n        while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)\n            findMax(failedRatio, failedButOkRatio, passedRatio)--;\n\n        stream << Colour(Colour::Error) << std::string(failedRatio, '=');\n        stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');\n        if (totals.testCases.allPassed())\n            stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');\n        else\n            stream << Colour(Colour::Success) << std::string(passedRatio, '=');\n    } else {\n        stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');\n    }\n    stream << '\\n';\n}\nvoid ConsoleReporter::printSummaryDivider() {\n    stream << getLineOfChars<'-'>() << '\\n';\n}\n\nvoid ConsoleReporter::printTestFilters() {\n    if (m_config->testSpec().hasFilters())\n        stream << Colour(Colour::BrightYellow) << \"Filters: \" << serializeFilters( m_config->getTestsOrTags() ) << '\\n';\n}\n\nCATCH_REGISTER_REPORTER(\"console\", ConsoleReporter)\n\n} // end namespace Catch\n\n#if defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n\n#if defined(__clang__)\n#  pragma clang diagnostic pop\n#endif\n// end catch_reporter_console.cpp\n// start catch_reporter_junit.cpp\n\n#include <cassert>\n#include <sstream>\n#include <ctime>\n#include <algorithm>\n\nnamespace Catch {\n\n    namespace {\n        std::string getCurrentTimestamp() {\n            // Beware, this is not reentrant because of backward compatibility issues\n            // Also, UTC only, again because of backward compatibility (%z is C++11)\n            time_t rawtime;\n            std::time(&rawtime);\n            auto const timeStampSize = sizeof(\"2017-01-16T17:06:45Z\");\n\n#ifdef _MSC_VER\n            std::tm timeInfo = {};\n            gmtime_s(&timeInfo, &rawtime);\n#else\n            std::tm* timeInfo;\n            timeInfo = std::gmtime(&rawtime);\n#endif\n\n            char timeStamp[timeStampSize];\n            const char * const fmt = \"%Y-%m-%dT%H:%M:%SZ\";\n\n#ifdef _MSC_VER\n            std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);\n#else\n            std::strftime(timeStamp, timeStampSize, fmt, timeInfo);\n#endif\n            return std::string(timeStamp);\n        }\n\n        std::string fileNameTag(const std::vector<std::string> &tags) {\n            auto it = std::find_if(begin(tags),\n                                   end(tags),\n                                   [] (std::string const& tag) {return tag.front() == '#'; });\n            if (it != tags.end())\n                return it->substr(1);\n            return std::string();\n        }\n    } // anonymous namespace\n\n    JunitReporter::JunitReporter( ReporterConfig const& _config )\n        :   CumulativeReporterBase( _config ),\n            xml( _config.stream() )\n        {\n            m_reporterPrefs.shouldRedirectStdOut = true;\n            m_reporterPrefs.shouldReportAllAssertions = true;\n        }\n\n    JunitReporter::~JunitReporter() {}\n\n    std::string JunitReporter::getDescription() {\n        return \"Reports test results in an XML format that looks like Ant's junitreport target\";\n    }\n\n    void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}\n\n    void JunitReporter::testRunStarting( TestRunInfo const& runInfo )  {\n        CumulativeReporterBase::testRunStarting( runInfo );\n        xml.startElement( \"testsuites\" );\n    }\n\n    void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {\n        suiteTimer.start();\n        stdOutForSuite.clear();\n        stdErrForSuite.clear();\n        unexpectedExceptions = 0;\n        CumulativeReporterBase::testGroupStarting( groupInfo );\n    }\n\n    void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {\n        m_okToFail = testCaseInfo.okToFail();\n    }\n\n    bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {\n        if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )\n            unexpectedExceptions++;\n        return CumulativeReporterBase::assertionEnded( assertionStats );\n    }\n\n    void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {\n        stdOutForSuite += testCaseStats.stdOut;\n        stdErrForSuite += testCaseStats.stdErr;\n        CumulativeReporterBase::testCaseEnded( testCaseStats );\n    }\n\n    void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {\n        double suiteTime = suiteTimer.getElapsedSeconds();\n        CumulativeReporterBase::testGroupEnded( testGroupStats );\n        writeGroup( *m_testGroups.back(), suiteTime );\n    }\n\n    void JunitReporter::testRunEndedCumulative() {\n        xml.endElement();\n    }\n\n    void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {\n        XmlWriter::ScopedElement e = xml.scopedElement( \"testsuite\" );\n\n        TestGroupStats const& stats = groupNode.value;\n        xml.writeAttribute( \"name\", stats.groupInfo.name );\n        xml.writeAttribute( \"errors\", unexpectedExceptions );\n        xml.writeAttribute( \"failures\", stats.totals.assertions.failed-unexpectedExceptions );\n        xml.writeAttribute( \"tests\", stats.totals.assertions.total() );\n        xml.writeAttribute( \"hostname\", \"tbd\" ); // !TBD\n        if( m_config->showDurations() == ShowDurations::Never )\n            xml.writeAttribute( \"time\", \"\" );\n        else\n            xml.writeAttribute( \"time\", suiteTime );\n        xml.writeAttribute( \"timestamp\", getCurrentTimestamp() );\n\n        // Write properties if there are any\n        if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {\n            auto properties = xml.scopedElement(\"properties\");\n            if (m_config->hasTestFilters()) {\n                xml.scopedElement(\"property\")\n                    .writeAttribute(\"name\", \"filters\")\n                    .writeAttribute(\"value\", serializeFilters(m_config->getTestsOrTags()));\n            }\n            if (m_config->rngSeed() != 0) {\n                xml.scopedElement(\"property\")\n                    .writeAttribute(\"name\", \"random-seed\")\n                    .writeAttribute(\"value\", m_config->rngSeed());\n            }\n        }\n\n        // Write test cases\n        for( auto const& child : groupNode.children )\n            writeTestCase( *child );\n\n        xml.scopedElement( \"system-out\" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );\n        xml.scopedElement( \"system-err\" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );\n    }\n\n    void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {\n        TestCaseStats const& stats = testCaseNode.value;\n\n        // All test cases have exactly one section - which represents the\n        // test case itself. That section may have 0-n nested sections\n        assert( testCaseNode.children.size() == 1 );\n        SectionNode const& rootSection = *testCaseNode.children.front();\n\n        std::string className = stats.testInfo.className;\n\n        if( className.empty() ) {\n            className = fileNameTag(stats.testInfo.tags);\n            if ( className.empty() )\n                className = \"global\";\n        }\n\n        if ( !m_config->name().empty() )\n            className = m_config->name() + \".\" + className;\n\n        writeSection( className, \"\", rootSection );\n    }\n\n    void JunitReporter::writeSection(  std::string const& className,\n                        std::string const& rootName,\n                        SectionNode const& sectionNode ) {\n        std::string name = trim( sectionNode.stats.sectionInfo.name );\n        if( !rootName.empty() )\n            name = rootName + '/' + name;\n\n        if( !sectionNode.assertions.empty() ||\n            !sectionNode.stdOut.empty() ||\n            !sectionNode.stdErr.empty() ) {\n            XmlWriter::ScopedElement e = xml.scopedElement( \"testcase\" );\n            if( className.empty() ) {\n                xml.writeAttribute( \"classname\", name );\n                xml.writeAttribute( \"name\", \"root\" );\n            }\n            else {\n                xml.writeAttribute( \"classname\", className );\n                xml.writeAttribute( \"name\", name );\n            }\n            xml.writeAttribute( \"time\", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );\n\n            writeAssertions( sectionNode );\n\n            if( !sectionNode.stdOut.empty() )\n                xml.scopedElement( \"system-out\" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );\n            if( !sectionNode.stdErr.empty() )\n                xml.scopedElement( \"system-err\" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );\n        }\n        for( auto const& childNode : sectionNode.childSections )\n            if( className.empty() )\n                writeSection( name, \"\", *childNode );\n            else\n                writeSection( className, name, *childNode );\n    }\n\n    void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {\n        for( auto const& assertion : sectionNode.assertions )\n            writeAssertion( assertion );\n    }\n\n    void JunitReporter::writeAssertion( AssertionStats const& stats ) {\n        AssertionResult const& result = stats.assertionResult;\n        if( !result.isOk() ) {\n            std::string elementName;\n            switch( result.getResultType() ) {\n                case ResultWas::ThrewException:\n                case ResultWas::FatalErrorCondition:\n                    elementName = \"error\";\n                    break;\n                case ResultWas::ExplicitFailure:\n                    elementName = \"failure\";\n                    break;\n                case ResultWas::ExpressionFailed:\n                    elementName = \"failure\";\n                    break;\n                case ResultWas::DidntThrowException:\n                    elementName = \"failure\";\n                    break;\n\n                // We should never see these here:\n                case ResultWas::Info:\n                case ResultWas::Warning:\n                case ResultWas::Ok:\n                case ResultWas::Unknown:\n                case ResultWas::FailureBit:\n                case ResultWas::Exception:\n                    elementName = \"internalError\";\n                    break;\n            }\n\n            XmlWriter::ScopedElement e = xml.scopedElement( elementName );\n\n            xml.writeAttribute( \"message\", result.getExpression() );\n            xml.writeAttribute( \"type\", result.getTestMacroName() );\n\n            ReusableStringStream rss;\n            if (stats.totals.assertions.total() > 0) {\n                rss << \"FAILED\" << \":\\n\";\n                if (result.hasExpression()) {\n                    rss << \"  \";\n                    rss << result.getExpressionInMacro();\n                    rss << '\\n';\n                }\n                if (result.hasExpandedExpression()) {\n                    rss << \"with expansion:\\n\";\n                    rss << Column(result.getExpandedExpression()).indent(2) << '\\n';\n                }\n            } else {\n                rss << '\\n';\n            }\n\n            if( !result.getMessage().empty() )\n                rss << result.getMessage() << '\\n';\n            for( auto const& msg : stats.infoMessages )\n                if( msg.type == ResultWas::Info )\n                    rss << msg.message << '\\n';\n\n            rss << \"at \" << result.getSourceInfo();\n            xml.writeText( rss.str(), XmlFormatting::Newline );\n        }\n    }\n\n    CATCH_REGISTER_REPORTER( \"junit\", JunitReporter )\n\n} // end namespace Catch\n// end catch_reporter_junit.cpp\n// start catch_reporter_listening.cpp\n\n#include <cassert>\n\nnamespace Catch {\n\n    ListeningReporter::ListeningReporter() {\n        // We will assume that listeners will always want all assertions\n        m_preferences.shouldReportAllAssertions = true;\n    }\n\n    void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {\n        m_listeners.push_back( std::move( listener ) );\n    }\n\n    void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {\n        assert(!m_reporter && \"Listening reporter can wrap only 1 real reporter\");\n        m_reporter = std::move( reporter );\n        m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;\n    }\n\n    ReporterPreferences ListeningReporter::getPreferences() const {\n        return m_preferences;\n    }\n\n    std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {\n        return std::set<Verbosity>{ };\n    }\n\n    void ListeningReporter::noMatchingTestCases( std::string const& spec ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->noMatchingTestCases( spec );\n        }\n        m_reporter->noMatchingTestCases( spec );\n    }\n\n    void ListeningReporter::reportInvalidArguments(std::string const&arg){\n        for ( auto const& listener : m_listeners ) {\n            listener->reportInvalidArguments( arg );\n        }\n        m_reporter->reportInvalidArguments( arg );\n    }\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n    void ListeningReporter::benchmarkPreparing( std::string const& name ) {\n\t\tfor (auto const& listener : m_listeners) {\n\t\t\tlistener->benchmarkPreparing(name);\n\t\t}\n\t\tm_reporter->benchmarkPreparing(name);\n\t}\n    void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->benchmarkStarting( benchmarkInfo );\n        }\n        m_reporter->benchmarkStarting( benchmarkInfo );\n    }\n    void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->benchmarkEnded( benchmarkStats );\n        }\n        m_reporter->benchmarkEnded( benchmarkStats );\n    }\n\n\tvoid ListeningReporter::benchmarkFailed( std::string const& error ) {\n\t\tfor (auto const& listener : m_listeners) {\n\t\t\tlistener->benchmarkFailed(error);\n\t\t}\n\t\tm_reporter->benchmarkFailed(error);\n\t}\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n    void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->testRunStarting( testRunInfo );\n        }\n        m_reporter->testRunStarting( testRunInfo );\n    }\n\n    void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->testGroupStarting( groupInfo );\n        }\n        m_reporter->testGroupStarting( groupInfo );\n    }\n\n    void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->testCaseStarting( testInfo );\n        }\n        m_reporter->testCaseStarting( testInfo );\n    }\n\n    void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->sectionStarting( sectionInfo );\n        }\n        m_reporter->sectionStarting( sectionInfo );\n    }\n\n    void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->assertionStarting( assertionInfo );\n        }\n        m_reporter->assertionStarting( assertionInfo );\n    }\n\n    // The return value indicates if the messages buffer should be cleared:\n    bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {\n        for( auto const& listener : m_listeners ) {\n            static_cast<void>( listener->assertionEnded( assertionStats ) );\n        }\n        return m_reporter->assertionEnded( assertionStats );\n    }\n\n    void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->sectionEnded( sectionStats );\n        }\n        m_reporter->sectionEnded( sectionStats );\n    }\n\n    void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->testCaseEnded( testCaseStats );\n        }\n        m_reporter->testCaseEnded( testCaseStats );\n    }\n\n    void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->testGroupEnded( testGroupStats );\n        }\n        m_reporter->testGroupEnded( testGroupStats );\n    }\n\n    void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->testRunEnded( testRunStats );\n        }\n        m_reporter->testRunEnded( testRunStats );\n    }\n\n    void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {\n        for ( auto const& listener : m_listeners ) {\n            listener->skipTest( testInfo );\n        }\n        m_reporter->skipTest( testInfo );\n    }\n\n    bool ListeningReporter::isMulti() const {\n        return true;\n    }\n\n} // end namespace Catch\n// end catch_reporter_listening.cpp\n// start catch_reporter_xml.cpp\n\n#if defined(_MSC_VER)\n#pragma warning(push)\n#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch\n                              // Note that 4062 (not all labels are handled\n                              // and default is missing) is enabled\n#endif\n\nnamespace Catch {\n    XmlReporter::XmlReporter( ReporterConfig const& _config )\n    :   StreamingReporterBase( _config ),\n        m_xml(_config.stream())\n    {\n        m_reporterPrefs.shouldRedirectStdOut = true;\n        m_reporterPrefs.shouldReportAllAssertions = true;\n    }\n\n    XmlReporter::~XmlReporter() = default;\n\n    std::string XmlReporter::getDescription() {\n        return \"Reports test results as an XML document\";\n    }\n\n    std::string XmlReporter::getStylesheetRef() const {\n        return std::string();\n    }\n\n    void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {\n        m_xml\n            .writeAttribute( \"filename\", sourceInfo.file )\n            .writeAttribute( \"line\", sourceInfo.line );\n    }\n\n    void XmlReporter::noMatchingTestCases( std::string const& s ) {\n        StreamingReporterBase::noMatchingTestCases( s );\n    }\n\n    void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {\n        StreamingReporterBase::testRunStarting( testInfo );\n        std::string stylesheetRef = getStylesheetRef();\n        if( !stylesheetRef.empty() )\n            m_xml.writeStylesheetRef( stylesheetRef );\n        m_xml.startElement( \"Catch\" );\n        if( !m_config->name().empty() )\n            m_xml.writeAttribute( \"name\", m_config->name() );\n        if (m_config->testSpec().hasFilters())\n            m_xml.writeAttribute( \"filters\", serializeFilters( m_config->getTestsOrTags() ) );\n        if( m_config->rngSeed() != 0 )\n            m_xml.scopedElement( \"Randomness\" )\n                .writeAttribute( \"seed\", m_config->rngSeed() );\n    }\n\n    void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {\n        StreamingReporterBase::testGroupStarting( groupInfo );\n        m_xml.startElement( \"Group\" )\n            .writeAttribute( \"name\", groupInfo.name );\n    }\n\n    void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {\n        StreamingReporterBase::testCaseStarting(testInfo);\n        m_xml.startElement( \"TestCase\" )\n            .writeAttribute( \"name\", trim( testInfo.name ) )\n            .writeAttribute( \"description\", testInfo.description )\n            .writeAttribute( \"tags\", testInfo.tagsAsString() );\n\n        writeSourceInfo( testInfo.lineInfo );\n\n        if ( m_config->showDurations() == ShowDurations::Always )\n            m_testCaseTimer.start();\n        m_xml.ensureTagClosed();\n    }\n\n    void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {\n        StreamingReporterBase::sectionStarting( sectionInfo );\n        if( m_sectionDepth++ > 0 ) {\n            m_xml.startElement( \"Section\" )\n                .writeAttribute( \"name\", trim( sectionInfo.name ) );\n            writeSourceInfo( sectionInfo.lineInfo );\n            m_xml.ensureTagClosed();\n        }\n    }\n\n    void XmlReporter::assertionStarting( AssertionInfo const& ) { }\n\n    bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {\n\n        AssertionResult const& result = assertionStats.assertionResult;\n\n        bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();\n\n        if( includeResults || result.getResultType() == ResultWas::Warning ) {\n            // Print any info messages in <Info> tags.\n            for( auto const& msg : assertionStats.infoMessages ) {\n                if( msg.type == ResultWas::Info && includeResults ) {\n                    m_xml.scopedElement( \"Info\" )\n                            .writeText( msg.message );\n                } else if ( msg.type == ResultWas::Warning ) {\n                    m_xml.scopedElement( \"Warning\" )\n                            .writeText( msg.message );\n                }\n            }\n        }\n\n        // Drop out if result was successful but we're not printing them.\n        if( !includeResults && result.getResultType() != ResultWas::Warning )\n            return true;\n\n        // Print the expression if there is one.\n        if( result.hasExpression() ) {\n            m_xml.startElement( \"Expression\" )\n                .writeAttribute( \"success\", result.succeeded() )\n                .writeAttribute( \"type\", result.getTestMacroName() );\n\n            writeSourceInfo( result.getSourceInfo() );\n\n            m_xml.scopedElement( \"Original\" )\n                .writeText( result.getExpression() );\n            m_xml.scopedElement( \"Expanded\" )\n                .writeText( result.getExpandedExpression() );\n        }\n\n        // And... Print a result applicable to each result type.\n        switch( result.getResultType() ) {\n            case ResultWas::ThrewException:\n                m_xml.startElement( \"Exception\" );\n                writeSourceInfo( result.getSourceInfo() );\n                m_xml.writeText( result.getMessage() );\n                m_xml.endElement();\n                break;\n            case ResultWas::FatalErrorCondition:\n                m_xml.startElement( \"FatalErrorCondition\" );\n                writeSourceInfo( result.getSourceInfo() );\n                m_xml.writeText( result.getMessage() );\n                m_xml.endElement();\n                break;\n            case ResultWas::Info:\n                m_xml.scopedElement( \"Info\" )\n                    .writeText( result.getMessage() );\n                break;\n            case ResultWas::Warning:\n                // Warning will already have been written\n                break;\n            case ResultWas::ExplicitFailure:\n                m_xml.startElement( \"Failure\" );\n                writeSourceInfo( result.getSourceInfo() );\n                m_xml.writeText( result.getMessage() );\n                m_xml.endElement();\n                break;\n            default:\n                break;\n        }\n\n        if( result.hasExpression() )\n            m_xml.endElement();\n\n        return true;\n    }\n\n    void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {\n        StreamingReporterBase::sectionEnded( sectionStats );\n        if( --m_sectionDepth > 0 ) {\n            XmlWriter::ScopedElement e = m_xml.scopedElement( \"OverallResults\" );\n            e.writeAttribute( \"successes\", sectionStats.assertions.passed );\n            e.writeAttribute( \"failures\", sectionStats.assertions.failed );\n            e.writeAttribute( \"expectedFailures\", sectionStats.assertions.failedButOk );\n\n            if ( m_config->showDurations() == ShowDurations::Always )\n                e.writeAttribute( \"durationInSeconds\", sectionStats.durationInSeconds );\n\n            m_xml.endElement();\n        }\n    }\n\n    void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {\n        StreamingReporterBase::testCaseEnded( testCaseStats );\n        XmlWriter::ScopedElement e = m_xml.scopedElement( \"OverallResult\" );\n        e.writeAttribute( \"success\", testCaseStats.totals.assertions.allOk() );\n\n        if ( m_config->showDurations() == ShowDurations::Always )\n            e.writeAttribute( \"durationInSeconds\", m_testCaseTimer.getElapsedSeconds() );\n\n        if( !testCaseStats.stdOut.empty() )\n            m_xml.scopedElement( \"StdOut\" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );\n        if( !testCaseStats.stdErr.empty() )\n            m_xml.scopedElement( \"StdErr\" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );\n\n        m_xml.endElement();\n    }\n\n    void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {\n        StreamingReporterBase::testGroupEnded( testGroupStats );\n        // TODO: Check testGroupStats.aborting and act accordingly.\n        m_xml.scopedElement( \"OverallResults\" )\n            .writeAttribute( \"successes\", testGroupStats.totals.assertions.passed )\n            .writeAttribute( \"failures\", testGroupStats.totals.assertions.failed )\n            .writeAttribute( \"expectedFailures\", testGroupStats.totals.assertions.failedButOk );\n        m_xml.endElement();\n    }\n\n    void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {\n        StreamingReporterBase::testRunEnded( testRunStats );\n        m_xml.scopedElement( \"OverallResults\" )\n            .writeAttribute( \"successes\", testRunStats.totals.assertions.passed )\n            .writeAttribute( \"failures\", testRunStats.totals.assertions.failed )\n            .writeAttribute( \"expectedFailures\", testRunStats.totals.assertions.failedButOk );\n        m_xml.endElement();\n    }\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n    void XmlReporter::benchmarkPreparing(std::string const& name) {\n        m_xml.startElement(\"BenchmarkResults\")\n            .writeAttribute(\"name\", name);\n    }\n\n    void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {\n        m_xml.writeAttribute(\"samples\", info.samples)\n            .writeAttribute(\"resamples\", info.resamples)\n            .writeAttribute(\"iterations\", info.iterations)\n            .writeAttribute(\"clockResolution\", static_cast<uint64_t>(info.clockResolution))\n            .writeAttribute(\"estimatedDuration\", static_cast<uint64_t>(info.estimatedDuration))\n            .writeComment(\"All values in nano seconds\");\n    }\n\n    void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {\n        m_xml.startElement(\"mean\")\n            .writeAttribute(\"value\", static_cast<uint64_t>(benchmarkStats.mean.point.count()))\n            .writeAttribute(\"lowerBound\", static_cast<uint64_t>(benchmarkStats.mean.lower_bound.count()))\n            .writeAttribute(\"upperBound\", static_cast<uint64_t>(benchmarkStats.mean.upper_bound.count()))\n            .writeAttribute(\"ci\", benchmarkStats.mean.confidence_interval);\n        m_xml.endElement();\n        m_xml.startElement(\"standardDeviation\")\n            .writeAttribute(\"value\", benchmarkStats.standardDeviation.point.count())\n            .writeAttribute(\"lowerBound\", benchmarkStats.standardDeviation.lower_bound.count())\n            .writeAttribute(\"upperBound\", benchmarkStats.standardDeviation.upper_bound.count())\n            .writeAttribute(\"ci\", benchmarkStats.standardDeviation.confidence_interval);\n        m_xml.endElement();\n        m_xml.startElement(\"outliers\")\n            .writeAttribute(\"variance\", benchmarkStats.outlierVariance)\n            .writeAttribute(\"lowMild\", benchmarkStats.outliers.low_mild)\n            .writeAttribute(\"lowSevere\", benchmarkStats.outliers.low_severe)\n            .writeAttribute(\"highMild\", benchmarkStats.outliers.high_mild)\n            .writeAttribute(\"highSevere\", benchmarkStats.outliers.high_severe);\n        m_xml.endElement();\n        m_xml.endElement();\n    }\n\n    void XmlReporter::benchmarkFailed(std::string const &error) {\n        m_xml.scopedElement(\"failed\").\n            writeAttribute(\"message\", error);\n        m_xml.endElement();\n    }\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n    CATCH_REGISTER_REPORTER( \"xml\", XmlReporter )\n\n} // end namespace Catch\n\n#if defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n// end catch_reporter_xml.cpp\n\nnamespace Catch {\n    LeakDetector leakDetector;\n}\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n// end catch_impl.hpp\n#endif\n\n#ifdef CATCH_CONFIG_MAIN\n// start catch_default_main.hpp\n\n#ifndef __OBJC__\n\n#if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)\n// Standard C/C++ Win32 Unicode wmain entry point\nextern \"C\" int wmain (int argc, wchar_t * argv[], wchar_t * []) {\n#else\n// Standard C/C++ main entry point\nint main (int argc, char * argv[]) {\n#endif\n\n    return Catch::Session().run( argc, argv );\n}\n\n#else // __OBJC__\n\n// Objective-C entry point\nint main (int argc, char * const argv[]) {\n#if !CATCH_ARC_ENABLED\n    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n#endif\n\n    Catch::registerTestMethods();\n    int result = Catch::Session().run( argc, (char**)argv );\n\n#if !CATCH_ARC_ENABLED\n    [pool drain];\n#endif\n\n    return result;\n}\n\n#endif // __OBJC__\n\n// end catch_default_main.hpp\n#endif\n\n#if !defined(CATCH_CONFIG_IMPL_ONLY)\n\n#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED\n#  undef CLARA_CONFIG_MAIN\n#endif\n\n#if !defined(CATCH_CONFIG_DISABLE)\n//////\n// If this config identifier is defined then all CATCH macros are prefixed with CATCH_\n#ifdef CATCH_CONFIG_PREFIX_ALL\n\n#define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( \"CATCH_REQUIRE\", Catch::ResultDisposition::Normal, __VA_ARGS__ )\n#define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( \"CATCH_REQUIRE_FALSE\", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )\n\n#define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( \"CATCH_REQUIRE_THROWS\", Catch::ResultDisposition::Normal, __VA_ARGS__ )\n#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( \"CATCH_REQUIRE_THROWS_AS\", exceptionType, Catch::ResultDisposition::Normal, expr )\n#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( \"CATCH_REQUIRE_THROWS_WITH\", Catch::ResultDisposition::Normal, matcher, expr )\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( \"CATCH_REQUIRE_THROWS_MATCHES\", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )\n#endif// CATCH_CONFIG_DISABLE_MATCHERS\n#define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( \"CATCH_REQUIRE_NOTHROW\", Catch::ResultDisposition::Normal, __VA_ARGS__ )\n\n#define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( \"CATCH_CHECK\", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( \"CATCH_CHECK_FALSE\", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )\n#define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( \"CATCH_CHECKED_IF\", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( \"CATCH_CHECKED_ELSE\", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( \"CATCH_CHECK_NOFAIL\", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )\n\n#define CATCH_CHECK_THROWS( ... )  INTERNAL_CATCH_THROWS( \"CATCH_CHECK_THROWS\", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( \"CATCH_CHECK_THROWS_AS\", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )\n#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( \"CATCH_CHECK_THROWS_WITH\", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( \"CATCH_CHECK_THROWS_MATCHES\", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n#define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( \"CATCH_CHECK_NOTHROW\", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( \"CATCH_CHECK_THAT\", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )\n\n#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( \"CATCH_REQUIRE_THAT\", matcher, Catch::ResultDisposition::Normal, arg )\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n\n#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( \"CATCH_INFO\", msg )\n#define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( \"CATCH_UNSCOPED_INFO\", msg )\n#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( \"CATCH_WARN\", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )\n#define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), \"CATCH_CAPTURE\",__VA_ARGS__ )\n\n#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )\n#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )\n#define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )\n#define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )\n#define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )\n#define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( \"CATCH_FAIL\", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )\n#define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( \"CATCH_FAIL_CHECK\", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( \"CATCH_SUCCEED\", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n\n#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )\n#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )\n#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )\n#else\n#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )\n#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )\n#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )\n#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )\n#endif\n\n#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)\n#define CATCH_STATIC_REQUIRE( ... )       static_assert(   __VA_ARGS__ ,      #__VA_ARGS__ );     CATCH_SUCCEED( #__VA_ARGS__ )\n#define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), \"!(\" #__VA_ARGS__ \")\" ); CATCH_SUCCEED( #__VA_ARGS__ )\n#else\n#define CATCH_STATIC_REQUIRE( ... )       CATCH_REQUIRE( __VA_ARGS__ )\n#define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )\n#endif\n\n// \"BDD-style\" convenience wrappers\n#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( \"Scenario: \" __VA_ARGS__ )\n#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, \"Scenario: \" __VA_ARGS__ )\n#define CATCH_GIVEN( desc )     INTERNAL_CATCH_DYNAMIC_SECTION( \"    Given: \" << desc )\n#define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( \"And given: \" << desc )\n#define CATCH_WHEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( \"     When: \" << desc )\n#define CATCH_AND_WHEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( \" And when: \" << desc )\n#define CATCH_THEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( \"     Then: \" << desc )\n#define CATCH_AND_THEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( \"      And: \" << desc )\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n#define CATCH_BENCHMARK(...) \\\n    INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))\n#define CATCH_BENCHMARK_ADVANCED(name) \\\n    INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\n// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required\n#else\n\n#define REQUIRE( ... ) INTERNAL_CATCH_TEST( \"REQUIRE\", Catch::ResultDisposition::Normal, __VA_ARGS__  )\n#define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( \"REQUIRE_FALSE\", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )\n\n#define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( \"REQUIRE_THROWS\", Catch::ResultDisposition::Normal, __VA_ARGS__ )\n#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( \"REQUIRE_THROWS_AS\", exceptionType, Catch::ResultDisposition::Normal, expr )\n#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( \"REQUIRE_THROWS_WITH\", Catch::ResultDisposition::Normal, matcher, expr )\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( \"REQUIRE_THROWS_MATCHES\", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n#define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( \"REQUIRE_NOTHROW\", Catch::ResultDisposition::Normal, __VA_ARGS__ )\n\n#define CHECK( ... ) INTERNAL_CATCH_TEST( \"CHECK\", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( \"CHECK_FALSE\", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )\n#define CHECKED_IF( ... ) INTERNAL_CATCH_IF( \"CHECKED_IF\", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( \"CHECKED_ELSE\", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( \"CHECK_NOFAIL\", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )\n\n#define CHECK_THROWS( ... )  INTERNAL_CATCH_THROWS( \"CHECK_THROWS\", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( \"CHECK_THROWS_AS\", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )\n#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( \"CHECK_THROWS_WITH\", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( \"CHECK_THROWS_MATCHES\", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n#define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( \"CHECK_NOTHROW\", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( \"CHECK_THAT\", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )\n\n#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( \"REQUIRE_THAT\", matcher, Catch::ResultDisposition::Normal, arg )\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n\n#define INFO( msg ) INTERNAL_CATCH_INFO( \"INFO\", msg )\n#define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( \"UNSCOPED_INFO\", msg )\n#define WARN( msg ) INTERNAL_CATCH_MSG( \"WARN\", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )\n#define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), \"CAPTURE\",__VA_ARGS__ )\n\n#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )\n#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )\n#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )\n#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )\n#define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )\n#define FAIL( ... ) INTERNAL_CATCH_MSG( \"FAIL\", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )\n#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( \"FAIL_CHECK\", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define SUCCEED( ... ) INTERNAL_CATCH_MSG( \"SUCCEED\", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )\n#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )\n#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )\n#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )\n#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)\n#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#else\n#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )\n#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )\n#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )\n#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )\n#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )\n#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )\n#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )\n#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )\n#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )\n#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )\n#endif\n\n#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)\n#define STATIC_REQUIRE( ... )       static_assert(   __VA_ARGS__,  #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )\n#define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), \"!(\" #__VA_ARGS__ \")\" ); SUCCEED( \"!(\" #__VA_ARGS__ \")\" )\n#else\n#define STATIC_REQUIRE( ... )       REQUIRE( __VA_ARGS__ )\n#define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )\n#endif\n\n#endif\n\n#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )\n\n// \"BDD-style\" convenience wrappers\n#define SCENARIO( ... ) TEST_CASE( \"Scenario: \" __VA_ARGS__ )\n#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, \"Scenario: \" __VA_ARGS__ )\n\n#define GIVEN( desc )     INTERNAL_CATCH_DYNAMIC_SECTION( \"    Given: \" << desc )\n#define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( \"And given: \" << desc )\n#define WHEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( \"     When: \" << desc )\n#define AND_WHEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( \" And when: \" << desc )\n#define THEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( \"     Then: \" << desc )\n#define AND_THEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( \"      And: \" << desc )\n\n#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)\n#define BENCHMARK(...) \\\n    INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))\n#define BENCHMARK_ADVANCED(name) \\\n    INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)\n#endif // CATCH_CONFIG_ENABLE_BENCHMARKING\n\nusing Catch::Detail::Approx;\n\n#else // CATCH_CONFIG_DISABLE\n\n//////\n// If this config identifier is defined then all CATCH macros are prefixed with CATCH_\n#ifdef CATCH_CONFIG_PREFIX_ALL\n\n#define CATCH_REQUIRE( ... )        (void)(0)\n#define CATCH_REQUIRE_FALSE( ... )  (void)(0)\n\n#define CATCH_REQUIRE_THROWS( ... ) (void)(0)\n#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)\n#define CATCH_REQUIRE_THROWS_WITH( expr, matcher )     (void)(0)\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)\n#endif// CATCH_CONFIG_DISABLE_MATCHERS\n#define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)\n\n#define CATCH_CHECK( ... )         (void)(0)\n#define CATCH_CHECK_FALSE( ... )   (void)(0)\n#define CATCH_CHECKED_IF( ... )    if (__VA_ARGS__)\n#define CATCH_CHECKED_ELSE( ... )  if (!(__VA_ARGS__))\n#define CATCH_CHECK_NOFAIL( ... )  (void)(0)\n\n#define CATCH_CHECK_THROWS( ... )  (void)(0)\n#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)\n#define CATCH_CHECK_THROWS_WITH( expr, matcher )     (void)(0)\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n#define CATCH_CHECK_NOTHROW( ... ) (void)(0)\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define CATCH_CHECK_THAT( arg, matcher )   (void)(0)\n\n#define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n\n#define CATCH_INFO( msg )          (void)(0)\n#define CATCH_UNSCOPED_INFO( msg ) (void)(0)\n#define CATCH_WARN( msg )          (void)(0)\n#define CATCH_CAPTURE( msg )       (void)(0)\n\n#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))\n#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))\n#define CATCH_METHOD_AS_TEST_CASE( method, ... )\n#define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)\n#define CATCH_SECTION( ... )\n#define CATCH_DYNAMIC_SECTION( ... )\n#define CATCH_FAIL( ... ) (void)(0)\n#define CATCH_FAIL_CHECK( ... ) (void)(0)\n#define CATCH_SUCCEED( ... ) (void)(0)\n\n#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)\n#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)\n#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)\n#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#else\n#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )\n#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )\n#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )\n#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#endif\n\n// \"BDD-style\" convenience wrappers\n#define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))\n#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )\n#define CATCH_GIVEN( desc )\n#define CATCH_AND_GIVEN( desc )\n#define CATCH_WHEN( desc )\n#define CATCH_AND_WHEN( desc )\n#define CATCH_THEN( desc )\n#define CATCH_AND_THEN( desc )\n\n#define CATCH_STATIC_REQUIRE( ... )       (void)(0)\n#define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)\n\n// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required\n#else\n\n#define REQUIRE( ... )       (void)(0)\n#define REQUIRE_FALSE( ... ) (void)(0)\n\n#define REQUIRE_THROWS( ... ) (void)(0)\n#define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)\n#define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n#define REQUIRE_NOTHROW( ... ) (void)(0)\n\n#define CHECK( ... ) (void)(0)\n#define CHECK_FALSE( ... ) (void)(0)\n#define CHECKED_IF( ... ) if (__VA_ARGS__)\n#define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))\n#define CHECK_NOFAIL( ... ) (void)(0)\n\n#define CHECK_THROWS( ... )  (void)(0)\n#define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)\n#define CHECK_THROWS_WITH( expr, matcher ) (void)(0)\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n#define CHECK_NOTHROW( ... ) (void)(0)\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n#define CHECK_THAT( arg, matcher ) (void)(0)\n\n#define REQUIRE_THAT( arg, matcher ) (void)(0)\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n\n#define INFO( msg ) (void)(0)\n#define UNSCOPED_INFO( msg ) (void)(0)\n#define WARN( msg ) (void)(0)\n#define CAPTURE( msg ) (void)(0)\n\n#define TEST_CASE( ... )  INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))\n#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))\n#define METHOD_AS_TEST_CASE( method, ... )\n#define REGISTER_TEST_CASE( Function, ... ) (void)(0)\n#define SECTION( ... )\n#define DYNAMIC_SECTION( ... )\n#define FAIL( ... ) (void)(0)\n#define FAIL_CHECK( ... ) (void)(0)\n#define SUCCEED( ... ) (void)(0)\n#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))\n\n#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR\n#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)\n#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)\n#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)\n#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#else\n#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )\n#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )\n#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )\n#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )\n#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )\n#endif\n\n#define STATIC_REQUIRE( ... )       (void)(0)\n#define STATIC_REQUIRE_FALSE( ... ) (void)(0)\n\n#endif\n\n#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )\n\n// \"BDD-style\" convenience wrappers\n#define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )\n#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )\n\n#define GIVEN( desc )\n#define AND_GIVEN( desc )\n#define WHEN( desc )\n#define AND_WHEN( desc )\n#define THEN( desc )\n#define AND_THEN( desc )\n\nusing Catch::Detail::Approx;\n\n#endif\n\n#endif // ! CATCH_CONFIG_IMPL_ONLY\n\n// start catch_reenable_warnings.h\n\n\n#ifdef __clang__\n#    ifdef __ICC // icpc defines the __clang__ macro\n#        pragma warning(pop)\n#    else\n#        pragma clang diagnostic pop\n#    endif\n#elif defined __GNUC__\n#    pragma GCC diagnostic pop\n#endif\n\n// end catch_reenable_warnings.h\n// end catch.hpp\n#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED\n\n"
  },
  {
    "path": "src/test/test.cpp",
    "content": "#include \"common.h\"\n\n#if TEST_MODE\n\n#define CATCH_CONFIG_RUNNER\n#include \"catch.hpp\"\n\n#include \"vm/machine.h\"\n#include \"io/loader.h\"\n#include \"lua/lua.hpp\"\n\n#include <unordered_set>\n#include <filesystem>\n\nusing namespace retro8;\nusing namespace retro8::gfx;\n\nextern retro8::Machine machine;\nMachine& m = machine;\n\nTEST_CASE(\"cursor([x,] [y,] [col])\")\n{\n  Machine& m = machine;\n  auto* cursor = m.memory().cursor();\n\n  SECTION(\"cursor starts at 0,0\")\n  {\n    REQUIRE((cursor->x() == 0 && cursor->y() == 0));\n  }\n}\n\nTEST_CASE(\"camera([x,] [y])\")\n{\n  auto* camera = m.memory().camera();\n\n  SECTION(\"camera starts at 0,0\")\n  {\n    REQUIRE((camera->x() == 0 && camera->y() == 0));\n  }\n\n  SECTION(\"camera is properly set by camera() function\")\n  {\n    m.code().initFromSource(\"camera(20,-10)\");\n    auto* camera = m.memory().camera();\n    REQUIRE(camera->x() == 20);\n    REQUIRE(camera->y() == -10);\n  }\n\n  SECTION(\"camera is properly reset by camera() function\")\n  {\n    m.code().initFromSource(\"camera(20,-10)\");\n    REQUIRE((camera->x() == 20 && camera->y() == -10));\n    m.code().initFromSource(\"camera()\");\n    REQUIRE((camera->x() == 0 && camera->y() == 0));\n  }\n\n  SECTION(\"single argument sets x and resets y\")\n  {\n    m.code().initFromSource(\"camera(20,-10)\");\n    REQUIRE((camera->x() == 20 && camera->y() == -10));\n    m.code().initFromSource(\"camera(40)\");\n    REQUIRE((camera->x() == 40 && camera->y() == 0));\n  }\n}\n\nTEST_CASE(\"tilemap\")\n{\n  Machine m;\n\n  SECTION(\"tilemap address space never overlap\")\n  {\n    std::unordered_set<const sprite_index_t*> addresses;\n\n    for (size_t y = 0; y < TILE_MAP_HEIGHT; ++y)\n    {\n      for (size_t x = 0; x < TILE_MAP_WIDTH; ++x)\n      {\n        const sprite_index_t* address = m.memory().spriteInTileMap(x, y);\n        addresses.insert(address);\n      }\n    }\n\n    REQUIRE(addresses.size() == TILE_MAP_WIDTH * TILE_MAP_HEIGHT);\n  }\n  \n  SECTION(\"tilemap halves are inverted compared to theie coordinates\")\n  {\n    REQUIRE(m.memory().spriteInTileMap(0, 32) - m.memory().base() == address::TILE_MAP_LOW);\n    REQUIRE(m.memory().spriteInTileMap(0, 0) - m.memory().base() == address::TILE_MAP_HIGH);\n    REQUIRE(address::TILE_MAP_HIGH > address::TILE_MAP_LOW);\n  }\n}\n\nTEST_CASE(\"mid\")\n{\n  Machine m;\n\n  SECTION(\"a < b < c = b\")\n  {\n    m.code().initFromSource(\"function _test() return mid(1, 2, 3) end\");\n    m.code().callFunction(\"_test\", 1);\n    REQUIRE(lua_tonumber(m.code().state(), -1) == 2);\n  }\n}\n\nTEST_CASE(\"bitwise\")\n{\n  Machine m;\n\n  std::string code;\n  uint32_t expected;\n\n  SECTION(\"and\")\n  {\n    auto i = GENERATE(range(0, 255));\n    auto j = GENERATE(range(0, 255));\n    \n    code = \"return band(\" + std::to_string(i) + \", \" + std::to_string(j) + \")\";\n    expected = i & j;\n  }\n\n  SECTION(\"or\")\n  {\n    auto i = GENERATE(range(0, 255));\n    auto j = GENERATE(range(0, 255));\n\n    code = \"return bor(\" + std::to_string(i) + \", \" + std::to_string(j) + \")\";\n    expected = i | j;\n  }\n\n  m.code().initFromSource(\"function _test() \" + code + \" end\");\n  m.code().callFunction(\"_test\", 1);\n  REQUIRE(lua_tonumber(m.code().state(), -1) == expected);\n}\n\nTEST_CASE(\"lua language modifications\")\n{\n  lua_State* L = luaL_newstate();\n\n  SECTION(\"!= operator\")\n  {\n    SECTION(\"!= operator is compiled successfully\")\n    {\n      const std::string code = \"x = 5 != 4\";\n\n      REQUIRE(luaL_loadstring(L, code.c_str()) == 0);\n      REQUIRE(lua_pcall(L, 0, 0, 0) == 0);\n    }\n\n  }\n\n  SECTION(\"binary literals\")\n  {\n    std::string literal;\n    int expected = 0;\n    \n    SECTION(\"0b1\")\n    {\n      literal = \"0b1\";\n      expected = 0b1;\n    }\n\n    SECTION(\"0b100\")\n    {\n      literal = \"0b100\";\n      expected = 0b100;\n    }\n\n    SECTION(\"0b000\")\n    {\n      literal = \"0b000\";\n      expected = 0b000;\n    }\n\n\n    const std::string code = \"x = \" + literal + \"; return x\";\n    REQUIRE(luaL_loadstring(L, code.c_str()) == 0);\n    REQUIRE(lua_pcall(L, 0, 1, 0) == 0);\n    REQUIRE(lua_tonumber(L, -1) == expected);\n  }\n\n  SECTION(\"compound assignment\")\n  {\n    SECTION(\"+= operator\")\n    {\n      std::string code = \"x = 2; x += 4; return x\";\n      REQUIRE(luaL_loadstring(L, code.c_str()) == 0);\n      REQUIRE(lua_pcall(L, 0, 1, 0) == 0);\n      REQUIRE(lua_tonumber(L, -1) == 6);\n    }\n\n\n  }\n\n  lua_close(L);\n}\n\n/*TEST_CASE(\"cartridge testing\")\n{\n  retro8::io::Loader loader;\n  retro8::Machine m;\n\n  namespace fs = std::filesystem;\n  std::error_code ec;\n  \n  for (const auto& p : fs::directory_iterator(\"cartridges\", ec))\n  {\n    const auto& path = p.path();\n\n    if (fs::is_regular_file(path) && path.extension() == \".p8\")\n    {\n      SECTION(std::string(\"Test on source file \") + path.filename().generic_u8string())\n      {\n        lua_State* L = luaL_newstate();\n\n        std::string code = loader.load(path.generic_u8string());\n        int status = luaL_loadbufferx(L, code.c_str(), code.length(), path.filename().generic_u8string().c_str(), nullptr);\n\n        if (status)\n        {\n          const char* message = \"unknown error\";\n          if (lua_isstring(L, -1))\n            message = lua_tostring(L, -1);\n          FAIL(\"Error: \" << message);\n        }\n\n        lua_close(L);\n      }\n    }\n  }\n\n}*/\n\nint testMain(int rargc, char* rargv[])\n{\n  Catch::Session session;\n\n  const char* argv2[] = { \"retro8\", \"--success\" };\n\n  int argc = rargc;\n  const char** argv = const_cast<const char**>(rargv);\n\n  int result = session.run(argc, argv);\n  return result;\n}\n\n#endif"
  },
  {
    "path": "src/views/game_view.cpp",
    "content": "#include \"main_view.h\"\r\n\r\n#include \"io/loader.h\"\r\n#include \"io/stegano.h\"\r\n\r\n#include <future>\r\n\r\n#include <SDL_audio.h>\r\n\r\nclass SDLAudio\r\n{\r\nprivate:\r\n  SDL_AudioSpec spec;\r\n  SDL_AudioDeviceID device;\r\n\r\n  static void audio_callback(void* data, uint8_t* cbuffer, int length);\r\n\r\npublic:\r\n  void init(retro8::sfx::APU* apu);\r\n\r\n  void pause();\r\n  void resume();\r\n  void close();\r\n};\r\n\r\nvoid SDLAudio::audio_callback(void* data, uint8_t* cbuffer, int length)\r\n{\r\n  retro8::sfx::APU* apu = static_cast<retro8::sfx::APU*>(data);\r\n  int16_t* buffer = reinterpret_cast<int16_t*>(cbuffer);\r\n  apu->renderSounds(buffer, length / sizeof(int16_t));\r\n  return;\r\n}\r\n\r\nvoid SDLAudio::init(retro8::sfx::APU* apu)\r\n{\r\n  SDL_AudioSpec wantSpec;\r\n  wantSpec.freq = 44100;\r\n  wantSpec.format = AUDIO_S16SYS;\r\n  wantSpec.channels = 1;\r\n  wantSpec.samples = 2048;\r\n  wantSpec.userdata = apu;\r\n  wantSpec.callback = audio_callback;\r\n\r\n  device = SDL_OpenAudioDevice(NULL, 0, &wantSpec, &spec, 0);\r\n\r\n  if (!device)\r\n  {\r\n    printf(\"Error while opening audio: %s\", SDL_GetError());\r\n  }\r\n}\r\n\r\nvoid SDLAudio::resume()\r\n{\r\n  SDL_PauseAudioDevice(device, false);\r\n}\r\n\r\nvoid SDLAudio::pause()\r\n{\r\n  SDL_PauseAudioDevice(device, true);\r\n}\r\n\r\nvoid SDLAudio::close()\r\n{\r\n  SDL_CloseAudioDevice(device);\r\n}\r\n\r\nSDLAudio sdlAudio;\r\n\r\nusing namespace ui;\r\nnamespace r8 = retro8;\r\n\r\n\r\nretro8::Machine machine;\r\n\r\nGameView::GameView(ViewManager* manager) : manager(manager),\r\n_paused(false), _showFPS(false), _showCartridgeName(false)\r\n{\r\n}\r\n\r\n\r\nvoid GameView::update()\r\n{\r\n  machine.code().update();\r\n  machine.code().draw();\r\n}\r\n\r\n\r\n\r\nretro8::io::PngData loadPng(const std::string& path)\r\n{\r\n  std::ifstream fl(path, std::ios_base::in | std::ios_base::binary);\r\n  fl.seekg(0, std::ios::end);\r\n  size_t length = fl.tellg();\r\n\r\n  char* bdata = new char[length];\r\n\r\n  fl.seekg(0, std::ios::beg);\r\n  fl.read(bdata, length);\r\n\r\n  fl.close();\r\n\r\n  std::vector<uint8_t> out;\r\n  unsigned long width, height;\r\n  auto result = Platform::loadPNG(out, width, height, (uint8_t*)bdata, length, true);\r\n\r\n  delete [] bdata;\r\n\r\n  assert(result == 0);\r\n\r\n  if (result != 0)\r\n  {\r\n    printf(\"Error while loading PNG cart.\");\r\n    assert(false);\r\n  }\r\n\r\n  SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);\r\n  std::memcpy(surface->pixels, out.data(), width*height * sizeof(uint32_t));\r\n\r\n  retro8::io::PngData pngData = { static_cast<const uint32_t*>(surface->pixels), surface, static_cast<size_t>(surface->h * surface->w)};\r\n  assert(surface->pitch == retro8::io::Stegano::IMAGE_WIDTH * sizeof(uint32_t));\r\n  assert(surface->format->BytesPerPixel == 4);\r\n\r\n  return pngData;\r\n}\r\n\r\nr8::gfx::ColorTable colorTable;\r\n\r\nstruct ColorMapper\r\n{\r\n  const SDL_PixelFormat* format;\r\n  ColorMapper(const SDL_PixelFormat* format) : format(format) { }\r\n\r\n  inline r8::gfx::ColorTable::pixel_t operator()(uint8_t r, uint8_t g, uint8_t b) const\r\n  {\r\n    return SDL_MapRGB(format, r, g, b);\r\n  }\r\n};\r\n\r\nvoid GameView::rasterize()\r\n{\r\n  auto* data = machine.memory().screenData();\r\n  auto* screenPalette = machine.memory().paletteAt(r8::gfx::SCREEN_PALETTE_INDEX);\r\n  uint32_t* output = _output.pixels();\r\n\r\n  for (size_t i = 0; i < r8::gfx::BYTES_PER_SCREEN; ++i)\r\n  {\r\n    const r8::gfx::color_byte_t* pixels = data + i;\r\n    const auto rc1 = colorTable.get(screenPalette->get((pixels)->low()));\r\n    const auto rc2 = colorTable.get(screenPalette->get((pixels)->high()));\r\n\r\n    *(output) = rc1;\r\n    *((output)+1) = rc2;\r\n    (output) += 2;\r\n  }\r\n}\r\n\r\n\r\n\r\nbool init = false;\r\nvoid GameView::render()\r\n{\r\n  if (!init)\r\n  {\r\n    LOGD(\"Initializing color table\");\r\n    auto* format = manager->displayFormat();\r\n    colorTable.init(ColorMapper(manager->displayFormat()));\r\n\r\n#if !defined(SDL12)\r\n    printf(\"Using renderer pixel format: %s\\n\", SDL_GetPixelFormatName(format->format));\r\n#endif\r\n\r\n    /* initialize main surface and its texture */\r\n    _output = manager->allocate(128, 128);\r\n\r\n    if (!_output)\r\n    {\r\n      printf(\"Unable to allocate buffer surface: %s\\n\", SDL_GetError());\r\n    }\r\n\r\n    assert(_output);\r\n\r\n    _frameCounter = 0;\r\n\r\n    machine.code().loadAPI();\r\n    _input.setMachine(&machine);\r\n\r\n\r\n    if (_path.empty())\r\n      _path = \"cartridges/pico-racer.png\";\r\n\r\n    if (r8::io::Loader::isPngCartridge(_path))\r\n    {\r\n      auto cartridge = loadPng(_path);\r\n\r\n      retro8::io::Stegano stegano;\r\n      stegano.load(cartridge, machine);\r\n\r\n      manager->setPngCartridge(static_cast<SDL_Surface*>(cartridge.userData));\r\n      SDL_FreeSurface(static_cast<SDL_Surface*>(cartridge.userData));\r\n    }\r\n    else\r\n    {\r\n      r8::io::Loader loader;\r\n      loader.loadFile(_path, machine);\r\n      manager->setPngCartridge(nullptr);\r\n    }\r\n\r\n    machine.memory().backupCartridge();\r\n\r\n    int32_t fps = machine.code().require60fps() ? 60 : 30;\r\n    manager->setFrameRate(fps);\r\n\r\n    if (machine.code().hasInit())\r\n    {\r\n      /* init is launched on a different thread because some developers are using busy loops and manual flips */\r\n      _initFuture = std::async(std::launch::async, []() {\r\n        LOGD(\"Cartridge has _init() function, calling it.\");\r\n        machine.code().init();\r\n        LOGD(\"_init() function completed execution.\");\r\n      });\r\n    }\r\n\r\n    machine.sound().init();\r\n    sdlAudio.init(&machine.sound());\r\n    sdlAudio.resume();\r\n\r\n    init = true;\r\n  }\r\n\r\n  _input.manageKeyRepeat();\r\n  _input.tick();\r\n\r\n  auto* renderer = manager->renderer();\r\n\r\n  manager->clear(0, 0, 0);\r\n\r\n  if (!_paused)\r\n  {\r\n    if (!_initFuture.valid() || _initFuture.wait_for(std::chrono::nanoseconds(0)) == std::future_status::ready)\r\n    {\r\n      update();\r\n      rasterize();\r\n    }\r\n\r\n    _output.update();\r\n  }\r\n\r\n  SDL_Rect dest;\r\n\r\n  if (_scaler == Scaler::UNSCALED)\r\n    dest = { (SCREEN_WIDTH - 128) / 2, (SCREEN_HEIGHT - 128) / 2, 128, 128 };\r\n  else if (_scaler == Scaler::SCALED_ASPECT_2x)\r\n    dest = { (SCREEN_WIDTH - 256) / 2, (SCREEN_HEIGHT - 256) / 2, 256, 256 };\r\n  else\r\n    dest = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };\r\n\r\n  manager->blitToScreen(_output, dest);\r\n\r\n  if (_showFPS)\r\n  {\r\n    char buffer[16];\r\n    sprintf(buffer, \"%.0f/%c0\", 1000.0f / manager->lastFrameTicks(), machine.code().require60fps() ? '6' : '3');\r\n    manager->text(buffer, 10, 10);\r\n  }\r\n\r\n  ++_frameCounter;\r\n\r\n#if DEBUGGER\r\n  {\r\n    /* sprite sheet */\r\n    {\r\n      SDL_Surface* spritesheet = SDL_CreateRGBSurface(0, 128, 128, 32, 0x00000000, 0x00ff0000, 0x0000ff00, 0x000000ff);\r\n\r\n      SDL_FillRect(spritesheet, nullptr, 0xFFFFFFFF);\r\n      auto* dest = static_cast<uint32_t*>(spritesheet->pixels);\r\n      for (r8::coord_t y = 0; y < r8::gfx::SPRITE_SHEET_HEIGHT; ++y)\r\n        for (r8::coord_t x = 0; x < r8::gfx::SPRITE_SHEET_PITCH; ++x)\r\n        {\r\n          const r8::gfx::color_byte_t* data = machine.memory().as<r8::gfx::color_byte_t>(r8::address::SPRITE_SHEET + y * r8::gfx::SPRITE_SHEET_PITCH + x);\r\n          RASTERIZE_PIXEL_PAIR(machine, dest, data);\r\n        }\r\n\r\n      Texture* texture = SDL_CreateTextureFromSurface(renderer, spritesheet);\r\n      SDL_Rect destr = { (1024 - 286) , 30, 256, 256 };\r\n      SDL_RenderCopy(renderer, texture, nullptr, &destr);\r\n      SDL_DestroyTexture(texture);\r\n      SDL_FreeSurface(spritesheet);\r\n    }\r\n\r\n    /* palettes */\r\n    {\r\n      SDL_Surface* palettes = SDL_CreateRGBSurface(0, 16, 2, 32, 0x00000000, 0x00ff0000, 0x0000ff00, 0x000000ff);\r\n\r\n      SDL_FillRect(palettes, nullptr, 0xFFFFFFFF);\r\n      auto* dest = static_cast<uint32_t*>(palettes->pixels);\r\n\r\n      for (r8::palette_index_t j = 0; j < 2; ++j)\r\n      {\r\n        const r8::gfx::palette_t* palette = machine.memory().paletteAt(j);\r\n\r\n        for (size_t i = 0; i < r8::gfx::COLOR_COUNT; ++i)\r\n          dest[j*16 + i] = colorTable.get(palette->get(r8::color_t(i)));\r\n      }\r\n\r\n      Texture* texture = SDL_CreateTextureFromSurface(renderer, palettes);\r\n      SDL_Rect destr = { (1024 - 286) , 300, 256, 32 };\r\n      SDL_RenderCopy(renderer, texture, nullptr, &destr);\r\n      SDL_DestroyTexture(texture);\r\n      SDL_FreeSurface(palettes);\r\n    }\r\n\r\n\r\n    {\r\n      /*\r\n      static SDL_Surface* tilemap = nullptr;\r\n\r\n      if (!tilemap)\r\n      {\r\n        tilemap = SDL_CreateRGBSurface(0, 1024, 512, 32, 0x00000000, 0x00ff0000, 0x0000ff00, 0x000000ff);\r\n        SDL_FillRect(tilemap, nullptr, 0x00000000);\r\n        uint32_t* base = static_cast<uint32_t*>(tilemap->pixels);\r\n        for (r8::coord_t ty = 0; ty < r8::gfx::TILE_MAP_HEIGHT; ++ty)\r\n        {\r\n          for (r8::coord_t tx = 0; tx < r8::gfx::TILE_MAP_WIDTH; ++tx)\r\n          {\r\n            r8::sprite_index_t index = *machine.memory().spriteInTileMap(tx, ty);\r\n\r\n            for (r8::coord_t y = 0; y < r8::gfx::SPRITE_HEIGHT; ++y)\r\n              for (r8::coord_t x = 0; x < r8::gfx::SPRITE_WIDTH; ++x)\r\n              {\r\n                auto* dest = base + x + tx * r8::gfx::SPRITE_WIDTH + (y + ty * r8::gfx::SPRITE_HEIGHT) * tilemap->h;\r\n                const r8::gfx::color_byte_t& pixels = machine.memory().spriteAt(index)->byteAt(x, y);\r\n                RASTERIZE_PIXEL_PAIR(machine, dest, &pixels);\r\n              }\r\n          }\r\n        }\r\n      }\r\n\r\n      Texture* texture = SDL_CreateTextureFromSurface(renderer, tilemap);\r\n      SDL_Rect destr = { (1024 - 286) , 256, 256, 128 };\r\n      SDL_RenderCopy(renderer, texture, nullptr, &destr);\r\n      SDL_DestroyTexture(texture);\r\n      SDL_FreeSurface(tilemap);*/\r\n    }\r\n\r\n  }\r\n#endif\r\n}\r\n\r\nvoid GameView::handleKeyboardEvent(const SDL_Event& event)\r\n{\r\n  switch (event.key.keysym.sym)\r\n  {\r\n  case KEY_LEFT:\r\n    _input.manageKey(0, 0, event.type == SDL_KEYDOWN);\r\n    break;\r\n  case KEY_RIGHT:\r\n    _input.manageKey(0, 1, event.type == SDL_KEYDOWN);\r\n    break;\r\n  case KEY_UP:\r\n    _input.manageKey(0, 2, event.type == SDL_KEYDOWN);\r\n    break;\r\n  case KEY_DOWN:\r\n    _input.manageKey(0, 3, event.type == SDL_KEYDOWN);\r\n    break;\r\n\r\n  case KEY_ACTION1_1:\r\n    _input.manageKey(0, 4, event.type == SDL_KEYDOWN);\r\n    break;\r\n\r\n  case KEY_ACTION1_2:\r\n    _input.manageKey(0, 5, event.type == SDL_KEYDOWN);\r\n    break;\r\n\r\n  case KEY_ACTION2_1:\r\n    _input.manageKey(1, 4, event.type == SDL_KEYDOWN);\r\n    break;\r\n\r\n  case KEY_ACTION2_2:\r\n    _input.manageKey(1, 5, event.type == SDL_KEYDOWN);\r\n    break;\r\n\r\n  case KEY_MUTE:\r\n  {\r\n    if (event.type == SDL_KEYDOWN)\r\n    {\r\n      bool s = machine.sound().isMusicEnabled();\r\n      machine.sound().toggleMusic(!s);\r\n      machine.sound().toggleSound(!s);\r\n    }\r\n    break;\r\n  }\r\n\r\n  case KEY_PAUSE:\r\n    if (event.type == SDL_KEYDOWN)\r\n      if (_paused)\r\n        pause();\r\n      else\r\n        resume();\r\n    break;\r\n\r\n  case KEY_NEXT_SCALER:\r\n    if (event.type == SDL_KEYDOWN)\r\n    {\r\n      if (_scaler < Scaler::LAST) _scaler = Scaler(_scaler + 1);\r\n      else _scaler = Scaler::FIRST;\r\n  }\r\n    break;\r\n\r\n  case KEY_MENU:\r\n    manager->openMenu();\r\n    break;\r\n\r\n  case KEY_EXIT:\r\n    if (event.type == SDL_KEYDOWN)\r\n      manager->exit();\r\n    break;\r\n\r\n  default:\r\n    break;\r\n}\r\n}\r\n\r\nvoid GameView::handleMouseEvent(const SDL_Event& event)\r\n{\r\n\r\n}\r\n\r\nvoid GameView::pause()\r\n{\r\n  _paused = true;\r\n\r\n#if SOUND_ENABLED\r\n  sdlAudio.pause();\r\n#endif\r\n}\r\n\r\nvoid GameView::resume()\r\n{\r\n  _paused = false;\r\n\r\n#if SOUND_ENABLED\r\n  sdlAudio.resume();\r\n#endif\r\n}\r\n\r\nGameView::~GameView()\r\n{\r\n  _output.release();\r\n  //TODO: the _init future is not destroyed\r\n  sdlAudio.close();\r\n}\r\n\r\n\r\nuint32_t Platform::getTicks() { return SDL_GetTicks(); }\r\n"
  },
  {
    "path": "src/views/main_view.h",
    "content": "#pragma once\r\n\r\n#include \"view_manager.h\"\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <streambuf>\r\n#include <future>\r\n\r\n#include \"lua/lua.hpp\"\r\n\r\n#include \"vm/machine.h\"\r\n#include \"vm/input.h\"\r\n#include \"vm/lua_bridge.h\"\r\n\r\nnamespace ui\r\n{\r\n  enum Scaler\r\n  {\r\n    UNSCALED = 0,\r\n    SCALED_ASPECT_2x,\r\n    FULLSCREEN,\r\n\r\n    FIRST = UNSCALED,\r\n    LAST = FULLSCREEN\r\n  };\r\n\r\n  class GameView : public View\r\n  {\r\n  private:\r\n    uint32_t _frameCounter;\r\n    Scaler _scaler = Scaler::UNSCALED;\r\n\r\n    ViewManager* manager;\r\n\r\n    retro8::input::InputManager _input;\r\n\r\n    Surface _output;\r\n\r\n    std::string _path;\r\n\r\n    std::future<void> _initFuture;\r\n\r\n    bool _paused;\r\n\r\n    bool _showFPS;\r\n    bool _showCartridgeName;\r\n\r\n    void rasterize();\r\n    void render();\r\n    void update();\r\n\r\n  public:\r\n    GameView(ViewManager* manager);\r\n    ~GameView();\r\n\r\n    void handleKeyboardEvent(const SDL_Event& event);\r\n    void handleMouseEvent(const SDL_Event& event);\r\n\r\n    void loadCartridge(const std::string& path) { _path = path; }\r\n\r\n    void pause();\r\n    void resume();\r\n\r\n    void setScaler(Scaler scaler) { _scaler = scaler; }\r\n    Scaler scaler() const { return _scaler; }\r\n\r\n    void toggleFPS(bool active) { _showFPS = active; }\r\n    bool isFPSShown() { return _showFPS; }\r\n  };\r\n\r\n  class MenuView : public View\r\n  {\r\n  private:\r\n    ViewManager* _gvm;\r\n    Surface _cartridge;\r\n\r\n  public:\r\n    MenuView(ViewManager* manager);\r\n    ~MenuView();\r\n\r\n    void handleKeyboardEvent(const SDL_Event& event) override;\r\n    void handleMouseEvent(const SDL_Event& event) override;\r\n    \r\n    void render() override;\r\n\r\n    void reset();\r\n    void updateLabels();\r\n\r\n    void setPngCartridge(SDL_Surface* cartridge);\r\n  };\r\n}\r\n"
  },
  {
    "path": "src/views/menu_view.cpp",
    "content": "#include \"main_view.h\"\r\n\r\nextern retro8::Machine machine;\r\n\r\nusing namespace ui;\r\n\r\nstruct MenuEntry\r\n{\r\n  mutable std::string caption;\r\n  mutable std::function<void(void)> lambda;\r\n\r\n  MenuEntry(const std::string& caption) : caption(caption) { }\r\n};\r\n\r\nstatic const std::vector<MenuEntry> mainMenu = {\r\n  MenuEntry(\"resume\"),\r\n  MenuEntry(\"help\"),\r\n  MenuEntry(\"options\"),\r\n  MenuEntry(\"reset\"),\r\n  MenuEntry(\"exit\")\r\n};\r\n\r\nstatic const std::vector<MenuEntry> optionsMenu = {\r\n  MenuEntry(\"show fps\"),\r\n  MenuEntry(\"scaler 1:1\"),\r\n  MenuEntry(\"sound on\"),\r\n  MenuEntry(\"music on\"),\r\n  MenuEntry(\"back\")\r\n};\r\n\r\nconst std::vector<MenuEntry>* menu;\r\nstd::vector<MenuEntry>::const_iterator selected;\r\n\r\nenum { RESUME = 0, HELP, OPTIONS, RESET, EXIT, SHOW_FPS = 0, SCALER, SOUND, MUSIC, BACK };\r\n\r\nMenuView::MenuView(ViewManager* gvm) : _gvm(gvm), _cartridge(nullptr)\r\n{\r\n  static_assert(SCALER == 1, \"must be 1\");\r\n\r\n  mainMenu[RESUME].lambda = [this]() {\r\n    _gvm->backToGame();\r\n  };\r\n\r\n  mainMenu[OPTIONS].lambda = [this]() {\r\n    menu = &optionsMenu;\r\n    selected = menu->begin();\r\n  };\r\n\r\n  mainMenu[EXIT].lambda = [this]() {\r\n    _gvm->exit();\r\n  };\r\n\r\n  optionsMenu[SHOW_FPS].lambda = [this]() {\r\n    bool v = !_gvm->gameView()->isFPSShown();\r\n    _gvm->gameView()->toggleFPS(v);\r\n    updateLabels();\r\n  };\r\n  optionsMenu[SCALER].lambda = [this]() {\r\n    auto scaler = _gvm->gameView()->scaler();\r\n    if (scaler < Scaler::LAST)\r\n      _gvm->gameView()->setScaler(Scaler(scaler + 1));\r\n    else\r\n      _gvm->gameView()->setScaler(Scaler::FIRST);\r\n    updateLabels();\r\n  };\r\n\r\n  optionsMenu[SOUND].lambda = [this]() {\r\n    bool v = !machine.sound().isSoundEnabled();\r\n    machine.sound().toggleSound(v);\r\n    updateLabels();\r\n  };\r\n\r\n\r\n  optionsMenu[MUSIC].lambda = [this]() {\r\n    bool v = !machine.sound().isMusicEnabled();\r\n    machine.sound().toggleMusic(v);\r\n    updateLabels();\r\n  };\r\n\r\n  optionsMenu[BACK].lambda = [this]() {\r\n    menu = &mainMenu;\r\n    selected = menu->begin();\r\n  };\r\n\r\n  reset();\r\n}\r\n\r\nMenuView::~MenuView() { }\r\n\r\nvoid MenuView::handleKeyboardEvent(const SDL_Event& event)\r\n{\r\n  static constexpr auto ACTION_BUTTON = KEY_ACTION1_1;\r\n  static constexpr auto BACK_BUTTON = KEY_ACTION1_2;\r\n\r\n  if (event.type == SDL_KEYDOWN)\r\n  {\r\n    switch (event.key.keysym.sym)\r\n    {\r\n    case KEY_UP: if (selected > menu->begin()) --selected; else selected = menu->end() - 1; break;\r\n    case KEY_DOWN: if (selected < menu->end() - 1) ++selected; else selected = menu->begin(); break;\r\n    case ACTION_BUTTON:\r\n    {\r\n      if (selected->lambda)\r\n        selected->lambda();\r\n      break;\r\n    }\r\n    case BACK_BUTTON:\r\n    {\r\n      if (menu == &mainMenu)\r\n        mainMenu[0].lambda();\r\n      else if (menu == &optionsMenu)\r\n        optionsMenu[4].lambda();\r\n      break;\r\n    }\r\n    }\r\n  }\r\n}\r\n\r\nvoid MenuView::handleMouseEvent(const SDL_Event& event)\r\n{\r\n\r\n}\r\n\r\nvoid MenuView::updateLabels()\r\n{\r\n  optionsMenu[MUSIC].caption = std::string(\"music \") + (machine.sound().isMusicEnabled() ? \"on\" : \"off\");\r\n  optionsMenu[SOUND].caption = std::string(\"sound \") + (machine.sound().isSoundEnabled() ? \"on\" : \"off\");\r\n  optionsMenu[SHOW_FPS].caption = std::string(\"show fps \") + (_gvm->gameView()->isFPSShown() ? \"on\" : \"off\");\r\n\r\n  auto scaler = _gvm->gameView()->scaler();\r\n  std::string scalerLabel = \"scaler \";\r\n  switch (scaler) {\r\n  case Scaler::UNSCALED: scalerLabel += \"1:1\"; break;\r\n  case Scaler::SCALED_ASPECT_2x: scalerLabel += \"2:1\"; break;\r\n  case Scaler::FULLSCREEN: scalerLabel += \"fit screen\"; break;\r\n  }\r\n\r\n  optionsMenu[SCALER].caption = scalerLabel;\r\n}\r\n\r\nvoid MenuView::reset()\r\n{\r\n  menu = &mainMenu;\r\n  selected = menu->begin();\r\n\r\n  updateLabels();\r\n}\r\n\r\nvoid MenuView::render()\r\n{\r\n  constexpr int32_t W = SCREEN_WIDTH;\r\n  constexpr int32_t H = SCREEN_HEIGHT;\r\n\r\n  _gvm->clear(0, 0, 0);\r\n  _gvm->rect(0, 0, W, H, 20, 20, 40, 255);\r\n\r\n  bool hasCartridge = _cartridge;\r\n\r\n  // 160x205\r\n\r\n  if (hasCartridge)\r\n    _gvm->blit(_cartridge, W/2 - 5, (240 - 205)/2);\r\n\r\n  const int32_t bx = hasCartridge ? W / 4 : W / 2;\r\n  const int32_t by = 24;\r\n\r\n  _gvm->text(\"retro8\", bx + 2, by + 2, { 0, 22, 120 }, TextAlign::CENTER, 4.0f);\r\n  _gvm->text(\"retro8\", bx, by, { 0, 47, 255 }, TextAlign::CENTER, 4.0f);\r\n  _gvm->text(\"v0.1b\", bx + _gvm->textWidth(\"retro8\", 4.0)/2 - _gvm->textWidth(\"v0.1b\", 1.0), by + 24, { 0, 47, 255 }, TextAlign::LEFT, 1.0f);\r\n\r\n  retro8::point_t menuBase = { bx, by + 70 };\r\n\r\n  for (auto it = menu->begin(); it != menu->end(); ++it)\r\n  {\r\n    SDL_Color color = it == selected ? SDL_Color{ 255, 255, 0 } : SDL_Color{ 255,255,255 };\r\n\r\n    if (it != selected && !it->lambda)\r\n      color = { 160, 160, 160 };\r\n\r\n    _gvm->text(it->caption, menuBase.x, menuBase.y, color, TextAlign::CENTER, 2.0f);\r\n    menuBase.y += 16;\r\n  }\r\n}\r\n\r\nvoid MenuView::setPngCartridge(SDL_Surface* cartridge)\r\n{\r\n#if !defined(SDL12)\r\n  if (_cartridge)\r\n    _cartridge.release();\r\n\r\n  if (cartridge)\r\n    _cartridge = Surface(cartridge, SDL_CreateTextureFromSurface(_gvm->renderer(), cartridge));\r\n  else\r\n    _cartridge = Surface(nullptr);   \r\n#else\r\n  _cartridge = nullptr;\r\n#endif\r\n}"
  },
  {
    "path": "src/views/sdl_helper.h",
    "content": "#pragma once\r\n\r\n#include \"common.h\"\r\n\r\n#include \"SDL.h\"\r\n\r\n#include <cstdint>\r\n#include <cstdio>\r\n#include <cassert>\r\n\r\n#if SDL_COMPILEDVERSION > 2000\r\n\r\nstruct Surface\r\n{\r\n  SDL_Surface* surface;\r\n  SDL_Texture* texture;\r\n\r\n  Surface(SDL_Surface* surface) : surface(surface) { }\r\n  Surface(SDL_Surface* surface, SDL_Texture* texture) : surface(surface), texture(texture) { }\r\n\r\n  Surface() : surface(nullptr), texture(nullptr) { }\r\n\r\n  operator bool() const { return surface != nullptr; }\r\n\r\n  void enableBlending() { assert(texture); SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); }\r\n  void releaseSurface() { if (surface) SDL_FreeSurface(surface); surface = nullptr; }\r\n\r\n  void release()\r\n  {\r\n    releaseSurface();\r\n    SDL_DestroyTexture(texture);\r\n    texture = nullptr;\r\n  }\r\n\r\n  void update() { SDL_UpdateTexture(texture, nullptr, surface->pixels, surface->pitch); }\r\n  inline uint32_t& pixel(size_t index) { return pixels()[index]; }\r\n  inline uint32_t* pixels() { return static_cast<uint32_t*>(surface->pixels); }\r\n};\r\n\r\n#if _WIN32\r\n  #define DEBUGGER false\r\n#endif\r\n\r\n#else\r\n\r\nstruct Surface\r\n{\r\n  SDL_Surface* surface;\r\n\r\n  Surface() : surface(nullptr) { }\r\n  Surface(SDL_Surface* surface) : surface(surface) { }\r\n\r\n  operator bool() const { return surface != nullptr; }\r\n\r\n  void enableBlending() { assert(surface); SDL_SetAlpha(surface, SDL_SRCALPHA, 0); }\r\n  void releaseSurface() {  }\r\n\r\n  void release()\r\n  {\r\n    assert(surface);\r\n    SDL_FreeSurface(surface);\r\n    surface = nullptr;\r\n  }\r\n\r\n  void update() { }\r\n  inline uint32_t& pixel(size_t index) { return pixels()[index]; }\r\n  inline uint32_t* pixels() { return static_cast<uint32_t*>(surface->pixels); }\r\n};\r\n\r\n#define SDL12\r\n\r\nusing SDL_Renderer = int;\r\nusing SDL_Window = int;\r\nusing SDL_AudioDeviceID = int;\r\n#define SDL_OpenAudioDevice(x, y, w, s, z) SDL_OpenAudio(w, s)\r\n#define SDL_PauseAudioDevice(_,y) SDL_PauseAudio(y)\r\n#define SDL_CloseAudioDevice(_) SDL_CloseAudio()\r\n\r\n#endif\r\n\r\nenum class Align { LEFT, CENTER, RIGHT };\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nclass SDL\r\n{\r\nprotected:\r\n  EventHandler& eventHandler;\r\n  Renderer& loopRenderer;\r\n\r\n  SDL_PixelFormat* _format;\r\n  SDL_Surface* _screen;\r\n  SDL_Window* _window;\r\n  SDL_Renderer* _renderer;\r\n\r\n  bool willQuit;\r\n  u32 ticks;\r\n  float _lastFrameTicks;\r\n\r\n  u32 frameRate;\r\n  float ticksPerFrame;\r\n\r\n\r\npublic:\r\n  SDL(EventHandler& eventHandler, Renderer& loopRenderer) : eventHandler(eventHandler), loopRenderer(loopRenderer),\r\n    _screen(nullptr), _window(nullptr), _renderer(nullptr), willQuit(false), ticks(0)\r\n  {\r\n    setFrameRate(60);\r\n  }\r\n\r\n  Surface allocate(int width, int height);\r\n\r\n  const SDL_PixelFormat* displayFormat() { return _format; }\r\n\r\n  void setFrameRate(u32 frameRate)\r\n  {\r\n    this->frameRate = frameRate;\r\n    this->ticksPerFrame = 1000 / (float)frameRate;\r\n  }\r\n\r\n  float lastFrameTicks() const { return _lastFrameTicks; }\r\n\r\n  bool init();\r\n  void deinit();\r\n  void capFPS();\r\n\r\n  void loop();\r\n  void handleEvents();\r\n\r\n  void exit() { willQuit = true; }\r\n\r\n  void blit(const Surface& texture, const SDL_Rect& src, const SDL_Rect& dest);\r\n  void blit(const Surface& texture, const SDL_Rect& src, int dx, int dy);\r\n  void blit(const Surface& texture, int sx, int sy, int w, int h, int dx, int dy);\r\n  void blit(const Surface& texture, int sx, int sy, int w, int h, int dx, int dy, int dw, int dh);\r\n  void blit(const Surface& texture, int dx, int dy);\r\n  void blitToScreen(const Surface& texture, const SDL_Rect& rect);\r\n\r\n  void clear(int r, int g, int b);\r\n  void rect(int x, int y, int w, int h, int r, int g, int b, int a);\r\n\r\n  void release(const Surface& texture);\r\n\r\n  SDL_Window* window() { return _window; }\r\n  SDL_Renderer* renderer() { return _renderer; }\r\n};\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nvoid SDL<EventHandler, Renderer>::capFPS()\r\n{\r\n  u32 ticks = SDL_GetTicks();\r\n  u32 elapsed = ticks - SDL::ticks;\r\n\r\n  _lastFrameTicks = elapsed;\r\n\r\n  if (elapsed < ticksPerFrame)\r\n  {\r\n    SDL_Delay(ticksPerFrame - elapsed);\r\n    _lastFrameTicks = ticksPerFrame;\r\n  }\r\n\r\n  SDL::ticks = SDL_GetTicks();\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nvoid SDL<EventHandler, Renderer>::handleEvents()\r\n{\r\n  SDL_Event event;\r\n  while (SDL_PollEvent(&event))\r\n  {\r\n    switch (event.type)\r\n    {\r\n    case SDL_QUIT:\r\n      willQuit = true;\r\n      break;\r\n\r\n    case SDL_KEYDOWN:\r\n    case SDL_KEYUP:\r\n#if !defined(SDL12)\r\n      if (!event.key.repeat)\r\n#endif\r\n        eventHandler.handleKeyboardEvent(event);\r\n      break;\r\n\r\n#if MOUSE_ENABLED\r\n    case SDL_MOUSEBUTTONDOWN:\r\n    case SDL_MOUSEBUTTONUP:\r\n#if defined(WINDOW_SCALE)\r\n      event.button.x /= WINDOW_SCALE;\r\n      event.button.y /= WINDOW_SCALE;\r\n#endif\r\n      eventHandler.handleMouseEvent(event);\r\n#endif\r\n    }\r\n  }\r\n}\r\n\r\n#if defined(SDL12)\r\n#include \"sdl_impl12.h\"\r\n#else\r\n#include \"sdl_impl.h\"\r\n#endif"
  },
  {
    "path": "src/views/sdl_impl.h",
    "content": "#pragma once\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nbool SDL<EventHandler, Renderer>::init()\r\n{\r\n  if (SDL_Init(SDL_INIT_EVERYTHING))\r\n  {\r\n    LOGD(\"Error on SDL_Init().\\n\");\r\n    return false;\r\n  }\r\n\r\n  // SDL_WINDOW_FULLSCREEN\r\n#if defined(WINDOW_SCALE)\r\n#if defined(DEBUGGER)\r\n  _window = SDL_CreateWindow(\"retro-8\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH*3, SCREEN_WIDTH*2, SDL_WINDOW_OPENGL);\r\n#else\r\n  _window = SDL_CreateWindow(\"retro-8\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH*2, SCREEN_HEIGHT*2, SDL_WINDOW_OPENGL);\r\n#endif\r\n#else\r\n  _window = SDL_CreateWindow(\"retro-8\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL);\r\n#endif\r\n  _renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED);\r\n\r\n  SDL_RendererInfo info;\r\n  SDL_GetRendererInfo(_renderer, &info);\r\n  _format = SDL_AllocFormat(info.texture_formats[0]);\r\n\r\n  return true;\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nvoid SDL<EventHandler, Renderer>::loop()\r\n{\r\n  while (!willQuit)\r\n  {\r\n    loopRenderer.render();\r\n    SDL_RenderPresent(_renderer);\r\n\r\n    handleEvents();\r\n\r\n    capFPS();\r\n  }\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nvoid SDL<EventHandler, Renderer>::deinit()\r\n{\r\n  SDL_FreeFormat(_format);\r\n  SDL_DestroyRenderer(_renderer);\r\n  SDL_DestroyWindow(_window);\r\n\r\n  SDL_Quit();\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nSurface SDL<EventHandler, Renderer>::allocate(int width, int height)\r\n{\r\n  SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, 32, _format->Rmask, _format->Gmask, _format->Bmask, _format->Amask);\r\n  SDL_Texture* texture = SDL_CreateTexture(_renderer, _format->format, SDL_TEXTUREACCESS_STREAMING, width, width);\r\n  return { surface, texture };\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nvoid SDL<EventHandler, Renderer>::blitToScreen(const Surface& surface, const SDL_Rect& rect)\r\n{\r\n  SDL_RenderCopy(_renderer, surface.texture, nullptr, &rect);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::blit(const Surface& surface, int sx, int sy, int w, int h, int dx, int dy, int dw, int dh)\r\n{\r\n  SDL_Rect from = { sx, sy, w, h };\r\n  SDL_Rect to = { dx, dy, dw, dh };\r\n  SDL_RenderCopy(_renderer, surface.texture, &from, &to);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::blit(const Surface& surface, const SDL_Rect& from, int dx, int dy)\r\n{\r\n  SDL_Rect to = { dx, dy, from.w, from.h };\r\n  SDL_RenderCopy(_renderer, surface.texture, &from, &to);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::blit(const Surface& surface, const SDL_Rect& src, const SDL_Rect& dest)\r\n{\r\n  SDL_RenderCopy(_renderer, surface.texture, &src, &dest);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::blit(const Surface& surface, int sx, int sy, int w, int h, int dx, int dy)\r\n{\r\n  blit(surface, { sx, sy, w, h }, dx, dy);\r\n}\r\n\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::blit(const Surface& surface, int dx, int dy)\r\n{\r\n  u32 dummy;\r\n  int dummy2;\r\n\r\n  SDL_Rect from = { 0, 0, 0, 0 };\r\n  SDL_Rect to = { dx, dy, 0, 0 };\r\n\r\n  SDL_QueryTexture(surface.texture, &dummy, &dummy2, &from.w, &from.h);\r\n\r\n  to.w = from.w;\r\n  to.h = from.h;\r\n\r\n  SDL_RenderCopy(_renderer, surface.texture, &from, &to);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::clear(int r, int g, int b)\r\n{\r\n  SDL_SetRenderDrawColor(_renderer, r, g, b, 255);\r\n  SDL_RenderClear(_renderer);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::rect(int x, int y, int w, int h, int r, int g, int b, int a)\r\n{\r\n  SDL_SetRenderDrawColor(_renderer, r, g, b, a);\r\n  SDL_Rect border = { x, y, w, h };\r\n  SDL_RenderDrawRect(_renderer, &border);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::release(const Surface& surface)\r\n{\r\n  SDL_DestroyTexture(surface.texture);\r\n\r\n  if (surface.surface)\r\n    SDL_FreeSurface(surface.surface);\r\n}\r\n\r\ninline static SDL_Rect SDL_MakeRect(int x, int y, int w, int h) { return { x, y, w, h }; }\r\n\r\n"
  },
  {
    "path": "src/views/sdl_impl12.h",
    "content": "#if defined(SDL12)\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nbool SDL<EventHandler, Renderer>::init()\r\n{\r\n  if (SDL_Init(SDL_INIT_EVERYTHING))\r\n  {\r\n    LOGD(\"Error on SDL_Init().\\n\");\r\n    return false;\r\n  }\r\n\r\n  SDL_ShowCursor(0);\r\n  SDL_EnableKeyRepeat(0, 0);\r\n\r\n#if defined(WINDOW_SCALE)\r\n  _screen = SDL_SetVideoMode(SCREEN_WIDTH*2, SCREEN_HEIGHT*2, 32, SDL_HWSURFACE);\r\n  #else\r\n  _screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_HWSURFACE);\r\n#endif\r\n\r\n  _format = _screen->format;\r\n  SDL_WM_SetCaption(\"retro-8\", nullptr);\r\n\r\n  return true;\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nvoid SDL<EventHandler, Renderer>::loop()\r\n{\r\n  while (!willQuit)\r\n  {\r\n    loopRenderer.render();\r\n    SDL_Flip(_screen);\r\n\r\n    handleEvents();\r\n\r\n    capFPS();\r\n  }\r\n}\r\n\r\nstatic constexpr auto RES_HW_SCREEN_VERTICAL = 240;\r\nstatic constexpr auto RES_HW_SCREEN_HORIZONTAL = 240;\r\n\r\nstatic void scale_NN_AllowOutOfScreen(SDL_Surface *src_surface, SDL_Surface *dst_surface, int new_w, int new_h)\r\n{\r\n\r\n  /// Sanity check\r\n  if (src_surface->format->BytesPerPixel != dst_surface->format->BytesPerPixel) {\r\n    printf(\"Error in %s, src_surface bpp: %d != dst_surface bpp: %d\", __func__,\r\n      src_surface->format->BytesPerPixel, dst_surface->format->BytesPerPixel);\r\n    return;\r\n  }\r\n\r\n  int BytesPerPixel = src_surface->format->BytesPerPixel;\r\n  int w1 = src_surface->w;\r\n  //int h1=src_surface->h;\r\n  int w2 = new_w;\r\n  int h2 = new_h;\r\n  int x_ratio = (int)((src_surface->w << 16) / w2);\r\n  int y_ratio = (int)((src_surface->h << 16) / h2);\r\n  int x2, y2;\r\n\r\n  /// --- Compute padding for centering when out of bounds ---\r\n  int y_padding = (RES_HW_SCREEN_VERTICAL - new_h) / 2;\r\n  int x_padding = 0;\r\n  if (w2 > RES_HW_SCREEN_HORIZONTAL) {\r\n    x_padding = (w2 - RES_HW_SCREEN_HORIZONTAL) / 2 + 1;\r\n  }\r\n  int x_padding_ratio = x_padding * w1 / w2;\r\n  //printf(\"src_surface->h=%d, h2=%d\\n\", src_surface->h, h2);\r\n\r\n  for (int i = 0; i < h2; i++)\r\n  {\r\n    if (i >= RES_HW_SCREEN_VERTICAL) {\r\n      continue;\r\n    }\r\n\r\n    uint8_t* t = (uint8_t*)(dst_surface->pixels) + ((i + y_padding) * ((w2 > RES_HW_SCREEN_HORIZONTAL) ? RES_HW_SCREEN_HORIZONTAL : w2))*BytesPerPixel;\r\n    y2 = ((i*y_ratio) >> 16);\r\n    uint8_t* p = (uint8_t*)(src_surface->pixels) + (y2*w1 + x_padding_ratio)*BytesPerPixel;\r\n    int rat = 0;\r\n    for (int j = 0; j < w2; j++)\r\n    {\r\n      if (j >= RES_HW_SCREEN_HORIZONTAL) {\r\n        continue;\r\n      }\r\n      x2 = (rat >> 16);\r\n      //*t++ = p[x2];\r\n      memcpy(t, &p[x2*BytesPerPixel], BytesPerPixel);\r\n      t += BytesPerPixel;\r\n      rat += x_ratio;\r\n    }\r\n  }\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nvoid SDL<EventHandler, Renderer>::blitToScreen(const Surface& surface, const SDL_Rect& rect)\r\n{\r\n#if PLATFORM == PLATFORM_FUNKEY\r\n  scale_NN_AllowOutOfScreen(surface.surface, _screen, 256, 256);\r\n#else\r\n  SDL_BlitSurface(surface.surface, nullptr, _screen, const_cast<SDL_Rect*>(&rect));\r\n#endif\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nvoid SDL<EventHandler, Renderer>::deinit()\r\n{\r\n  SDL_FreeSurface(_screen);\r\n  SDL_Quit();\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\nSurface SDL<EventHandler, Renderer>::allocate(int width, int height)\r\n{\r\n  SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, 32, _format->Rmask, _format->Gmask, _format->Bmask, _format->Amask);\r\n  return { surface };\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::blit(const Surface& surface, int sx, int sy, int w, int h, int dx, int dy, int dw, int dh)\r\n{\r\n  SDL_Rect from = { sx, sy, w, h };\r\n  SDL_Rect to = { dx, dy, dw, dh };\r\n  SDL_BlitSurface(surface.surface, &from, _screen, &to);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::blit(const Surface& surface, const SDL_Rect& from, int dx, int dy)\r\n{\r\n  SDL_Rect to = { dx, dy, from.w, from.h };\r\n  SDL_BlitSurface(surface.surface, &from, _screen, &to);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::blit(const Surface& surface, int sx, int sy, int w, int h, int dx, int dy)\r\n{\r\n  blit(surface, { sx, sy, w, h }, dx, dy);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::blit(const Surface& surface, const SDL_Rect& src, const SDL_Rect& dest)\r\n{\r\n  SDL_BlitSurface(surface.surface, const_cast<SDL_Rect*>(&src), _screen, const_cast<SDL_Rect*>(&dest));\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::blit(const Surface& surface, int dx, int dy)\r\n{\r\n  blit(surface.surface, 0, 0, surface.surface->w, surface.surface->h, 0, 0, surface.surface->w, surface.surface->h);\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::clear(int r, int g, int b)\r\n{\r\n  SDL_Rect to = { 0, 0, _screen->w, _screen->h };\r\n  SDL_FillRect(_screen, &to, SDL_MapRGB(_screen->format, r, g, b));\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::rect(int x, int y, int w, int h, int r, int g, int b, int a)\r\n{\r\n  //TODO: implement\r\n  /*SDL_SetRenderDrawColor(_renderer, r, g, b, a);\r\n  SDL_Rect border = { x, y, w, h };\r\n  SDL_RenderDrawRect(_renderer, &border);*/\r\n}\r\n\r\ntemplate<typename EventHandler, typename Renderer>\r\ninline void SDL<EventHandler, Renderer>::release(const Surface& surface)\r\n{\r\n  SDL_FreeSurface(surface.surface);\r\n}\r\n\r\n\r\ninline static SDL_Rect SDL_MakeRect(int x, int y, int w, int h) { return { (Sint16)x, (Sint16)y, (Uint16)w, (Uint16)h }; }\r\n\r\n#endif\r\n"
  },
  {
    "path": "src/views/view_manager.cpp",
    "content": "#include \"view_manager.h\"\r\n\r\n#include \"main_view.h\"\r\n#include \"gen/pico_font.h\"\r\n\r\n#ifdef _WIN32\r\n#define PREFIX  \"../../../\"\r\n#else\r\n#define PREFIX \"\"\r\n#endif\r\n\r\nusing namespace ui;\r\n\r\nextern retro8::Machine machine;\r\n\r\nui::ViewManager::ViewManager() : SDL<ui::ViewManager, ui::ViewManager>(*this, *this), _font(),\r\n_gameView(new GameView(this)), _menuView(new MenuView(this))\r\n{\r\n  _view = _gameView;\r\n}\r\n\r\nvoid ui::ViewManager::deinit()\r\n{\r\n  _font.release();\r\n  SDL::deinit();\r\n}\r\n\r\nbool ui::ViewManager::loadData()\r\n{\r\n  {\r\n    constexpr size_t FONT_WIDTH = 128, FONT_HEIGHT = 80;\r\n\r\n    /* create texture for font 128x80 1bit per pixel font */\r\n    const SDL_PixelFormat* format = displayFormat();\r\n\r\n    _font = allocate(FONT_WIDTH, FONT_HEIGHT);\r\n    \r\n    for (size_t i = 0; i < FONT_WIDTH*FONT_HEIGHT; ++i)\r\n      _font.pixel(i) = (retro8::gfx::font_map[i / 8] & (1 << (7 - (i % 8)))) ? 0xffffffff : 0;\r\n\r\n#if !defined(SDL12)\r\n    _font.texture = SDL_CreateTextureFromSurface(renderer(), _font.surface);\r\n#endif\r\n\r\n    _font.enableBlending();\r\n    _font.releaseSurface();\r\n  }\r\n\r\n  machine.font().load();\r\n\r\n  return true;\r\n}\r\n\r\nvoid ui::ViewManager::handleKeyboardEvent(const SDL_Event& event)\r\n{\r\n  _view->handleKeyboardEvent(event);\r\n}\r\n\r\nvoid ui::ViewManager::handleMouseEvent(const SDL_Event& event)\r\n{\r\n  _view->handleMouseEvent(event);\r\n}\r\n\r\n\r\nvoid ui::ViewManager::render()\r\n{\r\n  _view->render();\r\n}\r\n\r\nvoid ui::ViewManager::text(const std::string& text, int32_t x, int32_t y)\r\n{\r\n  constexpr float scale = 2.0;\r\n  constexpr int32_t GLYPHS_PER_ROW = 16;\r\n\r\n  for (size_t i = 0; i < text.length(); ++i)\r\n  {\r\n    SDL_Rect src = SDL_MakeRect(8 * (text[i] % GLYPHS_PER_ROW), 8 * (text[i] / GLYPHS_PER_ROW), 4, 6);\r\n    SDL_Rect dest = SDL_MakeRect(x + 4 * i * scale, y, 4 * scale, 6 * scale);\r\n    blit(_font, src, dest);\r\n  }\r\n}\r\n\r\nvoid ViewManager::text(const std::string& text, int32_t x, int32_t y, SDL_Color color, TextAlign align, float scale)\r\n{\r\n  constexpr int32_t GLYPHS_PER_ROW = 16;\r\n\r\n  const int32_t width = text.size() * 4 * scale;\r\n\r\n  if (align == TextAlign::CENTER)\r\n    x -= width / 2;\r\n  else if (align == TextAlign::RIGHT)\r\n    x -= width;\r\n\r\n#if !defined(SDL12)\r\n  SDL_SetTextureColorMod(_font.texture, color.r, color.g, color.b);\r\n#endif\r\n\r\n  for (size_t i = 0; i < text.length(); ++i)\r\n  {\r\n    SDL_Rect src = SDL_MakeRect(8 * (text[i] % GLYPHS_PER_ROW), 8 * (text[i] / GLYPHS_PER_ROW), 4, 6);\r\n    SDL_Rect dest = SDL_MakeRect(x + 4 * i * scale, y, 4 * scale, 6 * scale);\r\n    blit(_font, src, dest);\r\n  }\r\n\r\n#if !defined(SDL12)\r\n  SDL_SetTextureColorMod(_font.texture, 255, 255, 255);\r\n#endif\r\n}\r\n\r\nvoid ViewManager::openMenu()\r\n{\r\n  _gameView->pause();\r\n  _menuView->reset();\r\n  _view = _menuView;\r\n}\r\n\r\nvoid ViewManager::backToGame()\r\n{\r\n  _gameView->resume();\r\n  _view = _gameView;\r\n}\r\n\r\nvoid ViewManager::setPngCartridge(SDL_Surface* cartridge)\r\n{\r\n  _menuView->setPngCartridge(cartridge);\r\n}\r\n"
  },
  {
    "path": "src/views/view_manager.h",
    "content": "#pragma once\r\n\r\n#include \"sdl_helper.h\"\r\n\r\n#include <array>\r\n#include <string>\r\n\r\nnamespace ui\r\n{\r\n  class View\r\n  {\r\n  public:\r\n    virtual void render() = 0;\r\n    virtual void handleKeyboardEvent(const SDL_Event& event) = 0;\r\n    virtual void handleMouseEvent(const SDL_Event& event) = 0;\r\n  };\r\n\r\n  enum TextAlign\r\n  {\r\n    LEFT, CENTER, RIGHT\r\n  };\r\n\r\n  class GameView;\r\n  class MenuView;\r\n\r\n  class ViewManager : public SDL<ViewManager, ViewManager>\r\n  {\r\n  public:\r\n    using view_t = View;\r\n    static const size_t VIEW_COUNT = 1;\r\n\r\n    Surface _font;\r\n\r\n  private:\r\n    GameView* _gameView;\r\n    MenuView* _menuView;\r\n    view_t* _view;\r\n\r\n  public:\r\n    ViewManager();\r\n\r\n    bool loadData();\r\n\r\n    void handleKeyboardEvent(const SDL_Event& event);\r\n    void handleMouseEvent(const SDL_Event& event);\r\n    void render();\r\n\r\n    void deinit();\r\n\r\n    const Surface& font() { return _font; }\r\n\r\n    //TODO: hacky cast to avoid header inclusion\r\n    GameView* gameView() { return _gameView; }\r\n\r\n    int32_t textWidth(const std::string& text, float scale = 2.0f) const { return text.length() * scale * 4; }\r\n    void text(const std::string& text, int32_t x, int32_t y, SDL_Color color, TextAlign align, float scale = 2.0f);\r\n    void text(const std::string& text, int32_t x, int32_t y);\r\n\r\n    void openMenu();\r\n    void backToGame();\r\n\r\n    void setPngCartridge(SDL_Surface* cartridge);\r\n  };\r\n}\r\n\r\n"
  },
  {
    "path": "src/vm/defines.h",
    "content": "#pragma once\n\n#include <array>\n#include <cstddef>\n#include <cstdint>\n\nnamespace retro8\n{\n  enum color_t : uint8_t\n  {\n    BLACK, DARK_BLUE, DARK_PURPLE, DARK_GREEN,\n    BROWN, DARK_GREY, LIGHT_GREY, WHITE,\n    RED, ORANGE, YELLOW, GREEN,\n    BLUE, INDIGO, PINK, PEACH\n  };\n\n  enum class button_t\n  {\n    LEFT    = 0x0001,\n    RIGHT   = 0x0002,\n    UP      = 0x0004,\n    DOWN    = 0x0008,\n    ACTION1 = 0x0010,\n    ACTION2 = 0x0020,\n  };\n\n  static constexpr size_t BUTTON_COUNT = 6;\n  static constexpr size_t PLAYER_COUNT = 2;\n\n  using coord_t = int32_t;\n  using amount_t = int32_t;\n  using index_t = uint32_t;\n  using sprite_index_t = uint8_t;\n  using sprite_flags_t = uint8_t;\n  using integral_t = int32_t;\n  using color_index_t = uint8_t;\n  using palette_index_t = size_t;\n  using address_t = int32_t;\n  struct point_t { coord_t x, y; };\n\n  static constexpr coord_t TEXT_LINE_HEIGHT = 6;\n}\n\n#define RASTERIZE_PIXEL_PAIR(machine, dest, pixels) do { \\\n  auto* screenPalette = (machine).memory().paletteAt(retro8::gfx::SCREEN_PALETTE_INDEX); \\\n  const auto rc1 = colorTable.get(screenPalette->get((pixels)->low())); \\\n  const auto rc2 = colorTable.get(screenPalette->get((pixels)->high())); \\\n\\\n  *(dest) = rc1; \\\n  *((dest)+1) = rc2; \\\n  (dest) += 2; \\\n  } \\\n  while (false)\n"
  },
  {
    "path": "src/vm/gfx.cpp",
    "content": "#include \"gfx.h\"\n\n#include \"gen/pico_font.h\"\n\n\nusing namespace retro8;\nusing namespace retro8::gfx;\n\nvoid Font::load()\n{\n  // 128 x 80 bitmap (1 bit per pixel)\n\n  constexpr size_t BITS_PER_BYTE = 8;\n  constexpr size_t BYTES_PER_SPRITE = SPRITE_WIDTH * SPRITE_HEIGHT / 8;\n  constexpr size_t TOTAL_BYTES = FONT_GLYPHS_COLUMNS * FONT_GLYPHS_ROWS * BYTES_PER_SPRITE;\n  constexpr size_t BYTES_PER_ROW = FONT_GLYPHS_COLUMNS * BYTES_PER_SPRITE;\n  \n  static_assert(TOTAL_BYTES == sizeof(font_map) / sizeof(font_map[0]), \"Must be equal\");\n  static_assert(BYTES_PER_ROW == 128, \"\");\n  \n  for (size_t i = 0; i < TOTAL_BYTES; ++i)\n  {\n    const size_t row = i / BYTES_PER_ROW;\n    const size_t col = i % FONT_GLYPHS_COLUMNS;\n    const size_t index = row * FONT_GLYPHS_COLUMNS + col;\n    const size_t y = (i - (row * BYTES_PER_ROW)) / FONT_GLYPHS_COLUMNS;\n\n    const auto byte = font_map[i];\n    sequential_sprite_t& glyph = glyphs[index];\n    \n    for (size_t j = 0; j < BITS_PER_BYTE; ++j)\n    {\n      const bool s = (byte & (1 << (BITS_PER_BYTE - j - 1))) != 0;\n      const size_t x = ((i * BITS_PER_BYTE) + j) % 8;\n\n      glyph.set(x, y, s ? color_t::WHITE : color_t::BLACK);\n    }\n  }\n}\n\nvoid Font::load(const uint8_t* data)\n{\n  //assert(surface->w == SPRITE_WIDTH * FONT_GLYPHS_COLUMNS && surface->h == SPRITE_HEIGHT * FONT_GLYPHS_ROWS);\n\n  constexpr size_t pitch = SPRITE_WIDTH * FONT_GLYPHS_COLUMNS;\n\n  for (size_t gy = 0; gy < FONT_GLYPHS_ROWS; ++gy)\n    for (size_t gx = 0; gx < FONT_GLYPHS_COLUMNS; ++gx)\n    {\n      sequential_sprite_t& glyph = glyphs[gy*FONT_GLYPHS_COLUMNS + gx];\n\n      for (size_t sy = 0; sy < SPRITE_HEIGHT; ++sy)\n        for (size_t sx = 0; sx < SPRITE_WIDTH; ++sx)\n        {\n          size_t bx = gx * SPRITE_WIDTH;\n          size_t by = gy * SPRITE_HEIGHT;\n          size_t index = (by + sy) * pitch + bx + sx;\n\n          glyph.set(sx, sy, data[index] ? color_t::WHITE : color_t::BLACK);\n        }\n    }\n}\n"
  },
  {
    "path": "src/vm/gfx.h",
    "content": "#pragma once\n\n#include \"defines.h\"\n\n#include <array>\n#include <cassert>\n\nnamespace retro8\n{\n  namespace gfx\n  {\n    static constexpr size_t PIXEL_TO_BYTE_RATIO = 2;\n\n    static constexpr size_t SPRITE_WIDTH = 8;\n    static constexpr size_t SPRITE_HEIGHT = 8;\n\n    static constexpr size_t GLYPH_WIDTH = 4;\n    static constexpr size_t GLYPH_HEIGHT = 6;\n\n    static constexpr size_t SPRITE_BYTES_PER_SPRITE_ROW = SPRITE_WIDTH / PIXEL_TO_BYTE_RATIO;\n    static constexpr size_t PALETTE_SIZE = 16;\n\n    static constexpr size_t SCREEN_WIDTH = 128;\n    static constexpr size_t SCREEN_HEIGHT = 128;\n    static constexpr size_t SCREEN_PITCH = SCREEN_WIDTH / PIXEL_TO_BYTE_RATIO;;\n    static constexpr size_t BYTES_PER_SCREEN = SCREEN_WIDTH * SCREEN_HEIGHT / PIXEL_TO_BYTE_RATIO;\n\n    static constexpr size_t TILE_MAP_WIDTH = 128;\n    static constexpr size_t TILE_MAP_HEIGHT = 64;\n\n\n    static constexpr size_t SPRITE_SHEET_WIDTH = 128;\n    static constexpr size_t SPRITES_PER_SPRITE_SHEET_ROW = 16;\n    static constexpr size_t SPRITE_SHEET_PITCH = SPRITE_SHEET_WIDTH / PIXEL_TO_BYTE_RATIO;\n    static constexpr size_t SPRITE_SHEET_HEIGHT = 128;\n    static constexpr size_t SPRITE_COUNT = (SPRITE_SHEET_WIDTH * SPRITE_SHEET_HEIGHT) / (SPRITE_WIDTH * SPRITE_HEIGHT);\n\n    static constexpr size_t FONT_GLYPHS_COLUMNS = 16;\n    static constexpr size_t FONT_GLYPHS_ROWS = 10;\n\n    static constexpr size_t DRAW_PALETTE_INDEX = 0;\n    static constexpr size_t SCREEN_PALETTE_INDEX = 1;\n\n    static constexpr size_t COLOR_COUNT = 16;\n    \n    //TODO: optimize by generating it the same format as the destination surface\n\n    struct ColorTable\n    {\n    public:\n      using pixel_t = uint32_t;\n\n    private:\n      std::array<pixel_t, COLOR_COUNT> table;\n\n    public:\n      template<typename B>\n      void init(const B& mapper)\n      {\n        struct rgb_color_t { uint8_t r, g, b; };\n\n        constexpr std::array<rgb_color_t, COLOR_COUNT> colors = { {\n          {  0,   0,   0}, { 29,  43,  83}, {126,  37,  83}, {  0, 135,  81},\n          {171,  82,  54}, { 95,  87,  79}, {194, 195, 199}, {255, 241, 232},\n          {255,   0,  77}, {255, 163,   0}, {255, 236,  39}, {  0, 228,  54},\n          { 41, 173, 255}, {131, 118, 156}, {255, 119, 168}, {255, 204, 170}\n        } };\n\n        for (size_t i = 0; i < COLOR_COUNT; ++i)\n          table[i] = mapper(colors[i].r, colors[i].g, colors[i].b);\n      }\n      pixel_t get(color_t c) const { return table[c]; }\n    };\n\n    \n    static color_t colorForRGB(uint32_t color)\n    {\n      switch (color & 0x00ffffff)\n      {\n        case 0x000000: return color_t::BLACK;\n        case 0x1D2B53: return color_t::DARK_BLUE;\n        case 0x7E2553: return color_t::DARK_PURPLE;\n        case 0x008751: return color_t::DARK_GREEN;\n        case 0xAB5236: return color_t::BROWN;\n        case 0x5F574F: return color_t::DARK_GREY;\n        case 0xC2C3C7: return color_t::LIGHT_GREY;\n        case 0xFFF1E8: return color_t::WHITE;\n        case 0xFF004D: return color_t::RED;\n        case 0xFFA300: return color_t::ORANGE;\n        case 0xFFEC27: return color_t::YELLOW;\n        case 0x00E436: return color_t::GREEN;\n        case 0x29ADFF: return color_t::BLUE;\n        case 0x83769C: return color_t::INDIGO;\n        case 0xFF77A8: return color_t::PINK;\n        case 0xFFCCAA: return color_t::PEACH;\n        default: assert(false);\n      }\n    }\n\n\n\n    struct color_byte_t\n    {\n      uint8_t value;\n\n    public:\n      color_byte_t() = default;\n      color_byte_t(color_t low, color_t high) : value(low | (high << 4)) { }\n      inline color_t low() const { return static_cast<color_t>(value & 0x0F); }\n      inline color_t high() const { return static_cast<color_t>((value >> 4) & 0x0F); }\n      inline void low(color_t color) { value = ((value & 0xf0) | color); }\n      inline void high(color_t color) { value = ((value & 0x0f) | color << 4); }\n      inline color_t get(coord_t mod) const { return (mod % 2) == 0 ? low() : high(); }\n      inline void set(coord_t mod, color_t color) { value = (mod % 2) == 0 ? ((value & 0xf0) | color) : ((value & 0x0f) | color << 4); }\n      inline void setBoth(color_t low, color_t high) { value = low | high << 4; }\n    };\n\n    class sprite_t\n    {      \n    public:\n      color_t get(coord_t x, coord_t y) const { return byteAt(x, y).get(x); }\n      void set(coord_t x, coord_t y, color_t color) { byteAt(x, y).set(x, color); }\n      inline const color_byte_t& byteAt(coord_t x, coord_t y) const { return static_cast<const color_byte_t&>(((sprite_t*)this)->byteAt(x, y)); }\n      inline color_byte_t& byteAt(coord_t x, coord_t y) { return reinterpret_cast<color_byte_t*>(this)[y * SPRITE_SHEET_PITCH + x / 2]; }\n    };\n\n    class sequential_sprite_t\n    {\n      color_byte_t data[32];\n\n      inline const color_byte_t& byteAt(coord_t x, coord_t y) const { return static_cast<const color_byte_t&>(((sequential_sprite_t*)this)->byteAt(x, y)); }\n      inline color_byte_t& byteAt(coord_t x, coord_t y) { return data[y * SPRITE_BYTES_PER_SPRITE_ROW + x / 2]; }\n\n    public:\n      color_t get(coord_t x, coord_t y) const { return byteAt(x, y).get(x); }\n      void set(coord_t x, coord_t y, color_t color) { byteAt(x, y).set(x, color); }\n    };\n\n    class palette_t\n    {\n      std::array<uint8_t, COLOR_COUNT> colors;\n\n    public:\n      void reset()\n      {\n        for (size_t i = 0; i < COLOR_COUNT; ++i)\n          colors[i] = uint8_t(i);\n        transparent(color_t::BLACK, true);\n      }\n\n      void resetTransparency()\n      {\n        transparent(color_t::BLACK, true);\n\n        for (size_t i = 1; i < COLOR_COUNT; ++i)\n          transparent(color_t(i), false);\n      }\n\n      //TODO: %16 to make it wrap around, is it intended behavior? mandel.\n      color_t get(color_t i) const { return color_t(colors[i] & 0x0F); }\n      void set(color_t i, color_t color) { colors[i] = color | (colors[i] & 0x10); }\n      color_t operator[](color_t i) { return get(i); }\n      bool transparent(color_t i) const { return (colors[i] & 0x10) != 0; }\n      void transparent(color_t i, bool f) { colors[i] = f ? (colors[i] | 0x10) : (colors[i] & 0x0f); }\n    };\n\n    struct clip_rect_t\n    {\n      uint8_t x0;\n      uint8_t y0;\n      uint8_t x1;\n      uint8_t y1;\n\n      void reset() { x0 = y0 = 0; x1 = SCREEN_WIDTH - 1; y1 = SCREEN_HEIGHT - 1; }\n      void set(uint8_t xs, uint8_t ys, uint8_t xe, uint8_t ye) { x0 = xs; y0 = ys; x1 = xe; y1 = ye; }\n    };\n\n    struct cursor_t\n    {\n      uint8_t _x, _y;\n\n      void reset() { _x = _y = 0; }\n      void set(uint8_t x, uint8_t y) { _x = x; _y = y; }\n      uint8_t x() const { return _x; }\n      uint8_t y() const { return _y; }\n    };\n\n    struct camera_t\n    {\n\n      int16_t _x;\n      int16_t _y;\n\n      int16_t x() const { return _x; }\n      int16_t y() const { return _y; }\n\n#if SDL_BYTEORDER == SDL_BIG_ENDIAN\n      //TODO: raw memory addresses expect these to be little endian, FIX!\n      void set(int16_t x, int16_t y) { _x = x; _y = y; }\n#else\n      void set(int16_t x, int16_t y) { _x = x; _y = y; }\n#endif\n\n    };\n\n    class Font\n    {\n      sequential_sprite_t glyphs[FONT_GLYPHS_ROWS*FONT_GLYPHS_COLUMNS];\n\n    public:\n      Font() { }\n      inline const sequential_sprite_t* glyph(char c) const { return c < 128 ? &glyphs[c] : nullptr; }\n      inline const sequential_sprite_t* specialGlyph(size_t i) const { return &glyphs[128+i]; }\n\n      void load();\n\n      /* this assumes a 1 byte per pixel bmp */\n      void load(const uint8_t* data);\n    };\n\n  };\n\n\n}"
  },
  {
    "path": "src/vm/input.h",
    "content": "#pragma once\n\n#include \"common.h\"\n#include \"defines.h\"\n\n#include \"vm/machine.h\"\n\nnamespace retro8\n{\n  namespace input\n  {\n    class InputManager\n    {\n    private:\n      Machine* _machine;\n      uint32_t _frameCounter;\n\n      struct KeyStatus\n      {\n        enum class State { OFF, FIRST, WAITING, REPEATING } state;\n        retro8::button_t button;\n        uint32_t ticks;\n      };\n      std::array<std::array<KeyStatus, retro8::BUTTON_COUNT>, retro8::PLAYER_COUNT> keyStatus;\n\n    public:\n      InputManager();\n\n      void manageKeyRepeat();\n      void manageKey(size_t playerIndex, size_t buttonIndex, bool pressed);\n      void reset();\n      void tick() { ++_frameCounter; }\n      void setMachine(Machine* machine) { _machine = machine; }\n    };\n\n    inline InputManager::InputManager() : _frameCounter(0)\n    {\n      reset();\n    }\n\n    inline void InputManager::reset()\n    {\n      for (auto& pks : keyStatus)\n      {\n        for (uint32_t i = 0; i < pks.size(); ++i)\n        {\n          pks[i].button = retro8::button_t(1 << i);\n          pks[i].state = KeyStatus::State::OFF;\n        }\n      }\n    }\n\n    inline void InputManager::manageKeyRepeat()\n    {\n      static constexpr uint32_t TICKS_FOR_FIRST_REPEAT = 15;\n      static constexpr uint32_t TICKS_REPEATING = 4;\n\n      /* manage key repeats */\n      const uint32_t ticks = _frameCounter;\n\n      for (size_t i = 0; i < keyStatus.size(); ++i)\n      {\n        auto& pks = keyStatus[i];\n\n        for (KeyStatus& ks : pks)\n        {\n          if (ks.state == KeyStatus::State::FIRST)\n          {\n            _machine->state().previousButtons[i].set(ks.button);\n            ks.state = KeyStatus::State::WAITING;\n          }\n          else if (ks.state == KeyStatus::State::WAITING && (ticks - ks.ticks) >= TICKS_FOR_FIRST_REPEAT)\n          {\n            _machine->state().previousButtons[i].set(ks.button);\n            ks.state = KeyStatus::State::REPEATING;\n            ks.ticks = ticks;\n          }\n          else if (ks.state == KeyStatus::State::REPEATING && (ticks - ks.ticks) >= TICKS_REPEATING)\n          {\n            _machine->state().previousButtons[i].set(ks.button);\n            ks.ticks = ticks;\n          }\n          else\n            _machine->state().previousButtons[i].reset(ks.button);\n        }\n      }\n    }\n\n    inline void InputManager::manageKey(size_t pindex, size_t index, bool pressed)\n    {\n      const auto bt = keyStatus[pindex][index].button;\n      _machine->state().buttons[pindex].set(bt, pressed);\n      keyStatus[pindex][index].ticks = _frameCounter;\n      keyStatus[pindex][index].state = pressed ? KeyStatus::State::FIRST : KeyStatus::State::OFF;\n    }\n  }\n}"
  },
  {
    "path": "src/vm/lua_bridge.cpp",
    "content": "#include \"lua_bridge.h\"\n\n#include \"machine.h\"\n#include \"lua/lua.hpp\"\n#include \"gen/lua_api.h\"\n\n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <cstring>\n#include <cmath>\n\n#pragma warning(push)\n#pragma warning(disable: 4244)\n\nusing namespace lua;\nusing namespace retro8;\n\nextern retro8::Machine machine;\n\nusing real_t = float;\n\nint pset(lua_State* L)\n{\n  int args = lua_gettop(L);\n  //TODO: check validity of arguments\n\n  int x = lua_tonumber(L, 1);\n  int y = lua_tonumber(L, 2);\n  int c;\n\n  if (args == 3)\n    c = lua_tonumber(L, 3);\n  else\n    c = machine.memory().penColor()->low();\n\n  machine.pset(x, y, static_cast<color_t>(c));\n\n  return 0;\n}\n\nint pget(lua_State* L)\n{\n  int x = lua_tonumber(L, 1);\n  int y = lua_tonumber(L, 2);\n\n  lua_pushinteger(L, machine.pget(x, y));\n\n  return 1;\n}\n\nint color(lua_State* L)\n{\n  int c = lua_tonumber(L, 1);\n\n  machine.color(static_cast<color_t>(c));\n\n  return 0;\n}\n\nint line(lua_State* L)\n{\n  int x0 = lua_tonumber(L, 1);\n  int y0 = lua_tonumber(L, 2);\n  int x1 = lua_tonumber(L, 3);\n  int y1 = lua_tonumber(L, 4);\n\n  int c = lua_gettop(L) == 5 ? lua_tonumber(L, 5) : machine.memory().penColor()->low();\n\n  machine.line(x0, y0, x1, y1, static_cast<color_t>(c));\n\n  return 0;\n}\n\nint fillp(lua_State* L)\n{\n  //TODO: implement\n  return 0;\n}\n\nint rect(lua_State* L)\n{\n  int x0 = lua_tonumber(L, 1);\n  int y0 = lua_tonumber(L, 2);\n  int x1 = lua_tonumber(L, 3);\n  int y1 = lua_tonumber(L, 4);\n\n  int c = lua_gettop(L) == 5 ? lua_tonumber(L, 5) : machine.memory().penColor()->low();\n\n  machine.rect(x0, y0, x1, y1, static_cast<color_t>(c));\n\n  return 0;\n}\n\n// TODO: fill pattern on filled shaped\nint rectfill(lua_State* L)\n{\n  int x0 = lua_tonumber(L, 1);\n  int y0 = lua_tonumber(L, 2);\n  int x1 = lua_tonumber(L, 3);\n  int y1 = lua_tonumber(L, 4);\n\n  int c = lua_gettop(L) >= 5 ? lua_tonumber(L, 5) : machine.memory().penColor()->low();\n\n  machine.rectfill(x0, y0, x1, y1, static_cast<color_t>(c));\n\n  return 0;\n}\n\nint circ(lua_State* L)\n{\n  int x = lua_tonumber(L, 1);\n  int y = lua_tonumber(L, 2);\n  int r = lua_gettop(L) >= 3 ? lua_tonumber(L, 3) : 4;\n  int c = lua_gettop(L) >= 4 ? lua_tonumber(L, 4) : machine.memory().penColor()->low();\n\n  machine.circ(x, y, r, static_cast<color_t>(c));\n\n  return 0;\n}\n\nint circfill(lua_State* L)\n{\n  int x = lua_tonumber(L, 1);\n  int y = lua_tonumber(L, 2);\n  int r = lua_gettop(L) >= 3 ? lua_tonumber(L, 3) : 4;\n  int c = lua_gettop(L) >= 4 ? lua_tonumber(L, 4) : machine.memory().penColor()->low();\n\n  machine.circfill(x, y, r, color_t(c));\n\n  return 0;\n}\n\nint cls(lua_State* L)\n{\n  int c = lua_gettop(L) == 1 ? lua_tonumber(L, -1) : 0;\n\n  machine.cls(color_t(c));\n\n  return 0;\n}\n\nint spr(lua_State* L)\n{\n  assert(lua_isnumber(L, 2) && lua_isnumber(L, 3));\n\n  int idx = lua_tonumber(L, 1);\n  int x = lua_tonumber(L, 2);\n  int y = lua_tonumber(L, 3);\n\n  if (lua_gettop(L) > 3)\n  {\n    assert(lua_gettop(L) >= 5);\n\n    real_t w = lua_tonumber(L, 4);\n    real_t h = lua_tonumber(L, 5);\n    bool fx = false, fy = false;\n\n    if (lua_gettop(L) >= 6)\n      fx = lua_toboolean(L, 6);\n\n    if (lua_gettop(L) >= 7)\n      fy = lua_toboolean(L, 7);\n\n    machine.spr(idx, x, y, w, h, fx, fy);\n  }\n  else\n    /* optimized path */\n    machine.spr(idx, x, y);\n\n  return 0;\n}\n\nint sget(lua_State* L)\n{\n  int x = lua_tonumber(L, 1);\n  int y = lua_tonumber(L, 2);\n\n  lua_pushnumber(L, machine.memory().spriteSheet(x, y)->get(x));\n\n  return 1;\n}\n\nint sset(lua_State* L)\n{\n  int x = lua_tonumber(L, 1);\n  int y = lua_tonumber(L, 2);\n  color_t c = lua_gettop(L) >= 3 ? color_t((int)lua_tonumber(L, 3)) : machine.memory().penColor()->low();\n\n  machine.memory().spriteSheet(x, y)->set(x, c);\n\n  return 0;\n}\n\n\nint pal(lua_State* L)\n{\n  /* no arguments, reset palette */\n  if (lua_gettop(L) == 0)\n  {\n    machine.memory().paletteAt(gfx::DRAW_PALETTE_INDEX)->reset();\n    machine.memory().paletteAt(gfx::SCREEN_PALETTE_INDEX)->reset();\n  }\n  else\n  {\n    int c0 = lua_tonumber(L, 1);\n    int c1 = lua_tonumber(L, 2);\n    palette_index_t index = gfx::DRAW_PALETTE_INDEX;\n\n    if (lua_gettop(L) == 3)\n      index = lua_tonumber(L, 3);\n\n    machine.pal(static_cast<color_t>(c0), static_cast<color_t>(c1), index);\n  }\n  return 0;\n}\n\nint palt(lua_State* L)\n{\n  /* no arguments, reset palette */\n  if (lua_gettop(L) == 0)\n  {\n    machine.memory().paletteAt(gfx::DRAW_PALETTE_INDEX)->resetTransparency();\n    machine.memory().paletteAt(gfx::SCREEN_PALETTE_INDEX)->resetTransparency();\n  }\n  else\n  {\n    color_t c = color_t(int(lua_tonumber(L, 1)));\n    int f = lua_toboolean(L, 2);\n    palette_index_t index = gfx::DRAW_PALETTE_INDEX;\n\n    machine.memory().paletteAt(gfx::DRAW_PALETTE_INDEX)->transparent(c, f);\n  }\n  return 0;\n}\n\nnamespace draw\n{\n  int clip(lua_State* L)\n  {\n    if (lua_gettop(L) == 0)\n      machine.memory().clipRect()->reset();\n    else\n    {\n      uint8_t x0 = lua_tonumber(L, 1);\n      uint8_t y0 = lua_tonumber(L, 2);\n      uint8_t w = lua_tonumber(L, 3);\n      uint8_t h = lua_tonumber(L, 4);\n\n      machine.memory().clipRect()->set(x0, y0, std::min(x0 + w, int32_t(gfx::SCREEN_WIDTH-1)), std::min(y0 + h, int32_t(gfx::SCREEN_HEIGHT-1)));\n    }\n\n    return 0;\n  }\n}\n\n\n\nint camera(lua_State* L)\n{\n  int16_t cx = lua_gettop(L) >= 1 ? lua_tonumber(L, 1) : 0;\n  int16_t cy = lua_gettop(L) == 2 ? lua_tonumber(L, 2) : 0;\n  machine.memory().camera()->set(cx, cy);\n\n  return 0;\n}\n\nint map(lua_State* L)\n{\n  coord_t cx = lua_tonumber(L, 1);\n  coord_t cy = lua_tonumber(L, 2);\n  coord_t x = lua_tonumber(L, 3);\n  coord_t y = lua_tonumber(L, 4);\n  amount_t cw = lua_gettop(L) >= 5 ? lua_tonumber(L, 5) : (gfx::SCREEN_WIDTH / gfx::SPRITE_WIDTH);\n  amount_t ch = lua_gettop(L) >= 6 ? lua_tonumber(L, 6) : (gfx::SCREEN_HEIGHT / gfx::SPRITE_HEIGHT);\n  sprite_flags_t layer = 0;\n\n  if (lua_gettop(L) == 7)\n    layer = lua_tonumber(L, 7);\n\n  machine.map(cx, cy, x, y, cw, ch, layer);\n\n  return 0;\n}\n\nint mget(lua_State* L)\n{\n  int x = lua_tonumber(L, 1); //TODO: these are optional\n  int y = lua_tonumber(L, 2);\n\n  sprite_index_t index = 0;\n\n  if (x >= 0 && x <= gfx::TILE_MAP_WIDTH && y >= 0 && y < gfx::TILE_MAP_HEIGHT)\n    index = *machine.memory().spriteInTileMap(x, y);\n\n  //printf(\"mget(%d, %d) = %d\\n\", x, y, index);\n\n  lua_pushnumber(L, index);\n\n  return 1;\n}\n\nint mset(lua_State* L)\n{\n  int x = lua_tonumber(L, 1);\n  int y = lua_tonumber(L, 2);\n  retro8::sprite_index_t index = lua_tonumber(L, 3);\n\n  *machine.memory().spriteInTileMap(x, y) = index;\n\n  return 0;\n}\n\nint print(lua_State* L)\n{\n  //TODO: optimize and use const char*?\n  std::string text = lua_tostring(L, 1);\n\n  if (lua_gettop(L) == 1)\n  {\n    auto* cursor = machine.memory().cursor();\n\n    retro8::coord_t x = cursor->x();\n    retro8::coord_t y = cursor->y();\n    retro8::color_t c = machine.memory().penColor()->low();\n    machine.print(text, x, y, c);\n    cursor->set(cursor->x(), cursor->y() + TEXT_LINE_HEIGHT); //TODO: check height\n  }\n  else if (lua_gettop(L) >= 3)\n  {\n    int x = lua_tonumber(L, 2);\n    int y = lua_tonumber(L, 3);\n    int c = lua_gettop(L) == 4 ? lua_tonumber(L, 4) : machine.memory().penColor()->low();\n\n    machine.print(text, x, y, static_cast<retro8::color_t>(c));\n  }\n  else\n    assert(false);\n\n\n  return 0;\n}\n\nint cursor(lua_State* L)\n{\n  if (lua_gettop(L) >= 2)\n  {\n    int x = lua_tonumber(L, 1);\n    int y = lua_tonumber(L, 2);\n    *machine.memory().cursor() = { (uint8_t)x, (uint8_t)y };\n\n    if (lua_gettop(L) == 3)\n    {\n      retro8::color_t color = static_cast<retro8::color_t>((int)lua_tonumber(L, 2));\n      machine.memory().penColor()->low(color);\n    }\n  }\n  else\n    *machine.memory().cursor() = { 0, 0 };\n\n  return 0;\n}\n\nnamespace debug\n{\n  int debugprint(lua_State* L)\n  {\n    std::string text = lua_tostring(L, 1);\n    std::cout << text << std::endl;\n\n    return 0;\n  }\n\n  int breakpoint(lua_State* L)\n  {\n#if _WIN32\n    __debugbreak();\n#endif\n    return 0;\n  }\n}\n\n\nnamespace sprites\n{\n  int fget(lua_State* L)\n  {\n    retro8::sprite_index_t index = lua_tonumber(L, 1);\n    retro8::sprite_flags_t flags = *machine.memory().spriteFlagsFor(index);\n\n    if (lua_gettop(L) == 2)\n    {\n      int index = lua_tonumber(L, 2);\n      assert(index >= 0 && index <= 7);\n      lua_pushboolean(L, (flags >> index) & 0x1 ? true : false);\n    }\n    else\n      lua_pushnumber(L, *machine.memory().spriteFlagsFor(index));\n\n    return 1;\n  }\n\n  int fset(lua_State* L)\n  {\n    retro8::sprite_index_t index = lua_tonumber(L, 1);\n    retro8::sprite_flags_t* flags = machine.memory().spriteFlagsFor(index);\n\n    if (lua_gettop(L) == 3)\n    {\n      int index = lua_tonumber(L, 2);\n      bool value = lua_toboolean(L, 3);\n      assert(index >= 0 && index <= 7);\n\n      if (value)\n        *flags = *flags | (1 << index);\n      else\n        *flags = *flags & ~(1 << index);\n    }\n    else\n    {\n      retro8::sprite_flags_t value = lua_tonumber(L, 2);\n      *flags = value;\n    }\n\n    return 0;\n  }\n\n  int sspr(lua_State* L)\n  {\n    coord_t sx = lua_tonumber(L, 1);\n    coord_t sy = lua_tonumber(L, 2);\n    coord_t sw = lua_tonumber(L, 3);\n    coord_t sh = lua_tonumber(L, 4);\n    coord_t dx = lua_tonumber(L, 5);\n    coord_t dy = lua_tonumber(L, 6);\n    coord_t dw = lua_to_or_default(L, number, 7, sw);\n    coord_t dh = lua_to_or_default(L, number, 8, sh);\n    bool flipX = lua_to_or_default(L, boolean, 8, false);\n    bool flipY = lua_to_or_default(L, boolean, 8, false);\n\n    machine.sspr(sx, sy, sw, sh, dx, dy, dw, dh, flipX, flipY);\n\n    return 0;\n  }\n}\n\nnamespace math\n{\n  using real_t = float;\n  static constexpr float PI = 3.14159265358979323846;\n\n  int cos(lua_State* L)\n  {\n    if (lua_isnumber(L, 1))\n    {\n      real_t angle = lua_tonumber(L, 1);\n      real_t value = std::cos(angle * 2 * PI);\n      lua_pushnumber(L, value);\n    }\n    else\n      lua_pushnumber(L, 0);\n\n    return 1;\n  }\n\n  int sin(lua_State* L)\n  {\n    if (lua_isnumber(L, 1))\n    {\n      real_t angle = lua_tonumber(L, 1);\n      real_t value = std::sin(-angle * 2 * PI);\n      lua_pushnumber(L, value);\n    }\n    else\n      lua_pushnumber(L, 0);\n\n    return 1;\n  }\n\n  int atan2(lua_State* L)\n  {\n    assert(lua_isnumber(L, 1));\n    real_t dx = lua_tonumber(L, 1);\n    real_t dy = lua_tonumber(L, 2);\n    real_t value = std::atan2(dx, dy) / (2 * PI) - 0.25;\n    if (value < 0.0)\n      value += 1.0;\n\n    lua_pushnumber(L, value);\n\n    return 1;\n  }\n\n  int srand(lua_State* L)\n  {\n    assert(lua_gettop(L) == 1);\n    assert(lua_isnumber(L, 1));\n\n    real_t seed = lua_tonumber(L, 1);\n    machine.state().rnd.seed(seed);\n\n    return 0;\n  }\n\n#define FAIL_IF_NOT_NUMBER(i) do { if (!lua_isnumber(L, i)) { printf(\"Expected number but got %s\\n\", lua_typename(L, i)); assert(false); } } while (false)\n\n  int rnd(lua_State* L)\n  {\n    real_t max = lua_gettop(L) >= 1 ? lua_tonumber(L, 1) : 1.0f;\n    lua_pushnumber(L, (machine.state().rnd() / (float)machine.state().rnd.max()) * max);\n\n    return 1;\n  }\n\n  int flr(lua_State* L)\n  {\n    real_t value = lua_isnumber(L, 1) ? lua_tonumber(L, 1) : 0;\n    lua_pushnumber(L, std::floor(value));\n    return 1;\n  }\n\n  int ceil(lua_State* L)\n  {\n    real_t value = lua_isnumber(L, 1) ? lua_tonumber(L, 1) : 0;\n    lua_pushnumber(L, std::ceil(value));\n    return 1;\n  }\n\n\n  int min(lua_State* L)\n  {\n    real_t v1 = lua_isnumber(L, 1) ? lua_tonumber(L, 1) : 0;\n    real_t v2 = 0;\n\n    if (lua_gettop(L) == 2 && lua_isnumber(L, 2))\n      v2 = lua_tonumber(L, 2);\n\n    lua_pushnumber(L, std::min(v1, v2));\n\n    return 1;\n  }\n\n  int max(lua_State* L)\n  {\n    real_t v1 = lua_isnumber(L, 1) ? lua_tonumber(L, 1) : 0;\n    real_t v2 = 0;\n\n    if (lua_gettop(L) == 2 && lua_isnumber(L, 2))\n    {\n      FAIL_IF_NOT_NUMBER(2);\n      v2 = lua_tonumber(L, 2);\n    }\n\n    lua_pushnumber(L, std::max(v1, v2));\n\n    return 1;\n  }\n\n  int mid(lua_State* L)\n  {\n    real_t a = lua_tonumber(L, 1);\n    real_t b = lua_tonumber(L, 2);\n    real_t c = lua_gettop(L) >= 3 ? lua_tonumber(L, 3) : 0;\n\n    if ((a <= b && b <= c) || (c <= b && b <= a))\n      lua_pushnumber(L, b);\n    else if ((b <= a && a <= c) || (c <= a && a <= b))\n      lua_pushnumber(L, a);\n    else\n      lua_pushnumber(L, c);\n\n    return 1;\n  }\n\n  int abs(lua_State* L)\n  {\n    if (lua_isnumber(L, 1))\n    {\n      real_t v = lua_tonumber(L, 1);\n      lua_pushnumber(L, std::abs(v));\n    }\n    else\n      lua_pushnumber(L, 0);\n\n    return 1;\n  }\n\n  int sgn(lua_State* L)\n  {\n    assert(lua_isnumber(L, 1));\n\n    real_t v = lua_tonumber(L, 1);\n    lua_pushnumber(L, v > 0 ? 1.0 : -1.0);\n\n    return 1;\n  }\n\n  int sqrt(lua_State* L)\n  {\n    assert(lua_isnumber(L, 1));\n\n    real_t v = lua_tonumber(L, 1);\n    lua_pushnumber(L, sqrtf(v));\n\n    return 1;\n  }\n}\n\n#define EXPECT_TYPE(tn, idx) do { if (!lua_is ## tn(L, idx)) std::cout << \"expected \" # tn << \" but got \" << lua_typename(L, idx) << std::endl; assert(false);} while (false)\n\nnamespace bitwise\n{\n  using data_t = uint32_t;\n  static constexpr size_t DATA_WIDTH = 32;\n\n  template<typename F>\n  int bitwise(lua_State* L)\n  {\n    if (lua_isnumber(L, 1) && lua_isnumber(L, 2))\n    {\n      data_t a = lua_tonumber(L, 1);\n      data_t b = lua_tonumber(L, 2);\n\n      lua_pushnumber(L, F()(a, b));\n    }\n    else\n      lua_pushnumber(L, 0);\n\n\n    return 1;\n  }\n\n  struct shift_left\n  {\n    data_t operator()(data_t v, data_t a) { return v << a; }\n  };\n\n  struct shift_right\n  {\n    data_t operator()(data_t v, data_t a) { return v >> a; }\n  };\n\n  struct rotate_left\n  {\n    data_t operator()(data_t v, data_t a) { return (v << a) | (v >> (DATA_WIDTH - a)); }\n  };\n\n  struct rotate_right\n  {\n    data_t operator()(data_t v, data_t a) { return (v >> a) | (v << (DATA_WIDTH - a)); }\n  };\n\n  inline int band(lua_State* L) { return bitwise<std::bit_and<data_t>>(L); }\n  inline int bor(lua_State* L) { return bitwise<std::bit_or<data_t>>(L); }\n  inline int bxor(lua_State* L) { return bitwise<std::bit_xor<data_t>>(L); }\n\n  //TODO FIXME: fixme check implementation of logical and arithmetic shifts here\n\n  inline int shl(lua_State* L) { return bitwise<shift_left>(L); }\n  inline int shr(lua_State* L) { return bitwise<shift_right>(L); }\n  \n  inline int lshl(lua_State* L) { return bitwise<shift_left>(L); }\n  inline int lshr(lua_State* L) { return bitwise<shift_right>(L); }\n  \n  inline int rotl(lua_State* L) { return bitwise<rotate_left>(L); }\n  inline int rotr(lua_State* L) { return bitwise<rotate_right>(L); }\n\n\n  int bnot(lua_State* L)\n  {\n    assert(lua_isnumber(L, 1));\n\n    data_t a = lua_tonumber(L, 1);\n\n    lua_pushnumber(L, std::bit_not<data_t>()(a));\n\n    return 1;\n  }\n}\n\nnamespace sound\n{\n  int music(lua_State* L)\n  {\n    sfx::music_index_t index = lua_tonumber(L, 1);\n    int32_t fadeMs = lua_to_or_default(L, number, 2, 1);\n    int32_t mask = lua_to_or_default(L, number, 3, 0);\n\n    machine.sound().music(index, fadeMs, mask);\n\n    return 0;\n  }\n\n  int sfx(lua_State* L)\n  {\n    sfx::sound_index_t index = lua_tonumber(L, 1);\n    sfx::channel_index_t channel = lua_to_or_default(L, number, 2, -1);\n    int32_t start = lua_to_or_default(L, number, 3, 0);\n    int32_t end = lua_to_or_default(L, number, 3, machine.memory().sound(index)->length());\n\n    machine.sound().play(index, channel, start, end);\n\n    return 0;\n  }\n}\n\nnamespace string\n{\n  int sub(lua_State* L)\n  {\n    const std::string v = lua_tostring(L, 1);\n    size_t s = lua_tonumber(L, 2);\n    size_t e = lua_to_or_default(L, number, 3, -1);\n\n    size_t len = v.length();\n    if (s < 0)\n      s = len - s + 1;\n    if (e < 0)\n      e = len - e + 1;\n\n    // TODO: intended behavior? picotetris calls it with swapped indices\n    if (e < s || s > len)\n      lua_pushstring(L, \"\");\n    else\n    {\n      if (s == 0)\n        s = 1;\n\n      lua_pushstring(L, v.substr(s - 1, e - s + 1).c_str());\n    }\n\n\n    return 1;\n  }\n\n  int tostr(lua_State* L)\n  {\n    //TODO implement\n\n    static char buffer[20];\n\n    switch (lua_type(L, 1))\n    {\n    case LUA_TBOOLEAN: lua_pushstring(L, lua_toboolean(L, 1) ? \"true\" : \"false\"); break;\n    case LUA_TNUMBER:\n    {\n      snprintf(buffer, 20, \"% 4.4f\", lua_tonumber(L, 1));\n      lua_pushstring(L, buffer);\n      break;\n    }\n    case LUA_TSTRING: lua_pushstring(L, lua_tostring(L, 1)); break;\n    default: lua_pushstring(L, \"foo\");\n    }\n\n    return 1;\n  }\n\n  int tonum(lua_State* L)\n  {\n    //TODO implement\n    const char* string = lua_tostring(L, 1);\n\n    lua_pushnumber(L, 0);\n\n    return 1;\n  }\n}\n\nnamespace platform\n{\n  int poke(lua_State* L)\n  {\n    address_t addr = lua_tonumber(L, 1);\n    uint8_t byte = lua_tonumber(L, 2);\n\n    machine.memory().base()[addr] = byte;\n\n    return 0;\n  }\n\n  int poke2(lua_State* L)\n  {\n    address_t addr = lua_tonumber(L, 1);\n    uint32_t value = lua_tonumber(L, 2);\n\n    machine.memory().base()[addr] = value & 0xFF;\n    machine.memory().base()[addr+1] = (value & 0xFF00) >> 8;\n\n    return 0;\n  }\n\n  int poke4(lua_State* L)\n  {\n    address_t addr = lua_tonumber(L, 1);\n    uint32_t value = lua_tonumber(L, 2);\n\n    machine.memory().base()[addr] = value & 0xFF;\n    machine.memory().base()[addr + 1] = (value & 0xFF00) >> 8;\n    machine.memory().base()[addr + 2] = (value & 0xFF0000) >> 16;\n    machine.memory().base()[addr + 3] = (value & 0xFF000000) >> 24;\n\n    return 0;\n  }\n\n  int peek(lua_State* L)\n  {\n    address_t addr = lua_tonumber(L, 1);\n    uint8_t value = machine.memory().base()[addr];\n\n    lua_pushnumber(L, value);\n\n    return 1;\n  }\n\n  int peek2(lua_State* L)\n  {\n    address_t addr = lua_tonumber(L, 1);\n    uint8_t low = machine.memory().base()[addr];\n    uint8_t high = machine.memory().base()[addr+1];\n\n    lua_pushnumber(L, (low | high << 8));\n\n    return 1;\n  }\n\n  int peek4(lua_State* L)\n  {\n    address_t addr = lua_tonumber(L, 1);\n    uint8_t b1 = machine.memory().base()[addr];\n    uint8_t b2 = machine.memory().base()[addr + 1];\n    uint8_t b3 = machine.memory().base()[addr + 2];\n    uint8_t b4 = machine.memory().base()[addr + 3];\n\n    lua_pushnumber(L, b1 | (b2 << 8) | (b3 << 16) | (b4 << 24));\n\n    return 1;\n  }\n\n  int memset(lua_State* L)\n  {\n    address_t addr = lua_tonumber(L, 1);\n    uint8_t value = lua_tonumber(L, 2);\n    int32_t length = lua_tonumber(L, 3);\n\n    if (length > 0)\n      std::memset(machine.memory().base() + addr, 0, length);\n\n    return 0;\n  }\n\n  int memcpy(lua_State* L)\n  {\n    address_t dest = lua_tonumber(L, 1);\n    address_t src = lua_tonumber(L, 2);\n    int32_t length = lua_tonumber(L, 3);\n\n    //TODO: optimize overlap case?\n    if ((src + length < dest) || (dest + length < src))\n      std::memcpy(machine.memory().base() + dest, machine.memory().base() + src, length);\n    else\n    {\n      for (size_t i = 0; i < length; ++i)\n        machine.memory().base()[dest + i] = machine.memory().base()[src + i];\n    }\n\n    return 0;\n  }\n\n  int reload(lua_State* L)\n  {\n    assert(lua_gettop(L) <= 3);\n    \n    address_t dest = lua_to_or_default(L, number, 1, 0);\n    address_t src = lua_to_or_default(L, number, 1, 0);\n    int32_t length = lua_to_or_default(L, number, 1, address::CART_DATA_LENGTH);\n    \n    std::memcpy(machine.memory().base() + dest, machine.memory().backup() + src, length);\n\n    return 0;\n  }\n\n  int btn(lua_State* L)\n  {\n    index_t index = lua_gettop(L) >= 2 ? lua_tonumber(L, 2) : 0;\n    if (index >= PLAYER_COUNT) index = 0;\n \n    /* we're asking for a specific button*/\n    if (lua_gettop(L) >= 1)\n    {\n      using bt_t = retro8::button_t;\n      static constexpr std::array<bt_t, 6> buttons = { bt_t::LEFT, bt_t::RIGHT, bt_t::UP, bt_t::DOWN, bt_t::ACTION1, bt_t::ACTION2 };\n      size_t bindex = lua_tonumber(L, 1);\n\n      if (bindex < buttons.size())\n        lua_pushboolean(L, machine.state().buttons[index].isSet(buttons[bindex]));\n      else\n        lua_pushboolean(L, false);\n\n    }\n    /* push whole bitmask*/\n    else\n    {\n      lua_pushnumber(L, machine.state().buttons[index].value);\n    }\n\n    //TODO: finish for player 2?\n    return 1;\n  }\n\n  int btnp(lua_State* L)\n  {\n    const index_t index = lua_gettop(L) >= 2 ? lua_tonumber(L, 2) : 0;\n\n    //TODO: check behavior\n\n    /* we're asking for a specific button*/\n    if (lua_gettop(L) >= 1)\n    {\n      using bt_t = retro8::button_t;\n      static constexpr std::array<bt_t, 6> buttons = { bt_t::LEFT, bt_t::RIGHT, bt_t::UP, bt_t::DOWN, bt_t::ACTION1, bt_t::ACTION2 };\n      size_t bindex = lua_tonumber(L, 1);\n      lua_pushboolean(L, machine.state().previousButtons[index].isSet(buttons[bindex]));\n    }\n    /* push whole bitmask*/\n    else\n    {\n      lua_pushnumber(L, machine.state().previousButtons[index].value);\n    }\n\n    //TODO: finish for player?\n    return 1;\n  }\n\n  int stat(lua_State* L)\n  {\n    //TODO: implement\n\n    enum class Stat { FRAME_RATE = 7 };\n    Stat s = static_cast<Stat>((int)lua_tonumber(L, -1));\n\n\n    switch (s)\n    {\n    case Stat::FRAME_RATE: lua_pushnumber(L, machine.code().require60fps() ? 60 : 30); break;\n    default: lua_pushnumber(L, 0);\n\n    }\n\n    return 1;\n  }\n\n  int cartdata(lua_State* L)\n  {\n    //TODO: implement\n    return 0;\n  }\n\n  int dset(lua_State* L)\n  {\n    index_t idx = lua_tonumber(L, 1);\n    integral_t value = lua_tonumber(L, 2);\n\n    *machine.memory().cartData(idx) = value;\n    return 0;\n  }\n\n  int dget(lua_State* L)\n  {\n    index_t idx = lua_tonumber(L, 1);\n\n    lua_pushnumber(L, *machine.memory().cartData(idx));\n\n    return 1;\n  }\n\n  int flip(lua_State* L)\n  {\n    //TODO: this call should syncronize to 30fps, at the moment it just\n    // returns producing a lot of flips in non synchronized code (eg. _init() busy loop)\n    //TODO: flip is handled by backend so we should find a way to set the callback that should be called\n\n    return 0;\n  }\n\n  int extcmd(lua_State* L)\n  {\n    //TODO: implement\n    return 0;\n  }\n\n  int menuitem(lua_State* L)\n  {\n    //TODO: implement\n    return 0;\n  }\n\n  int time(lua_State* L)\n  {\n    lua_pushnumber(L, Platform::getTicks() / 1000.0f);\n    return 1;\n  }\n\n  int printh(lua_State* L)\n  {\n    //TODO: finish implementing additional parameters\n    \n    std::string text = lua_tostring(L, 1);\n    std::cout << text << std::endl;\n\n    return 0;\n  }\n}\n\n#pragma warning(pop)\n\nvoid lua::registerFunctions(lua_State* L)\n{\n  lua_register(L, \"pset\", pset);\n  lua_register(L, \"pget\", pget);\n  lua_register(L, \"pal\", pal);\n  lua_register(L, \"palt\", palt);\n  lua_register(L, \"color\", color);\n  lua_register(L, \"line\", line);\n  lua_register(L, \"fillp\", fillp);\n  lua_register(L, \"rect\", rect);\n  lua_register(L, \"rectfill\", rectfill);\n  lua_register(L, \"circ\", circ);\n  lua_register(L, \"circfill\", circfill);\n  lua_register(L, \"clip\", draw::clip);\n  lua_register(L, \"cls\", cls);\n  lua_register(L, \"spr\", spr);\n  lua_register(L, \"camera\", camera);\n  lua_register(L, \"map\", map);\n  lua_register(L, \"mget\", mget);\n  lua_register(L, \"mset\", mset);\n  lua_register(L, \"sget\", sget);\n  lua_register(L, \"sset\", sset);\n\n  lua_register(L, \"print\", print);\n  lua_register(L, \"cursor\", cursor);\n\n  lua_register(L, \"fset\", sprites::fset);\n  lua_register(L, \"fget\", sprites::fget);\n  lua_register(L, \"sspr\", sprites::sspr);\n\n  lua_register(L, \"__debugprint\", debug::debugprint);\n  lua_register(L, \"__breakpoint\", debug::breakpoint);\n\n  lua_register(L, \"cos\", math::cos);\n  lua_register(L, \"sin\", math::sin);\n  lua_register(L, \"atan2\", math::atan2);\n  lua_register(L, \"srand\", math::srand);\n  lua_register(L, \"rnd\", math::rnd);\n  lua_register(L, \"flr\", math::flr);\n  lua_register(L, \"ceil\", math::ceil);\n  lua_register(L, \"min\", math::min);\n  lua_register(L, \"max\", math::max);\n  lua_register(L, \"mid\", math::mid);\n  lua_register(L, \"abs\", math::abs);\n  lua_register(L, \"sgn\", math::sgn);\n  lua_register(L, \"sqrt\", math::sqrt);\n\n  lua_register(L, \"band\", bitwise::band);\n  lua_register(L, \"bor\", bitwise::bor);\n  lua_register(L, \"bxor\", bitwise::bxor);\n  lua_register(L, \"bnot\", bitwise::bnot);\n  lua_register(L, \"shl\", bitwise::shl);\n  lua_register(L, \"shr\", bitwise::shr);\n  lua_register(L, \"lshl\", bitwise::lshl);\n  lua_register(L, \"lshr\", bitwise::lshr);\n  lua_register(L, \"rotl\", bitwise::rotl);\n  lua_register(L, \"rotr\", bitwise::rotr);\n\n  lua_register(L, \"music\", ::sound::music);\n  lua_register(L, \"sfx\", ::sound::sfx);\n\n  lua_register(L, \"sub\", string::sub);\n  lua_register(L, \"tostr\", string::tostr);\n  lua_register(L, \"tonum\", string::tonum);\n\n  lua_register(L, \"btn\", platform::btn);\n  lua_register(L, \"btnp\", platform::btnp);\n  lua_register(L, \"time\", platform::time);\n  lua_register(L, \"t\", platform::time);\n  lua_register(L, \"extcmd\", platform::extcmd);\n  lua_register(L, \"menuitem\", platform::menuitem);\n  lua_register(L, \"stat\", platform::stat);\n  lua_register(L, \"cartdata\", platform::cartdata);\n  lua_register(L, \"dset\", platform::dset);\n  lua_register(L, \"dget\", platform::dget);\n  lua_register(L, \"poke\", platform::poke);\n  lua_register(L, \"peek\", platform::peek);\n  lua_register(L, \"poke2\", platform::poke2);\n  lua_register(L, \"peek2\", platform::peek2);\n  lua_register(L, \"poke4\", platform::poke4);\n  lua_register(L, \"peek4\", platform::peek4);\n  lua_register(L, \"memset\", platform::memset);\n  lua_register(L, \"memcpy\", platform::memcpy);\n  lua_register(L, \"reload\", platform::reload);\n  lua_register(L, \"printh\", platform::printh);\n\n  lua_register(L, \"flip\", platform::flip);\n}\n\nCode::~Code()\n{\n  if (L)\n    lua_close(L);\n}\n\nvoid Code::loadAPI()\n{\n  if (!L)\n  {\n    L = luaL_newstate();\n  }\n\n  luaL_openlibs(L);\n\n  /*std::ifstream apiFile(\"api.lua\");\n  std::string api((std::istreambuf_iterator<char>(apiFile)), std::istreambuf_iterator<char>());*/\n\n  LOGD(\"Loading extended PICO-8 Api\");\n\n  if (luaL_dostring(L, lua_api_string))\n    printError(\"api.lua loading\");\n}\n\nvoid Code::printError(const char* where)\n{\n  //for (int i = 1; i < lua_gettop(L); ++i)\n  {\n    std::cout << \"Error on \" << where << std::endl;\n\n    //luaL_traceback(L, L, NULL, 1);\n    //printf(\"%s\\n\", lua_tostring(L, -1));\n\n    if (lua_isstring(L, -1))\n    {\n      const char* message = lua_tostring(L, -1);\n      std::cout << message << std::endl;\n    }\n  }\n  getchar();\n}\n\nvoid Code::initFromSource(const std::string& code)\n{\n  if (!L)\n    L = luaL_newstate();\n\n  registerFunctions(L);\n\n\n\n  if (luaL_loadstring(L, code.c_str()))\n    printError(\"luaL_loadString\");\n\n  int error = lua_pcall(L, 0, 0, 0);\n\n  if (error)\n    printError(\"lua_pcall on init\");\n\n\n  lua_getglobal(L, \"_update\");\n  if (lua_isfunction(L, -1))\n  {\n    _update = lua_topointer(L, -1);\n    lua_pop(L, 1);\n  }\n\n  lua_getglobal(L, \"_update60\");\n\n  if (lua_isfunction(L, -1))\n  {\n    _update60 = lua_topointer(L, -1);\n    lua_pop(L, 1);\n  }\n\n  lua_getglobal(L, \"_draw\");\n\n  if (lua_isfunction(L, -1))\n  {\n    _draw = lua_topointer(L, -1);\n    lua_pop(L, 1);\n  }\n\n  lua_getglobal(L, \"_init\");\n\n  if (lua_isfunction(L, -1))\n  {\n    _init = lua_topointer(L, -1);\n    lua_pop(L, 1);\n  }\n}\n\nvoid Code::callFunction(const char* name, int ret)\n{\n  lua_getglobal(L, name);\n  int error = lua_pcall(L, 0, ret, 0);\n\n  if (error)\n    printError(name);\n}\n\nvoid Code::update()\n{\n  if (_update60)\n    callFunction(\"_update60\");\n  else if (_update)\n    callFunction(\"_update\");\n}\n\nvoid Code::draw()\n{\n  if (_draw)\n    callFunction(\"_draw\");\n}\n\nvoid Code::init()\n{\n  if (_init)\n    callFunction(\"_init\");\n}\n"
  },
  {
    "path": "src/vm/lua_bridge.h",
    "content": "#pragma once\n\n#include <string>\n\nstruct lua_State;\n\nnamespace lua\n{\n  void registerFunctions(lua_State* state);\n\n  class Code\n  {\n  public:\n    struct Result\n    {\n      bool success;\n      std::string error;\n    };  \n  \n  private:\n    lua_State* L;\n\n    const void* _init;\n    const void* _update;\n    const void* _update60;\n    const void* _draw;\n\n  public:\n    Code() : L(nullptr) { }\n    ~Code();\n\n    void loadAPI();\n\n\n    void printError(const char* where);\n    void initFromSource(const std::string& code);\n    void callFunction(const char* name, int ret = 0);\n\n    bool hasUpdate() const { return _update != nullptr || _update60 != nullptr; }\n    bool hasDraw() const { return _draw != nullptr; }\n    bool require60fps() const { return _update60 != nullptr; }\n    bool hasInit() const { return _init != nullptr; }\n\n    void init();\n    void update();\n    void draw();\n\n#if TEST_MODE\n    lua_State* state() const { return L; }\n#endif\n  };\n}"
  },
  {
    "path": "src/vm/machine.cpp",
    "content": "#include \"machine.h\"\n\n#include <algorithm>\n\nusing namespace retro8;\n\nvoid Machine::color(color_t color)\n{\n  gfx::color_byte_t* penColor = _memory.penColor();\n  penColor->low(color);\n}\n\nvoid Machine::cls(color_t color)\n{\n  color = _memory.paletteAt(gfx::DRAW_PALETTE_INDEX)->get(color);\n  gfx::color_byte_t value = gfx::color_byte_t(color, color);\n\n  auto* data = _memory.screenData();\n  memset(data, value.value, gfx::BYTES_PER_SCREEN);\n\n  _memory.clipRect()->reset();\n  *_memory.cursor() = { 0, 0 };\n}\n\nvoid Machine::pset(coord_t x, coord_t y, color_t color)\n{\n  auto* clip = _memory.clipRect();\n  x -= memory().camera()->x();\n  y -= memory().camera()->y();\n\n  if (x >= clip->x0 && x < clip->x1 && y >= clip->y0 && y < clip->y1)\n  {\n    color = _memory.paletteAt(gfx::DRAW_PALETTE_INDEX)->get(color_t(color % gfx::COLOR_COUNT));\n    _memory.screenData(x, y)->set(x, color);\n  }\n}\n\ncolor_t Machine::pget(coord_t x, coord_t y)\n{\n  return _memory.screenData(x, y)->get(x);\n}\n\nvoid Machine::line(coord_t x0, coord_t y0, coord_t x1, coord_t y1, color_t color)\n{\n  // vertical\n  if (y0 == y1)\n  {\n    if (x0 > x1) std::swap(x0, x1);\n\n    for (coord_t x = x0; x <= x1; ++x)\n      pset(x, y0, color);\n  }\n  // horizontal\n  else if (x0 == x1)\n  {\n    if (y0 > y1) std::swap(y0, y1);\n\n    for (coord_t y = y0; y <= y1; ++y)\n      pset(x0, y, color);\n  }\n  else\n  {\n    coord_t dx = abs(x1 - x0);\n    coord_t sx = x0 < x1 ? 1 : -1;\n    coord_t dy = -abs(y1 - y0);\n    coord_t sy = y0 < y1 ? 1 : -1;\n    coord_t err = dx + dy;\n\n    while (true)\n    {\n      pset(x0, y0, color);\n\n      if (x0 == x1 && y0 == y1)\n        break;\n\n      coord_t err2 = 2 * err;\n\n      if (err2 >= dy)\n      {\n        err += dy;\n        x0 += sx;\n      }\n\n      if (err2 <= dx)\n      {\n        err += dx;\n        y0 += sy;\n      }\n    }\n  }\n\n  // TODO: shouldn't be updated when invoked from other primitives, eg rect\n  _state.lastLineEnd.x = x1;\n  _state.lastLineEnd.x = y1;\n}\n\nvoid Machine::rect(coord_t x0, coord_t y0, coord_t x1, coord_t y1, color_t color)\n{\n  line(x0, y0, x1, y0, color);\n  line(x1, y0, x1, y1, color);\n  line(x0, y1, x1, y1, color);\n  line(x0, y1, x0, y0, color);\n}\n\nvoid Machine::rectfill(coord_t x0, coord_t y0, coord_t x1, coord_t y1, color_t color)\n{\n#if R8_OPTS_ENABLED\n\n  /* compute directly actual bounding box and set the rect without invoking pset */\n\n  auto* clip = _memory.clipRect();\n  auto cx = memory().camera()->x(), cy = memory().camera()->y();\n\n  x0 -= cx;\n  y0 -= cy;\n  x1 -= cx;\n  y1 -= cy;\n\n  x0 = std::max(x0, coord_t(clip->x0));\n  x1 = std::min(x1, coord_t(clip->x1));\n  y0 = std::max(y0, coord_t(clip->y0));\n  y1 = std::min(y1, coord_t(clip->y1));\n\n  color = _memory.paletteAt(gfx::DRAW_PALETTE_INDEX)->get(color_t(color % gfx::COLOR_COUNT));\n\n  for (coord_t y = y0; y <= y1; ++y)\n    for (coord_t x = x0; x <= x1; ++x)\n      _memory.screenData(x, y)->set(x, color);\n#else\n  for (coord_t y = y0; y <= y1; ++y)\n    for (coord_t x = x0; x <= x1; ++x)\n      pset(x, y, color);\n#endif\n}\n\nvoid Machine::circHelper(coord_t xc, coord_t yc, coord_t x, coord_t y, color_t color)\n{\n  pset(xc + x, yc + y, color);\n  pset(xc - x, yc + y, color);\n  pset(xc + x, yc - y, color);\n  pset(xc - x, yc - y, color);\n  pset(xc + y, yc + x, color);\n  pset(xc - y, yc + x, color);\n  pset(xc + y, yc - x, color);\n  pset(xc - y, yc - x, color);\n}\n\nvoid Machine::circ(coord_t xc, coord_t yc, amount_t r, color_t color)\n{\n  //TODO: not identical to pico-8 but acceptable for now\n  coord_t x = 0, y = r;\n  float d = 3 - 2 * r;\n  circHelper(xc, yc, x, y, color);\n\n  while (y >= x)\n  {\n    x++;\n\n    if (d > 0)\n    {\n      y--;\n      d = d + 4 * (x - y) + 5;\n    }\n    else\n      d = d + 4 * x + 3;\n\n    circHelper(xc, yc, x, y, color);\n  }\n}\n\nvoid Machine::circFillHelper(coord_t xc, coord_t yc, coord_t x, coord_t y, color_t col)\n{\n  //TODO: totally inefficient\n  rectfill(xc - x, yc - y, xc + x, yc + y, col);\n  rectfill(xc - y, yc - x, xc + y, yc + x, col);\n}\n\n\nvoid Machine::circfill(coord_t xc, coord_t yc, amount_t r, color_t color)\n{\n  //TODO: not identical to pico-8 but acceptable for now\n  coord_t x = 0, y = r;\n  float d = 3 - 2 * r;\n  circFillHelper(xc, yc, x, y, color);\n\n  int ctr = 0;\n  while (y >= x)\n  {\n    x++;\n\n    if (d > 0)\n    {\n      y--;\n      d = d + 3 * (x - y) + 5;\n    }\n    else\n      d = d + 3 * x + 3;\n\n    circFillHelper(xc, yc, x, y, color);\n  }\n}\n\nvoid Machine::spr(index_t idx, coord_t x, coord_t y)\n{\n  const gfx::sprite_t* sprite = _memory.spriteAt(idx);\n  const gfx::palette_t* palette = _memory.paletteAt(gfx::DRAW_PALETTE_INDEX);\n\n  for (coord_t ty = 0; ty < gfx::SPRITE_HEIGHT; ++ty)\n    for (coord_t tx = 0; tx < gfx::SPRITE_WIDTH; ++tx)\n    {\n      color_t color = sprite->get(tx, ty);\n      if (!palette->transparent(color))\n        pset(x + tx, y + ty, color);\n    }\n}\n\nvoid Machine::spr(index_t idx, coord_t bx, coord_t by, float sw, float sh, bool flipX, bool flipY)\n{\n  const gfx::palette_t* palette = _memory.paletteAt(gfx::DRAW_PALETTE_INDEX);\n\n  coord_t w = sw * gfx::SPRITE_WIDTH;\n  coord_t h = sh * gfx::SPRITE_HEIGHT;\n\n  /* we bypass spriteAt since we can use directly the address */\n  const gfx::color_byte_t* base = reinterpret_cast<const gfx::color_byte_t*>(_memory.spriteAt(idx));\n\n  for (coord_t y = 0; y < h; ++y)\n  {\n    for (coord_t x = 0; x < w; ++x)\n    {\n      coord_t fx = flipX ? (w - x - 1) : x;\n      coord_t fy = flipY ? (h - y - 1) : y;\n\n      //TODO: optimize by fetching only once if we need to read next pixel?\n      const gfx::color_byte_t pair = *(base + y * gfx::SPRITE_SHEET_PITCH + x / gfx::PIXEL_TO_BYTE_RATIO);\n      const color_t color = pair.get(x);\n\n      if (!palette->transparent(color))\n        pset(bx + fx, by + fy, color);\n    }\n  }\n}\n\nvoid Machine::sspr(coord_t sx, coord_t sy, coord_t sw, coord_t sh, coord_t dx, coord_t dy, coord_t dw, coord_t dh, bool flipX, bool flipY)\n{\n  const gfx::palette_t* palette = _memory.paletteAt(gfx::DRAW_PALETTE_INDEX);\n\n  float fx = sx, fy = sy;\n  float xr = sw / float(dw);\n  float yr = sh / float(dh);\n\n  //TODO: flipx flipy, test ratio calculation\n\n  for (coord_t y = 0; y < dh; ++y)\n  {\n    for (coord_t x = 0; x < dw; ++x)\n    {\n      coord_t cx = fx, cy = fy;\n      auto pair = _memory.spriteSheet(cx, cy);\n      auto color = pair->get(cx);\n\n      if (!palette->transparent(color))\n        pset(dx + x, dy + y, color);\n\n      fx += xr;\n    }\n\n    fx = sx;\n    fy += yr;\n  }\n}\n\n// TODO: add support for strange characters like symbols\nvoid Machine::print(const std::string& string, coord_t x, coord_t y, color_t color)\n{\n  \n  struct SpecialGlyph\n  {\n    std::vector<uint8_t> encoding;\n    size_t index;\n  };\n\n  static const std::array<SpecialGlyph, 12> SpecialGlyphs = { {\n    { { 0xe2, 0xac, 0x87, 0xef, 0xb8, 0x8f }, 3 }, // down arrow\n    { { 0xe2, 0xac, 0x86, 0xef, 0xb8, 0x8f }, 20}, // up arrow\n    { { 0xe2, 0xac, 0x85, 0xef, 0xb8, 0x8f }, 11}, // left arrow\n    { { 0xe2, 0x9e, 0xa1, 0xef, 0xb8, 0x8f }, 17}, // right arrow\n    { { 0xf0, 0x9f, 0x85, 0xbe, 0xef, 0xb8, 0x8f }, 14 }, // o button\n    { { 0xe2, 0x9d, 0x8e }, 23 }, // x button\n\n    // 0x8b left, 0x91 right, 0x94 up, 0x83 down, 0x83 o, 0x97 x\n    { { 0x8b }, 11 }, { { 0x91, }, 17 }, { { 0x94 }, 20 }, { { 0x83 }, 3 }, { { 0x8e }, 14 }, { { 0x97 }, 23 } \n  } };\n\n  static const std::array<uint8_t, 2> Prefixes = { 0xe2, 0xf0 };\n\n  const coord_t sx = x;\n  for (size_t i = 0; i < string.length(); ++i)\n  {\n    auto c = string[i];\n\n    if (c == '\\n')\n    {\n      y += TEXT_LINE_HEIGHT;\n      x = sx;\n      continue;\n    }\n\n    auto specialGlyph = std::find_if(SpecialGlyphs.begin(), SpecialGlyphs.end(), [&string, &i](const SpecialGlyph& glyph) {\n      return string.size() >= i + glyph.encoding.size() && memcmp(&string[i], &glyph.encoding[0], glyph.encoding.size()) == 0; //TODO: memcmp is not best design ever\n    });\n\n    const gfx::sequential_sprite_t* sprite = nullptr;\n    coord_t width = gfx::GLYPH_WIDTH;\n\n    if (specialGlyph != SpecialGlyphs.end())\n    {\n      sprite = _font.specialGlyph(specialGlyph->index);\n      width = 8;\n      i += specialGlyph->encoding.size() - 1;\n    }\n    else\n      sprite = _font.glyph(c);\n\n    if (sprite)\n    {\n      for (coord_t ty = 0; ty < gfx::GLYPH_HEIGHT; ++ty)\n        for (coord_t tx = 0; tx < width; ++tx)\n        {\n          color_t fcolor = sprite->get(tx, ty);\n          if (fcolor != 0)\n            pset(x + tx, y + ty, color);\n        }\n\n      x += width;\n    }\n  }\n}\n\nvoid Machine::pal(color_t c0, color_t c1, palette_index_t index)\n{\n  gfx::palette_t* palette = _memory.paletteAt(index);\n  palette->set(c0, c1);\n}\n\n\nvoid Machine::map(coord_t cx, coord_t cy, coord_t x, coord_t y, amount_t cw, amount_t ch, sprite_flags_t layer)\n{\n  for (amount_t ty = 0; ty < ch; ++ty)\n  {\n    for (amount_t tx = 0; tx < cw; ++tx)\n    {\n      const sprite_index_t index = *_memory.spriteInTileMap(cx + tx, cy + ty);\n\n      /* don't draw if index is 0 or layer is not zero and sprite flags are not correcly masked to it */\n      /* TODO: experimentally the behavior is layer & flags != 0 instead that layer & flags == layer */\n      if (index != 0 && (!layer || (layer & *_memory.spriteFlagsFor(index)) != 0))\n        spr(index, x + tx * gfx::SPRITE_WIDTH, y + ty * gfx::SPRITE_HEIGHT);\n    }\n  }\n}\n"
  },
  {
    "path": "src/vm/machine.h",
    "content": "#pragma once\n\n#include \"common.h\"\n#include \"defines.h\"\n#include \"gfx.h\"\n#include \"sound.h\"\n#include \"lua_bridge.h\"\n#include \"memory.h\"\n\n#include <array>\n#include <random>\n\nnamespace retro8\n{\n  class State\n  {\n  public:\n    std::mt19937 rnd;\n    point_t lastLineEnd;\n    std::array<bit_mask<button_t>, PLAYER_COUNT> buttons;\n    std::array<bit_mask<button_t>, PLAYER_COUNT> previousButtons;\n  };\n\n  class Machine\n  {\n  private:\n    State _state;\n    Memory _memory;\n    sfx::APU _sound;\n    gfx::Font _font;\n    lua::Code _code;\n\n  private:\n    void circHelper(coord_t xc, coord_t yc, coord_t x, coord_t y, color_t col);\n    void circFillHelper(coord_t xc, coord_t yc, coord_t x, coord_t y, color_t col);\n\n\n  public:\n    Machine() : _sound(_memory)\n    {\n    }\n\n    Machine(const Machine&) = delete;\n    Machine& operator=(const Machine&) = delete;\n\n    void color(color_t color);\n\n    void cls(color_t color);\n\n    void pset(coord_t x, coord_t y, color_t color);\n    color_t pget(coord_t x, coord_t y);\n\n    void line(coord_t x0, coord_t y0, coord_t x1, coord_t y1, color_t color);\n    void rect(coord_t x0, coord_t y0, coord_t x1, coord_t y1, color_t color);\n    void rectfill(coord_t x0, coord_t y0, coord_t x1, coord_t y1, color_t color);\n    void circ(coord_t x, coord_t y, amount_t r, color_t color);\n    void circfill(coord_t x, coord_t y, amount_t r, color_t color);\n\n    void pal(color_t c0, color_t c1, palette_index_t index);\n\n    void map(coord_t cx, coord_t cy, coord_t x, coord_t y, amount_t cw, amount_t ch, sprite_flags_t layer);\n    void spr(index_t idx, coord_t x, coord_t y);\n    void spr(index_t idx, coord_t x, coord_t y, float w, float h, bool flipX, bool flipY);\n    void sspr(coord_t sx, coord_t sy, coord_t sw, coord_t sh, coord_t dx, coord_t dy, coord_t dw, coord_t dh, bool flipX, bool flipY);\n\n    void print(const std::string& string, coord_t x, coord_t y, color_t color);\n\n    State& state() { return _state; }\n    Memory& memory() { return _memory; }\n    gfx::Font& font() { return _font; }\n    lua::Code& code() { return _code; }\n    sfx::APU& sound() { return _sound; }\n  };\n}\n"
  },
  {
    "path": "src/vm/memory.cpp",
    "content": "#include \"memory.h\""
  },
  {
    "path": "src/vm/memory.h",
    "content": "#pragma once\n\n#include \"common.h\"\n#include \"defines.h\"\n#include \"gfx.h\"\n#include \"sound.h\"\n#include \"lua_bridge.h\"\n\n#include <array>\n#include <random>\n#include <cstring>\n\nnamespace retro8\n{\n  namespace address\n  {\n    static constexpr address_t SPRITE_SHEET = 0x0000;\n    static constexpr address_t SPRITE_FLAGS = 0x3000;\n\n    static constexpr address_t MUSIC = 0x3100;\n    static constexpr address_t SOUNDS = 0x3200;\n\n    static constexpr address_t CART_DATA = 0x5e00;\n    static constexpr address_t PALETTES = 0x5f00;\n    static constexpr address_t CLIP_RECT = 0x5f20;\n    static constexpr address_t PEN_COLOR = 0x5f25;\n    static constexpr address_t CURSOR = 0x5f26;\n    static constexpr address_t CAMERA = 0x5f28;\n\n    static constexpr address_t SCREEN_DATA = 0x6000;\n\n    static constexpr address_t TILE_MAP_LOW = 0x1000;\n    static constexpr address_t TILE_MAP_HIGH = 0x2000;\n\n    static constexpr int32_t CART_DATA_LENGTH = 0x4300;\n  };\n\n  class Memory\n  {\n  private:\n    uint8_t _backup[address::CART_DATA_LENGTH];\n    uint8_t memory[1024 * 32];\n\n    static constexpr size_t BYTES_PER_PALETTE = sizeof(retro8::gfx::palette_t);\n    static constexpr size_t BYTES_PER_SPRITE = sizeof(retro8::gfx::sprite_t);\n\n    static constexpr size_t ROWS_PER_TILE_MAP_HALF = 32;\n\n\n  public:\n    Memory()\n    {\n      memset(memory, 0, 1024 * 32);\n      paletteAt(gfx::DRAW_PALETTE_INDEX)->reset();\n      paletteAt(gfx::SCREEN_PALETTE_INDEX)->reset();\n      clipRect()->reset();\n      cursor()->reset();\n    }\n\n    void backupCartridge()\n    {\n      std::memcpy(_backup, memory, address::CART_DATA_LENGTH);\n    }\n\n    const uint8_t* backup() const { return _backup; }\n    uint8_t* base() { return memory; }\n\n    gfx::color_byte_t* penColor() { return as<gfx::color_byte_t>(address::PEN_COLOR); }\n    gfx::cursor_t* cursor() { return as<gfx::cursor_t>(address::CURSOR); }\n    gfx::camera_t* camera() { return as<gfx::camera_t>(address::CAMERA); }\n    gfx::clip_rect_t* clipRect() { return as<gfx::clip_rect_t>(address::CLIP_RECT); }\n\n    gfx::color_byte_t* spriteSheet(coord_t x, coord_t y) { return spriteSheet() + x / gfx::PIXEL_TO_BYTE_RATIO + y * gfx::SPRITE_SHEET_PITCH; }\n    gfx::color_byte_t* spriteSheet() { return as<gfx::color_byte_t>(address::SPRITE_SHEET); }\n    gfx::color_byte_t* screenData() { return as<gfx::color_byte_t>(address::SCREEN_DATA); }\n    gfx::color_byte_t* screenData(coord_t x, coord_t y) { return screenData() + y * gfx::SCREEN_PITCH + x / gfx::PIXEL_TO_BYTE_RATIO; }\n    integral_t* cartData(index_t idx) { return as<integral_t>(address::CART_DATA + idx * sizeof(integral_t)); } //TODO: ENDIANNESS!!\n\n    sfx::Sound* sound(sfx::sound_index_t i) { return as<sfx::Sound>(address::SOUNDS + sizeof(sfx::Sound)*i); }\n    sfx::Music* music(sfx::music_index_t i) { return as<sfx::Music>(address::MUSIC + sizeof(sfx::Music)*i); }\n\n    sprite_flags_t* spriteFlagsFor(sprite_index_t index)\n    {\n      return as<sprite_flags_t>(address::SPRITE_FLAGS + index);\n    }\n\n    sprite_index_t* spriteInTileMap(coord_t x, coord_t y)\n    {\n      static_assert(sizeof(sprite_index_t) == 1, \"sprite_index_t must be 1 byte\");\n\n      sprite_index_t *addr;\n\n      if (y >= ROWS_PER_TILE_MAP_HALF)\n        addr = as<sprite_index_t>(address::TILE_MAP_LOW) + x + (y - ROWS_PER_TILE_MAP_HALF) * gfx::TILE_MAP_WIDTH * sizeof(sprite_index_t);\n      else\n        addr = as<sprite_index_t>(address::TILE_MAP_HIGH) + x + y * gfx::TILE_MAP_WIDTH * sizeof(sprite_index_t);\n\n      assert((addr >= memory + address::TILE_MAP_LOW && addr <= memory + address::TILE_MAP_LOW * gfx::TILE_MAP_WIDTH * gfx::TILE_MAP_HEIGHT * sizeof(sprite_index_t)));\n\n      return addr;\n    }\n\n    gfx::sprite_t* spriteAt(sprite_index_t index) {\n      return reinterpret_cast<gfx::sprite_t*>(&memory[address::SPRITE_SHEET\n        + (index % gfx::SPRITES_PER_SPRITE_SHEET_ROW) * gfx::SPRITE_BYTES_PER_SPRITE_ROW]\n        + (index / gfx::SPRITES_PER_SPRITE_SHEET_ROW) * gfx::SPRITE_SHEET_PITCH * gfx::SPRITE_HEIGHT\n        ); }\n    gfx::palette_t* paletteAt(palette_index_t index) { return reinterpret_cast<gfx::palette_t*>(&memory[address::PALETTES + index * BYTES_PER_PALETTE]); }\n\n    template<typename T> T* as(address_t addr) { return reinterpret_cast<T*>(&memory[addr]); }\n  };\n}\n"
  },
  {
    "path": "src/vm/sound.cpp",
    "content": "#include \"sound.h\"\n\n#include \"memory.h\"\n\n#include <random>\n#include <cassert>\n\nusing namespace retro8;\nusing namespace retro8::sfx;\n\n\ninline void DSP::squareWave(uint32_t frequency, int16_t amplitude, int16_t offset, int32_t position, int16_t* dest, size_t samples)\n{\n  const size_t periodLength = float(rate) / frequency;\n  const size_t halfPeriod = periodLength / 2;\n\n  for (size_t i = 0; i < samples; ++i)\n  {\n    const auto sampleInPeriod = position % periodLength;\n    dest[i] += offset + sampleInPeriod < halfPeriod ? -amplitude : amplitude;\n    ++position;\n  }\n}\n\ninline void DSP::pulseWave(uint32_t frequency, int16_t amplitude, int16_t offset, float dutyCycle, int32_t position, int16_t* dest, size_t samples)\n{\n  const size_t periodLength = float(rate) / frequency;\n  const size_t dutyOnLength = dutyCycle * periodLength;\n\n  for (size_t i = 0; i < samples; ++i)\n  {\n    const auto sampleInPeriod = position % periodLength;\n    dest[i] += offset + sampleInPeriod < dutyOnLength ? amplitude : -amplitude;\n    ++position;\n  }\n}\n\ninline void DSP::triangleWave(uint32_t frequency, int16_t amplitude, int16_t offset, int32_t position, int16_t* dest, size_t samples)\n{\n  const size_t periodLength = float(rate) / frequency;\n\n  for (size_t i = 0; i < samples; ++i)\n  {\n    const size_t repetitions = position / periodLength;\n    const float p = position / float(periodLength) - repetitions;\n\n    if (p < 0.50f)\n      dest[i] += offset + amplitude - amplitude * 2 * (p / 0.5f);\n    else\n      dest[i] += offset - amplitude + amplitude * 2 * ((p - 0.5f) / 0.5f);\n\n    ++position;\n  }\n}\n\ninline void DSP::sawtoothWave(uint32_t frequency, int16_t amplitude, int16_t offset, int32_t position, int16_t* dest, size_t samples)\n{\n  const size_t periodLength = float(rate) / frequency;\n\n  for (size_t i = 0; i < samples; ++i)\n  {\n    const size_t repetitions = position / periodLength;\n    const float p = position / float(periodLength) - repetitions;\n    dest[i] += offset - amplitude + amplitude * 2 * p;\n    ++position;\n  }\n}\n\ninline void DSP::tiltedSawtoothWave(uint32_t frequency, int16_t amplitude, int16_t offset, float dutyCycle, int32_t position, int16_t* dest, size_t samples)\n{\n  const size_t periodLength = float(rate) / frequency;\n\n  for (size_t i = 0; i < samples; ++i)\n  {\n    const size_t repetitions = position / periodLength;\n    const float p = position / float(periodLength) - repetitions;\n\n    if (p < dutyCycle)\n      dest[i] += offset - amplitude + amplitude * 2 * (p / dutyCycle);\n    else\n    {\n      const float op = (p - dutyCycle) / (1.0f - dutyCycle);\n      dest[i] += offset + amplitude - amplitude * 2 * op;\n    }\n\n    ++position;\n  }\n}\n\ninline void DSP::organWave(uint32_t frequency, int16_t amplitude, int16_t offset, float coefficient, int32_t position, int16_t* dest, size_t samples)\n{\n  const size_t periodLength = float(rate) / frequency;\n\n  for (size_t i = 0; i < samples; ++i)\n  {\n    const size_t repetitions = position / periodLength;\n    const float p = position / float(periodLength) - repetitions;\n\n    if (p < 0.25f) // drop +a -a\n      dest[i] += offset + amplitude - amplitude * 2 * (p / 0.25f);\n    else if (p < 0.50f) // raise -a +c\n      dest[i] += offset - amplitude + amplitude * (1.0f + coefficient) * (p - 0.25) / 0.25;\n    else if (p < 0.75) // drop +c -a\n      dest[i] += offset + amplitude * coefficient - amplitude * (1.0f + coefficient) * (p - 0.50) / 0.25f;\n    else\n      dest[i] += offset - amplitude + amplitude * 2 * (p - 0.75f) / 0.25f;\n\n    ++position;\n  }\n}\n\ninline void DSP::noise(uint32_t frequency, int16_t amplitude, int32_t position, int16_t* dest, size_t samples)\n{\n  static std::random_device rdevice;\n  static std::mt19937 mt(rdevice());\n\n  std::uniform_int_distribution<int16_t> dist(-amplitude/2, amplitude/2);\n\n  const size_t periodLength = float(rate) / frequency;\n  const size_t halfPeriod = periodLength / 2;\n\n  for (size_t i = 0; i < samples; ++i)\n  {\n    const auto sampleInPeriod = position % periodLength;\n    dest[i] += dist(mt);\n    ++position;\n  }\n}\n\nvoid DSP::fadeIn(int16_t amplitude, int16_t* dest, size_t samples)\n{\n  const float incr = 1.0f / samples;\n\n  for (size_t i = 0; i < samples; ++i)\n  {\n    const float v = dest[i] / amplitude;\n    dest[i] = v * incr * i * amplitude;\n  }\n}\n\nvoid DSP::fadeOut(int16_t amplitude, int16_t* dest, size_t samples)\n{\n  const float incr = 1.0f / samples;\n\n  for (size_t i = 0; i < samples; ++i)\n  {\n    const float v = dest[i] / amplitude;\n    dest[i] = v * incr * (samples - i - 1) * amplitude;\n  }\n}\n\nstatic int pos = 0;\nstatic float period = 44100 / 440.0f;\n\nDSP dsp(44100);\n\n// C C# D D# E F F# G G# A A# B\n\nconstexpr std::array<float, 12> Note::frequencies;\n\nconstexpr float PULSE_WAVE_DEFAULT_DUTY = 1 / 3.0f;\nconstexpr float ORGAN_DEFAULT_COEFFICIENT = 0.5f;\n\nsize_t position = 0;\nint16_t* rendered = nullptr;\n\n\n\nvoid APU::init()\n{\n  static_assert(sizeof(SoundSample) == 2, \"Must be 2 bytes\");\n  static_assert(sizeof(Sound) == 68, \"Must be 68 bytes\");\n  for (auto& channel : channels) channel.sound = nullptr;\n}\n\nvoid APU::play(sound_index_t index, channel_index_t channel, uint32_t start, uint32_t end)\n{\n  queueMutex.lock();\n  queue.emplace_back(index, channel, start, end);\n  queueMutex.unlock();\n}\n\nvoid APU::music(music_index_t index, int32_t fadeMs, int32_t mask)\n{\n  queueMutex.lock();\n  queue.emplace_back(index, fadeMs, mask);\n  queueMutex.unlock();\n}\n\nvoid APU::handleCommands()\n{\n  if (queueMutex.try_lock())\n  {\n    for (Command& c : queue)\n    {\n      if (!c.isMusic)\n      {\n        auto& s = c.sound;\n\n        /* stop sound on channel*/\n        if (s.index == -1)\n        {\n          if (s.channel >= 0 && s.channel <= channels.size())\n            channels[s.channel].sound = nullptr;\n          continue;\n        }\n        /* stop sound from looping */\n        else if (s.index == -2)\n        {\n          continue;\n        }\n        /* stop sound on all channels that are playing it*/\n        else if (s.channel == -2)\n        {\n          for (auto& chan : channels)\n            if (chan.soundIndex == s.index)\n              chan.sound = nullptr;\n          continue;\n        }\n        /* find first available channel*/\n        else if (s.channel == -1)\n          for (size_t i = 0; i < channels.size(); ++i)\n            if (!channels[i].sound)\n            {\n              s.channel = i;\n              break;\n            }\n\n\n        if (s.channel >= 0 && s.channel < channels.size() && s.index >= 0 && s.index <= SOUND_COUNT)\n        {\n          /* overtaking channel */\n          auto& channel = channels[s.channel];\n\n          channel.soundIndex = s.index;\n          channel.sound = memory.sound(s.index);\n          channel.end = s.end;\n          channel.sample = s.start;\n\n          size_t samplePerTick = (44100 / 128) * (channel.sound->speed + 1);\n\n          channel.position = s.start*samplePerTick;\n        }\n      }\n      else\n      {\n        const auto& m = c.music;\n\n        if (m.index == -1)\n          mstate.music = nullptr;\n        else\n        {\n          mstate.pattern = m.index;\n          mstate.music = memory.music(m.index);\n          mstate.channelMask = m.mask;\n\n          for (size_t i = 0; i < CHANNEL_COUNT; ++i)\n          {\n            if (mstate.music->isChannelEnabled(i))\n            {\n              mstate.channels[i].sound = memory.sound(mstate.music->sound(i));\n              mstate.channels[i].sample = 0;\n              mstate.channels[i].position = 0;\n              mstate.channels[i].end = 31; //TODO: fix according to behavior\n            }\n            else\n              mstate.channels[i].sound = nullptr;\n          }\n        }\n      }\n    }\n\n    queue.clear();\n    queueMutex.unlock();\n  }\n\n  /* stop sound on channel*/\n}\n\nvoid APU::updateMusic()\n{\n  if (mstate.music)\n  {\n    for (channel_index_t i = 0; i < CHANNEL_COUNT; ++i)\n    {\n      /* will use channel if channel is forced or there's no sound currently playing there */\n      bool willUseChannel = ((mstate.channelMask & (1 << i)) != 0) || !channels[i].sound;\n\n\n    }\n\n  }\n\n}\n\nvoid APU::updateChannel(SoundState& channel, const Music* music)\n{\n  if (!music)\n  {\n    if (channel.sample >= channel.end)\n      channel.sound = nullptr;\n  }\n  else\n  {\n    /* sound is ended, behavior depends on flag for music*/\n    if (channel.sample >= channel.end)\n    {\n      if (music->isStop())\n      {\n        this->mstate.music = nullptr;\n        for (auto& channel : mstate.channels)\n          channel.sound = nullptr;\n        return;\n      }\n\n      ++mstate.pattern;\n\n      if (music->isLoopEnd() || mstate.pattern == MUSIC_COUNT)\n      {\n        music_index_t i = mstate.pattern - 1;\n        const Music* next = nullptr;\n\n        while (i >= 0)\n        {\n          next = memory.music(i);\n          if (next->isLoopBegin() || i == 0)\n            break;\n\n          --i;\n        }\n\n        mstate.pattern = i;\n        mstate.music = next;\n      }\n\n      mstate.music = memory.music(mstate.pattern);\n\n      for (size_t i = 0; i < CHANNEL_COUNT; ++i)\n      {\n        if (mstate.music->isChannelEnabled(i))\n        {\n          mstate.channels[i].sound = memory.sound(mstate.music->sound(i));\n          mstate.channels[i].sample = 0;\n          mstate.channels[i].position = 0;\n          mstate.channels[i].end = 31; //TODO: fix according to behavior\n        }\n        else\n          mstate.channels[i].sound = nullptr;\n      }\n    }\n  }\n}\n\nvoid APU::renderSound(const SoundState& channel, int16_t* buffer, size_t samples)\n{\n  const SoundSample& sample = channel.sound->samples[channel.sample];\n\n  constexpr int16_t maxVolume = 4096;\n  const int16_t volume = (maxVolume / 8) * sample.volume();\n  const frequency_t frequency = Note::frequency(sample.pitch());\n\n  /* render samples */\n  switch (sample.waveform())\n  {\n  case Waveform::SQUARE:\n    dsp.squareWave(frequency, volume, 0, channel.position, buffer, samples);\n    break;\n  case Waveform::TILTED_SAW:\n    dsp.tiltedSawtoothWave(frequency, volume, 0, 0.85f, channel.position, buffer, samples);\n    break;\n  case Waveform::SAW:\n    dsp.sawtoothWave(frequency, volume, 0, channel.position, buffer, samples);\n    break;\n  case Waveform::TRIANGLE:\n    dsp.triangleWave(frequency, volume, 0, channel.position, buffer, samples);\n    break;\n  case Waveform::PULSE:\n    dsp.pulseWave(frequency, volume, 0, 1 / 3.0f, channel.position, buffer, samples);\n    break;\n  case Waveform::ORGAN:\n    dsp.organWave(frequency, volume, 0, 0.5f, channel.position, buffer, samples);\n    break;\n  case Waveform::NOISE:\n    dsp.noise(frequency, volume, channel.position, buffer, samples);\n    break;\n  }\n}\n\nvoid APU::renderSounds(int16_t* dest, size_t totalSamples)\n{\n  handleCommands();\n\n  constexpr size_t rate = 44100;\n  constexpr int16_t maxVolume = 4096;\n\n  memset(dest, 0, sizeof(int16_t)*totalSamples);\n\n  for (size_t i = 0; i < CHANNEL_COUNT; ++i)\n  {\n    int16_t* buffer = dest;\n    size_t samples = totalSamples;\n\n    SoundState& channel = channels[i].sound ? channels[i] : mstate.channels[i];\n    const Music* music = &channel == &this->mstate.channels[i] ? this->mstate.music : nullptr; //TODO: crappy comparison\n  \n    /* render only if enabled */\n    if ((music && _musicEnabled) || (!music && _soundEnabled))\n    {\n      if (channel.sound)\n      {\n        const size_t samplePerTick = (44100 / 128) * (channel.sound->speed + 1);\n        while (samples > 0 && channel.sound)\n        {\n          /* generate the maximum amount of samples available for same note */\n          // TODO: optimize if next note is equal to current\n          size_t available = std::min(samples, samplePerTick - (channel.position % samplePerTick));\n          renderSound(channel, buffer, available);\n\n          samples -= available;\n          buffer += available;\n          channel.position += available;\n          channel.sample = channel.position / samplePerTick;\n\n          updateChannel(channel, music);\n        }\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "src/vm/sound.h",
    "content": "#pragma once\n\n#include \"defines.h\"\n#include \"common.h\"\n\n#include <array>\n#include <vector>\n#include <mutex>\n\n#if SOUND_ENABLED\n\nnamespace retro8\n{\n  class Memory;\n  \n  namespace sfx\n  {\n    using volume_t = int32_t;\n    using pitch_t = int32_t;\n    using frequency_t = int32_t;\n    using channel_index_t = int32_t;\n    using sound_index_t = int32_t;\n    using music_index_t = int32_t;\n    \n    enum class Waveform\n    {\n      TRIANGLE, TILTED_SAW, SAW, SQUARE, PULSE, ORGAN, NOISE, PHASER\n    };\n\n    enum class Effect\n    {\n      NONE, SLIDE, VIBRATO, DROP, FADE_IN, FADE_OUT, ARPEGGIO_FAST, ARPEGGIO_SLOW\n    };\n\n    enum class Tone { C, CS, D, DS, E, F, FS, G, GS, A, AS, B };\n    struct Note\n    {\n    private:\n      constexpr static std::array<float, 12> frequencies = {\n        //16.35, 17.32f, 18.35f, 19.45f, 20.60f, 21.83f, 23.12f, 24.50f, 25.96f, 27.50f, 29.14f, 30.87f\n        130.81f, 138.59f, 146.83f, 155.56f, 164.81f, 174.61f, 185.00f, 196.00, 207.65, 220.0, 233.08, 246.94\n      };\n\n    public:\n      static pitch_t pitch(Tone tone, int32_t octave = 1) { return pitch_t(tone) + octave * 12; }\n      static frequency_t frequency(Tone tone, int32_t octave = 1) { return frequencies[size_t(tone)] * octave; };\n        static frequency_t frequency(pitch_t pitch) { return frequencies[pitch % 12] / 2 * (1 << (pitch / 12)); }\n    };\n\n    struct SoundSample\n    {\n      static constexpr uint16_t EffectMask = 0x7000;\n      static constexpr uint16_t VolumeMask = 0x0E00;\n      static constexpr uint16_t WaveformMask = 0x01C0;\n      static constexpr uint16_t PitchMask = 0x003F;\n\n      static constexpr uint32_t EffectShift = 12;\n      static constexpr uint32_t VolumeShift = 9;\n      static constexpr uint32_t WaveformShift = 6;\n      \n      //TODO: endianness is a fail here\n      uint16_t value;\n\n      inline bool useSfx() const { return value & 0x8000; }\n      inline Effect effect() const { return Effect((value & EffectMask) >> EffectShift); }\n      inline Waveform waveform() const { return Waveform((value & WaveformMask) >> WaveformShift); }\n      inline volume_t volume() const { return (value & VolumeMask) >> VolumeShift; }\n      inline pitch_t pitch() const { return value & PitchMask; }\n      \n      void setPitch(pitch_t pitch) { value = (value & ~PitchMask) | pitch; }\n      void setVolume(volume_t volume) { value = (value & ~VolumeMask) | (volume << VolumeShift); }\n      void setEffect(Effect effect) { value = (value & ~EffectMask) | (uint16_t(effect) << EffectShift); }\n      void setWaveform(Waveform waveform) { value = (value & ~WaveformMask) | (uint16_t(waveform) << WaveformShift); }\n    };\n\n    struct Sound\n    {\n      std::array<SoundSample, 32> samples;\n      uint8_t editorMode; // TODO ??\n      uint8_t speed; // 1 note = 1/128 sec * speed\n      uint8_t loopStart;\n      uint8_t loopEnd;\n\n      int32_t length() const\n      {        \n        for (int32_t l = samples.size() - 1; l > 0; --l)\n        {\n          if (samples[l].volume() > 0)\n            return l;\n        }\n\n        return 1;\n      }\n    };\n\n    struct Music\n    {\n    private:\n      constexpr static uint8_t SOUND_INDEX_MASK = 0b00111111;\n      constexpr static uint8_t CONFIG_MASK = 0b11000000;\n      constexpr static uint8_t SOUND_ON_FLAG = 0b01000000;\n      constexpr static uint8_t LOOP_FLAG = 0b10000000;\n\n      std::array<uint8_t, 4> indices;\n\n    public:\n      \n      void setSound(channel_index_t channel, sound_index_t index) { indices[channel] = (indices[channel] & CONFIG_MASK) | index | SOUND_ON_FLAG; }\n      void markLoopBegin() { indices[0] |= LOOP_FLAG; }\n      void markLoopEnd() { indices[1] |= LOOP_FLAG; }\n      void markStop() { indices[2] |= LOOP_FLAG; }\n\n      inline bool isLoopBegin() const { return (indices[0] & LOOP_FLAG) != 0; }\n      inline bool isLoopEnd() const { return (indices[1] & LOOP_FLAG) != 0; }\n      inline bool isStop() const { return (indices[2] & LOOP_FLAG) != 0; }\n\n      inline bool isChannelEnabled(channel_index_t channel) const { return (indices[channel] & SOUND_ON_FLAG) != 0; }\n      sound_index_t sound(channel_index_t channel) const { return indices[channel] & SOUND_INDEX_MASK; }\n    };\n\n    using sound_t = Sound;\n    using music_t = Music;\n\n    static constexpr size_t SOUND_COUNT = 64;\n    static constexpr size_t MUSIC_COUNT = 64;\n    static constexpr size_t TICKS_PER_SECOND = 128;\n\n    struct SoundState\n    {\n      const Sound* sound;\n      uint32_t soundIndex;\n      uint32_t sample;\n      uint32_t position; // absolute\n      uint32_t end;\n    };\n\n    struct MusicState\n    {\n      std::array<SoundState, 4> channels;\n      const Music* music;\n      music_index_t pattern;\n      uint8_t channelMask;\n    };\n    \n    class DSP\n    {\n    private:\n      int32_t rate;\n\n    public:\n      DSP(int32_t rate) : rate(rate) { }\n      void squareWave(uint32_t frequency, int16_t amplitude, int16_t offset, int32_t position, int16_t* dest, size_t samples);\n      void pulseWave(uint32_t frequency, int16_t amplitude, int16_t offset, float dutyCycle, int32_t position, int16_t* dest, size_t samples);\n      void triangleWave(uint32_t frequency, int16_t amplitude, int16_t offset, int32_t position, int16_t* dest, size_t samples);\n      void sawtoothWave(uint32_t frequency, int16_t amplitude, int16_t offset, int32_t position, int16_t* dest, size_t samples);\n      void tiltedSawtoothWave(uint32_t frequency, int16_t amplitude, int16_t offset, float dutyCycle, int32_t position, int16_t* dest, size_t samples);\n      void organWave(uint32_t frequency, int16_t amplitude, int16_t offset, float coefficient, int32_t position, int16_t* dest, size_t samples);\n      void noise(uint32_t frequency, int16_t amplitude, int32_t position, int16_t* dest, size_t samples);\n\n      void fadeIn(int16_t amplitude, int16_t* dest, size_t samples);\n      void fadeOut(int16_t amplitude, int16_t* dest, size_t samples);\n\n    };\n\n\n    class APU\n    {\n    public:\n      static constexpr size_t CHANNEL_COUNT = 4;\n\n    private:\n      retro8::Memory& memory;\n      \n      struct Command\n      {\n        bool isMusic;\n\n        union\n        {\n          struct\n          {\n            sound_index_t index;\n            channel_index_t channel;\n            uint32_t start;\n            uint32_t end;\n          } sound;\n\n          struct\n          {\n            music_index_t index;\n            int32_t fadeMs;\n            int32_t mask;\n          } music;\n        };\n\n        Command(sound_index_t index, channel_index_t channel, uint32_t start, uint32_t end) : isMusic(false), sound({ index, channel, start, end }) { }\n        Command(music_index_t index, int32_t fadeMs, int32_t mask) : isMusic(true), music({ index, fadeMs, mask }) { }\n      };\n\n      std::array<SoundState, CHANNEL_COUNT> channels;\n      MusicState mstate;\n\n      std::mutex queueMutex;\n      std::vector<Command> queue;\n\n      bool _soundEnabled, _musicEnabled;\n\n      void handleCommands();\n\n      void updateMusic();\n      void renderSound(const SoundState& sound, int16_t* buffer, size_t samples);\n      void updateChannel(SoundState& channel, const Music* music);\n\n      \n\n    public:\n      APU(Memory& memory) : memory(memory), _soundEnabled(true), _musicEnabled(true) { }\n\n      void init();\n\n      void play(sound_index_t index, channel_index_t channel, uint32_t start, uint32_t end);\n      void music(music_index_t index, int32_t fadeMs, int32_t mask);\n\n      void renderSounds(int16_t* dest, size_t samples);\n\n      bool isMusicEnabled() const { return _musicEnabled; }\n      bool isSoundEnabled() const { return _soundEnabled; }\n\n      void toggleSound(bool active) { _soundEnabled = active; }\n      void toggleMusic(bool active) { _musicEnabled = active; }\n    };\n  }\n}\n\n#endif"
  },
  {
    "path": "status.md",
    "content": "# API Status\n| __Graphics__ | implemented? | tests? | notes |\n| --- | --- | --- | --- |\n| `camera([x,] [y])` | ✔ | ✔ | |\n| `circ(x, y, r, [col])` | ✔ |  | |\n| `circfill(x, y, r, [col])` | ✔ | | |\n| `clip([x,] [y,] [w,] [h])` | ✔ | | |\n| `cls()` | ✔ | | |\n| `color(col)` | ✔ | | |\n| `cursor([x,] [y,] [col])` | ✔ | | |\n| `fget(n, [f])` | ✔ | | |\n| `fillp([pat])` |  | | |\n| `fset(n, [f,] [v])` | ✔ | | |\n| `line(x0, y0, x1, y1, [col])` | ✔ | | |\n| `pal([c0,] [c1,] [p])` | ✔ | | |\n| `palt([c,] [t])` | ✔ | | |\n| `print(str, [x,] [y,] [col])` | ✔ | | |\n| `pset(x, y, [c])` | ✔ | | |\n| `rect(x0, y0, x1, y1, [col])` | ✔ | | |\n| `rectfill(x0, y0, x1, y1, [col])` | ✔ | | |\n| `spr(n, x, y, [w,] [h,] [flip_x,] [flip_y])` | ✔ | | |\n| `sset(x, y, [c])` | ✔ | | |\n| `sspr(sx, sy, sw, sh, dx, dy, [dw,] [dh,] [flip_x,] [flip_y])` | ✔ | | missing flip |\n| __Input__ | | | |\n| `btn([i,] [p])` | ✔ | | 1 player only |\n| `btnp([i,] [p])` | ✔ | | not working as intended, 1 player only |\n| __Math__ | | | |\n| | | | `atan2` only one missing |\n| __Tables__ | | | |\n| | | | all functions implemented, not tested |\n| __Map__ | | | |\n| `map(cel_x, cel_y, sx, sy, cel_w, cel_h, [layer])` | ✔ |  | |\n| `mget(x, y)` | ✔ | | |\n| `mset(x, y, v)` | ✔ | | |\n| __Cartridge__ | | | |\n| `carddata` | ✔ | | just noop for now |\n| `dget` | ✔ | | |\n| `dset` | ✔ | | |\n"
  }
]