[
  {
    "path": ".gitignore",
    "content": "dist\nnode_modules\n/wasm_forth.egg-info\n/_binaryen_c.abi3.so\n/.eggs\n/.vscode\n/build\n/env\n__pycache__\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": "README.md",
    "content": "WASM Forth\n==========\n\nA Forth implementation compiling to WebAssembly.\n\nIt includes an ANS Forth standard environment containing all the CORE words.\nThe system has a fixed amount of memory available, currently 128 MB.\n\nInteraction with Javascript at the moment is limited to textual input (using `WasmForth.source`)\nand output (through the `write` configuration parameter passed to `WasmForth.boot`).\n\nUsing the included (optional) virtual DOM library it's possible to\nwrite interactive web apps. See the code in `examples/todomvc/` for an\nexample TODO list web app fully implemented in Forth.\n\nInstallation\n============\n\n    $ npm install wasm-forth\n\nUsage\n=====\n\nThe following code instantiates the interpreter and runs a program that prints \"Hello, World!\" to the console:\n\n    import * as WasmForth from 'wasm-forth';\n    import wasmURL from 'wasm-forth/dist/kernel.wasm';\n    import coreURL from 'wasm-forth/dist/core.f';\n    import vdomURL from 'wasm-forth/dist/vdom.f';\n\n    WasmForth.boot({\n        wasmURL,\n        sources: [coreURL, vdomURL],\n        write: (text) => {\n            console.log(text);\n        }\n    }).then(() => {\n        WasmForth.source(': HELLO S\" Hello, World!\" TYPE ; HELLO\\n');\n    });\n\n`WasmForth.boot({ ... })` initializes the system and returns a Promise. Once resolved, it's possible to\ninterpret forth code by passing it to `WasmForth.source(string)`. Note that the string passed must end with a newline.\n\n`WasmForth.boot` accepts a configuration object with 3 required parameters:\n\n- `wasmURL`: URL where to fetch the \"kernel.wasm\" included in the NPM package.\n- `sources`: a list of URLs where to fetch the forth \"core.f\" included in the NPM package.\n- `write`: a function that will be called when the forth code needs to output text.\n\nIf you're using webpack, you can use the file-loader (https://github.com/webpack-contrib/file-loader)\nplugin to distribute `kernel.wasm`, `core.f` and `vdom.f`.\n\nYou can also use this library without a module bundler by loading it in a <script> tag.\n\nSee https://github.com/stefano/wasm-forth/tree/master/examples/webpack for an example usage with webpack,\nand https://github.com/stefano/wasm-forth/tree/master/examples/script for an example usage as a <script> tag.\n\nSee https://github.com/stefano/wasm-forth/tree/master/examples/todomvc for an example of a full web app that interacts with the DOM.\n\nBuilding from source\n====================\n\nTo build the forth kernel distribution and the interactive environment (see below), you will\nfirst need to install binaryen (https://github.com/WebAssembly/binaryen)\nand ensure that `libbinaryen.so` is in the library path (LD_LIBRARY_PATH).\n\nThen build the kernel (Python 3.6 is required):\n\n    $ python3.6 -m venv env\n    $ source env/bin/activate\n    $ python setup.py build_ext -L path/to/binaryen/lib/\n    $ python setup.py develop\n    $ python kernel\n    $ npm install\n    $ npm run build # or 'npm run watch'\n\nInteractive Environment\n=======================\n\nThis repository also contains a REPL static page (see the `repl` directory).\nTo serve it locally, follow the instructions above and then run the following command:\n\n    $ python kernel --demo-repl\n\nThe REPL will be served at http://localhost:8080/\n"
  },
  {
    "path": "examples/script/README",
    "content": "To run this example:\n\n    $ npm install\n    $ python3 -m http.server 8080\n\nthen open the browser at http://localhost:8080\n"
  },
  {
    "path": "examples/script/index.html",
    "content": "<!DOCTYPE html>\n\n<html>\n    <head>\n        <title>Example</title>\n    </head>\n    <body>\n        <div id=\"content\"></div>\n        <script type=\"text/javascript\" src=\"node_modules/wasm-forth/dist/wasm-forth.js\"></script>\n        <script type=\"text/javascript\" src=\"index.js\"></script>\n    </body>\n</html>\n"
  },
  {
    "path": "examples/script/index.js",
    "content": "WasmForth.boot({\n    wasmURL: 'node_modules/wasm-forth/dist/kernel.wasm',\n    sources: ['node_modules/wasm-forth/dist/core.f', 'node_modules/wasm-forth/dist/vdom.f'],\n    write: (text) => {\n        document.getElementById('content').textContent += text;\n    }\n}).then(() => {\n    WasmForth.source(': HELLO S\" Hello, World!\" TYPE ; HELLO\\n');\n});\n"
  },
  {
    "path": "examples/script/package.json",
    "content": "{\n  \"name\": \"example\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"author\": \"\",\n  \"license\": \"GPL-3.0\",\n  \"dependencies\": {\n    \"wasm-forth\": \"^2.0.0\"\n  }\n}\n"
  },
  {
    "path": "examples/todomvc/README",
    "content": "To run this example:\n\n    $ npm install\n    $ python3 -m http.server 8080\n\nthen open the browser at http://localhost:8080\n"
  },
  {
    "path": "examples/todomvc/index.f",
    "content": "1 QUIET !\n\nVARIABLE first-render TRUE first-render !\n\n( each todo has: 4 byte length [excluding flags], 1 byte completed flag, 1 byte editing flag, 1 byte show remove button 1 byte focus editing, string content )\n1 MB buffer todos\n\n1025 buffer todo-temp 0 todo-temp !\n1025 buffer item-temp 0 item-temp !\n\n: completed ( addr -- flag ) CELL+ C@ ;\n: set-completed ( flag addr -- ) CELL+ C! ;\n\n: editing ( addr -- flag ) CELL+ 1+ C@ ;\n: set-editing ( flag addr -- ) CELL+ 1+ C! ;\n\n: show-remove ( addr -- flag ) CELL+ 2 + C@ ;\n: set-show-remove ( flag addr -- ) CELL+ 2 + C! ;\n\n: focus ( addr -- flag ) CELL+ 3 + C@ ;\n: set-focus ( flag addr -- ) CELL+ 3 + C! ;\n\n: text-addr ( addr -- addr1 ) 2 CELLS + ;\n: todo-text ( addr -- addr1 u ) text-addr & @ ;\n: todo-text-len @ ;\n\n: bytes-to-end ( addr -- n ) todos buf-next @ SWAP - ;\n: eof-todo ( addr -- addr1 ) todo-text + ;\n: no-space-to-replace? ( u addr -- flag )\n  DUP eof-todo bytes-to-end + + 2 CELLS + todos buf-end > ;\n: set-todo-text ( c-addr u addr -- )\n  2DUP no-space-to-replace? IF abort-task\" no space left to set todo text\" THEN\n  2DUP + 2 CELLS + >R\n  DUP eof-todo DUP bytes-to-end R> 2DUP + >R SWAP MOVE ( make space )\n  R> todos buf-next !\n  2DUP ! ( set text length )\n  2 CELLS + SWAP MOVE ; ( copy text )\n: add-empty-todo ( -- addr ) todos buf-next @ 0 todos ,buf 0 todos ,buf ;\n: remove-todo ( addr -- )\n  DUP eof-todo SWAP OVER bytes-to-end 2DUP + >R MOVE\n  R> todos buf-next ! ;\n: next-todo-offset ( addr1 -- u ) @ 2 CELLS + ;\n: next-todo ( addr -- addr1 ) DUP next-todo-offset + ;\n: remove-completed ( -- )\n  todos BEGIN DUP todos buf-next @ < WHILE DUP completed IF DUP remove-todo ELSE next-todo THEN REPEAT DROP ;\n: each-todo ( xt -- )\n  todos buf-next @ todos = IF DROP EXIT THEN\n  todos buf-next @ todos DO I SWAP DUP >R EXECUTE R> I next-todo-offset +LOOP DROP ;\n: inc-count ( n addr -- n2 ) DROP 1+ ;\n: count-todos ( -- u )\n  0 ['] inc-count each-todo ;\n: inc-completed ( n addr -- n2 ) completed IF 1+ THEN ;\n: count-completed ( -- u ) 0 ['] inc-completed each-todo ;\n: inc-not-completed ( n addr -- n2 ) completed 0= IF 1+ THEN ;\n: count-left ( -- u ) 0 ['] inc-not-completed each-todo ;\n\n: .todo ( addr -- ) todo-text TYPE ;\n: .todos ( -- ) ['] .todo each-todo ;\n\n: is-checked ( flag1 addr -- flag2 ) completed AND ;\n: toggle-all-state ( -- flag )\n  TRUE ['] is-checked each-todo ;\n\n: checked ( -- flag ) S\" target.checked\" 0 0 EVT-ATTR ;\n: key-code ( -- x ) S\" keyCode\" 0 0 EVT-ATTR ;\n\n: clear-completed ( -- ) remove-completed repaint ;\n\n: temp-str ( addr -- c-addr u ) CELL+ & @ ;\n\n: save-todo-temp ( -- ) S\" target.value\" todo-temp CELL+ 1024 EVT-ATTR todo-temp ! ;\n: reset-todo-temp ( -- ) 0 todo-temp ! ;\n: todo-tmp-str ( -- c-addr u ) todo-temp temp-str ;\n\n: set-item-temp ( addr -- ) todo-text TUCK item-temp CELL+ SWAP CMOVE item-temp ! ;\n: item-tmp-str ( -- c-addr u ) item-temp temp-str ;\n\n: on-todo-input ( -- ) save-todo-temp ;\n: on-todo-action ( -- )\n  key-code 13 = IF todo-tmp-str trim DUP 0= IF 2DROP EXIT THEN add-empty-todo set-todo-text reset-todo-temp THEN repaint ;\n: set-completed' ( flag addr -- flag ) OVER /top set-completed ;\n: on-toggle-all ( -- )\n  checked ['] set-completed' each-todo DROP\n  repaint ;\n: on-item-checked ( data -- ) checked SWAP set-completed repaint ;\n: on-todo-item-enter ( addr -- ) TRUE SWAP set-show-remove repaint ;\n: on-todo-item-leave ( addr -- ) 0 SWAP set-show-remove repaint ;\n: on-item-start-editing ( addr -- )\n  DUP set-item-temp\n  TRUE OVER set-editing\n  TRUE OVER set-focus\n  repaint\n  0 SWAP set-focus\n  repaint ;\n: on-remove-todo ( addr -- ) remove-todo repaint ;\n: trim-item ( addr -- )\n  DUP todo-text trim ROT set-todo-text ;\n: on-item-blur ( addr -- )\n  DUP trim-item DUP todo-text-len 0= IF remove-todo ELSE 0 SWAP set-editing THEN repaint ;\n\n: on-item-input ( addr -- )\n  HERE S\" target.value\" HERE 1024 EVT-ATTR ROT set-todo-text repaint ;\n: on-item-action ( addr -- )\n  key-code 13 = IF on-item-blur EXIT THEN\n  key-code 27 = IF item-tmp-str ROT set-todo-text repaint EXIT THEN ( reset from temp )\n  DROP ;\n\n: todo-header ( -- )\n  <header> S\" header\" =class\n   <h1> S\" todos\" text </h1>\n   <input>\n     S\" new-todo\" =class\n     S\" What needs to be done?\" =placeholder\n     first-render @ IF empty-attr =focus THEN\n     ['] on-todo-input =oninput\n     ['] on-todo-action =onkeydown\n     todo-tmp-str to-rbuf =input-value\n   </input>\n  </header> ;\n\n: todo-item ( addr -- )\n  >R\n  <li>\n       R@ bind on-todo-item-enter =onmouseenter\n       R@ bind on-todo-item-leave =onmouseleave\n       R@ editing IF R@ completed IF S\" completed editing\" ELSE S\" editing\" THEN\n                  ELSE R@ completed IF S\" completed\" ELSE S\" \" THEN\n                  THEN =class\n    <div> S\" view\" =class\n      <input>\n        S\" toggle\" =class\n        S\" checkbox\" =type\n        R@ completed IF empty-attr =checked THEN\n        R@ bind on-item-checked =onchange\n      </input>\n      <label> R@ bind on-item-start-editing =ondblclick\n        R@ todo-text to-rbuf text\n      </label>\n      R@ show-remove IF <button> S\" destroy\" =class R@ bind on-remove-todo =onclick </button> THEN\n    </div>\n    <input>\n      S\" edit\" =class\n      R@ todo-text to-rbuf =input-value\n      R@ focus IF empty-attr =focus THEN\n      R@ bind on-item-blur =onblur\n      R@ bind on-item-start-editing =onfocus\n      R@ bind on-item-input =oninput\n      R@ bind on-item-action =onkeydown\n    </input>\n  </li>\n  R> DROP ;\n\n: render-todos ( -- )\n  count-todos 0= IF EXIT THEN\n  <section> S\" main\" =class\n    <input>\n      S\" toggle-all\" =id\n      S\" toggle-all\" =class\n      S\" checkbox\" =type\n      toggle-all-state IF S\" checked\" =checked THEN\n      ['] on-toggle-all =onchange\n    </input>\n    <label> S\" toggle-all\" =for S\" Mark all as complete\" text </label>\n    <ul> S\" todo-list\" =class\n        ['] todo-item each-todo\n    </ul>\n  </section> ;\n\n: items-left ( n-left -- )\n  >R\n  <span>\n    <strong> R@ fmt-int text </strong> S\"  \" text\n    R> 1 = IF S\" item left\" ELSE S\" items left\" THEN text\n  </span> ;\n: clear-completed-btn ( -- )\n  <button> S\" clear-completed\" =class ['] clear-completed =onclick\n    S\" Clear completed\" text\n  </button> ;\n: todo-footer ( n-completed n-left -- )\n  count-todos 0= IF 2DROP EXIT THEN\n  2>R\n  <footer> S\" footer\" =class\n    R> items-left\n    R> 0 > IF clear-completed-btn THEN\n  </footer> ;\n\n: todo-app ( -- )\n  <section> S\" todoapp\" =class\n    todo-header\n    render-todos\n    count-completed count-left todo-footer\n  </section> ;\n\n: footer-info ( -- )\n  <footer> S\" info\" =class\n    <p> S\" Double click to edit a todo\" text </p>\n    <p> S\" Part of \" text <a> S\" https://github.com/stefano/wasm-forth\" =href S\" wasm-forth\" text </a> </p>\n  </footer> ;\n\n: app <div> todo-app footer-info </div> 0 first-render ! ;\n\nrepaint-with app\nrepaint\n\n0 QUIET !\n"
  },
  {
    "path": "examples/todomvc/index.html",
    "content": "<!DOCTYPE html>\n\n<html>\n  <head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n    <title>TodoMVC</title>\n    <link rel=\"stylesheet\" href=\"vendor/index.css\">\n\n    <script type=\"text/javascript\" src=\"node_modules/wasm-forth/dist/wasm-forth.js\"></script>\n    <script type=\"text/javascript\" src=\"index.js\"></script>\n  </head>\n\n  <body id=\"body\">\n  </body>\n</html>\n"
  },
  {
    "path": "examples/todomvc/index.js",
    "content": "WasmForth.boot({\n    wasmURL: 'node_modules/wasm-forth/dist/kernel.wasm',\n    sources: ['node_modules/wasm-forth/dist/core.f', 'node_modules/wasm-forth/dist/vdom.f', 'index.f'],\n    write: msg => console.log(msg)\n});\n"
  },
  {
    "path": "examples/todomvc/package.json",
    "content": "{\n  \"name\": \"example\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"author\": \"\",\n  \"license\": \"GPL-3.0\",\n  \"dependencies\": {\n    \"wasm-forth\": \"^2.0.0\"\n  }\n}\n"
  },
  {
    "path": "examples/todomvc/vendor/index.css",
    "content": "/*\n * Copied from https://github.com/tastejs/todomvc/\n */\n\nhtml,\nbody {\n\tmargin: 0;\n\tpadding: 0;\n}\n\nbutton {\n\tmargin: 0;\n\tpadding: 0;\n\tborder: 0;\n\tbackground: none;\n\tfont-size: 100%;\n\tvertical-align: baseline;\n\tfont-family: inherit;\n\tfont-weight: inherit;\n\tcolor: inherit;\n\t-webkit-appearance: none;\n\tappearance: none;\n\t-webkit-font-smoothing: antialiased;\n\t-moz-osx-font-smoothing: grayscale;\n}\n\nbody {\n\tfont: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;\n\tline-height: 1.4em;\n\tbackground: #f5f5f5;\n\tcolor: #4d4d4d;\n\tmin-width: 230px;\n\tmax-width: 550px;\n\tmargin: 0 auto;\n\t-webkit-font-smoothing: antialiased;\n\t-moz-osx-font-smoothing: grayscale;\n\tfont-weight: 300;\n}\n\n:focus {\n\toutline: 0;\n}\n\n.hidden {\n\tdisplay: none;\n}\n\n.todoapp {\n\tbackground: #fff;\n\tmargin: 130px 0 40px 0;\n\tposition: relative;\n\tbox-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),\n\t            0 25px 50px 0 rgba(0, 0, 0, 0.1);\n}\n\n.todoapp input::-webkit-input-placeholder {\n\tfont-style: italic;\n\tfont-weight: 300;\n\tcolor: #e6e6e6;\n}\n\n.todoapp input::-moz-placeholder {\n\tfont-style: italic;\n\tfont-weight: 300;\n\tcolor: #e6e6e6;\n}\n\n.todoapp input::input-placeholder {\n\tfont-style: italic;\n\tfont-weight: 300;\n\tcolor: #e6e6e6;\n}\n\n.todoapp h1 {\n\tposition: absolute;\n\ttop: -155px;\n\twidth: 100%;\n\tfont-size: 100px;\n\tfont-weight: 100;\n\ttext-align: center;\n\tcolor: rgba(175, 47, 47, 0.15);\n\t-webkit-text-rendering: optimizeLegibility;\n\t-moz-text-rendering: optimizeLegibility;\n\ttext-rendering: optimizeLegibility;\n}\n\n.new-todo,\n.edit {\n\tposition: relative;\n\tmargin: 0;\n\twidth: 100%;\n\tfont-size: 24px;\n\tfont-family: inherit;\n\tfont-weight: inherit;\n\tline-height: 1.4em;\n\tborder: 0;\n\tcolor: inherit;\n\tpadding: 6px;\n\tborder: 1px solid #999;\n\tbox-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);\n\tbox-sizing: border-box;\n\t-webkit-font-smoothing: antialiased;\n\t-moz-osx-font-smoothing: grayscale;\n}\n\n.new-todo {\n\tpadding: 16px 16px 16px 60px;\n\tborder: none;\n\tbackground: rgba(0, 0, 0, 0.003);\n\tbox-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);\n}\n\n.main {\n\tposition: relative;\n\tz-index: 2;\n\tborder-top: 1px solid #e6e6e6;\n}\n\n.toggle-all {\n\twidth: 1px;\n\theight: 1px;\n\tborder: none; /* Mobile Safari */\n\topacity: 0;\n\tposition: absolute;\n\tright: 100%;\n\tbottom: 100%;\n}\n\n.toggle-all + label {\n\twidth: 60px;\n\theight: 34px;\n\tfont-size: 0;\n\tposition: absolute;\n\ttop: -52px;\n\tleft: -13px;\n\t-webkit-transform: rotate(90deg);\n\ttransform: rotate(90deg);\n}\n\n.toggle-all + label:before {\n\tcontent: '❯';\n\tfont-size: 22px;\n\tcolor: #e6e6e6;\n\tpadding: 10px 27px 10px 27px;\n}\n\n.toggle-all:checked + label:before {\n\tcolor: #737373;\n}\n\n.todo-list {\n\tmargin: 0;\n\tpadding: 0;\n\tlist-style: none;\n}\n\n.todo-list li {\n\tposition: relative;\n\tfont-size: 24px;\n\tborder-bottom: 1px solid #ededed;\n}\n\n.todo-list li:last-child {\n\tborder-bottom: none;\n}\n\n.todo-list li.editing {\n\tborder-bottom: none;\n\tpadding: 0;\n}\n\n.todo-list li.editing .edit {\n\tdisplay: block;\n\twidth: calc(100% - 43px);\n\tpadding: 12px 16px;\n\tmargin: 0 0 0 43px;\n}\n\n.todo-list li.editing .view {\n\tdisplay: none;\n}\n\n.todo-list li .toggle {\n\ttext-align: center;\n\twidth: 40px;\n\t/* auto, since non-WebKit browsers doesn't support input styling */\n\theight: auto;\n\tposition: absolute;\n\ttop: 0;\n\tbottom: 0;\n\tmargin: auto 0;\n\tborder: none; /* Mobile Safari */\n\t-webkit-appearance: none;\n\tappearance: none;\n}\n\n.todo-list li .toggle {\n\topacity: 0;\n}\n\n.todo-list li .toggle + label {\n\t/*\n\t\tFirefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433\n\t\tIE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/\n\t*/\n\tbackground-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23ededed%22%20stroke-width%3D%223%22/%3E%3C/svg%3E');\n\tbackground-repeat: no-repeat;\n\tbackground-position: center left;\n}\n\n.todo-list li .toggle:checked + label {\n\tbackground-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23bddad5%22%20stroke-width%3D%223%22/%3E%3Cpath%20fill%3D%22%235dc2af%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22/%3E%3C/svg%3E');\n}\n\n.todo-list li label {\n\tword-break: break-all;\n\tpadding: 15px 15px 15px 60px;\n\tdisplay: block;\n\tline-height: 1.2;\n\ttransition: color 0.4s;\n}\n\n.todo-list li.completed label {\n\tcolor: #d9d9d9;\n\ttext-decoration: line-through;\n}\n\n.todo-list li .destroy {\n\tdisplay: none;\n\tposition: absolute;\n\ttop: 0;\n\tright: 10px;\n\tbottom: 0;\n\twidth: 40px;\n\theight: 40px;\n\tmargin: auto 0;\n\tfont-size: 30px;\n\tcolor: #cc9a9a;\n\tmargin-bottom: 11px;\n\ttransition: color 0.2s ease-out;\n}\n\n.todo-list li .destroy:hover {\n\tcolor: #af5b5e;\n}\n\n.todo-list li .destroy:after {\n\tcontent: '×';\n}\n\n.todo-list li:hover .destroy {\n\tdisplay: block;\n}\n\n.todo-list li .edit {\n\tdisplay: none;\n}\n\n.todo-list li.editing:last-child {\n\tmargin-bottom: -1px;\n}\n\n.footer {\n\tcolor: #777;\n\tpadding: 10px 15px;\n\theight: 20px;\n\ttext-align: center;\n\tborder-top: 1px solid #e6e6e6;\n}\n\n.footer:before {\n\tcontent: '';\n\tposition: absolute;\n\tright: 0;\n\tbottom: 0;\n\tleft: 0;\n\theight: 50px;\n\toverflow: hidden;\n\tbox-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),\n\t            0 8px 0 -3px #f6f6f6,\n\t            0 9px 1px -3px rgba(0, 0, 0, 0.2),\n\t            0 16px 0 -6px #f6f6f6,\n\t            0 17px 2px -6px rgba(0, 0, 0, 0.2);\n}\n\n.todo-count {\n\tfloat: left;\n\ttext-align: left;\n}\n\n.todo-count strong {\n\tfont-weight: 300;\n}\n\n.filters {\n\tmargin: 0;\n\tpadding: 0;\n\tlist-style: none;\n\tposition: absolute;\n\tright: 0;\n\tleft: 0;\n}\n\n.filters li {\n\tdisplay: inline;\n}\n\n.filters li a {\n\tcolor: inherit;\n\tmargin: 3px;\n\tpadding: 3px 7px;\n\ttext-decoration: none;\n\tborder: 1px solid transparent;\n\tborder-radius: 3px;\n}\n\n.filters li a:hover {\n\tborder-color: rgba(175, 47, 47, 0.1);\n}\n\n.filters li a.selected {\n\tborder-color: rgba(175, 47, 47, 0.2);\n}\n\n.clear-completed,\nhtml .clear-completed:active {\n\tfloat: right;\n\tposition: relative;\n\tline-height: 20px;\n\ttext-decoration: none;\n\tcursor: pointer;\n}\n\n.clear-completed:hover {\n\ttext-decoration: underline;\n}\n\n.info {\n\tmargin: 65px auto 0;\n\tcolor: #bfbfbf;\n\tfont-size: 10px;\n\ttext-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);\n\ttext-align: center;\n}\n\n.info p {\n\tline-height: 1;\n}\n\n.info a {\n\tcolor: inherit;\n\ttext-decoration: none;\n\tfont-weight: 400;\n}\n\n.info a:hover {\n\ttext-decoration: underline;\n}\n\n/*\n\tHack to remove background from Mobile Safari.\n\tCan't use it globally since it destroys checkboxes in Firefox\n*/\n@media screen and (-webkit-min-device-pixel-ratio:0) {\n\t.toggle-all,\n\t.todo-list li .toggle {\n\t\tbackground: none;\n\t}\n\n\t.todo-list li .toggle {\n\t\theight: 40px;\n\t}\n}\n\n@media (max-width: 430px) {\n\t.footer {\n\t\theight: 50px;\n\t}\n\n\t.filters {\n\t\tbottom: 10px;\n\t}\n}\n"
  },
  {
    "path": "examples/webpack/README",
    "content": "To run this example:\n\n    $ npm install\n    $ npm run build\n    $ python3 -m http.server 8080\n\nthen open the browser at http://localhost:8080\n"
  },
  {
    "path": "examples/webpack/index.html",
    "content": "<!DOCTYPE html>\n\n<html>\n    <head>\n        <title>Example</title>\n    </head>\n    <body>\n        <div id=\"content\"></div>\n        <script type=\"text/javascript\" src=\"dist/index.js\"></script>\n    </body>\n</html>\n"
  },
  {
    "path": "examples/webpack/index.js",
    "content": "import * as WasmForth from 'wasm-forth';\nimport wasmURL from 'wasm-forth/dist/kernel.wasm';\nimport coreURL from 'wasm-forth/dist/core.f';\nimport vdomURL from 'wasm-forth/dist/vdom.f';\n\nWasmForth.boot({\n    wasmURL,\n    sources: [coreURL, vdomURL],\n    write: (text) => {\n        document.getElementById('content').textContent += text;\n    }\n}).then(() => {\n    WasmForth.source(': HELLO S\" Hello, World!\" TYPE ; HELLO\\n');\n});\n"
  },
  {
    "path": "examples/webpack/package.json",
    "content": "{\n  \"name\": \"example\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"author\": \"\",\n  \"license\": \"GPL-3.0\",\n  \"scripts\": {\n    \"build\": \"webpack\"\n  },\n  \"dependencies\": {\n    \"wasm-forth\": \"^2.0.0\"\n  },\n  \"devDependencies\": {\n    \"file-loader\": \"^1.1.6\",\n    \"webpack\": \"^3.10.0\"\n  }\n}\n"
  },
  {
    "path": "examples/webpack/webpack.config.js",
    "content": "let path = require('path');\n\nmodule.exports = {\n    entry: {\n        main: './index.js'\n    },\n    output: {\n        path: path.resolve(__dirname, 'dist'),\n        filename: 'index.js',\n        publicPath: 'dist/'\n    },\n    module: {\n        rules: [\n            {\n                test   : /\\.(f|wasm)$/,\n                loader : 'file-loader'\n            }\n        ]\n    }\n};\n"
  },
  {
    "path": "kernel/__init__.py",
    "content": ""
  },
  {
    "path": "kernel/__main__.py",
    "content": "import shutil\nimport sys\nimport os\n\nimport assembler\n\n\nBASE_PATH = os.path.abspath(os.path.dirname(__file__))\nDIST_PATH = os.path.join(BASE_PATH, '../dist')\n\nif not os.path.exists(DIST_PATH):\n    os.makedirs(DIST_PATH)\n\nassembler.build_kernel(os.path.join(DIST_PATH, 'kernel.wasm'))\nfor file_name in ('core.f', 'vdom.f'):\n    shutil.copy(\n        os.path.join(BASE_PATH, os.path.join('forth', file_name)),\n        os.path.join(DIST_PATH, file_name),\n    )\n\nif len(sys.argv) > 1 and sys.argv[1] == '--demo-repl':\n    import http.server\n    import socketserver\n\n    REPL_DIST_PATH = os.path.join(BASE_PATH, '../repl/dist/')\n\n    if not os.path.exists(REPL_DIST_PATH):\n        os.makedirs(REPL_DIST_PATH)\n\n    for file_name in ('core.f', 'vdom.f'):\n        shutil.copy(\n            os.path.join(BASE_PATH, 'forth', file_name),\n            os.path.join(REPL_DIST_PATH, file_name),\n        )\n    shutil.copy(\n        os.path.join(DIST_PATH, 'kernel.wasm'),\n        os.path.join(REPL_DIST_PATH, 'kernel.wasm'),\n    )\n\n    os.chdir(os.path.join(BASE_PATH, '..', 'repl'))\n\n    socketserver.TCPServer.allow_reuse_address = True\n    with socketserver.TCPServer(('', 8080), http.server.SimpleHTTPRequestHandler) as httpd:\n        print('Open your browser at http://localhost:8080/')\n        httpd.serve_forever()\n"
  },
  {
    "path": "kernel/asm_ops.py",
    "content": "\"\"\"\nUtilities to make it easier to write webassembly opcodes.\n\"\"\"\n\nfrom _binaryen_c import ffi, lib\n\nfrom binaryen_module import module, retain_gc\nfrom memory_layout import *\n\n\n# Control flow\n\n\ndef block(*instrs, label=None):\n    if label is None:\n        label = ffi.NULL\n    else:\n        label = label.encode('ascii')\n\n    instrs_array = ffi.new('BinaryenExpressionRef[]', _flatten(instrs))\n\n    return lib.BinaryenBlock(\n        module,\n        label,\n        instrs_array,\n        len(instrs_array),\n        lib.BinaryenNone(),\n    )\n\n    retain_gc.append(instrs_array)\n\n\ndef _flatten(lst, res=None):\n    if res is None:\n        res = []\n\n    for item in lst:\n        if isinstance(item, (list, tuple)):\n            _flatten(item, res)\n        else:\n            res.append(item)\n\n    return res\n\n\ndef loop(label, expr):\n    return lib.BinaryenLoop(\n        module,\n        label.encode('ascii'),\n        expr,\n    )\n\n\ndef switch(labels, default_label, cond_expr):\n    labels_array_elems = [ffi.new('char[]', label.encode('ascii')) for label in labels]\n    labels_array = ffi.new('char*[]', labels_array_elems)\n\n    retain_gc(labels_array_elems, labels_array)\n\n    return lib.BinaryenSwitch(module, labels_array, len(labels_array), default_label.encode('ascii'), cond_expr, ffi.NULL)\n\n\ndef jmp(label, cond_expr=ffi.NULL):\n    return lib.BinaryenBreak(module, label.encode('ascii'), cond_expr, ffi.NULL)\n\n\n# Function calls\n\n\ndef call_iiin(label, expr1, expr2, expr3):\n    params = ffi.new('BinaryenExpressionRef[3]', [expr1, expr2, expr3])\n\n    retain_gc(params)\n\n    return lib.BinaryenCall(module, label.encode('ascii'), params, 3, lib.BinaryenNone())\n\n\ndef call_iin(label, expr1, expr2):\n    params = ffi.new('BinaryenExpressionRef[2]', [expr1, expr2])\n\n    retain_gc(params)\n\n    return lib.BinaryenCall(module, label.encode('ascii'), params, 2, lib.BinaryenNone())\n\n\ndef call_iiii_i(label, expr1, expr2, expr3, expr4):\n    params = ffi.new('BinaryenExpressionRef[4]', [expr1, expr2, expr3, expr4])\n\n    retain_gc(params)\n\n    return lib.BinaryenCall(module, label.encode('ascii'), params, 4, lib.BinaryenInt32())\n\n\n# Memory access\n\n\ndef get_reg(reg):\n    return lib.BinaryenGetLocal(module, reg, CELL_TYPE)\n\n\ndef get_double_reg(reg):\n    return lib.BinaryenGetLocal(module, reg, DOUBLE_CELL_TYPE)\n\n\ndef set_reg(reg, expr):\n    return lib.BinaryenSetLocal(module, reg, expr)\n\n\ndef load_cell(addr_expr, cells_offset=0):\n    return lib.BinaryenLoad(\n        module,\n        CELL_SIZE,\n        0,\n        cells_offset * CELL_SIZE,\n        0,\n        CELL_TYPE,\n        addr_expr,\n    )\n\n\ndef load_double_cell(addr_expr, cells_offset=0):\n    return lib.BinaryenLoad(\n        module,\n        CELL_SIZE * 2,\n        0,\n        cells_offset * CELL_SIZE,\n        0,\n        DOUBLE_CELL_TYPE,\n        addr_expr,\n    )\n\n\ndef store_cell(addr_expr, value_expr, cells_offset=0):\n    return lib.BinaryenStore(\n        module,\n        CELL_SIZE,\n        cells_offset * CELL_SIZE,\n        0,\n        addr_expr,\n        value_expr,\n        CELL_TYPE,\n    )\n\n\ndef store_double_cell(addr_expr, value_expr, cells_offset=0):\n    return lib.BinaryenStore(\n        module,\n        CELL_SIZE * 2,\n        cells_offset * CELL_SIZE,\n        0,\n        addr_expr,\n        value_expr,\n        DOUBLE_CELL_TYPE,\n    )\n\n\ndef load_byte(addr_expr):\n    return lib.BinaryenLoad(\n        module,\n        1,\n        0,\n        0,\n        0,\n        CELL_TYPE,\n        addr_expr,\n    )\n\n\ndef store_byte(addr_expr, value_expr):\n    return lib.BinaryenStore(\n        module,\n        1,\n        0,\n        0,\n        addr_expr,\n        value_expr,\n        CELL_TYPE,  # NOTE: there is no 'byte' type in webassembly\n    )\n\n\n# Stack helpers\n\n\ndef invert_double_cell(expr):\n    \"\"\"forth wants low | hi, but wasm is little endian (i.e. the\n    reverse). Cells are already stored in little-endian, so we can get\n    a proper 64 bit number by rotating by 32 bits.\n\n    \"\"\"\n    return lib.BinaryenBinary(module, lib.BinaryenRotRInt64(), expr, lib.BinaryenConst(module, lib.BinaryenLiteralInt64(32)))\n\n\ndef peek(stack_reg, cells_offset):\n    return load_cell(get_reg(stack_reg), cells_offset)\n\n\ndef peek_double(stack_reg, cells_offset):\n    return invert_double_cell(load_double_cell(get_reg(stack_reg), cells_offset))\n\n\ndef put(stack_reg, cells_offset, expr):\n    return store_cell(get_reg(stack_reg), expr, cells_offset)\n\n\ndef put_double(stack_reg, cells_offset, expr):\n    return store_double_cell(get_reg(stack_reg), invert_double_cell(expr), cells_offset)\n\n\ndef inc(reg, n_cells):\n    return set_reg(reg, add_cell_size(reg, n_cells))\n\n\ndef drop(reg, n_cells):\n    return inc(reg, n_cells)\n\n\ndef push(stack_reg, expr):\n    \"\"\"\n    NOTE: the stack size is already incremented by 1 cell when expr is evaluated.\n    \"\"\"\n\n    return [\n        inc(stack_reg, -1),\n        put(stack_reg, 0, expr),\n    ]\n\n\ndef add_cell_size(reg, n_cells):\n    if n_cells == 0:\n        return get_reg(reg)\n\n    return add(\n        get_reg(reg),\n        const_cell(n_cells * CELL_SIZE),\n    )\n\n\ndef cmp_neg(cmp_op):\n    # NOT: cmp_op MUST be the reverse of the desired one!\n    return [\n        put(\n            SP,\n            1,\n            sub(\n                cmp_op(\n                    peek(SP, 1),\n                    peek(SP, 0),\n                ),\n                const_cell(1),\n            ),\n        ),\n        drop(SP, 1),\n    ]\n\n\ndef cmp_neg_zero(cmp_op):\n    # NOT: cmp_op MUST be the reverse of the desired one!\n    return [\n        put(\n            SP,\n            0,\n            sub(\n                cmp_op(\n                    peek(SP, 0),\n                    const_cell(0),\n                ),\n                const_cell(1),\n            ),\n        ),\n    ]\n\n\ndef op_on_tos(op, rhs_expr, stack_reg=SP):\n    \"\"\"\n    Applies X = op(X, rhs_expr), where X is the top of the stack.\n    \"\"\"\n\n    return put(stack_reg, 0, op(peek(stack_reg, 0), rhs_expr))\n\n\ndef bin_op(op):\n    return [\n        put(SP, 1, op(peek(SP, 1), peek(SP, 0))),\n        drop(SP, 1),\n    ]\n\n\ndef bin_op_32_32_64(op):\n    return put_double(SP, 0, op(peek(SP, 1), peek(SP, 0)))\n\n\ndef bin_op_64_32_64(op):\n    return [\n        put_double(SP, 1, op(peek_double(SP, 1), peek(SP, 0))),\n        drop(SP, 1),\n    ]\n\n\n# Constants\n\n\ndef const_cell(value):\n    return lib.BinaryenConst(module, lib.BinaryenLiteralInt32(value))\n\n\ndef const_double_cell(value):\n    return lib.BinaryenConst(module, lib.BinaryenLiteralInt64(value))\n\n\n# Type conversions\n\n\ndef u_32_to_64(expr):\n    return lib.BinaryenUnary(module, lib.BinaryenExtendUInt32(), expr)\n\n\ndef u_64_to_32(expr):\n    return lib.BinaryenUnary(module, lib.BinaryenWrapInt64(), expr)\n\n\ndef s_32_to_64(expr):\n    return lib.BinaryenUnary(module, lib.BinaryenExtendSInt32(), expr)\n\n\ndef s_64_to_32(expr):\n    return lib.BinaryenUnary(module, lib.BinaryenWrapInt64(), expr)\n\n\n# Comparisons\n\n\ndef eqz(expr):\n    return lib.BinaryenUnary(module, lib.BinaryenEqZInt32(), expr)\n\n\ndef eq(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenEqInt32(), expr1, expr2)\n\n\ndef ne(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenNeInt32(), expr1, expr2)\n\n\ndef ge_s(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenGeSInt32(), expr1, expr2)\n\n\ndef ge_u(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenGeUInt32(), expr1, expr2)\n\n\ndef le_s(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenLeSInt32(), expr1, expr2)\n\n\ndef le_u(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenLeUInt32(), expr1, expr2)\n\n\ndef l_s(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenLtSInt32(), expr1, expr2)\n\n\n# Math/bit-ops\n\n\ndef add(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenAddInt32(), expr1, expr2)\n\n\ndef add_64_32(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenAddInt64(), expr1, u_32_to_64(expr2))\n\n\ndef add_64(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenAddInt64(), expr1, expr2)\n\n\ndef sub(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenSubInt32(), expr1, expr2)\n\n\ndef mul(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenMulInt32(), expr1, expr2)\n\n\ndef mul_32_32_64(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenMulInt64(), s_32_to_64(expr1), s_32_to_64(expr2))\n\n\ndef mul_64(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenMulInt64(), expr1, expr2)\n\n\ndef umul_32_32_64(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenMulInt64(), u_32_to_64(expr1), u_32_to_64(expr2))\n\n\ndef div(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenDivSInt32(), expr1, expr2)\n\n\ndef rem(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenRemSInt32(), expr1, expr2)\n\n\ndef div_64_32_32(expr1, expr2):\n    return s_64_to_32(lib.BinaryenBinary(module, lib.BinaryenDivSInt64(), expr1, s_32_to_64(expr2)))\n\n\ndef udiv_64_32_32(expr1, expr2):\n    return u_64_to_32(lib.BinaryenBinary(module, lib.BinaryenDivUInt64(), expr1, u_32_to_64(expr2)))\n\n\ndef udiv_64_32_64(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenDivUInt64(), expr1, u_32_to_64(expr2))\n\n\ndef rem_64_32_32(expr1, expr2):\n    return s_64_to_32(lib.BinaryenBinary(module, lib.BinaryenRemSInt64(), expr1, s_32_to_64(expr2)))\n\n\ndef urem_64_32_32(expr1, expr2):\n    return u_64_to_32(lib.BinaryenBinary(module, lib.BinaryenRemUInt64(), expr1, u_32_to_64(expr2)))\n\n\ndef ls(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenShlInt32(), expr1, expr2)\n\n\ndef a_rs(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenShrSInt32(), expr1, expr2)\n\n\ndef l_rs(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenShrUInt32(), expr1, expr2)\n\n\ndef bit_and(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenAndInt32(), expr1, expr2)\n\n\ndef bit_or(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenOrInt32(), expr1, expr2)\n\n\ndef bit_xor(expr1, expr2):\n    return lib.BinaryenBinary(module, lib.BinaryenXorInt32(), expr1, expr2)\n"
  },
  {
    "path": "kernel/assembler.py",
    "content": "from _binaryen_c import ffi, lib\n\nfrom asm_ops import *\nfrom binaryen_module import module, retain_gc, release_gc\nfrom code_words import load_registers, CODE_WORDS\nfrom forth_interpreter import FORTH_CONSTANTS, FORTH_VARIABLES, FORTH_COL_DEFS\nfrom memory_layout import *\n\n\ndef build_kernel(output_file):\n    \"\"\"\n    Builds the basic forth kernel, with just enough primitives to run an interpreter,\n    and saves it to a WASM file.\n    \"\"\"\n\n    assemble()\n    save_kernel(output_file)\n    destroy()\n\n\ndef assemble():\n    \"\"\"\n    Assembles the forth kernel into the global binaryen module.\n    \"\"\"\n\n    add_imports()\n    add_exports()\n    add_initial_memory()\n    add_interpreter()\n\n\ndef add_imports():\n    \"\"\"\n    Add FFI imports to the module (io.read and io.write).\n    \"\"\"\n\n    iii_params = ffi.new('BinaryenType[3]', [CELL_TYPE] * 3)\n    iiin = lib.BinaryenAddFunctionType(module, b'iiin', lib.BinaryenNone(), iii_params, 3)\n\n    ii_params = ffi.new('BinaryenType[2]', [CELL_TYPE] * 2)\n    iin = lib.BinaryenAddFunctionType(module, b'iin', lib.BinaryenNone(), ii_params, 2)\n\n    iiii_params = ffi.new('BinaryenType[4]', [CELL_TYPE] * 4)\n    iiii_i = lib.BinaryenAddFunctionType(module, b'iiiii', lib.BinaryenInt32(), iiii_params, 4)\n\n    lib.BinaryenAddFunctionImport(module, b'read', b'io', b'read', iiin)\n    lib.BinaryenAddFunctionImport(module, b'write', b'io', b'write', iin)\n    lib.BinaryenAddFunctionImport(module, b'patchBody', b'io', b'patchBody', iin)\n    lib.BinaryenAddFunctionImport(module, b'evtAttr', b'io', b'evtAttr', iiii_i)\n\n    retain_gc(iiii_params)\n    retain_gc(iii_params)\n    retain_gc(ii_params)\n\n\ndef add_exports():\n    \"\"\"\n    Exports the interpreter entry point.\n    \"\"\"\n\n    lib.BinaryenAddExport(module, b'exec', b'exec')\n\n\ndef add_initial_memory():\n    \"\"\"\n    Initializes the memory with compiled forth constants, variables and column definition.\n    \"\"\"\n\n    forth_words_addrs = {}\n    dictionary_bytes = []\n    last_name_addr = 0\n    last_name_addr = add_code_primitives_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr)\n    last_name_addr = add_forth_constants_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr)\n    last_name_addr = add_forth_variables_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr)\n    last_name_addr = add_forth_col_defs_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr)\n\n    # set LATEST to last_name_addr\n    replace_forth_variable_value(dictionary_bytes, forth_words_addrs, 'LATEST', last_name_addr)\n    # set HERE to HERE_INITIAL + len(dictionary_bytes)\n    replace_forth_variable_value(dictionary_bytes, forth_words_addrs, '\\'HERE', HERE_INITIAL + len(dictionary_bytes))\n\n    # main task saved registers initial values, will be loaded into registers when the interpreter first boots\n    reg_initial_bytes = []\n    append_cell(reg_initial_bytes, MAIN_TASK_BASE_VALUE + IP_INITIAL_OFFSET)\n    append_cell(reg_initial_bytes, MAIN_TASK_BASE_VALUE + SP_INITIAL_OFFSET)\n    append_cell(reg_initial_bytes, MAIN_TASK_BASE_VALUE + RS_INITIAL_OFFSET)\n\n    # address of first forth word to run\n    ip_initial_bytes = []\n    append_cell(ip_initial_bytes, forth_words_addrs['ABORT'])\n\n    dictionary_data = ffi.new('char[]', bytes(dictionary_bytes))\n    reg_initial_data = ffi.new('char[]', bytes(reg_initial_bytes))\n    ip_initial_data = ffi.new('char[]', bytes(ip_initial_bytes))\n\n    segment_contents = ffi.new('char*[]', [reg_initial_data, ip_initial_data, dictionary_data])\n    segment_offsets = ffi.new('BinaryenExpressionRef[]', [const_cell(MAIN_TASK_BASE_VALUE),\n                                                          const_cell(MAIN_TASK_BASE_VALUE + IP_INITIAL_OFFSET),\n                                                          const_cell(HERE_INITIAL)])\n    segment_sizes = ffi.new('BinaryenIndex[]', [len(reg_initial_bytes), len(ip_initial_bytes), len(dictionary_bytes)])\n    segments_passive = ffi.new('char[]', bytes([0, 0, 0]))\n\n    # memory size is given in number of 64 KB pages,\n    # in this case we use a fixed 128 MB size\n    lib.BinaryenSetMemory(module, 2048, 2048, b'mem', segment_contents, segments_passive, segment_offsets, segment_sizes, 3, 0)\n\n    retain_gc(dictionary_data, reg_initial_data, segment_contents, segment_offsets, segment_sizes, segments_passive)\n\n\ndef add_interpreter():\n    \"\"\"\n    Adds the interpreter function to the global module.\n    \"\"\"\n\n    ii_params = ffi.new('BinaryenType[2]', [CELL_TYPE, CELL_TYPE])\n    iin = lib.BinaryenAddFunctionType(module, b't_iin', lib.BinaryenNone(), ii_params, len(ii_params))\n\n    registers = ffi.new('BinaryenType[]', 8)\n    registers[IP - 2] = CELL_TYPE\n    registers[W - 2] = CELL_TYPE\n    registers[SP - 2] = CELL_TYPE\n    registers[RS - 2] = CELL_TYPE\n    registers[SCRATCH_1 - 2] = CELL_TYPE\n    registers[SCRATCH_2 - 2] = CELL_TYPE\n    registers[SCRATCH_3 - 2] = CELL_TYPE\n    registers[SCRATCH_DOUBLE_1 - 2] = DOUBLE_CELL_TYPE\n\n    exec_body = block(\n        load_registers(),\n        assemble_interpreter(),\n        label='entry',\n    )\n    lib.BinaryenAddFunction(module, b'exec', iin, registers, len(registers), exec_body)\n\n    retain_gc(ii_params, registers)\n\n\ndef assemble_interpreter():\n    # main interpreter switch to execute code words\n    interpreter_body = switch(\n        [label for label, _ in CODE_WORDS],\n        # memory addresses in the dictionary are always greater than\n        # primitive indexes (because of how far into the memory the\n        # dictionary starts). If a code index is not found, we assume\n        # it's a custom initiation code defined using DOES>, so we\n        # execute (dodoes) to run it.\n        '(dodoes)',\n        load_cell(get_reg(W)),\n    )\n\n    for label, instrs in CODE_WORDS:\n        interpreter_body = block(block(interpreter_body, label=label), instrs)\n\n    interpreter_body = block(\n        set_reg(W, load_cell(get_reg(IP))),\n        inc(IP, 1),\n        loop('interpreter_switch', interpreter_body),\n    )\n\n    return loop('next', interpreter_body)\n\n\ndef add_code_primitives_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr):\n    for code_addr, (label, _) in enumerate(CODE_WORDS):\n        last_name_addr = append_dict_header(dictionary_bytes, forth_words_addrs, last_name_addr, label)\n\n        append_cell(dictionary_bytes, code_addr)\n\n    return last_name_addr\n\n\ndef add_forth_constants_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr):\n    doconst_addr = find_code_primitive_addr('(doconst)')\n\n    for label, initial_value in FORTH_CONSTANTS:\n        last_name_addr = append_dict_header(dictionary_bytes, forth_words_addrs, last_name_addr, label)\n\n        append_cell(dictionary_bytes, doconst_addr)\n        append_cell(dictionary_bytes, initial_value)\n\n    return last_name_addr\n\n\ndef add_forth_variables_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr):\n    dovar_addr = find_code_primitive_addr('(dovar)')\n\n    for label, initial_value in FORTH_VARIABLES:\n        last_name_addr = append_dict_header(dictionary_bytes, forth_words_addrs, last_name_addr, label)\n\n        append_cell(dictionary_bytes, dovar_addr)\n        # variable values can be a byte-string or a single-cell integer\n        if isinstance(initial_value, bytes):\n            append_aligned_bytes(dictionary_bytes, initial_value)\n        else:\n            append_cell(dictionary_bytes, initial_value)\n\n    return last_name_addr\n\n\ndef replace_forth_variable_value(dictionary_bytes, forth_words_addrs, label, new_value):\n    replace_cell(dictionary_bytes, forth_words_addrs[label] + CELL_SIZE - HERE_INITIAL, new_value)\n\n\ndef add_forth_col_defs_dict_entries(dictionary_bytes, forth_words_addrs, last_name_addr):\n    docol_addr = find_code_primitive_addr('(docol)')\n\n    for label, words, immediate in FORTH_COL_DEFS:\n        last_name_addr = append_dict_header(dictionary_bytes, forth_words_addrs, last_name_addr, label, immediate)\n\n        append_cell(dictionary_bytes, docol_addr)\n\n        # compile the body\n        for word in words:\n            if isinstance(word, int):\n                append_cell(dictionary_bytes, word)\n            else:\n                assert word in forth_words_addrs, 'word {} not defined'.format(word)\n                append_cell(dictionary_bytes, forth_words_addrs[word])\n\n        append_cell(dictionary_bytes, forth_words_addrs['EXIT'])\n\n    return last_name_addr\n\n\ndef find_code_primitive_addr(primitive_label):\n    for code_addr, (label, _) in enumerate(CODE_WORDS):\n        if label == primitive_label:\n            return code_addr\n    else:\n        raise Exception('The {} code primitive must be defined'.format(primitive_label))\n\n\ndef append_dict_header(dictionary_bytes, forth_words_addrs, last_name_addr, label, immediate=False):\n    \"\"\"\n    Appends the header for a definition entry in the forth dictionary.\n    Adds the address of the code word to forth_words_addrs, and returns the\n    address where the (length, name) pair starts.\n\n    Header structure:\n    - 4 bytes pointer to previous entry\n    - 1 byte of flags (1 = immediate word, 0 = non-immediate word)\n    - 1 byte of label length\n    - 4-byte aligned label bytes (max 30)\n    \"\"\"\n\n    assert len(label) < 31\n\n    append_cell(dictionary_bytes, last_name_addr)  # pointer to previous entry\n\n    dictionary_bytes.append(int(immediate))  # 1 byte of flags: 1 = IMMEDIATE, 0 = normal\n\n    last_name_addr = HERE_INITIAL + len(dictionary_bytes)\n\n    dictionary_bytes.append(len(label))  # 1 byte of label length (high-bit can be set to 1 to hide the word)\n    append_aligned_bytes(dictionary_bytes, label.encode('ascii'))\n\n    forth_words_addrs[label] = HERE_INITIAL + len(dictionary_bytes)\n\n    return last_name_addr\n\n\ndef append_aligned_bytes(dictionary_bytes, value):\n    dictionary_bytes.extend(value)\n    append_padding(dictionary_bytes)\n\n\ndef append_padding(dictionary_bytes):\n    \"\"\"pad to CELL_SIZE boundary\"\"\"\n\n    size = len(dictionary_bytes)\n    padded_size = ((CELL_SIZE - (size & (CELL_SIZE - 1))) & (CELL_SIZE - 1)) + size\n    dictionary_bytes.extend([0] * (padded_size - size))\n\n\ndef append_cell(dictionary_bytes, value):\n    # webassembly uses little endian\n    dictionary_bytes.append(value & 0xFF)\n    dictionary_bytes.append((value >> 8) & 0xFF)\n    dictionary_bytes.append((value >> 16) & 0xFF)\n    dictionary_bytes.append((value >> 24) & 0xFF)\n\n\ndef replace_cell(dictionary_bytes, offset, value):\n    # webassembly uses little endian\n    dictionary_bytes[offset] = value & 0xFF\n    dictionary_bytes[offset + 1] = (value >> 8) & 0xFF\n    dictionary_bytes[offset + 2] = (value >> 16) & 0xFF\n    dictionary_bytes[offset + 3] = (value >> 24) & 0xFF\n\n\ndef print_debug():\n    lib.BinaryenModulePrint(module)\n\n\ndef save_kernel(output_file):\n    \"\"\"\n    Saves the global module to a file.\n    \"\"\"\n\n    assert lib.BinaryenModuleValidate(module) == 1\n\n    size = 1024\n    while True:\n        buf = ffi.new('char[]', size)\n        written_size = lib.BinaryenModuleWrite(module, buf, size)\n        if written_size < size:\n            with open(output_file, 'w+b') as out:\n                out.write(ffi.buffer(buf, written_size))\n            break\n        size *= 2\n\n\ndef destroy():\n    \"\"\"\n    Frees memory allocated to build to the global module.\n    \"\"\"\n\n    lib.BinaryenModuleDispose(module)\n    release_gc()\n"
  },
  {
    "path": "kernel/binaryen_module.py",
    "content": "from _binaryen_c import lib\n\n_no_gc = []\nmodule = lib.BinaryenModuleCreate()\n\n\ndef retain_gc(*items):\n    _no_gc.extend(items)\n\n\ndef release_gc():\n    global _no_gc\n    _no_gc = []\n"
  },
  {
    "path": "kernel/build_binaryen_ext.py",
    "content": "from os import path\n\nfrom cffi import FFI\n\n\nffibuilder = FFI()\n\nbase_path = path.abspath(path.dirname(__file__))\nheader_path = path.join(base_path, 'vendor/binaryen-c.h')\n\nwith open(header_path, 'r') as header_file:\n    source = header_file.read()\n    ffibuilder.set_source(\n        '_binaryen_c',\n        r\"\"\"\n        #include <stddef.h>\n        #include <stdint.h>\n        {}\"\"\".format(source),\n        libraries=['binaryen'],\n        library_dirs=['vendor'],\n    )\n    ffibuilder.cdef(source)\n\n\nif __name__ == '__main__':\n    ffibuilder.compile(verbose=True)\n"
  },
  {
    "path": "kernel/code_words.py",
    "content": "\"\"\"\nBasic Forth words defined directly in WebAssembly.\n\"\"\"\n\nfrom asm_ops import *\n\n\ndef store_registers():\n    \"\"\"\n    Store registers into the memory, so the interpeter can be restarted,\n    similar to a context switch.\n    \"\"\"\n\n    # NOTE: it's not necessary to store/reload register W, its value\n    # will be refreshed from the IP\n    return [\n        store_cell(_register_mem_addr(IP_MEM_OFFSET), get_reg(IP)),\n        store_cell(_register_mem_addr(SP_MEM_OFFSET), get_reg(SP)),\n        store_cell(_register_mem_addr(RS_MEM_OFFSET), get_reg(RS)),\n    ]\n\n\ndef load_registers():\n    \"\"\"\n    Load registers from the memory, to restart the interpeter,\n    similar to a context switch.\n    \"\"\"\n\n    return [\n        set_reg(IP, load_cell(_register_mem_addr(IP_MEM_OFFSET))),\n        set_reg(SP, load_cell(_register_mem_addr(SP_MEM_OFFSET))),\n        set_reg(RS, load_cell(_register_mem_addr(RS_MEM_OFFSET))),\n    ]\n\n\ndef _register_mem_addr(offset):\n    return add(get_reg(TASK_BASE_PARAM), const_cell(offset))\n\n\ndef _branch():\n    \"\"\"\n    Branch to the instruction indicated by the byte offset stored in the next cell\n    pointed by IP\n    \"\"\"\n\n    return [\n        # relative jump to offset, bytes offset calculated and stored\n        # after the current codeword\n        set_reg(\n            IP,\n            add(\n                get_reg(IP),\n                # note: offset in bytes, user must manually skip the address\n                load_cell(get_reg(IP)),\n            ),\n        ),\n        jmp('next'),\n    ]\n\n\ndef _call_iin_sync(name):\n    return [\n        call_iin(name, peek(SP, 1), peek(SP, 0)),\n        drop(SP, 2),\n    ]\n\n\ndef _call_iiii_i_sync(name):\n    return [\n        put(SP, 3, call_iiii_i(name, peek(SP, 3), peek(SP, 2), peek(SP, 1), peek(SP, 0))),\n        drop(SP, 3),\n    ]\n\n\ndef _call_iiin_async(name):\n    return [\n        # store in temporary registers, so we can drop\n        # from the stack before executing the FFI call\n        set_reg(SCRATCH_1, peek(SP, 1)),\n        set_reg(SCRATCH_2, peek(SP, 0)),\n        drop(SP, 2),\n        # store before the FFI call, so it can re-enter the interpeter asynchronously\n        store_registers(),\n        call_iiin(name, get_reg(TASK_BASE_PARAM), get_reg(SCRATCH_1), get_reg(SCRATCH_2)),\n        # quit, it's responsibility of the FFI call to restart the\n        # interpreter in a future next event loop cycle\n        jmp('entry'),\n    ]\n\n\nCODE_WORDS = [\n    # Initiation codes (non-standard words)\n    ('(docol)', [  # ( R: -- c-addr )\n        push(RS, get_reg(IP)),\n        set_reg(IP, add_cell_size(W, 1)),\n        jmp('next'),\n    ]),\n    ('(doconst)', [  # ( -- x )\n        push(SP, load_cell(get_reg(W), 1)),\n        jmp('next'),\n    ]),\n    ('(dovar)', [  # ( -- a-addr )\n        push(SP, add_cell_size(W, 1)),\n        jmp('next'),\n    ]),\n    ('(dodoes)', [ # ( -- a-addr )\n        push(RS, get_reg(IP)),\n        push(SP, add_cell_size(W, 1)),\n        # see the switch in assemble_interpreter, the cell pointed by\n        # W contains the address to execute compiled in by (DOES>)\n        set_reg(IP, load_cell(get_reg(W))),\n        jmp('next'),\n    ]),\n    # FFI (non-standard words, async)\n    # these quit the interpreter. The called foreign function must then re-enter it. Return value is obtained using 'task-param'.\n    ('READ', [  # ( c-addr u1 -- )\n        _call_iiin_async('read'),\n    ]),\n    # FFI (sync)\n    ('WRITE', [  # ( c-addr u1 -- )\n        _call_iin_sync('write'),\n        jmp('next'),\n    ]),\n    ('PATCH-BODY', [ # ( addr u1 -- )\n\t_call_iin_sync('patchBody'),\n        jmp('next'),\n    ]),\n    ('EVT-ATTR', [ # ( addr1 u1 addr2 u2 -- u3 )\n\t_call_iiii_i_sync('evtAttr'),\n        jmp('next'),\n    ]),\n    # Non-standard extensions, useful to implement the interpreter\n    ('task-base', [ # ( -- addr )\n        push(SP, get_reg(TASK_BASE_PARAM)),\n        jmp('next'),\n    ]),\n    ('task-base!', [ # ( addr -- )\n        set_reg(TASK_BASE_PARAM, peek(SP, 0)),\n        drop(SP, 1),\n        jmp('next'),\n    ]),\n    ('task-param', [ # ( -- x )\n        push(SP, get_reg(TASK_PARAM)),\n        jmp('next'),\n    ]),\n    ('lit', [ # ( -- x )\n        # load literal value kept in next cell, which is now pointed by IP\n        push(SP, load_cell(get_reg(IP))),\n        inc(IP, 1),\n        jmp('next'),\n    ]),\n    ('RP!', [ # ( a-addr -- )\n        set_reg(RS, peek(SP, 0)),\n        drop(SP, 1),\n        jmp('next'),\n    ]),\n    ('RP@', [ # ( -- a-addr )\n        inc(SP, -1),\n        put(SP, 0, get_reg(RS)),\n        jmp('next'),\n    ]),\n    ('SP!', [ # ( a-addr -- )\n        set_reg(SP, peek(SP, 0)),\n        jmp('next'),\n    ]),\n    ('SP@', [ # ( -- a-addr )\n        # returns address of stack top on top of the stack,\n        # counting the newly added address\n        inc(SP, -1),\n        put(SP, 0, get_reg(SP)),\n        jmp('next'),\n    ]),\n    ('SKIP', [  # ( c-addr1 u1 c -- c-addr2 u2 )\n        set_reg(SCRATCH_1, peek(SP, 0)),  # c\n        set_reg(SCRATCH_2, peek(SP, 1)),  # u1\n        set_reg(SCRATCH_3, peek(SP, 2)),  # c-addr1\n        drop(SP, 1),\n        loop(\n            'SKIP-loop',\n            block(\n                jmp(\n                    'SKIP-loop-done',\n                    cond_expr=le_s(get_reg(SCRATCH_2), const_cell(0)),\n                ),\n                jmp(\n                    'SKIP-loop-done',\n                    cond_expr=ne(load_byte(get_reg(SCRATCH_3)), get_reg(SCRATCH_1)),\n                ),\n                set_reg(SCRATCH_2, sub(get_reg(SCRATCH_2), const_cell(1))),\n                set_reg(SCRATCH_3, add(get_reg(SCRATCH_3), const_cell(1))),\n                jmp('SKIP-loop'),\n                label='SKIP-loop-done',\n            ),\n        ),\n        put(SP, 0, get_reg(SCRATCH_2)),\n        put(SP, 1, get_reg(SCRATCH_3)),\n        jmp('next'),\n    ]),\n    ('SCAN', [  # ( c-addr1 u1 c -- c-addr2 u2 )\n        set_reg(SCRATCH_1, peek(SP, 0)),  # c\n        set_reg(SCRATCH_2, peek(SP, 1)),  # u1\n        set_reg(SCRATCH_3, peek(SP, 2)),  # c-addr1\n        drop(SP, 1),\n        loop(\n            'SCAN-loop',\n            block(\n                jmp(\n                    'SCAN-loop-done',\n                    cond_expr=le_s(get_reg(SCRATCH_2), const_cell(0)),\n                ),\n                jmp(\n                    'SCAN-loop-done',\n                    cond_expr=eq(load_byte(get_reg(SCRATCH_3)), get_reg(SCRATCH_1)),\n                ),\n                set_reg(SCRATCH_2, sub(get_reg(SCRATCH_2), const_cell(1))),\n                set_reg(SCRATCH_3, add(get_reg(SCRATCH_3), const_cell(1))),\n                jmp('SCAN-loop'),\n                label='SCAN-loop-done',\n            ),\n        ),\n        put(SP, 0, get_reg(SCRATCH_2)),\n        put(SP, 1, get_reg(SCRATCH_3)),\n        jmp('next'),\n    ]),\n    ('EQ-COUNTED', [  # ( c-addr1 c-addr2 -- flag )\n        set_reg(SCRATCH_1, load_byte(peek(SP, 0))),  # n1\n        set_reg(SCRATCH_2, load_byte(peek(SP, 1))),  # n2\n        block(\n            jmp('eq-counted-if', cond_expr=eq(get_reg(SCRATCH_1), get_reg(SCRATCH_2))),\n            put(SP, 1, const_cell(0)),\n            drop(SP, 1),\n            jmp('next'),\n            label='eq-counted-if',\n        ),\n        loop(\n            'eq-counted-loop',\n            block(\n                block(\n                    jmp(\n                        'eq-counted-ok',\n                        cond_expr=le_s(get_reg(SCRATCH_1), const_cell(0)),\n                    ),\n                    jmp(\n                        'eq-counted-loop-fail',\n                        cond_expr=ne(\n                            load_byte(add(peek(SP, 0), get_reg(SCRATCH_1))),\n                            load_byte(add(peek(SP, 1), get_reg(SCRATCH_1))),\n                        ),\n                    ),\n                    set_reg(SCRATCH_1, sub(get_reg(SCRATCH_1), const_cell(1))),\n                    jmp('eq-counted-loop'),\n                    label='eq-counted-loop-fail',\n                ),\n                put(SP, 1, const_cell(0)),\n                drop(SP, 1),\n                jmp('next'),\n                label='eq-counted-ok',\n            ),\n        ),\n        put(SP, 1, const_cell(-1)),\n        drop(SP, 1),\n        jmp('next'),\n    ]),\n    # Branching/looping (non-standard words)\n    ('branch', [  # ( -- )\n        _branch(),\n    ]),\n    ('?branch', [  # ( x -- )\n        block(\n            jmp('?branch-if', cond_expr=ne(peek(SP, 0), const_cell(0))),\n            drop(SP, 1),\n            _branch(),\n            label='?branch-if',\n        ),\n        drop(SP, 1),\n        inc(IP, 1),  # if false, skip the address\n        jmp('next'),\n    ]),\n    ('(do)', [  # ( limit index -- R: -- loop-end-addr limit index )\n        inc(RS, -3),\n        # copy limit and index in one go\n        store_double_cell(get_reg(RS), load_double_cell(get_reg(SP))),\n        put(RS, 2, load_cell(get_reg(IP))), # the loop end address, stored in the next cell\n        inc(IP, 1), # skip the loop-end-addr\n        drop(SP, 2),\n        jmp('next'),\n    ]),\n    ('(loop)', [  # ( R: loop-end-addr limit index1 -- | loop-end-addr limit index2 )\n        op_on_tos(add, const_cell(1), stack_reg=RS),\n        block(\n            jmp('(loop)-if', l_s(peek(RS, 0), peek(RS, 1))),\n            drop(RS, 3),\n            inc(IP, 1),  # skip the address\n            jmp('next'),\n            label='(loop)-if',\n        ),\n        _branch(),\n    ]),\n    ('(+loop)', [  # ( n -- R: loop-end-addr limit index1 -- | loop-end-addr limit index2 )\n        op_on_tos(add, peek(SP, 0), stack_reg=RS),\n        drop(SP, 1),\n        block(\n            jmp('(+loop)-if', l_s(peek(RS, 0), peek(RS, 1))),\n            drop(RS, 3),\n            inc(IP, 1),  # skip the address\n            jmp('next'),\n            label='(+loop)-if',\n        ),\n        _branch(),\n    ]),\n\n    # Core words\n\n    # Stack manipulation\n    ('>R', [  # ( x -- R: -- x )\n        push(RS, peek(SP, 0)),\n        drop(SP, 1),\n        jmp('next'),\n    ]),\n    ('R>', [  # ( -- x R: x -- )\n        push(SP, peek(RS, 0)),\n        drop(RS, 1),\n        jmp('next'),\n    ]),\n    ('R@', [  # ( -- x R: x -- x )\n        push(SP, peek(RS, 0)),\n        jmp('next'),\n    ]),\n    ('DROP', [  # ( x -- )\n        drop(SP, 1),\n        jmp('next'),\n    ]),\n    ('DUP', [  # ( x -- x x )\n        push(SP, peek(SP, 1)),\n        jmp('next'),\n    ]),\n    ('2DUP', [  # ( x1 x2 -- x1 x2 x1 x2 )\n        inc(SP, -2),\n        store_double_cell(get_reg(SP), load_double_cell(get_reg(SP), 2)),\n        jmp('next'),\n    ]),\n    ('SWAP', [  # ( x1 x2 -- x2 x1 )\n        set_reg(SCRATCH_1, peek(SP, 0)),\n        put(SP, 0, peek(SP, 1)),\n        put(SP, 1, get_reg(SCRATCH_1)),\n        jmp('next'),\n    ]),\n    ('OVER', [  # ( x1 x2 -- x1 x2 x1 )\n        push(SP, peek(SP, 2)),\n        jmp('next'),\n    ]),\n    ('ROT', [  # ( x1 x2 x3 -- x2 x3 x1 )\n        set_reg(SCRATCH_1, peek(SP, 2)),\n        put(SP, 2, peek(SP, 1)),\n        put(SP, 1, peek(SP, 0)),\n        put(SP, 0, get_reg(SCRATCH_1)),\n        jmp('next'),\n    ]),\n    ('NIP', [  # ( x1 x2 -- x2 )\n        put(SP, 1, peek(SP, 0)),\n        drop(SP, 1),\n        jmp('next'),\n    ]),\n    ('TUCK', [  # ( x1 x2 -- x2 x1 x2 )\n        inc(SP, -1),\n        put(SP, 0, peek(SP, 1)),\n        put(SP, 1, peek(SP, 2)),\n        put(SP, 2, peek(SP, 0)),\n        jmp('next'),\n    ]),\n    ('2DROP', [  # ( x x -- )\n        drop(SP, 2),\n        jmp('next'),\n    ]),\n    ('2OVER', [  # ( x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2 )\n        inc(SP, -2),\n        store_double_cell(get_reg(SP), load_double_cell(get_reg(SP), 4)),\n        jmp('next'),\n    ]),\n    ('2SWAP', [  # ( x1 x2 x3 x4 -- x3 x4 x1 x2 )\n        set_reg(SCRATCH_DOUBLE_1, load_double_cell(get_reg(SP))),\n        store_double_cell(get_reg(SP), load_double_cell(get_reg(SP), 2)),\n        store_double_cell(get_reg(SP), get_double_reg(SCRATCH_DOUBLE_1), 2),\n        jmp('next'),\n    ]),\n    # Memory access\n    ('@', [  # ( a-addr -- x )\n        put(SP, 0, load_cell(peek(SP, 0))),\n        jmp('next'),\n    ]),\n    ('!', [  # ( x a-addr -- )\n        store_cell(peek(SP, 0), peek(SP, 1)),\n        drop(SP, 2),\n        jmp('next'),\n    ]),\n    ('+!', [ # ( n1|u1 a-addr -- )\n        store_cell(\n            peek(SP, 0),\n            add(\n                load_cell(peek(SP, 0)),\n                peek(SP, 1),\n            ),\n        ),\n        drop(SP, 2),\n        jmp('next'),\n    ]),\n    ('C@', [  # ( a-addr -- x )\n        put(SP, 0, load_byte(peek(SP, 0))),\n        jmp('next'),\n    ]),\n    ('C!', [  # ( c c-addr -- )\n        store_byte(peek(SP, 0), peek(SP, 1)),\n        drop(SP, 2),\n        jmp('next'),\n    ]),\n    ('CMOVE', [  # ( c-addr1 c-addr2 u -- )\n        set_reg(SCRATCH_1, peek(SP, 2)),  # c-addr-1\n        set_reg(SCRATCH_2, add(get_reg(SCRATCH_1), peek(SP, 0))),  # c-addr-1 + u\n        set_reg(SCRATCH_3, peek(SP, 1)),  # c-addr-2\n        loop(\n            'cmove-loop',\n            block(\n                jmp(\n                    'cmove-loop-done',\n                    cond_expr=le_s(get_reg(SCRATCH_2), get_reg(SCRATCH_1)),\n                ),\n                store_byte(get_reg(SCRATCH_3), load_byte(get_reg(SCRATCH_1))),\n                set_reg(SCRATCH_1, add(get_reg(SCRATCH_1), const_cell(1))),\n                set_reg(SCRATCH_3, add(get_reg(SCRATCH_3), const_cell(1))),\n                jmp('cmove-loop'),\n                label='cmove-loop-done',\n            ),\n        ),\n        drop(SP, 3),\n        jmp('next'),\n    ]),\n    ('CMOVE>', [  # ( c-addr1 c-addr2 u -- )\n        set_reg(SCRATCH_2, peek(SP, 0)),  # u\n        set_reg(SCRATCH_1, peek(SP, 2)),  # c-addr-1\n        set_reg(SCRATCH_3, sub(add(get_reg(SCRATCH_2), peek(SP, 1)), const_cell(1))),  # c-addr-2 + u - 1\n        set_reg(SCRATCH_2, sub(add(get_reg(SCRATCH_2), get_reg(SCRATCH_1)), const_cell(1))),  # c-addr-1 + u - 1\n        loop(\n            'cmove>-loop',\n            block(\n                jmp(\n                    'cmove>-loop-done',\n                    cond_expr=l_s(get_reg(SCRATCH_2), get_reg(SCRATCH_1)),\n                ),\n                store_byte(get_reg(SCRATCH_3), load_byte(get_reg(SCRATCH_2))),\n                set_reg(SCRATCH_2, sub(get_reg(SCRATCH_2), const_cell(1))),\n                set_reg(SCRATCH_3, sub(get_reg(SCRATCH_3), const_cell(1))),\n                jmp('cmove>-loop'),\n                label='cmove>-loop-done',\n            ),\n        ),\n        drop(SP, 3),\n        jmp('next'),\n    ]),\n    # Loops\n    ('I', [ # ( -- n|u R: loop-sys1 -- loop-sys1 )\n        push(SP, peek(RS, 0)),\n        jmp('next'),\n    ]),\n    ('J', [ # ( -- n|u R: loop-sys1 loop-sys2 -- loop-sys1 loop-sys2 )\n        push(SP, peek(RS, 3)),  # a do-loop has 3 control parameters\n        jmp('next'),\n    ]),\n    ('UNLOOP', [ # ( R: loop-end-addr sys1 sys2 -- )\n        drop(RS, 3),\n        jmp('next'),\n    ]),\n    ('LEAVE', [  # ( loop-end-addr limit index -- )\n        set_reg(IP, peek(RS, 2)),\n        drop(RS, 3),\n        jmp('next'),\n    ]),\n    # Control\n    ('EXECUTE', [  # ( i*x xt -- j*x )\n        set_reg(W, peek(SP, 0)),\n        drop(SP, 1),\n        jmp('interpreter_switch'),\n    ]),\n    ('EXIT', [\n        set_reg(IP, load_cell(get_reg(RS))),\n        drop(RS, 1),\n        jmp('next'),\n    ]),\n    ('BYE', [\n        jmp('entry'),\n    ]),\n    # Type conversions\n    ('S>D', [ # ( n -- d )\n        inc(SP, -1),\n        put_double(SP, 0, s_32_to_64(peek(SP, 1))),\n        jmp('next'),\n    ]),\n    ('D>S', [ # ( d -- n )\n        put(SP, 1, s_64_to_32(peek_double(SP, 0))),\n        drop(SP, 1),\n        jmp('next'),\n    ]),\n    # Comparisons\n    ('=', [ # ( x1 x2 -- flag )\n        cmp_neg(ne),\n        jmp('next'),\n    ]),\n    ('<>', [  # ( x1 x2 -- x3 )\n        cmp_neg(eq),\n        jmp('next'),\n    ]),\n    ('<', [ # ( n1 n2 -- flag )\n        cmp_neg(ge_s),\n        jmp('next'),\n    ]),\n    ('>', [ # ( n1 n2 -- flag )\n        cmp_neg(le_s),\n        jmp('next'),\n    ]),\n    ('U<', [  # ( u1 u2 -- flag )\n        cmp_neg(ge_u),\n        jmp('next'),\n    ]),\n    ('U>', [  # ( u1 u2 -- flag )\n        cmp_neg(le_u),\n        jmp('next'),\n    ]),\n    ('0<', [ # ( n -- flag )\n        cmp_neg_zero(ge_s),\n        jmp('next'),\n    ]),\n    ('0=', [ # ( n -- flag )\n        cmp_neg_zero(ne),\n        jmp('next'),\n    ]),\n    # Bitwise operations\n    ('INVERT', [  # ( x1 -- x2 )\n        op_on_tos(bit_xor, const_cell(-1)),\n        jmp('next'),\n    ]),\n    ('AND', [ # ( x1 x2 -- x3 )\n        bin_op(bit_and),\n        jmp('next'),\n    ]),\n    ('OR', [  # ( x1 x2 -- x3 )\n        bin_op(bit_or),\n        jmp('next'),\n    ]),\n    ('XOR', [  # ( x1 x2 -- x3 )\n        bin_op(bit_xor),\n        jmp('next'),\n    ]),\n    ('LSHIFT', [  # ( x1 u -- x2 )\n        bin_op(ls),\n        jmp('next'),\n    ]),\n    ('RSHIFT', [  # ( x1 u -- x2 )\n        bin_op(l_rs),\n        jmp('next'),\n    ]),\n    # Single-cell math\n    ('NEGATE', [  # ( x1 -- x2 )\n        op_on_tos(mul, const_cell(-1)),\n        jmp('next'),\n    ]),\n    ('+', [ # ( n1|u1 n2|u2 -- n3|u3 )\n        bin_op(add),\n        jmp('next'),\n    ]),\n    ('-', [ # ( n1|u1 n2|u2 -- n3|u3 )\n        bin_op(sub),\n        jmp('next'),\n    ]),\n    ('*', [ # ( n1 n2 -- n3 )\n        bin_op(mul),\n        jmp('next'),\n    ]),\n    ('/MOD', [ # ( n1 n2 -- n_rem n_quot )\n        set_reg(SCRATCH_1, div(peek(SP, 1), peek(SP, 0))),\n        put(SP, 1, rem(peek(SP, 1), peek(SP, 0))),\n        put(SP, 0, get_reg(SCRATCH_1)),\n        jmp('next'),\n    ]),\n    ('1+', [ # ( n1|u1 -- n2|u2 )\n        op_on_tos(add, const_cell(1)),\n        jmp('next'),\n    ]),\n    ('1-', [ # ( n1|u1 -- n2|u2 )\n        op_on_tos(add, const_cell(-1)),\n        jmp('next'),\n    ]),\n    ('2*', [ # ( x1 -- x2 )\n        op_on_tos(ls, const_cell(1)),\n        jmp('next'),\n    ]),\n    ('2/', [ # ( x1 -- x2 )\n        op_on_tos(a_rs, const_cell(1)),\n        jmp('next'),\n    ]),\n    # Mixed math\n    ('M*', [ # ( n1 n2 -- d )\n        bin_op_32_32_64(mul_32_32_64),\n        jmp('next'),\n    ]),\n    ('UM*', [ # ( u1 u2 -- ud )\n        bin_op_32_32_64(umul_32_32_64),\n        jmp('next'),\n    ]),\n    ('SM/REM', [ # ( d1 n1 -- n_rem n_quot )\n        set_reg(SCRATCH_1, div_64_32_32(peek_double(SP, 1), peek(SP, 0))),\n        put(SP, 2, rem_64_32_32(peek_double(SP, 1), peek(SP, 0))),\n        put(SP, 1, get_reg(SCRATCH_1)),\n        drop(SP, 1),\n        jmp('next'),\n    ]),\n    ('UM/MOD', [ # ( ud u1 -- u_rem u_quot )\n        set_reg(SCRATCH_1, udiv_64_32_32(peek_double(SP, 1), peek(SP, 0))),\n        put(SP, 1, urem_64_32_32(peek_double(SP, 1), peek(SP, 0))),\n        put(SP, 2, get_reg(SCRATCH_1)),\n        drop(SP, 1),\n        jmp('next'),\n    ]),\n    ('UD/MOD', [ # ( ud1 u1 -- ud_quot u_rem )\n        set_reg(SCRATCH_DOUBLE_1, udiv_64_32_64(peek_double(SP, 1), peek(SP, 0))),\n        put(SP, 0, urem_64_32_32(peek_double(SP, 1), peek(SP, 0))),\n        put_double(SP, 1, get_double_reg(SCRATCH_DOUBLE_1)),\n        jmp('next'),\n    ]),\n    # Double-cell math\n    ('DNEGATE', [  # ( d1 -- d2 )\n        put_double(SP, 0, mul_64(peek_double(SP, 0), const_double_cell(-1))),\n        jmp('next'),\n    ]),\n    ('D+', [  # ( d1|ud1 d2|ud2 -- d3|ud3 )\n        put_double(SP, 2, add_64(peek_double(SP, 2), peek_double(SP, 0))),\n        drop(SP, 2),\n        jmp('next'),\n    ]),\n    ('D*', [ # ( d1|ud1 d2|ud2 -- d3|ud3 )\n        put_double(SP, 2, mul_64(peek_double(SP, 2), peek_double(SP, 0))),\n        drop(SP, 2),\n        jmp('next'),\n    ]),\n]\n"
  },
  {
    "path": "kernel/forth/core.f",
    "content": "1 QUIET !\n\n: IMMEDIATE 1 LATEST @ 1- C! ;\n\n: ( SOURCE >IN @ /STRING 41 SCAN DROP CHAR+ SOURCE DROP - >IN ! ; IMMEDIATE\n\n: CELLS ( n1 -- n2 )\n  0 CELL+ * ;\n\n: NFA>CFA ( c-addr1 -- c-addr2 )\n  ( 127 AND to unsmudge the length in case the definition is hidden )\n  DUP C@ 127 AND + 1+ ALIGNED ;\n\n: DOES> ( R: ret -- )\n  R> LATEST @ NFA>CFA ! ;\n\n: CREATE ( \"<spaces>name\" -- )\n  HEADER lit (dovar) @ , ;\n\n: VARIABLE ( \"<spaces>name\" -- )\n  CREATE 0 CELL+ ALLOT ;\n\n: CONSTANT ( x \"<spaces>name\" -- )\n  HEADER lit (doconst) @ , , ;\n\n: EMBED-STR ( \"ccc<quote>\" -- )\n  SOURCE >IN @ /STRING OVER >R 34 SCAN DROP\n  R@ -\n  DUP CHAR+ >IN +!\n  DUP ,\n  R> HERE ROT DUP >R CMOVE\n  R> ALIGNED ALLOT ;\n\n: GET-EMBEDDED-STR ( -- a-addr u )\n  R> DUP DUP @ + ALIGNED CELL+ >R ( skip the characters when executing )\n  DUP CELL+ SWAP @ ;\n\n: S\" ( \"ccc<quote>\" -- )\n  lit GET-EMBEDDED-STR , EMBED-STR ; IMMEDIATE\n\n: .\" ( \"ccc<quote>\" -- )\n  lit GET-EMBEDDED-STR , EMBED-STR lit WRITE , ; IMMEDIATE\n\n: IF ( compilation: C: -- orig, runtime: x -- )\n  lit ?branch , HERE 0 , ( placeholder, filled in by THEN/ELSE )\n  ; IMMEDIATE\n\n: PATCH-IF ( orig -- )\n  HERE OVER - SWAP !\n  ;\n\n: ELSE ( compilation: C: orig1 -- orig2, runtime: -- )\n  lit branch , HERE 0 , SWAP PATCH-IF\n  ; IMMEDIATE\n\n: THEN ( compilation: C: orig --, runtime: -- )\n  PATCH-IF\n  ; IMMEDIATE\n\n: ' ( \"<spaces>name\" -- xt )\n  BL WORD FIND 0= IF .\" word to compile not found: \" COUNT WRITE ABORT THEN\n  ;\n\n: ['] ( compilation: \"<spaces>name\" --, runtime: -- xt )\n  lit lit , ' , ; IMMEDIATE\n\n: POSTPONE ( compilation: \"<spaces>name\" -- )\n  BL WORD FIND DUP\n  0= IF .\" word to postpone not found: \" OVER COUNT WRITE ABORT THEN\n  SWAP lit lit , ,\n  1 = IF ['] EXECUTE , ELSE ['] , , THEN ; IMMEDIATE\n\n: DO ( compilation: C: -- loop-addr, runtime: n1|u1 n2|u2 -- R: -- loop-end-addr limit index )\n  ['] (do) , 0 , ( will be patched by LOOP/+LOOP )\n  HERE\n  ; IMMEDIATE\n\n: PATCH-DO ( do-sys -- )\n  HERE SWAP 1 CELLS - ! ( patch the paren-do-paren introduced by DO )\n  ;\n\n: LOOP ( compilation: C: do-sys --, runtime: R: loop-sys1 -- | loop-sys2 )\n  ['] (loop) , DUP HERE - ,\n  PATCH-DO\n  ; IMMEDIATE\n\n: +LOOP ( compilation: C: do-sys --, runtime: n -- R: loop-sys1 -- | loop-sys2 )\n  ['] (+loop) , DUP HERE - ,\n  PATCH-DO\n  ; IMMEDIATE\n\n: BEGIN ( compilation: C: -- dest, runtime: -- )\n  HERE\n  ; IMMEDIATE\n\n: UNTIL ( compilation: C: dest -- , runtime: x -- )\n  ['] ?branch , HERE - ,\n  ; IMMEDIATE\n\n: WHILE ( compilation: C: dest -- orig dest, runtime: x -- )\n  ['] ?branch , HERE SWAP 0 , ( placeholder, patched by REPEAT )\n  ; IMMEDIATE\n\n: REPEAT ( compilation: orig dest --, runtime: -- )\n  ['] branch , HERE - ,\n  HERE OVER - SWAP ! ( patch WHILE ?branch offset )\n  ; IMMEDIATE\n\n: AGAIN ( compilation: dest --, runtime: -- )\n  ['] branch , HERE - , ; IMMEDIATE\n\n: [ ( -- )\n  0 STATE ! ; IMMEDIATE\n\n: ] ( -- )\n  1 STATE ! ;\n\n: CHAR ( \"<spaces>name\" -- char )\n  BL WORD 1+ C@ ;\n\n: [CHAR] ( compilation: \"<spaces>name\" --, runtime: -- c )\n  CHAR ['] lit , , ; IMMEDIATE\n\nVARIABLE #SIZE\n1024 CONSTANT #MAX-SIZE\n\n: #NEXT-FREE-SPACE ( -- c-addr )\n  HERE #MAX-SIZE + #SIZE @ - ;\n\n: <# ( -- )\n  0 #SIZE ! ;\n\n: HOLD ( char -- )\n  #NEXT-FREE-SPACE C! 1 #SIZE +! ;\n\n: SIGN ( n -- )\n  0 < IF [CHAR] - HOLD THEN ;\n\n: # ( ud1 -- ud2 )\n  BASE @ UD/MOD DUP 10 < IF 48 ELSE 65 THEN + HOLD ;\n\n: #S ( ud1 -- ud2 )\n  BEGIN # 2DUP 0= SWAP 0= AND UNTIL ;\n\n: #> ( xd -- c-addr u )\n  2DROP #NEXT-FREE-SPACE 1+ #SIZE @ ;\n\n: */MOD ( n1 n2 n3 -- n4 n5 )\n  >R M* R> SM/REM ;\n\n: */ ( n1 n2 n3 -- n4 )\n  */MOD SWAP DROP ;\n\n: FM/MOD ( d1 n1 -- n2 n3 )\n  ( note: the sign is in the high cell )\n  2DUP 0 < SWAP 0 < XOR IF DUP >R SM/REM 1- SWAP R> + SWAP ELSE SM/REM THEN ;\n\n: ABS ( n -- u )\n  DUP 0 < IF 0 SWAP - THEN ;\n\n: TYPE ( c-addr u -- )\n  WRITE ;\n\n: . ( n -- )\n  DUP ABS S>D <# BL HOLD #S ROT SIGN #> TYPE ;\n\n: U. ( u -- )\n  0 <# BL HOLD #S #> TYPE ;\n\n: 2! ( x1 x2 a-addr -- )\n  SWAP OVER ! CELL+ ! ;\n\n: 2@ ( a-addr -- x1 x2 )\n  DUP CELL+ @ SWAP @ ;\n\n: >BODY ( xt -- a-addr )\n  CELL+ ;\n\n: (ABORT\") ( i*x x1 c-addr u -- | i*x R: j*x -- | j*x )\n  ROT IF TYPE ABORT ELSE 2DROP THEN ;\n\n: ABORT\" ( compilation: \"ccc<quote>\" --, runtime: i*x x1 -- | i*x R: j*x -- | j*x )\n  ['] GET-EMBEDDED-STR , EMBED-STR ['] (ABORT\") , ; IMMEDIATE\n\n: ALIGN ( -- )\n  HERE ALIGNED HERE - ALLOT ;\n\n: CHARS ( n1 -- n2 ) ;\n\n: EMIT ( x -- )\n  PAD C! PAD 1 TYPE ;\n\n: CR ( -- )\n  10 EMIT ;\n\n: S= ( c-addr1 u1 c-addr2 u2 -- flag )\n  ROT 2DUP =\n    IF\n      DROP\n      0 DO 2DUP I + C@ SWAP I + C@ = INVERT IF UNLOOP 2DROP 0 EXIT THEN LOOP\n      2DROP 0 1-\n    ELSE\n      2DROP 2DROP 0\n    THEN\n  ;\n\n: TRUE ( -- true )\n  0 1- ;\n\n: ENVIRONMENT? ( c-addr u -- false | i*x true )\n  2DUP S\" /COUNTED-STRING\" S= IF 2DROP 127 TRUE EXIT THEN\n  2DUP S\" /HOLD\" S= IF 2DROP #MAX-SIZE TRUE EXIT THEN\n  2DUP S\" /PAD\" S= IF 2DROP 4096 TRUE EXIT THEN\n  2DUP S\" ADDRESS-UNIT-BITS\" S= IF 2DROP 8 TRUE EXIT THEN\n  2DUP S\" CORE\" S= IF 2DROP TRUE TRUE EXIT THEN\n  2DUP S\" CORE-EXT\" S= IF 2DROP 0 TRUE EXIT THEN\n  2DUP S\" FLOORED\" S= IF 2DROP 0 TRUE EXIT THEN\n  2DUP S\" MAX-CHAR\" S= IF 2DROP TRUE TRUE EXIT THEN\n  2DUP S\" MAX-D\" S= IF 2DROP 0 INVERT DUP 1 RSHIFT TRUE EXIT THEN\n  2DUP S\" MAX-N\" S= IF 2DROP 1 31 LSHIFT 1- TRUE EXIT THEN\n  2DUP S\" MAX-U\" S= IF 2DROP 0 INVERT TRUE EXIT THEN\n  2DUP S\" MAX-UD\" S= IF 2DROP 0 INVERT DUP TRUE EXIT THEN\n  2DUP S\" RETURN-STACK-CELLS\" S= IF 2DROP 1024 TRUE EXIT THEN\n  2DUP S\" STACK-CELLS\" S= IF 2DROP 1024 TRUE EXIT THEN\n  2DROP 0\n  ;\n\n: EVALUATE ( i*x c-addr u -- j*x )\n  SOURCE-ID @ >R\n  IN-BUF @ >R\n  IN-BUF-EOL @ >R\n  IN-BUF-SIZE @ >R\n  >IN @ >R\n\n  -1 SOURCE-ID !\n  0 >IN !\n  IN-BUF-EOL !\n  IN-BUF !\n\n  INTERPRET\n\n  R> >IN !\n  R> IN-BUF-SIZE !\n  R> IN-BUF-EOL !\n  R> IN-BUF !\n  R> SOURCE-ID ! ;\n\n: KEY ( -- char )\n  >IN @ IN-BUF-EOL @ > IF LINE 2DROP 0 >IN ! THEN\n  IN-BUF @ >IN @ + C@ 1 >IN +! ;\n\n: LITERAL ( compilation: x --, runtime: -- x )\n  ['] lit , , ; IMMEDIATE\n\n: MAX ( n1 n2 -- n3 )\n  2DUP < IF SWAP THEN DROP ;\n\n: MIN ( n1 n2 -- n3 )\n  2DUP > IF SWAP THEN DROP ;\n\n: MOD ( n1 n2 -- n3 )\n  /MOD DROP ;\n\n: MOVE ( addr1 addr2 u -- )\n  >R 2DUP < IF R> CMOVE> ELSE R> CMOVE THEN ;\n\n: RECURSE ( compilation: -- )\n  LATEST @ NFA>CFA , ; IMMEDIATE\n\n: SPACE ( -- )\n  BL EMIT ;\n\n: SPACES ( n -- )\n  0 SWAP DO SPACE LOOP ;\n\n: >= ( n1 n2 -- flag )\n  < INVERT ;\n\n: ACCEPT ( c-addr +n1 -- +n2 )\n  >IN @ IN-BUF-EOL @ >= IF LINE 2DROP 0 >IN ! THEN\n  IN-BUF-EOL @ >IN @ - MIN >R ( c-addr R: n2 )\n  IN-BUF @ >IN @ + SWAP R@ MOVE\n  R@ >IN +!\n  R> ;\n\n: ?DUP ( x -- 0 | x x )\n  DUP 0= IF DUP THEN ;\n\n: FILL ( c-addr u c -- )\n  ROT ROT 0 DO 2DUP I + C! LOOP 2DROP ;\n\n( core extension words )\n\n( NOTE: #TIB, .(, .R, :NONAME, ?DO, C\" not implemented )\n\n: 0<> ( x -- flag )\n  0= INVERT ;\n\n: 0> ( x -- flag )\n  0 > ;\n\n: 2>R ( x1 x2 -- R: -- x1 x2 )\n  R> ROT >R SWAP >R >R ;\n\n: 2R> ( -- x1 x2 R: x1 x2 -- )\n  R> R> R> SWAP ROT >R ;\n\n: 2R@ ( -- x1 x2 R: x1 x2 -- x1 x2 )\n  R> R> R> 2DUP >R >R ROT >R SWAP ;\n\n: <> ( x1 x2 - flag )\n  = INVERT ;\n\n( non-standard utilities )\n\n: SP0 ( -- addr ) 10 1024 * CELL+ task-base + ;\n: sl ( -- n ) SP@ CELL+ SP0 SWAP - 0 CELL+ /MOD SWAP DROP ;\n: .NOSPACE ( n -- ) DUP ABS S>D <# #S ROT SIGN #> TYPE ;\n: .sl ( -- ) S\" <\" TYPE sl .NOSPACE S\" > \" TYPE ;\n: PEEK ( u -- x ) 1+ CELLS SP0 SWAP - @ ;\n: .sitem ( u -- ) PEEK . ;\n: .s ( -- ) .sl sl 0 > IF sl 0 DO I .sitem LOOP THEN ;\n\n( setup cooperative multi tasking )\n\n11 1024 * CONSTANT task-size\n5 1024 * CELL+ CONSTANT task-rs-offset\n3 CELLS CONSTANT task-ip-initial-offset\n0 CONSTANT ip-mem-offset\n\nVARIABLE task-free-block 0 task-free-block !\n\n: find-free-block ( -- addr flag )\n  task-free-block @ DUP 0= IF 0 EXIT THEN\n  DUP @ task-free-block ! 1 ;\n: create-block ( -- addr ) HERE task-size ALLOT ;\n: alloc-block ( -- addr ) find-free-block 0= IF DROP create-block THEN ;\n: release-block ( addr -- ) task-free-block @ OVER ! task-free-block ! ;\n\n: end-task ( -- ) task-base release-block BYE ;\n: new-task ( xt -- )\n  alloc-block task-base!\n  >R RESET-SP R>\n  task-base task-rs-offset + RP!\n  EXECUTE end-task ;\n: start-task ( -- ) task-param new-task ;\n\n: ready ( -- ) .\" Ready\" CR 0 QUIET ! RESET-SP 0 (QUIT) ;\n: setup-tasks ( -- )\n  ( must be within word definition, or an async FFI call from the interpreter will mess it up )\n  task-base task-ip-initial-offset + task-base ip-mem-offset + !\n  ( start-task is the new main task )\n  ['] start-task task-base task-ip-initial-offset + !\n  ( run interpreter in new task )\n  ['] ready new-task ;\n\n: (abort-task\") ( c-str u -- ) TYPE end-task ;\n: abort-task\" ( compilation: \"<ccc>quote\" --, runtime: -- )\n  ['] GET-EMBEDDED-STR , EMBED-STR ['] (abort-task\") , ; IMMEDIATE\n\nsetup-tasks ( must be last, since it calls ABORT which empties the I/O buffers )\n"
  },
  {
    "path": "kernel/forth/vdom.f",
    "content": "1 QUIET !\n\n( utils )\n\n: MB 1024 * 1024 * ;\n\n: 2exec ( x w1 w2 -- x1 x2 ) 2>R DUP R> EXECUTE SWAP R> EXECUTE SWAP ;\n: 2exec1 ( x1 x2 w -- x3 x4 ) DUP >R EXECUTE SWAP R> EXECUTE SWAP ;\n: exec-under ( x1 x2 w -- x3 x2 ) SWAP >R EXECUTE R> ;\n\n: compile-push-word ( \"<spaces>name\" -- ) lit lit , ' , ;\n: /top compile-push-word ['] exec-under , ; IMMEDIATE\n: 2& compile-push-word ['] 2exec1 , ; IMMEDIATE\n: pop-here ( -- x ) HERE -1 CELLS + @ -1 CELLS 'HERE +! ;\n: & pop-here lit lit , , compile-push-word ['] 2exec , ; IMMEDIATE\n\n: emit\" 34 EMIT ;\n\n: buffer ( \"<space>name\" size -- ) CELLS CREATE DUP HERE + 2 CELLS + , HERE CELL+ , ALLOT DOES> 2 CELLS + ;\n: buf-next ( buf -- addr ) -1 CELLS + ;\n: buf-cell-rel ( n buf -- addr ) buf-next @ SWAP CELLS + @ ;\n: buf-end ( buf -- u ) -2 CELLS + @ ;\n: buf-reset ( buf -- ) DUP buf-next ! ;\n: buf-assert-space ( n-bytes buf -- ) buf-end & buf-next @ ROT + < IF abort-task\" buffer out of space\" THEN ;\n: ,buf ( x buf -- ) 1 CELLS OVER buf-assert-space TUCK buf-next @ ! buf-next 1 CELLS SWAP +! ;\n: buf-empty? ( buf -- flag ) DUP buf-next @ = ;\n: .buffer ( buf -- )\n  DUP buf-empty? IF DROP .\" empty\" EXIT THEN\n  DUP buf-next @ SWAP DO I @ . 1 CELLS +LOOP ;\n\n: -ROT ( x1 x2 x3 -- x3 x1 x2 ) ROT ROT ;\n: 2@ ( addr1 addr2 -- x1 x2 ) @ SWAP @ SWAP ;\n: idiv /MOD SWAP DROP ;\n: swap-vars ( a1 a2 -- ) 2DUP 2@ >R SWAP ! R> SWAP ! ;\n\n: word-cstr ( \"<spaces>name\" --, E: -- c-addr ) CREATE LATEST @ , DOES> @ ;\n\n: last-char ( addr u -- c ) + 1- C@ ;\n: trim ( addr u -- addr1 u1 ) BL SKIP BEGIN 2DUP last-char BL = OVER 0 > AND WHILE 1- REPEAT ;\n\n( merge sort )\n\nVARIABLE sort-cell-size\n\n: sort-cells ( n1 -- n2 ) sort-cell-size @ * ;\n: sort-cell+ ( n1 -- n2 ) sort-cell-size @ + ;\n: sort-cell-cp ( addr1 addr2 -- ) sort-cell-size @ CMOVE ;\n: sort-cell-aligned ( u1 -- u2 )\n  sort-cell-size @ /MOD SWAP 0 > IF 1+ THEN sort-cell-size @ * ;\n\n1 31 LSHIFT 1- CONSTANT max-int\n: /2-aligned 1 RSHIFT sort-cell-aligned ;\n\n: cp ( to end start -- to-end )\n  DO I @ OVER ! CELL+ 1 CELLS +LOOP max-int OVER ! 1 CELLS sort-cell-aligned + ;\n: prepare ( end mid mid start -- buf-mid buf-start )\n  HERE -ROT cp DUP >R -ROT cp DROP R> HERE ;\n: split ( end start -- end mid mid start )\n  2DUP SWAP OVER - /2-aligned + DUP ROT ;\n: merge ( end start -- )\n  2DUP split prepare\n  2SWAP DO 2DUP 2@ < IF SWAP THEN DUP I sort-cell-cp sort-cell+ sort-cell-size @ +LOOP 2DROP ;\n: merge-sort ( end start -- )\n  2DUP - 2 sort-cells < IF 2DROP EXIT THEN\n  2DUP split RECURSE RECURSE merge ;\n: sort ( addr n -- ) sort-cells OVER + SWAP merge-sort ;\n\n( DOM VM )\n\nword-cstr text-node-type\nword-cstr text-attr-type\n\n1 MB buffer ops\n\n: push-op ( arg op -- ) ops ,buf ops ,buf ;\n: prev-op ( -- op ) ops buf-empty? IF 0 ELSE -2 ops buf-cell-rel @ THEN ;\n: rm-attr ( type -- ) 1 push-op ;\n: set-attr ( addr -- ) DUP @ text-attr-type = IF 10 push-op ELSE 2 push-op THEN ;\n: mk-node ( type -- ) DUP text-node-type = IF 9 push-op ELSE 3 push-op THEN ; ( note: this won't advance the position )\n: skip-node ( -- ) prev-op 4 = IF 1 -1 ops buf-cell-rel +! ELSE 1 4 push-op THEN ;\n: rm-node ( -- ) 0 5 push-op ;\n: enter-node ( -- ) 0 6 push-op ;\n: leave-node ( -- ) prev-op 6 = IF -2 CELLS ops buf-next +! ELSE 0 7 push-op THEN ;\n: stop ( -- ) 0 8 push-op ;\n\n( node & attr structures )\n\n( buffers for use by client code, to keep any non-static strings/event handlers/etc referenced by the vdom )\n1 MB buffer render-buf-1\n1 MB buffer render-buf-2\nVARIABLE render-buf-n render-buf-1 render-buf-n !\nVARIABLE render-buf-c render-buf-2 render-buf-c !\n\n: render-buf ( -- buf ) render-buf-n @ ;\n: ,rbuf ( x -- ) render-buf ,buf ;\n: to-rbuf ( addr1 u -- addr2 u )\n  DUP render-buf buf-assert-space\n  render-buf buf-next @ >R TUCK R@ SWAP CMOVE DUP render-buf buf-next +! R> SWAP ;\n\n1 MB buffer dom-buf-1\n1 MB buffer dom-buf-2\nVARIABLE dom-n dom-buf-1 dom-n !\nVARIABLE dom-c dom-buf-2 dom-c !\n\n: reset-ndom-bufs ( -- ) dom-n @ buf-reset render-buf buf-reset ;\n: swap-diff-buffers ( -- )\n  dom-n dom-c swap-vars\n  render-buf-n render-buf-c swap-vars ;\n: ndom-here ( -- addr ) dom-n @ buf-next ;\n: cdom-here ( -- addr ) dom-c @ buf-next ;\n: ,ndom ( n -- ) dom-n @ ,buf ;\n\n3 CELLS CONSTANT attr-size\n: attr-end-sentinel ( -- ) max-int ,ndom 0 ,ndom 0 ,ndom ;\n\n3 CELLS CONSTANT node-header-size\n: node-start ( type -- node ) ndom-here @ SWAP ,ndom attr-size ,ndom 0 ,ndom attr-end-sentinel ;\n\n: empty-node ( -- node ) 0 node-start ;\n\n: node-type ( node -- x ) @ ;\n: node-attr-size-cell ( node -- addr ) 1 CELLS + ;\n: node-attr-size ( node -- n ) node-attr-size-cell @ ;\n: node-children-size-cell ( node -- addr ) 2 CELLS + ;\n: node-children-size ( node -- n ) node-children-size-cell @ ;\n\n: cur-node-size ( node -- node n ) ndom-here @ OVER - ;\n: node-end ( node -- )\n  empty-node DROP\n  cur-node-size node-header-size - OVER node-attr-size - SWAP node-children-size-cell ! ;\n\n: first-child ( node-addr -- addr ) DUP node-attr-size + node-header-size + ;\n: next-child ( node-addr -- addr2 )\n  DUP DUP node-attr-size SWAP node-children-size node-header-size + + + ;\n: node-n-attrs ( node-addr -- n ) node-attr-size attr-size idiv 1- ; ( don't count sentinel )\n: attr-start ( node-addr -- attr-addr ) node-header-size + ;\n: attr-len-cell ( addr1 -- addr2 ) CELL+ ;\n: attr-str-cell ( addr1 -- addr2 ) 2 CELLS + ;\n: attr-type ( addr1 -- x ) @ ;\n: attr-len ( addr1 -- x ) attr-len-cell @ ;\n: attr-str ( addr1 -- x ) attr-str-cell @ ;\n: inc-attr-size ( node -- node ) attr-size OVER node-attr-size-cell +! ;\n: !attr ( node attr-type value-addr value-len -- node )\n  attr-size NEGATE ndom-here +! ( remove previous sentinel )\n  ROT ,ndom ,ndom ,ndom attr-end-sentinel inc-attr-size ;\n\n: text ( addr n -- )\n  text-node-type node-start text-attr-type 2SWAP !attr node-end ;\n\n: reset-ndom ( -- ) reset-ndom-bufs empty-node DROP reset-ndom-bufs ;\n\n( diffing )\n\n: sort-attrs ( node-addr -- )\n  attr-size sort-cell-size !\n  attr-start & node-n-attrs sort ; ( don't sort sentinel )\n: rem-cur-attr ( cur-attr1 next-attr1 -- cur-attr1 next-attr1 ) OVER rm-attr ;\n: add-next-attr ( cur-attr1 next-attr1 -- cur-attr1 next-attr1 ) DUP set-attr ;\n: attrs-more? ( addr -- flag ) @ max-int <> ;\n: is-attr-xt? ( addr -- flag ) attr-len max-int = ;\n: attr-value-diff ( cur-attr1 next-attr1 -- cur-attr1 next-attr1 )\n  2DUP 2DUP 2& attr-len = -ROT 2& attr-str = AND IF EXIT THEN\n  add-next-attr ;\n: inc-attr ( addr1 -- addr2 ) DUP attrs-more? IF attr-size + THEN ;\n: attr-diff-1 ( cur-attr1 next-attr1 -- cur-attr2 next-attr2 )\n  2DUP 2& attr-type = IF attr-value-diff 2& inc-attr ELSE\n  2DUP 2& attr-type < IF rem-cur-attr /top inc-attr ELSE ( note: sentinel is max-int )\n                         add-next-attr inc-attr\n  THEN THEN ;\n: attr-diff ( cur-node next-node -- )\n  2DUP sort-attrs sort-attrs\n  2& attr-start BEGIN 2DUP 2& attrs-more? OR WHILE attr-diff-1 REPEAT 2DROP ;\n\n: first-children ( cur-node next-node -- cur-node1 next-node1 ) 2& first-child ;\n: next-children ( cur-node next-node -- cur-node1 next-node1 ) 2& next-child ;\n: next-child-next next-child ;\n: next-child-cur /top next-child ;\n\n: is-child? ( parent-node node -- flag ) SWAP next-child < ;\n: end-node? ( node -- flag ) @ 0= ;\n: create-attrs ( node -- )\n  attr-start BEGIN DUP attrs-more? WHILE DUP set-attr attr-size + REPEAT DROP ;\n: create-tree ( node -- )\n  DUP node-type mk-node\n  DUP create-attrs\n  first-child enter-node BEGIN DUP end-node? INVERT WHILE DUP RECURSE next-child REPEAT leave-node skip-node\n  DROP ;\n: node-diff ( cur-node1 next-node1 -- cur-node2 next-node2 )\n  2DUP 2& end-node? AND IF leave-node skip-node next-children ELSE\n  2DUP 2& node-type = IF 2DUP attr-diff enter-node first-children ELSE\n  DUP end-node? IF rm-node next-child-cur ELSE\n  DUP create-tree next-child-next THEN THEN THEN ;\n: more-nodes? ( cur-node next-node -- flag )\n  ndom-here @ < SWAP cdom-here @ < OR ;\n: nodes-diff ( cur-node next-node -- )\n  BEGIN 2DUP more-nodes? WHILE node-diff REPEAT 2DROP ;\n: diff ( -- )\n  ops buf-reset dom-c @ dom-n @ nodes-diff stop swap-diff-buffers ;\n\n: render ( xt -- )\n  reset-ndom EXECUTE diff ops 0 PATCH-BODY ;\n\n: def-tag CREATE LATEST @ , DOES> @ node-start ;\n: closed-by CREATE DOES> DROP node-end ;\n\n: def-attr CREATE LATEST @ , DOES> @ -ROT !attr ;\n\n: def-event CREATE LATEST @ , DOES> @ SWAP -1 !attr ;\n\n: (bind) ( data xt1 -- xt2 )\n  render-buf buf-next @ >R SWAP\n  lit (docol) @ ,rbuf lit lit ,rbuf ,rbuf ,rbuf lit EXIT ,rbuf R> ;\n: bind ( \"<spaces>name\" -- ) compile-push-word ['] (bind) , ; IMMEDIATE\n\n: empty-attr ( -- c-addr u ) S\" \" ;\n: fmt-int ( n -- addr u ) S>D <# #S #> to-rbuf ;\n\nVARIABLE render-xt\n: repaint ( -- ) render-xt @ render ;\n: repaint-with ( \"<spaces>name\" -- ) ' render-xt ! ;\n\n( define a few common tags/attrs/events )\n\ndef-tag <footer> closed-by </footer>\ndef-tag <section> closed-by </section>\ndef-tag <button> closed-by </button>\ndef-tag <ul> closed-by </ul>\ndef-tag <li> closed-by </li>\ndef-tag <a> closed-by </a>\ndef-tag <span> closed-by </span>\ndef-tag <p> closed-by </p>\ndef-tag <div> closed-by </div>\ndef-tag <label> closed-by </label>\ndef-tag <input> closed-by </input>\ndef-tag <header> closed-by </header>\ndef-tag <h1> closed-by </h1>\ndef-tag <strong> closed-by </strong>\n\ndef-attr =class\ndef-attr =id\ndef-attr =for\ndef-attr =placeholder\ndef-attr =type\ndef-attr =checked\ndef-attr =value\ndef-attr =href\n\n( virtual attrs )\ndef-attr =input-value\ndef-attr =focus\n\ndef-event =onclick\ndef-event =oninput\ndef-event =onchange\ndef-event =onkeydown\ndef-event =onmouseenter\ndef-event =onmouseleave\ndef-event =ondblclick\ndef-event =onblur\ndef-event =onfocus\n\n0 QUIET !\n"
  },
  {
    "path": "kernel/forth_interpreter.py",
    "content": "\"\"\"\nForth interepter, defined in Forth within Python.\n\"\"\"\n\nfrom asm_ops import *\nfrom memory_layout import *\n\n\ndef forth_def(label, *code, immediate=False):\n    \"\"\"\n    Splits each code string into forth byte-string words, and returns a flat list of words.\n    Also allows to define labels using '~<label name>', which are not returned as words,\n    and label references using ':~<label-name>', which are replaced by an integer offset\n    from the current position to the label definition.\n    \"\"\"\n\n    # first, find labels and their offset from the start of the colon definition\n    jump_labels = {}\n    code_offset = 0\n    for item in code:\n        if isinstance(item, int):\n            # literals use 2 cells\n            code_offset += 2\n            continue\n        else:\n            for word in item.split(' '):\n                if word == '':\n                    continue\n\n                if word.startswith('~'):\n                    # a label definition\n                    jump_labels[word] = code_offset\n                    continue\n                elif word.startswith(':~'):\n                    # a label reference, will use 1 cell\n                    code_offset += 1\n                    continue\n\n                try:\n                    int(word)\n                    # an int literal\n                    code_offset += 2\n                except ValueError:\n                    # it's a word reference\n                    code_offset += 1\n\n    res = []\n    for item in code:\n        if isinstance(item, int):\n            res.append('lit')\n            res.append(item)\n        else:\n            for word in item.split(' '):\n                if word == '':\n                    continue\n\n                if word.startswith('~'):\n                    # don't add labels to ouput\n                    continue\n                elif word.startswith(':~'):\n                    jump_label = word[1:]\n                    offset = CELL_SIZE * (jump_labels[jump_label] - len(res))\n                    res.append(offset)\n                    continue\n\n                try:\n                    value = int(word)\n                    res.append('lit')\n                    res.append(value)\n                except ValueError:\n                    res.append(word)\n\n    return label, res, immediate\n\n\nWORD_NOT_FOUND_ERR = b'word not found: '\nOK_MSG = b' ok\\n'\n\n\nFORTH_CONSTANTS = [\n    ('IN-BUF-MAX', PAD_START - BUFFER_START),\n    ('PAD', PAD_START),\n]\n\n\nFORTH_VARIABLES = [\n    ('STATE', 0),\n    ('SOURCE-ID', 0),\n    ('IN-BUF', BUFFER_START),\n    ('>IN', 0),\n    ('IN-BUF-EOL', -1),  # index of line terminator in input buffer\n    ('IN-BUF-SIZE', 0),  # number of chars in input buffer\n    ('\\'HERE', 0),\n    ('LATEST', 0),  # not standard: pointer to start of the last defined word (points to the address of the name length)\n    ('BASE', 10),\n    ('WORD-NOT-FOUND-ERR', WORD_NOT_FOUND_ERR),\n    ('QUIET', 0),  # not standard: tells if the interpreter prints \" OK\"\n    ('OK-MSG', OK_MSG),\n]\n\n\nFORTH_COL_DEFS = [\n    forth_def(\n        'HERE',  # ( -- a-addr )\n        '\\'HERE @',\n    ),\n    forth_def(\n        'ALLOT',  # ( n -- )\n        '\\'HERE +!',\n    ),\n    forth_def(\n        'CELL+',  # ( a-addr1 -- a-addr2 )\n        CELL_SIZE, '+',\n    ),\n    forth_def(\n        'SOURCE',  # ( -- c-addr u )\n        'IN-BUF @',\n        'IN-BUF-EOL @',\n    ),\n    forth_def(\n        'SCAN-NEWLINE',  # ( -- newline-addr u )\n        'IN-BUF @ IN-BUF-SIZE @', ord('\\n'), 'SCAN',\n    ),\n    forth_def(\n        'ADDR>IN-BUF-EOL!',  # ( newline-addr -- )\n        'IN-BUF @ - IN-BUF-EOL !',\n    ),\n    forth_def(\n        'LINE',  # ( -- c-addr u )\n        'IN-BUF @', # ( in )\n        'IN-BUF-EOL @ 1+', # ( in index-after-newline )\n        'OVER +', # ( in new-line-addr+1 )\n        'SWAP IN-BUF-SIZE @ 1- IN-BUF-EOL @ - DUP >R', # ( new-line-addr+1 in n-remaining R: n-remaining )\n        'CMOVE', # ( R: n-remaining )\n        'R> IN-BUF-SIZE !', # ( )\n        'SCAN-NEWLINE', # ( newline-addr u )\n        '0 > ?branch :~REFILL', # ( newline-addr )\n        'ADDR>IN-BUF-EOL! branch :~FINISH',\n        '~REFILL',\n        'IN-BUF-MAX IN-BUF-SIZE @ - READ task-param IN-BUF-SIZE +!', # ( )\n        # even if we don't find a newline now, consider it a newline\n        # TODO: show an error if we still didn't find a newline, a single line must be less than 4k chars long\n        'SCAN-NEWLINE DROP ADDR>IN-BUF-EOL!',\n        '~FINISH SOURCE',\n    ),\n    forth_def(\n        'BL',  # ( -- c )\n        ord(b' '),\n    ),\n    forth_def(\n        'CHAR+',  # ( a-addr1 -- a-addr2 )\n        '1+'\n    ),\n    forth_def(\n        '>COUNTED',  # ( a-addr-src n a-addr-dst -- )\n        '2DUP C! CHAR+ SWAP CMOVE'\n    ),\n    forth_def(\n        '/STRING',  # ( a-addr u n -- a-addr+n u-n )\n        'DUP >R -',  # ( a-addr u-n R: n )\n        'SWAP R> +',  # ( u-n a-addr+n R: )\n        'SWAP',\n    ),\n    forth_def(\n        '_WORD',  # ( dest-addr c -- c-addr )\n        '>R SOURCE >IN @ /STRING R@ SKIP',  # ( dest-addr c-addr-start u-start R: c )\n        'SWAP DUP ROT', # ( dest-addr c-addr-start c-addr-start u-start R: c )\n        'R> SCAN', # ( dest-addr c-addr-start c-addr-end u-end R: )\n        '>R OVER -', # ( dest-addr c-addr-start (c-addr-end-c - addr-start) R: u-end )\n        'ROT DUP >R >COUNTED R>', # ( dest-addr R: u-end )\n        'SOURCE R@ - + R>', # ( dest-addr c-addr-end u-end )\n        '1 /STRING', # ( dest-addr c-addr-end-skipped u-end-skipped )\n        'SOURCE ROT -', # ( dest-addr c-addr-end-skipped c-addr (u - u-end-skipped) )\n        '>IN ! DROP DROP', # ( dest-addr )\n    ),\n    forth_def(\n        'WORD',  # ( c -- c-addr )\n        'HERE SWAP _WORD',\n    ),\n    forth_def(\n        'ALIGNED',  # ( u1 -- u2 )\n        CELL_SIZE, 'OVER', CELL_SIZE - 1, 'AND -', CELL_SIZE - 1, 'AND +',\n    ),\n    forth_def(\n        'COUNT',  # ( c-addr1 -- c-addr2 u )\n        'DUP C@ SWAP 1+ SWAP',\n    ),\n    forth_def(\n        'FIND',  # ( c-addr -- c-addr 0  |  xt 1  |  xt -1 )\n        '>R', # ( R: c-addr )\n        'LATEST @', # ( a-addr R: c-addr )\n        '~LOOP DUP 0=', # ( a-addr flag R: c-addr )\n        '?branch :~NOT-ZERO', # ( a-addr R: c-addr )\n        'DROP R> 0 EXIT', # ( c-addr 0 )\n        '~NOT-ZERO DUP R@', # ( a-addr a-addr c-addr R: c-addr )\n        'EQ-COUNTED', # ( a-addr flag R: c-addr )\n        '?branch :~NOT-EQ', # ( a-addr R: c-addr )\n        'DUP DUP C@ 127 AND 1+ + ALIGNED', # ( a-addr a-addr' R: c-addr ) 127 AND to remove the smudge bit\n        'SWAP 1-', # ( a-addr' (a-addr - 1) R: c-addr )\n        'C@ 1 =', # ( a-addr' is-imm-flag R: c-addr )\n        'R> DROP', # ( a-addr' is-imm-flag )\n        '0= 1 OR EXIT', # ( a-addr' -1/1 )\n        '~NOT-EQ', CELL_SIZE, '- 1-', # ( (a-addr - 5) )\n        '@ branch :~LOOP'\n    ),\n    forth_def(\n        'DIGIT',  # ( char -- u flag )\n        'DUP 48 < OVER 57 > OR ?branch :~parse-dec', # jump when 48 <= c <= 57 (i.e. '0'..'9')\n        'DUP 65 < OVER 90 > OR ?branch :~parse-alpha-upper', # jump when 65 <= c <= 90 (i.e. 'A'..'Z')\n        'DUP 97 < OVER 122 > OR ?branch :~parse-alpha-lower', # jump when 97 <= c <= 122 (i.e. 'a'..'z')\n        '0 EXIT', # else not found\n        '~parse-dec 48 - branch :~done',\n        '~parse-alpha-upper 65 - 10 + branch :~done',\n        '~parse-alpha-lower 97 - 10 + branch :~done',\n        '~done DUP BASE @ < ?branch :~out-of-base',\n        '-1 EXIT',\n        '~out-of-base 0',\n    ),\n    forth_def(\n        'SKIP-SIGN',  # ( c-addr1 u1 -- c-addr2 u2 )\n        'DUP ?branch :~DONE', # end if empty\n        'OVER C@ 45 = ?branch :~DONE', # end if doesn't start with '-'\n        '1 /STRING',\n        '~DONE',\n    ),\n    forth_def(\n        'NEGATIVE',  # ( char -- flag )\n        ord('-'), '=',\n    ),\n    forth_def(\n        'BASE*',  # ( ud1 -- ud2 )\n        'BASE @ S>D D*',\n    ),\n    forth_def(\n        '>NUMBER',  # ( ud1 c-addr1 u1 -- ud2 c-addr2 u2 )\n        '~LOOP',\n        'DUP ?branch :~END', # if empty, go to end\n        'OVER C@ DIGIT ?branch :~PARTIAL', # if can't parse digit, error\n        'SWAP >R SWAP >R >R BASE* R> S>D D+ R> R> 1 /STRING branch :~LOOP',\n        '~PARTIAL DROP', # drop unparsed digit\n        '~END',\n    ),\n    forth_def(\n        'COUNTED>NUMBER',  # ( c-addr -- d 1 | n 2 | 0 )\n        '0 0 ROT', # ( 0 0 c-addr )\n        'COUNT OVER C@ NEGATIVE >R',  # ( 0 0 c-addr1 u R: negative-flag )\n        'SKIP-SIGN >NUMBER',  # ( ud2 c-addr2 u2 R: negative-flag )\n        'R> ?branch :~FINISH', # ( ud2 c-addr2 u2 )\n        # negative\n        '>R >R DNEGATE R> R>',\n        '~FINISH', # ( ud2 c-addr2 u2 )\n        'DUP ?branch :~SINGLE', # jump if no char left unconverted\n        '1 = ?branch :~ERROR', # jump if more than 1 char unconverted ( ud2 c-addr2 )\n        'DUP C@ 46 = ?branch :~ERROR', # jump if doesn't end in '.'\n        'DROP 1 EXIT', # double number\n        '~SINGLE DROP DROP D>S 2 EXIT', # single number\n        '~ERROR DROP DROP DROP 0', # error\n    ),\n    forth_def(\n        ',',  # ( x -- )\n        'HERE ! 0 CELL+ ALLOT',\n    ),\n    forth_def(\n        'C,',  # ( c -- )\n        'HERE C! 1 ALLOT',\n    ),\n    forth_def(\n        '(LITERAL)',  # ( x -- )\n        'lit lit , ,', # yep, literal of itself\n    ),\n    forth_def(\n        'INTERPRET',  # ( x*j -- y*i flag )\n        '~I-LOOP',\n        INTERPRET_WORD, 'BL _WORD',\n        'DUP C@ ?branch :~EMPTY-WORD',  # skip empty words\n        'FIND',\n        'DUP ?branch :~NOT-FOUND',\n        # found\n        '-1 = ?branch :~IMM', # immediate word\n        'STATE @ ?branch :~IMM', # interpretation state\n        # compile\n        ', branch :~DONE',\n        # execute\n        '~IMM EXECUTE branch :~DONE',\n        # parse number\n        '~NOT-FOUND DROP DUP >R COUNTED>NUMBER',\n        'DUP ?branch :~NOT-NUMBER',\n        'R> DROP',\n        'STATE @ ?branch :~DONE-NUMBER', # am I interpreting?\n        'DUP 1 = ?branch :~SINGLE-NUMBER',\n        # compiling double number\n        'DROP SWAP (LITERAL) (LITERAL) branch :~DONE',\n        # compiling single number\n        '~SINGLE-NUMBER DROP (LITERAL) branch :~DONE',\n        '(LITERAL) branch :~DONE',\n        '~EMPTY-WORD DROP branch :~DONE',\n        '~DONE-NUMBER DROP',\n        '~DONE',\n        # continue interpreting if there are more words in the parse\n        # area\n        'SOURCE SWAP DROP >IN @ SWAP < INVERT ?branch :~I-LOOP',\n        '-1 EXIT',\n        '~NOT-NUMBER WORD-NOT-FOUND-ERR', len(WORD_NOT_FOUND_ERR), 'WRITE R> COUNT WRITE',\n    ),\n    forth_def(\n        'OK',  # ( -- )\n        'QUIET @ ?branch :~VERBOSE EXIT ~VERBOSE OK-MSG', len(OK_MSG), 'WRITE',\n    ),\n    forth_def(\n        'RESET-SP',  # ( -- )\n        'task-base', SP_INITIAL_OFFSET, '+ SP!',\n    ),\n    forth_def(\n        '(QUIT)', # (  x*j flag -- y*i ) if flag true, reset I/O buffers (on error, always reset anyway)\n        '?branch :~IOBUF',\n        '~START',\n        '0 SOURCE-ID !',\n        BUFFER_START, 'IN-BUF !',\n        -1, 'IN-BUF-EOL !',\n        0, 'IN-BUF-SIZE !',\n        '~IOBUF',\n        'task-base', RS_INITIAL_OFFSET, '+ RP!',\n        '0 STATE !',\n        '~LOOP 0 >IN ! LINE DROP DROP INTERPRET',\n        '0= ?branch :~OK',\n        'RESET-SP branch :~START', # simulate abort without recursive calls\n        '~OK STATE @ 0= ?branch :~LOOP OK', # show prompt only if in interpretation state\n        'branch :~LOOP', # infinite loop\n    ),\n    forth_def(\n        'QUIT', # (  x*j -- y*i )\n        '1 (QUIT)',\n    ),\n    forth_def(\n        'ABORT', # (  x*j -- y*i )\n        'RESET-SP QUIT',\n    ),\n    forth_def(\n        'HEADER',  # ( -- )\n        'LATEST @ , 0 C, HERE LATEST ! BL WORD HERE OVER C@ 1+ DUP >R CMOVE R> 1+ ALIGNED 1- ALLOT',\n    ),\n    forth_def(\n        ':',  # ( -- word-addr )\n        # 128 OR applies the smudge bit to keep this definition hidden\n        'HEADER LATEST @ DUP C@ 128 OR OVER C! lit (docol) @ , 1 STATE !',\n    ),\n    forth_def(\n        ';',  # ( word-addr -- )\n        # 127 AND un-smudges the length\n        '0 STATE ! lit EXIT , DUP C@ 127 AND SWAP C!',\n        immediate=True,\n    ),\n]\n"
  },
  {
    "path": "kernel/memory_layout.py",
    "content": "\"\"\"\nConstants that define the memory layout.\n\"\"\"\n\nfrom _binaryen_c import lib\n\n\nCELL_SIZE = 4\nCELL_TYPE = lib.BinaryenInt32()\nDOUBLE_CELL_TYPE = lib.BinaryenInt64()\n\n# Interpreter parameters\nTASK_BASE_PARAM = 0\nTASK_PARAM = 1\n\n# registers, stored as local variables in the evaluation function\nIP = 2  # instruction pointer\nW = 3  # address of the codeword of the word being executed\nSP = 4  # stack pointer, points to the top of the stack (grow downwards)\nRS = 5  # return stack pointer, points to the top of the stack  (grow downwards)\nSCRATCH_1 = 6 # whatever\nSCRATCH_2 = 7 # whatever\nSCRATCH_3 = 8 # whatever\nSCRATCH_DOUBLE_1 = 9 # whatever\n\n# Memory layout:\n\n# bytes: 0 .. 11k: main task memory area\nMAIN_TASK_BASE_VALUE = 0\n\n# bytes: 0 .. 12: main task saved registers\n# register offsets, registers are saved/loaded from get_reg(TASK_BASE_PARAM) + OFFSET\nIP_MEM_OFFSET = 0\nSP_MEM_OFFSET = IP_MEM_OFFSET + CELL_SIZE\nRS_MEM_OFFSET = SP_MEM_OFFSET + CELL_SIZE\n\n# bytes: 12 .. 16: offset to the address of the initial forth word to run when the interpreter starts\nIP_INITIAL_OFFSET = RS_MEM_OFFSET + CELL_SIZE\n\n# bytes: 16 ... 1k: random bytes (to avoid a simple return stack\n# overflow to overwrite the registers)\n\n# bytes: 1k ... 5k: return stack\nRS_INITIAL_OFFSET = 5 * 1024 + CELL_SIZE  # stack empty, point one cell above start of stack\n\n# bytes: 5k ... 6k: random bytes (to avoid a simple return stack\n# underflow to overwrite the params stack)\n\n# bytes: 6k ... 10k: params stack\nSP_INITIAL_OFFSET = 10 * 1024 + CELL_SIZE  # stack empty, point one cell above start of stack\n\n# bytes: 10k ... 11k: random bytes (to avoid a simple params stack\n# underflow to overwrite the buffers)\n\n# main task memory area ends here\n\n# bytes: 11k ... 15k: I/O buffers\nBUFFER_START = 11 * 1024\n\n# bytes: 15k ... 19k: pad (multi-purpose memory area for use by forth code)\nPAD_START = 15 * 1024\n\n# bytes: 19k ... 20k: scratch area used by the interpreter to keep\n# parsed words\nINTERPRET_WORD = 19 * 1024\n\n# bytes: 20k ... : dictionary\nHERE_INITIAL = 20 * 1024\n"
  },
  {
    "path": "kernel/vendor/binaryen-c.h",
    "content": "/*\n * Copyright 2016 WebAssembly Community Group participants\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//================\n// Binaryen C API\n//\n// The first part of the API lets you create modules and their parts.\n//\n// The second part of the API lets you perform operations on modules.\n//\n// The third part of the API lets you provide a general control-flow\n//   graph (CFG) as input.\n//\n// The final part of the API contains miscellaneous utilities like\n//   debugging/tracing for the API itself.\n//\n// ---------------\n//\n// Thread safety: You can create Expressions in parallel, as they do not\n//                refer to global state. BinaryenAddFunction and\n//                BinaryenAddFunctionType are also thread-safe, which means\n//                that you can create functions and their contents in multiple\n//                threads. This is important since functions are where the\n//                majority of the work is done.\n//                Other methods - creating imports, exports, etc. - are\n//                not currently thread-safe (as there is typically no need\n//                to parallelize them).\n//\n//================\n\n//\n// ========== Module Creation ==========\n//\n\n// BinaryenIndex\n//\n// Used for internal indexes and list sizes.\n\ntypedef uint32_t BinaryenIndex;\n\n// Core types (call to get the value of each; you can cache them, they\n// never change)\n\ntypedef uint32_t BinaryenType;\n\nBinaryenType BinaryenTypeNone(void);\nBinaryenType BinaryenTypeInt32(void);\nBinaryenType BinaryenTypeInt64(void);\nBinaryenType BinaryenTypeFloat32(void);\nBinaryenType BinaryenTypeFloat64(void);\nBinaryenType BinaryenTypeVec128(void);\nBinaryenType BinaryenTypeUnreachable(void);\n// Not a real type. Used as the last parameter to BinaryenBlock to let\n// the API figure out the type instead of providing one.\nBinaryenType BinaryenTypeAuto(void);\n\nBinaryenType BinaryenNone(void);\nBinaryenType BinaryenInt32(void);\nBinaryenType BinaryenInt64(void);\nBinaryenType BinaryenFloat32(void);\nBinaryenType BinaryenFloat64(void);\nBinaryenType BinaryenUndefined(void);\n\n// Expression ids (call to get the value of each; you can cache them)\n\ntypedef uint32_t BinaryenExpressionId;\n\nBinaryenExpressionId BinaryenInvalidId(void);\nBinaryenExpressionId BinaryenBlockId(void);\nBinaryenExpressionId BinaryenIfId(void);\nBinaryenExpressionId BinaryenLoopId(void);\nBinaryenExpressionId BinaryenBreakId(void);\nBinaryenExpressionId BinaryenSwitchId(void);\nBinaryenExpressionId BinaryenCallId(void);\nBinaryenExpressionId BinaryenCallIndirectId(void);\nBinaryenExpressionId BinaryenGetLocalId(void);\nBinaryenExpressionId BinaryenSetLocalId(void);\nBinaryenExpressionId BinaryenGetGlobalId(void);\nBinaryenExpressionId BinaryenSetGlobalId(void);\nBinaryenExpressionId BinaryenLoadId(void);\nBinaryenExpressionId BinaryenStoreId(void);\nBinaryenExpressionId BinaryenConstId(void);\nBinaryenExpressionId BinaryenUnaryId(void);\nBinaryenExpressionId BinaryenBinaryId(void);\nBinaryenExpressionId BinaryenSelectId(void);\nBinaryenExpressionId BinaryenDropId(void);\nBinaryenExpressionId BinaryenReturnId(void);\nBinaryenExpressionId BinaryenHostId(void);\nBinaryenExpressionId BinaryenNopId(void);\nBinaryenExpressionId BinaryenUnreachableId(void);\nBinaryenExpressionId BinaryenAtomicCmpxchgId(void);\nBinaryenExpressionId BinaryenAtomicRMWId(void);\nBinaryenExpressionId BinaryenAtomicWaitId(void);\nBinaryenExpressionId BinaryenAtomicNotifyId(void);\nBinaryenExpressionId BinaryenSIMDExtractId(void);\nBinaryenExpressionId BinaryenSIMDReplaceId(void);\nBinaryenExpressionId BinaryenSIMDShuffleId(void);\nBinaryenExpressionId BinaryenSIMDBitselectId(void);\nBinaryenExpressionId BinaryenSIMDShiftId(void);\nBinaryenExpressionId BinaryenMemoryInitId(void);\nBinaryenExpressionId BinaryenDataDropId(void);\nBinaryenExpressionId BinaryenMemoryCopyId(void);\nBinaryenExpressionId BinaryenMemoryFillId(void);\n\n// External kinds (call to get the value of each; you can cache them)\n\ntypedef uint32_t BinaryenExternalKind;\n\nBinaryenExternalKind BinaryenExternalFunction(void);\nBinaryenExternalKind BinaryenExternalTable(void);\nBinaryenExternalKind BinaryenExternalMemory(void);\nBinaryenExternalKind BinaryenExternalGlobal(void);\n\n// Modules\n//\n// Modules contain lists of functions, imports, exports, function types. The\n// Add* methods create them on a module. The module owns them and will free their\n// memory when the module is disposed of.\n//\n// Expressions are also allocated inside modules, and freed with the module. They\n// are not created by Add* methods, since they are not added directly on the\n// module, instead, they are arguments to other expressions (and then they are\n// the children of that AST node), or to a function (and then they are the body\n// of that function).\n//\n// A module can also contain a function table for indirect calls, a memory,\n// and a start method.\n\ntypedef void* BinaryenModuleRef;\n\nBinaryenModuleRef BinaryenModuleCreate(void);\nvoid BinaryenModuleDispose(BinaryenModuleRef module);\n\n// Function types\n\ntypedef void* BinaryenFunctionTypeRef;\n\n// Add a new function type. This is thread-safe.\n// Note: name can be NULL, in which case we auto-generate a name\nBinaryenFunctionTypeRef BinaryenAddFunctionType(BinaryenModuleRef module, const char* name, BinaryenType result, BinaryenType* paramTypes, BinaryenIndex numParams);\n// Removes a function type.\nvoid BinaryenRemoveFunctionType(BinaryenModuleRef module, const char* name);\n\n// Literals. These are passed by value.\n\nstruct BinaryenLiteral {\n  int32_t type;\n  union {\n    int32_t i32;\n    int64_t i64;\n    float f32;\n    double f64;\n    uint8_t v128[16];\n  };\n};\n\nstruct BinaryenLiteral BinaryenLiteralInt32(int32_t x);\nstruct BinaryenLiteral BinaryenLiteralInt64(int64_t x);\nstruct BinaryenLiteral BinaryenLiteralFloat32(float x);\nstruct BinaryenLiteral BinaryenLiteralFloat64(double x);\nstruct BinaryenLiteral BinaryenLiteralVec128(const uint8_t x[16]);\nstruct BinaryenLiteral BinaryenLiteralFloat32Bits(int32_t x);\nstruct BinaryenLiteral BinaryenLiteralFloat64Bits(int64_t x);\n\n// Expressions\n//\n// Some expressions have a BinaryenOp, which is the more\n// specific operation/opcode.\n//\n// Some expressions have optional parameters, like Return may not\n// return a value. You can supply a NULL pointer in those cases.\n//\n// For more information, see wasm.h\n\ntypedef int32_t BinaryenOp;\n\nBinaryenOp BinaryenClzInt32(void);\nBinaryenOp BinaryenCtzInt32(void);\nBinaryenOp BinaryenPopcntInt32(void);\nBinaryenOp BinaryenNegFloat32(void);\nBinaryenOp BinaryenAbsFloat32(void);\nBinaryenOp BinaryenCeilFloat32(void);\nBinaryenOp BinaryenFloorFloat32(void);\nBinaryenOp BinaryenTruncFloat32(void);\nBinaryenOp BinaryenNearestFloat32(void);\nBinaryenOp BinaryenSqrtFloat32(void);\nBinaryenOp BinaryenEqZInt32(void);\nBinaryenOp BinaryenClzInt64(void);\nBinaryenOp BinaryenCtzInt64(void);\nBinaryenOp BinaryenPopcntInt64(void);\nBinaryenOp BinaryenNegFloat64(void);\nBinaryenOp BinaryenAbsFloat64(void);\nBinaryenOp BinaryenCeilFloat64(void);\nBinaryenOp BinaryenFloorFloat64(void);\nBinaryenOp BinaryenTruncFloat64(void);\nBinaryenOp BinaryenNearestFloat64(void);\nBinaryenOp BinaryenSqrtFloat64(void);\nBinaryenOp BinaryenEqZInt64(void);\nBinaryenOp BinaryenExtendSInt32(void);\nBinaryenOp BinaryenExtendUInt32(void);\nBinaryenOp BinaryenWrapInt64(void);\nBinaryenOp BinaryenTruncSFloat32ToInt32(void);\nBinaryenOp BinaryenTruncSFloat32ToInt64(void);\nBinaryenOp BinaryenTruncUFloat32ToInt32(void);\nBinaryenOp BinaryenTruncUFloat32ToInt64(void);\nBinaryenOp BinaryenTruncSFloat64ToInt32(void);\nBinaryenOp BinaryenTruncSFloat64ToInt64(void);\nBinaryenOp BinaryenTruncUFloat64ToInt32(void);\nBinaryenOp BinaryenTruncUFloat64ToInt64(void);\nBinaryenOp BinaryenReinterpretFloat32(void);\nBinaryenOp BinaryenReinterpretFloat64(void);\nBinaryenOp BinaryenConvertSInt32ToFloat32(void);\nBinaryenOp BinaryenConvertSInt32ToFloat64(void);\nBinaryenOp BinaryenConvertUInt32ToFloat32(void);\nBinaryenOp BinaryenConvertUInt32ToFloat64(void);\nBinaryenOp BinaryenConvertSInt64ToFloat32(void);\nBinaryenOp BinaryenConvertSInt64ToFloat64(void);\nBinaryenOp BinaryenConvertUInt64ToFloat32(void);\nBinaryenOp BinaryenConvertUInt64ToFloat64(void);\nBinaryenOp BinaryenPromoteFloat32(void);\nBinaryenOp BinaryenDemoteFloat64(void);\nBinaryenOp BinaryenReinterpretInt32(void);\nBinaryenOp BinaryenReinterpretInt64(void);\nBinaryenOp BinaryenExtendS8Int32(void);\nBinaryenOp BinaryenExtendS16Int32(void);\nBinaryenOp BinaryenExtendS8Int64(void);\nBinaryenOp BinaryenExtendS16Int64(void);\nBinaryenOp BinaryenExtendS32Int64(void);\nBinaryenOp BinaryenAddInt32(void);\nBinaryenOp BinaryenSubInt32(void);\nBinaryenOp BinaryenMulInt32(void);\nBinaryenOp BinaryenDivSInt32(void);\nBinaryenOp BinaryenDivUInt32(void);\nBinaryenOp BinaryenRemSInt32(void);\nBinaryenOp BinaryenRemUInt32(void);\nBinaryenOp BinaryenAndInt32(void);\nBinaryenOp BinaryenOrInt32(void);\nBinaryenOp BinaryenXorInt32(void);\nBinaryenOp BinaryenShlInt32(void);\nBinaryenOp BinaryenShrUInt32(void);\nBinaryenOp BinaryenShrSInt32(void);\nBinaryenOp BinaryenRotLInt32(void);\nBinaryenOp BinaryenRotRInt32(void);\nBinaryenOp BinaryenEqInt32(void);\nBinaryenOp BinaryenNeInt32(void);\nBinaryenOp BinaryenLtSInt32(void);\nBinaryenOp BinaryenLtUInt32(void);\nBinaryenOp BinaryenLeSInt32(void);\nBinaryenOp BinaryenLeUInt32(void);\nBinaryenOp BinaryenGtSInt32(void);\nBinaryenOp BinaryenGtUInt32(void);\nBinaryenOp BinaryenGeSInt32(void);\nBinaryenOp BinaryenGeUInt32(void);\nBinaryenOp BinaryenAddInt64(void);\nBinaryenOp BinaryenSubInt64(void);\nBinaryenOp BinaryenMulInt64(void);\nBinaryenOp BinaryenDivSInt64(void);\nBinaryenOp BinaryenDivUInt64(void);\nBinaryenOp BinaryenRemSInt64(void);\nBinaryenOp BinaryenRemUInt64(void);\nBinaryenOp BinaryenAndInt64(void);\nBinaryenOp BinaryenOrInt64(void);\nBinaryenOp BinaryenXorInt64(void);\nBinaryenOp BinaryenShlInt64(void);\nBinaryenOp BinaryenShrUInt64(void);\nBinaryenOp BinaryenShrSInt64(void);\nBinaryenOp BinaryenRotLInt64(void);\nBinaryenOp BinaryenRotRInt64(void);\nBinaryenOp BinaryenEqInt64(void);\nBinaryenOp BinaryenNeInt64(void);\nBinaryenOp BinaryenLtSInt64(void);\nBinaryenOp BinaryenLtUInt64(void);\nBinaryenOp BinaryenLeSInt64(void);\nBinaryenOp BinaryenLeUInt64(void);\nBinaryenOp BinaryenGtSInt64(void);\nBinaryenOp BinaryenGtUInt64(void);\nBinaryenOp BinaryenGeSInt64(void);\nBinaryenOp BinaryenGeUInt64(void);\nBinaryenOp BinaryenAddFloat32(void);\nBinaryenOp BinaryenSubFloat32(void);\nBinaryenOp BinaryenMulFloat32(void);\nBinaryenOp BinaryenDivFloat32(void);\nBinaryenOp BinaryenCopySignFloat32(void);\nBinaryenOp BinaryenMinFloat32(void);\nBinaryenOp BinaryenMaxFloat32(void);\nBinaryenOp BinaryenEqFloat32(void);\nBinaryenOp BinaryenNeFloat32(void);\nBinaryenOp BinaryenLtFloat32(void);\nBinaryenOp BinaryenLeFloat32(void);\nBinaryenOp BinaryenGtFloat32(void);\nBinaryenOp BinaryenGeFloat32(void);\nBinaryenOp BinaryenAddFloat64(void);\nBinaryenOp BinaryenSubFloat64(void);\nBinaryenOp BinaryenMulFloat64(void);\nBinaryenOp BinaryenDivFloat64(void);\nBinaryenOp BinaryenCopySignFloat64(void);\nBinaryenOp BinaryenMinFloat64(void);\nBinaryenOp BinaryenMaxFloat64(void);\nBinaryenOp BinaryenEqFloat64(void);\nBinaryenOp BinaryenNeFloat64(void);\nBinaryenOp BinaryenLtFloat64(void);\nBinaryenOp BinaryenLeFloat64(void);\nBinaryenOp BinaryenGtFloat64(void);\nBinaryenOp BinaryenGeFloat64(void);\nBinaryenOp BinaryenCurrentMemory(void);\nBinaryenOp BinaryenGrowMemory(void);\nBinaryenOp BinaryenAtomicRMWAdd(void);\nBinaryenOp BinaryenAtomicRMWSub(void);\nBinaryenOp BinaryenAtomicRMWAnd(void);\nBinaryenOp BinaryenAtomicRMWOr(void);\nBinaryenOp BinaryenAtomicRMWXor(void);\nBinaryenOp BinaryenAtomicRMWXchg(void);\nBinaryenOp BinaryenTruncSatSFloat32ToInt32(void);\nBinaryenOp BinaryenTruncSatSFloat32ToInt64(void);\nBinaryenOp BinaryenTruncSatUFloat32ToInt32(void);\nBinaryenOp BinaryenTruncSatUFloat32ToInt64(void);\nBinaryenOp BinaryenTruncSatSFloat64ToInt32(void);\nBinaryenOp BinaryenTruncSatSFloat64ToInt64(void);\nBinaryenOp BinaryenTruncSatUFloat64ToInt32(void);\nBinaryenOp BinaryenTruncSatUFloat64ToInt64(void);\nBinaryenOp BinaryenSplatVecI8x16(void);\nBinaryenOp BinaryenExtractLaneSVecI8x16(void);\nBinaryenOp BinaryenExtractLaneUVecI8x16(void);\nBinaryenOp BinaryenReplaceLaneVecI8x16(void);\nBinaryenOp BinaryenSplatVecI16x8(void);\nBinaryenOp BinaryenExtractLaneSVecI16x8(void);\nBinaryenOp BinaryenExtractLaneUVecI16x8(void);\nBinaryenOp BinaryenReplaceLaneVecI16x8(void);\nBinaryenOp BinaryenSplatVecI32x4(void);\nBinaryenOp BinaryenExtractLaneVecI32x4(void);\nBinaryenOp BinaryenReplaceLaneVecI32x4(void);\nBinaryenOp BinaryenSplatVecI64x2(void);\nBinaryenOp BinaryenExtractLaneVecI64x2(void);\nBinaryenOp BinaryenReplaceLaneVecI64x2(void);\nBinaryenOp BinaryenSplatVecF32x4(void);\nBinaryenOp BinaryenExtractLaneVecF32x4(void);\nBinaryenOp BinaryenReplaceLaneVecF32x4(void);\nBinaryenOp BinaryenSplatVecF64x2(void);\nBinaryenOp BinaryenExtractLaneVecF64x2(void);\nBinaryenOp BinaryenReplaceLaneVecF64x2(void);\nBinaryenOp BinaryenEqVecI8x16(void);\nBinaryenOp BinaryenNeVecI8x16(void);\nBinaryenOp BinaryenLtSVecI8x16(void);\nBinaryenOp BinaryenLtUVecI8x16(void);\nBinaryenOp BinaryenGtSVecI8x16(void);\nBinaryenOp BinaryenGtUVecI8x16(void);\nBinaryenOp BinaryenLeSVecI8x16(void);\nBinaryenOp BinaryenLeUVecI8x16(void);\nBinaryenOp BinaryenGeSVecI8x16(void);\nBinaryenOp BinaryenGeUVecI8x16(void);\nBinaryenOp BinaryenEqVecI16x8(void);\nBinaryenOp BinaryenNeVecI16x8(void);\nBinaryenOp BinaryenLtSVecI16x8(void);\nBinaryenOp BinaryenLtUVecI16x8(void);\nBinaryenOp BinaryenGtSVecI16x8(void);\nBinaryenOp BinaryenGtUVecI16x8(void);\nBinaryenOp BinaryenLeSVecI16x8(void);\nBinaryenOp BinaryenLeUVecI16x8(void);\nBinaryenOp BinaryenGeSVecI16x8(void);\nBinaryenOp BinaryenGeUVecI16x8(void);\nBinaryenOp BinaryenEqVecI32x4(void);\nBinaryenOp BinaryenNeVecI32x4(void);\nBinaryenOp BinaryenLtSVecI32x4(void);\nBinaryenOp BinaryenLtUVecI32x4(void);\nBinaryenOp BinaryenGtSVecI32x4(void);\nBinaryenOp BinaryenGtUVecI32x4(void);\nBinaryenOp BinaryenLeSVecI32x4(void);\nBinaryenOp BinaryenLeUVecI32x4(void);\nBinaryenOp BinaryenGeSVecI32x4(void);\nBinaryenOp BinaryenGeUVecI32x4(void);\nBinaryenOp BinaryenEqVecF32x4(void);\nBinaryenOp BinaryenNeVecF32x4(void);\nBinaryenOp BinaryenLtVecF32x4(void);\nBinaryenOp BinaryenGtVecF32x4(void);\nBinaryenOp BinaryenLeVecF32x4(void);\nBinaryenOp BinaryenGeVecF32x4(void);\nBinaryenOp BinaryenEqVecF64x2(void);\nBinaryenOp BinaryenNeVecF64x2(void);\nBinaryenOp BinaryenLtVecF64x2(void);\nBinaryenOp BinaryenGtVecF64x2(void);\nBinaryenOp BinaryenLeVecF64x2(void);\nBinaryenOp BinaryenGeVecF64x2(void);\nBinaryenOp BinaryenNotVec128(void);\nBinaryenOp BinaryenAndVec128(void);\nBinaryenOp BinaryenOrVec128(void);\nBinaryenOp BinaryenXorVec128(void);\nBinaryenOp BinaryenNegVecI8x16(void);\nBinaryenOp BinaryenAnyTrueVecI8x16(void);\nBinaryenOp BinaryenAllTrueVecI8x16(void);\nBinaryenOp BinaryenShlVecI8x16(void);\nBinaryenOp BinaryenShrSVecI8x16(void);\nBinaryenOp BinaryenShrUVecI8x16(void);\nBinaryenOp BinaryenAddVecI8x16(void);\nBinaryenOp BinaryenAddSatSVecI8x16(void);\nBinaryenOp BinaryenAddSatUVecI8x16(void);\nBinaryenOp BinaryenSubVecI8x16(void);\nBinaryenOp BinaryenSubSatSVecI8x16(void);\nBinaryenOp BinaryenSubSatUVecI8x16(void);\nBinaryenOp BinaryenMulVecI8x16(void);\nBinaryenOp BinaryenNegVecI16x8(void);\nBinaryenOp BinaryenAnyTrueVecI16x8(void);\nBinaryenOp BinaryenAllTrueVecI16x8(void);\nBinaryenOp BinaryenShlVecI16x8(void);\nBinaryenOp BinaryenShrSVecI16x8(void);\nBinaryenOp BinaryenShrUVecI16x8(void);\nBinaryenOp BinaryenAddVecI16x8(void);\nBinaryenOp BinaryenAddSatSVecI16x8(void);\nBinaryenOp BinaryenAddSatUVecI16x8(void);\nBinaryenOp BinaryenSubVecI16x8(void);\nBinaryenOp BinaryenSubSatSVecI16x8(void);\nBinaryenOp BinaryenSubSatUVecI16x8(void);\nBinaryenOp BinaryenMulVecI16x8(void);\nBinaryenOp BinaryenNegVecI32x4(void);\nBinaryenOp BinaryenAnyTrueVecI32x4(void);\nBinaryenOp BinaryenAllTrueVecI32x4(void);\nBinaryenOp BinaryenShlVecI32x4(void);\nBinaryenOp BinaryenShrSVecI32x4(void);\nBinaryenOp BinaryenShrUVecI32x4(void);\nBinaryenOp BinaryenAddVecI32x4(void);\nBinaryenOp BinaryenSubVecI32x4(void);\nBinaryenOp BinaryenMulVecI32x4(void);\nBinaryenOp BinaryenNegVecI64x2(void);\nBinaryenOp BinaryenAnyTrueVecI64x2(void);\nBinaryenOp BinaryenAllTrueVecI64x2(void);\nBinaryenOp BinaryenShlVecI64x2(void);\nBinaryenOp BinaryenShrSVecI64x2(void);\nBinaryenOp BinaryenShrUVecI64x2(void);\nBinaryenOp BinaryenAddVecI64x2(void);\nBinaryenOp BinaryenSubVecI64x2(void);\nBinaryenOp BinaryenAbsVecF32x4(void);\nBinaryenOp BinaryenNegVecF32x4(void);\nBinaryenOp BinaryenSqrtVecF32x4(void);\nBinaryenOp BinaryenAddVecF32x4(void);\nBinaryenOp BinaryenSubVecF32x4(void);\nBinaryenOp BinaryenMulVecF32x4(void);\nBinaryenOp BinaryenDivVecF32x4(void);\nBinaryenOp BinaryenMinVecF32x4(void);\nBinaryenOp BinaryenMaxVecF32x4(void);\nBinaryenOp BinaryenAbsVecF64x2(void);\nBinaryenOp BinaryenNegVecF64x2(void);\nBinaryenOp BinaryenSqrtVecF64x2(void);\nBinaryenOp BinaryenAddVecF64x2(void);\nBinaryenOp BinaryenSubVecF64x2(void);\nBinaryenOp BinaryenMulVecF64x2(void);\nBinaryenOp BinaryenDivVecF64x2(void);\nBinaryenOp BinaryenMinVecF64x2(void);\nBinaryenOp BinaryenMaxVecF64x2(void);\nBinaryenOp BinaryenTruncSatSVecF32x4ToVecI32x4(void);\nBinaryenOp BinaryenTruncSatUVecF32x4ToVecI32x4(void);\nBinaryenOp BinaryenTruncSatSVecF64x2ToVecI64x2(void);\nBinaryenOp BinaryenTruncSatUVecF64x2ToVecI64x2(void);\nBinaryenOp BinaryenConvertSVecI32x4ToVecF32x4(void);\nBinaryenOp BinaryenConvertUVecI32x4ToVecF32x4(void);\nBinaryenOp BinaryenConvertSVecI64x2ToVecF64x2(void);\nBinaryenOp BinaryenConvertUVecI64x2ToVecF64x2(void);\n\ntypedef void* BinaryenExpressionRef;\n\n// Block: name can be NULL. Specifying BinaryenUndefined() as the 'type'\n//        parameter indicates that the block's type shall be figured out\n//        automatically instead of explicitly providing it. This conforms\n//        to the behavior before the 'type' parameter has been introduced.\nBinaryenExpressionRef BinaryenBlock(BinaryenModuleRef module, const char* name, BinaryenExpressionRef* children, BinaryenIndex numChildren, BinaryenType type);\n// If: ifFalse can be NULL\nBinaryenExpressionRef BinaryenIf(BinaryenModuleRef module, BinaryenExpressionRef condition, BinaryenExpressionRef ifTrue, BinaryenExpressionRef ifFalse);\nBinaryenExpressionRef BinaryenLoop(BinaryenModuleRef module, const char* in, BinaryenExpressionRef body);\n// Break: value and condition can be NULL\nBinaryenExpressionRef BinaryenBreak(BinaryenModuleRef module, const char* name, BinaryenExpressionRef condition, BinaryenExpressionRef value);\n// Switch: value can be NULL\nBinaryenExpressionRef BinaryenSwitch(BinaryenModuleRef module, const char** names, BinaryenIndex numNames, const char* defaultName, BinaryenExpressionRef condition, BinaryenExpressionRef value);\n// Call: Note the 'returnType' parameter. You must declare the\n//       type returned by the function being called, as that\n//       function might not have been created yet, so we don't\n//       know what it is.\nBinaryenExpressionRef BinaryenCall(BinaryenModuleRef module, const char* target, BinaryenExpressionRef* operands, BinaryenIndex numOperands, BinaryenType returnType);\nBinaryenExpressionRef BinaryenCallIndirect(BinaryenModuleRef module, BinaryenExpressionRef target, BinaryenExpressionRef* operands, BinaryenIndex numOperands, const char* type);\n// GetLocal: Note the 'type' parameter. It might seem redundant, since the\n//           local at that index must have a type. However, this API lets you\n//           build code \"top-down\": create a node, then its parents, and so\n//           on, and finally create the function at the end. (Note that in fact\n//           you do not mention a function when creating ExpressionRefs, only\n//           a module.) And since GetLocal is a leaf node, we need to be told\n//           its type. (Other nodes detect their type either from their\n//           type or their opcode, or failing that, their children. But\n//           GetLocal has no children, it is where a \"stream\" of type info\n//           begins.)\n//           Note also that the index of a local can refer to a param or\n//           a var, that is, either a parameter to the function or a variable\n//           declared when you call BinaryenAddFunction. See BinaryenAddFunction\n//           for more details.\nBinaryenExpressionRef BinaryenGetLocal(BinaryenModuleRef module, BinaryenIndex index, BinaryenType type);\nBinaryenExpressionRef BinaryenSetLocal(BinaryenModuleRef module, BinaryenIndex index, BinaryenExpressionRef value);\nBinaryenExpressionRef BinaryenTeeLocal(BinaryenModuleRef module, BinaryenIndex index, BinaryenExpressionRef value);\nBinaryenExpressionRef BinaryenGetGlobal(BinaryenModuleRef module, const char* name, BinaryenType type);\nBinaryenExpressionRef BinaryenSetGlobal(BinaryenModuleRef module, const char* name, BinaryenExpressionRef value);\n// Load: align can be 0, in which case it will be the natural alignment (equal to bytes)\nBinaryenExpressionRef BinaryenLoad(BinaryenModuleRef module, uint32_t bytes, int8_t signed_, uint32_t offset, uint32_t align, BinaryenType type, BinaryenExpressionRef ptr);\n// Store: align can be 0, in which case it will be the natural alignment (equal to bytes)\nBinaryenExpressionRef BinaryenStore(BinaryenModuleRef module, uint32_t bytes, uint32_t offset, uint32_t align, BinaryenExpressionRef ptr, BinaryenExpressionRef value, BinaryenType type);\nBinaryenExpressionRef BinaryenConst(BinaryenModuleRef module, struct BinaryenLiteral value);\nBinaryenExpressionRef BinaryenUnary(BinaryenModuleRef module, BinaryenOp op, BinaryenExpressionRef value);\nBinaryenExpressionRef BinaryenBinary(BinaryenModuleRef module, BinaryenOp op, BinaryenExpressionRef left, BinaryenExpressionRef right);\nBinaryenExpressionRef BinaryenSelect(BinaryenModuleRef module, BinaryenExpressionRef condition, BinaryenExpressionRef ifTrue, BinaryenExpressionRef ifFalse);\nBinaryenExpressionRef BinaryenDrop(BinaryenModuleRef module, BinaryenExpressionRef value);\n// Return: value can be NULL\nBinaryenExpressionRef BinaryenReturn(BinaryenModuleRef module, BinaryenExpressionRef value);\n// Host: name may be NULL\nBinaryenExpressionRef BinaryenHost(BinaryenModuleRef module, BinaryenOp op, const char* name, BinaryenExpressionRef* operands, BinaryenIndex numOperands);\nBinaryenExpressionRef BinaryenNop(BinaryenModuleRef module);\nBinaryenExpressionRef BinaryenUnreachable(BinaryenModuleRef module);\nBinaryenExpressionRef BinaryenAtomicLoad(BinaryenModuleRef module, uint32_t bytes, uint32_t offset, BinaryenType type, BinaryenExpressionRef ptr);\nBinaryenExpressionRef BinaryenAtomicStore(BinaryenModuleRef module, uint32_t bytes, uint32_t offset, BinaryenExpressionRef ptr, BinaryenExpressionRef value, BinaryenType type);\nBinaryenExpressionRef BinaryenAtomicRMW(BinaryenModuleRef module, BinaryenOp op, BinaryenIndex bytes, BinaryenIndex offset, BinaryenExpressionRef ptr, BinaryenExpressionRef value, BinaryenType type);\nBinaryenExpressionRef BinaryenAtomicCmpxchg(BinaryenModuleRef module, BinaryenIndex bytes, BinaryenIndex offset, BinaryenExpressionRef ptr, BinaryenExpressionRef expected, BinaryenExpressionRef replacement, BinaryenType type);\nBinaryenExpressionRef BinaryenAtomicWait(BinaryenModuleRef module, BinaryenExpressionRef ptr, BinaryenExpressionRef expected, BinaryenExpressionRef timeout, BinaryenType type);\nBinaryenExpressionRef BinaryenAtomicNotify(BinaryenModuleRef module, BinaryenExpressionRef ptr, BinaryenExpressionRef notifyCount);\nBinaryenExpressionRef BinaryenSIMDExtract(BinaryenModuleRef module, BinaryenOp op, BinaryenExpressionRef vec, uint8_t index);\nBinaryenExpressionRef BinaryenSIMDReplace(BinaryenModuleRef module, BinaryenOp op, BinaryenExpressionRef vec, uint8_t index, BinaryenExpressionRef value);\nBinaryenExpressionRef BinaryenSIMDShuffle(BinaryenModuleRef module, BinaryenExpressionRef left, BinaryenExpressionRef right, const uint8_t mask[16]);\nBinaryenExpressionRef BinaryenSIMDBitselect(BinaryenModuleRef module, BinaryenExpressionRef left, BinaryenExpressionRef right, BinaryenExpressionRef cond);\nBinaryenExpressionRef BinaryenSIMDShift(BinaryenModuleRef module, BinaryenOp op, BinaryenExpressionRef vec, BinaryenExpressionRef shift);\nBinaryenExpressionRef BinaryenMemoryInit(BinaryenModuleRef module, uint32_t segment, BinaryenExpressionRef dest, BinaryenExpressionRef offset, BinaryenExpressionRef size);\nBinaryenExpressionRef BinaryenDataDrop(BinaryenModuleRef module, uint32_t segment);\nBinaryenExpressionRef BinaryenMemoryCopy(BinaryenModuleRef module, BinaryenExpressionRef dest, BinaryenExpressionRef source, BinaryenExpressionRef size);\nBinaryenExpressionRef BinaryenMemoryFill(BinaryenModuleRef module, BinaryenExpressionRef dest, BinaryenExpressionRef value, BinaryenExpressionRef size);\n\nBinaryenExpressionId BinaryenExpressionGetId(BinaryenExpressionRef expr);\nBinaryenType BinaryenExpressionGetType(BinaryenExpressionRef expr);\nvoid BinaryenExpressionPrint(BinaryenExpressionRef expr);\n\nconst char* BinaryenBlockGetName(BinaryenExpressionRef expr);\nBinaryenIndex BinaryenBlockGetNumChildren(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenBlockGetChild(BinaryenExpressionRef expr, BinaryenIndex index);\n\nBinaryenExpressionRef BinaryenIfGetCondition(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenIfGetIfTrue(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenIfGetIfFalse(BinaryenExpressionRef expr);\n\nconst char* BinaryenLoopGetName(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenLoopGetBody(BinaryenExpressionRef expr);\n\nconst char* BinaryenBreakGetName(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenBreakGetCondition(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenBreakGetValue(BinaryenExpressionRef expr);\n\nBinaryenIndex BinaryenSwitchGetNumNames(BinaryenExpressionRef expr);\nconst char* BinaryenSwitchGetName(BinaryenExpressionRef expr, BinaryenIndex index);\nconst char* BinaryenSwitchGetDefaultName(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSwitchGetCondition(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSwitchGetValue(BinaryenExpressionRef expr);\n\nconst char* BinaryenCallGetTarget(BinaryenExpressionRef expr);\nBinaryenIndex BinaryenCallGetNumOperands(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenCallGetOperand(BinaryenExpressionRef expr, BinaryenIndex index);\n\nBinaryenExpressionRef BinaryenCallIndirectGetTarget(BinaryenExpressionRef expr);\nBinaryenIndex BinaryenCallIndirectGetNumOperands(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenCallIndirectGetOperand(BinaryenExpressionRef expr, BinaryenIndex index);\n\nBinaryenIndex BinaryenGetLocalGetIndex(BinaryenExpressionRef expr);\n\nint BinaryenSetLocalIsTee(BinaryenExpressionRef expr);\nBinaryenIndex BinaryenSetLocalGetIndex(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSetLocalGetValue(BinaryenExpressionRef expr);\n\nconst char* BinaryenGetGlobalGetName(BinaryenExpressionRef expr);\n\nconst char* BinaryenSetGlobalGetName(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSetGlobalGetValue(BinaryenExpressionRef expr);\n\nBinaryenOp BinaryenHostGetOp(BinaryenExpressionRef expr);\nconst char* BinaryenHostGetNameOperand(BinaryenExpressionRef expr);\nBinaryenIndex BinaryenHostGetNumOperands(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenHostGetOperand(BinaryenExpressionRef expr, BinaryenIndex index);\n\nint BinaryenLoadIsAtomic(BinaryenExpressionRef expr);\nint BinaryenLoadIsSigned(BinaryenExpressionRef expr);\nuint32_t BinaryenLoadGetOffset(BinaryenExpressionRef expr);\nuint32_t BinaryenLoadGetBytes(BinaryenExpressionRef expr);\nuint32_t BinaryenLoadGetAlign(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenLoadGetPtr(BinaryenExpressionRef expr);\n\nint BinaryenStoreIsAtomic(BinaryenExpressionRef expr);\nuint32_t BinaryenStoreGetBytes(BinaryenExpressionRef expr);\nuint32_t BinaryenStoreGetOffset(BinaryenExpressionRef expr);\nuint32_t BinaryenStoreGetAlign(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenStoreGetPtr(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenStoreGetValue(BinaryenExpressionRef expr);\n\nint32_t BinaryenConstGetValueI32(BinaryenExpressionRef expr);\nint64_t BinaryenConstGetValueI64(BinaryenExpressionRef expr);\nint32_t BinaryenConstGetValueI64Low(BinaryenExpressionRef expr);\nint32_t BinaryenConstGetValueI64High(BinaryenExpressionRef expr);\nfloat BinaryenConstGetValueF32(BinaryenExpressionRef expr);\ndouble BinaryenConstGetValueF64(BinaryenExpressionRef expr);\nvoid BinaryenConstGetValueV128(BinaryenExpressionRef expr, uint8_t* out);\n\nBinaryenOp BinaryenUnaryGetOp(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenUnaryGetValue(BinaryenExpressionRef expr);\n\nBinaryenOp BinaryenBinaryGetOp(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenBinaryGetLeft(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenBinaryGetRight(BinaryenExpressionRef expr);\n\nBinaryenExpressionRef BinaryenSelectGetIfTrue(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSelectGetIfFalse(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSelectGetCondition(BinaryenExpressionRef expr);\n\nBinaryenExpressionRef BinaryenDropGetValue(BinaryenExpressionRef expr);\n\nBinaryenExpressionRef BinaryenReturnGetValue(BinaryenExpressionRef expr);\n\nBinaryenOp BinaryenAtomicRMWGetOp(BinaryenExpressionRef expr);\nuint32_t BinaryenAtomicRMWGetBytes(BinaryenExpressionRef expr);\nuint32_t BinaryenAtomicRMWGetOffset(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenAtomicRMWGetPtr(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenAtomicRMWGetValue(BinaryenExpressionRef expr);\n\nuint32_t BinaryenAtomicCmpxchgGetBytes(BinaryenExpressionRef expr);\nuint32_t BinaryenAtomicCmpxchgGetOffset(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenAtomicCmpxchgGetPtr(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenAtomicCmpxchgGetExpected(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenAtomicCmpxchgGetReplacement(BinaryenExpressionRef expr);\n\nBinaryenExpressionRef BinaryenAtomicWaitGetPtr(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenAtomicWaitGetExpected(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenAtomicWaitGetTimeout(BinaryenExpressionRef expr);\nBinaryenType BinaryenAtomicWaitGetExpectedType(BinaryenExpressionRef expr);\n\nBinaryenExpressionRef BinaryenAtomicNotifyGetPtr(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenAtomicNotifyGetNotifyCount(BinaryenExpressionRef expr);\n\nBinaryenOp BinaryenSIMDExtractGetOp(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSIMDExtractGetVec(BinaryenExpressionRef expr);\nuint8_t BinaryenSIMDExtractGetIndex(BinaryenExpressionRef expr);\n\nBinaryenOp BinaryenSIMDReplaceGetOp(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSIMDReplaceGetVec(BinaryenExpressionRef expr);\nuint8_t BinaryenSIMDReplaceGetIndex(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSIMDReplaceGetValue(BinaryenExpressionRef expr);\n\nBinaryenExpressionRef BinaryenSIMDShuffleGetLeft(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSIMDShuffleGetRight(BinaryenExpressionRef expr);\nvoid BinaryenSIMDShuffleGetMask(BinaryenExpressionRef expr, uint8_t *mask);\n\nBinaryenExpressionRef BinaryenSIMDBitselectGetLeft(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSIMDBitselectGetRight(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSIMDBitselectGetCond(BinaryenExpressionRef expr);\n\nBinaryenOp BinaryenSIMDShiftGetOp(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSIMDShiftGetVec(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenSIMDShiftGetShift(BinaryenExpressionRef expr);\n\nuint32_t BinaryenMemoryInitGetSegment(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenMemoryInitGetDest(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenMemoryInitGetOffset(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenMemoryInitGetSize(BinaryenExpressionRef expr);\n\nuint32_t BinaryenDataDropGetSegment(BinaryenExpressionRef expr);\n\nBinaryenExpressionRef BinaryenMemoryCopyGetDest(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenMemoryCopyGetSource(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenMemoryCopyGetSize(BinaryenExpressionRef expr);\n\nBinaryenExpressionRef BinaryenMemoryFillGetDest(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenMemoryFillGetValue(BinaryenExpressionRef expr);\nBinaryenExpressionRef BinaryenMemoryFillGetSize(BinaryenExpressionRef expr);\n\n// Functions\n\ntypedef void* BinaryenFunctionRef;\n\n// Adds a function to the module. This is thread-safe.\n// @varTypes: the types of variables. In WebAssembly, vars share\n//            an index space with params. In other words, params come from\n//            the function type, and vars are provided in this call, and\n//            together they are all the locals. The order is first params\n//            and then vars, so if you have one param it will be at index\n//            0 (and written $0), and if you also have 2 vars they will be\n//            at indexes 1 and 2, etc., that is, they share an index space.\nBinaryenFunctionRef BinaryenAddFunction(BinaryenModuleRef module, const char* name, BinaryenFunctionTypeRef type, BinaryenType* varTypes, BinaryenIndex numVarTypes, BinaryenExpressionRef body);\n\n// Gets a function reference by name.\nBinaryenFunctionRef BinaryenGetFunction(BinaryenModuleRef module, const char* name);\n\n// Removes a function by name.\nvoid BinaryenRemoveFunction(BinaryenModuleRef module, const char* name);\n\n// Imports\n\nvoid BinaryenAddFunctionImport(BinaryenModuleRef module, const char* internalName, const char* externalModuleName, const char* externalBaseName, BinaryenFunctionTypeRef functionType);\nvoid BinaryenAddTableImport(BinaryenModuleRef module, const char* internalName, const char* externalModuleName, const char* externalBaseName);\nvoid BinaryenAddMemoryImport(BinaryenModuleRef module, const char* internalName, const char* externalModuleName, const char* externalBaseName, uint8_t shared);\nvoid BinaryenAddGlobalImport(BinaryenModuleRef module, const char* internalName, const char* externalModuleName, const char* externalBaseName, BinaryenType globalType);\n\n// Exports\n\ntypedef void* BinaryenExportRef;\n\nBinaryenExportRef BinaryenAddExport(BinaryenModuleRef module, const char* internalName, const char* externalName);\nBinaryenExportRef BinaryenAddFunctionExport(BinaryenModuleRef module, const char* internalName, const char* externalName);\nBinaryenExportRef BinaryenAddTableExport(BinaryenModuleRef module, const char* internalName, const char* externalName);\nBinaryenExportRef BinaryenAddMemoryExport(BinaryenModuleRef module, const char* internalName, const char* externalName);\nBinaryenExportRef BinaryenAddGlobalExport(BinaryenModuleRef module, const char* internalName, const char* externalName);\nvoid BinaryenRemoveExport(BinaryenModuleRef module, const char* externalName);\n\n// Globals\n\ntypedef void* BinaryenGlobalRef;\n\nBinaryenGlobalRef BinaryenAddGlobal(BinaryenModuleRef module, const char* name, BinaryenType type, int8_t mutable_, BinaryenExpressionRef init);\nvoid BinaryenRemoveGlobal(BinaryenModuleRef module, const char* name);\n\n// Function table. One per module\n\nvoid BinaryenSetFunctionTable(BinaryenModuleRef module, BinaryenIndex initial, BinaryenIndex maximum, const char** funcNames, BinaryenIndex numFuncNames);\n\n// Memory. One per module\n\n// Each segment has data in segments, a start offset in segmentOffsets, and a size in segmentSizes.\n// exportName can be NULL\nvoid BinaryenSetMemory(BinaryenModuleRef module, BinaryenIndex initial, BinaryenIndex maximum, const char* exportName, const char** segments, int8_t* segmentPassive, BinaryenExpressionRef* segmentOffsets, BinaryenIndex* segmentSizes, BinaryenIndex numSegments, uint8_t shared);\n\n// Start function. One per module\n\nvoid BinaryenSetStart(BinaryenModuleRef module, BinaryenFunctionRef start);\n\n//\n// ========== Module Operations ==========\n//\n\n// Parse a module in s-expression text format\nBinaryenModuleRef BinaryenModuleParse(const char* text);\n\n// Print a module to stdout in s-expression text format. Useful for debugging.\nvoid BinaryenModulePrint(BinaryenModuleRef module);\n\n// Print a module to stdout in asm.js syntax.\nvoid BinaryenModulePrintAsmjs(BinaryenModuleRef module);\n\n// Validate a module, showing errors on problems.\n//  @return 0 if an error occurred, 1 if validated succesfully\nint BinaryenModuleValidate(BinaryenModuleRef module);\n\n// Runs the standard optimization passes on the module. Uses the currently set\n// global optimize and shrink level.\nvoid BinaryenModuleOptimize(BinaryenModuleRef module);\n\n// Gets the currently set optimize level. Applies to all modules, globally.\n// 0, 1, 2 correspond to -O0, -O1, -O2 (default), etc.\nint BinaryenGetOptimizeLevel(void);\n\n// Sets the optimization level to use. Applies to all modules, globally.\n// 0, 1, 2 correspond to -O0, -O1, -O2 (default), etc.\nvoid BinaryenSetOptimizeLevel(int level);\n\n// Gets the currently set shrink level. Applies to all modules, globally.\n// 0, 1, 2 correspond to -O0, -Os (default), -Oz.\nint BinaryenGetShrinkLevel(void);\n\n// Sets the shrink level to use. Applies to all modules, globally.\n// 0, 1, 2 correspond to -O0, -Os (default), -Oz.\nvoid BinaryenSetShrinkLevel(int level);\n\n// Gets whether generating debug information is currently enabled or not.\n// Applies to all modules, globally.\nint BinaryenGetDebugInfo(void);\n\n// Enables or disables debug information in emitted binaries.\n// Applies to all modules, globally.\nvoid BinaryenSetDebugInfo(int on);\n\n// Runs the specified passes on the module. Uses the currently set global\n// optimize and shrink level.\nvoid BinaryenModuleRunPasses(BinaryenModuleRef module, const char** passes, BinaryenIndex numPasses);\n\n// Auto-generate drop() operations where needed. This lets you generate code without\n// worrying about where they are needed. (It is more efficient to do it yourself,\n// but simpler to use autodrop).\nvoid BinaryenModuleAutoDrop(BinaryenModuleRef module);\n\n// Serialize a module into binary form. Uses the currently set global debugInfo option.\n// @return how many bytes were written. This will be less than or equal to outputSize\nsize_t BinaryenModuleWrite(BinaryenModuleRef module, char* output, size_t outputSize);\n\ntypedef struct BinaryenBufferSizes {\n  size_t outputBytes;\n  size_t sourceMapBytes;\n} BinaryenBufferSizes;\n\n// Serialize a module into binary form including its source map. Uses the currently set\n// global debugInfo option.\n// @returns how many bytes were written. This will be less than or equal to outputSize\nBinaryenBufferSizes BinaryenModuleWriteWithSourceMap(BinaryenModuleRef module, const char* url, char* output, size_t outputSize, char* sourceMap, size_t sourceMapSize);\n\n// Result structure of BinaryenModuleAllocateAndWrite. Contained buffers have been allocated\n// using malloc() and the user is expected to free() them manually once not needed anymore.\ntypedef struct BinaryenModuleAllocateAndWriteResult {\n  void* binary;\n  size_t binaryBytes;\n  char* sourceMap;\n} BinaryenModuleAllocateAndWriteResult;\n\n// Serializes a module into binary form, optionally including its source map if\n// sourceMapUrl has been specified. Uses the currently set global debugInfo option.\n// Differs from BinaryenModuleWrite in that it implicitly allocates appropriate buffers\n// using malloc(), and expects the user to free() them manually once not needed anymore.\nBinaryenModuleAllocateAndWriteResult BinaryenModuleAllocateAndWrite(BinaryenModuleRef module, const char* sourceMapUrl);\n\n// Deserialize a module from binary form.\nBinaryenModuleRef BinaryenModuleRead(char* input, size_t inputSize);\n\n// Execute a module in the Binaryen interpreter. This will create an instance of\n// the module, run it in the interpreter - which means running the start method -\n// and then destroying the instance.\nvoid BinaryenModuleInterpret(BinaryenModuleRef module);\n\n// Adds a debug info file name to the module and returns its index.\nBinaryenIndex BinaryenModuleAddDebugInfoFileName(BinaryenModuleRef module, const char* filename);\n\n// Gets the name of the debug info file at the specified index. Returns `NULL` if it\n// does not exist.\nconst char* BinaryenModuleGetDebugInfoFileName(BinaryenModuleRef module, BinaryenIndex index);\n\n//\n// ======== FunctionType Operations ========\n//\n\n// Gets the name of the specified `FunctionType`.\nconst char* BinaryenFunctionTypeGetName(BinaryenFunctionTypeRef ftype);\n// Gets the number of parameters of the specified `FunctionType`.\nBinaryenIndex BinaryenFunctionTypeGetNumParams(BinaryenFunctionTypeRef ftype);\n// Gets the type of the parameter at the specified index of the specified `FunctionType`.\nBinaryenType BinaryenFunctionTypeGetParam(BinaryenFunctionTypeRef ftype, BinaryenIndex index);\n// Gets the result type of the specified `FunctionType`.\nBinaryenType BinaryenFunctionTypeGetResult(BinaryenFunctionTypeRef ftype);\n\n//\n// ========== Function Operations ==========\n//\n\n// Gets the name of the specified `Function`.\nconst char* BinaryenFunctionGetName(BinaryenFunctionRef func);\n// Gets the name of the `FunctionType` associated with the specified `Function`. May be `NULL` if the signature is implicit.\nconst char* BinaryenFunctionGetType(BinaryenFunctionRef func);\n// Gets the number of parameters of the specified `Function`.\nBinaryenIndex BinaryenFunctionGetNumParams(BinaryenFunctionRef func);\n// Gets the type of the parameter at the specified index of the specified `Function`.\nBinaryenType BinaryenFunctionGetParam(BinaryenFunctionRef func, BinaryenIndex index);\n// Gets the result type of the specified `Function`.\nBinaryenType BinaryenFunctionGetResult(BinaryenFunctionRef func);\n// Gets the number of additional locals within the specified `Function`.\nBinaryenIndex BinaryenFunctionGetNumVars(BinaryenFunctionRef func);\n// Gets the type of the additional local at the specified index within the specified `Function`.\nBinaryenType BinaryenFunctionGetVar(BinaryenFunctionRef func, BinaryenIndex index);\n// Gets the body of the specified `Function`.\nBinaryenExpressionRef BinaryenFunctionGetBody(BinaryenFunctionRef func);\n\n// Runs the standard optimization passes on the function. Uses the currently set\n// global optimize and shrink level.\nvoid BinaryenFunctionOptimize(BinaryenFunctionRef func, BinaryenModuleRef module);\n\n// Runs the specified passes on the function. Uses the currently set global\n// optimize and shrink level.\nvoid BinaryenFunctionRunPasses(BinaryenFunctionRef func, BinaryenModuleRef module, const char** passes, BinaryenIndex numPasses);\n\n// Sets the debug location of the specified `Expression` within the specified `Function`.\nvoid BinaryenFunctionSetDebugLocation(BinaryenFunctionRef func, BinaryenExpressionRef expr, BinaryenIndex fileIndex, BinaryenIndex lineNumber, BinaryenIndex columnNumber);\n\n//\n// ========== Import Operations ==========\n//\n\n// Gets the external module name of the specified import.\nconst char* BinaryenFunctionImportGetModule(BinaryenFunctionRef import);\n// const char* BinaryeGlobalImportGetModule(BinaryenGlobalRef import);\n// Gets the external base name of the specified import.\nconst char* BinaryenFunctionImportGetBase(BinaryenFunctionRef import);\nconst char* BinaryenGlobalImportGetBase(BinaryenGlobalRef import);\n\n//\n// ========== Export Operations ==========\n//\n\n// Gets the external kind of the specified export.\nBinaryenExternalKind BinaryenExportGetKind(BinaryenExportRef export_);\n// Gets the external name of the specified export.\nconst char* BinaryenExportGetName(BinaryenExportRef export_);\n// Gets the internal name of the specified export.\nconst char* BinaryenExportGetValue(BinaryenExportRef export_);\n\n//\n// ========== CFG / Relooper ==========\n//\n// General usage is (1) create a relooper, (2) create blocks, (3) add\n// branches between them, (4) render the output.\n//\n// For more details, see src/cfg/Relooper.h and\n// https://github.com/WebAssembly/binaryen/wiki/Compiling-to-WebAssembly-with-Binaryen#cfg-api\n\ntypedef void* RelooperRef;\ntypedef void* RelooperBlockRef;\n\n// Create a relooper instance\nRelooperRef RelooperCreate(BinaryenModuleRef module);\n\n// Create a basic block that ends with nothing, or with some simple branching\nRelooperBlockRef RelooperAddBlock(RelooperRef relooper, BinaryenExpressionRef code);\n\n// Create a branch to another basic block\n// The branch can have code on it, that is executed as the branch happens. this is useful for phis. otherwise, code can be NULL\nvoid RelooperAddBranch(RelooperBlockRef from, RelooperBlockRef to, BinaryenExpressionRef condition, BinaryenExpressionRef code);\n\n// Create a basic block that ends a switch on a condition\nRelooperBlockRef RelooperAddBlockWithSwitch(RelooperRef relooper, BinaryenExpressionRef code, BinaryenExpressionRef condition);\n\n// Create a switch-style branch to another basic block. The block's switch table will have these indexes going to that target\nvoid RelooperAddBranchForSwitch(RelooperBlockRef from, RelooperBlockRef to, BinaryenIndex* indexes, BinaryenIndex numIndexes, BinaryenExpressionRef code);\n\n// Generate structed wasm control flow from the CFG of blocks and branches that were created\n// on this relooper instance. This returns the rendered output, and also disposes of the\n// relooper and its blocks and branches, as they are no longer needed.\n//   @param labelHelper To render irreducible control flow, we may need a helper variable to\n//                      guide us to the right target label. This value should be an index of\n//                      an i32 local variable that is free for us to use.\nBinaryenExpressionRef RelooperRenderAndDispose(RelooperRef relooper, RelooperBlockRef entry, BinaryenIndex labelHelper);\n\n//\n// ========= Other APIs =========\n//\n\n// Sets whether API tracing is on or off. It is off by default. When on, each call\n// to an API method will print out C code equivalent to it, which is useful for\n// auto-generating standalone testcases from projects using the API.\n// When calling this to turn on tracing, the prelude of the full program is printed,\n// and when calling it to turn it off, the ending of the program is printed, giving\n// you the full compilable testcase.\n// TODO: compile-time option to enable/disable this feature entirely at build time?\nvoid BinaryenSetAPITracing(int on);\n\n//\n// ========= Utilities =========\n//\n\n// Note that this function has been added because there is no better alternative\n// currently and is scheduled for removal once there is one. It takes the same set\n// of parameters as BinaryenAddFunctionType but instead of adding a new function\n// signature, it returns a pointer to the existing signature or NULL if there is no\n// such signature yet.\nBinaryenFunctionTypeRef BinaryenGetFunctionTypeBySignature(BinaryenModuleRef module, BinaryenType result, BinaryenType* paramTypes, BinaryenIndex numParams);\n\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"wasm-forth\",\n  \"version\": \"2.0.0\",\n  \"description\": \"A Forth implementation compiling to WebAssembly.\",\n  \"main\": \"dist/wasm-forth.js\",\n  \"module\": \"src/index.js\",\n  \"files\": [\n    \"dist/wasm-forth.js\",\n    \"dist/kernel.wasm\",\n    \"dist/core.f\",\n    \"dist/vdom.f\",\n    \"README.md\",\n    \"LICENSE\"\n  ],\n  \"scripts\": {\n    \"build\": \"webpack\",\n    \"watch\": \"webpack --watch\",\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"keywords\": [\n    \"forth\",\n    \"wasm\",\n    \"WebAssembly\",\n    \"compiler\",\n    \"interpreter\"\n  ],\n  \"author\": \"Stefano Dissegna\",\n  \"license\": \"GPL-3.0\",\n  \"devDependencies\": {\n    \"webpack\": \"^3.10.0\"\n  }\n}\n"
  },
  {
    "path": "repl/index.html",
    "content": "<!DOCTYPE html>\n\n<html>\n    <head>\n        <title>WASM Forth - Interactive Environment</title>\n        <meta charset=\"utf-8\"/>\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n        <link rel=\"stylesheet\" type=\"text/css\" href=\"repl.css\"/>\n    </head>\n\n    <body>\n        <h1>WASM Forth - Interactive Environment</h1>\n        <div id=\"loading\">Loading...</div>\n        <pre id=\"output\"></pre>\n        <div id=\"input\" style=\"display: none\">\n            <textarea id=\"source-input\" type=\"text\" placeholder=\"Evaluate code\" tabindex=\"0\"></textarea>\n            <button id=\"enter\">Enter</button>\n        </div>\n\n        <script type=\"text/javascript\" src=\"dist/repl.js\"></script>\n    </body>\n</html>\n"
  },
  {
    "path": "repl/repl.css",
    "content": "html, body {\n    height: 100%;\n}\n\nhtml {\n    background-color: #002b36;\n    color: #93a1a1;\n    font-family: monospace;\n}\n\nbody {\n    margin: 0 auto;\n    padding: 2em;\n    max-width: 70ch;\n    font-size: 14px;\n    display: flex;\n    flex-direction: column;\n    box-sizing: border-box;\n}\n\nh1 {\n    font-size: 1.5em;\n}\n\n#output {\n    white-space: pre-wrap;\n    overflow-y: auto;\n}\n\n#input {\n    display: flex;\n    flex-shrink: 0;\n}\n\n#source-input {\n    flex: 1;\n    margin-right: 1em;\n    border: none;\n    caret-color: #859900;\n    border-bottom: 1px solid #859900;\n    padding-bottom: 0.5em;\n    color: #93a1a1;\n    font-family: monospace;\n    background-color: #002b36;\n    outline: none;\n    resize: none;\n    height: 1.25em;\n}\n\nbutton {\n    background: none;\n    border: none;\n    color: #859900;\n    cursor: pointer;\n    padding: 0;\n}\n\nbutton::-moz-focus-inner, input::-moz-focus-inner {\n    border: 0;\n    padding: 0;\n}\n\nbutton:active {\n    padding: 0;\n    color: #2aa198;\n}\n"
  },
  {
    "path": "repl/repl.js",
    "content": "import * as WasmForth from '../src/index';\n\nlet loadingElement = document.getElementById('loading');\nlet inputElement = document.getElementById('input');\nlet sourceInputElement = document.getElementById('source-input');\nlet enterElement = document.getElementById('enter');\nlet outputElement = document.getElementById('output');\n\nfunction onInputLine(evt) {\n    if (evt.keyCode === 13) {\n        evt.preventDefault();\n        processLine();\n    }\n}\n\nfunction processLine() {\n    let line = sourceInputElement.value;\n\n    outputElement.innerText += line + ' ';\n    sourceInputElement.value = '';\n\n    WasmForth.source(line + '\\n');\n\n    sourceInputElement.focus();\n}\n\nWasmForth.boot({\n    wasmURL: 'dist/kernel.wasm',\n    sources: ['dist/core.f', 'dist/vdom.f'],\n    write: (text) => {\n        outputElement.innerText += text;\n        outputElement.scrollTop = outputElement.scrollHeight;\n    }\n}).then(() => {\n    sourceInputElement.addEventListener('keypress', onInputLine);\n    enterElement.addEventListener('click', processLine);\n\n    loadingElement.parentElement.removeChild(loadingElement);\n    inputElement.removeAttribute('style');\n    sourceInputElement.focus();\n});\n"
  },
  {
    "path": "setup.py",
    "content": "from os import path\n\nfrom setuptools import setup, find_packages\n\n\ndef get_long_description():\n    readme_path = path.join(path.abspath(path.dirname(__file__)), 'README.md')\n    with open(readme_path, encoding='utf-8') as readme:\n        return readme.read()\n\n\nsetup(\n    name='wasm-forth',\n    version='1.0.0',\n    author='Stefano Dissegna',\n    description='A Forth implementation compiling to WebAssembly.',\n    long_description=get_long_description(),\n    url='https://github.com/stefano/wasm-forth/',\n    license='GPLv3',\n    keywords='forth wasm WebAssembly compiler interpreter',\n    classifiers=[\n        'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n        'Programming Language :: Python :: 3',\n        'Topic :: Software Development :: Interpreters',\n    ],\n    packages=find_packages(),\n    setup_requires=['cffi>=1.0.0'],\n    cffi_modules=['kernel/build_binaryen_ext.py:ffibuilder'],\n    install_requires=['cffi>=1.0.0'],\n)\n"
  },
  {
    "path": "src/index.js",
    "content": "let interpreter;\nlet memBytes;\nlet memCells;\nlet inputBuffer = '';\nlet onSourceAvailable;\n\nfunction decodeString(memoryIndex, nBytes) {\n  let chars = [];\n\n  for (let i = 0; i < nBytes; i++) {\n    chars.push(String.fromCharCode(memBytes[memoryIndex + i]));\n  }\n\n  return chars.join('');\n}\n\nfunction encodeString(target, value, limit) {\n    limit = Math.min(limit, value.length);\n    for (let i = 0; i < limit; i++) {\n        memBytes[target + i] = value.charCodeAt(i);\n    }\n    return limit;\n}\n\nfunction makeFFI(config) {\n    let currentEvent = null;\n\n    let io = {\n        read: (token, memoryIndex, nBytes) => {\n            let continuation = () => {\n                let limit = encodeString(memoryIndex, inputBuffer, nBytes);\n                inputBuffer = inputBuffer.substr(limit);\n                onSourceAvailable = undefined;\n                interpreter.exports.exec(token, limit);\n            };\n\n            if (inputBuffer.length > 0) {\n                setTimeout(continuation, 0);\n            } else {\n                onSourceAvailable = continuation;\n            }\n        },\n\n        patchBody: (memoryIndex, unused) => {\n            let parent = document.querySelector('#body'), nodeIdx = 0;\n            let parentStack = [], idxStack = [];\n            loop:\n            for (let idx = memoryIndex / 4;; idx += 2) {\n                switch (memCells[idx]) {\n                case 1: {\n                    // remove attr\n                    let structAddr = memCells[idx+1];\n                    let nameAddr = memCells[structAddr/4];\n                    let name = decodeString(nameAddr+2, memBytes[nameAddr]-1);\n                    let valueNBytes = memCells[structAddr/4+1];\n                    if (valueNBytes === 0xFFFFFFFF) {\n                        parent.childNodes[nodeIdx][name] = undefined;\n                    } else if (name === 'focus') {\n                        // nothing\n                    } else if (name === 'input-value') {\n                        parent.childNodes[nodeIdx].value = '';\n                    } else if (name === 'checked') {\n                        parent.childNodes[nodeIdx].checked = false;\n                    } else {\n                        parent.childNodes[nodeIdx].removeAttribute(name);\n                    }\n                    break;\n                }\n                case 2: {\n                    // set attr\n                    let structAddr = memCells[idx+1];\n                    let nameAddr = memCells[structAddr/4];\n                    let name = decodeString(nameAddr+2, memBytes[nameAddr]-1);\n                    let valueNBytes = memCells[structAddr/4+1];\n                    let valueAddr = memCells[structAddr/4+2];\n                    if (valueNBytes === 0xFFFFFFFF) {\n                        parent.childNodes[nodeIdx][name] = (evt) => {\n                            currentEvent = evt;\n                            interpreter.exports.exec(0, valueAddr);\n                        };\n                    } else if (name === 'focus') {\n                        parent.childNodes[nodeIdx].focus();\n                    } else if (name === 'input-value') {\n                        parent.childNodes[nodeIdx].value = decodeString(valueAddr, valueNBytes);\n                    } else if (name === 'checked') {\n                        parent.childNodes[nodeIdx].checked = true;\n                    } else {\n                        parent.childNodes[nodeIdx].setAttribute(name, decodeString(valueAddr, valueNBytes));\n                    }\n                    break;\n                }\n                case 3: // create\n                    let addr = memCells[idx+1];\n                    let nBytes = memBytes[addr];\n                    let name = decodeString(addr+2, nBytes-2); // skip starting '<' and ending '>'\n                    let elem = document.createElement(name);\n                    parent.insertBefore(elem, parent.childNodes[nodeIdx]);\n                    break;\n                case 4: // skip\n                    nodeIdx += memCells[idx+1];\n                    break;\n                case 5: // remove\n                    parent.removeChild(parent.childNodes[nodeIdx]);\n                    break;\n                case 6: // enter\n                    parentStack.push(parent);\n                    idxStack.push(nodeIdx);\n                    parent = parent.childNodes[nodeIdx];\n                    nodeIdx = 0;\n                    break;\n                case 7: // leave\n                    parent = parentStack.pop();\n                    nodeIdx = idxStack.pop();\n                    break;\n                case 8: // stop\n                    break loop;\n                case 9: // create text node\n                    parent.insertBefore(document.createTextNode(''), parent.childNodes[nodeIdx]);\n                    break;\n                case 10: // set text content\n                    let textNBytes = memCells[memCells[idx+1]/4+1];\n                    let textAddr = memCells[memCells[idx+1]/4+2];\n                    parent.childNodes[nodeIdx].textContent = decodeString(textAddr, textNBytes);\n                    break;\n                default:\n                    console.log('unknown opcode:' + memCells[idx]);\n                    break loop;\n                }\n            }\n        },\n\n        write: (memoryIndex, nBytes) => {\n            try {\n                config.write(decodeString(memoryIndex, nBytes));\n            } catch (e) {\n                console.error(e);\n            }\n        },\n\n        evtAttr: (memoryIndex, nBytes, targetAddr, limit) => {\n            let path = decodeString(memoryIndex, nBytes).split('.');\n            let value = currentEvent;\n            for (let item of path) {\n                value = value[item];\n            }\n            if (value === true || value === false) {\n                return value;\n            }\n            if (typeof value === 'number') {\n                return value;\n            }\n            return encodeString(targetAddr, value, limit);\n        }\n    };\n\n    return { io };\n}\n\n/**\n * Provide Forth source code to be executed.\n *\n * @param {string} text\n */\nexport function source(text) {\n    inputBuffer += text;\n\n    if (onSourceAvailable) {\n        onSourceAvailable();\n    }\n}\n\n/**\n * Boots the forth system.\n *\n * @param config\n * {\n *     wasm: string; // URL to dist/kernel.wasm\n *     sources: string[]; // URLs to forth source code (should at least include dist/core.f)\n *     write: (text) => void; // a function called with the output emitted by Forth code\n * }\n *\n * @returns {Promise} resolved when the system is ready to process forth code.\n */\nexport function boot(config) {\n    return fetch(config.wasmURL).then(\n        res => res.arrayBuffer()\n    ).then(\n        bytes => WebAssembly.instantiate(bytes, makeFFI(config))\n    ).then(compiled => {\n        interpreter = compiled.instance;\n        memBytes = new Uint8Array(interpreter.exports.mem.buffer);\n        memCells = new Uint32Array(interpreter.exports.mem.buffer);\n        window.memBytes = memBytes;\n        window.memCells = memCells;\n\n        interpreter.exports.exec(0, 0);\n    }).then(\n        () => Promise.all(config.sources.map(url => fetch(url)))\n    ).then(\n        results => Promise.all(results.map(res => res.text()))\n    ).then(\n        texts => texts.forEach(source)\n    );\n}\n"
  },
  {
    "path": "webpack.config.js",
    "content": "let path = require('path');\n\nlet wasmForth = {\n    entry: {\n        main: './src/index.js'\n    },\n    output: {\n        path: path.resolve(__dirname, 'dist'),\n        filename: 'wasm-forth.js',\n        library: 'WasmForth',\n        libraryTarget: 'umd'\n    }\n};\n\nlet repl = {\n    entry: {\n        main: './repl/repl.js'\n    },\n    output: {\n        path: path.resolve(__dirname, 'repl/dist'),\n        filename: 'repl.js'\n    }\n};\n\nmodule.exports = [wasmForth, repl];\n"
  }
]